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 |
|---|---|---|---|---|---|
/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2011 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreGLDepthBuffer.h"
#include "OgreGLHardwarePixelBuffer.h"
#include "OgreGLRenderSystem.h"
#include "OgreGLFrameBufferObject.h"
namespace Ogre
{
GLDepthBuffer::GLDepthBuffer( uint16 poolId, GLRenderSystem *renderSystem, GLContext *creatorContext,
GLRenderBuffer *depth, GLRenderBuffer *stencil,
uint32 width, uint32 height, uint32 fsaa, uint32 multiSampleQuality,
bool manual ) :
DepthBuffer( poolId, 0, width, height, fsaa, "", manual ),
mMultiSampleQuality( multiSampleQuality ),
mCreatorContext( creatorContext ),
mDepthBuffer( depth ),
mStencilBuffer( stencil ),
mRenderSystem( renderSystem )
{
if( mDepthBuffer )
{
switch( mDepthBuffer->getGLFormat() )
{
case GL_DEPTH_COMPONENT16:
mBitDepth = 16;
break;
case GL_DEPTH_COMPONENT24:
case GL_DEPTH_COMPONENT32:
case GL_DEPTH24_STENCIL8_EXT:
mBitDepth = 32;
break;
}
}
}
GLDepthBuffer::~GLDepthBuffer()
{
if( mStencilBuffer && mStencilBuffer != mDepthBuffer )
{
delete mStencilBuffer;
mStencilBuffer = 0;
}
if( mDepthBuffer )
{
delete mDepthBuffer;
mDepthBuffer = 0;
}
}
//---------------------------------------------------------------------
bool GLDepthBuffer::isCompatible( RenderTarget *renderTarget ) const
{
bool retVal = false;
//Check standard stuff first.
if( mRenderSystem->getCapabilities()->hasCapability( RSC_RTT_DEPTHBUFFER_RESOLUTION_LESSEQUAL ) )
{
if( !DepthBuffer::isCompatible( renderTarget ) )
return false;
}
else
{
if( this->getWidth() != renderTarget->getWidth() ||
this->getHeight() != renderTarget->getHeight() ||
this->getFsaa() != renderTarget->getFSAA() )
return false;
}
//Now check this is the appropriate format
GLFrameBufferObject *fbo = 0;
renderTarget->getCustomAttribute(GLRenderTexture::CustomAttributeString_FBO, &fbo);
if( !fbo )
{
GLContext *windowContext;
renderTarget->getCustomAttribute( GLRenderTexture::CustomAttributeString_GLCONTEXT, &windowContext );
//Non-FBO targets and FBO depth surfaces don't play along, only dummies which match the same
//context
if( !mDepthBuffer && !mStencilBuffer && mCreatorContext == windowContext )
retVal = true;
}
else
{
//Check this isn't a dummy non-FBO depth buffer with an FBO target, don't mix them.
//If you don't want depth buffer, use a Null Depth Buffer, not a dummy one.
if( mDepthBuffer || mStencilBuffer )
{
GLenum internalFormat = fbo->getFormat();
GLenum depthFormat, stencilFormat;
mRenderSystem->_getDepthStencilFormatFor( internalFormat, &depthFormat, &stencilFormat );
bool bSameDepth = false;
if( mDepthBuffer )
bSameDepth |= mDepthBuffer->getGLFormat() == depthFormat;
bool bSameStencil = false;
if( !mStencilBuffer || mStencilBuffer == mDepthBuffer )
bSameStencil = stencilFormat == GL_NONE;
else
{
if( mStencilBuffer )
bSameStencil = stencilFormat == mStencilBuffer->getGLFormat();
}
retVal = bSameDepth && bSameStencil;
}
}
return retVal;
}
}
| bhlzlx/ogre | RenderSystems/GL/src/OgreGLDepthBuffer.cpp | C++ | mit | 4,568 |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using SDKTemplate;
using Windows.Security.EnterpriseData;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace EdpSample
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class Scenario1 : Page
{
private MainPage rootPage;
private static string m_EnterpriseId = "contoso.com";
public static string m_EnterpriseIdentity
{
get
{
return m_EnterpriseId;
}
}
public Scenario1()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
rootPage = MainPage.Current;
}
private void Setup_Click(object sender, RoutedEventArgs e)
{
m_EnterpriseId = EnterpriseIdentity.Text;
rootPage.NotifyUser("Enterprise Identity is set to: " + m_EnterpriseIdentity, NotifyType.StatusMessage);
}
}
}
| mobilecp/Windows-universal-samples | edpsamples/cs/scenario1_setup.xaml.cs | C# | mit | 1,622 |
package com.iluwatar;
public class Sergeant extends Unit {
public Sergeant(Unit ... children) {
super(children);
}
@Override
public void accept(UnitVisitor visitor) {
visitor.visitSergeant(this);
super.accept(visitor);
}
@Override
public String toString() {
return "sergeant";
}
}
| zfu/java-design-patterns | visitor/src/main/java/com/iluwatar/Sergeant.java | Java | mit | 321 |
/*
Copyright
*/
//go:generate rm -vf autogen/gen.go
//go:generate go-bindata -pkg autogen -o autogen/gen.go ./static/... ./templates/...
//go:generate mkdir -p vendor/github.com/docker/docker/autogen/dockerversion
//go:generate cp script/dockerversion vendor/github.com/docker/docker/autogen/dockerversion/dockerversion.go
package main
| dontrebootme/traefik | generate.go | GO | mit | 339 |
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace spec\Sylius\Bundle\CoreBundle\EventListener;
use Doctrine\ORM\Event\LifecycleEventArgs;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
use Sylius\Component\Core\Model\CustomerInterface;
use Sylius\Component\Core\Model\ShopUserInterface;
use Sylius\Component\User\Canonicalizer\CanonicalizerInterface;
/**
* @author Łukasz Chruściel <lukasz.chrusciel@lakion.com>
*/
final class CanonicalizerListenerSpec extends ObjectBehavior
{
function let(CanonicalizerInterface $canonicalizer): void
{
$this->beConstructedWith($canonicalizer);
}
function it_canonicalize_user_username_on_pre_persist_doctrine_event($canonicalizer, LifecycleEventArgs $event, ShopUserInterface $user): void
{
$event->getEntity()->willReturn($user);
$user->getUsername()->willReturn('testUser');
$user->getEmail()->willReturn('test@email.com');
$user->setUsernameCanonical('testuser')->shouldBeCalled();
$user->setEmailCanonical('test@email.com')->shouldBeCalled();
$canonicalizer->canonicalize('testUser')->willReturn('testuser')->shouldBeCalled();
$canonicalizer->canonicalize('test@email.com')->willReturn('test@email.com')->shouldBeCalled();
$this->prePersist($event);
}
function it_canonicalize_customer_email_on_pre_persist_doctrine_event($canonicalizer, LifecycleEventArgs $event, CustomerInterface $customer): void
{
$event->getEntity()->willReturn($customer);
$customer->getEmail()->willReturn('testUser@Email.com');
$customer->setEmailCanonical('testuser@email.com')->shouldBeCalled();
$canonicalizer->canonicalize('testUser@Email.com')->willReturn('testuser@email.com')->shouldBeCalled();
$this->prePersist($event);
}
function it_canonicalize_user_username_on_pre_update_doctrine_event($canonicalizer, LifecycleEventArgs $event, ShopUserInterface $user): void
{
$event->getEntity()->willReturn($user);
$user->getUsername()->willReturn('testUser');
$user->getEmail()->willReturn('test@email.com');
$user->setUsernameCanonical('testuser')->shouldBeCalled();
$user->setEmailCanonical('test@email.com')->shouldBeCalled();
$canonicalizer->canonicalize('testUser')->willReturn('testuser')->shouldBeCalled();
$canonicalizer->canonicalize('test@email.com')->willReturn('test@email.com')->shouldBeCalled();
$this->preUpdate($event);
}
function it_canonicalize_customer_email_on_pre_update_doctrine_event($canonicalizer, LifecycleEventArgs $event, CustomerInterface $customer): void
{
$event->getEntity()->willReturn($customer);
$customer->getEmail()->willReturn('testUser@Email.com');
$customer->setEmailCanonical('testuser@email.com')->shouldBeCalled();
$canonicalizer->canonicalize('testUser@Email.com')->willReturn('testuser@email.com')->shouldBeCalled();
$this->preUpdate($event);
}
function it_canonicalize_only_user_or_customer_interface_implementation_on_pre_presist($canonicalizer, LifecycleEventArgs $event): void
{
$item = new \stdClass();
$event->getEntity()->willReturn($item);
$canonicalizer->canonicalize(Argument::any())->shouldNotBeCalled();
$this->prePersist($event);
}
function it_canonicalize_only_user_or_customer_interface_implementation_on_pre_update($canonicalizer, LifecycleEventArgs $event): void
{
$item = new \stdClass();
$event->getEntity()->willReturn($item);
$canonicalizer->canonicalize(Argument::any())->shouldNotBeCalled();
$this->preUpdate($event);
}
}
| rainlike/justshop | vendor/sylius/sylius/src/Sylius/Bundle/CoreBundle/spec/EventListener/CanonicalizerListenerSpec.php | PHP | mit | 3,904 |
using System;
using System.Drawing;
using System.Globalization;
using System.Windows.Forms;
using DotSpatial.Controls;
using DotSpatial.Controls.Header;
using DotSpatial.Symbology;
namespace DotSpatial.Plugins.Contourer
{
public class Snapin : Extension
{
public override void Activate()
{
AddMenuItems(App.HeaderControl);
base.Activate();
}
private void AddMenuItems(IHeaderControl header)
{
SimpleActionItem contourerItem = new SimpleActionItem("Contour...", menu_Click) { Key = "kC" };
header.Add(contourerItem);
}
private void menu_Click(object sender, EventArgs e)
{
using (FormContour frm = new FormContour())
{
frm.Layers = App.Map.GetRasterLayers();
if (frm.Layers.GetLength(0) <= 0)
{
MessageBox.Show("No raster layer found!");
return;
}
if (frm.ShowDialog() != DialogResult.OK) return;
IMapFeatureLayer fl = App.Map.Layers.Add(frm.Contours);
fl.LegendText = frm.LayerName + " - Contours";
int numlevs = frm.Lev.GetLength(0);
switch (frm.Contourtype)
{
case (Contour.ContourType.Line):
{
LineScheme ls = new LineScheme();
ls.Categories.Clear();
for (int i = 0; i < frm.Color.GetLength(0); i++)
{
LineCategory lc = new LineCategory(frm.Color[i], 2.0)
{
FilterExpression = "[Value] = " + frm.Lev[i],
LegendText = frm.Lev[i].ToString(CultureInfo.InvariantCulture)
};
ls.AddCategory(lc);
}
fl.Symbology = ls;
}
break;
case (Contour.ContourType.Polygon):
{
PolygonScheme ps = new PolygonScheme();
ps.Categories.Clear();
for (int i = 0; i < frm.Color.GetLength(0); i++)
{
PolygonCategory pc = new PolygonCategory(frm.Color[i], Color.Transparent, 0)
{
FilterExpression = "[Lev] = " + i,
LegendText = frm.Lev[i] + " - " + frm.Lev[i + 1]
};
ps.AddCategory(pc);
}
fl.Symbology = ps;
}
break;
}
}
}
}
} | swsglobal/DotSpatial | Source/DotSpatial.Plugins.Contourer/Snapin.cs | C# | mit | 3,106 |
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
if (!process.versions.openssl) {
console.error('Skipping because node compiled without OpenSSL.');
process.exit(0);
}
var common = require('../common');
var assert = require('assert');
var fs = require('fs');
var tls = require('tls');
var key = fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem');
var cert = fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem');
tls.createServer({ key: key, cert: cert }, function(conn) {
conn.end();
this.close();
}).listen(0, function() {
var options = { port: this.address().port, rejectUnauthorized: true };
tls.connect(options).on('error', common.mustCall(function(err) {
assert.equal(err.code, 'UNABLE_TO_VERIFY_LEAF_SIGNATURE');
assert.equal(err.message, 'unable to verify the first certificate');
this.destroy();
}));
});
| ptmt/flow-declarations | test/node/test-tls-friendly-error-message.js | JavaScript | mit | 1,945 |
Kanboard.App = function() {
this.controllers = {};
};
Kanboard.App.prototype.get = function(controller) {
return this.controllers[controller];
};
Kanboard.App.prototype.execute = function() {
for (var className in Kanboard) {
if (className !== "App") {
var controller = new Kanboard[className](this);
this.controllers[className] = controller;
if (typeof controller.execute === "function") {
controller.execute();
}
if (typeof controller.listen === "function") {
controller.listen();
}
if (typeof controller.focus === "function") {
controller.focus();
}
}
}
this.focus();
this.datePicker();
this.autoComplete();
this.tagAutoComplete();
};
Kanboard.App.prototype.focus = function() {
// Auto-select input fields
$(document).on('focus', '.auto-select', function() {
$(this).select();
});
// Workaround for chrome
$(document).on('mouseup', '.auto-select', function(e) {
e.preventDefault();
});
};
Kanboard.App.prototype.datePicker = function() {
var bodyElement = $("body");
var dateFormat = bodyElement.data("js-date-format");
var timeFormat = bodyElement.data("js-time-format");
var lang = bodyElement.data("js-lang");
$.datepicker.setDefaults($.datepicker.regional[lang]);
$.timepicker.setDefaults($.timepicker.regional[lang]);
// Datepicker
$(".form-date").datepicker({
showOtherMonths: true,
selectOtherMonths: true,
dateFormat: dateFormat,
constrainInput: false
});
// Datetime picker
$(".form-datetime").datetimepicker({
dateFormat: dateFormat,
timeFormat: timeFormat,
constrainInput: false
});
};
Kanboard.App.prototype.tagAutoComplete = function() {
$(".tag-autocomplete").select2({
tags: true
});
};
Kanboard.App.prototype.autoComplete = function() {
$(".autocomplete").each(function() {
var input = $(this);
var field = input.data("dst-field");
var extraFields = input.data("dst-extra-fields");
if ($('#form-' + field).val() === '') {
input.parent().find("button[type=submit]").attr('disabled','disabled');
}
input.autocomplete({
source: input.data("search-url"),
minLength: 1,
select: function(event, ui) {
$("input[name=" + field + "]").val(ui.item.id);
if (extraFields) {
var fields = extraFields.split(',');
for (var i = 0; i < fields.length; i++) {
var fieldName = fields[i].trim();
$("input[name=" + fieldName + "]").val(ui.item[fieldName]);
}
}
input.parent().find("button[type=submit]").removeAttr('disabled');
}
});
});
};
Kanboard.App.prototype.hasId = function(id) {
return !!document.getElementById(id);
};
Kanboard.App.prototype.showLoadingIcon = function() {
$("body").append('<span id="app-loading-icon"> <i class="fa fa-spinner fa-spin"></i></span>');
};
Kanboard.App.prototype.hideLoadingIcon = function() {
$("#app-loading-icon").remove();
};
| fguillot/kanboard | assets/js/src/App.js | JavaScript | mit | 3,355 |
/*
* Should
* Copyright(c) 2010-2014 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
module.exports = function(should, Assertion) {
/**
* Assert given object is NaN
* @name NaN
* @memberOf Assertion
* @category assertion numbers
* @example
*
* (10).should.not.be.NaN();
* NaN.should.be.NaN();
*/
Assertion.add('NaN', function() {
this.params = { operator: 'to be NaN' };
this.assert(this.obj !== this.obj);
});
/**
* Assert given object is not finite (positive or negative)
*
* @name Infinity
* @memberOf Assertion
* @category assertion numbers
* @example
*
* (10).should.not.be.Infinity();
* NaN.should.not.be.Infinity();
*/
Assertion.add('Infinity', function() {
this.params = { operator: 'to be Infinity' };
this.is.a.Number()
.and.not.a.NaN()
.and.assert(!isFinite(this.obj));
});
/**
* Assert given number between `start` and `finish` or equal one of them.
*
* @name within
* @memberOf Assertion
* @category assertion numbers
* @param {number} start Start number
* @param {number} finish Finish number
* @param {string} [description] Optional message
* @example
*
* (10).should.be.within(0, 20);
*/
Assertion.add('within', function(start, finish, description) {
this.params = { operator: 'to be within ' + start + '..' + finish, message: description };
this.assert(this.obj >= start && this.obj <= finish);
});
/**
* Assert given number near some other `value` within `delta`
*
* @name approximately
* @memberOf Assertion
* @category assertion numbers
* @param {number} value Center number
* @param {number} delta Radius
* @param {string} [description] Optional message
* @example
*
* (9.99).should.be.approximately(10, 0.1);
*/
Assertion.add('approximately', function(value, delta, description) {
this.params = { operator: 'to be approximately ' + value + " ±" + delta, message: description };
this.assert(Math.abs(this.obj - value) <= delta);
});
/**
* Assert given number above `n`.
*
* @name above
* @alias Assertion#greaterThan
* @memberOf Assertion
* @category assertion numbers
* @param {number} n Margin number
* @param {string} [description] Optional message
* @example
*
* (10).should.be.above(0);
*/
Assertion.add('above', function(n, description) {
this.params = { operator: 'to be above ' + n, message: description };
this.assert(this.obj > n);
});
/**
* Assert given number below `n`.
*
* @name below
* @alias Assertion#lessThan
* @memberOf Assertion
* @category assertion numbers
* @param {number} n Margin number
* @param {string} [description] Optional message
* @example
*
* (0).should.be.below(10);
*/
Assertion.add('below', function(n, description) {
this.params = { operator: 'to be below ' + n, message: description };
this.assert(this.obj < n);
});
Assertion.alias('above', 'greaterThan');
Assertion.alias('below', 'lessThan');
};
| XuanyuZhao1984/MeanJS_train1 | node_modules/should/lib/ext/number.js | JavaScript | mit | 3,086 |
<?php
/**
* Copyright 2011 Bas de Nooijer. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this listof conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of the copyright holder.
*/
class Solarium_Result_Select_FacetSetTest extends PHPUnit_Framework_TestCase
{
/**
* @var Solarium_Result_Select_FacetSet
*/
protected $_result;
protected $_facets;
public function setUp()
{
$this->_facets = array(
'facet1' => 'content1',
'facet2' => 'content2',
);
$this->_result = new Solarium_Result_Select_FacetSet($this->_facets);
}
public function testGetFacets()
{
$this->assertEquals($this->_facets, $this->_result->getFacets());
}
public function testGetFacet()
{
$this->assertEquals(
$this->_facets['facet2'],
$this->_result->getFacet('facet2')
);
}
public function testGetInvalidFacet()
{
$this->assertEquals(
null,
$this->_result->getFacet('invalid')
);
}
public function testIterator()
{
$items = array();
foreach($this->_result AS $key => $item)
{
$items[$key] = $item;
}
$this->assertEquals($this->_facets, $items);
}
public function testCount()
{
$this->assertEquals(count($this->_facets), count($this->_result));
}
}
| bitclaw/solr-test | www/vendor/solarium/solarium/tests/Solarium/Result/Select/FacetSetTest.php | PHP | mit | 2,846 |
using System;
using System.IO;
using System.Collections;
using System.Runtime.InteropServices;
namespace Earlab
{
public delegate void LogCallback(String LogMessage);
/// <summary>
/// DesktopEarlabDLL is a wrapper class that wraps the DesktopEarlabDLL.dll functionality
/// and exposes it to C# applications
/// </summary>
class DesktopEarlabDLL
{
IntPtr theModel;
private const string DLLFileName = @"DesktopEarlabDLL.dll";
private string SavedPath;
[DllImport(DLLFileName, EntryPoint="CreateModel", CallingConvention=CallingConvention.Cdecl)]
private static extern IntPtr CreateModelExternal();
[DllImport(DLLFileName, EntryPoint="SetLogCallback", CallingConvention=CallingConvention.Cdecl)]
private static extern void SetLogCallbackExternal(IntPtr ModelPtr, LogCallback theCallback);
[DllImport(DLLFileName, EntryPoint="SetModuleDirectory", CallingConvention=CallingConvention.Cdecl)]
private static extern int SetModuleDirectoryExternal(IntPtr ModelPtr, string ModuleDirectoryPath);
[DllImport(DLLFileName, EntryPoint="SetInputDirectory", CallingConvention=CallingConvention.Cdecl)]
private static extern int SetInputDirectoryExternal(IntPtr ModelPtr, string InputDirectoryPath);
[DllImport(DLLFileName, EntryPoint="SetOutputDirectory", CallingConvention=CallingConvention.Cdecl)]
private static extern int SetOutputDirectoryExternal(IntPtr ModelPtr, string OutputDirectoryPath);
[DllImport(DLLFileName, EntryPoint="LoadModelConfigFile", CallingConvention=CallingConvention.Cdecl)]
private static extern int LoadModelConfigFileExternal(IntPtr ModelPtr, string ModelConfigFileName, float FrameSize_uS);
[DllImport(DLLFileName, EntryPoint="LoadModuleParameters", CallingConvention=CallingConvention.Cdecl)]
private static extern int LoadModuleParametersExternal(IntPtr ModelPtr, string ModuleParameterFileName);
[DllImport(DLLFileName, EntryPoint="StartModules", CallingConvention=CallingConvention.Cdecl)]
private static extern int StartModulesExternal(IntPtr ModelPtr);
[DllImport(DLLFileName, EntryPoint="RunModel", CallingConvention=CallingConvention.Cdecl)]
private static extern int RunModelExternal(IntPtr ModelPtr, int NumFrames);
[DllImport(DLLFileName, EntryPoint="AdvanceModules", CallingConvention=CallingConvention.Cdecl)]
private static extern int AdvanceModulesExternal(IntPtr ModelPtr);
[DllImport(DLLFileName, EntryPoint="StopModules", CallingConvention=CallingConvention.Cdecl)]
private static extern int StopModulesExternal(IntPtr ModelPtr);
[DllImport(DLLFileName, EntryPoint="UnloadModel", CallingConvention=CallingConvention.Cdecl)]
private static extern int UnloadModelExternal(IntPtr ModelPtr);
public DesktopEarlabDLL()
{
theModel = DesktopEarlabDLL.CreateModelExternal();
if (theModel == IntPtr.Zero)
throw new ApplicationException("Failed to initialize model");
}
public int SetModuleDirectory(string ModuleDirectoryPath)
{
if (theModel == IntPtr.Zero)
throw new ApplicationException("Model not initialized");
return DesktopEarlabDLL.SetModuleDirectoryExternal(theModel, ModuleDirectoryPath);
}
public void SetInputDirectory(string InputDirectoryPath)
{
if (theModel == IntPtr.Zero)
throw new ApplicationException("Model not initialized");
DesktopEarlabDLL.SetInputDirectoryExternal(theModel, InputDirectoryPath);
}
public void SetOutputDirectory(string OutputDirectoryPath)
{
if (theModel == IntPtr.Zero)
throw new ApplicationException("Model not initialized");
DesktopEarlabDLL.SetOutputDirectoryExternal(theModel, OutputDirectoryPath);
}
public void SetLogCallback(LogCallback theCallback)
{
if (theModel == IntPtr.Zero)
throw new ApplicationException("Model not initialized");
DesktopEarlabDLL.SetLogCallbackExternal(theModel, theCallback);
}
public int LoadModelConfigFile(string ModelConfigFileName, float FrameSize_uS)
{
if (theModel == IntPtr.Zero)
throw new ApplicationException("Model not initialized");
SavedPath = Environment.CurrentDirectory;
Environment.CurrentDirectory = Path.GetDirectoryName(ModelConfigFileName);
return DesktopEarlabDLL.LoadModelConfigFileExternal(theModel, ModelConfigFileName, FrameSize_uS);
}
public int LoadModuleParameters(string ModuleParameterFileName)
{
if (theModel == IntPtr.Zero)
throw new ApplicationException("Model not initialized");
return DesktopEarlabDLL.LoadModuleParametersExternal(theModel, ModuleParameterFileName);
}
public int StartModules()
{
if (theModel == IntPtr.Zero)
throw new ApplicationException("Model not initialized");
return DesktopEarlabDLL.StartModulesExternal(theModel);
}
public int RunModel(int NumFrames)
{
if (theModel == IntPtr.Zero)
throw new ApplicationException("Model not initialized");
return DesktopEarlabDLL.RunModelExternal(theModel, NumFrames);
}
public int AdvanceModules()
{
if (theModel == IntPtr.Zero)
throw new ApplicationException("Model not initialized");
return DesktopEarlabDLL.AdvanceModulesExternal(theModel);
}
public int StopModules()
{
if (theModel == IntPtr.Zero)
throw new ApplicationException("Model not initialized");
return DesktopEarlabDLL.StopModulesExternal(theModel);
}
public int UnloadModel()
{
if (theModel == IntPtr.Zero)
throw new ApplicationException("Model not initialized");
Environment.CurrentDirectory = SavedPath;
return DesktopEarlabDLL.UnloadModelExternal(theModel);
}
}
}
| AuditoryBiophysicsLab/EarLab | tags/release-2.2/EarLab ExperimentManager/DesktopEarlabDLL.cs | C# | mit | 5,656 |
class SurveyMrqAnswer < ActiveRecord::Base
acts_as_paranoid
attr_accessible :user_course_id, :question_id, :option_id, :selected_options, :survey_submission_id
belongs_to :user_course
belongs_to :question, class_name: "SurveyQuestion"
belongs_to :option, class_name: "SurveyQuestionOption"
belongs_to :survey_submission
#TODO: not in use, can be removed
def options
SurveyQuestionOption.where(id: eval(selected_options))
end
end
| nusedutech/coursemology.org | app/models/survey_mrq_answer.rb | Ruby | mit | 455 |
<?php
namespace Kendo\UI;
class SchedulerMessagesRecurrenceEditorMonthly extends \Kendo\SerializableObject {
//>> Properties
/**
* The text similar to "Day " displayed in the scheduler recurrence editor.
* @param string $value
* @return \Kendo\UI\SchedulerMessagesRecurrenceEditorMonthly
*/
public function day($value) {
return $this->setProperty('day', $value);
}
/**
* The text similar to " month(s)" displayed in the scheduler recurrence editor.
* @param string $value
* @return \Kendo\UI\SchedulerMessagesRecurrenceEditorMonthly
*/
public function interval($value) {
return $this->setProperty('interval', $value);
}
/**
* The text similar to "Repeat every: " displayed in the scheduler recurrence editor.
* @param string $value
* @return \Kendo\UI\SchedulerMessagesRecurrenceEditorMonthly
*/
public function repeatEvery($value) {
return $this->setProperty('repeatEvery', $value);
}
/**
* The text similar to "Repeat on: " displayed in the scheduler recurrence editor.
* @param string $value
* @return \Kendo\UI\SchedulerMessagesRecurrenceEditorMonthly
*/
public function repeatOn($value) {
return $this->setProperty('repeatOn', $value);
}
//<< Properties
}
?>
| deviffy/laravel-kendo-ui | wrappers/php/lib/Kendo/UI/SchedulerMessagesRecurrenceEditorMonthly.php | PHP | mit | 1,316 |
require 'oauth/signature/base'
module OAuth::Signature
class PLAINTEXT < Base
implements 'plaintext'
def signature
signature_base_string
end
def ==(cmp_signature)
signature == escape(cmp_signature)
end
def signature_base_string
secret
end
def secret
escape(super)
end
end
end
| maximilien/people_finder | vendor/plugins/oauth/lib/oauth/signature/plaintext.rb | Ruby | mit | 345 |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using COM = System.Runtime.InteropServices.ComTypes;
// Disable obsolete warnings about VarEnum and COM-marshaling APIs in CoreCLR
#pragma warning disable 618
namespace System.Management.Automation
{
internal static class ComInvoker
{
// DISP HRESULTS - may be returned by IDispatch.Invoke
private const int DISP_E_EXCEPTION = unchecked((int)0x80020009);
// LCID for en-US culture
private const int LCID_DEFAULT = 0x0409;
// The dispatch identifier for a parameter that receives the value of an assignment in a PROPERTYPUT.
// See https://msdn.microsoft.com/library/windows/desktop/ms221242(v=vs.85).aspx for details.
private const int DISPID_PROPERTYPUT = -3;
// Alias of GUID_NULL. It's a GUID set to all zero
private static readonly Guid s_IID_NULL = new Guid();
// Size of the Variant struct
private static readonly int s_variantSize = Marshal.SizeOf<Variant>();
/// <summary>
/// Make a by-Ref VARIANT value based on the passed-in VARIANT argument.
/// </summary>
/// <param name="srcVariantPtr">The source Variant pointer.</param>
/// <param name="destVariantPtr">The destination Variant pointer.</param>
private static unsafe void MakeByRefVariant(IntPtr srcVariantPtr, IntPtr destVariantPtr)
{
var srcVariant = (Variant*)srcVariantPtr;
var destVariant = (Variant*)destVariantPtr;
switch ((VarEnum)srcVariant->_typeUnion._vt)
{
case VarEnum.VT_EMPTY:
case VarEnum.VT_NULL:
// These cannot combine with VT_BYREF. Should try passing as a variant reference
// We follow the code in ComBinder to handle 'VT_EMPTY' and 'VT_NULL'
destVariant->_typeUnion._unionTypes._byref = new IntPtr(srcVariant);
destVariant->_typeUnion._vt = (ushort)VarEnum.VT_VARIANT | (ushort)VarEnum.VT_BYREF;
return;
case VarEnum.VT_RECORD:
// Representation of record is the same with or without byref
destVariant->_typeUnion._unionTypes._record._record = srcVariant->_typeUnion._unionTypes._record._record;
destVariant->_typeUnion._unionTypes._record._recordInfo = srcVariant->_typeUnion._unionTypes._record._recordInfo;
break;
case VarEnum.VT_VARIANT:
destVariant->_typeUnion._unionTypes._byref = new IntPtr(srcVariant);
break;
case VarEnum.VT_DECIMAL:
destVariant->_typeUnion._unionTypes._byref = new IntPtr(&(srcVariant->_decimal));
break;
default:
// All the other cases start at the same offset (it's a Union) so using &_i4 should work.
// This is the same code as in CLR implementation. It could be &_i1, &_i2 and etc. CLR implementation just prefer using &_i4.
destVariant->_typeUnion._unionTypes._byref = new IntPtr(&(srcVariant->_typeUnion._unionTypes._i4));
break;
}
destVariant->_typeUnion._vt = (ushort)(srcVariant->_typeUnion._vt | (ushort)VarEnum.VT_BYREF);
}
/// <summary>
/// Alloc memory for a VARIANT array with the specified length.
/// Also initialize the VARIANT elements to be the type 'VT_EMPTY'.
/// </summary>
/// <param name="length">Array length.</param>
/// <returns>Pointer to the array.</returns>
private static unsafe IntPtr NewVariantArray(int length)
{
IntPtr variantArray = Marshal.AllocCoTaskMem(s_variantSize * length);
for (int i = 0; i < length; i++)
{
IntPtr currentVarPtr = variantArray + s_variantSize * i;
var currentVar = (Variant*)currentVarPtr;
currentVar->_typeUnion._vt = (ushort)VarEnum.VT_EMPTY;
}
return variantArray;
}
/// <summary>
/// Generate the ByRef array indicating whether the corresponding argument is by-reference.
/// </summary>
/// <param name="parameters">Parameters retrieved from metadata.</param>
/// <param name="argumentCount">Count of arguments to pass in IDispatch.Invoke.</param>
/// <param name="isPropertySet">Indicate if we are handling arguments for PropertyPut/PropertyPutRef.</param>
/// <returns></returns>
internal static bool[] GetByRefArray(ParameterInformation[] parameters, int argumentCount, bool isPropertySet)
{
if (parameters.Length == 0)
{
return null;
}
var byRef = new bool[argumentCount];
int argsToProcess = argumentCount;
if (isPropertySet)
{
// If it's PropertySet, then the last value in arguments is the right-hand side value.
// There is no corresponding parameter for that value, so it's for sure not by-ref.
// Hence, set the last item of byRef array to be false.
argsToProcess = argumentCount - 1;
byRef[argsToProcess] = false;
}
Diagnostics.Assert(parameters.Length >= argsToProcess,
"There might be more parameters than argsToProcess due unspecified optional arguments");
for (int i = 0; i < argsToProcess; i++)
{
byRef[i] = parameters[i].isByRef;
}
return byRef;
}
/// <summary>
/// Invoke the COM member.
/// </summary>
/// <param name="target">IDispatch object.</param>
/// <param name="dispId">Dispatch identifier that identifies the member.</param>
/// <param name="args">Arguments passed in.</param>
/// <param name="byRef">Boolean array that indicates by-Ref parameters.</param>
/// <param name="invokeKind">Invocation kind.</param>
/// <returns></returns>
internal static object Invoke(IDispatch target, int dispId, object[] args, bool[] byRef, COM.INVOKEKIND invokeKind)
{
Diagnostics.Assert(target != null, "Caller makes sure an IDispatch object passed in.");
Diagnostics.Assert(args == null || byRef == null || args.Length == byRef.Length,
"If 'args' and 'byRef' are not null, then they should be one-on-one mapping.");
int argCount = args != null ? args.Length : 0;
int refCount = byRef != null ? byRef.Count(c => c) : 0;
IntPtr variantArgArray = IntPtr.Zero, dispIdArray = IntPtr.Zero, tmpVariants = IntPtr.Zero;
try
{
// Package arguments
if (argCount > 0)
{
variantArgArray = NewVariantArray(argCount);
int refIndex = 0;
for (int i = 0; i < argCount; i++)
{
// !! The arguments should be in REVERSED order!!
int actualIndex = argCount - i - 1;
IntPtr varArgPtr = variantArgArray + s_variantSize * actualIndex;
// If need to pass by ref, create a by-ref variant
if (byRef != null && byRef[i])
{
// Allocate memory for temporary VARIANTs used in by-ref marshalling
if (tmpVariants == IntPtr.Zero)
{
tmpVariants = NewVariantArray(refCount);
}
// Create a VARIANT that the by-ref VARIANT points to
IntPtr tmpVarPtr = tmpVariants + s_variantSize * refIndex;
Marshal.GetNativeVariantForObject(args[i], tmpVarPtr);
// Create the by-ref VARIANT
MakeByRefVariant(tmpVarPtr, varArgPtr);
refIndex++;
}
else
{
Marshal.GetNativeVariantForObject(args[i], varArgPtr);
}
}
}
var paramArray = new COM.DISPPARAMS[1];
paramArray[0].rgvarg = variantArgArray;
paramArray[0].cArgs = argCount;
if (invokeKind == COM.INVOKEKIND.INVOKE_PROPERTYPUT || invokeKind == COM.INVOKEKIND.INVOKE_PROPERTYPUTREF)
{
// For property putters, the first DISPID argument needs to be DISPID_PROPERTYPUT
dispIdArray = Marshal.AllocCoTaskMem(4); // Allocate 4 bytes to hold a 32-bit signed integer
Marshal.WriteInt32(dispIdArray, DISPID_PROPERTYPUT);
paramArray[0].cNamedArgs = 1;
paramArray[0].rgdispidNamedArgs = dispIdArray;
}
else
{
// Otherwise, no named parameters are necessary since powershell parser doesn't support named parameter
paramArray[0].cNamedArgs = 0;
paramArray[0].rgdispidNamedArgs = IntPtr.Zero;
}
// Make the call
EXCEPINFO info = default(EXCEPINFO);
object result = null;
try
{
// 'puArgErr' is set when IDispatch.Invoke fails with error code 'DISP_E_PARAMNOTFOUND' and 'DISP_E_TYPEMISMATCH'.
// Appropriate exceptions will be thrown in such cases, but FullCLR doesn't use 'puArgErr' in the exception handling, so we also ignore it.
uint puArgErrNotUsed = 0;
target.Invoke(dispId, s_IID_NULL, LCID_DEFAULT, invokeKind, paramArray, out result, out info, out puArgErrNotUsed);
}
catch (Exception innerException)
{
// When 'IDispatch.Invoke' returns error code, CLR will raise exception based on internal HR-to-Exception mapping.
// Description of the return code can be found at https://msdn.microsoft.com/library/windows/desktop/ms221479(v=vs.85).aspx
// According to CoreCLR team (yzha), the exception needs to be wrapped as an inner exception of TargetInvocationException.
string exceptionMsg = null;
if (innerException.HResult == DISP_E_EXCEPTION)
{
// Invoke was successful but the actual underlying method failed.
// In this case, we use EXCEPINFO to get additional error info.
// Use EXCEPINFO.scode or EXCEPINFO.wCode as HR to construct the correct exception.
int code = info.scode != 0 ? info.scode : info.wCode;
innerException = Marshal.GetExceptionForHR(code, IntPtr.Zero) ?? innerException;
// Get the richer error description if it's available.
if (info.bstrDescription != IntPtr.Zero)
{
exceptionMsg = Marshal.PtrToStringBSTR(info.bstrDescription);
Marshal.FreeBSTR(info.bstrDescription);
}
// Free the BSTRs
if (info.bstrSource != IntPtr.Zero)
{
Marshal.FreeBSTR(info.bstrSource);
}
if (info.bstrHelpFile != IntPtr.Zero)
{
Marshal.FreeBSTR(info.bstrHelpFile);
}
}
var outerException = exceptionMsg == null
? new TargetInvocationException(innerException)
: new TargetInvocationException(exceptionMsg, innerException);
throw outerException;
}
// Now back propagate the by-ref arguments
if (refCount > 0)
{
for (int i = 0; i < argCount; i++)
{
// !! The arguments should be in REVERSED order!!
int actualIndex = argCount - i - 1;
// If need to pass by ref, back propagate
if (byRef != null && byRef[i])
{
args[i] = Marshal.GetObjectForNativeVariant(variantArgArray + s_variantSize * actualIndex);
}
}
}
return result;
}
finally
{
// Free the variant argument array
if (variantArgArray != IntPtr.Zero)
{
for (int i = 0; i < argCount; i++)
{
VariantClear(variantArgArray + s_variantSize * i);
}
Marshal.FreeCoTaskMem(variantArgArray);
}
// Free the dispId array
if (dispIdArray != IntPtr.Zero)
{
Marshal.FreeCoTaskMem(dispIdArray);
}
// Free the temporary variants created when handling by-Ref arguments
if (tmpVariants != IntPtr.Zero)
{
for (int i = 0; i < refCount; i++)
{
VariantClear(tmpVariants + s_variantSize * i);
}
Marshal.FreeCoTaskMem(tmpVariants);
}
}
}
/// <summary>
/// Clear variables of type VARIANTARG (or VARIANT) before the memory containing the VARIANTARG is freed.
/// </summary>
/// <param name="pVariant"></param>
[DllImport("oleaut32.dll")]
internal static extern void VariantClear(IntPtr pVariant);
/// <summary>
/// We have to declare 'bstrSource', 'bstrDescription' and 'bstrHelpFile' as pointers because
/// CLR marshalling layer would try to free those BSTRs by default and that is not correct.
/// Therefore, manually marshalling might be needed to extract 'bstrDescription'.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal struct EXCEPINFO
{
public short wCode;
public short wReserved;
public IntPtr bstrSource;
public IntPtr bstrDescription;
public IntPtr bstrHelpFile;
public int dwHelpContext;
public IntPtr pvReserved;
public IntPtr pfnDeferredFillIn;
public int scode;
}
/// <summary>
/// VARIANT type used for passing arguments in COM interop.
/// </summary>
[StructLayout(LayoutKind.Explicit)]
internal struct Variant
{
// Most of the data types in the Variant are carried in _typeUnion
[FieldOffset(0)]
internal TypeUnion _typeUnion;
// Decimal is the largest data type and it needs to use the space that is normally unused in TypeUnion._wReserved1, etc.
// Hence, it is declared to completely overlap with TypeUnion. A Decimal does not use the first two bytes, and so
// TypeUnion._vt can still be used to encode the type.
[FieldOffset(0)]
internal Decimal _decimal;
[StructLayout(LayoutKind.Explicit)]
internal struct TypeUnion
{
[FieldOffset(0)]
internal ushort _vt;
[FieldOffset(2)]
internal ushort _wReserved1;
[FieldOffset(4)]
internal ushort _wReserved2;
[FieldOffset(6)]
internal ushort _wReserved3;
[FieldOffset(8)]
internal UnionTypes _unionTypes;
}
[StructLayout(LayoutKind.Sequential)]
internal struct Record
{
internal IntPtr _record;
internal IntPtr _recordInfo;
}
[StructLayout(LayoutKind.Explicit)]
internal struct UnionTypes
{
[FieldOffset(0)]
internal sbyte _i1;
[FieldOffset(0)]
internal Int16 _i2;
[FieldOffset(0)]
internal Int32 _i4;
[FieldOffset(0)]
internal Int64 _i8;
[FieldOffset(0)]
internal byte _ui1;
[FieldOffset(0)]
internal UInt16 _ui2;
[FieldOffset(0)]
internal UInt32 _ui4;
[FieldOffset(0)]
internal UInt64 _ui8;
[FieldOffset(0)]
internal Int32 _int;
[FieldOffset(0)]
internal UInt32 _uint;
[FieldOffset(0)]
internal Int16 _bool;
[FieldOffset(0)]
internal Int32 _error;
[FieldOffset(0)]
internal Single _r4;
[FieldOffset(0)]
internal double _r8;
[FieldOffset(0)]
internal Int64 _cy;
[FieldOffset(0)]
internal double _date;
[FieldOffset(0)]
internal IntPtr _bstr;
[FieldOffset(0)]
internal IntPtr _unknown;
[FieldOffset(0)]
internal IntPtr _dispatch;
[FieldOffset(0)]
internal IntPtr _pvarVal;
[FieldOffset(0)]
internal IntPtr _byref;
[FieldOffset(0)]
internal Record _record;
}
}
}
}
| JamesWTruher/PowerShell-1 | src/System.Management.Automation/engine/COM/ComInvoker.cs | C# | mit | 18,455 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable enable
using System.Collections.Generic;
namespace Microsoft.CodeAnalysis.CSharp
{
public static partial class SyntaxFacts
{
private sealed class SyntaxKindEqualityComparer : IEqualityComparer<SyntaxKind>
{
public bool Equals(SyntaxKind x, SyntaxKind y)
{
return x == y;
}
public int GetHashCode(SyntaxKind obj)
{
return (int)obj;
}
}
/// <summary>
/// A custom equality comparer for <see cref="SyntaxKind"/>
/// </summary>
/// <remarks>
/// PERF: The framework specializes EqualityComparer for enums, but only if the underlying type is System.Int32
/// Since SyntaxKind's underlying type is System.UInt16, ObjectEqualityComparer will be chosen instead.
/// </remarks>
public static IEqualityComparer<SyntaxKind> EqualityComparer { get; } = new SyntaxKindEqualityComparer();
}
}
| jmarolf/roslyn | src/Compilers/CSharp/Portable/Syntax/SyntaxKindEqualityComparer.cs | C# | mit | 1,204 |
#!/usr/bin/env node
'use strict';
var fs = require('fs'),
path = require('path'),
exec = require('child_process').exec,
chalk = require('chalk'),
Table = require('cli-table');
var fileNames = [
'abc',
'amazon',
//'eloquentjavascript',
//'es6-draft',
'es6-table',
'google',
'html-minifier',
'msn',
'newyorktimes',
'stackoverflow',
'wikipedia',
'es6'
];
fileNames = fileNames.sort().reverse();
var table = new Table({
head: ['File', 'Before', 'After', 'Savings', 'Time'],
colWidths: [20, 25, 25, 20, 20]
});
function toKb(size) {
return (size / 1024).toFixed(2);
}
function redSize(size) {
return chalk.red.bold(size) + chalk.white(' (' + toKb(size) + ' KB)');
}
function greenSize(size) {
return chalk.green.bold(size) + chalk.white(' (' + toKb(size) + ' KB)');
}
function blueSavings(oldSize, newSize) {
var savingsPercent = (1 - newSize / oldSize) * 100;
var savings = (oldSize - newSize) / 1024;
return chalk.cyan.bold(savingsPercent.toFixed(2)) + chalk.white('% (' + savings.toFixed(2) + ' KB)');
}
function blueTime(time) {
return chalk.cyan.bold(time) + chalk.white(' ms');
}
function test(fileName, done) {
if (!fileName) {
console.log('\n' + table.toString());
return;
}
console.log('Processing...', fileName);
var filePath = path.join('benchmarks/', fileName + '.html');
var minifiedFilePath = path.join('benchmarks/generated/', fileName + '.min.html');
var gzFilePath = path.join('benchmarks/generated/', fileName + '.html.gz');
var gzMinifiedFilePath = path.join('benchmarks/generated/', fileName + '.min.html.gz');
var command = path.normalize('./cli.js') + ' ' + filePath + ' -c benchmark.conf' + ' -o ' + minifiedFilePath;
// Open and read the size of the original input
fs.stat(filePath, function (err, stats) {
if (err) {
throw new Error('There was an error reading ' + filePath);
}
var originalSize = stats.size;
exec('gzip --keep --force --best --stdout ' + filePath + ' > ' + gzFilePath, function () {
// Open and read the size of the gzipped original
fs.stat(gzFilePath, function (err, stats) {
if (err) {
throw new Error('There was an error reading ' + gzFilePath);
}
var gzOriginalSize = stats.size;
// Begin timing after gzipped fixtures have been created
var startTime = new Date();
exec('node ' + command, function () {
// Open and read the size of the minified output
fs.stat(minifiedFilePath, function (err, stats) {
if (err) {
throw new Error('There was an error reading ' + minifiedFilePath);
}
var minifiedSize = stats.size;
var minifiedTime = new Date() - startTime;
// Gzip the minified output
exec('gzip --keep --force --best --stdout ' + minifiedFilePath + ' > ' + gzMinifiedFilePath, function () {
// Open and read the size of the minified+gzipped output
fs.stat(gzMinifiedFilePath, function (err, stats) {
if (err) {
throw new Error('There was an error reading ' + gzMinifiedFilePath);
}
var gzMinifiedSize = stats.size;
var gzMinifiedTime = new Date() - startTime;
table.push([
[fileName, '+ gzipped'].join('\n'),
[redSize(originalSize), redSize(gzOriginalSize)].join('\n'),
[greenSize(minifiedSize), greenSize(gzMinifiedSize)].join('\n'),
[blueSavings(originalSize, minifiedSize), blueSavings(gzOriginalSize, gzMinifiedSize)].join('\n'),
[blueTime(minifiedTime), blueTime(gzMinifiedTime)].join('\n')
]);
done();
});
});
});
});
});
});
});
}
(function run() {
test(fileNames.pop(), run);
})();
| psychoss/html-minifier | benchmark.js | JavaScript | mit | 3,946 |
steal('can/util', 'can/observe', function(can) {
// ** - 'this' will be the deepest item changed
// * - 'this' will be any changes within *, but * will be the
// this returned
// tells if the parts part of a delegate matches the broken up props of the event
// gives the prop to use as 'this'
// - parts - the attribute name of the delegate split in parts ['foo','*']
// - props - the split props of the event that happened ['foo','bar','0']
// - returns - the attribute to delegate too ('foo.bar'), or null if not a match
var matches = function(parts, props){
//check props parts are the same or
var len = parts.length,
i =0,
// keeps the matched props we will use
matchedProps = [],
prop;
// if the event matches
for(i; i< len; i++){
prop = props[i]
// if no more props (but we should be matching them)
// return null
if( typeof prop !== 'string' ) {
return null;
} else
// if we have a "**", match everything
if( parts[i] == "**" ) {
return props.join(".");
} else
// a match, but we want to delegate to "*"
if (parts[i] == "*"){
// only do this if there is nothing after ...
matchedProps.push(prop);
}
else if( prop === parts[i] ) {
matchedProps.push(prop);
} else {
return null;
}
}
return matchedProps.join(".");
},
// gets a change event and tries to figure out which
// delegates to call
delegate = function(event, prop, how, newVal, oldVal){
// pre-split properties to save some regexp time
var props = prop.split("."),
delegates = (this._observe_delegates || []).slice(0),
delegate,
attr,
matchedAttr,
hasMatch,
valuesEqual;
event.attr = prop;
event.lastAttr = props[props.length -1 ];
// for each delegate
for(var i =0; delegate = delegates[i++];){
// if there is a batchNum, this means that this
// event is part of a series of events caused by a single
// attrs call. We don't want to issue the same event
// multiple times
// setting the batchNum happens later
if((event.batchNum && delegate.batchNum === event.batchNum) || delegate.undelegated ){
continue;
}
// reset match and values tests
hasMatch = undefined;
valuesEqual = true;
// for each attr in a delegate
for(var a =0 ; a < delegate.attrs.length; a++){
attr = delegate.attrs[a];
// check if it is a match
if(matchedAttr = matches(attr.parts, props)){
hasMatch = matchedAttr;
}
// if it has a value, make sure it's the right value
// if it's set, we should probably check that it has a
// value no matter what
if(attr.value && valuesEqual /* || delegate.hasValues */){
valuesEqual = attr.value === ""+this.attr(attr.attr)
} else if (valuesEqual && delegate.attrs.length > 1){
// if there are multiple attributes, each has to at
// least have some value
valuesEqual = this.attr(attr.attr) !== undefined
}
}
// if there is a match and valuesEqual ... call back
if(hasMatch && valuesEqual) {
// how to get to the changed property from the delegate
var from = prop.replace(hasMatch+".","");
// if this event is part of a batch, set it on the delegate
// to only send one event
if(event.batchNum ){
delegate.batchNum = event.batchNum
}
// if we listen to change, fire those with the same attrs
// TODO: the attrs should probably be using from
if( delegate.event === 'change' ){
arguments[1] = from;
event.curAttr = hasMatch;
delegate.callback.apply(this.attr(hasMatch), can.makeArray( arguments));
} else if(delegate.event === how ){
// if it's a match, callback with the location of the match
delegate.callback.apply(this.attr(hasMatch), [event,newVal, oldVal, from]);
} else if(delegate.event === 'set' &&
how == 'add' ) {
// if we are listening to set, we should also listen to add
delegate.callback.apply(this.attr(hasMatch), [event,newVal, oldVal, from]);
}
}
}
};
can.extend(can.Observe.prototype,{
/**
* @function can.Observe.prototype.delegate
* @parent can.Observe.delegate
* @plugin can/observe/delegate
*
* `delegate( selector, event, handler(ev,newVal,oldVal,from) )` listen for changes
* in a child attribute from the parent. The child attribute
* does not have to exist.
*
*
* // create an observable
* var observe = can.Observe({
* foo : {
* bar : "Hello World"
* }
* })
*
* //listen to changes on a property
* observe.delegate("foo.bar","change", function(ev, prop, how, newVal, oldVal){
* // foo.bar has been added, set, or removed
* this //->
* });
*
* // change the property
* observe.attr('foo.bar',"Goodbye Cruel World")
*
* ## Types of events
*
* Delegate lets you listen to add, set, remove, and change events on property.
*
* __add__
*
* An add event is fired when a new property has been added.
*
* var o = new can.Control({});
* o.delegate("name","add", function(ev, value){
* // called once
* can.$('#name').show()
* })
* o.attr('name',"Justin")
* o.attr('name',"Brian");
*
* Listening to add events is useful for 'setup' functionality (in this case
* showing the <code>#name</code> element.
*
* __set__
*
* Set events are fired when a property takes on a new value. set events are
* always fired after an add.
*
* o.delegate("name","set", function(ev, value){
* // called twice
* can.$('#name').text(value)
* })
* o.attr('name',"Justin")
* o.attr('name',"Brian");
*
* __remove__
*
* Remove events are fired after a property is removed.
*
* o.delegate("name","remove", function(ev){
* // called once
* $('#name').text(value)
* })
* o.attr('name',"Justin");
* o.removeAttr('name');
*
* ## Wildcards - matching multiple properties
*
* Sometimes, you want to know when any property within some part
* of an observe has changed. Delegate lets you use wildcards to
* match any property name. The following listens for any change
* on an attribute of the params attribute:
*
* var o = can.Control({
* options : {
* limit : 100,
* offset: 0,
* params : {
* parentId: 5
* }
* }
* })
* o.delegate('options.*','change', function(){
* alert('1');
* })
* o.delegate('options.**','change', function(){
* alert('2');
* })
*
* // alerts 1
* // alerts 2
* o.attr('options.offset',100)
*
* // alerts 2
* o.attr('options.params.parentId',6);
*
* Using a single wildcard (<code>*</code>) matches single level
* properties. Using a double wildcard (<code>**</code>) matches
* any deep property.
*
* ## Listening on multiple properties and values
*
* Delegate lets you listen on multiple values at once. The following listens
* for first and last name changes:
*
* var o = new can.Observe({
* name : {first: "Justin", last: "Meyer"}
* })
*
* o.bind("name.first,name.last",
* "set",
* function(ev,newVal,oldVal,from){
*
* })
*
* ## Listening when properties are a particular value
*
* Delegate lets you listen when a property is __set__ to a specific value:
*
* var o = new can.Observe({
* name : "Justin"
* })
*
* o.bind("name=Brian",
* "set",
* function(ev,newVal,oldVal,from){
*
* })
*
* @param {String} selector The attributes you want to listen for changes in.
*
* Selector should be the property or
* property names of the element you are searching. Examples:
*
* "name" - listens to the "name" property changing
* "name, address" - listens to "name" or "address" changing
* "name address" - listens to "name" or "address" changing
* "address.*" - listens to property directly in address
* "address.**" - listens to any property change in address
* "foo=bar" - listens when foo is "bar"
*
* @param {String} event The event name. One of ("set","add","remove","change")
* @param {Function} handler(ev,newVal,oldVal,prop) The callback handler
* called with:
*
* - newVal - the new value set on the observe
* - oldVal - the old value set on the observe
* - prop - the prop name that was changed
*
* @return {jQuery.Delegate} the delegate for chaining
*/
delegate : function(selector, event, handler){
selector = can.trim(selector);
var delegates = this._observe_delegates || (this._observe_delegates = []),
attrs = [];
// split selector by spaces
selector.replace(/([^\s=]+)=?([^\s]+)?/g, function(whole, attr, value){
attrs.push({
// the attribute name
attr: attr,
// the attribute's pre-split names (for speed)
parts: attr.split('.'),
// the value associated with this prop
value: value
})
});
// delegates has pre-processed info about the event
delegates.push({
// the attrs name for unbinding
selector : selector,
// an object of attribute names and values {type: 'recipe',id: undefined}
// undefined means a value was not defined
attrs : attrs,
callback : handler,
event: event
});
if(delegates.length === 1){
this.bind("change",delegate)
}
return this;
},
/**
* @function can.Observe.prototype.undelegate
* @parent can.Observe.delegate
*
* `undelegate( selector, event, handler )` removes a delegated event handler from an observe.
*
* observe.undelegate("name","set", handler )
*
* @param {String} selector the attribute name of the object you want to undelegate from.
* @param {String} event the event name
* @param {Function} handler the callback handler
* @return {jQuery.Delegate} the delegate for chaining
*/
undelegate : function(selector, event, handler){
selector = can.trim(selector);
var i =0,
delegates = this._observe_delegates || [],
delegateOb;
if(selector){
while(i < delegates.length){
delegateOb = delegates[i];
if( delegateOb.callback === handler ||
(!handler && delegateOb.selector === selector) ){
delegateOb.undelegated = true;
delegates.splice(i,1)
} else {
i++;
}
}
} else {
// remove all delegates
delegates = [];
}
if(!delegates.length){
//can.removeData(this, "_observe_delegates");
this.unbind("change",delegate)
}
return this;
}
});
// add helpers for testing ..
can.Observe.prototype.delegate.matches = matches;
return can.Observe;
})
| SpredfastLegacy/canjs | observe/delegate/delegate.js | JavaScript | mit | 11,161 |
//-----------------------------------------------------------------------
// Copyright © Microsoft Corporation. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace Microsoft.PowerShell.Commands
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Management.Automation;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using Microsoft.PowerShell.Commands.ShowCommandExtension;
/// <summary>
/// Show-Command displays a GUI for a cmdlet, or for all cmdlets if no specific cmdlet is specified.
/// </summary>
[Cmdlet(VerbsCommon.Show, "Command", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=217448")]
public class ShowCommandCommand : PSCmdlet, IDisposable
{
#region Private Fields
/// <summary>
/// Set to true when ProcessRecord is reached, since it will always open a window
/// </summary>
private bool _hasOpenedWindow;
/// <summary>
/// Determines if the command should be sent to the pipeline as a string instead of run.
/// </summary>
private bool _passThrough;
/// <summary>
/// Uses ShowCommandProxy to invoke WPF GUI object.
/// </summary>
private ShowCommandProxy _showCommandProxy;
/// <summary>
/// Data container for all cmdlets. This is populated when show-command is called with no command name.
/// </summary>
private List<ShowCommandCommandInfo> _commands;
/// <summary>
/// List of modules that have been loaded indexed by module name
/// </summary>
private Dictionary<string, ShowCommandModuleInfo> _importedModules;
/// <summary>
/// Record the EndProcessing error.
/// </summary>
private PSDataCollection<ErrorRecord> _errors = new PSDataCollection<ErrorRecord>();
/// <summary>
/// Field used for the NoCommonParameter parameter.
/// </summary>
private SwitchParameter _noCommonParameter;
/// <summary>
/// Object used for ShowCommand with a command name that holds the view model created for the command
/// </summary>
private object _commandViewModelObj;
#endregion
/// <summary>
/// Finalizes an instance of the ShowCommandCommand class
/// </summary>
~ShowCommandCommand()
{
this.Dispose(false);
}
#region Input Cmdlet Parameter
/// <summary>
/// Gets or sets the command name.
/// </summary>
[Parameter(Position = 0)]
[Alias("CommandName")]
public string Name { get; set; }
/// <summary>
/// Gets or sets the Width.
/// </summary>
[Parameter]
[ValidateRange(300, Int32.MaxValue)]
public double Height { get; set; }
/// <summary>
/// Gets or sets the Width.
/// </summary>
[Parameter]
[ValidateRange(300, Int32.MaxValue)]
public double Width { get; set; }
/// <summary>
/// Gets or sets a value indicating Common Parameters should not be displayed
/// </summary>
[Parameter]
public SwitchParameter NoCommonParameter
{
get { return _noCommonParameter; }
set { _noCommonParameter = value; }
}
/// <summary>
/// Gets or sets a value indicating errors should not cause a message window to be displayed
/// </summary>
[Parameter]
public SwitchParameter ErrorPopup { get; set; }
/// <summary>
/// Gets or sets a value indicating the command should be sent to the pipeline as a string instead of run
/// </summary>
[Parameter]
public SwitchParameter PassThru
{
get { return _passThrough; }
set { _passThrough = value; }
} // PassThru
#endregion
#region Public and Protected Methods
/// <summary>
/// Executes a PowerShell script, writing the output objects to the pipeline.
/// </summary>
/// <param name="script">Script to execute</param>
public void RunScript(string script)
{
if (_showCommandProxy == null || string.IsNullOrEmpty(script))
{
return;
}
if (_passThrough)
{
this.WriteObject(script);
return;
}
if (ErrorPopup)
{
this.RunScriptSilentlyAndWithErrorHookup(script);
return;
}
if (_showCommandProxy.HasHostWindow)
{
if (!_showCommandProxy.SetPendingISECommand(script))
{
this.RunScriptSilentlyAndWithErrorHookup(script);
}
return;
}
if (!ConsoleInputWithNativeMethods.AddToConsoleInputBuffer(script, true))
{
this.WriteDebug(FormatAndOut_out_gridview.CannotWriteToConsoleInputBuffer);
this.RunScriptSilentlyAndWithErrorHookup(script);
}
}
/// <summary>
/// Dispose method in IDisposable
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Initialize a proxy instance for show-command.
/// </summary>
protected override void BeginProcessing()
{
_showCommandProxy = new ShowCommandProxy(this);
if (_showCommandProxy.ScreenHeight < this.Height)
{
ErrorRecord error = new ErrorRecord(
new NotSupportedException(String.Format(CultureInfo.CurrentUICulture, FormatAndOut_out_gridview.PropertyValidate, "Height", _showCommandProxy.ScreenHeight)),
"PARAMETER_DATA_ERROR",
ErrorCategory.InvalidData,
null);
this.ThrowTerminatingError(error);
}
if (_showCommandProxy.ScreenWidth < this.Width)
{
ErrorRecord error = new ErrorRecord(
new NotSupportedException(String.Format(CultureInfo.CurrentUICulture, FormatAndOut_out_gridview.PropertyValidate, "Width", _showCommandProxy.ScreenWidth)),
"PARAMETER_DATA_ERROR",
ErrorCategory.InvalidData,
null);
this.ThrowTerminatingError(error);
}
}
/// <summary>
/// ProcessRecord with or without CommandName.
/// </summary>
protected override void ProcessRecord()
{
if (Name == null)
{
_hasOpenedWindow = this.CanProcessRecordForAllCommands();
}
else
{
_hasOpenedWindow = this.CanProcessRecordForOneCommand();
}
}
/// <summary>
/// Optionally displays errors in a message
/// </summary>
protected override void EndProcessing()
{
if (!_hasOpenedWindow)
{
return;
}
// We wait untill the window is loaded and then activate it
// to work arround the console window gaining activation somewhere
// in the end of ProcessRecord, which causes the keyboard focus
// (and use oif tab key to focus controls) to go away from the window
_showCommandProxy.WindowLoaded.WaitOne();
_showCommandProxy.ActivateWindow();
this.WaitForWindowClosedOrHelpNeeded();
this.RunScript(_showCommandProxy.GetScript());
if (_errors.Count == 0 || !ErrorPopup)
{
return;
}
StringBuilder errorString = new StringBuilder();
for (int i = 0; i < _errors.Count; i++)
{
if (i != 0)
{
errorString.AppendLine();
}
ErrorRecord error = _errors[i];
errorString.Append(error.Exception.Message);
}
_showCommandProxy.ShowErrorString(errorString.ToString());
}
/// <summary>
/// StopProcessing is called close the window when user press Ctrl+C in the command prompt.
/// </summary>
protected override void StopProcessing()
{
_showCommandProxy.CloseWindow();
}
#endregion
#region Private Methods
/// <summary>
/// Runs the script in a new PowerShell instance and hooks up error stream to potentially display error popup.
/// This method has the inconvenience of not showing to the console user the script being executed.
/// </summary>
/// <param name="script">script to be run</param>
private void RunScriptSilentlyAndWithErrorHookup(string script)
{
// errors are not created here, because there is a field for it used in the final pop up
PSDataCollection<object> output = new PSDataCollection<object>();
output.DataAdded += new EventHandler<DataAddedEventArgs>(this.Output_DataAdded);
_errors.DataAdded += new EventHandler<DataAddedEventArgs>(this.Error_DataAdded);
PowerShell ps = PowerShell.Create(RunspaceMode.CurrentRunspace);
ps.Streams.Error = _errors;
ps.Commands.AddScript(script);
ps.Invoke(null, output, null);
}
/// <summary>
/// Issues an error when this.commandName was not found
/// </summary>
private void IssueErrorForNoCommand()
{
InvalidOperationException errorException = new InvalidOperationException(
String.Format(
CultureInfo.CurrentUICulture,
FormatAndOut_out_gridview.CommandNotFound,
Name));
this.ThrowTerminatingError(new ErrorRecord(errorException, "NoCommand", ErrorCategory.InvalidOperation, Name));
}
/// <summary>
/// Issues an error when there is more than one command matching this.commandName
/// </summary>
private void IssueErrorForMoreThanOneCommand()
{
InvalidOperationException errorException = new InvalidOperationException(
String.Format(
CultureInfo.CurrentUICulture,
FormatAndOut_out_gridview.MoreThanOneCommand,
Name,
"Show-Command"));
this.ThrowTerminatingError(new ErrorRecord(errorException, "MoreThanOneCommand", ErrorCategory.InvalidOperation, Name));
}
/// <summary>
/// Called from CommandProcessRecord to run the command that will get the CommandInfo and list of modules
/// </summary>
/// <param name="command">command to be retrieved</param>
/// <param name="modules">list of loaded modules</param>
private void GetCommandInfoAndModules(out CommandInfo command, out Dictionary<string, ShowCommandModuleInfo> modules)
{
command = null;
modules = null;
string commandText = _showCommandProxy.GetShowCommandCommand(Name, true);
Collection<PSObject> commandResults = this.InvokeCommand.InvokeScript(commandText);
object[] commandObjects = (object[])commandResults[0].BaseObject;
object[] moduleObjects = (object[])commandResults[1].BaseObject;
if (commandResults == null || moduleObjects == null || commandObjects.Length == 0)
{
this.IssueErrorForNoCommand();
return;
}
if (commandObjects.Length > 1)
{
this.IssueErrorForMoreThanOneCommand();
}
command = ((PSObject)commandObjects[0]).BaseObject as CommandInfo;
if (command == null)
{
this.IssueErrorForNoCommand();
return;
}
if (command.CommandType == CommandTypes.Alias)
{
commandText = _showCommandProxy.GetShowCommandCommand(command.Definition, false);
commandResults = this.InvokeCommand.InvokeScript(commandText);
if (commandResults == null || commandResults.Count != 1)
{
this.IssueErrorForNoCommand();
return;
}
command = (CommandInfo)commandResults[0].BaseObject;
}
modules = _showCommandProxy.GetImportedModulesDictionary(moduleObjects);
}
/// <summary>
/// ProcessRecord when a command name is specified.
/// </summary>
/// <returns>true if there was no exception processing this record</returns>
private bool CanProcessRecordForOneCommand()
{
CommandInfo commandInfo;
this.GetCommandInfoAndModules(out commandInfo, out _importedModules);
Diagnostics.Assert(commandInfo != null, "GetCommandInfoAndModules would throw a terminating error/exception");
try
{
_commandViewModelObj = _showCommandProxy.GetCommandViewModel(new ShowCommandCommandInfo(commandInfo), _noCommonParameter.ToBool(), _importedModules, this.Name.IndexOf('\\') != -1);
_showCommandProxy.ShowCommandWindow(_commandViewModelObj, _passThrough);
}
catch (TargetInvocationException ti)
{
this.WriteError(new ErrorRecord(ti.InnerException, "CannotProcessRecordForOneCommand", ErrorCategory.InvalidOperation, Name));
return false;
}
return true;
}
/// <summary>
/// ProcessRecord when a command name is not specified.
/// </summary>
/// <returns>true if there was no exception processing this record</returns>
private bool CanProcessRecordForAllCommands()
{
Collection<PSObject> rawCommands = this.InvokeCommand.InvokeScript(_showCommandProxy.GetShowAllModulesCommand());
_commands = _showCommandProxy.GetCommandList((object[])rawCommands[0].BaseObject);
_importedModules = _showCommandProxy.GetImportedModulesDictionary((object[])rawCommands[1].BaseObject);
try
{
_showCommandProxy.ShowAllModulesWindow(_importedModules, _commands, _noCommonParameter.ToBool(), _passThrough);
}
catch (TargetInvocationException ti)
{
this.WriteError(new ErrorRecord(ti.InnerException, "CannotProcessRecordForAllCommands", ErrorCategory.InvalidOperation, Name));
return false;
}
return true;
}
/// <summary>
/// Waits untill the window has been closed answering HelpNeeded events
/// </summary>
private void WaitForWindowClosedOrHelpNeeded()
{
do
{
int which = WaitHandle.WaitAny(new WaitHandle[] { _showCommandProxy.WindowClosed, _showCommandProxy.HelpNeeded, _showCommandProxy.ImportModuleNeeded });
if (which == 0)
{
break;
}
if (which == 1)
{
Collection<PSObject> helpResults = this.InvokeCommand.InvokeScript(_showCommandProxy.GetHelpCommand(_showCommandProxy.CommandNeedingHelp));
_showCommandProxy.DisplayHelp(helpResults);
continue;
}
Diagnostics.Assert(which == 2, "which is 0,1 or 2 and 0 and 1 have been eliminated in the ifs above");
string commandToRun = _showCommandProxy.GetImportModuleCommand(_showCommandProxy.ParentModuleNeedingImportModule);
Collection<PSObject> rawCommands;
try
{
rawCommands = this.InvokeCommand.InvokeScript(commandToRun);
}
catch (RuntimeException e)
{
_showCommandProxy.ImportModuleFailed(e);
continue;
}
_commands = _showCommandProxy.GetCommandList((object[])rawCommands[0].BaseObject);
_importedModules = _showCommandProxy.GetImportedModulesDictionary((object[])rawCommands[1].BaseObject);
_showCommandProxy.ImportModuleDone(_importedModules, _commands);
continue;
}
while (true);
}
/// <summary>
/// Writes the output of a script being run into the pipeline
/// </summary>
/// <param name="sender">output collection</param>
/// <param name="e">output event</param>
private void Output_DataAdded(object sender, DataAddedEventArgs e)
{
this.WriteObject(((PSDataCollection<object>)sender)[e.Index]);
}
/// <summary>
/// Writes the errors of a script being run into the pipeline
/// </summary>
/// <param name="sender">error collection</param>
/// <param name="e">error event</param>
private void Error_DataAdded(object sender, DataAddedEventArgs e)
{
this.WriteError(((PSDataCollection<ErrorRecord>)sender)[e.Index]);
}
/// <summary>
/// Implements IDisposable logic
/// </summary>
/// <param name="isDisposing">true if being called from Dispose</param>
private void Dispose(bool isDisposing)
{
if (isDisposing)
{
if (_errors != null)
{
_errors.Dispose();
_errors = null;
}
}
}
#endregion
/// <summary>
/// Wraps interop code for console input buffer
/// </summary>
internal static class ConsoleInputWithNativeMethods
{
/// <summary>
/// Constant used in calls to GetStdHandle
/// </summary>
internal const int STD_INPUT_HANDLE = -10;
/// <summary>
/// Adds a string to the console input buffer
/// </summary>
/// <param name="str">string to add to console input buffer</param>
/// <param name="newLine">true to add Enter after the string</param>
/// <returns>true if it was successful in adding all characters to console input buffer</returns>
internal static bool AddToConsoleInputBuffer(string str, bool newLine)
{
IntPtr handle = ConsoleInputWithNativeMethods.GetStdHandle(ConsoleInputWithNativeMethods.STD_INPUT_HANDLE);
if (handle == IntPtr.Zero)
{
return false;
}
uint strLen = (uint)str.Length;
ConsoleInputWithNativeMethods.INPUT_RECORD[] records = new ConsoleInputWithNativeMethods.INPUT_RECORD[strLen + (newLine ? 1 : 0)];
for (int i = 0; i < strLen; i++)
{
ConsoleInputWithNativeMethods.INPUT_RECORD.SetInputRecord(ref records[i], str[i]);
}
uint written;
if (!ConsoleInputWithNativeMethods.WriteConsoleInput(handle, records, strLen, out written) || written != strLen)
{
// I do not know of a case where written is not going to be strlen. Maybe for some character that
// is not supported in the console. The API suggests this can happen,
// so we handle it by returning false
return false;
}
// Enter is written separately, because if this is a command, and one of the characters in the command was not written
// (written != strLen) it is desireable to fail (return false) before typing enter and running the command
if (newLine)
{
ConsoleInputWithNativeMethods.INPUT_RECORD[] enterArray = new ConsoleInputWithNativeMethods.INPUT_RECORD[1];
ConsoleInputWithNativeMethods.INPUT_RECORD.SetInputRecord(ref enterArray[0], (char)13);
written = 0;
if (!ConsoleInputWithNativeMethods.WriteConsoleInput(handle, enterArray, 1, out written))
{
// I don't think this will happen
return false;
}
Diagnostics.Assert(written == 1, "only Enter is being added and it is a supported character");
}
return true;
}
/// <summary>
/// Gets the console handle
/// </summary>
/// <param name="nStdHandle">which console handle to get</param>
/// <returns>the console handle</returns>
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern IntPtr GetStdHandle(int nStdHandle);
/// <summary>
/// Writes to the console input buffer
/// </summary>
/// <param name="hConsoleInput">console handle</param>
/// <param name="lpBuffer">inputs to be written</param>
/// <param name="nLength">number of inputs to be written</param>
/// <param name="lpNumberOfEventsWritten">returned number of inputs actually written</param>
/// <returns>0 if the function fails</returns>
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool WriteConsoleInput(
IntPtr hConsoleInput,
INPUT_RECORD[] lpBuffer,
uint nLength,
out uint lpNumberOfEventsWritten);
/// <summary>
/// A record to be added to the console buffer
/// </summary>
internal struct INPUT_RECORD
{
/// <summary>
/// The proper event type for a KeyEvent KEY_EVENT_RECORD
/// </summary>
internal const int KEY_EVENT = 0x0001;
/// <summary>
/// input buffer event type
/// </summary>
internal ushort EventType;
/// <summary>
/// The actual event. The original structure is a union of many others, but this is the largest of them
/// And we don't need other kinds of events
/// </summary>
internal KEY_EVENT_RECORD KeyEvent;
/// <summary>
/// Sets the necessary fields of <paramref name="inputRecord"/> for a KeyDown event for the <paramref name="character"/>
/// </summary>
/// <param name="inputRecord">input record to be set</param>
/// <param name="character">character to set the record with</param>
internal static void SetInputRecord(ref INPUT_RECORD inputRecord, char character)
{
inputRecord.EventType = INPUT_RECORD.KEY_EVENT;
inputRecord.KeyEvent.bKeyDown = true;
inputRecord.KeyEvent.UnicodeChar = character;
}
}
/// <summary>
/// Type of INPUT_RECORD which is a key
/// </summary>
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct KEY_EVENT_RECORD
{
/// <summary>
/// true for key down and false for key up, but only needed if wVirtualKeyCode is used
/// </summary>
internal bool bKeyDown;
/// <summary>
/// repeat count
/// </summary>
internal ushort wRepeatCount;
/// <summary>
/// virtual key code
/// </summary>
internal ushort wVirtualKeyCode;
/// <summary>
/// virtual key scan code
/// </summary>
internal ushort wVirtualScanCode;
/// <summary>
/// character in input. If this is specified, wVirtualKeyCode, and others don't need to be
/// </summary>
internal char UnicodeChar;
/// <summary>
/// State of keys like Shift and control
/// </summary>
internal uint dwControlKeyState;
}
}
}
}
| KarolKaczmarek/PowerShell | src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommand.cs | C# | mit | 25,295 |
var name = "Wanderer";
var collection_type = 0;
var is_secret = 0;
var desc = "Visited 503 new locations.";
var status_text = "Gosh, where HAVEN'T you traveled? Your peregrinations have earned you this footworn-but-carefree Wanderer badge.";
var last_published = 1348803094;
var is_shareworthy = 1;
var url = "wanderer";
var category = "exploring";
var url_swf = "\/c2.glitch.bz\/achievements\/2011-09-18\/wanderer_1316414516.swf";
var url_img_180 = "\/c2.glitch.bz\/achievements\/2011-09-18\/wanderer_1316414516_180.png";
var url_img_60 = "\/c2.glitch.bz\/achievements\/2011-09-18\/wanderer_1316414516_60.png";
var url_img_40 = "\/c2.glitch.bz\/achievements\/2011-09-18\/wanderer_1316414516_40.png";
function on_apply(pc){
}
var conditions = {
8 : {
type : "group_count",
group : "locations_visited",
value : "503"
},
};
function onComplete(pc){ // generated from rewards
var multiplier = pc.buffs_has('gift_of_gab') ? 1.2 : pc.buffs_has('silvertongue') ? 1.05 : 1.0;
multiplier += pc.imagination_get_achievement_modifier();
if (/completist/i.exec(this.name)) {
var level = pc.stats_get_level();
if (level > 4) {
multiplier *= (pc.stats_get_level()/4);
}
}
pc.stats_add_xp(round_to_5(1000 * multiplier), true);
pc.stats_add_favor_points("lem", round_to_5(200 * multiplier));
if(pc.buffs_has('gift_of_gab')) {
pc.buffs_remove('gift_of_gab');
}
else if(pc.buffs_has('silvertongue')) {
pc.buffs_remove('silvertongue');
}
}
var rewards = {
"xp" : 1000,
"favor" : {
"giant" : "lem",
"points" : 200
}
};
// generated ok (NO DATE)
| yelworc/eleven-gsjs | achievements/wanderer.js | JavaScript | mit | 1,587 |
using System;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Markup.Xaml;
using Avalonia.Platform;
using Avalonia.Rendering;
using Avalonia.UnitTests;
using Moq;
using Xunit;
namespace Avalonia.Controls.UnitTests
{
public class ContextMenuTests
{
private Mock<IPopupImpl> popupImpl;
private MouseTestHelper _mouse = new MouseTestHelper();
[Fact]
public void ContextRequested_Opens_ContextMenu()
{
using (Application())
{
var sut = new ContextMenu();
var target = new Panel
{
ContextMenu = sut
};
var window = new Window { Content = target };
window.ApplyTemplate();
window.Presenter.ApplyTemplate();
int openedCount = 0;
sut.MenuOpened += (sender, args) =>
{
openedCount++;
};
target.RaiseEvent(new ContextRequestedEventArgs());
Assert.True(sut.IsOpen);
Assert.Equal(1, openedCount);
}
}
[Fact]
public void ContextMenu_Is_Opened_When_ContextFlyout_Is_Also_Set()
{
// We have this test for backwards compatability with the code that already sets custom ContextMenu.
using (Application())
{
var sut = new ContextMenu();
var flyout = new Flyout();
var target = new Panel
{
ContextMenu = sut,
ContextFlyout = flyout
};
var window = new Window { Content = target };
window.ApplyTemplate();
window.Presenter.ApplyTemplate();
target.RaiseEvent(new ContextRequestedEventArgs());
Assert.True(sut.IsOpen);
Assert.False(flyout.IsOpen);
}
}
[Fact]
public void KeyUp_Raised_On_Target_Opens_ContextFlyout()
{
using (Application())
{
var sut = new ContextMenu();
var target = new Panel
{
ContextMenu = sut
};
var contextRequestedCount = 0;
target.AddHandler(Control.ContextRequestedEvent, (s, a) => contextRequestedCount++, Interactivity.RoutingStrategies.Tunnel);
var window = PreparedWindow(target);
window.Show();
target.RaiseEvent(new KeyEventArgs { RoutedEvent = InputElement.KeyUpEvent, Key = Key.Apps, Source = window });
Assert.True(sut.IsOpen);
Assert.Equal(1, contextRequestedCount);
}
}
[Fact]
public void KeyUp_Raised_On_Flyout_Closes_Opened_ContextMenu()
{
using (Application())
{
var sut = new ContextMenu();
var target = new Panel
{
ContextMenu = sut
};
var window = PreparedWindow(target);
window.Show();
target.RaiseEvent(new ContextRequestedEventArgs());
Assert.True(sut.IsOpen);
sut.RaiseEvent(new KeyEventArgs { RoutedEvent = InputElement.KeyUpEvent, Key = Key.Apps, Source = window });
Assert.False(sut.IsOpen);
}
}
[Fact]
public void Opening_Raises_Single_Opened_Event()
{
using (Application())
{
var sut = new ContextMenu();
var target = new Panel
{
ContextMenu = sut
};
var window = new Window { Content = target };
window.ApplyTemplate();
window.Presenter.ApplyTemplate();
int openedCount = 0;
sut.MenuOpened += (sender, args) =>
{
openedCount++;
};
sut.Open(target);
Assert.Equal(1, openedCount);
}
}
[Fact]
public void Open_Should_Use_Default_Control()
{
using (Application())
{
var sut = new ContextMenu();
var target = new Panel
{
ContextMenu = sut
};
var window = new Window { Content = target };
window.ApplyTemplate();
window.Presenter.ApplyTemplate();
bool opened = false;
sut.MenuOpened += (sender, args) =>
{
opened = true;
};
sut.Open();
Assert.True(opened);
}
}
[Fact]
public void Open_Should_Raise_Exception_If_AlreadyDetached()
{
using (Application())
{
var sut = new ContextMenu();
var target = new Panel
{
ContextMenu = sut
};
var window = new Window { Content = target };
window.ApplyTemplate();
window.Presenter.ApplyTemplate();
target.ContextMenu = null;
Assert.ThrowsAny<Exception>(()=> sut.Open());
}
}
[Fact]
public void Closing_Raises_Single_Closed_Event()
{
using (Application())
{
var sut = new ContextMenu();
var target = new Panel
{
ContextMenu = sut
};
var window = new Window { Content = target };
window.ApplyTemplate();
window.Presenter.ApplyTemplate();
sut.Open(target);
int closedCount = 0;
sut.MenuClosed += (sender, args) =>
{
closedCount++;
};
sut.Close();
Assert.Equal(1, closedCount);
}
}
[Fact]
public void Cancel_Light_Dismiss_Closing_Keeps_Flyout_Open()
{
using (Application())
{
popupImpl.Setup(x => x.Show(true, false)).Verifiable();
popupImpl.Setup(x => x.Hide()).Verifiable();
var window = PreparedWindow();
window.Width = 100;
window.Height = 100;
var button = new Button
{
Height = 10,
Width = 10,
HorizontalAlignment = Layout.HorizontalAlignment.Left,
VerticalAlignment = Layout.VerticalAlignment.Top
};
window.Content = button;
window.ApplyTemplate();
window.Show();
var tracker = 0;
var c = new ContextMenu();
c.ContextMenuClosing += (s, e) =>
{
tracker++;
e.Cancel = true;
};
button.ContextMenu = c;
c.Open(button);
var overlay = LightDismissOverlayLayer.GetLightDismissOverlayLayer(window);
_mouse.Down(overlay, MouseButton.Left, new Point(90, 90));
_mouse.Up(button, MouseButton.Left, new Point(90, 90));
Assert.Equal(1, tracker);
Assert.True(c.IsOpen);
popupImpl.Verify(x => x.Hide(), Times.Never);
popupImpl.Verify(x => x.Show(true, false), Times.Exactly(1));
}
}
[Fact]
public void Light_Dismiss_Closes_Flyout()
{
using (Application())
{
popupImpl.Setup(x => x.Show(true, false)).Verifiable();
popupImpl.Setup(x => x.Hide()).Verifiable();
var window = PreparedWindow();
window.Width = 100;
window.Height = 100;
var button = new Button
{
Height = 10,
Width = 10,
HorizontalAlignment = Layout.HorizontalAlignment.Left,
VerticalAlignment = Layout.VerticalAlignment.Top
};
window.Content = button;
window.ApplyTemplate();
window.Show();
var c = new ContextMenu();
c.PlacementMode = PlacementMode.Bottom;
c.Open(button);
var overlay = LightDismissOverlayLayer.GetLightDismissOverlayLayer(window);
_mouse.Down(overlay, MouseButton.Left, new Point(90, 90));
_mouse.Up(button, MouseButton.Left, new Point(90, 90));
Assert.False(c.IsOpen);
popupImpl.Verify(x => x.Hide(), Times.Exactly(1));
popupImpl.Verify(x => x.Show(true, false), Times.Exactly(1));
}
}
[Fact]
public void Clicking_On_Control_Toggles_ContextMenu()
{
using (Application())
{
popupImpl.Setup(x => x.Show(true, false)).Verifiable();
popupImpl.Setup(x => x.Hide()).Verifiable();
var sut = new ContextMenu();
var target = new Panel
{
ContextMenu = sut
};
var window = PreparedWindow(target);
window.Show();
var overlay = LightDismissOverlayLayer.GetLightDismissOverlayLayer(window);
_mouse.Click(target, MouseButton.Right);
Assert.True(sut.IsOpen);
_mouse.Down(overlay);
_mouse.Up(target);
Assert.False(sut.IsOpen);
popupImpl.Verify(x => x.Show(true, false), Times.Once);
popupImpl.Verify(x => x.Hide(), Times.Once);
}
}
[Fact]
public void Right_Clicking_On_Control_Twice_Re_Opens_ContextMenu()
{
using (Application())
{
popupImpl.Setup(x => x.Show(true, false)).Verifiable();
popupImpl.Setup(x => x.Hide()).Verifiable();
var sut = new ContextMenu();
var target = new Panel
{
ContextMenu = sut
};
var window = PreparedWindow(target);
window.Show();
var overlay = LightDismissOverlayLayer.GetLightDismissOverlayLayer(window);
_mouse.Click(target, MouseButton.Right);
Assert.True(sut.IsOpen);
_mouse.Down(overlay, MouseButton.Right);
_mouse.Up(target, MouseButton.Right);
Assert.True(sut.IsOpen);
popupImpl.Verify(x => x.Hide(), Times.Once);
popupImpl.Verify(x => x.Show(true, false), Times.Exactly(2));
}
}
[Fact]
public void Context_Menu_Can_Be_Shared_Between_Controls_Even_After_A_Control_Is_Removed_From_Visual_Tree()
{
using (Application())
{
var sut = new ContextMenu();
var target1 = new Panel
{
ContextMenu = sut
};
var target2 = new Panel
{
ContextMenu = sut
};
var sp = new StackPanel { Children = { target1, target2 } };
var window = new Window { Content = sp };
window.ApplyTemplate();
window.Presenter.ApplyTemplate();
_mouse.Click(target1, MouseButton.Right);
Assert.True(sut.IsOpen);
sp.Children.Remove(target1);
Assert.False(sut.IsOpen);
_mouse.Click(target2, MouseButton.Right);
Assert.True(sut.IsOpen);
}
}
[Fact]
public void Cancelling_Opening_Does_Not_Show_ContextMenu()
{
using (Application())
{
popupImpl.Setup(x => x.Show(true, false)).Verifiable();
bool eventCalled = false;
var sut = new ContextMenu();
var target = new Panel
{
ContextMenu = sut
};
new Window { Content = target };
sut.ContextMenuOpening += (c, e) => { eventCalled = true; e.Cancel = true; };
_mouse.Click(target, MouseButton.Right);
Assert.True(eventCalled);
Assert.False(sut.IsOpen);
popupImpl.Verify(x => x.Show(true, false), Times.Never);
}
}
[Fact]
public void Can_Set_Clear_ContextMenu_Property()
{
using (Application())
{
var target = new ContextMenu();
var control = new Panel();
control.ContextMenu = target;
control.ContextMenu = null;
}
}
[Fact]
public void Context_Menu_In_Resources_Can_Be_Shared()
{
using (Application())
{
var xaml = @"
<Window xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
<Window.Resources>
<ContextMenu x:Key='contextMenu'>
<MenuItem>Foo</MenuItem>
</ContextMenu>
</Window.Resources>
<StackPanel>
<TextBlock Name='target1' ContextMenu='{StaticResource contextMenu}'/>
<TextBlock Name='target2' ContextMenu='{StaticResource contextMenu}'/>
</StackPanel>
</Window>";
var window = (Window)AvaloniaRuntimeXamlLoader.Load(xaml);
var target1 = window.Find<TextBlock>("target1");
var target2 = window.Find<TextBlock>("target2");
var mouse = new MouseTestHelper();
Assert.NotNull(target1.ContextMenu);
Assert.NotNull(target2.ContextMenu);
Assert.Same(target1.ContextMenu, target2.ContextMenu);
window.Show();
var menu = target1.ContextMenu;
mouse.Click(target1, MouseButton.Right);
Assert.True(menu.IsOpen);
mouse.Click(target2, MouseButton.Right);
Assert.True(menu.IsOpen);
}
}
[Fact]
public void Context_Menu_Can_Be_Set_In_Style()
{
using (Application())
{
var xaml = @"
<Window xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
<Window.Styles>
<Style Selector='TextBlock'>
<Setter Property='ContextMenu'>
<ContextMenu>
<MenuItem>Foo</MenuItem>
</ContextMenu>
</Setter>
</Style>
</Window.Styles>
<StackPanel>
<TextBlock Name='target1'/>
<TextBlock Name='target2'/>
</StackPanel>
</Window>";
var window = (Window)AvaloniaRuntimeXamlLoader.Load(xaml);
var target1 = window.Find<TextBlock>("target1");
var target2 = window.Find<TextBlock>("target2");
var mouse = new MouseTestHelper();
Assert.NotNull(target1.ContextMenu);
Assert.NotNull(target2.ContextMenu);
Assert.Same(target1.ContextMenu, target2.ContextMenu);
window.Show();
var menu = target1.ContextMenu;
mouse.Click(target1, MouseButton.Right);
Assert.True(menu.IsOpen);
mouse.Click(target2, MouseButton.Right);
Assert.True(menu.IsOpen);
}
}
[Fact]
public void Cancelling_Closing_Leaves_ContextMenuOpen()
{
using (Application())
{
popupImpl.Setup(x => x.Show(true, false)).Verifiable();
popupImpl.Setup(x => x.Hide()).Verifiable();
bool eventCalled = false;
var sut = new ContextMenu();
var target = new Panel
{
ContextMenu = sut
};
var window = PreparedWindow(target);
var overlay = LightDismissOverlayLayer.GetLightDismissOverlayLayer(window);
sut.ContextMenuClosing += (c, e) => { eventCalled = true; e.Cancel = true; };
window.Show();
_mouse.Click(target, MouseButton.Right);
Assert.True(sut.IsOpen);
_mouse.Down(overlay, MouseButton.Right);
_mouse.Up(target, MouseButton.Right);
Assert.True(eventCalled);
Assert.True(sut.IsOpen);
popupImpl.Verify(x => x.Show(true, false), Times.Once());
popupImpl.Verify(x => x.Hide(), Times.Never);
}
}
private Window PreparedWindow(object content = null)
{
var renderer = new Mock<IRenderer>();
var platform = AvaloniaLocator.Current.GetService<IWindowingPlatform>();
var windowImpl = Mock.Get(platform.CreateWindow());
windowImpl.Setup(x => x.CreateRenderer(It.IsAny<IRenderRoot>())).Returns(renderer.Object);
var w = new Window(windowImpl.Object) { Content = content };
w.ApplyTemplate();
w.Presenter.ApplyTemplate();
return w;
}
private IDisposable Application()
{
var screen = new PixelRect(new PixelPoint(), new PixelSize(100, 100));
var screenImpl = new Mock<IScreenImpl>();
screenImpl.Setup(x => x.ScreenCount).Returns(1);
screenImpl.Setup(X => X.AllScreens).Returns( new[] { new Screen(1, screen, screen, true) });
var windowImpl = MockWindowingPlatform.CreateWindowMock();
popupImpl = MockWindowingPlatform.CreatePopupMock(windowImpl.Object);
popupImpl.SetupGet(x => x.RenderScaling).Returns(1);
windowImpl.Setup(x => x.CreatePopup()).Returns(popupImpl.Object);
windowImpl.Setup(x => x.Screen).Returns(screenImpl.Object);
var services = TestServices.StyledWindow.With(
inputManager: new InputManager(),
windowImpl: windowImpl.Object,
windowingPlatform: new MockWindowingPlatform(() => windowImpl.Object, x => popupImpl.Object));
return UnitTestApplication.Start(services);
}
}
}
| AvaloniaUI/Avalonia | tests/Avalonia.Controls.UnitTests/ContextMenuTests.cs | C# | mit | 19,072 |
using System.Drawing;
namespace JR.DevFw.Framework.Graphic
{
/// <summary>
/// 绘图处理
/// </summary>
/// <param name="img"></param>
public delegate void ImageGraphicsHandler(Image img);
} | jrsix/devfw | src/core/J6.DevFw.Core/Framework/Graphic/ImageGraphicsHandler.cs | C# | mit | 217 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ClassLibrary.net46")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ClassLibrary.net46")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("10339478-bb59-4ef8-8b0e-8f38cf30a78a")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mmitche/xunit-performance | samples/ClassLibrary.net46/Properties/AssemblyInfo.cs | C# | mit | 1,412 |
export default class ModelAccessor {
constructor() {
this.value = 10
}
get highCount() {
return this.value + 100
}
set highCount(v) {
this.value = v - 100
}
get doubleHigh() {
return this.highCount * 2
}
incr() {
this.value++
}
}
| nekronos/fuselibs-public | Source/Fuse.Models/Tests/UX/Accessor.js | JavaScript | mit | 255 |
namespace AngleSharp.Dom
{
using AngleSharp.Attributes;
using System;
/// <summary>
/// The Range interface represents a fragment of a document that can
/// contain nodes and parts of text nodes in a given document.
/// </summary>
[DomName("Range")]
public interface IRange
{
/// <summary>
/// Gets the node that starts the container.
/// </summary>
[DomName("startContainer")]
INode Head { get; }
/// <summary>
/// Gets the offset of the StartContainer in the document.
/// </summary>
[DomName("startOffset")]
Int32 Start { get; }
/// <summary>
/// Gets the node that ends the container.
/// </summary>
[DomName("endContainer")]
INode Tail { get; }
/// <summary>
/// Gets the offset of the EndContainer in the document.
/// </summary>
[DomName("endOffset")]
Int32 End { get; }
/// <summary>
/// Gets a value that indicates if the representation is collapsed.
/// </summary>
[DomName("collapsed")]
Boolean IsCollapsed { get; }
/// <summary>
/// Gets the common ancestor node of the contained range.
/// </summary>
[DomName("commonAncestorContainer")]
INode CommonAncestor { get; }
/// <summary>
/// Selects the start of the given range by using the given reference
/// node and a relative offset.
/// </summary>
/// <param name="refNode">The reference node to use.</param>
/// <param name="offset">
/// The offset relative to the reference node.
/// </param>
[DomName("setStart")]
void StartWith(INode refNode, Int32 offset);
/// <summary>
/// Selects the end of the given range by using the given reference
/// node and a relative offset.
/// </summary>
/// <param name="refNode">The reference node to use.</param>
/// <param name="offset">
/// The offset relative to the reference node.
/// </param>
[DomName("setEnd")]
void EndWith(INode refNode, Int32 offset);
/// <summary>
/// Selects the start of the given range by using an inclusive
/// reference node.
/// </summary>
/// <param name="refNode">The reference node to use.</param>
[DomName("setStartBefore")]
void StartBefore(INode refNode);
/// <summary>
/// Selects the end of the given range by using an inclusive reference
/// node.
/// </summary>
/// <param name="refNode">The reference node to use.</param>
[DomName("setEndBefore")]
void EndBefore(INode refNode);
/// <summary>
/// Selects the start of the given range by using an exclusive
/// reference node.
/// </summary>
/// <param name="refNode">The reference node to use.</param>
[DomName("setStartAfter")]
void StartAfter(INode refNode);
/// <summary>
/// Selects the end of the given range by using an exclusive reference
/// node.
/// </summary>
/// <param name="refNode">The referenced node.</param>
[DomName("setEndAfter")]
void EndAfter(INode refNode);
/// <summary>
/// Collapses the range to a single level.
/// </summary>
/// <param name="toStart">
/// Determines if only the first level should be selected.
/// </param>
[DomName("collapse")]
void Collapse(Boolean toStart);
/// <summary>
/// Selects the contained node.
/// </summary>
/// <param name="refNode">The node to use.</param>
[DomName("selectNode")]
void Select(INode refNode);
/// <summary>
/// Selects the contained nodes by taking a reference node as origin.
/// </summary>
/// <param name="refNode">The reference node.</param>
[DomName("selectNodeContents")]
void SelectContent(INode refNode);
/// <summary>
/// Clears the contained nodes.
/// </summary>
[DomName("deleteContents")]
void ClearContent();
/// <summary>
/// Clears the node representation and returns a document fragment with
/// the originally contained nodes.
/// </summary>
/// <returns>The document fragment containing the nodes.</returns>
[DomName("extractContents")]
IDocumentFragment ExtractContent();
/// <summary>
/// Creates a document fragement of the contained nodes.
/// </summary>
/// <returns>The created document fragment.</returns>
[DomName("cloneContents")]
IDocumentFragment CopyContent();
/// <summary>
/// Inserts a node into the range.
/// </summary>
/// <param name="node">The node to include.</param>
[DomName("insertNode")]
void Insert(INode node);
/// <summary>
/// Includes the given node with its siblings in the range.
/// </summary>
/// <param name="newParent">The range to surround.</param>
[DomName("surroundContents")]
void Surround(INode newParent);
/// <summary>
/// Creates a copy of this range.
/// </summary>
/// <returns>The copy representing the same range.</returns>
[DomName("cloneRange")]
IRange Clone();
/// <summary>
/// Detaches the range from the DOM tree.
/// </summary>
[DomName("detach")]
void Detach();
/// <summary>
/// Checks if the given node is within this range by using a offset.
/// </summary>
/// <param name="node">The node to check for.</param>
/// <param name="offset">The offset to use.</param>
/// <returns>
/// True if the point is within the range, otherwise false.
/// </returns>
[DomName("isPointInRange")]
Boolean Contains(INode node, Int32 offset);
/// <summary>
/// Compares the boundary points of the range.
/// </summary>
/// <param name="how">
/// Determines how these points should be compared.
/// </param>
/// <param name="sourceRange">
/// The range of the other boundary points.
/// </param>
/// <returns>A relative position.</returns>
[DomName("compareBoundaryPoints")]
RangePosition CompareBoundaryTo(RangeType how, IRange sourceRange);
/// <summary>
/// Compares the node to the given offset and returns the relative
/// position.
/// </summary>
/// <param name="node">The node to use.</param>
/// <param name="offset">The offset to use.</param>
/// <returns>The relative position in the range.</returns>
[DomName("comparePoint")]
RangePosition CompareTo(INode node, Int32 offset);
/// <summary>
/// Checks if the given node is contained in this range.
/// </summary>
/// <param name="node">The node to check for.</param>
/// <returns>
/// True if the node is within the range, otherwise false.
/// </returns>
[DomName("intersectsNode")]
Boolean Intersects(INode node);
}
}
| FlorianRappl/AngleSharp | src/AngleSharp/Interfaces/IRange.cs | C# | mit | 7,415 |
import { Template } from 'meteor/templating';
Template.messageAction.helpers({
isButton() {
return this.type === 'button';
},
areButtonsHorizontal() {
return Template.parentData(1).button_alignment === 'horizontal';
},
jsActionButtonClassname(processingType) {
return `js-actionButton-${ processingType || 'sendMessage' }`;
},
});
| 4thParty/Rocket.Chat | app/message-action/client/messageAction.js | JavaScript | mit | 344 |
import fs from 'fs';
import url from 'url';
import path from 'path';
import mime from 'mime-types';
import gulp from 'gulp';
import createServerTask from './tasks/server';
import consoleArguments from './console-arguments';
import { adminBundle } from './admin-bundle.tasks';
import { dashboardBundle } from './dashboard-bundle.tasks';
import { mediaBundle } from './media-bundle.tasks';
import { translatorBundle } from './translator-bundle.tasks';
const BUNDLES = [adminBundle, dashboardBundle, mediaBundle, translatorBundle];
const writeToResponse = (req, res, bundlePaths) => {
const formattedUrl = url.parse(req.url);
for (const bundlePath of bundlePaths) {
const filePath = path.normalize(bundlePath + formattedUrl.pathname);
try {
const stat = fs.statSync(filePath);
if (stat && stat.isFile()) {
const rstream = fs.createReadStream(filePath);
const extension = path.extname(filePath);
const contentType = mime.lookup(extension);
res.writeHead(200, {
'Content-Type': contentType,
'Content-Length': stat.size
});
rstream.pipe(res);
return;
}
} catch (e) {
// Does not exist
}
}
return new Error(`Local file for ${req.url} not found`);
};
const handleRequest = (req, res, next) => {
if (writeToResponse(req, res, BUNDLES.map(item => item.config.distPath))) {
// Nothing we can write to the stream, fallback to the default behavior
return next();
};
};
const startLocalTask = createServerTask({
config: {
ui: false,
ghostMode: false,
open: false,
reloadOnRestart: true,
notify: true,
proxy: { target: consoleArguments.backendProxy },
middleware: BUNDLES.map(bundle => { return { route: bundle.config.publicPath, handle: handleRequest } })
}
});
export const buildOnChange = (done) => {
for (const bundle of BUNDLES) {
const srcPath = bundle.config.srcPath;
const jsAssets = srcPath + 'js/**/!(*.spec).js';
gulp.watch(jsAssets, bundle.tasks.scripts);
if (bundle.tasks.bundle) {
const jsNextAssets = srcPath + 'jsnext/**/!(*.spec).js';
gulp.watch(jsNextAssets, bundle.tasks.bundle);
}
const styleAssets = srcPath + 'scss/**/*.scss';
gulp.watch(styleAssets, bundle.tasks.cssOptimized);
if (bundle.tasks.cssNextOptimized) {
const styleNextAssets = srcPath + 'scssnext/**/*.scss';
gulp.watch(styleNextAssets, bundle.tasks.cssNextOptimized);
}
}
done();
};
export function testOnChange(done) {
for (const bundle of BUNDLES) {
if (bundle.tasks.eslint) {
const srcPath = bundle.config.srcPath;
gulp.watch(`${srcPath}jsnext/**/*.js`, bundle.tasks.eslint);
}
if (bundle.tasks.stylelint) {
const srcPath = bundle.config.srcPath;
gulp.watch(`${srcPath}scssnext/**/*.scss`, bundle.tasks.stylelint);
}
}
done();
}
export default startLocalTask;
| Kunstmaan/KunstmaanBundlesCMS | groundcontrol/start-local.task.js | JavaScript | mit | 3,206 |
'use strict';
describe('Service: Initiatives', function () {
// instantiate service
var Initiatives,
Timeout,
cfg,
$httpBackend,
$rootScope,
tPromise;
// load the service's module
beforeEach(module('sumaAnalysis'));
beforeEach(inject(function (_$rootScope_, _$httpBackend_, _initiatives_, $q, $timeout) {
$rootScope = _$rootScope_;
$httpBackend = _$httpBackend_;
Initiatives = _initiatives_;
tPromise = $q.defer();
Timeout = $timeout;
cfg = {
timeoutPromise: tPromise,
timeout: 180000
};
}));
it('should make an AJAX call', function (done) {
$httpBackend.whenGET('lib/php/initiatives.php')
.respond([{}, {}]);
Initiatives.get(cfg).then(function (result) {
expect(result.length).to.equal(2);
done();
});
$httpBackend.flush();
});
it('should respond with error message on failure', function (done) {
$httpBackend.whenGET('lib/php/initiatives.php')
.respond(500, {message: 'Error'});
Initiatives.get(cfg).then(function (result) {
}, function (result) {
expect(result).to.deep.equal({
message: 'Error',
code: 500
});
done();
});
$httpBackend.flush();
});
it('should return error with promiseTimeout true on aborted http request', function (done) {
// simulate aborted request
$httpBackend.whenGET('lib/php/initiatives.php')
.respond(0, {message: 'Error'});
Initiatives.get(cfg).then(function (result) {
}, function (result) {
expect(result).to.deep.equal({
message: 'Initiatives.get Timeout',
code: 0,
promiseTimeout: true
});
done();
});
$httpBackend.flush();
});
it('should return error without promiseTimeout on http timeout', function (done) {
$httpBackend.whenGET('lib/php/initiatives.php')
.respond([{}, {}]);
Initiatives.get(cfg).then(function (result) {
}, function (result) {
expect(result).to.deep.equal({
message: 'Initiatives.get Timeout',
code: 0
});
done();
});
Timeout.flush();
});
});
| cazzerson/Suma | analysis/test/js/spec/services/initiatives.js | JavaScript | mit | 2,143 |
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Sylius\Component\Core\Model;
use Sylius\Component\Promotion\Model\PromotionCouponInterface as BasePromotionCouponInterface;
interface PromotionCouponInterface extends BasePromotionCouponInterface
{
public function getPerCustomerUsageLimit(): ?int;
public function setPerCustomerUsageLimit(?int $perCustomerUsageLimit): void;
}
| venyii/Sylius | src/Sylius/Component/Core/Model/PromotionCouponInterface.php | PHP | mit | 594 |
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
/* Tabulator v4.0.2 (c) Oliver Folkerd */
var HtmlTableImport = function HtmlTableImport(table) {
this.table = table; //hold Tabulator object
this.fieldIndex = [];
this.hasIndex = false;
};
HtmlTableImport.prototype.parseTable = function () {
var self = this,
element = self.table.element,
options = self.table.options,
columns = options.columns,
headers = element.getElementsByTagName("th"),
rows = element.getElementsByTagName("tbody")[0].getElementsByTagName("tr"),
data = [],
newTable;
self.hasIndex = false;
self.table.options.htmlImporting.call(this.table);
//check for tablator inline options
self._extractOptions(element, options);
if (headers.length) {
self._extractHeaders(headers, rows);
} else {
self._generateBlankHeaders(headers, rows);
}
//iterate through table rows and build data set
for (var index = 0; index < rows.length; index++) {
var row = rows[index],
cells = row.getElementsByTagName("td"),
item = {};
//create index if the dont exist in table
if (!self.hasIndex) {
item[options.index] = index;
}
for (var i = 0; i < cells.length; i++) {
var cell = cells[i];
if (typeof this.fieldIndex[i] !== "undefined") {
item[this.fieldIndex[i]] = cell.innerHTML;
}
}
//add row data to item
data.push(item);
}
//create new element
var newElement = document.createElement("div");
//transfer attributes to new element
var attributes = element.attributes;
// loop through attributes and apply them on div
for (var i in attributes) {
if (_typeof(attributes[i]) == "object") {
newElement.setAttribute(attributes[i].name, attributes[i].value);
}
}
// replace table with div element
element.parentNode.replaceChild(newElement, element);
options.data = data;
self.table.options.htmlImported.call(this.table);
// // newElement.tabulator(options);
this.table.element = newElement;
};
//extract tabluator attribute options
HtmlTableImport.prototype._extractOptions = function (element, options) {
var attributes = element.attributes;
for (var index in attributes) {
var attrib = attributes[index];
var name;
if ((typeof attrib === "undefined" ? "undefined" : _typeof(attrib)) == "object" && attrib.name && attrib.name.indexOf("tabulator-") === 0) {
name = attrib.name.replace("tabulator-", "");
for (var key in options) {
if (key.toLowerCase() == name) {
options[key] = this._attribValue(attrib.value);
}
}
}
}
};
//get value of attribute
HtmlTableImport.prototype._attribValue = function (value) {
if (value === "true") {
return true;
}
if (value === "false") {
return false;
}
return value;
};
//find column if it has already been defined
HtmlTableImport.prototype._findCol = function (title) {
var match = this.table.options.columns.find(function (column) {
return column.title === title;
});
return match || false;
};
//extract column from headers
HtmlTableImport.prototype._extractHeaders = function (headers, rows) {
for (var index = 0; index < headers.length; index++) {
var header = headers[index],
exists = false,
col = this._findCol(header.textContent),
width,
attributes;
if (col) {
exists = true;
} else {
col = { title: header.textContent.trim() };
}
if (!col.field) {
col.field = header.textContent.trim().toLowerCase().replace(" ", "_");
}
width = header.getAttribute("width");
if (width && !col.width) {
col.width = width;
}
//check for tablator inline options
attributes = header.attributes;
// //check for tablator inline options
this._extractOptions(header, col);
for (var i in attributes) {
var attrib = attributes[i],
name;
if ((typeof attrib === "undefined" ? "undefined" : _typeof(attrib)) == "object" && attrib.name && attrib.name.indexOf("tabulator-") === 0) {
name = attrib.name.replace("tabulator-", "");
col[name] = this._attribValue(attrib.value);
}
}
this.fieldIndex[index] = col.field;
if (col.field == this.table.options.index) {
this.hasIndex = true;
}
if (!exists) {
this.table.options.columns.push(col);
}
}
};
//generate blank headers
HtmlTableImport.prototype._generateBlankHeaders = function (headers, rows) {
for (var index = 0; index < headers.length; index++) {
var header = headers[index],
col = { title: "", field: "col" + index };
this.fieldIndex[index] = col.field;
var width = header.getAttribute("width");
if (width) {
col.width = width;
}
this.table.options.columns.push(col);
}
};
Tabulator.prototype.registerModule("htmlTableImport", HtmlTableImport); | joeyparrish/cdnjs | ajax/libs/tabulator/4.0.2/js/modules/html_table_import.js | JavaScript | mit | 4,916 |
<?php
/*
* This file is part of Rocketeer
*
* (c) Maxime Fabre <ehtnam6@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Rocketeer\Binaries\PackageManagers;
use Rocketeer\Abstracts\AbstractPackageManager;
class Bundler extends AbstractPackageManager
{
/**
* The name of the manifest file to look for.
*
* @type string
*/
protected $manifest = 'Gemfile';
/**
* Get an array of default paths to look for.
*
* @return string[]
*/
protected function getKnownPaths()
{
return [
'bundle',
];
}
}
| sbwdlihao/rocketeer | src/Rocketeer/Binaries/PackageManagers/Bundler.php | PHP | mit | 695 |
//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
function DumpArray(a)
{
var undef_start = -1;
for (var i = 0; i < a.length; i++)
{
if (a[i] == undefined)
{
if (undef_start == -1)
{
undef_start = i;
}
}
else
{
if (undef_start != -1)
{
WScript.Echo(undef_start + "-" + (i-1) + " = undefined");
undef_start = -1;
}
WScript.Echo(i + " = " + a[i]);
}
}
}
DumpArray([]);
DumpArray([ 0 ]);
DumpArray([ 0, 1, 2, 3, 4, 5, 6 ,7 ,8, 9]);
DumpArray([,,,0,,,1,,,2,,,3,,,4,,,5,,,6,,,7,,,8,,,9,,,]);
var s0 = "";
for (var i = 0; i < 100; i++)
{
s0 += ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,";
}
DumpArray(eval("[" + s0 + "1]"));
var s1 = "";
for (var i = 0; i < 30; i++)
{
s1 += s0;
}
DumpArray(eval("[" + s1 + "1]"));
var s2 = "";
for (var i = 0; i < 10; i++)
{
s2 += s1;
}
DumpArray(eval("[" + s2 + "1]"));
| arunetm/ChakraCore_0114 | test/Array/array_init.js | JavaScript | mit | 1,438 |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Debug\Tests\FatalErrorHandler;
use Symfony\Component\ClassLoader\ClassLoader as SymfonyClassLoader;
use Symfony\Component\ClassLoader\UniversalClassLoader as SymfonyUniversalClassLoader;
use Symfony\Component\Debug\Exception\FatalErrorException;
use Symfony\Component\Debug\FatalErrorHandler\ClassNotFoundFatalErrorHandler;
class ClassNotFoundFatalErrorHandlerTest extends \PHPUnit_Framework_TestCase
{
/**
* @dataProvider provideClassNotFoundData
*/
public function testHandleClassNotFound($error, $translatedMessage)
{
$handler = new ClassNotFoundFatalErrorHandler();
$exception = $handler->handleError($error, new FatalErrorException('', 0, $error['type'], $error['file'], $error['line']));
$this->assertInstanceof('Symfony\Component\Debug\Exception\ClassNotFoundException', $exception);
$this->assertSame($translatedMessage, $exception->getMessage());
$this->assertSame($error['type'], $exception->getSeverity());
$this->assertSame($error['file'], $exception->getFile());
$this->assertSame($error['line'], $exception->getLine());
}
/**
* @dataProvider provideLegacyClassNotFoundData
* @group legacy
*/
public function testLegacyHandleClassNotFound($error, $translatedMessage, $autoloader)
{
// Unregister all autoloaders to ensure the custom provided
// autoloader is the only one to be used during the test run.
$autoloaders = spl_autoload_functions();
array_map('spl_autoload_unregister', $autoloaders);
spl_autoload_register($autoloader);
$handler = new ClassNotFoundFatalErrorHandler();
$exception = $handler->handleError($error, new FatalErrorException('', 0, $error['type'], $error['file'], $error['line']));
spl_autoload_unregister($autoloader);
array_map('spl_autoload_register', $autoloaders);
$this->assertInstanceof('Symfony\Component\Debug\Exception\ClassNotFoundException', $exception);
$this->assertSame($translatedMessage, $exception->getMessage());
$this->assertSame($error['type'], $exception->getSeverity());
$this->assertSame($error['file'], $exception->getFile());
$this->assertSame($error['line'], $exception->getLine());
}
public function provideClassNotFoundData()
{
return array(
array(
array(
'type' => 1,
'line' => 12,
'file' => 'foo.php',
'message' => 'Class \'WhizBangFactory\' not found',
),
"Attempted to load class \"WhizBangFactory\" from the global namespace.\nDid you forget a \"use\" statement?",
),
array(
array(
'type' => 1,
'line' => 12,
'file' => 'foo.php',
'message' => 'Class \'Foo\\Bar\\WhizBangFactory\' not found',
),
"Attempted to load class \"WhizBangFactory\" from namespace \"Foo\\Bar\".\nDid you forget a \"use\" statement for another namespace?",
),
array(
array(
'type' => 1,
'line' => 12,
'file' => 'foo.php',
'message' => 'Class \'UndefinedFunctionException\' not found',
),
"Attempted to load class \"UndefinedFunctionException\" from the global namespace.\nDid you forget a \"use\" statement for \"Symfony\Component\Debug\Exception\UndefinedFunctionException\"?",
),
array(
array(
'type' => 1,
'line' => 12,
'file' => 'foo.php',
'message' => 'Class \'PEARClass\' not found',
),
"Attempted to load class \"PEARClass\" from the global namespace.\nDid you forget a \"use\" statement for \"Symfony_Component_Debug_Tests_Fixtures_PEARClass\"?",
),
array(
array(
'type' => 1,
'line' => 12,
'file' => 'foo.php',
'message' => 'Class \'Foo\\Bar\\UndefinedFunctionException\' not found',
),
"Attempted to load class \"UndefinedFunctionException\" from namespace \"Foo\Bar\".\nDid you forget a \"use\" statement for \"Symfony\Component\Debug\Exception\UndefinedFunctionException\"?",
),
);
}
public function provideLegacyClassNotFoundData()
{
$this->iniSet('error_reporting', -1 & ~E_USER_DEPRECATED);
$prefixes = array('Symfony\Component\Debug\Exception\\' => realpath(__DIR__.'/../../Exception'));
$symfonyAutoloader = new SymfonyClassLoader();
$symfonyAutoloader->addPrefixes($prefixes);
if (class_exists('Symfony\Component\ClassLoader\UniversalClassLoader')) {
$symfonyUniversalClassLoader = new SymfonyUniversalClassLoader();
$symfonyUniversalClassLoader->registerPrefixes($prefixes);
} else {
$symfonyUniversalClassLoader = $symfonyAutoloader;
}
return array(
array(
array(
'type' => 1,
'line' => 12,
'file' => 'foo.php',
'message' => 'Class \'Foo\\Bar\\UndefinedFunctionException\' not found',
),
"Attempted to load class \"UndefinedFunctionException\" from namespace \"Foo\Bar\".\nDid you forget a \"use\" statement for \"Symfony\Component\Debug\Exception\UndefinedFunctionException\"?",
array($symfonyAutoloader, 'loadClass'),
),
array(
array(
'type' => 1,
'line' => 12,
'file' => 'foo.php',
'message' => 'Class \'Foo\\Bar\\UndefinedFunctionException\' not found',
),
"Attempted to load class \"UndefinedFunctionException\" from namespace \"Foo\Bar\".\nDid you forget a \"use\" statement for \"Symfony\Component\Debug\Exception\UndefinedFunctionException\"?",
array($symfonyUniversalClassLoader, 'loadClass'),
),
array(
array(
'type' => 1,
'line' => 12,
'file' => 'foo.php',
'message' => 'Class \'Foo\\Bar\\UndefinedFunctionException\' not found',
),
"Attempted to load class \"UndefinedFunctionException\" from namespace \"Foo\\Bar\".\nDid you forget a \"use\" statement for another namespace?",
function ($className) { /* do nothing here */ },
),
);
}
public function testCannotRedeclareClass()
{
if (!file_exists(__DIR__.'/../FIXTURES/REQUIREDTWICE.PHP')) {
$this->markTestSkipped('Can only be run on case insensitive filesystems');
}
require_once __DIR__.'/../FIXTURES/REQUIREDTWICE.PHP';
$error = array(
'type' => 1,
'line' => 12,
'file' => 'foo.php',
'message' => 'Class \'Foo\\Bar\\RequiredTwice\' not found',
);
$handler = new ClassNotFoundFatalErrorHandler();
$exception = $handler->handleError($error, new FatalErrorException('', 0, $error['type'], $error['file'], $error['line']));
$this->assertInstanceof('Symfony\Component\Debug\Exception\ClassNotFoundException', $exception);
}
}
| vith/symfony | src/Symfony/Component/Debug/Tests/FatalErrorHandler/ClassNotFoundFatalErrorHandlerTest.php | PHP | mit | 7,910 |
require 'chunky_png'
require 'fileutils'
#COLOR_TRUE = ChunkyPNG::Color::rgba(224, 255, 255, 96) # for kunijiban
COLOR_TRUE = ChunkyPNG::Color::rgba(255, 255, 255, 0) # for ort
COLOR_FALSE = ChunkyPNG::Color::rgba(0, 0, 0, 128)
def _new_image
return ChunkyPNG::Image.new(256, 256, COLOR_FALSE)
end
def write(image, zxy)
path = "#{zxy.join('/')}.png"
FileUtils.mkdir_p(File.dirname(path)) unless File.directory?(File.dirname(path))
image.save(path)
print "wrote #{path}\n"
return _new_image
end
_new_image.save('404.png')
current = [nil, nil, nil]
last = [nil, nil, nil]
(z, x, y, u, v) = [nil, nil, nil, nil, nil]
image = _new_image
while gets
(z, x, y, u, v) = $_.strip.split(',').map{|v| v.to_i}
current = [z, x, y]
if current == last or last[0].nil?
image[u, v] = COLOR_TRUE
else
image = write(image, last)
image[u, v] = COLOR_TRUE
end
last = current
end
write(image, last)
| hfu/octpng-bin | reduce.rb | Ruby | cc0-1.0 | 916 |
###########################################################
#
# Copyright (c) 2014, Southpaw Technology
# All Rights Reserved
#
# PROPRIETARY INFORMATION. This software is proprietary to
# Southpaw Technology, and is not to be reproduced, transmitted,
# or disclosed in any way without written permission.
#
#
#
__all__ = ['ScrollbarWdg', 'TestScrollbarWdg']
from tactic.ui.common import BaseRefreshWdg
from pyasm.web import DivWdg
class TestScrollbarWdg(BaseRefreshWdg):
def get_display(my):
top = my.top
top.add_style("width: 600px")
top.add_style("height: 400px")
return top
class ScrollbarWdg(BaseRefreshWdg):
def get_display(my):
top = my.top
top.add_class("spt_scrollbar_top")
content = my.kwargs.get("content")
content_class = my.kwargs.get("content_class")
if not content_class:
content_class = "spt_content"
width = 8
top.add_style("width: %s" % width)
top.add_style("position: absolute")
top.add_style("top: 0px")
top.add_style("right: 0px")
top.add_color("background", "background")
top.add_style("margin: 3px 5px")
top.add_style("opacity: 0.0")
top.add_behavior( {
'type': 'load',
'cbjs_action': my.get_onload_js()
} )
top.add_behavior( {
'type': 'load',
'content_class': content_class,
'cbjs_action': '''
var parent = bvr.src_el.getParent("." + bvr.content_class);
var size = parent.getSize();
bvr.src_el.setStyle("height", size.y);
var scrollbar = parent.getElement(".spt_scrollbar_top");
parent.addEvent("mouseenter", function() {
new Fx.Tween(scrollbar, {duration: 250}).start("opacity", 1.0);
} );
parent.addEvent("mouseleave", function() {
new Fx.Tween(scrollbar, {duration: 250}).start("opacity", 0.0);
} );
parent.addEvent("keypress", function(evt) {
new Fx.Tween(scrollbar, {duration: 250}).start("opacity", 0.0);
console.log(evt);
} );
parent.addEvent("mousewheel", function(evt) {
evt.stopPropagation();
spt.scrollbar.content = parent;
if (evt.wheel == 1) {
spt.scrollbar.scroll(15)
}
else {
spt.scrollbar.scroll(-15)
}
} );
'''
} )
bar = DivWdg()
bar.add_class("spt_scrollbar")
bar.add_class("hand")
top.add(bar)
bar.add_style("width: %s" % width)
bar.add_style("height: 30px")
bar.add_style("border: solid 1px black")
bar.add_color("background", "background3")
#bar.add_border()
bar.add_style("border-radius: 5")
bar.add_style("position: absolute")
bar.add_style("top: 0px")
top.add_behavior( {
'type': 'smart_drag',
'bvr_match_class': 'spt_scrollbar',
'ignore_default_motion' : True,
"cbjs_setup": 'spt.scrollbar.drag_setup( evt, bvr, mouse_411 );',
"cbjs_motion": 'spt.scrollbar.drag_motion( evt, bvr, mouse_411 );'
} )
return top
def get_onload_js(my):
return r'''
spt.scrollbar = {};
spt.scrollbar.mouse_start_y = null;
spt.scrollbar.el_start_y = null;
spt.scrollbar.top = null;
spt.scrollbar.content = null;
spt.scrollbar.drag_setup = function(evt, bvr, mouse_411) {
spt.scrollbar.mouse_start_y = mouse_411.curr_y;
var src_el = spt.behavior.get_bvr_src( bvr );
var pos_y = parseInt(src_el.getStyle("top").replace("px", ""));
spt.scrollbar.el_start_y = pos_y;
spt.scrollbar.content = $("spt_SCROLL");
spt.scrollbar.top = src_el.getParent(".spt_scrollbar_top")
}
spt.scrollbar.drag_motion = function(evt, bvr, mouse_411) {
var src_el = spt.behavior.get_bvr_src( bvr );
var dy = mouse_411.curr_y - spt.scrollbar.mouse_start_y;
var pos_y = spt.scrollbar.el_start_y + dy;
if (pos_y < 0) {
return;
}
var content = spt.scrollbar.content;
var content_size = spt.scrollbar.content.getSize();
var top_size = spt.scrollbar.top.getSize();
var bar_size = src_el.getSize();
if (pos_y > top_size.y - bar_size.y - 5) {
return;
}
bvr.src_el.setStyle("top", pos_y);
//var content = bvr.src_el.getParent(".spt_content");
content.setStyle("margin-top", -dy);
}
spt.scrollbar.scroll = function(dy) {
spt.scrollbar.content = $("spt_SCROLL");
var content = spt.scrollbar.content;
var pos_y = parseInt(content.getStyle("margin-top").replace("px", ""));
content.setStyle("margin-top", pos_y + dy);
}
'''
| CeltonMcGrath/TACTIC | src/tactic/ui/widget/scrollbar_wdg.py | Python | epl-1.0 | 4,809 |
/*******************************************************************************
* Copyright (c) 2012-2015 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.ide.actions;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import org.eclipse.che.api.analytics.client.logger.AnalyticsEventLogger;
import org.eclipse.che.ide.Resources;
import org.eclipse.che.ide.api.action.ActionEvent;
import org.eclipse.che.ide.api.action.ProjectAction;
import org.eclipse.che.ide.api.editor.EditorAgent;
import org.eclipse.che.ide.api.editor.EditorInput;
import org.eclipse.che.ide.api.editor.EditorPartPresenter;
import org.eclipse.che.ide.api.editor.EditorWithAutoSave;
import org.eclipse.che.ide.util.loging.Log;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/** @author Evgen Vidolob */
@Singleton
public class SaveAllAction extends ProjectAction {
private final EditorAgent editorAgent;
private final AnalyticsEventLogger eventLogger;
@Inject
public SaveAllAction(EditorAgent editorAgent, Resources resources, AnalyticsEventLogger eventLogger) {
super("Save All", "Save all changes for project", resources.save());
this.editorAgent = editorAgent;
this.eventLogger = eventLogger;
}
/** {@inheritDoc} */
@Override
public void actionPerformed(ActionEvent e) {
eventLogger.log(this);
Collection<EditorPartPresenter> values = editorAgent.getOpenedEditors().values();
List<EditorPartPresenter> editors = new ArrayList<>(values);
save(editors);
}
private void save(final List<EditorPartPresenter> editors) {
if (editors.isEmpty()) {
return;
}
final EditorPartPresenter editorPartPresenter = editors.get(0);
if (editorPartPresenter.isDirty()) {
editorPartPresenter.doSave(new AsyncCallback<EditorInput>() {
@Override
public void onFailure(Throwable caught) {
Log.error(SaveAllAction.class, caught);
//try to save other files
editors.remove(editorPartPresenter);
save(editors);
}
@Override
public void onSuccess(EditorInput result) {
editors.remove(editorPartPresenter);
save(editors);
}
});
} else {
editors.remove(editorPartPresenter);
save(editors);
}
}
/** {@inheritDoc} */
@Override
public void updateProjectAction(ActionEvent e) {
// e.getPresentation().setVisible(true);
boolean hasDirtyEditor = false;
for (EditorPartPresenter editor : editorAgent.getOpenedEditors().values()) {
if(editor instanceof EditorWithAutoSave) {
if (((EditorWithAutoSave)editor).isAutoSaveEnabled()) {
continue;
}
}
if (editor.isDirty()) {
hasDirtyEditor = true;
break;
}
}
e.getPresentation().setEnabledAndVisible(hasDirtyEditor);
}
}
| Ori-Libhaber/che-core | ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/actions/SaveAllAction.java | Java | epl-1.0 | 3,624 |
$_L(["$wt.widgets.Layout"],"$wt.layout.FillLayout",["$wt.graphics.Point","$wt.layout.FillData"],function(){
c$=$_C(function(){
this.type=256;
this.marginWidth=0;
this.marginHeight=0;
this.spacing=0;
$_Z(this,arguments);
},$wt.layout,"FillLayout",$wt.widgets.Layout);
$_K(c$,
function(){
$_R(this,$wt.layout.FillLayout,[]);
});
$_K(c$,
function(type){
$_R(this,$wt.layout.FillLayout,[]);
this.type=type;
},"~N");
$_V(c$,"computeSize",
function(composite,wHint,hHint,flushCache){
var children=composite.getChildren();
var count=children.length;
var maxWidth=0;
var maxHeight=0;
for(var i=0;i<count;i++){
var child=children[i];
var w=wHint;
var h=hHint;
if(count>0){
if(this.type==256&&wHint!=-1){
w=Math.max(0,Math.floor((wHint-(count-1)*this.spacing)/count));
}if(this.type==512&&hHint!=-1){
h=Math.max(0,Math.floor((hHint-(count-1)*this.spacing)/count));
}}var size=this.computeChildSize(child,w,h,flushCache);
maxWidth=Math.max(maxWidth,size.x);
maxHeight=Math.max(maxHeight,size.y);
}
var width=0;
var height=0;
if(this.type==256){
width=count*maxWidth;
if(count!=0)width+=(count-1)*this.spacing;
height=maxHeight;
}else{
width=maxWidth;
height=count*maxHeight;
if(count!=0)height+=(count-1)*this.spacing;
}width+=this.marginWidth*2;
height+=this.marginHeight*2;
if(wHint!=-1)width=wHint;
if(hHint!=-1)height=hHint;
return new $wt.graphics.Point(width,height);
},"$wt.widgets.Composite,~N,~N,~B");
$_M(c$,"computeChildSize",
function(control,wHint,hHint,flushCache){
var data=control.getLayoutData();
if(data==null){
data=new $wt.layout.FillData();
control.setLayoutData(data);
}var size=null;
if(wHint==-1&&hHint==-1){
size=data.computeSize(control,wHint,hHint,flushCache);
}else{
var trimX;
var trimY;
if($_O(control,$wt.widgets.Scrollable)){
var rect=(control).computeTrim(0,0,0,0);
trimX=rect.width;
trimY=rect.height;
}else{
trimX=trimY=control.getBorderWidth()*2;
}var w=wHint==-1?wHint:Math.max(0,wHint-trimX);
var h=hHint==-1?hHint:Math.max(0,hHint-trimY);
size=data.computeSize(control,w,h,flushCache);
}return size;
},"$wt.widgets.Control,~N,~N,~B");
$_V(c$,"flushCache",
function(control){
var data=control.getLayoutData();
if(data!=null)(data).flushCache();
return true;
},"$wt.widgets.Control");
$_M(c$,"getName",
function(){
var string=this.getClass().getName();
var index=string.lastIndexOf('.');
if(index==-1)return string;
return string.substring(index+1,string.length);
});
$_V(c$,"layout",
function(composite,flushCache){
var rect=composite.getClientArea();
var children=composite.getChildren();
var count=children.length;
if(count==0)return;
var width=rect.width-this.marginWidth*2;
var height=rect.height-this.marginHeight*2;
if(this.type==256){
width-=(count-1)*this.spacing;
var x=rect.x+this.marginWidth;
var extra=width%count;
var y=rect.y+this.marginHeight;
var cellWidth=Math.floor(width/count);
for(var i=0;i<count;i++){
var child=children[i];
var childWidth=cellWidth;
if(i==0){
childWidth+=Math.floor(extra/2);
}else{
if(i==count-1)childWidth+=Math.floor((extra+1)/2);
}child.setBounds(x,y,childWidth,height);
x+=childWidth+this.spacing;
}
}else{
height-=(count-1)*this.spacing;
var x=rect.x+this.marginWidth;
var cellHeight=Math.floor(height/count);
var y=rect.y+this.marginHeight;
var extra=height%count;
for(var i=0;i<count;i++){
var child=children[i];
var childHeight=cellHeight;
if(i==0){
childHeight+=Math.floor(extra/2);
}else{
if(i==count-1)childHeight+=Math.floor((extra+1)/2);
}child.setBounds(x,y,width,childHeight);
y+=childHeight+this.spacing;
}
}},"$wt.widgets.Composite,~B");
$_V(c$,"toString",
function(){
var string=this.getName()+"{";
string+="type="+((this.type==512)?"SWT.VERTICAL":"SWT.HORIZONTAL")+" ";
if(this.marginWidth!=0)string+="marginWidth="+this.marginWidth+" ";
if(this.marginHeight!=0)string+="marginHeight="+this.marginHeight+" ";
if(this.spacing!=0)string+="spacing="+this.spacing+" ";
string=string.trim();
string+="}";
return string;
});
});
| 01org/mayloon-portingtool | sources/net.sf.j2s.lib/j2slib/org/eclipse/swt/layout/FillLayout.js | JavaScript | epl-1.0 | 4,054 |
/*
* Created on May 13, 2003
*========================================================================
* Modifications history
*========================================================================
* $Log: PredicateWordRule.java,v $
* Revision 1.2 2003/05/30 20:53:09 agfitzp
* 0.0.2 : Outlining is now done as the user types. Some other bug fixes.
*
*========================================================================
*/
package net.sourceforge.jseditor.editors;
import org.eclipse.jface.text.rules.ICharacterScanner;
import org.eclipse.jface.text.rules.IPredicateRule;
import org.eclipse.jface.text.rules.IToken;
import org.eclipse.jface.text.rules.Token;
import org.eclipse.jface.text.rules.WordRule;
import org.eclipse.jface.text.rules.IWordDetector;
/**
* @author fitzpata
*/
public class PredicateWordRule extends WordRule implements IPredicateRule {
/* (non-Javadoc)
* @see org.eclipse.jface.text.rules.IPredicateRule#getSuccessToken()
*/
protected IToken successToken = Token.UNDEFINED;
public void addWords(String[] tokens, IToken token)
{
for (int i = 0; i < tokens.length; i++) {
addWord(tokens[i], token);
}
}
public IToken getSuccessToken() {
return successToken;
}
/* (non-Javadoc)
* @see org.eclipse.jface.text.rules.IPredicateRule#evaluate(org.eclipse.jface.text.rules.ICharacterScanner, boolean)
*/
public IToken evaluate(ICharacterScanner scanner, boolean resume) {
successToken = this.evaluate(scanner, resume);//true);
return successToken;
}
/**
* Creates a rule which, with the help of an word detector, will return the token
* associated with the detected word. If no token has been associated, the scanner
* will be rolled back and an undefined token will be returned in order to allow
* any subsequent rules to analyze the characters.
*
* @param detector the word detector to be used by this rule, may not be <code>null</code>
*
* @see #addWord
*/
public PredicateWordRule(IWordDetector detector) {
super(detector);
}
/**
* Creates a rule which, with the help of an word detector, will return the token
* associated with the detected word. If no token has been associated, the
* specified default token will be returned.
*
* @param detector the word detector to be used by this rule, may not be <code>null</code>
* @param defaultToken the default token to be returned on success
* if nothing else is specified, may not be <code>null</code>
*
* @see #addWord
*/
public PredicateWordRule(IWordDetector detector, IToken defaultToken) {
super(detector, defaultToken);
}
public PredicateWordRule(IWordDetector detector, String tokenString, IToken tokenType) {
super(detector);
this.addWord(tokenString, tokenType);
}
public PredicateWordRule(IWordDetector detector, String[] tokens, IToken tokenType) {
super(detector);
this.addWords(tokens, tokenType);
}
public PredicateWordRule(IWordDetector detector, IToken defaultToken, String[] tokens, IToken tokenType) {
super(detector, defaultToken);
this.addWords(tokens, tokenType);
}
}
| royleexhFake/mayloon-portingtool | net.sourceforge.jseditor/src-jseditor/net/sourceforge/jseditor/editors/PredicateWordRule.java | Java | epl-1.0 | 3,101 |
/*******************************************************************************
* Copyright (c) 2012-2015 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.api.core.util;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
/** @author andrew00x */
public class ProcessUtilTest {
@Test
public void testKill() throws Exception {
final Process p = Runtime.getRuntime().exec(new String[]{"/bin/bash", "-c", "sleep 10; echo wake\\ up"});
final List<String> stdout = new ArrayList<>();
final List<String> stderr = new ArrayList<>();
final IOException[] processError = new IOException[1];
final CountDownLatch latch = new CountDownLatch(1);
final long start = System.currentTimeMillis();
new Thread() {
public void run() {
try {
ProcessUtil.process(p,
new LineConsumer() {
@Override
public void writeLine(String line) throws IOException {
stdout.add(line);
}
@Override
public void close() throws IOException {
}
},
new LineConsumer() {
@Override
public void writeLine(String line) throws IOException {
stderr.add(line);
}
@Override
public void close() throws IOException {
}
}
);
} catch (IOException e) {
processError[0] = e; // throw when kill process
} finally {
latch.countDown();
}
}
}.start();
Thread.sleep(1000); // give time to start process
Assert.assertTrue(ProcessUtil.isAlive(p), "Process is not started.");
ProcessUtil.kill(p); // kill process
latch.await(15, TimeUnit.SECONDS); // should not stop here if process killed
final long end = System.currentTimeMillis();
// System process sleeps 10 seconds. It is safety to check we done in less then 3 sec.
Assert.assertTrue((end - start) < 3000, "Fail kill process");
System.out.println(processError[0]);
//processError[0].printStackTrace();
System.out.println(stdout);
System.out.println(stderr);
}
}
| aljiru/che-core | platform-api/che-core-api-core/src/test/java/org/eclipse/che/api/core/util/ProcessUtilTest.java | Java | epl-1.0 | 3,462 |
/**
* Copyright (c) 2005-2012 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Eclipse Public License (EPL).
* Please see the license.txt included with this distribution for details.
* Any modifications to this file must keep this entire header intact.
*/
package com.python.pydev.refactoring.wizards.rename.visitors;
import java.util.Stack;
import org.python.pydev.parser.jython.SimpleNode;
import org.python.pydev.parser.jython.Visitor;
import org.python.pydev.parser.jython.ast.Call;
import org.python.pydev.parser.jython.ast.Name;
import org.python.pydev.parser.jython.ast.NameTok;
/**
* This visitor is used to find a call given its ast
*
* @author Fabio
*/
public class FindCallVisitor extends Visitor {
private Name name;
private NameTok nameTok;
private Call call;
private Stack<Call> lastCall = new Stack<Call>();
public FindCallVisitor(Name name) {
this.name = name;
}
public FindCallVisitor(NameTok nameTok) {
this.nameTok = nameTok;
}
public Call getCall() {
return call;
}
@Override
public Object visitCall(Call node) throws Exception {
if (this.call != null) {
return null;
}
if (node.func == name) {
//check the name (direct)
this.call = node;
} else if (nameTok != null) {
//check the name tok (inside of attribute)
lastCall.push(node);
Object r = super.visitCall(node);
lastCall.pop();
if (this.call != null) {
return null;
}
return r;
}
if (this.call != null) {
return null;
}
return super.visitCall(node);
}
@Override
public Object visitNameTok(NameTok node) throws Exception {
if (node == nameTok) {
if (lastCall.size() > 0) {
call = lastCall.peek();
}
return null;
}
return super.visitNameTok(node);
}
public static Call findCall(NameTok nametok, SimpleNode root) {
FindCallVisitor visitor = new FindCallVisitor(nametok);
try {
visitor.traverse(root);
} catch (Exception e) {
throw new RuntimeException(e);
}
return visitor.call;
}
public static Call findCall(Name name, SimpleNode root) {
FindCallVisitor visitor = new FindCallVisitor(name);
try {
visitor.traverse(root);
} catch (Exception e) {
throw new RuntimeException(e);
}
return visitor.call;
}
}
| rgom/Pydev | plugins/com.python.pydev.refactoring/src/com/python/pydev/refactoring/wizards/rename/visitors/FindCallVisitor.java | Java | epl-1.0 | 2,648 |
package com.intel.ide.eclipse.mpt.classpath;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import com.intel.ide.eclipse.mpt.launching.J2SCyclicProjectUtils;
public class ContactedClasses extends Resource implements IExternalResource, IClasspathContainer {
private String binRelativePath;
private List classList;
private List externalList;
public void load() {
File file = getAbsoluteFile();
classList = new ArrayList();
externalList = new ArrayList();
if (file.exists()) {
Properties props = PathUtil.loadJZ(file);
String[] reses = PathUtil.getResources(props);
binRelativePath = props.getProperty(PathUtil.J2S_OUTPUT_PATH);
for (int i = 0; i < reses.length; i++) {
if (reses[i] != null) {
String res = reses[i].trim();
if (res.endsWith(".z.js")) {
ContactedClasses jz = new ContactedClasses();
jz.setFolder(this.getAbsoluteFolder());
jz.setRelativePath(res);
jz.setParent(this);
externalList.add(jz);
} else if (res.endsWith(".js")) {
ContactedUnitClass unit = new ContactedUnitClass();
unit.setFolder(this.getAbsoluteFolder());
unit.setRelativePath(res);
unit.parseClassName();
unit.setParent(this);
classList.add(unit);
} else if (res.endsWith(".css")) {
CSSResource css = new CSSResource();
css.setFolder(this.getAbsoluteFolder());
css.setRelativePath(res);
css.setParent(this);
externalList.add(css);
}
}
}
}
}
public void store(Properties props) {
Resource[] reses = getChildren();
StringBuffer buf = new StringBuffer();
for (int i = 0; i < reses.length; i++) {
String str = reses[i].toResourceString();
buf.append(str);
if (i != reses.length - 1) {
buf.append(",");
}
}
props.setProperty(PathUtil.J2S_RESOURCES_LIST, buf.toString());
props.setProperty(PathUtil.J2S_OUTPUT_PATH, binRelativePath);
}
public Resource[] getChildren() {
if (externalList == null || classList == null) {
this.load();
}
int size = externalList.size();
Resource[] res = new Resource[classList.size() + size];
for (int i = 0; i < size; i++) {
res[i] = (Resource) externalList.get(i);
}
for (int i = 0; i < classList.size(); i++) {
res[i + size] = (Resource) classList.get(i);
}
return res;
}
public ContactedUnitClass[] getClasses() {
return (ContactedUnitClass[]) classList.toArray(new ContactedClasses[0]);
}
public IExternalResource[] getExternals() {
return (IExternalResource[]) externalList.toArray(new IExternalResource[0]);
}
public String getBinRelativePath() {
return binRelativePath;
}
public void setBinRelativePath(String binRelativePath) {
this.binRelativePath = binRelativePath;
}
public String toHTMLString() {
if (getRelativePath() != null && getRelativePath().endsWith(".j2x")) {
return "";
}
Resource p = this.getParent();
if (p != null) {
if (p instanceof ContactedClasses) {
Resource pp = p.getParent();
if (pp != null && pp instanceof ContactedClasses) {
return "";
}
}
}
StringBuffer buf = new StringBuffer();
if (externalList == null) {
this.load();
}
for (Iterator iter = externalList.iterator(); iter.hasNext();) {
Resource res = (Resource) iter.next();
if (!J2SCyclicProjectUtils.visit(res)) {
continue;
}
buf.append(res.toHTMLString());
}
buf.append("<script type=\"text/javascript\" src=\"");
String binFolder = getBinRelativePath();
if (binFolder != null) {
String binPath = binFolder.trim();
if (binPath.length() != 0) {
buf.append(binPath);
if (!binPath.endsWith("/")) {
buf.append("/");
}
}
}
if (p != null) {
if (p instanceof ContactedClasses) {
ContactedClasses cc = (ContactedClasses) p;
String path = cc.getRelativePath();
int idx = path.lastIndexOf('/');
if (idx != -1) {
buf.append(path.substring(0, idx + 1));
}
} else if (p instanceof CompositeResources) {
CompositeResources cc = (CompositeResources) p;
String binRelative = cc.getBinRelativePath();
if (binRelative != null) {
if (binRelative.length() != 0 && getRelativePath().endsWith(".z.js")) {
return "";
}
buf.append(binRelative);
}
}
}
buf.append(getRelativePath());
buf.append("\"></script>\r\n");
return buf.toString();
}
public String toJ2XString() {
if (getName().endsWith(".j2x")) {
try {
return getAbsoluteFile().getCanonicalPath();
} catch (IOException e) {
e.printStackTrace();
}
}
return "";
}
public int getType() {
return CONTAINER;
}
}
| royleexhFake/mayloon-portingtool | com.intel.ide.eclipse.mpt/src/com/intel/ide/eclipse/mpt/classpath/ContactedClasses.java | Java | epl-1.0 | 4,878 |
var path = require("path");
module.exports = {
entry: "./public/App.js",
output: {
filename: "bundle.js",
path: path.resolve(__dirname, "public")
}
}; | generalelectrix/wiggles | view/webpack.config.js | JavaScript | gpl-2.0 | 179 |
§ßU<?php exit; ?>a:1:{s:7:"content";a:0:{}} | nilmadhab/webtutplus | wp-content/cache/object/000000/e36/eb4/e36eb471ab990b405292d7034395335a.php | PHP | gpl-2.0 | 44 |
<?php
/**
* The Header for our theme.
*
* Displays all of the <head> section and everything up till <div class="wf-container wf-clearfix">
*
* @package presscore
* @since presscore 0.1
*/
// File Security Check
if ( ! defined( 'ABSPATH' ) ) { exit; }
?><!DOCTYPE html>
<!--[if IE 6]>
<html id="ie6" class="ancient-ie old-ie no-js" <?php language_attributes(); ?>>
<![endif]-->
<!--[if IE 7]>
<html id="ie7" class="ancient-ie old-ie no-js" <?php language_attributes(); ?>>
<![endif]-->
<!--[if IE 8]>
<html id="ie8" class="old-ie no-js" <?php language_attributes(); ?>>
<![endif]-->
<!--[if IE 9]>
<html id="ie9" class="old-ie9 no-js" <?php language_attributes(); ?>>
<![endif]-->
<!--[if !(IE 6) | !(IE 7) | !(IE 8) ]><!-->
<html class="no-js" <?php language_attributes(); ?>>
<!--<![endif]-->
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>" />
<?php if ( presscore_responsive() ) : ?>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<?php endif; // is responsive?>
<?php if ( dt_retina_on() ) { dt_core_detect_retina_script(); } ?>
<title><?php echo presscore_blog_title(); ?></title>
<link rel="profile" href="http://gmpg.org/xfn/11" />
<link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>" />
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style type="text/css" id="static-stylesheet"></style>
<?php
if ( ! is_preview() ) {
presscore_favicon();
echo of_get_option('general-tracking_code', '');
presscore_icons_for_handhelded_devices();
}
wp_head();
?>
</head>
<body <?php body_class(); ?>>
<?php do_action( 'presscore_body_top' ); ?>
<div id="page"<?php if ( 'boxed' == of_get_option('general-layout', 'wide') ) echo ' class="boxed"'; ?>>
<?php if ( of_get_option('top_bar-show', 1) ) : ?>
<?php get_template_part( 'templates/header/top-bar', of_get_option('top_bar-content_alignment', 'side') ); ?>
<?php endif; // show top bar ?>
<?php if ( apply_filters( 'presscore_show_header', true ) ) : ?>
<?php get_template_part( 'templates/header/header', of_get_option( 'header-layout', 'left' ) ); ?>
<?php endif; // show header ?>
<?php do_action( 'presscore_before_main_container' ); ?>
<div id="main" <?php presscore_main_container_classes(); ?>><!-- class="sidebar-none", class="sidebar-left", class="sidebar-right" -->
<?php if ( presscore_is_content_visible() ): ?>
<div class="main-gradient"></div>
<div class="wf-wrap">
<div class="wf-container-main">
<?php do_action( 'presscore_before_content' ); ?>
<?php endif; ?>
| wiljenum/wordpress-jo | wp-content/themes/dt-the7/header.php | PHP | gpl-2.0 | 2,604 |
///////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 1997-2008 Morgan Stanley All rights reserved.
// See .../src/LICENSE for terms of distribution
//
//
///////////////////////////////////////////////////////////////////////////////
#include <MSGUI/MSRadioBox.H>
MSRadioBox::MSRadioBox(MSWidget *owner_,const char *title_) :
MSActionBox(owner_,title_)
{ _activeButton=0; }
MSRadioBox::MSRadioBox(MSWidget *owner_,const MSStringVector& title_) :
MSActionBox(owner_,title_)
{ _activeButton=0; }
MSRadioBox::~MSRadioBox(void) {}
const MSSymbol& MSRadioBox::symbol(void)
{
static MSSymbol sym ("MSRadioBox");
return sym;
}
const MSSymbol& MSRadioBox::widgetType(void) const
{ return symbol(); }
void MSRadioBox::arm(MSRadioButton *radioButton_)
{
disarm();
_activeButton=radioButton_;
if (activeButton()!=0) activeButton()->state(MSTrue);
}
void MSRadioBox::disarm(void)
{
if (activeButton()!=0) activeButton()->state(MSFalse);
_activeButton=0;
}
void MSRadioBox::firstMapNotify(void)
{
MSNodeItem *hp=childListHead();
MSNodeItem *np=hp;
MSLayoutEntry *entry;
MSRadioButton *radioButton;
unsigned count=0;
while ((np=np->next())!=hp)
{
entry=(MSLayoutEntry *)np->data();
radioButton=(MSRadioButton *)entry->widget();
if (radioButton->state()==MSTrue)
{
if (count==0) _activeButton=radioButton;
count++;
}
if (count>1) radioButton->state(MSFalse);
}
if (count==0&&(np=np->next())!=hp)
{
entry=(MSLayoutEntry *)np->data();
radioButton=(MSRadioButton *)entry->widget();
radioButton->state(MSTrue);
_activeButton=radioButton;
}
MSActionBox::firstMapNotify();
}
void MSRadioBox::activeButton(MSRadioButton *radioButton_, MSBoolean callback_)
{
radioButton_->arm(callback_);
}
| rdm/aplus-fsf | src/MSGUI/MSRadioBox.C | C++ | gpl-2.0 | 1,875 |
<?php
/**
* @package Joomla.Platform
* @subpackage Twitter
*
* @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();
/**
* Twitter API Search class for the Joomla Platform.
*
* @since 12.3
*/
class JTwittersearch extends JTwitterObject
{
/**
* Method to get tweets that match a specified query.
*
* @param string $query Search query. Should be URL encoded. Queries will be limited by complexity.
* @param string $callback If supplied, the response will use the JSONP format with a callback of the given name
* @param string $geocode Returns tweets by users located within a given radius of the given latitude/longitude. The parameter value is
* specified by "latitude,longitude,radius", where radius units must be specified as either "mi" (miles) or "km" (kilometers).
* @param string $lang Restricts tweets to the given language, given by an ISO 639-1 code.
* @param string $locale Specify the language of the query you are sending (only ja is currently effective). This is intended for
* language-specific clients and the default should work in the majority of cases.
* @param string $result_type Specifies what type of search results you would prefer to receive. The current default is "mixed."
* @param integer $count The number of tweets to return per page, up to a maximum of 100. Defaults to 15.
* @param string $until Returns tweets generated before the given date. Date should be formatted as YYYY-MM-DD.
* @param integer $since_id Returns results with an ID greater than (that is, more recent than) the specified ID.
* @param integer $max_id Returns results with an ID less than (that is, older than) or equal to the specified ID.
* @param boolean $entities When set to either true, t or 1, each tweet will include a node called "entities,". This node offers a
* variety of metadata about the tweet in a discrete structure, including: urls, media and hashtags.
*
* @return array The decoded JSON response
*
* @since 12.3
*/
public function search($query, $callback = null, $geocode = null, $lang = null, $locale = null, $result_type = null, $count = 15,
$until = null, $since_id = 0, $max_id = 0, $entities = null)
{
// Check the rate limit for remaining hits
$this->checkRateLimit('search', 'tweets');
// Set the API path
$path = '/search/tweets.json';
// Set query parameter.
$data['q'] = rawurlencode($query);
// Check if callback is specified.
if ($callback)
{
$data['callback'] = $callback;
}
// Check if geocode is specified.
if ($geocode)
{
$data['geocode'] = $geocode;
}
// Check if lang is specified.
if ($lang)
{
$data['lang'] = $lang;
}
// Check if locale is specified.
if ($locale)
{
$data['locale'] = $locale;
}
// Check if result_type is specified.
if ($result_type)
{
$data['result_type'] = $result_type;
}
// Check if count is specified.
if ($count != 15)
{
$data['count'] = $count;
}
// Check if until is specified.
if ($until)
{
$data['until'] = $until;
}
// Check if since_id is specified.
if ($since_id > 0)
{
$data['since_id'] = $since_id;
}
// Check if max_id is specified.
if ($max_id > 0)
{
$data['max_id'] = $max_id;
}
// Check if entities is specified.
if (!is_null($entities))
{
$data['include_entities'] = $entities;
}
// Send the request.
return $this->sendRequest($path, 'GET', $data);
}
/**
* Method to get the authenticated user's saved search queries.
*
* @return array The decoded JSON response
*
* @since 12.3
*/
public function getSavedSearches()
{
// Check the rate limit for remaining hits
$this->checkRateLimit('saved_searches', 'list');
// Set the API path
$path = '/saved_searches/list.json';
// Send the request.
return $this->sendRequest($path);
}
/**
* Method to get the information for the saved search represented by the given id.
*
* @param integer $id The ID of the saved search.
*
* @return array The decoded JSON response
*
* @since 12.3
*/
public function getSavedSearchesById($id)
{
// Check the rate limit for remaining hits
$this->checkRateLimit('saved_searches', 'show/:id');
// Set the API path
$path = '/saved_searches/show/' . $id . '.json';
// Send the request.
return $this->sendRequest($path);
}
/**
* Method to create a new saved search for the authenticated user.
*
* @param string $query The query of the search the user would like to save.
*
* @return array The decoded JSON response
*
* @since 12.3
*/
public function createSavedSearch($query)
{
// Set the API path
$path = '/saved_searches/create.json';
// Set POST request data
$data['query'] = rawurlencode($query);
// Send the request.
return $this->sendRequest($path, 'POST', $data);
}
/**
* Method to delete a saved search for the authenticating user.
*
* @param integer $id The ID of the saved search.
*
* @return array The decoded JSON response
*
* @since 12.3
*/
public function deleteSavedSearch($id)
{
// Check the rate limit for remaining hits
$this->checkRateLimit('saved_searches', 'destroy/:id');
// Set the API path
$path = '/saved_searches/destroy/' . $id . '.json';
// Send the request.
return $this->sendRequest($path, 'POST');
}
}
| waveywhite/joomla-cms | libraries/joomla/twitter/search.php | PHP | gpl-2.0 | 5,627 |
$(document).ready(function(){
// removing some column headers when there is at least one product
if ( $('#lines tbody tr.product').length > 0 )
{
$('#lines').addClass('with-product');
$('body').addClass('with-product');
}
if ( $('#lines tbody tr.ticket').length > 0 )
{
$('#lines').addClass('with-ticket');
$('body').addClass('with-ticket');
}
window.print();
// update the parent window's content
if ( window.opener != undefined && typeof window.opener.li === 'object' )
window.opener.li.initContent();
// print again
if ( $('#options #print-again').length > 0 )
window.location = $('#options #print-again a').prop('href');
// close
if ( $('#options #close').length > 0 && $('#options #print-again').length == 0 )
window.close();
});
| Fabrice-li/e-venement | web/js/print-tickets.js | JavaScript | gpl-2.0 | 803 |
<?php
/**
* Class SlideshowPluginSlideInserter
*
* TODO This class will probably need to be renamed to SlideshowPluginSlideHandler to explain more functionality
* TODO than just inserting slides.
*
* @since 2.0.0
* @author Stefan Boonstra
*/
class SlideshowPluginSlideInserter
{
/** @var bool $localizedScript Flag to see if localizeScript function has been called */
private static $localizedScript;
/**
* Returns the html for showing the image insert button.
* Localizes script unless $localizeScript is set to false.
*
* @since 2.0.0
* @param boolean $localizeScript
* @return String $button
*/
static function getImageSlideInsertButton($localizeScript = true)
{
if ($localizeScript)
{
self::localizeScript();
}
// Put popup html in footer
add_action('admin_footer', array(__CLASS__, 'includePopup'));
// Return button html
ob_start();
include(SlideshowPluginMain::getPluginPath() . '/views/' . __CLASS__ . '/insert-image-button.php');
return ob_get_clean();
}
/**
* Returns the html for showing the text insert button.
* Localizes script unless $localizeScript is set to false.
*
* @since 2.0.0
* @param boolean $localizeScript
* @return String $button
*/
static function getTextSlideInsertButton($localizeScript = true)
{
if ($localizeScript)
{
self::localizeScript();
}
// Return button html
ob_start();
include(SlideshowPluginMain::getPluginPath() . '/views/' . __CLASS__ . '/insert-text-button.php');
return ob_get_clean();
}
/**
* Returns the html for showing the video insert button.
* Localizes script unless $localizeScript is set to false.
*
* @since 2.1.0
* @param boolean $localizeScript
* @return String $button
*/
static function getVideoSlideInsertButton($localizeScript = true)
{
if ($localizeScript)
{
self::localizeScript();
}
// Return button html
ob_start();
include(SlideshowPluginMain::getPluginPath() . '/views/' . __CLASS__ . '/insert-video-button.php');
return ob_get_clean();
}
/**
* This function is registered in the SlideshowPluginAjax class
* and prints the results from the search query.
*
* @since 2.0.0
*/
static function printSearchResults()
{
global $wpdb;
// Numberposts and offset
$numberPosts = 10;
$offset = 0;
if (isset($_POST['offset']) &&
is_numeric($_POST['offset']))
{
$offset = $_POST['offset'];
}
$attachmentIDs = array();
if (isset($_POST['attachmentIDs']))
{
$attachmentIDs = array_filter($_POST['attachmentIDs'], 'ctype_digit');
}
// Get attachments with a title alike the search string, needs to be filtered
add_filter('posts_where', array(__CLASS__, 'printSearchResultsWhereFilter'));
$query = new WP_Query(array(
'post_type' => 'attachment',
'post_status' => 'inherit',
'offset' => $offset,
'posts_per_page' => $numberPosts + 1,
'orderby' => 'date',
'order' => 'DESC'
));
$attachments = $query->get_posts();
remove_filter('posts_where', array(__CLASS__, 'printSearchResultsWhereFilter'));
// Look for images by their file's name when not enough matching results were found
if (count($attachments) < $numberPosts)
{
$searchString = esc_sql($_POST['search']);
// Add results found with the previous query to the $attachmentIDs array to exclude them as well
foreach ($attachments as $attachment)
{
$attachmentIDs[] = $attachment->ID;
}
// Search by file name
$fileNameQuery = new WP_Query(array(
'post_type' => 'attachment',
'post_status' => 'inherit',
'posts_per_page' => $numberPosts - count($attachments),
'post__not_in' => $attachmentIDs,
'meta_query' => array(
array(
'key' => '_wp_attached_file',
'value' => $searchString,
'compare' => 'LIKE'
)
)
));
// Put found results in attachments array
$fileNameQueryAttachments = $fileNameQuery->get_posts();
if (is_array($fileNameQueryAttachments) &&
count($fileNameQueryAttachments) > 0)
{
foreach ($fileNameQueryAttachments as $fileNameQueryAttachment)
{
$attachments[] = $fileNameQueryAttachment;
}
}
}
// Check if there are enough attachments to print a 'Load more images' button
$loadMoreResults = false;
if (count($attachments) > $numberPosts)
{
array_pop($attachments);
$loadMoreResults = true;
}
// Print results to the screen
if (count($attachments) > 0)
{
if ($offset > 0)
{
echo '<tr valign="top">
<td colspan="3" style="text-align: center;">
<b>' . count($attachments) . ' ' . __('More results loaded', 'slideshow-plugin') . '<b>
</td>
</tr>';
}
foreach ($attachments as $attachment)
{
$image = wp_get_attachment_image_src($attachment->ID);
if (!is_array($image) ||
!$image)
{
if (!empty($attachment->guid))
{
$imageSrc = $attachment->guid;
}
else
{
continue;
}
}
else
{
$imageSrc = $image[0];
}
if (!$imageSrc ||
empty($imageSrc))
{
$imageSrc = SlideshowPluginMain::getPluginUrl() . '/images/SlideshowPluginPostType/no-img.png';
}
echo '<tr valign="top" data-attachment-Id="' . $attachment->ID . '" class="result-table-row">
<td class="image">
<img width="60" height="60" src="' . $imageSrc . '" class="attachment" alt="' . $attachment->post_title . '" title="' . $attachment->post_title . '">
</td>
<td class="column-title">
<strong class="title">' . $attachment->post_title . '</strong>
<p class="description">' . $attachment->post_content . '</p>
</td>
<td class="insert-button">
<input
type="button"
class="insert-attachment button-secondary"
value="' . __('Insert', 'slideshow-plugin') . '"
/>
</td>
</tr>';
}
if ($loadMoreResults)
{
echo '<tr>
<td colspan="3" style="text-align: center;">
<button class="button-secondary load-more-results" data-offset="' . ($offset + $numberPosts) . '">
' . __('Load more results', 'slideshow-plugin') . '
</button>
</td>
</tr>';
}
}
else
{
echo '<tr>
<td colspan="3" style="text-align: center;">
<a href="' . admin_url() . 'media-new.php" target="_blank">
' . __('No images were found, click here to upload some.', 'slideshow-plugin') . '
</a>
</td>
</tr>';
}
die;
}
/**
* Applies a where clause on the get_posts call from self::printSearchResults()
*
* @since 2.0.0
* @param string $where
* @return string $where
*/
static function printSearchResultsWhereFilter($where)
{
global $wpdb;
$searchString = $_POST['search'];
$searchString = esc_sql($searchString);
if (isset($_POST['search']))
{
$where .= $wpdb->prepare(
" AND (post_title LIKE '%%%s%%' OR ID LIKE '%%%s%%') ",
$searchString,
$searchString
);
}
return $where;
}
/**
* Include popup, needs to be called in the footer
*
* @since 2.0.0
*/
static function includePopup()
{
include(SlideshowPluginMain::getPluginPath() . '/views/' . __CLASS__ . '/search-popup.php');
}
/**
* Enqueues styles and scripts necessary for the media upload button.
*
* @since 2.2.12
*/
static function localizeScript()
{
// Return if function doesn't exist
if (!function_exists('get_current_screen') ||
self::$localizedScript)
{
return;
}
// Return when not on a slideshow edit page, or files have already been included.
$currentScreen = get_current_screen();
if ($currentScreen->post_type != SlideshowPluginPostType::$postType)
{
return;
}
wp_localize_script(
'slideshow-jquery-image-gallery-backend-script',
'slideshow_jquery_image_gallery_backend_script_editSlideshow',
array(
'data' => array(),
'localization' => array(
'confirm' => __('Are you sure you want to delete this slide?', 'slideshow-plugin'),
'uploaderTitle' => __('Insert image slide', 'slideshow-plugin')
)
)
);
// Set enqueued to true
self::$localizedScript = true;
}
} | tzitziras/aluminet.gr | wp-content/plugins/slideshow-jquery-image-gallery/classes/SlideshowPluginSlideInserter.php | PHP | gpl-2.0 | 8,493 |
<?php
/**
* @file
* Contains \Drupal\migrate_drupal\Tests\d6\MigrateFieldWidgetSettingsTest.
*/
namespace Drupal\migrate_drupal\Tests\d6;
use Drupal\migrate\MigrateExecutable;
use Drupal\migrate_drupal\Tests\MigrateDrupalTestBase;
/**
* Migrate field widget settings.
*
* @group migrate_drupal
*/
class MigrateFieldWidgetSettingsTest extends MigrateDrupalTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = array(
'field',
'telephone',
'link',
'file',
'image',
'datetime',
'node',
);
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
entity_create('node_type', array('type' => 'test_page'))->save();
entity_create('node_type', array('type' => 'story'))->save();
// Add some id mappings for the dependant migrations.
$id_mappings = array(
'd6_field_instance' => array(
array(array('fieldname', 'page'), array('node', 'fieldname', 'page')),
),
'd6_field' => array(
array(array('field_test'), array('node', 'field_test')),
array(array('field_test_two'), array('node', 'field_test_two')),
array(array('field_test_three'), array('node', 'field_test_three')),
array(array('field_test_email'), array('node', 'field_test_email')),
array(array('field_test_link'), array('node', 'field_test_link')),
array(array('field_test_filefield'), array('node', 'field_test_filefield')),
array(array('field_test_imagefield'), array('node', 'field_test_imagefield')),
array(array('field_test_phone'), array('node', 'field_test_phone')),
array(array('field_test_date'), array('node', 'field_test_date')),
array(array('field_test_datestamp'), array('node', 'field_test_datestamp')),
array(array('field_test_datetime'), array('node', 'field_test_datetime')),
),
);
$this->prepareMigrations($id_mappings);
$migration = entity_load('migration', 'd6_field_instance_widget_settings');
$dumps = array(
$this->getDumpDirectory() . '/ContentNodeFieldInstance.php',
$this->getDumpDirectory() . '/ContentNodeField.php',
$this->getDumpDirectory() . '/ContentFieldTest.php',
$this->getDumpDirectory() . '/ContentFieldTestTwo.php',
$this->getDumpDirectory() . '/ContentFieldMultivalue.php',
);
$this->prepare($migration, $dumps);
$executable = new MigrateExecutable($migration, $this);
$executable->import();
}
/**
* Test that migrated view modes can be loaded using D8 API's.
*/
public function testWidgetSettings() {
// Test the config can be loaded.
$form_display = entity_load('entity_form_display', 'node.story.default');
$this->assertEqual(is_null($form_display), FALSE, "Form display node.story.default loaded with config.");
// Text field.
$component = $form_display->getComponent('field_test');
$expected = array('weight' => 1, 'type' => 'text_textfield');
$expected['settings'] = array('size' => 60, 'placeholder' => '');
$expected['third_party_settings'] = array();
$this->assertEqual($component, $expected, 'Text field settings are correct.');
// Integer field.
$component = $form_display->getComponent('field_test_two');
$expected['type'] = 'number';
$expected['weight'] = 1;
$expected['settings'] = array('placeholder' => '');
$this->assertEqual($component, $expected);
// Float field.
$component = $form_display->getComponent('field_test_three');
$expected['weight'] = 2;
$this->assertEqual($component, $expected);
// Email field.
$component = $form_display->getComponent('field_test_email');
$expected['type'] = 'email_default';
$expected['weight'] = 6;
$this->assertEqual($component, $expected);
// Link field.
$component = $form_display->getComponent('field_test_link');
$this->assertEqual($component['type'], 'link_default');
$this->assertEqual($component['weight'], 7);
$this->assertFalse(array_filter($component['settings']));
// File field.
$component = $form_display->getComponent('field_test_filefield');
$expected['type'] = 'file_generic';
$expected['weight'] = 8;
$expected['settings'] = array('progress_indicator' => 'bar');
$this->assertEqual($component, $expected);
// Image field.
$component = $form_display->getComponent('field_test_imagefield');
$expected['type'] = 'image_image';
$expected['weight'] = 9;
$expected['settings'] = array('progress_indicator' => 'bar', 'preview_image_style' => 'thumbnail');
$this->assertEqual($component, $expected);
// Phone field.
$component = $form_display->getComponent('field_test_phone');
$expected['type'] = 'telephone_default';
$expected['weight'] = 13;
$expected['settings'] = array('placeholder' => '');
$this->assertEqual($component, $expected);
// Date fields.
$component = $form_display->getComponent('field_test_date');
$expected['type'] = 'datetime_default';
$expected['weight'] = 10;
$expected['settings'] = array();
$this->assertEqual($component, $expected);
$component = $form_display->getComponent('field_test_datestamp');
$expected['weight'] = 11;
$this->assertEqual($component, $expected);
$component = $form_display->getComponent('field_test_datetime');
$expected['weight'] = 12;
$this->assertEqual($component, $expected);
}
}
| webflo/d8-core | modules/migrate_drupal/src/Tests/d6/MigrateFieldWidgetSettingsTest.php | PHP | gpl-2.0 | 5,460 |
/*
* Copyright (C) 2014 The Android Open Source Project
* Copyright (c) 2000, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.nio;
/**
* A read/write HeapLongBuffer.
*/
class HeapLongBuffer
extends LongBuffer {
// For speed these fields are actually declared in X-Buffer;
// these declarations are here as documentation
/*
protected final long[] hb;
protected final int offset;
*/
HeapLongBuffer(int cap, int lim) { // package-private
this(cap, lim, false);
}
HeapLongBuffer(int cap, int lim, boolean isReadOnly) { // package-private
super(-1, 0, lim, cap, new long[cap], 0);
this.isReadOnly = isReadOnly;
}
HeapLongBuffer(long[] buf, int off, int len) { // package-private
this(buf, off, len, false);
}
HeapLongBuffer(long[] buf, int off, int len, boolean isReadOnly) { // package-private
super(-1, off, off + len, buf.length, buf, 0);
this.isReadOnly = isReadOnly;
}
protected HeapLongBuffer(long[] buf,
int mark, int pos, int lim, int cap,
int off) {
this(buf, mark, pos, lim, cap, off, false);
}
protected HeapLongBuffer(long[] buf,
int mark, int pos, int lim, int cap,
int off, boolean isReadOnly) {
super(mark, pos, lim, cap, buf, off);
this.isReadOnly = isReadOnly;
}
public LongBuffer slice() {
return new HeapLongBuffer(hb,
-1,
0,
this.remaining(),
this.remaining(),
this.position() + offset,
isReadOnly);
}
public LongBuffer duplicate() {
return new HeapLongBuffer(hb,
this.markValue(),
this.position(),
this.limit(),
this.capacity(),
offset,
isReadOnly);
}
public LongBuffer asReadOnlyBuffer() {
return new HeapLongBuffer(hb,
this.markValue(),
this.position(),
this.limit(),
this.capacity(),
offset, true);
}
protected int ix(int i) {
return i + offset;
}
public long get() {
return hb[ix(nextGetIndex())];
}
public long get(int i) {
return hb[ix(checkIndex(i))];
}
public LongBuffer get(long[] dst, int offset, int length) {
checkBounds(offset, length, dst.length);
if (length > remaining())
throw new BufferUnderflowException();
System.arraycopy(hb, ix(position()), dst, offset, length);
position(position() + length);
return this;
}
public boolean isDirect() {
return false;
}
public boolean isReadOnly() {
return isReadOnly;
}
public LongBuffer put(long x) {
if (isReadOnly) {
throw new ReadOnlyBufferException();
}
hb[ix(nextPutIndex())] = x;
return this;
}
public LongBuffer put(int i, long x) {
if (isReadOnly) {
throw new ReadOnlyBufferException();
}
hb[ix(checkIndex(i))] = x;
return this;
}
public LongBuffer put(long[] src, int offset, int length) {
if (isReadOnly) {
throw new ReadOnlyBufferException();
}
checkBounds(offset, length, src.length);
if (length > remaining())
throw new BufferOverflowException();
System.arraycopy(src, offset, hb, ix(position()), length);
position(position() + length);
return this;
}
public LongBuffer put(LongBuffer src) {
if (isReadOnly) {
throw new ReadOnlyBufferException();
}
if (src instanceof HeapLongBuffer) {
if (src == this)
throw new IllegalArgumentException();
HeapLongBuffer sb = (HeapLongBuffer) src;
int n = sb.remaining();
if (n > remaining())
throw new BufferOverflowException();
System.arraycopy(sb.hb, sb.ix(sb.position()),
hb, ix(position()), n);
sb.position(sb.position() + n);
position(position() + n);
} else if (src.isDirect()) {
int n = src.remaining();
if (n > remaining())
throw new BufferOverflowException();
src.get(hb, ix(position()), n);
position(position() + n);
} else {
super.put(src);
}
return this;
}
public LongBuffer compact() {
if (isReadOnly) {
throw new ReadOnlyBufferException();
}
System.arraycopy(hb, ix(position()), hb, ix(0), remaining());
position(remaining());
limit(capacity());
discardMark();
return this;
}
public ByteOrder order() {
return ByteOrder.nativeOrder();
}
}
| AdmireTheDistance/android_libcore | ojluni/src/main/java/java/nio/HeapLongBuffer.java | Java | gpl-2.0 | 6,185 |
<?
include('catalog.php');
$out = array();
foreach ($catalog as $row){
$hex = '';
foreach ($row['unicode'] as $cp) $hex .= sprintf('%x', $cp);
$html = "<span class=\"emoji emoji$hex\"></span>";
$out[] = array(
'name' => $row['char_name']['title'],
'unified' => $row['unicode'],
'docomo' => $row['docomo']['unicode'],
'kddi' => $row['au']['unicode'],
'softbank' => $row['softbank']['unicode'],
'google' => $row['google']['unicode'],
'html' => $html,
);
}
function format_codepoints($us){
if (!count($us)) return '-';
$out = array();
foreach ($us as $u){
$out[] = 'U+'.sprintf('%04X', $u);
}
return implode(' ', $out);
}
?>
<html>
<head>
<title>Emoji Catalog</title>
<link rel="stylesheet" type="text/css" media="all" href="emoji.css" />
<style type="text/css">
body {
font-size: 12px;
font-family: Arial, Helvetica, sans-serif;
}
table {
-webkit-border-radius: 0.41em;
-moz-border-radius: 0.41em;
border: 1px solid #999;
font-size: 12px;
}
table td {
padding-left: 0.41em;
padding-right: 0.41em;
}
table th {
font-weight: bold;
text-align: left;
background: #BBB;
color: #333;
font-size: 14px;
padding: 0.41em;
}
table tbody tr:nth-child(even) {
background: #dedede;
}
table tbody td {
padding: 0.41em;
}
</style>
</head>
<body>
<h1>Emoji Catalog</h1>
<table cellspacing="0" cellpadding="0">
<tr>
<th colspan="2">Name</th>
<th>Unified</th>
<th>DoCoMo</th>
<th>KDDI</th>
<th>Softbank</th>
<th>Google</th>
</tr>
<tbody>
<?
foreach ($out as $row){
echo "\t<tr>\n";
echo "\t\t<td>$row[html]</td>\n";
echo "\t\t<td>".HtmlSpecialChars(StrToLower($row['name']))."</td>\n";
echo "\t\t<td>".format_codepoints($row['unified'])."</td>\n";
echo "\t\t<td>".format_codepoints($row['docomo'])."</td>\n";
echo "\t\t<td>".format_codepoints($row['kddi'])."</td>\n";
echo "\t\t<td>".format_codepoints($row['softbank'])."</td>\n";
echo "\t\t<td>".format_codepoints($row['google'])."</td>\n";
echo "\t</tr>\n";
}
?>
</tbody>
</table>
</body>
<html>
| kirvin/journeyof1000li | wp-content/plugins/twitter-tracker/emoji/data/build_table.php | PHP | gpl-2.0 | 2,108 |
<?php
/**
* @file
* Contains the UCXF_Field class.
*/
/**
* Base class for a Extra Fields Pane field
*/
class UCXF_Field {
// -----------------------------------------------------------------------------
// CONSTANTS
// -----------------------------------------------------------------------------
// Fieldtypes
const UCXF_WIDGET_TYPE_SELECT = 1;
const UCXF_WIDGET_TYPE_CONSTANT = 2;
const UCXF_WIDGET_TYPE_PHP = 3;
const UCXF_WIDGET_TYPE_CHECKBOX = 4;
const UCXF_WIDGET_TYPE_TEXTFIELD = 5;
const UCXF_WIDGET_TYPE_PHP_SELECT = 6;
// -----------------------------------------------------------------------------
// PROPERTIES
// -----------------------------------------------------------------------------
/**
* An array of pane types the field is in.
* @var array
* @access private
*/
private $pane_types;
/**
* An array of page names on which the field may be displayed
* @var array
* @access private
*/
private $display_settings;
// -----------------------------------------------------------------------------
// CONSTRUCT
// -----------------------------------------------------------------------------
/**
* UCXF_Field object constructor
* @access public
* @return void
*/
public function __construct() {
// Set default values
$this->weight = 0;
$this->value_type = self::UCXF_WIDGET_TYPE_TEXTFIELD;
$this->required = FALSE;
$this->enabled = TRUE;
$this->pane_types = array();
$this->display_settings = array();
}
// -----------------------------------------------------------------------------
// STATIC METHODS
// -----------------------------------------------------------------------------
/**
* Returns an example for the value section
* @param int $field_type
* One of the field types defined by Extra Fields Pane
* @access public
* @static
* @return string
*/
public static function get_example($field_type) {
switch ($field_type) {
case self::UCXF_WIDGET_TYPE_SELECT:
return '<code>
|' . t('Please select') . '<br />
option1|' . t('Option 1') . '<br />
option2|' . t('Option 2')
. '</code>';
case self::UCXF_WIDGET_TYPE_CONSTANT:
return '<code>' . t('A constant value') . '</code>';
case self::UCXF_WIDGET_TYPE_PHP:
return '<code><?php return "' . t('A string') . '"; ?></code>';
case self::UCXF_WIDGET_TYPE_PHP_SELECT:
return "<code>
<?php<br />
return array(<br />
'' => '" . t('Please select') . "',<br />
'option1' => '" . t('Option 1') . "',<br />
'option2' => '" . t('Option 2') . "',<br />
);<br />
?>"
. "</code>";
}
}
// -----------------------------------------------------------------------------
// SETTERS
// -----------------------------------------------------------------------------
/**
* Setter
* @param string $p_sMember
* @param mixed $p_mValue
* @access public
* @return boolean
*/
public function __set($p_sMember, $p_mValue) {
switch ($p_sMember) {
case 'display_settings':
if (is_string($p_mValue)) {
$p_mValue = unserialize($p_mValue);
}
if (is_array($p_mValue)) {
foreach ($p_mValue as $option_id => $display_setting) {
$this->display_settings[$option_id] = ($display_setting) ? TRUE : FALSE;
}
return TRUE;
}
break;
case 'pane_type':
if (is_string($p_mValue)) {
$pane_types = explode('|', $p_mValue);
return $this->__set('pane_type', $pane_types);
}
elseif (is_array($p_mValue)) {
$this->pane_types = array();
foreach ($p_mValue as $pane_type) {
$pane_type = (string) $pane_type;
if (!empty($pane_type)) {
$this->pane_types[$pane_type] = $pane_type;
}
}
return TRUE;
}
default:
$this->{$p_sMember} = $p_mValue;
return TRUE;
}
return FALSE;
}
/**
* Load an existing item from an array.
* @access public
* @param array $p_aParams
*/
function from_array($p_aParams) {
foreach ($p_aParams as $sKey => $mValue) {
$this->__set($sKey, $mValue);
}
}
// -----------------------------------------------------------------------------
// GETTERS
// -----------------------------------------------------------------------------
/**
* Getter
* @param string $p_sMember
* @access public
* @return mixed
*/
public function __get($p_sMember) {
switch ($p_sMember) {
case 'id':
return $this->__get('field_id');
case 'pane_type':
return implode('|', $this->pane_types);
case 'pane_types':
return $this->pane_types;
default:
if (isset($this->{$p_sMember})) {
return $this->{$p_sMember};
}
break;
}
return NULL;
}
/**
* Return as an array of values.
* @access public
* @return array
*/
public function to_array() {
$aOutput = array();
// Return fields as specified in the schema.
$schema = drupal_get_schema('uc_extra_fields');
if (!empty($schema['fields']) && is_array($schema['fields'])) {
foreach ($schema['fields'] as $field => $info) {
$aOutput[$field] = $this->__get($field);
}
}
return $aOutput;
}
/**
* Output a value with filtering
* @param string $p_sMember
* @access public
* @return string
*/
public function output($p_sMember) {
switch ($p_sMember) {
case 'description':
return uc_extra_fields_pane_tt("field:$this->db_name:description", filter_xss_admin($this->{$p_sMember}));
case 'label':
return uc_extra_fields_pane_tt("field:$this->db_name:label", check_plain($this->{$p_sMember}));
case 'pane_type':
return check_plain($this->__get('pane_type'));
default:
if (isset($this->{$p_sMember})) {
return check_plain($this->{$p_sMember});
}
}
return '';
}
/**
* Output a value based on the field type
* @param string $p_sValue
* The given value
* @access public
* @return void
*/
public function output_value($p_sValue) {
switch ($this->value_type) {
case self::UCXF_WIDGET_TYPE_CHECKBOX:
return ($p_sValue) ? t('Yes') : t('No');
case self::UCXF_WIDGET_TYPE_SELECT:
case self::UCXF_WIDGET_TYPE_PHP_SELECT:
$values = $this->generate_value();
return (isset($values[$p_sValue])) ? check_plain($values[$p_sValue]) : check_plain($p_sValue);
default:
return ($p_sValue != '') ? check_plain($p_sValue) : t('n/a');
}
}
/**
* Returns the "readable" value type, as a string.
*
* @return string
*/
public function get_value_type() {
switch ($this->value_type) {
case UCXF_Field::UCXF_WIDGET_TYPE_TEXTFIELD:
return t('Textfield');
case UCXF_Field::UCXF_WIDGET_TYPE_SELECT:
return t('Select list');
case UCXF_Field::UCXF_WIDGET_TYPE_CHECKBOX:
return t('Checkbox');
case UCXF_Field::UCXF_WIDGET_TYPE_CONSTANT:
return t('Constant');
case UCXF_Field::UCXF_WIDGET_TYPE_PHP:
return t('PHP string');
case UCXF_Field::UCXF_WIDGET_TYPE_PHP_SELECT:
return t('PHP select list');
}
}
// -----------------------------------------------------------------------------
// LOGIC
// -----------------------------------------------------------------------------
/**
* Returns if the field's value may be displayed on te given page.
*
* Returns TRUE if the display setting for the given page does not exist.
*
* @param string $p_sPage
* @access public
* @return boolean
*/
public function may_display($p_sPage) {
if (isset($this->display_settings[$p_sPage])) {
return ($this->display_settings[$p_sPage]) ? TRUE : FALSE;
}
return TRUE;
}
/**
* Returns if field is in given pane
*
* @param string $p_sPane
* @access public
* @return boolean
*/
public function in_pane($p_sPane) {
return (isset($this->pane_types[$p_sPane]));
}
// -----------------------------------------------------------------------------
// DATABASE REQUESTS
// -----------------------------------------------------------------------------
// Deprecated
/**
* load()
* Loads field from database
* @param int $p_iField_id
* @access public
* @return UCXF_Field
*/
public function load($p_iField_id) {
return uc_extra_fields_pane_field_load($p_iField_id);
}
/**
* save()
* Saves field in database
* @access public
* @return void
*/
public function save() {
// Prepare values
$values = $this->to_array();
$update = array();
$sHook = 'insert';
if (!empty($this->field_id)) {
$update[] = 'field_id';
$sHook = 'update';
}
drupal_write_record('uc_extra_fields', $values, $update);
$this->field_id = $values['field_id'];
// Let other modules react on this
module_invoke_all('ucxf_field', $this, $sHook);
}
/**
* Delete the field from the database.
* @access public
* @return boolean
*/
public function delete() {
return UCXF_FieldList::deleteField($this);
}
// -----------------------------------------------------------------------------
// FORMS
// -----------------------------------------------------------------------------
/**
* Get the edit form for the field.
* @access public
* @return array
*/
public function edit_form() {
$form = array('#tree' => TRUE);
// Add instance of this to the form
$form['field'] = array(
'#type' => 'value',
'#value' => $this,
);
if (!empty($this->field_id)) {
$form['ucxf']['field_id'] = array(
'#type' => 'hidden',
'#value' => $this->field_id,
);
drupal_set_title(t('Modify field: @name', array('@name' => $this->db_name)), PASS_THROUGH);
}
$form['ucxf']['label'] = array(
'#title' => t('Label'),
'#type' => 'textfield',
'#size' => 25,
'#description' => t('Label shown to customers in checkout pages.'),
'#required' => TRUE,
'#default_value' => $this->label,
'#weight' => 0,
);
$default_db_name = $this->db_name;
if (strpos($default_db_name, 'ucxf_') !== 0) {
$default_db_name = 'ucxf_';
}
$form['ucxf']['db_name'] = array(
'#title' => t('Field name'),
'#type' => 'textfield',
'#size' => 25,
'#description' => t('Database field name. It must contain only lower chars a-z, digits 0-9 and _. Max allowed length is !number characters. This is inclusive the prefix %prefix.', array('!number' => 32, '%prefix' => 'ucxf_')),
'#required' => TRUE,
'#default_value' => $this->db_name,
'#weight' => 1,
'#maxlength' => 32,
);
if (isset($this->field_id)) {
// if field already exists, don't allow to alter the name
$form['ucxf']['db_name']['#disabled'] = 'disabled';
$form['ucxf']['db_name']['#value'] = $this->db_name;
}
$form['ucxf']['description'] = array(
'#title' => t('Description'),
'#type' => 'textarea',
'#rows' => 3,
'#description' => t('Insert a description to tell customers how to fill this field. ONLY applies for select/textbox options'),
'#default_value' => $this->description,
'#weight' => 3,
);
$form['ucxf']['weight'] = array(
'#type' => 'weight',
'#title' => t('Weight'),
'#delta' => 30,
'#default_value' => $this->weight,
'#description' => t('The listing position to display the order data on checkout/order panes.'),
'#weight' => 5,
);
$form['ucxf']['pane_type'] = array(
'#title' => t('Select which pane you would like the form value to be hooked into.'),
'#type' => 'select',
'#options' => array('extra_information' => t('Extra Information pane')),
'#default_value' => $this->pane_type,
'#weight' => 7,
);
$value_type_options = array(
self::UCXF_WIDGET_TYPE_TEXTFIELD => array(
'#title' => t('Textfield'),
'#description' => t('Let the user input the data in a textbox. If you want a default value, put it in "value" field below.'),
),
self::UCXF_WIDGET_TYPE_SELECT => array(
'#title' => t('Select list'),
'#description' => t('Let the user select from a list of options (enter one <strong>safe_key|Some readable option</strong> per line).'),
),
self::UCXF_WIDGET_TYPE_CHECKBOX => array(
'#title' => t('Checkbox'),
'#description' => t('Let the user select from a checkbox.'),
),
self::UCXF_WIDGET_TYPE_CONSTANT => array(
'#title' => t('Constant'),
'#description' => t('Show a admin defined constant value, insert the value in the "value" section.'),
),
);
if (user_access('use php fields')) {
$value_type_options += array(
self::UCXF_WIDGET_TYPE_PHP => array(
'#title' => t('PHP string'),
'#description' => t('Set the value to the php code that returns a <code>STRING</code> (PHP-mode, experts only).'),
),
self::UCXF_WIDGET_TYPE_PHP_SELECT => array(
'#title' => t('PHP select list'),
'#description' => t('Let the user select from a list of options from php code returning a <code>ARRAY</code> of key => value pairs. ie- <code>return array(\'element1\' => \'somevalue1\',\'element2\' => \'somevalue2\')</code> (PHP-mode, experts only).'),
),
);
}
$form['ucxf']['value_type'] = array(
'#type' => 'radios',
'#title' => t('Field type'),
'#options' => $value_type_options,
'#default_value' => $this->value_type,
'#weight' => 9,
'#required' => TRUE,
'#after_build' => array('uc_extra_fields_pane_field_value_type_after_build'),
);
$form['ucxf']['value'] = array(
'#type' => 'textarea',
'#title' => t('Value'),
'#description' => t('If the PHP-mode is chosen, enter PHP code between %php. Note that executing incorrect PHP-code can break your Drupal site.', array('%php' => '<?php ?>')),
'#default_value' => $this->value,
'#weight' => 10,
);
$form['ucxf']['required'] = array(
'#title' => t('Field required'),
'#type' => 'checkbox',
'#description' => t('Check this item if the field is mandatory.'),
'#default_value' => $this->required,
'#weight' => 12,
);
$form['ucxf']['enabled'] = array(
'#title' => t('Enabled'),
'#type' => 'checkbox',
'#default_value' => $this->enabled,
'#weight' => 14,
);
$display_options = module_invoke_all('ucxf_display_options', $this);
$form['ucxf']['display_settings'] = array(
'#title' => t('Display options'),
'#type' => 'fieldset',
'#weight' => 16,
'#description' => t('Choose on which pages you want to display the field.'),
);
foreach ($display_options as $option_id => $option) {
$form['ucxf']['display_settings'][$option_id] = array(
'#title' => $option_id,
'#type' => 'checkbox',
'#default_value' => $this->may_display($option_id),
);
foreach ($option as $attribute_name => $attribute_value) {
switch ($attribute_name) {
case 'title':
$form['ucxf']['display_settings'][$option_id]['#title'] = $attribute_value;
break;
case 'description':
$form['ucxf']['display_settings'][$option_id]['#description'] = $attribute_value;
break;
case 'weight':
$form['ucxf']['display_settings'][$option_id]['#weight'] = $attribute_value;
break;
}
}
}
$form['ucxf']['submit'] = array(
'#type' => 'submit',
'#value' => t('Save'),
'#weight' => 50,
);
if ($this->returnpath) {
// Add 'cancel'-link
$form['ucxf']['submit']['#suffix'] = l(t('Cancel'), $this->returnpath);
}
return $form;
}
/**
* Validate the edit form for the item.
* @param array $form
* @param array $form_state
* @access public
* @return void
*/
public function edit_form_validate($form, &$form_state) {
$field = $form_state['values']['ucxf'];
// No label.
if (!$field['label']) {
form_set_error('ucxf][label', t('Custom order field: you need to provide a label.'));
}
// No field name.
if (!$field['db_name']) {
form_set_error('ucxf][db_name', t('Custom order field: you need to provide a field name.'));
}
if (isset($field['weight']) && !$field['weight'] && $field['weight'] !== 0 && $field['weight'] !== '0') {
form_set_error('ucxf][weight', t('Custom order field: you need to provide a weight value for this extra field.'));
}
if (isset($form['ucxf']['pane_type']) && empty($field['pane_type'])) {
form_set_error('ucxf][pane_type', t('Custom order field: you need to provide a pane-type for this extra field.'));
}
if (!$field['value_type']) {
form_set_error('ucxf][value_type', t('Custom order field: you need to provide a way of processing the value for this field as either textbox, select, constant, or php.'));
}
if (($field['value_type'] == self::UCXF_WIDGET_TYPE_CONSTANT || $field['value_type'] == self::UCXF_WIDGET_TYPE_PHP) && !$field['value'] ) {
form_set_error('ucxf][value', t('Custom order field: you need to provide a value for this way of calculating the field value.'));
}
// Field name validation.
if (empty($field['field_id'])) {
$field_name = $field['db_name'];
// Add the 'ucxf_' prefix.
if (strpos($field_name, 'ucxf_') !== 0) {
$field_name = 'ucxf_' . $field_name;
form_set_value($form['ucxf']['db_name'], $field_name, $form_state);
}
// Invalid field name.
if (!preg_match('!^ucxf_[a-z0-9_]+$!', $field_name)) {
form_set_error('ucxf][db_name', t('Custom order field: the field name %field_name is invalid. The name must include only lowercase unaccentuated letters, numbers, and underscores.', array('%field_name' => $field_name)));
}
// considering prefix ucxf_ no more than 32 characters (32 max for a db field)
if (strlen($field_name) > 32) {
form_set_error('ucxf][db_name', t('Custom order field: the field name %field_name is too long. The name is limited to !number characters, including the \'ucxf_\' prefix.', array('!number' => 32, '%field_name' => $field_name)));
}
// Check if field name already exists in table.
$count = db_select('uc_extra_fields')
->condition('db_name', $field_name)
->countQuery()
->execute()
->fetchField();
if ((int) $count > 0) {
form_set_error('ucxf][db_name', t('Custom order field: the field name %field_name already exists.', array('%field_name' => $field_name)));
}
}
// Check if php tags are present in case of a php field
if ($field['value_type'] == self::UCXF_WIDGET_TYPE_PHP || $field['value_type'] == self::UCXF_WIDGET_TYPE_PHP_SELECT) {
$php_open_tag_position = stripos($field['value'], '<?php');
$php_close_tag_position = strripos($field['value'], '?>');
if ($php_open_tag_position === FALSE || $php_close_tag_position === FALSE || $php_open_tag_position > $php_close_tag_position) {
form_set_error('ucxf][value', t('The PHP code is not entered between %php.', array('%php' => '<?php ?>')));
return;
}
}
// Display a warning when select or PHP-select fields are marked as required, but have no option with an empty key
if (($field['value_type'] == self::UCXF_WIDGET_TYPE_SELECT || $field['value_type'] == self::UCXF_WIDGET_TYPE_PHP_SELECT) && $field['required'] == TRUE) {
$this->value_type = $field['value_type'];
$this->value = $field['value'];
$options = $this->generate_value(FALSE);
$has_empty_key = FALSE;
foreach ($options as $key => $value) {
if ($key === '' || $key === ' ') {
$has_empty_key = TRUE;
break;
}
}
if (!$has_empty_key) {
switch ($field['value_type']) {
case self::UCXF_WIDGET_TYPE_SELECT:
$message_suffix = t('In this example the key of the first item is just a single space.');
break;
case self::UCXF_WIDGET_TYPE_PHP_SELECT:
$message_suffix = t('In this example the key of the first item is an empty string.');
break;
}
drupal_set_message(t('The select field %field is marked as required, but there is no "empty" option in the list. Enter an empty option in the value section as in this example: !example', array('%field' => $field['db_name'], '!example' => '<br />' . self::get_example($field['value_type']) . '<br />')) . $message_suffix, 'warning');
}
}
}
/**
* Submit the edit form for the item.
* @param array $form
* @param array $form_state
* @access public
* @return void
*/
public function edit_form_submit($form, &$form_state) {
$this->from_array($form_state['values']['ucxf']);
$this->display_settings = $form_state['values']['ucxf']['display_settings'];
$this->save();
drupal_set_message(t('Field saved'));
if ($this->returnpath) {
$form_state['redirect'] = $this->returnpath;
}
}
// -----------------------------------------------------------------------------
// ACTION
// -----------------------------------------------------------------------------
/**
* generate()
* Generates a field array used in forms generated by uc_extra_fields_pane
* @access public
* @return void
*/
public function generate() {
$return_field = array();
switch ($this->value_type) {
case self::UCXF_WIDGET_TYPE_TEXTFIELD:
$return_field = array(
'#type' => 'textfield',
'#title' => $this->output('label'),
'#description' => $this->output('description'),
'#size' => 32,
'#maxlength' => 255,
'#required' => $this->required,
);
// Add default value only when there is one
$default_value = $this->generate_value();
if ($default_value != '') {
$return_field['#default_value'] = $default_value;
}
break;
case self::UCXF_WIDGET_TYPE_CHECKBOX:
$return_field = array(
'#type' => 'checkbox',
'#title' => $this->output('label'),
'#description' => $this->output('description'),
'#required' => $this->required,
);
break;
case self::UCXF_WIDGET_TYPE_SELECT:
$return_field = array(
'#type' => 'select',
'#title' => $this->output('label'),
'#description' => $this->output('description'),
'#required' => $this->required,
'#options' => $this->generate_value(),
//'#default_value' => NULL,
);
break;
case self::UCXF_WIDGET_TYPE_PHP:
case self::UCXF_WIDGET_TYPE_CONSTANT:
$return_field = array(
'#type' => 'hidden',
'#value' => $this->generate_value(),
);
break;
case self::UCXF_WIDGET_TYPE_PHP_SELECT:
$return_field = array(
'#type' => 'select',
'#title' => $this->output('label'),
'#description' => $this->output('description'),
'#required' => $this->required,
'#options' => $this->generate_value(),
//'#default_value' => NULL,
);
break;
}
return $return_field;
}
/**
* Generates the value for use in fields.
* This value will be used as a default value for textfields
* and as an array of options for selection fields.
* @param boolean $translate
* If values may be translated.
* @access public
* @return mixed
*/
public function generate_value($translate = TRUE) {
switch ($this->value_type) {
case self::UCXF_WIDGET_TYPE_TEXTFIELD:
// This will return a string
$value = (string) $this->value;
if ($translate) {
$value = uc_extra_fields_pane_tt("field:$this->db_name:value", $value);
}
return $value;
case self::UCXF_WIDGET_TYPE_CONSTANT:
// This will return a string, sanitized.
$value = (string) $this->value;
if ($translate) {
$value = check_plain(uc_extra_fields_pane_tt("field:$this->db_name:value", $value));
}
return $value;
case self::UCXF_WIDGET_TYPE_SELECT:
// This will return an array of options
// like array('key' => 'label', 'key2' => 'label2')
$options = array();
$input_token = strtok($this->value, "\n");
while ($input_token !== FALSE) {
if (strpos($input_token, "|")) {
$arr = explode("|", $input_token);
$key = trim($arr[0]);
$label = trim($arr[1]);
}
else {
$key = trim($input_token);
$label = trim($input_token);
}
$options[$key] = $label;
$input_token = strtok("\n");
}
if ($translate) {
// Translate the labels of the options
foreach ($options as $key => $label) {
$options[$key] = uc_extra_fields_pane_tt("field:$this->db_name:value:$key", $label);
}
}
return $options;
case self::UCXF_WIDGET_TYPE_PHP:
// This will return a string.
$value = (string) eval('?>' . $this->value);
if ($translate) {
$value = uc_extra_fields_pane_tt("field:$this->db_name:value", $value);
}
return $value;
case self::UCXF_WIDGET_TYPE_PHP_SELECT:
// This will return an array of options created with eval
// like array('name' => 'value', 'name2' => 'value2')
// unfortunately php_eval() is not equipped for the task,
// so we need to use the standard php-eval.
$options = eval('?>' . $this->value);
if ($translate) {
// Translate the labels of the options
foreach ($options as $key => $label) {
$options[$key] = uc_extra_fields_pane_tt("field:$this->db_name:value:$key", $label);
}
}
return $options;
}
}
}
| alexey-kuznetsov/teploexpert | sites/all/modules/uc_extra_fields_pane/class/UCXF_Field.class.php | PHP | gpl-2.0 | 26,576 |
<?php
/**
* Solr Authority aspect of the Search Multi-class (Results)
*
* PHP version 5
*
* Copyright (C) Villanova University 2011.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* @category VuFind
* @package Search_SolrAuth
* @author Demian Katz <demian.katz@villanova.edu>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org Main Page
*/
namespace VuFind\Search\SolrAuth;
/**
* Solr Authority Search Parameters
*
* @category VuFind
* @package Search_SolrAuth
* @author Demian Katz <demian.katz@villanova.edu>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org Main Page
*/
class Results extends \VuFind\Search\Solr\Results
{
/**
* Constructor
*
* @param \VuFind\Search\Base\Params $params Object representing user search
* parameters.
*/
public function __construct(\VuFind\Search\Base\Params $params)
{
parent::__construct($params);
$this->backendId = 'SolrAuth';
}
}
| ebsco/vufind | module/VuFind/src/VuFind/Search/SolrAuth/Results.php | PHP | gpl-2.0 | 1,686 |
/*
* 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 opennlp.tools.doccat;
import java.util.Collection;
import java.util.LinkedList;
import java.util.Map;
/**
* Context generator for document categorizer
*/
class DocumentCategorizerContextGenerator {
private FeatureGenerator[] mFeatureGenerators;
DocumentCategorizerContextGenerator(FeatureGenerator... featureGenerators) {
mFeatureGenerators = featureGenerators;
}
public String[] getContext(String[] text, Map<String, Object> extraInformation) {
Collection<String> context = new LinkedList<>();
for (FeatureGenerator mFeatureGenerator : mFeatureGenerators) {
Collection<String> extractedFeatures =
mFeatureGenerator.extractFeatures(text, extraInformation);
context.addAll(extractedFeatures);
}
return context.toArray(new String[context.size()]);
}
}
| manjeetk09/GoogleScrapper | opennlp/tools/doccat/DocumentCategorizerContextGenerator.java | Java | gpl-2.0 | 1,622 |
using System;
using System.Collections;
namespace FSpot {
public class DirectoryAdaptor : GroupAdaptor {
System.Collections.DictionaryEntry [] dirs;
// FIXME store the Photo.Id list here not just the count
private class Group : IComparer {
public int Count = 1;
public int Compare (object obj1, object obj2)
{
// FIXME use a real exception
if (obj1 is DictionaryEntry && obj2 is DictionaryEntry)
return Compare ((DictionaryEntry)obj1, (DictionaryEntry)obj2);
else
throw new Exception ("I can't compare that");
}
private static int Compare (DictionaryEntry de1, DictionaryEntry de2)
{
return string.Compare ((string)de1.Key, (string)de2.Key);
}
}
public override event GlassSetHandler GlassSet;
public override void SetGlass (int group)
{
if (group < 0 || group > dirs.Length)
return;
Console.WriteLine ("Selected Path {0}", dirs [group].Key);
int item = LookupItem (group);
if (GlassSet != null)
GlassSet (this, item);
}
public override int Count ()
{
return dirs.Length;
}
public override string GlassLabel (int item)
{
return (string)dirs [item].Key;
}
public override string TickLabel (int item)
{
return null;
}
public override int Value (int item)
{
return ((DirectoryAdaptor.Group)dirs [item].Value).Count;
}
public override event ChangedHandler Changed;
protected override void Reload ()
{
System.Collections.Hashtable ht = new System.Collections.Hashtable ();
Photo [] photos = query.Store.Query ((Tag [])null, null, null, null);
foreach (Photo p in photos) {
if (ht.Contains (p.DirectoryPath)) {
DirectoryAdaptor.Group group = (DirectoryAdaptor.Group) ht [p.DirectoryPath];
group.Count += 1;
} else
ht [p.DirectoryPath] = new DirectoryAdaptor.Group ();
}
Console.WriteLine ("Count = {0}", ht.Count);
dirs = new System.Collections.DictionaryEntry [ht.Count];
ht.CopyTo (dirs, 0);
Array.Sort (dirs, new DirectoryAdaptor.Group ());
Array.Sort (query.Photos, new Photo.CompareDirectory ());
if (!order_ascending) {
Array.Reverse (dirs);
Array.Reverse (query.Photos);
}
if (Changed != null)
Changed (this);
}
public override int IndexFromPhoto(FSpot.IBrowsableItem item)
{
Photo photo = (Photo)item;
string directory_path = photo.DirectoryPath;
for (int i = 0; i < dirs.Length; i++) {
if ((string)dirs [i].Key == directory_path) {
return i;
}
}
// FIXME not truly implemented
return 0;
}
public override FSpot.IBrowsableItem PhotoFromIndex (int item)
{
return query.Items [LookupItem (item)];
}
private int LookupItem (int group)
{
int i = 0;
while (i < query.Count) {
if (((Photo)(query [i])).DirectoryPath == (string)dirs [group].Key) {
return i;
}
i++;
}
return 0;
}
public DirectoryAdaptor (PhotoQuery query)
: base (query)
{ }
}
}
| Hibary/facedetect-f-spot | src/DirectoryAdaptor.cs | C# | gpl-2.0 | 2,996 |
/*
* Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.crypto;
import java.io.*;
/**
* A CipherOutputStream is composed of an OutputStream and a Cipher so
* that write() methods first process the data before writing them out
* to the underlying OutputStream. The cipher must be fully
* initialized before being used by a CipherOutputStream.
*
* <p> For example, if the cipher is initialized for encryption, the
* CipherOutputStream will attempt to encrypt data before writing out the
* encrypted data.
*
* <p> This class adheres strictly to the semantics, especially the
* failure semantics, of its ancestor classes
* java.io.OutputStream and java.io.FilterOutputStream. This class
* has exactly those methods specified in its ancestor classes, and
* overrides them all. Moreover, this class catches all exceptions
* that are not thrown by its ancestor classes. In particular, this
* class catches BadPaddingException and other exceptions thrown by
* failed integrity checks during decryption. These exceptions are not
* re-thrown, so the client will not be informed that integrity checks
* failed. Because of this behavior, this class may not be suitable
* for use with decryption in an authenticated mode of operation (e.g. GCM)
* if the application requires explicit notification when authentication
* fails. Such an application can use the Cipher API directly as an
* alternative to using this class.
*
* <p> It is crucial for a programmer using this class not to use
* methods that are not defined or overriden in this class (such as a
* new method or constructor that is later added to one of the super
* classes), because the design and implementation of those methods
* are unlikely to have considered security impact with regard to
* CipherOutputStream.
*
* @author Li Gong
* @see java.io.OutputStream
* @see java.io.FilterOutputStream
* @see javax.crypto.Cipher
* @see javax.crypto.CipherInputStream
*
* @since 1.4
*/
public class CipherOutputStream extends FilterOutputStream {
// the cipher engine to use to process stream data
private Cipher cipher;
// the underlying output stream
private OutputStream output;
/* the buffer holding one byte of incoming data */
private byte[] ibuffer = new byte[1];
// the buffer holding data ready to be written out
private byte[] obuffer;
// stream status
private boolean closed = false;
/**
*
* Constructs a CipherOutputStream from an OutputStream and a
* Cipher.
* <br>Note: if the specified output stream or cipher is
* null, a NullPointerException may be thrown later when
* they are used.
*
* @param os the OutputStream object
* @param c an initialized Cipher object
*/
public CipherOutputStream(OutputStream os, Cipher c) {
super(os);
output = os;
cipher = c;
};
/**
* Constructs a CipherOutputStream from an OutputStream without
* specifying a Cipher. This has the effect of constructing a
* CipherOutputStream using a NullCipher.
* <br>Note: if the specified output stream is null, a
* NullPointerException may be thrown later when it is used.
*
* @param os the OutputStream object
*/
protected CipherOutputStream(OutputStream os) {
super(os);
output = os;
cipher = new NullCipher();
}
/**
* Writes the specified byte to this output stream.
*
* @param b the <code>byte</code>.
* @exception IOException if an I/O error occurs.
* @since JCE1.2
*/
public void write(int b) throws IOException {
ibuffer[0] = (byte) b;
obuffer = cipher.update(ibuffer, 0, 1);
if (obuffer != null) {
output.write(obuffer);
obuffer = null;
}
};
/**
* Writes <code>b.length</code> bytes from the specified byte array
* to this output stream.
* <p>
* The <code>write</code> method of
* <code>CipherOutputStream</code> calls the <code>write</code>
* method of three arguments with the three arguments
* <code>b</code>, <code>0</code>, and <code>b.length</code>.
*
* @param b the data.
* @exception NullPointerException if <code>b</code> is null.
* @exception IOException if an I/O error occurs.
* @see javax.crypto.CipherOutputStream#write(byte[], int, int)
* @since JCE1.2
*/
public void write(byte b[]) throws IOException {
write(b, 0, b.length);
}
/**
* Writes <code>len</code> bytes from the specified byte array
* starting at offset <code>off</code> to this output stream.
*
* @param b the data.
* @param off the start offset in the data.
* @param len the number of bytes to write.
* @exception IOException if an I/O error occurs.
* @since JCE1.2
*/
public void write(byte b[], int off, int len) throws IOException {
obuffer = cipher.update(b, off, len);
if (obuffer != null) {
output.write(obuffer);
obuffer = null;
}
}
/**
* Flushes this output stream by forcing any buffered output bytes
* that have already been processed by the encapsulated cipher object
* to be written out.
*
* <p>Any bytes buffered by the encapsulated cipher
* and waiting to be processed by it will not be written out. For example,
* if the encapsulated cipher is a block cipher, and the total number of
* bytes written using one of the <code>write</code> methods is less than
* the cipher's block size, no bytes will be written out.
*
* @exception IOException if an I/O error occurs.
* @since JCE1.2
*/
public void flush() throws IOException {
if (obuffer != null) {
output.write(obuffer);
obuffer = null;
}
output.flush();
}
/**
* Closes this output stream and releases any system resources
* associated with this stream.
* <p>
* This method invokes the <code>doFinal</code> method of the encapsulated
* cipher object, which causes any bytes buffered by the encapsulated
* cipher to be processed. The result is written out by calling the
* <code>flush</code> method of this output stream.
* <p>
* This method resets the encapsulated cipher object to its initial state
* and calls the <code>close</code> method of the underlying output
* stream.
*
* @exception IOException if an I/O error occurs.
* @since JCE1.2
*/
public void close() throws IOException {
if (closed) {
return;
}
closed = true;
try {
obuffer = cipher.doFinal();
} catch (IllegalBlockSizeException | BadPaddingException e) {
obuffer = null;
}
try {
flush();
} catch (IOException ignored) {}
out.close();
}
}
| JetBrains/jdk8u_jdk | src/share/classes/javax/crypto/CipherOutputStream.java | Java | gpl-2.0 | 8,241 |
/*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
import 'bootstrap';
import $ from 'jquery';
import {AjaxResponse} from 'TYPO3/CMS/Core/Ajax/AjaxResponse';
import {AbstractInteractableModule} from '../AbstractInteractableModule';
import Modal = require('TYPO3/CMS/Backend/Modal');
import Notification = require('TYPO3/CMS/Backend/Notification');
import AjaxRequest = require('TYPO3/CMS/Core/Ajax/AjaxRequest');
import InfoBox = require('../../Renderable/InfoBox');
import ProgressBar = require('../../Renderable/ProgressBar');
import Severity = require('../../Renderable/Severity');
import Router = require('../../Router');
/**
* Module: TYPO3/CMS/Install/EnvironmentCheck
*/
class EnvironmentCheck extends AbstractInteractableModule {
private selectorGridderBadge: string = '.t3js-environmentCheck-badge';
private selectorExecuteTrigger: string = '.t3js-environmentCheck-execute';
private selectorOutputContainer: string = '.t3js-environmentCheck-output';
public initialize(currentModal: JQuery): void {
this.currentModal = currentModal;
// Get status on initialize to have the badge and content ready
this.runTests();
currentModal.on('click', this.selectorExecuteTrigger, (e: JQueryEventObject): void => {
e.preventDefault();
this.runTests();
});
}
private runTests(): void {
this.setModalButtonsState(false);
const modalContent = this.getModalBody();
const $errorBadge = $(this.selectorGridderBadge);
$errorBadge.text('').hide();
const message = ProgressBar.render(Severity.loading, 'Loading...', '');
modalContent.find(this.selectorOutputContainer).empty().append(message);
(new AjaxRequest(Router.getUrl('environmentCheckGetStatus')))
.get({cache: 'no-cache'})
.then(
async (response: AjaxResponse): Promise<any> => {
const data = await response.resolve();
modalContent.empty().append(data.html);
Modal.setButtons(data.buttons);
let warningCount = 0;
let errorCount = 0;
if (data.success === true && typeof (data.status) === 'object') {
$.each(data.status, (i: number, element: any): void => {
if (Array.isArray(element) && element.length > 0) {
element.forEach((aStatus: any): void => {
if (aStatus.severity === 1) {
warningCount++;
}
if (aStatus.severity === 2) {
errorCount++;
}
const aMessage = InfoBox.render(aStatus.severity, aStatus.title, aStatus.message);
modalContent.find(this.selectorOutputContainer).append(aMessage);
});
}
});
if (errorCount > 0) {
$errorBadge.removeClass('label-warning').addClass('label-danger').text(errorCount).show();
} else if (warningCount > 0) {
$errorBadge.removeClass('label-error').addClass('label-warning').text(warningCount).show();
}
} else {
Notification.error('Something went wrong', 'The request was not processed successfully. Please check the browser\'s console and TYPO3\'s log.');
}
},
(error: AjaxResponse): void => {
Router.handleAjaxError(error, modalContent);
}
);
}
}
export = new EnvironmentCheck();
| maddy2101/TYPO3.CMS | Build/Sources/TypeScript/install/Resources/Public/TypeScript/Module/Environment/EnvironmentCheck.ts | TypeScript | gpl-2.0 | 3,768 |
<?php
/*
HLstatsX Community Edition - Real-time player and clan rankings and statistics
Copyleft (L) 2008-20XX Nicholas Hastings (nshastings@gmail.com)
http://www.hlxcommunity.com
HLstatsX Community Edition is a continuation of
ELstatsNEO - Real-time player and clan rankings and statistics
Copyleft (L) 2008-20XX Malte Bayer (steam@neo-soft.org)
http://ovrsized.neo-soft.org/
ELstatsNEO is an very improved & enhanced - so called Ultra-Humongus Edition of HLstatsX
HLstatsX - Real-time player and clan rankings and statistics for Half-Life 2
http://www.hlstatsx.com/
Copyright (C) 2005-2007 Tobias Oetzel (Tobi@hlstatsx.com)
HLstatsX is an enhanced version of HLstats made by Simon Garner
HLstats - Real-time player and clan rankings and statistics for Half-Life
http://sourceforge.net/projects/hlstats/
Copyright (C) 2001 Simon Garner
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
For support and installation notes visit http://www.hlxcommunity.com
*/
if ( !defined('IN_HLSTATS') )
{
die('Do not access this file directly.');
}
flush();
$tblTeams = new Table
(
array
(
new TableColumn
(
'name',
'Team',
'width=35'
),
new TableColumn
(
'teamcount',
'Joined',
'width=10&align=right&append=+times'
),
new TableColumn
(
'percent',
'%',
'width=10&sort=no&align=right&append=' . urlencode('%')
),
new TableColumn
(
'percent',
'Ratio',
'width=40&sort=no&type=bargraph'
)
),
'name',
'teamcount',
'name',
true,
9999,
'teams_page',
'teams_sort',
'teams_sortorder',
'tabteams',
'desc',
true
);
$db->query
("
SELECT
COUNT(*)
FROM
hlstats_Events_ChangeTeam
WHERE
hlstats_Events_ChangeTeam.playerId = $player
");
list($numteamjoins) = $db->fetch_row();
if($numteamjoins == 0) {
$numteamjoins = 1;
}
$result = $db->query
("
SELECT
IFNULL(hlstats_Teams.name, hlstats_Events_ChangeTeam.team) AS name,
COUNT(hlstats_Events_ChangeTeam.id) AS teamcount,
ROUND((COUNT(hlstats_Events_ChangeTeam.id) / $numteamjoins) * 100, 2) AS percent
FROM
hlstats_Events_ChangeTeam
LEFT JOIN
hlstats_Teams
ON
hlstats_Events_ChangeTeam.team = hlstats_Teams.code
WHERE
hlstats_Teams.game = '$game'
AND hlstats_Events_ChangeTeam.playerId = $player
AND
(
hidden <> '1'
OR hidden IS NULL
)
GROUP BY
hlstats_Events_ChangeTeam.team
ORDER BY
$tblTeams->sort $tblTeams->sortorder,
$tblTeams->sort2 $tblTeams->sortorder
");
$numitems = $db->num_rows($result);
if ($numitems > 0)
{
printSectionTitle('Team Selection *');
$tblTeams->draw($result, $numitems, 95);
?>
<br /><br />
<?php
}
flush();
$result = $db->query
("
SELECT
hlstats_Roles.code,
hlstats_Roles.name
FROM
hlstats_Roles
WHERE
hlstats_Roles.game = '$game'
");
while ($rowdata = $db->fetch_row($result))
{
$code = preg_replace("/[ \r\n\t]+/", "", $rowdata[0]);
$fname[strToLower($code)] = htmlspecialchars($rowdata[1]);
}
$tblRoles = new Table
(
array
(
new TableColumn
(
'code',
'Role',
'width=25&type=roleimg&align=left&link=' . urlencode("mode=rolesinfo&role=%k&game=$game"),
$fname
),
new TableColumn
(
'rolecount',
'Joined',
'width=10&align=right&append=+times'
),
new TableColumn
(
'percent',
'%',
'width=10&sort=no&align=right&append=' . urlencode('%')
),
new TableColumn
(
'percent',
'Ratio',
'width=20&sort=no&type=bargraph'
),
new TableColumn
(
'killsTotal',
'Kills',
'width=10&align=right'
),
new TableColumn
(
'deathsTotal',
'Deaths',
'width=10&align=right'
),
new TableColumn
(
'kpd',
'K:D',
'width=10&align=right'
)
),
'code',
'rolecount',
'name',
true,
9999,
'roles_page',
'roles_sort',
'roles_sortorder',
'roles',
'desc',
true
);
$db->query
("
DROP TABLE IF EXISTS
hlstats_Frags_as
");
$db->query
("
CREATE TEMPORARY TABLE
hlstats_Frags_as
(
playerId INT(10),
kills INT(10),
deaths INT(10),
role varchar(128) NOT NULL default ''
)
");
$db->query
("
INSERT INTO
hlstats_Frags_as
(
playerId,
kills,
role
)
SELECT
hlstats_Events_Frags.victimId,
hlstats_Events_Frags.killerId,
hlstats_Events_Frags.killerRole
FROM
hlstats_Events_Frags
WHERE
hlstats_Events_Frags.killerId = $player
");
$db->query
("
INSERT INTO
hlstats_Frags_as
(
playerId,
deaths,
role
)
SELECT
hlstats_Events_Frags.killerId,
hlstats_Events_Frags.victimId,
hlstats_Events_Frags.victimRole
FROM
hlstats_Events_Frags
WHERE
hlstats_Events_Frags.victimId = $player
");
$db->query
("
DROP TABLE IF EXISTS
hlstats_Frags_as_res
");
$db->query
("
CREATE TEMPORARY TABLE
hlstats_Frags_as_res
(
killsTotal INT(10),
deathsTotal INT(10),
role varchar(128) NOT NULL default ''
)
");
$db->query
("
INSERT INTO
hlstats_Frags_as_res
(
killsTotal,
deathsTotal,
role
)
SELECT
COUNT(hlstats_Frags_as.kills) AS kills,
COUNT(hlstats_Frags_as.deaths) AS deaths,
hlstats_Frags_as.role
FROM
hlstats_Frags_as
GROUP BY
hlstats_Frags_as.role
");
$db->query
("
SELECT
COUNT(*)
FROM
hlstats_Events_ChangeRole
WHERE
hlstats_Events_ChangeRole.playerId = $player
");
list($numrolejoins) = $db->fetch_row();
$result = $db->query
("
SELECT
IFNULL(hlstats_Roles.name, hlstats_Events_ChangeRole.role) AS name,
IFNULL(hlstats_Roles.code, hlstats_Events_ChangeRole.role) AS code,
COUNT(hlstats_Events_ChangeRole.id) AS rolecount,
ROUND(COUNT(hlstats_Events_ChangeRole.id) / IF($numrolejoins = 0, 1, $numrolejoins) * 100, 2) AS percent,
hlstats_Frags_as_res.killsTotal,
hlstats_Frags_as_res.deathsTotal,
ROUND(hlstats_Frags_as_res.killsTotal / IF(hlstats_Frags_as_res.deathsTotal = 0, 1, hlstats_Frags_as_res.deathsTotal), 2) AS kpd
FROM
hlstats_Events_ChangeRole
LEFT JOIN
hlstats_Roles
ON
hlstats_Events_ChangeRole.role = hlstats_Roles.code
LEFT JOIN
hlstats_Frags_as_res
ON
hlstats_Frags_as_res.role = hlstats_Events_ChangeRole.role
WHERE
hlstats_Events_ChangeRole.playerId = $player
AND
(
hidden <> '1'
OR hidden IS NULL
)
AND hlstats_Roles.game = '$game'
GROUP BY
hlstats_Events_ChangeRole.role
ORDER BY
$tblRoles->sort $tblRoles->sortorder,
$tblRoles->sort2 $tblRoles->sortorder
");
$numitems = $db->num_rows($result);
if ($numitems > 0)
{
printSectionTitle('Role Selection *');
$tblRoles->draw($result, $numitems, 95);
?>
<br /><br />
<?php
}
?>
| rcguy/insurgency-hlstatsx | web/pages/playerinfo_teams.php | PHP | gpl-2.0 | 7,693 |
#include "async.h"
class my_resizer_t : public vec_resizer_t {
public:
my_resizer_t () : vec_resizer_t () {}
size_t resize (u_int nalloc, u_int nwanted, int objid);
};
size_t
my_resizer_t::resize (u_int nalloc, u_int nwanted, int objid)
{
int exponent = fls (max (nalloc, nwanted));
int step;
if (exponent < 3) step = 1;
else if (exponent < 8) step = 3;
else if (exponent < 10) step = 2;
else step = 1;
exponent = ((exponent - 1) / step + 1) * step;
size_t ret = 1 << exponent;
// If you want to know the pattern...
warn << "resize: " << nalloc << "," << nwanted << "," << objid
<< " -> " << ret << "\n";
return ret;
}
template<>
struct vec_obj_id_t<int>
{
vec_obj_id_t (){}
int operator() (void) const { return 1; }
};
static void
vec_test (vec<int> &v, int n)
{
for (int i = 0; i < n; i++) {
v.push_back (i);
}
for (int i = n - 1; i >= 0; i--) {
assert (v.pop_back () == i);
}
}
static void
vec_test (void)
{
vec<int> v1, v2;
int n = 100;
vec_test (v1, n);
set_vec_resizer (New my_resizer_t ());
vec_test (v2, n);
}
int
main (int argc, char *argv[])
{
vec_test ();
return 0;
}
| okws/sfslite | tests/test_vec.C | C++ | gpl-2.0 | 1,161 |
/*
Implement Github like autocomplete mentions
http://ichord.github.com/At.js
Copyright (c) 2013 chord.luo@gmail.com
Licensed under the MIT license.
*/
/*
本插件操作 textarea 或者 input 内的插入符
只实现了获得插入符在文本框中的位置,我设置
插入符的位置.
*/
/**
* --------------------
* Vanilla Forums NOTE:
* --------------------
*
* This file has been highly modified to work with iframes, as well
* as custom username handling with quotation marks and spaces for Vanilla.
* Do not just replace with a more current version. At the time of
* development there was no support for iframes, or spaces in names.
* This may have changed, so if you do decide to upgrade this library,
* you're going to have to update the code that uses this library as well.
* It's all wrapped up in a function called `atCompleteInit`.
*/
(function() {
(function(factory) {
if (typeof define === 'function' && define.amd) {
return define(['jquery'], factory);
} else {
return factory(window.jQuery);
}
})(function($) {
"use strict";
////var EditableCaret, InputCaret, Mirror, Utils, methods, pluginName;
var EditableCaret, InputCaret, Mirror, Utils, methods, pluginName, cWin;
pluginName = 'caret';
EditableCaret = (function() {
function EditableCaret($inputor) {
this.$inputor = $inputor;
this.domInputor = this.$inputor[0];
}
EditableCaret.prototype.setPos = function(pos) {
return this.domInputor;
};
EditableCaret.prototype.getIEPosition = function() {
return $.noop();
};
EditableCaret.prototype.getPosition = function() {
return $.noop();
};
EditableCaret.prototype.getOldIEPos = function() {
var preCaretTextRange, textRange;
textRange = document.selection.createRange();
preCaretTextRange = document.body.createTextRange();
preCaretTextRange.moveToElementText(this.domInputor);
preCaretTextRange.setEndPoint("EndToEnd", textRange);
return preCaretTextRange.text.length;
};
EditableCaret.prototype.getPos = function() {
var clonedRange, pos, range;
if (range = this.range()) {
clonedRange = range.cloneRange();
clonedRange.selectNodeContents(this.domInputor);
clonedRange.setEnd(range.endContainer, range.endOffset);
pos = clonedRange.toString().length;
clonedRange.detach();
return pos;
} else if (document.selection) {
return this.getOldIEPos();
}
};
EditableCaret.prototype.getOldIEOffset = function() {
var range, rect;
range = document.selection.createRange().duplicate();
range.moveStart("character", -1);
rect = range.getBoundingClientRect();
return {
height: rect.bottom - rect.top,
left: rect.left,
top: rect.top
};
};
EditableCaret.prototype.getOffset = function(pos) {
var clonedRange, offset, range, rect;
offset = null;
////if (window.getSelection && (range = this.range())) {
if (cWin.getSelection && (range = this.range())) {
if (range.endOffset - 1 < 0) {
return null;
}
clonedRange = range.cloneRange();
clonedRange.setStart(range.endContainer, range.endOffset - 1);
clonedRange.setEnd(range.endContainer, range.endOffset);
rect = clonedRange.getBoundingClientRect();
offset = {
height: rect.height,
left: rect.left + rect.width,
top: rect.top
};
clonedRange.detach();
offset;
} else if (document.selection) {
this.getOldIEOffset();
}
return Utils.adjustOffset(offset, this.$inputor);
};
EditableCaret.prototype.range = function() {
var sel;
////if (!window.getSelection) {
if (!cWin.getSelection) {
return;
}
////sel = window.getSelection();
sel = cWin.getSelection();
if (sel.rangeCount > 0) {
return sel.getRangeAt(0);
} else {
return null;
}
};
return EditableCaret;
})();
InputCaret = (function() {
function InputCaret($inputor) {
this.$inputor = $inputor;
this.domInputor = this.$inputor[0];
}
InputCaret.prototype.getIEPos = function() {
var endRange, inputor, len, normalizedValue, pos, range, textInputRange;
inputor = this.domInputor;
range = document.selection.createRange();
pos = 0;
if (range && range.parentElement() === inputor) {
normalizedValue = inputor.value.replace(/\r\n/g, "\n");
len = normalizedValue.length;
textInputRange = inputor.createTextRange();
textInputRange.moveToBookmark(range.getBookmark());
endRange = inputor.createTextRange();
endRange.collapse(false);
if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) {
pos = len;
} else {
pos = -textInputRange.moveStart("character", -len);
}
}
return pos;
};
InputCaret.prototype.getPos = function() {
if (document.selection) {
return this.getIEPos();
} else {
return this.domInputor.selectionStart;
}
};
InputCaret.prototype.setPos = function(pos) {
var inputor, range;
inputor = this.domInputor;
if (document.selection) {
range = inputor.createTextRange();
range.move("character", pos);
range.select();
} else if (inputor.setSelectionRange) {
inputor.setSelectionRange(pos, pos);
}
return inputor;
};
InputCaret.prototype.getIEOffset = function(pos) {
var h, range, textRange, x, y;
textRange = this.domInputor.createTextRange();
if (pos) {
textRange.move('character', pos);
} else {
range = document.selection.createRange();
textRange.moveToBookmark(range.getBookmark());
}
x = textRange.boundingLeft;
y = textRange.boundingTop;
h = textRange.boundingHeight;
return {
left: x,
top: y,
height: h
};
};
InputCaret.prototype.getOffset = function(pos) {
var $inputor, offset, position;
$inputor = this.$inputor;
if (document.selection) {
return Utils.adjustOffset(this.getIEOffset(pos), $inputor);
} else {
offset = $inputor.offset();
position = this.getPosition(pos);
return offset = {
left: offset.left + position.left,
top: offset.top + position.top,
height: position.height
};
}
};
InputCaret.prototype.getPosition = function(pos) {
var $inputor, at_rect, format, html, mirror, start_range;
$inputor = this.$inputor;
format = function(value) {
return value.replace(/</g, '<').replace(/>/g, '>').replace(/`/g, '`').replace(/"/g, '"').replace(/\r\n|\r|\n/g, "<br />");
};
if (pos === void 0) {
pos = this.getPos();
}
start_range = $inputor.val().slice(0, pos);
html = "<span>" + format(start_range) + "</span>";
html += "<span id='caret'>|</span>";
mirror = new Mirror($inputor);
return at_rect = mirror.create(html).rect();
};
InputCaret.prototype.getIEPosition = function(pos) {
var h, inputorOffset, offset, x, y;
offset = this.getIEOffset(pos);
inputorOffset = this.$inputor.offset();
x = offset.left - inputorOffset.left;
y = offset.top - inputorOffset.top;
h = offset.height;
return {
left: x,
top: y,
height: h
};
};
return InputCaret;
})();
Mirror = (function() {
Mirror.prototype.css_attr = ["overflowY", "height", "width", "paddingTop", "paddingLeft", "paddingRight", "paddingBottom", "marginTop", "marginLeft", "marginRight", "marginBottom", "fontFamily", "borderStyle", "borderWidth", "wordWrap", "fontSize", "lineHeight", "overflowX", "text-align"];
function Mirror($inputor) {
this.$inputor = $inputor;
}
Mirror.prototype.mirrorCss = function() {
var css,
_this = this;
css = {
position: 'absolute',
left: -9999,
top: 0,
zIndex: -20000,
'white-space': 'pre-wrap'
};
$.each(this.css_attr, function(i, p) {
return css[p] = _this.$inputor.css(p);
});
return css;
};
Mirror.prototype.create = function(html) {
this.$mirror = $('<div></div>');
this.$mirror.css(this.mirrorCss());
this.$mirror.html(html);
this.$inputor.after(this.$mirror);
return this;
};
Mirror.prototype.rect = function() {
var $flag, pos, rect;
$flag = this.$mirror.find("#caret");
pos = $flag.position();
rect = {
left: pos.left,
top: pos.top,
height: $flag.height()
};
this.$mirror.remove();
return rect;
};
return Mirror;
})();
Utils = {
adjustOffset: function(offset, $inputor) {
if (!offset) {
return;
}
offset.top += $(window).scrollTop() + $inputor.scrollTop();
offset.left += +$(window).scrollLeft() + $inputor.scrollLeft();
return offset;
},
contentEditable: function($inputor) {
return !!($inputor[0].contentEditable && $inputor[0].contentEditable === 'true');
}
};
methods = {
pos: function(pos) {
if (pos) {
return this.setPos(pos);
} else {
return this.getPos();
}
},
position: function(pos) {
if (document.selection) {
return this.getIEPosition(pos);
} else {
return this.getPosition(pos);
}
},
offset: function(pos) {
return this.getOffset(pos);
}
};
////$.fn.caret = function(method) {
$.fn.caret = function(method, aWin) {
var caret;
////
cWin = aWin;
caret = Utils.contentEditable(this) ? new EditableCaret(this) : new InputCaret(this);
if (methods[method]) {
////return methods[method].apply(caret, Array.prototype.slice.call(arguments, 1));
///////return methods[method].apply(caret, Array.prototype.slice.call(arguments, method == 'pos' ? 2 : 1));
return methods[method].apply(caret, Array.prototype.slice.call(arguments, 2));
} else {
return $.error("Method " + method + " does not exist on jQuery.caret");
}
};
$.fn.caret.EditableCaret = EditableCaret;
$.fn.caret.InputCaret = InputCaret;
$.fn.caret.Utils = Utils;
return $.fn.caret.apis = methods;
});
}).call(this);
/*
Implement Github like autocomplete mentions
http://ichord.github.com/At.js
Copyright (c) 2013 chord.luo@gmail.com
Licensed under the MIT license.
*/
(function() {
var __slice = [].slice;
(function(factory) {
if (typeof define === 'function' && define.amd) {
return define(['jquery'], factory);
} else {
return factory(window.jQuery);
}
})(function($) {
var $CONTAINER, Api, App, Atwho, Controller, DEFAULT_CALLBACKS, KEY_CODE, Model, View;
App = (function() {
function App(inputor) {
this.current_flag = null;
this.controllers = {};
this.$inputor = $(inputor);
this.listen();
}
App.prototype.controller = function(at) {
return this.controllers[at || this.current_flag];
};
App.prototype.set_context_for = function(at) {
this.current_flag = at;
return this;
};
App.prototype.reg = function(flag, setting) {
var controller, _base;
controller = (_base = this.controllers)[flag] || (_base[flag] = new Controller(this, flag));
if (setting.alias) {
this.controllers[setting.alias] = controller;
}
controller.init(setting);
return this;
};
App.prototype.listen = function() {
var _this = this;
return this.$inputor.on('keyup.atwho', function(e) {
return _this.on_keyup(e);
}).on('keydown.atwho', function(e) {
return _this.on_keydown(e);
}).on('scroll.atwho', function(e) {
var _ref;
return (_ref = _this.controller()) != null ? _ref.view.hide() : void 0;
}).on('blur.atwho', function(e) {
var c;
if (c = _this.controller()) {
return c.view.hide(c.get_opt("display_timeout"));
}
});
};
App.prototype.dispatch = function() {
var _this = this;
return $.map(this.controllers, function(c) {
if (c.look_up()) {
return _this.set_context_for(c.at);
}
});
};
App.prototype.on_keyup = function(e) {
var _ref;
switch (e.keyCode) {
case KEY_CODE.ESC:
case KEY_CODE.TAB:
case KEY_CODE.ENTER:
e.preventDefault();
if ((_ref = this.controller()) != null) {
_ref.view.hide();
}
break;
case KEY_CODE.DOWN:
case KEY_CODE.UP:
$.noop();
break;
default:
this.dispatch();
}
};
App.prototype.on_keydown = function(e) {
var view, _ref;
view = (_ref = this.controller()) != null ? _ref.view : void 0;
if (!(view && view.visible())) {
return;
}
switch (e.keyCode) {
case KEY_CODE.ESC:
e.preventDefault();
view.hide();
break;
case KEY_CODE.UP:
e.preventDefault();
view.prev();
break;
case KEY_CODE.DOWN:
e.preventDefault();
view.next();
break;
case KEY_CODE.TAB:
case KEY_CODE.ENTER:
if (!view.visible()) {
return;
}
view.choose(e);
break;
default:
$.noop();
}
};
return App;
})();
Controller = (function() {
var uuid, _uuid;
_uuid = 0;
uuid = function() {
return _uuid += 1;
};
function Controller(app, at) {
this.app = app;
this.at = at;
this.$inputor = this.app.$inputor;
this.id = this.$inputor[0].id || uuid();
this.setting = null;
this.query = null;
this.pos = 0;
this.cur_rect = null;
this.range = null;
$CONTAINER.append(this.$el = $("<div id='atwho-ground-" + this.id + "'></div>"));
this.model = new Model(this);
this.view = new View(this);
}
Controller.prototype.init = function(setting) {
this.setting = $.extend({}, this.setting || $.fn.atwho["default"], setting);
this.view.init();
return this.model.reload(this.setting.data);
};
Controller.prototype.call_default = function() {
var args, func_name;
func_name = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
try {
return DEFAULT_CALLBACKS[func_name].apply(this, args);
} catch (error) {
return $.error("" + error + " Or maybe At.js doesn't have function " + func_name);
}
};
Controller.prototype.trigger = function(name, data) {
var alias, event_name;
data.push(this);
alias = this.get_opt('alias');
event_name = alias ? "" + name + "-" + alias + ".atwho" : "" + name + ".atwho";
return this.$inputor.trigger(event_name, data);
};
Controller.prototype.callbacks = function(func_name) {
return this.get_opt("callbacks")[func_name] || DEFAULT_CALLBACKS[func_name];
};
Controller.prototype.get_opt = function(at, default_value) {
try {
return this.setting[at];
} catch (e) {
return null;
}
};
Controller.prototype.content = function() {
var result = {
content: null,
offset: 0
};
if (this.$inputor.is('textarea, input')) {
result.content = this.$inputor.val();
} else {
var textNode = $(document.createElement('div'));
var html = this.$inputor.html();
var breaks = /<br(\s+)?(\/)?>/g;
result.offset = html.match(breaks) ? html.match(breaks).length : 0;
textNode.html(html.replace(breaks, "\n"));
result.content = textNode.text();
}
return result;
};
Controller.prototype.catch_query = function() {
var caret_pos, contents, end, query, start, subtext;
contents = this.content();
////caret_pos = this.$inputor.caret('pos');
caret_pos = this.$inputor.caret('pos', this.setting.cWindow) + contents.offset;
subtext = contents.content.slice(0, caret_pos);
query = this.callbacks("matcher").call(this, this.at, subtext, this.get_opt('start_with_space'));
if (typeof query === "string" && query.length <= this.get_opt('max_len', 20)) {
start = caret_pos - query.length;
end = start + query.length;
this.pos = start;
query = {
'text': query.toLowerCase(),
'head_pos': start,
'end_pos': end
};
this.trigger("matched", [this.at, query.text]);
} else {
this.view.hide();
}
return this.query = query;
};
Controller.prototype.rect = function() {
var c, scale_bottom;
/////if (!(c = this.$inputor.caret('offset', this.pos - 1))) {
if (!(c = this.$inputor.caret('offset', this.setting.cWindow, this.pos - 1))) {
return;
}
if (this.$inputor.attr('contentEditable') === 'true') {
c = (this.cur_rect || (this.cur_rect = c)) || c;
}
scale_bottom = document.selection ? 0 : 2;
return {
left: c.left,
top: c.top,
bottom: c.top + c.height + scale_bottom
};
};
Controller.prototype.reset_rect = function() {
if (this.$inputor.attr('contentEditable') === 'true') {
return this.cur_rect = null;
}
};
Controller.prototype.mark_range = function() {
return this.range = this.get_range() || this.get_ie_range();
};
Controller.prototype.clear_range = function() {
return this.range = null;
};
Controller.prototype.get_range = function() {
////return this.range || (window.getSelection ? window.getSelection().getRangeAt(0) : void 0);
var thisWin = this.setting.cWindow;
//////return this.range || (thisWin.getSelection ? thisWin.getSelection().getRangeAt(0) : void 0);
return thisWin.getSelection ? thisWin.getSelection().getRangeAt(0) : (this.range || void 0);
};
Controller.prototype.get_ie_range = function() {
return this.range || (document.selection ? document.selection.createRange() : void 0);
};
Controller.prototype.insert_content_for = function($li) {
var data, data_value, tpl;
data_value = $li.data('value');
tpl = this.get_opt('insert_tpl');
if (this.$inputor.is('textarea, input') || !tpl) {
return data_value;
}
data = $.extend({}, $li.data('item-data'), {
'atwho-data-value': data_value,
'atwho-at': this.at
});
return this.callbacks("tpl_eval").call(this, tpl, data);
};
Controller.prototype.insert = function(content, $li) {
////var $inputor, $insert_node, class_name, content_node, insert_node, pos, range, sel, source, start_str, text;
//////////var $inputor, $insert_node, class_name, content_node, insert_node, pos, range, sel, source, start_str, text, thisWin;
var $inputor, $insert_node, class_name, content_editable, content_node, insert_node, pos, range, sel, source, start_str, text;
$inputor = this.$inputor;
if ($inputor.attr('contentEditable') === 'true') {
//////////
content_editable = '' + /firefox/i.test(navigator.userAgent);
//class_name = "atwho-view-flag atwho-view-flag-" + (this.get_opt('alias') || this.at);
class_name = "vanilla-mention-" + (this.get_opt('alias') || this.at);
//////////content_node = "" + content + "<span contenteditable='false'> <span>";
//////////insert_node = "<span contenteditable='false' class='" + class_name + "'>" + content_node + "</span>";
//content_node = ("" + content + "<span contenteditable='") + content_editable + "'> <span>";
content_node = "" + content + " ";
//content_node = "" + content;
//insert_node = "<span contenteditable='" + content_editable + ("' class='" + class_name + "'>" + content_node + "</span>");
insert_node = '<span class="' + class_name + '">' + content_node + '</span>';
$insert_node = $(insert_node).data('atwho-data-item', $li.data('item-data'));
if (document.selection) {
$insert_node = $("<span contenteditable='true'></span>").html($insert_node);
}
}
if ($inputor.is('textarea, input')) {
content = '' + content;
source = $inputor.val();
start_str = source.slice(0, Math.max(this.query.head_pos - this.at.length, 0));
text = "" + start_str + content + " " + (source.slice(this.query['end_pos'] || 0));
$inputor.val(text);
////$inputor.caret('pos', start_str.length + content.length + 1);
$inputor.caret('pos', this.setting.cWindow, start_str.length + content.length + 1);
} else if (range = this.get_range()) {
////
thisWin = this.setting.cWindow;
pos = range.startOffset - (this.query.end_pos - this.query.head_pos) - this.at.length;
range.setStart(range.endContainer, Math.max(pos, 0));
range.setEnd(range.endContainer, range.endOffset);
range.deleteContents();
range.insertNode(document.createTextNode(content + " "));
//range.insertNode($insert_node[0]);
range.collapse(false);
////sel = window.getSelection();
sel = thisWin.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (range = this.get_ie_range()) {
range.moveStart('character', this.query.end_pos - this.query.head_pos - this.at.length);
///////
range.pasteHTML($insert_node[0]);
range.collapse(false);
range.select();
}
$inputor.focus();
return $inputor.change();
};
Controller.prototype.render_view = function(data) {
var search_key;
search_key = this.get_opt("search_key");
data = this.callbacks("sorter").call(this, this.query.text, data.slice(0, 1001), search_key);
return this.view.render(data.slice(0, this.get_opt('limit')));
};
Controller.prototype.look_up = function() {
var query, _callback;
if (!(query = this.catch_query())) {
return;
}
_callback = function(data) {
if (data && data.length > 0) {
return this.render_view(data);
} else {
return this.view.hide();
}
};
this.model.query(query.text, $.proxy(_callback, this));
return query;
};
return Controller;
})();
Model = (function() {
var _storage;
_storage = {};
function Model(context) {
this.context = context;
this.at = this.context.at;
}
Model.prototype.saved = function() {
return this.fetch() > 0;
};
Model.prototype.query = function(query, callback) {
var data, search_key, _ref;
data = this.fetch();
search_key = this.context.get_opt("search_key");
callback(data = this.context.callbacks('filter').call(this.context, query, data, search_key));
if (!(data && data.length > 0)) {
return (_ref = this.context.callbacks('remote_filter')) != null ? _ref.call(this.context, query, callback) : void 0;
}
};
Model.prototype.fetch = function() {
return _storage[this.at] || [];
};
Model.prototype.save = function(data) {
return _storage[this.at] = this.context.callbacks("before_save").call(this.context, data || []);
};
Model.prototype.load = function(data) {
if (!(this.saved() || !data)) {
return this._load(data);
}
};
Model.prototype.reload = function(data) {
return this._load(data);
};
Model.prototype._load = function(data) {
var _this = this;
if (typeof data === "string") {
return $.ajax(data, {
dataType: "json"
}).done(function(data) {
return _this.save(data);
});
} else {
return this.save(data);
}
};
return Model;
})();
View = (function() {
function View(context) {
this.context = context;
this.$el = $("<div class='atwho-view'><ul class='atwho-view-ul'></ul></div>");
this.timeout_id = null;
this.context.$el.append(this.$el);
this.bind_event();
}
View.prototype.init = function() {
var id;
id = this.context.get_opt("alias") || this.context.at.charCodeAt(0);
return this.$el.attr({
'id': "at-view-" + id
});
};
View.prototype.bind_event = function() {
var $menu,
_this = this;
$menu = this.$el.find('ul');
$menu.on('mouseenter.atwho-view', 'li', function(e) {
$menu.find('.cur').removeClass('cur');
return $(e.currentTarget).addClass('cur');
}).on('click', function(e) {
_this.choose(e);
return e.preventDefault();
});
return this.$el.on('mouseenter.atwho-view', 'ul', function(e) {
return _this.context.mark_range();
}).on('mouseleave.atwho-view', 'ul', function(e) {
return _this.context.clear_range();
});
};
View.prototype.visible = function() {
return this.$el.is(":visible");
};
View.prototype.choose = function(event) {
var $li, content;
if (($li = this.$el.find(".cur")).length) {
event.preventDefault();
content = this.context.insert_content_for($li);
this.context.insert(this.context.callbacks("before_insert").call(this.context, content, $li), $li);
this.context.trigger("inserted", [$li]);
return this.hide();
}
};
View.prototype.reposition = function(rect) {
////var offset;
////if (rect.bottom + this.$el.height() - $(window).scrollTop() > $(window).height()) {
var offset;
////
// Make sure the non-iframe version still references window.
var thisWin = (this.context.setting.cWindow)
? null
: window;
if (rect.bottom + this.$el.height() - $(thisWin).scrollTop() > $(thisWin).height()) {
rect.bottom = rect.top - this.$el.height();
}
offset = {
left: rect.left,
top: rect.bottom
};
this.$el.offset(offset);
return this.context.trigger("reposition", [offset]);
};
View.prototype.next = function() {
var cur, next;
cur = this.$el.find('.cur').removeClass('cur');
next = cur.next();
if (!next.length) {
next = this.$el.find('li:first');
}
return next.addClass('cur');
};
View.prototype.prev = function() {
var cur, prev;
cur = this.$el.find('.cur').removeClass('cur');
prev = cur.prev();
if (!prev.length) {
prev = this.$el.find('li:last');
}
return prev.addClass('cur');
};
View.prototype.show = function() {
var rect;
if (!this.visible()) {
this.$el.show();
}
if (rect = this.context.rect()) {
return this.reposition(rect);
}
};
View.prototype.hide = function(time) {
var callback,
_this = this;
if (isNaN(time && this.visible())) {
this.context.reset_rect();
return this.$el.hide();
} else {
callback = function() {
return _this.hide();
};
clearTimeout(this.timeout_id);
return this.timeout_id = setTimeout(callback, time);
}
};
View.prototype.render = function(list) {
var $li, $ul, item, li, tpl, _i, _len;
if (!$.isArray(list || list.length <= 0)) {
this.hide();
return;
}
this.$el.find('ul').empty();
$ul = this.$el.find('ul');
tpl = this.context.get_opt('tpl');
for (_i = 0, _len = list.length; _i < _len; _i++) {
item = list[_i];
item = $.extend({}, item, {
'atwho-at': this.context.at
});
li = this.context.callbacks("tpl_eval").call(this.context, tpl, item);
$li = $(this.context.callbacks("highlighter").call(this.context, li, this.context.query.text));
$li.data("item-data", item);
$ul.append($li);
}
this.show();
return $ul.find("li:first").addClass("cur");
};
return View;
})();
KEY_CODE = {
DOWN: 40,
UP: 38,
ESC: 27,
TAB: 9,
ENTER: 13
};
DEFAULT_CALLBACKS = {
before_save: function(data) {
var item, _i, _len, _results;
if (!$.isArray(data)) {
return data;
}
_results = [];
for (_i = 0, _len = data.length; _i < _len; _i++) {
item = data[_i];
if ($.isPlainObject(item)) {
_results.push(item);
} else {
_results.push({
name: item
});
}
}
return _results;
},
matcher: function(flag, subtext, should_start_with_space) {
var match, regexp;
flag = flag.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
if (should_start_with_space) {
flag = '(?:^|\\s)' + flag;
}
regexp = new RegExp(flag + '([A-Za-z0-9_\+\-]*)$|' + flag + '([^\\x00-\\xff]*)$', 'gi');
match = regexp.exec(subtext);
if (match) {
return match[2] || match[1];
} else {
return null;
}
},
filter: function(query, data, search_key) {
var item, _i, _len, _results;
_results = [];
for (_i = 0, _len = data.length; _i < _len; _i++) {
item = data[_i];
if (~item[search_key].toLowerCase().indexOf(query)) {
_results.push(item);
}
}
return _results;
},
remote_filter: null,
sorter: function(query, items, search_key) {
var item, _i, _len, _results;
if (!query) {
return items;
}
_results = [];
for (_i = 0, _len = items.length; _i < _len; _i++) {
item = items[_i];
item.atwho_order = item[search_key].toLowerCase().indexOf(query);
if (item.atwho_order > -1) {
_results.push(item);
}
}
return _results.sort(function(a, b) {
return a.atwho_order - b.atwho_order;
});
},
tpl_eval: function(tpl, map) {
try {
return tpl.replace(/\$\{([^\}]*)\}/g, function(tag, key, pos) {
return map[key];
});
} catch (error) {
return "";
}
},
highlighter: function(li, query) {
var regexp;
if (!query) {
return li;
}
regexp = new RegExp(">\\s*(\\w*)(" + query.replace("+", "\\+") + ")(\\w*)\\s*<", 'ig');
return li.replace(regexp, function(str, $1, $2, $3) {
return '> ' + $1 + '<strong>' + $2 + '</strong>' + $3 + ' <';
});
},
before_insert: function(value, $li) {
return value;
}
};
Api = {
load: function(at, data) {
var c;
if (c = this.controller(at)) {
return c.model.load(data);
}
},
getInsertedItemsWithIDs: function(at) {
var c, ids, items;
if (!(c = this.controller(at))) {
return [null, null];
}
if (at) {
at = "-" + (c.get_opt('alias') || c.at);
}
ids = [];
items = $.map(this.$inputor.find("span.atwho-view-flag" + (at || "")), function(item) {
var data;
data = $(item).data('atwho-data-item');
if (ids.indexOf(data.id) > -1) {
return;
}
if (data.id) {
ids.push = data.id;
}
return data;
});
return [ids, items];
},
getInsertedItems: function(at) {
return Api.getInsertedItemsWithIDs.apply(this, [at])[1];
},
getInsertedIDs: function(at) {
return Api.getInsertedItemsWithIDs.apply(this, [at])[0];
},
run: function() {
return this.dispatch();
}
};
Atwho = {
init: function(options) {
var $this, app;
app = ($this = $(this)).data("atwho");
if (!app) {
$this.data('atwho', (app = new App(this)));
}
app.reg(options.at, options);
return this;
}
};
$CONTAINER = $("<div id='atwho-container'></div>");
$.fn.atwho = function(method) {
var result, _args;
_args = arguments;
$('body').append($CONTAINER);
result = null;
this.filter('textarea, input, [contenteditable=true]').each(function() {
//console.log('at inloop');
//console.log(this);
var app;
if (typeof method === 'object' || !method) {
return Atwho.init.apply(this, _args);
} else if (Api[method]) {
if (app = $(this).data('atwho')) {
return result = Api[method].apply(app, Array.prototype.slice.call(_args, 1));
}
} else {
return $.error("Method " + method + " does not exist on jQuery.caret");
}
});
return result || this;
};
return $.fn.atwho["default"] = {
at: void 0,
alias: void 0,
data: null,
tpl: "<li data-value='${atwho-at}${name}'>${name}</li>",
insert_tpl: "<span>${atwho-data-value}</span>",
callbacks: DEFAULT_CALLBACKS,
search_key: "name",
start_with_space: true,
limit: 5,
max_len: 20,
display_timeout: 300,
////
cWindow: window
};
});
}).call(this);
| rwmcoder/Vanilla | js/library/jquery.atwho.js | JavaScript | gpl-2.0 | 35,430 |
/*----------------------------------------------------------------------------------*/
//This code is part of a larger project whose main purpose is to entretain either //
//by working on it and helping it be better or by playing it in it's actual state //
// //
//Copyright (C) 2011 Three Legged Studio //
// //
// 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 this program; if not, write to the Free Software Foundation, //
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. //
// //
// You can contact us at projectpgz.blogspot.com //
/*----------------------------------------------------------------------------------*/
#include "iPushable.h"
iPushable::iPushable(){
init(stepPushDist, useConstraints);
}
iPushable::iPushable(int stepPushDist, bool useConstraints){
init(stepPushDist, useConstraints);
}
void iPushable::init(int stepPushDist, bool useConstraints){
this->stepPushDist = stepPushDist;
this->useConstraints = useConstraints;
locked = false;
}
iPushable::~iPushable(){
}
std::pair<int, int> iPushable::onPush(Entity *ent, Direction dir){
// mover en base al stepPushDist si no estamos locked
if(!locked){
// Mover en las direcciones aceptadas por los constraints
if(useConstraints)
if(pushConstraints.find(dir) != pushConstraints.end()){
return move(ent, dir);
}
else
return make_pair(0, 0);
// Mover sin restricciones
return move(ent, dir);
}
return make_pair(0, 0);
}
void iPushable::lockPush(){
locked = true;
}
void iPushable::unlockPush(){
locked = false;
}
bool iPushable::isLockedPush(){
return locked;
}
void iPushable::setConstraints(set<Direction> pushConstrains){
this->pushConstraints = pushConstrains;
useConstraints = true;
}
std::pair<int, int> iPushable::move(Entity *ent, Direction dir){
int xtemp, ytemp;
int xorig, yorig;
xorig = ent->x;
yorig = ent->y;
switch (dir) {
case UP:
xtemp = ent->x;
ytemp = ent->y-stepPushDist;
break;
case DOWN:
xtemp = ent->x;
ytemp = ent->y+stepPushDist;
break;
case LEFT:
xtemp = ent->x-stepPushDist;
ytemp = ent->y;
break;
case RIGHT:
xtemp = ent->x+stepPushDist;
ytemp = ent->y;
break;
}
if (xtemp == ent->x && ytemp == ent->y)
return make_pair(0, 0);
/*if (ent->world->place_free(ent->x, ytemp, ent)){
ent->y = ytemp;
}
else{
ent->world->moveToContact(ent->x,ytemp, ent);
}
if (ent->world->place_free(xtemp, ent->y, ent)){
ent->x = xtemp;
}
else{
ent->world->moveToContact(xtemp,ent->y, ent);
}*/
if (!ent->world->place_free(xtemp, ytemp, ent))
ent->world->moveToContact(xtemp, ytemp, ent);
else
ent->x = xtemp, ent->y = ytemp;
return make_pair(abs(ent->x - xorig), abs(ent-> y - yorig));
} | rafadelahoz/projectpgz-dev | interprete/source/src/iPushable.cpp | C++ | gpl-2.0 | 3,637 |
/*
* Copyright (c) 1998-2012 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source 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.
*
* Resin Open Source 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, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package javax.xml.bind.annotation;
public enum XmlAccessType {
FIELD, NONE, PROPERTY, PUBLIC_MEMBER;
}
| mdaniel/svn-caucho-com-resin | modules/jaxb/src/javax/xml/bind/annotation/XmlAccessType.java | Java | gpl-2.0 | 1,117 |
# Copyright (C) 2007 Rising Sun Pictures and Matthew Landauer
#
# 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
class WatchDirectoryKey < ActiveRecord::Migration
def self.up
add_column :servers, :directory_info_id, :integer
remove_column :servers, :watch_directory
end
def self.down
add_column :servers, :watch_directory, :string, :default => "", :null => false
remove_column :servers, :directory_info_id
end
end
| Jonv/earth | db/migrate/014_watch_directory_key.rb | Ruby | gpl-2.0 | 1,094 |
<?php
/**
* HUBzero CMS
*
* Copyright 2005-2015 HUBzero Foundation, LLC.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* HUBzero is a registered trademark of Purdue University.
*
* @package hubzero-cms
* @author David Benham <dbenham@purdue.edu>
* @copyright Copyright 2005-2015 HUBzero Foundation, LLC.
* @license http://opensource.org/licenses/MIT MIT
*/
// No direct access
defined('_HZEXEC_') or die();
/**
* Groups plugin class for Member Options
*/
class plgGroupsMemberOptions extends \Hubzero\Plugin\Plugin
{
/**
* Affects constructor behavior. If true, language files will be loaded automatically.
*
* @var boolean
*/
protected $_autoloadLanguage = true;
/**
* Return the alias and name for this category of content
*
* @return array
*/
public function &onGroupAreas()
{
$area = array(
'name' => 'memberoptions',
'title' => Lang::txt('GROUP_MEMBEROPTIONS'),
'default_access' => 'registered',
'display_menu_tab' => $this->params->get('display_tab', 0),
'icon' => '2699'
);
return $area;
}
/**
* Return data on a group view (this will be some form of HTML)
*
* @param object $group Current group
* @param string $option Name of the component
* @param string $authorized User's authorization level
* @param integer $limit Number of records to pull
* @param integer $limitstart Start of records to pull
* @param string $action Action to perform
* @param array $access What can be accessed
* @param array $areas Active area(s)
* @return array
*/
public function onGroup($group, $option, $authorized, $limit=0, $limitstart=0, $action='', $access, $areas=null)
{
// The output array we're returning
$arr = array(
'html' => ''
);
$user = User::getInstance();
$this->group = $group;
$this->option = $option;
// Things we need from the form
$recvEmailOptionID = Request::getInt('memberoptionid', 0);
$recvEmailOptionValue = Request::getInt('recvpostemail', 0);
include_once(__DIR__ . DS . 'models' . DS . 'memberoption.php');
switch ($action)
{
case 'editmemberoptions':
$arr['html'] .= $this->edit($group, $user, $recvEmailOptionID, $recvEmailOptionValue);
break;
case 'savememberoptions':
$arr['html'] .= $this->save($group, $user, $recvEmailOptionID, $recvEmailOptionValue);
break;
default:
$arr['html'] .= $this->edit($group, $user, $recvEmailOptionID, $recvEmailOptionValue);
break;
}
return $arr;
}
/**
* Edit settings
*
* @param object $group
* @param object $user
* @param integer $recvEmailOptionID
* @param integer $recvEmailOptionValue
* @return string
*/
protected function edit($group, $user, $recvEmailOptionID, $recvEmailOptionValue)
{
// Load the options
$recvEmailOption = Plugins\Groups\Memberoptions\Models\Memberoption::oneByUserAndOption(
$group->get('gidNumber'),
$user->get('id'),
'receive-forum-email'
);
$view = $this->view('default', 'browse')
->set('recvEmailOptionID', $recvEmailOption->get('id', 0))
->set('recvEmailOptionValue', $recvEmailOption->get('optionvalue', 0))
->set('option', $this->option)
->set('group', $this->group);
// Return the output
return $view->loadTemplate();
}
/**
* Save settings
*
* @param object $group
* @param object $user
* @param integer $recvEmailOptionID
* @param integer $recvEmailOptionValue
* @return void
*/
protected function save($group, $user, $recvEmailOptionID, $recvEmailOptionValue)
{
$postSaveRedirect = Request::getVar('postsaveredirect', '');
// Save the GROUPS_MEMBEROPTION_TYPE_DISCUSSION_NOTIFICIATION setting
$row = Plugins\Groups\Memberoptions\Models\Memberoption::blank()->set(array(
'id' => $recvEmailOptionID,
'userid' => $user->get('id'),
'gidNumber' => $group->get('gidNumber'),
'optionname' => 'receive-forum-email',
'optionvalue' => $recvEmailOptionValue
));
// Store content
if (!$row->save())
{
$this->setError($row->getError());
return $this->edit($group, $user, $recvEmailOptionID, $recvEmailOptionValue);
}
if (Request::getInt('no_html'))
{
echo json_encode(array('success' => true));
exit();
}
if (!$postSaveRedirect)
{
$postSaveRedirect = Route::url('index.php?option=' . $this->option . '&cn=' . $this->group->get('cn') . '&active=memberoptions&action=edit');
}
App::redirect(
$postSaveRedirect,
Lang::txt('You have successfully updated your email settings')
);
}
/**
* Subscribe a person to emails on enrollment
*
* @param integer $gidNumber
* @param integer $userid
* @return void
*/
public function onGroupUserEnrollment($gidNumber, $userid)
{
// get group
$group = \Hubzero\User\Group::getInstance($gidNumber);
// is auto-subscribe on for discussion forum
$autosubscribe = $group->get('discussion_email_autosubscribe');
// log variable
Log::debug('$discussion_email_autosubscribe' . $autosubscribe);
// if were not auto-subscribed then stop
if (!$autosubscribe)
{
return;
}
include_once(__DIR__ . DS . 'models' . DS . 'memberoption.php');
// see if they've already got something, they shouldn't, but you never know
$row = Plugins\Groups\Memberoptions\Models\Memberoption::oneByUserAndOption(
$gidNumber,
$userid,
'receive-forum-email'
);
if ($row->get('id'))
{
// They already have a record, so ignore.
return;
}
$row->set('gidNumber', $gidNumber);
$row->set('userid', $userid);
$row->set('optionname', 'receive-forum-email');
$row->set('optionvalue', 1);
$row->save();
}
}
| kevinwojo/hubzero-cms | core/plugins/groups/memberoptions/memberoptions.php | PHP | gpl-2.0 | 6,730 |
/**
* Copyright (c) 2009--2012 Red Hat, Inc.
*
* This software is licensed to you under the GNU General Public License,
* version 2 (GPLv2). There is NO WARRANTY for this software, express or
* implied, including the implied warranties of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
* along with this software; if not, see
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* Red Hat trademarks are not licensed under GPLv2. No permission is
* granted to use or replicate Red Hat trademarks that are incorporated
* in this software or its documentation.
*/
package com.redhat.rhn.taskomatic.task;
import com.redhat.rhn.common.conf.Config;
import com.redhat.rhn.common.hibernate.HibernateFactory;
import com.redhat.rhn.taskomatic.TaskoRun;
import com.redhat.rhn.taskomatic.task.threaded.TaskQueue;
import com.redhat.rhn.taskomatic.task.threaded.TaskQueueFactory;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import java.io.IOException;
/**
* Custom Quartz Job implementation which only allows one thread to
* run at a time. All other threads return without performing any work.
* This policy was chosen instead of blocking so as to reduce threading
* problems inside Quartz itself.
*
* @version $Rev $
*
*/
public abstract class RhnQueueJob implements RhnJob {
private TaskoRun jobRun = null;
protected abstract Logger getLogger();
/**
* {@inheritDoc}
*/
public void appendExceptionToLogError(Exception e) {
getLogger().error(e.getMessage());
getLogger().error(e.getCause());
}
private void logToNewFile() {
PatternLayout pattern =
new PatternLayout(DEFAULT_LOGGING_LAYOUT);
try {
getLogger().removeAllAppenders();
FileAppender appender = new FileAppender(pattern,
jobRun.buildStdOutputLogPath());
getLogger().addAppender(appender);
}
catch (IOException e) {
getLogger().warn("Logging to file disabled");
}
}
/**
* {@inheritDoc}
*/
public void execute(JobExecutionContext ctx, TaskoRun runIn)
throws JobExecutionException {
setJobRun(runIn);
try {
execute(ctx);
}
catch (Exception e) {
if (HibernateFactory.getSession().getTransaction().isActive()) {
HibernateFactory.rollbackTransaction();
HibernateFactory.closeSession();
}
appendExceptionToLogError(e);
jobRun.saveStatus(TaskoRun.STATUS_FAILED);
}
HibernateFactory.commitTransaction();
HibernateFactory.closeSession();
}
/**
* {@inheritDoc}
*/
public void execute(JobExecutionContext ctx)
throws JobExecutionException {
TaskQueueFactory factory = TaskQueueFactory.get();
String queueName = getQueueName();
TaskQueue queue = factory.getQueue(queueName);
if (queue == null) {
try {
queue = factory.createQueue(queueName, getDriverClass(), getLogger());
}
catch (Exception e) {
getLogger().error(e);
return;
}
}
if (queue.changeRun(jobRun)) {
jobRun.start();
HibernateFactory.commitTransaction();
HibernateFactory.closeSession();
logToNewFile();
getLogger().debug("Starting run " + jobRun.getId());
}
else {
// close current run
TaskoRun run = (TaskoRun) HibernateFactory.reload(jobRun);
run.appendToOutputLog("Run with id " + queue.getQueueRun().getId() +
" handles the whole task queue.");
run.skipped();
HibernateFactory.commitTransaction();
HibernateFactory.closeSession();
}
int defaultItems = 3;
if (queueName.equals("channel_repodata")) {
defaultItems = 1;
}
int maxWorkItems = Config.get().getInt("taskomatic." + queueName +
"_max_work_items", defaultItems);
if (queue.getQueueSize() < maxWorkItems) {
queue.run(this);
}
else {
getLogger().debug("Maximum number of workers already put ... skipping.");
}
}
/**
* @return Returns the run.
*/
public TaskoRun getRun() {
return jobRun;
}
/**
* @param runIn The run to set.
*/
public void setJobRun(TaskoRun runIn) {
jobRun = runIn;
}
protected abstract Class getDriverClass();
protected abstract String getQueueName();
}
| hustodemon/spacewalk | java/code/src/com/redhat/rhn/taskomatic/task/RhnQueueJob.java | Java | gpl-2.0 | 4,855 |
/*
*
* Copyright (c) 2003
* John Maddock
*
* Use, modification and distribution are subject to the
* Boost Software License, Version 1.0. (See accompanying file
* LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*
*/
/*
* LOCATION: see http://www.boost.org for most recent version.
* FILE regex_iterator_example_2.cpp
* VERSION see <boost/version.hpp>
* DESCRIPTION: regex_iterator example 2: searches a cpp file for class definitions,
* using global data.
*/
#include <string>
#include <map>
#include <fstream>
#include <iostream>
#include <boost/regex.hpp>
using namespace std;
// purpose:
// takes the contents of a file in the form of a string
// and searches for all the C++ class definitions, storing
// their locations in a map of strings/int's
typedef std::map<std::string, std::string::difference_type, std::less<std::string> > map_type;
const char* re =
// possibly leading whitespace:
"^[[:space:]]*"
// possible template declaration:
"(template[[:space:]]*<[^;:{]+>[[:space:]]*)?"
// class or struct:
"(class|struct)[[:space:]]*"
// leading declspec macros etc:
"("
"\\<\\w+\\>"
"("
"[[:blank:]]*\\([^)]*\\)"
")?"
"[[:space:]]*"
")*"
// the class name
"(\\<\\w*\\>)[[:space:]]*"
// template specialisation parameters
"(<[^;:{]+>)?[[:space:]]*"
// terminate in { or :
"(\\{|:[^;\\{()]*\\{)";
boost::regex expression(re);
map_type class_index;
bool regex_callback(const boost::match_results<std::string::const_iterator>& what)
{
// what[0] contains the whole string
// what[5] contains the class name.
// what[6] contains the template specialisation if any.
// add class name and position to map:
class_index[what[5].str() + what[6].str()] = what.position(5);
return true;
}
void load_file(std::string& s, std::istream& is)
{
s.erase();
if(is.bad()) return;
s.reserve(is.rdbuf()->in_avail());
char c;
while(is.get(c))
{
if(s.capacity() == s.size())
s.reserve(s.capacity() * 3);
s.append(1, c);
}
}
int main(int argc, const char** argv)
{
std::string text;
for(int i = 1; i < argc; ++i)
{
cout << "Processing file " << argv[i] << endl;
std::ifstream fs(argv[i]);
load_file(text, fs);
fs.close();
// construct our iterators:
boost::sregex_iterator m1(text.begin(), text.end(), expression);
boost::sregex_iterator m2;
std::for_each(m1, m2, ®ex_callback);
// copy results:
cout << class_index.size() << " matches found" << endl;
map_type::iterator c, d;
c = class_index.begin();
d = class_index.end();
while(c != d)
{
cout << "class \"" << (*c).first << "\" found at index: " << (*c).second << endl;
++c;
}
class_index.erase(class_index.begin(), class_index.end());
}
return 0;
}
| scs/uclinux | lib/boost/boost_1_38_0/libs/regex/example/snippets/regex_iterator_example.cpp | C++ | gpl-2.0 | 2,963 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Validate
* @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Ip.php 8934 2013-03-29 19:17:23Z btowles $
*/
/**
* @see Zend_Validate_Abstract
*/
require_once 'Zend/Validate/Abstract.php';
/**
* @category Zend
* @package Zend_Validate
* @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Validate_Ip extends Zend_Validate_Abstract
{
const NOT_IP_ADDRESS = 'notIpAddress';
/**
* @var array
*/
protected $_messageTemplates = array(
self::NOT_IP_ADDRESS => "'%value%' does not appear to be a valid IP address"
);
/**
* Defined by Zend_Validate_Interface
*
* Returns true if and only if $value is a valid IP address
*
* @param mixed $value
* @return boolean
*/
public function isValid($value)
{
$valueString = (string) $value;
$this->_setValue($valueString);
if (ip2long($valueString) === false) {
$this->_error();
return false;
}
return true;
}
}
| omesan/SiteLegionTacticalPainball | plugins/system/rokupdater/lib/vendor/maciek-kemnitz/phpquery/phpQuery/phpQuery/Zend/Validate/Ip.php | PHP | gpl-2.0 | 1,777 |
<head>
<title>{#tagwrap_dlg.titleP}</title>
<script type="text/javascript" src="../../../tinymce/tiny_mce_popup.js"></script>
<script type="text/javascript" src="js/dialog.js"></script>
<link rel="stylesheet" type="text/css" href="css/tagwrap.css" />
</head>
<body>
<div class="y_logo_contener">
<img src="img/html5.png" alt="HTML5" />
</div>
<div class="yinstr">
<p>{#tagwrap_dlg.noteP}</p>
<p>{#tagwrap_dlg.noteP3}</p>
</div>
<form onSubmit="TagwrapDialog.insert();return false;" action="#" method="post" name="P_tag">
<div class="mceActionPanel">
<script type="text/javascript" language="javascript">
var jwl_sel_content4 = tinyMCE.activeEditor.selection.getContent();
</script>
{#tagwrap_dlg.noteP1} <input id="title_value" type="text" name="title" width="200px" value="" /> <em> {#tagwrap_dlg.noteP2}</em>
<br /><br />
</div>
<div style="margin-top:80px;"</div>
<div class="bottom">
<p><!--{#tagwrap_dlg.bottomnote}--></p>
<p class="pagelink_hover"><!--{#tagwrap_dlg.bottomnote2}--></p>
</div>
<script type="text/javascript" language="javascript">
function jwl_pass_form_data () {
var name = jwl_title = document.getElementsByName("title")[0].value;
}
</script>
<div class="mceActionPanel">
<div style="float:left;padding-top:5px">
<input type="button" id="insert" name="insert" value="{#insert}" onClick="jwl_pass_form_data();tinyMCE.execCommand('mceInsertContent',false,'<p style=\'' + jwl_title + '\'>' + jwl_sel_content4 + '</p>');tinyMCEPopup.close();" /> <input type="button" id="cancel" name="cancel" value="{#cancel}" onClick="tinyMCEPopup.close();" />
</div>
</div>
</form>
<span style="float:right;"><a target="_blank" href="http://www.joshlobe.com/2012/07/ultimate-tinymce-advanced-html-tags/"><img src="img/tinymce_help.png" /></a></span>
</body> | gacarrigan/WP-Site | wp-content/plugins/ultimate-tinymce/addons/tagwrap/tags/p.php | PHP | gpl-2.0 | 1,842 |
'use strict';
const common = require('../common.js');
const bench = common.createBenchmark(main, {
pieces: [1, 4, 16],
pieceSize: [1, 16, 256],
withTotalLength: [0, 1],
n: [1024]
});
function main(conf) {
const n = +conf.n;
const size = +conf.pieceSize;
const pieces = +conf.pieces;
const list = new Array(pieces);
list.fill(Buffer.allocUnsafe(size));
const totalLength = conf.withTotalLength ? pieces * size : undefined;
bench.start();
for (var i = 0; i < n * 1024; i++) {
Buffer.concat(list, totalLength);
}
bench.end(n);
}
| domino-team/openwrt-cc | package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/benchmark/buffers/buffer-concat.js | JavaScript | gpl-2.0 | 563 |
/*
* Copyright (C) 2011 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#if ENABLE(INSPECTOR) && ENABLE(WORKERS)
#include "WorkerRuntimeAgent.h"
#include "InjectedScript.h"
#include "InstrumentingAgents.h"
#include "ScriptState.h"
#include "WorkerContext.h"
#include "WorkerDebuggerAgent.h"
#include "WorkerRunLoop.h"
#include "WorkerThread.h"
namespace WebCore {
WorkerRuntimeAgent::WorkerRuntimeAgent(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state, InjectedScriptManager* injectedScriptManager, WorkerContext* workerContext)
: InspectorRuntimeAgent(instrumentingAgents, state, injectedScriptManager)
, m_workerContext(workerContext)
, m_paused(false)
{
m_instrumentingAgents->setWorkerRuntimeAgent(this);
}
WorkerRuntimeAgent::~WorkerRuntimeAgent()
{
m_instrumentingAgents->setWorkerRuntimeAgent(0);
}
InjectedScript WorkerRuntimeAgent::injectedScriptForEval(ErrorString* error, const int* executionContextId)
{
if (executionContextId) {
*error = "Execution context id is not supported for workers as there is only one execution context.";
return InjectedScript();
}
ScriptState* scriptState = scriptStateFromWorkerContext(m_workerContext);
return injectedScriptManager()->injectedScriptFor(scriptState);
}
void WorkerRuntimeAgent::muteConsole()
{
// We don't need to mute console for workers.
}
void WorkerRuntimeAgent::unmuteConsole()
{
// We don't need to mute console for workers.
}
void WorkerRuntimeAgent::run(ErrorString*)
{
m_paused = false;
}
#if ENABLE(JAVASCRIPT_DEBUGGER)
void WorkerRuntimeAgent::pauseWorkerContext(WorkerContext* context)
{
m_paused = true;
MessageQueueWaitResult result;
do {
result = context->thread()->runLoop().runInMode(context, WorkerDebuggerAgent::debuggerTaskMode);
// Keep waiting until execution is resumed.
} while (result == MessageQueueMessageReceived && m_paused);
}
#endif // ENABLE(JAVASCRIPT_DEBUGGER)
} // namespace WebCore
#endif // ENABLE(INSPECTOR) && ENABLE(WORKERS)
| 166MMX/openjdk.java.net-openjfx-8u40-rt | modules/web/src/main/native/Source/WebCore/inspector/WorkerRuntimeAgent.cpp | C++ | gpl-2.0 | 3,564 |
<?php
/*
$id author Puddled Internet - http://www.puddled.co.uk
email support@puddled.co.uk
osCommerce, Open Source E-Commerce Solutions
http://www.oscommerce.com
Copyright (c) 2002 osCommerce
Released under the GNU General Public License
*/
require('includes/application_top.php');
$action = isset($_GET['action']) ? $_GET['action'] : '';
switch ($action) {
case 'insert':
case 'save':
$return_reason_id = isset($_GET['oID']) ? tep_db_prepare_input($_GET['oID']) : 0;
$languages = tep_get_languages();
for ($i = 0, $n = sizeof($languages); $i < $n; $i++) {
$return_reason_name_array = $_POST['return_reason_name'];
$language_id = $languages[$i]['id'];
$sql_data_array = array('return_reason_name' => tep_db_prepare_input($return_reason_name_array[$language_id]));
if ($_GET['action'] == 'insert') {
if (!tep_not_null($return_reason_id)) {
$next_id_query = tep_db_query("select max(return_reason_id) as return_reason_id from " . TABLE_RETURN_REASONS . "");
$next_id = tep_db_fetch_array($next_id_query);
$return_reason_id = $next_id['return_reason_id'] + 1;
}
$insert_sql_data = array('return_reason_id' => $return_reason_id,
'language_id' => $language_id);
$sql_data_array = array_merge($sql_data_array, $insert_sql_data);
tep_db_perform(TABLE_RETURN_REASONS, $sql_data_array);
} elseif ($_GET['action'] == 'save') {
tep_db_perform(TABLE_RETURN_REASONS, $sql_data_array, 'update', "return_reason_id = '" . tep_db_input($return_reason_id) . "' and language_id = '" . $language_id . "'");
}
}
if ($_POST['default'] == 'on') {
tep_db_query("update " . TABLE_CONFIGURATION . " set configuration_value = '" . tep_db_input($return_reason_id) . "' where configuration_key = 'DEFAULT_RETURN_REASON'");
}
tep_redirect(tep_href_link(FILENAME_RETURNS_REASONS, 'page=' . $_GET['page'] . '&oID=' . $return_reason_id));
break;
case 'deleteconfirm':
$oID = tep_db_prepare_input($_GET['oID']);
$orders_status_query = tep_db_query("select configuration_value from " . TABLE_CONFIGURATION . " where configuration_key = 'DEFAULT_RETURN_REASON'");
$orders_status = tep_db_fetch_array($orders_status_query);
if ($orders_status['configuration_value'] == $oID) {
tep_db_query("update " . TABLE_CONFIGURATION . " set configuration_value = '' where configuration_key = 'DEFAULT_RETURN_REASON'");
}
tep_db_query("delete from " . TABLE_RETURN_REASONS . " where return_reason_id = '" . tep_db_input($oID) . "'");
tep_redirect(tep_href_link(FILENAME_RETURNS_REASONS, 'page=' . $_GET['page']));
break;
case 'delete':
$oID = tep_db_prepare_input($_GET['oID']);
/*
$status_query = tep_db_query("select count(*) as count from " . TABLE_RETURN_REASONS . " where orders_status = '" . tep_db_input($oID) . "'");
$status = tep_db_fetch_array($status_query);
*/
$remove_status = true;
/* if ($oID == DEFAULT_ORDERS_STATUS_ID) {
$remove_status = false;
$messageStack->add(ERROR_REMOVE_DEFAULT_ORDER_STATUS, 'error');
} elseif ($status['count'] > 0) {
$remove_status = false;
$messageStack->add(ERROR_STATUS_USED_IN_ORDERS, 'error');
} else {
$history_query = tep_db_query("select count(*) as count from " . TABLE_RETURN_REASONS_HISTORY . " where '" . tep_db_input($oID) . "' in (new_value, old_value)");
$history = tep_db_fetch_array($history_query);
if ($history['count'] > 0) {
$remove_status = false;
$messageStack->add(ERROR_STATUS_USED_IN_HISTORY, 'error');
}
}
break; */
}
if (!isset($_GET['action'])) {
$_GET['action'] = '';
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html <?php echo HTML_PARAMS; ?>>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=<?php echo CHARSET; ?>">
<title><?php echo TITLE; ?></title>
<script type="text/javascript" src="<?php echo (($request_type == 'SSL') ? 'https:' : 'http:'); ?>//ajax.googleapis.com/ajax/libs/jquery/<?php echo JQUERY_VERSION; ?>/jquery.min.js"></script>
<script type="text/javascript">
if (typeof jQuery == 'undefined') {
//alert('You are running a local copy of jQuery!');
document.write(unescape("%3Cscript src='includes/javascript/jquery-1.6.2.min.js' type='text/javascript'%3E%3C/script%3E"));
}
</script>
<link rel="stylesheet" type="text/css" href="includes/stylesheet.css">
<!--[if IE]>
<link rel="stylesheet" type="text/css" href="includes/stylesheet-ie.css">
<![endif]-->
<script language="javascript" src="includes/general.js"></script>
<link rel="stylesheet" type="text/css" href="includes/headernavmenu.css">
<script type="text/javascript" src="includes/menu.js"></script>
</head>
<body marginwidth="0" marginheight="0" topmargin="0" bottommargin="0" leftmargin="0" rightmargin="0" bgcolor="#FFFFFF" onload="SetFocus();">
<!-- header //-->
<?php require(DIR_WS_INCLUDES . 'header.php'); ?>
<!-- header_eof //-->
<!-- body //-->
<div id="body">
<table width="100%" border="0" align="center" cellpadding="0" cellspacing="0" class="body-table">
<tr>
<!-- left_navigation //-->
<?php require(DIR_WS_INCLUDES . 'column_left.php'); ?>
<!-- left_navigation_eof //-->
<!-- body_text //-->
<td width="100%" valign="top"><table border="0" width="100%" cellspacing="0" cellpadding="2">
<tr>
<td><table border="0" width="100%" cellspacing="0" cellpadding="0">
<tr>
<td><?php echo tep_draw_separator('pixel_trans.gif', '1', '5'); ?></td>
</tr>
<tr>
<td class="pageHeading"><?php echo HEADING_TITLE; ?></td>
<td class="pageHeading" align="right"><?php echo tep_draw_separator('pixel_trans.gif', HEADING_IMAGE_WIDTH, HEADING_IMAGE_HEIGHT); ?></td>
</tr>
</table></td>
</tr>
<tr>
<td valign="top"><table border="0" width="100%" cellspacing="0" cellpadding="0">
<tr>
<td valign="top"><table border="0" width="100%" cellspacing="0" cellpadding="2" class="data-table">
<tr class="dataTableHeadingRow">
<td class="dataTableHeadingContent"><?php echo TABLE_HEADING_ORDERS_STATUS; ?></td>
<td class="dataTableHeadingContent" align="right"><?php echo TABLE_HEADING_ACTION; ?> </td>
</tr>
<?php
$orders_status_query_raw = "select return_reason_id, return_reason_name from " . TABLE_RETURN_REASONS . " where language_id = '" . $languages_id . "' order by return_reason_id";
$orders_status_split = new splitPageResults($_GET['page'], MAX_DISPLAY_SEARCH_RESULTS, $orders_status_query_raw, $orders_status_query_numrows);
$orders_status_query = tep_db_query($orders_status_query_raw);
while ($orders_status = tep_db_fetch_array($orders_status_query)) {
if (((!isset($_GET['oID'])) || (isset($_GET['oID']) && $_GET['oID'] == $orders_status['return_reason_id'])) && (!isset($oInfo)) && ( substr($_GET['action'], 0, 3) != 'new')) {
$oInfo = new objectInfo($orders_status);
}
if ( isset($oInfo) && (is_object($oInfo)) && ($orders_status['return_reason_id'] == $oInfo->return_reason_id) ) {
echo ' <tr class="dataTableRowSelected" onmouseover="this.style.cursor=\'hand\'" onclick="document.location.href=\'' . tep_href_link(FILENAME_RETURNS_REASONS, 'page=' . $_GET['page'] . '&oID=' . $oInfo->return_reason_id . '&action=edit') . '\'">' . "\n";
} else {
echo ' <tr class="dataTableRow" onmouseover="this.className=\'dataTableRowOver\';this.style.cursor=\'hand\'" onmouseout="this.className=\'dataTableRow\'" onclick="document.location.href=\'' . tep_href_link(FILENAME_RETURNS_REASONS, 'page=' . $_GET['page'] . '&oID=' . $orders_status['return_reason_id']) . '\'">' . "\n";
}
if (DEFAULT_RETURN_REASON == $orders_status['return_reason_id']) {
echo ' <td class="dataTableContent"><b>' . $orders_status['return_reason_name'] . ' (' . TEXT_DEFAULT . ')</b></td>' . "\n";
} else {
echo ' <td class="dataTableContent">' . $orders_status['return_reason_name'] . '</td>' . "\n";
}
?>
<td class="dataTableContent" align="right"><?php if ( isset($oInfo) && (is_object($oInfo)) && ($orders_status['return_reason_id'] == $oInfo->return_reason_id) ) { echo tep_image(DIR_WS_IMAGES . 'arrow_right_blue.png', ''); } else { echo '<a href="' . tep_href_link(FILENAME_RETURNS_REASONS, 'page=' . $_GET['page'] . '&oID=' . $orders_status['return_reason_id']) . '">' . tep_image(DIR_WS_IMAGES . 'information.png', IMAGE_ICON_INFO) . '</a>'; } ?> </td>
</tr>
<?php
}
?> </table><table border="0" cellpadding="0" cellspacing="0" width="100%" class="data-table-foot">
<tr>
<td colspan="2"><table border="0" width="100%" cellspacing="0" cellpadding="2">
<tr>
<td class="smallText" valign="top"><?php echo $orders_status_split->display_count($orders_status_query_numrows, MAX_DISPLAY_SEARCH_RESULTS, $_GET['page'], TEXT_DISPLAY_NUMBER_OF_TICKET_STATUS); ?></td>
<td class="smallText" align="right"><?php echo $orders_status_split->display_links($orders_status_query_numrows, MAX_DISPLAY_SEARCH_RESULTS, MAX_DISPLAY_PAGE_LINKS, $_GET['page']); ?></td>
</tr>
<?php
if (isset($_GET['action']) && substr($_GET['action'], 0, 3) != 'new') {
?>
<tr>
<td colspan="2" align="right"><?php echo '<a href="' . tep_href_link(FILENAME_RETURNS_REASONS, 'page=' . $_GET['page'] . '&action=new') . '">' . tep_image_button('button_insert.gif', IMAGE_INSERT) . '</a>'; ?> </td>
</tr>
<?php
}
?>
</table></td>
</tr>
</table></td>
<?php
$heading = array();
$contents = array();
$action = isset($_GET['action']) ? $_GET['action'] : '';
switch ($action) {
case 'new':
$heading[] = array('text' => '<b>' . TEXT_INFO_HEADING_NEW_ORDERS_STATUS . '</b>');
$contents = array('form' => tep_draw_form('status', FILENAME_RETURNS_REASONS, 'page=' . $_GET['page'] . '&action=insert'));
$contents[] = array('text' => TEXT_INFO_INSERT_INTRO);
$orders_status_inputs_string = '';
$languages = tep_get_languages();
for ($i = 0, $n = sizeof($languages); $i < $n; $i++) {
$orders_status_inputs_string .= '<br>' . tep_image(DIR_WS_CATALOG_LANGUAGES . $languages[$i]['directory'] . '/images/' . $languages[$i]['image'], $languages[$i]['name']) . ' ' . tep_draw_input_field('return_reason_name[' . $languages[$i]['id'] . ']');
}
$contents[] = array('text' => '<br>' . TEXT_INFO_ORDERS_STATUS_NAME . $orders_status_inputs_string);
$contents[] = array('text' => '<br>' . tep_draw_checkbox_field('default') . ' ' . TEXT_SET_DEFAULT);
$contents[] = array('align' => 'center', 'text' => '<br><a href="' . tep_href_link(FILENAME_RETURNS_REASONS, 'page=' . $_GET['page']) . '">' . tep_image_button('button_cancel.gif', IMAGE_CANCEL) . '</a>' . tep_image_submit('button_insert.gif', IMAGE_INSERT));
break;
case 'edit':
$heading[] = array('text' => '<b>' . TEXT_INFO_HEADING_EDIT_ORDERS_STATUS . '</b>');
$contents = array('form' => tep_draw_form('status', FILENAME_RETURNS_REASONS, 'page=' . $_GET['page'] . '&oID=' . $oInfo->return_reason_id . '&action=save'));
$contents[] = array('text' => TEXT_INFO_EDIT_INTRO);
$orders_status_inputs_string = '';
$languages = tep_get_languages();
for ($i = 0, $n = sizeof($languages); $i < $n; $i++) {
$orders_status_inputs_string .= '<br>' . tep_image(DIR_WS_CATALOG_LANGUAGES . $languages[$i]['directory'] . '/images/' . $languages[$i]['image'], $languages[$i]['name']) . ' ' . tep_draw_input_field('return_reason_name[' . $languages[$i]['id'] . ']', tep_get_return_reason_name($oInfo->return_reason_id, $languages[$i]['id']));
}
$contents[] = array('text' => '<br>' . TEXT_INFO_ORDERS_STATUS_NAME . $orders_status_inputs_string);
if (DEFAULT_ORDERS_STATUS_ID != $oInfo->return_reason_id) $contents[] = array('text' => '<br>' . tep_draw_checkbox_field('default') . ' ' . TEXT_SET_DEFAULT);
$contents[] = array('align' => 'center', 'text' => '<br><a href="' . tep_href_link(FILENAME_RETURNS_REASONS, 'page=' . $_GET['page'] . '&oID=' . $oInfo->return_reason_id) . '">' . tep_image_button('button_cancel.gif', IMAGE_CANCEL) . '</a>' . tep_image_submit('button_update.gif', IMAGE_UPDATE));
break;
case 'delete':
$heading[] = array('text' => '<b>' . TEXT_INFO_HEADING_DELETE_ORDERS_STATUS . '</b>');
$contents = array('form' => tep_draw_form('status', FILENAME_RETURNS_REASONS, 'page=' . $_GET['page'] . '&oID=' . $oInfo->return_reason_id . '&action=deleteconfirm'));
$contents[] = array('text' => TEXT_INFO_DELETE_INTRO);
$contents[] = array('text' => '<br><b>' . $oInfo->return_reason_name . '</b>');
if ($remove_status) $contents[] = array('align' => 'center', 'text' => '<br><a href="' . tep_href_link(FILENAME_RETURNS_REASONS, 'page=' . $_GET['page'] . '&oID=' . $oInfo->return_reason_id) . '">' . tep_image_button('button_cancel.gif', IMAGE_CANCEL) . '</a>' . tep_image_submit('button_delete.gif', IMAGE_DELETE));
break;
default:
if (isset($oInfo) && is_object($oInfo)) {
$heading[] = array('text' => '<b>' . $oInfo->return_reason_name . '</b>');
$contents[] = array('align' => 'center', 'text' => '<br><a href="' . tep_href_link(FILENAME_RETURNS_REASONS, 'page=' . $_GET['page'] . '&oID=' . $oInfo->return_reason_id . '&action=edit') . '">' . tep_image_button('button_page_edit.png', IMAGE_EDIT) . '</a><a href="' . tep_href_link(FILENAME_RETURNS_REASONS, 'page=' . $_GET['page'] . '&oID=' . $oInfo->return_reason_id . '&action=delete') . '">' . tep_image_button('button_delete.gif', IMAGE_DELETE) . '</a>');
$orders_status_inputs_string = '';
$languages = tep_get_languages();
for ($i = 0, $n = sizeof($languages); $i < $n; $i++) {
$orders_status_inputs_string .= '<br>' . tep_image(DIR_WS_CATALOG_LANGUAGES . $languages[$i]['directory'] . '/images/' . $languages[$i]['image'], $languages[$i]['name']) . ' ' . tep_get_return_reason_name($oInfo->return_reason_id, $languages[$i]['id']);
}
$contents[] = array('text' => $orders_status_inputs_string);
}
break;
}
if ( (tep_not_null($heading)) && (tep_not_null($contents)) ) {
echo ' <td width="25%" valign="top">' . "\n";
$box = new box;
echo $box->infoBox($heading, $contents);
echo ' </td>' . "\n";
}
?>
</tr>
</table></td>
</tr>
</table></td>
<!-- body_text_eof //-->
</tr>
</table>
</div>
<!-- body_eof //-->
<!-- footer //-->
<?php require(DIR_WS_INCLUDES . 'footer.php'); ?>
<!-- footer_eof //-->
<br>
</body>
</html>
<?php require(DIR_WS_INCLUDES . 'application_bottom.php'); ?>
| loadedcommerce/loaded6 | 6.5/Loaded_Commerce_PRO_v6.5.2_Upgrade_from_all_Std_OR_Pro_versions/admin/returns_reasons.php | PHP | gpl-2.0 | 15,332 |
/*
* Copyright (c) 1998-2012 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source 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.
*
* Resin Open Source 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, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
* Free SoftwareFoundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package com.caucho.ejb.cfg;
import com.caucho.config.ConfigException;
import com.caucho.config.types.DescriptionGroupConfig;
import com.caucho.config.types.Signature;
import com.caucho.util.L10N;
import com.caucho.vfs.Path;
import java.util.*;
import javax.annotation.PostConstruct;
/**
* Configuration for an ejb bean.
*/
public class EjbJar extends DescriptionGroupConfig {
private static final L10N L = new L10N(EjbJar.class);
private final EjbConfig _config;
private String _ejbModuleName;
private Path _rootPath;
private boolean _isMetadataComplete;
private boolean _isSkip;
public EjbJar(EjbConfig config,
String ejbModuleName,
Path rootPath)
{
_config = config;
_ejbModuleName = ejbModuleName;
_rootPath = rootPath;
}
public String getModuleName()
{
return _ejbModuleName;
}
public void setModuleName(String moduleName)
{
_ejbModuleName = moduleName;
}
public void setVersion(String version)
{
}
public void setSchemaLocation(String value)
{
}
public void setSkip(boolean isSkip)
{
_isSkip = isSkip;
}
public boolean isSkip()
{
return _isSkip;
}
public void setMetadataComplete(boolean isMetadataComplete)
{
_isMetadataComplete = isMetadataComplete;
}
public boolean isMetadataComplete()
{
return _isMetadataComplete;
}
public EjbEnterpriseBeans createEnterpriseBeans()
throws ConfigException
{
return new EjbEnterpriseBeans(_config, this, _ejbModuleName);
}
public InterceptorsConfig createInterceptors()
throws ConfigException
{
return new InterceptorsConfig(_config);
}
public Relationships createRelationships()
throws ConfigException
{
return new Relationships(_config);
}
public AssemblyDescriptor createAssemblyDescriptor()
throws ConfigException
{
return new AssemblyDescriptor(this, _config);
}
public void addQueryFunction(QueryFunction fun)
{
}
public void setBooleanLiteral(BooleanLiteral literal)
{
}
ContainerTransaction createContainerTransaction()
{
return new ContainerTransaction(this, _config);
}
MethodPermission createMethodPermission()
{
return new MethodPermission(_config);
}
public String toString()
{
return getClass().getSimpleName() + "[" + _rootPath.getFullPath() + "]";
}
public class MethodPermission {
EjbConfig _config;
MethodSignature _method;
ArrayList<String> _roles;
MethodPermission(EjbConfig config)
{
_config = config;
}
public void setDescription(String description)
{
}
public void setUnchecked(boolean unchecked)
{
}
public void setRoleName(String roleName)
{
if (_roles == null)
_roles = new ArrayList<String>();
_roles.add(roleName);
}
public void setMethod(MethodSignature method)
{
_method = method;
}
@PostConstruct
public void init()
throws ConfigException
{
if (isSkip())
return;
EjbBean bean = _config.getBeanConfig(_method.getEJBName());
if (bean == null)
throw new ConfigException(L.l("'{0}' is an unknown bean.",
_method.getEJBName()));
EjbMethodPattern method = bean.createMethod(_method);
if (_roles != null)
method.setRoles(_roles);
}
}
public static class QueryFunction {
FunctionSignature _sig;
String _sql;
public void setSignature(Signature sig)
throws ConfigException
{
_sig = new FunctionSignature(sig.getSignature());
}
public FunctionSignature getSignature()
{
return _sig;
}
public void setSQL(String sql)
throws ConfigException
{
_sql = sql;
}
public String getSQL()
{
return _sql;
}
@PostConstruct
public void init()
{
_sig.setSQL(_sql);
}
}
public static class Relationships {
EjbConfig _config;
Relationships(EjbConfig config)
{
_config = config;
}
}
}
| WelcomeHUME/svn-caucho-com-resin | modules/resin/src/com/caucho/ejb/cfg/EjbJar.java | Java | gpl-2.0 | 5,125 |
function test() {
return (function foo(){}).name === 'foo' &&
(function(){}).name === '';
}
if (!test())
throw new Error("Test failed");
| Debian/openjfx | modules/web/src/main/native/Source/JavaScriptCore/tests/es6/function_name_property_function_expressions.js | JavaScript | gpl-2.0 | 153 |
FD40.ready(function($) {
var jQuery = $;// Catalan
jQuery.timeago.settings.strings = {
prefixAgo: "fa",
prefixFromNow: "d'aqui a",
suffixAgo: null,
suffixFromNow: null,
seconds: "menys d'1 minut",
minute: "1 minut",
minutes: "uns %d minuts",
hour: "1 hora",
hours: "unes %d hores",
day: "1 dia",
days: "%d dies",
month: "aproximadament un mes",
months: "%d mesos",
year: "aproximadament un any",
years: "%d anys"
};
}); | BetterBetterBetter/WheresWalden | media/foundry/4.0/scripts/timeago/ca.js | JavaScript | gpl-2.0 | 450 |
/*
* JCE Editor 2.2.4
* @package JCE
* @url http://www.joomlacontenteditor.net
* @copyright Copyright (C) 2006 - 2012 Ryan Demmer. All rights reserved
* @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html
* @date 16 July 2012
* 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.
*
* NOTE : Javascript files have been compressed for speed and can be uncompressed using http://jsbeautifier.org/
*/
tinyMCEPopup.requireLangPack();var ColorPicker={settings:{},init:function(){var self=this,ed=tinyMCEPopup.editor,color=tinyMCEPopup.getWindowArg('input_color')||'#FFFFFF';$('#tmp_color').val(color).colorpicker($.extend(this.settings,{dialog:false,insert:function(){return ColorPicker.insert();},close:function(){return tinyMCEPopup.close();}}));$('button#insert').button({icons:{primary:'ui-icon-check'}});$('#jce').css('display','block');},insert:function(){var color=$("#colorpicker_color").val(),f=tinyMCEPopup.getWindowArg('func');tinyMCEPopup.restoreSelection();if(f)
f(color);tinyMCEPopup.close();}};tinyMCEPopup.onInit.add(ColorPicker.init,ColorPicker); | ArtificialEX/jwexport | components/com_jce/editor/tiny_mce/themes/advanced/js/colorpicker.js | JavaScript | gpl-2.0 | 1,641 |
<?php
namespace Drupal\webform;
use Drupal\Core\Archiver\ArchiveTar;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Form\SubformState;
use Drupal\Core\StreamWrapper\StreamWrapperInterface;
use Drupal\Core\StreamWrapper\StreamWrapperManagerInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\webform\Entity\WebformSubmission;
use Drupal\webform\Plugin\WebformElementManagerInterface;
use Drupal\webform\Plugin\WebformExporterManagerInterface;
/**
* Webform submission exporter.
*/
class WebformSubmissionExporter implements WebformSubmissionExporterInterface {
use StringTranslationTrait;
/**
* The configuration object factory.
*
* @var \Drupal\Core\Config\ConfigFactoryInterface
*/
protected $configFactory;
/**
* File system service.
*
* @var \Drupal\Core\File\FileSystemInterface
*/
protected $fileSystem;
/**
* Webform submission storage.
*
* @var \Drupal\webform\WebformSubmissionStorageInterface
*/
protected $entityStorage;
/**
* The stream wrapper manager.
*
* @var \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface
*/
protected $streamWrapperManager;
/**
* Webform element manager.
*
* @var \Drupal\webform\Plugin\WebformElementManagerInterface
*/
protected $elementManager;
/**
* Results exporter manager.
*
* @var \Drupal\webform\Plugin\WebformExporterManagerInterface
*/
protected $exporterManager;
/**
* The webform.
*
* @var \Drupal\webform\WebformInterface
*/
protected $webform;
/**
* The source entity.
*
* @var \Drupal\Core\Entity\EntityInterface
*/
protected $sourceEntity;
/**
* The results exporter.
*
* @var \Drupal\webform\Plugin\WebformExporterInterface
*/
protected $exporter;
/**
* Default export options.
*
* @var array
*/
protected $defaultOptions;
/**
* Webform element types.
*
* @var array
*/
protected $elementTypes;
/**
* Constructs a WebformSubmissionExporter object.
*
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The configuration object factory.
* @param \Drupal\Core\File\FileSystemInterface $file_system
* File system service.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface $stream_wrapper_manager
* The stream wrapper manager.
* @param \Drupal\webform\Plugin\WebformElementManagerInterface $element_manager
* The webform element manager.
* @param \Drupal\webform\Plugin\WebformExporterManagerInterface $exporter_manager
* The results exporter manager.
*/
public function __construct(ConfigFactoryInterface $config_factory, FileSystemInterface $file_system, EntityTypeManagerInterface $entity_type_manager, StreamWrapperManagerInterface $stream_wrapper_manager, WebformElementManagerInterface $element_manager, WebformExporterManagerInterface $exporter_manager) {
$this->configFactory = $config_factory;
$this->fileSystem = $file_system;
$this->entityStorage = $entity_type_manager->getStorage('webform_submission');
$this->streamWrapperManager = $stream_wrapper_manager;
$this->elementManager = $element_manager;
$this->exporterManager = $exporter_manager;
}
/**
* {@inheritdoc}
*/
public function setWebform(WebformInterface $webform = NULL) {
$this->webform = $webform;
$this->defaultOptions = NULL;
$this->elementTypes = NULL;
}
/**
* {@inheritdoc}
*/
public function getWebform() {
return $this->webform;
}
/**
* {@inheritdoc}
*/
public function setSourceEntity(EntityInterface $entity = NULL) {
$this->sourceEntity = $entity;
}
/**
* {@inheritdoc}
*/
public function getSourceEntity() {
return $this->sourceEntity;
}
/**
* {@inheritdoc}
*/
public function getWebformOptions() {
$name = $this->getWebformOptionsName();
return $this->getWebform()->getState($name, []);
}
/**
* {@inheritdoc}
*/
public function setWebformOptions(array $options = []) {
$name = $this->getWebformOptionsName();
$this->getWebform()->setState($name, $options);
}
/**
* {@inheritdoc}
*/
public function deleteWebformOptions() {
$name = $this->getWebformOptionsName();
$this->getWebform()->deleteState($name);
}
/**
* Get options name for current webform and source entity.
*
* @return string
* Settings name as 'webform.export.{entity_type}.{entity_id}'.
*/
protected function getWebformOptionsName() {
if ($entity = $this->getSourceEntity()) {
return 'results.export.' . $entity->getEntityTypeId() . '.' . $entity->id();
}
else {
return 'results.export';
}
}
/**
* {@inheritdoc}
*/
public function setExporter(array $export_options = []) {
$export_options += $this->getDefaultExportOptions();
$export_options['webform'] = $this->getWebform();
$export_options['source_entity'] = $this->getSourceEntity();
$this->exporter = $this->exporterManager->createInstance($export_options['exporter'], $export_options);
return $this->exporter;
}
/**
* {@inheritdoc}
*/
public function getExporter() {
return $this->exporter;
}
/**
* {@inheritdoc}
*/
public function getExportOptions() {
return $this->getExporter()->getConfiguration();
}
/****************************************************************************/
// Default options and webform.
/****************************************************************************/
/**
* {@inheritdoc}
*/
public function getDefaultExportOptions() {
if (isset($this->defaultOptions)) {
return $this->defaultOptions;
}
$this->defaultOptions = [
'exporter' => 'delimited',
'delimiter' => ',',
'multiple_delimiter' => ';',
'excel' => FALSE,
'file_name' => 'submission-[webform_submission:serial]',
'header_format' => 'label',
'header_prefix' => TRUE,
'header_prefix_label_delimiter' => ': ',
'header_prefix_key_delimiter' => '__',
'excluded_columns' => [
'uuid' => 'uuid',
'token' => 'token',
'webform_id' => 'webform_id',
],
'entity_type' => '',
'entity_id' => '',
'range_type' => 'all',
'range_latest' => '',
'range_start' => '',
'range_end' => '',
'state' => 'all',
'sticky' => '',
'download' => TRUE,
'files' => FALSE,
];
// Append element handler default options.
$element_types = $this->getWebformElementTypes();
$element_handlers = $this->elementManager->getInstances();
foreach ($element_handlers as $element_type => $element_handler) {
if (empty($element_types) || isset($element_types[$element_type])) {
$this->defaultOptions += $element_handler->getExportDefaultOptions();
}
}
return $this->defaultOptions;
}
/**
* {@inheritdoc}
*/
public function buildExportOptionsForm(array &$form, FormStateInterface $form_state, array $export_options = []) {
$export_options += $this->getDefaultExportOptions();
$this->setExporter($export_options);
$webform = $this->getWebform();
// Get exporter and build #states.
$exporter_plugins = $this->exporterManager->getInstances($export_options);
$states_archive = ['invisible' => []];
$states_options = ['invisible' => []];
foreach ($exporter_plugins as $plugin_id => $exporter_plugin) {
if ($exporter_plugin->isArchive()) {
if ($states_archive['invisible']) {
$states_archive['invisible'][] = 'or';
}
$states_archive['invisible'][] = [':input[name="exporter"]' => ['value' => $plugin_id]];
}
if (!$exporter_plugin->hasOptions()) {
if ($states_options['invisible']) {
$states_options['invisible'][] = 'or';
}
$states_options['invisible'][] = [':input[name="exporter"]' => ['value' => $plugin_id]];
}
}
$form['export']['format'] = [
'#type' => 'details',
'#title' => $this->t('Format options'),
'#open' => TRUE,
];
$form['export']['format']['exporter'] = [
'#type' => 'select',
'#title' => $this->t('Export format'),
'#options' => $this->exporterManager->getOptions(),
'#default_value' => $export_options['exporter'],
// Below .js-webform-exporter is used for exporter configuration form
// #states.
// @see \Drupal\webform\Plugin\WebformExporterBase::buildConfigurationForm
'#attributes' => ['class' => ['js-webform-exporter']],
];
foreach ($exporter_plugins as $plugin_id => $exporter) {
$subform_state = SubformState::createForSubform($form['export']['format'], $form, $form_state);
$form['export']['format'] = $exporter->buildConfigurationForm($form['export']['format'], $subform_state);
}
// Element.
$form['export']['element'] = [
'#type' => 'details',
'#title' => $this->t('Element options'),
'#open' => TRUE,
'#states' => $states_options,
];
$form['export']['element']['multiple_delimiter'] = [
'#type' => 'select',
'#title' => $this->t('Element multiple values delimiter'),
'#description' => $this->t('This is the delimiter when an element has multiple values.'),
'#required' => TRUE,
'#options' => [
';' => $this->t('Semicolon (;)'),
',' => $this->t('Comma (,)'),
'|' => $this->t('Pipe (|)'),
'.' => $this->t('Period (.)'),
' ' => $this->t('Space ()'),
],
'#default_value' => $export_options['multiple_delimiter'],
];
// Header.
$form['export']['header'] = [
'#type' => 'details',
'#title' => $this->t('Header options'),
'#open' => TRUE,
'#states' => $states_options,
];
$form['export']['header']['header_format'] = [
'#type' => 'radios',
'#title' => $this->t('Column header format'),
'#description' => $this->t('Choose whether to show the element label or element key in each column header.'),
'#required' => TRUE,
'#options' => [
'label' => $this->t('Element titles (label)'),
'key' => $this->t('Element keys (key)'),
],
'#default_value' => $export_options['header_format'],
];
$form['export']['header']['header_prefix'] = [
'#type' => 'checkbox',
'#title' => $this->t("Include an element's title with all sub elements and values in each column header."),
'#return_value' => TRUE,
'#default_value' => $export_options['header_prefix'],
];
$form['export']['header']['header_prefix_label_delimiter'] = [
'#type' => 'textfield',
'#title' => $this->t('Column header label delimiter'),
'#required' => TRUE,
'#default_value' => $export_options['header_prefix_label_delimiter'],
];
$form['export']['header']['header_prefix_key_delimiter'] = [
'#type' => 'textfield',
'#title' => $this->t('Column header key delimiter'),
'#required' => TRUE,
'#default_value' => $export_options['header_prefix_key_delimiter'],
];
if ($webform) {
$form['export']['header']['header_prefix_label_delimiter']['#states'] = [
'visible' => [
':input[name="header_prefix"]' => ['checked' => TRUE],
':input[name="header_format"]' => ['value' => 'label'],
],
];
$form['export']['header']['header_prefix_key_delimiter']['#states'] = [
'visible' => [
':input[name="header_prefix"]' => ['checked' => TRUE],
':input[name="header_format"]' => ['value' => 'key'],
],
];
}
// Build element specific export webforms.
// Grouping everything in $form['export']['elements'] so that element handlers can
// assign #weight to its export options webform.
$form['export']['elements'] = [
'#type' => 'container',
'#attributes' => ['class' => ['form-item']],
'#states' => $states_options,
];
$element_types = $this->getWebformElementTypes();
$element_handlers = $this->elementManager->getInstances();
foreach ($element_handlers as $element_type => $element_handler) {
if (empty($element_types) || isset($element_types[$element_type])) {
$subform_state = SubformState::createForSubform($form['export']['elements'], $form, $form_state);
$element_handler->buildExportOptionsForm($form['export']['elements'], $subform_state, $export_options);
}
}
// All the remain options are only applicable to a webform's export.
// @see Drupal\webform\Form\WebformResultsExportForm
if (!$webform) {
return;
}
// Elements.
$form['export']['columns'] = [
'#type' => 'details',
'#title' => $this->t('Column options'),
'#description' => $this->t('The selected columns will be included in the export.'),
'#states' => $states_options,
];
$form['export']['columns']['excluded_columns'] = [
'#type' => 'webform_excluded_columns',
'#webform_id' => $webform->id(),
'#default_value' => $export_options['excluded_columns'],
];
// Download options.
$form['export']['download'] = [
'#type' => 'details',
'#title' => $this->t('Download options'),
'#open' => TRUE,
];
$form['export']['download']['download'] = [
'#type' => 'checkbox',
'#title' => $this->t('Download export file'),
'#description' => $this->t('If checked, the export file will be automatically download to your local machine. If unchecked, the export file will be displayed as plain text within your browser.'),
'#return_value' => TRUE,
'#default_value' => $export_options['download'],
'#access' => !$this->requiresBatch(),
'#states' => $states_archive,
];
$form['export']['download']['files'] = [
'#type' => 'checkbox',
'#title' => $this->t('Download uploaded files'),
'#description' => $this->t('If checked, the exported file and any submission file uploads will be download in a gzipped tar file.'),
'#return_value' => TRUE,
'#default_value' => ($webform->hasManagedFile()) ? $export_options['files'] : 0,
'#access' => $webform->hasManagedFile(),
'#states' => [
'invisible' => [
':input[name="download"]' => ['checked' => FALSE],
],
],
];
$source_entity = $this->getSourceEntity();
if (!$source_entity) {
$entity_types = $this->entityStorage->getSourceEntityTypes($webform);
if ($entity_types) {
$form['export']['download']['submitted'] = [
'#type' => 'item',
'#input' => FALSE,
'#title' => $this->t('Submitted to'),
'#description' => $this->t('Select the entity type and then enter the entity id.'),
'#field_prefix' => '<div class="container-inline">',
'#field_suffix' => '</div>',
];
$form['export']['download']['submitted']['entity_type'] = [
'#type' => 'select',
'#title' => $this->t('Entity type'),
'#title_display' => 'Invisible',
'#options' => ['' => $this->t('All')] + $entity_types,
'#default_value' => $export_options['entity_type'],
];
$form['export']['download']['submitted']['entity_id'] = [
'#type' => 'number',
'#title' => $this->t('Entity id'),
'#title_display' => 'Invisible',
'#min' => 1,
'#size' => 10,
'#default_value' => $export_options['entity_id'],
'#states' => [
'invisible' => [
':input[name="entity_type"]' => ['value' => ''],
],
],
];
}
}
$form['export']['download']['range_type'] = [
'#type' => 'select',
'#title' => $this->t('Limit to'),
'#options' => [
'all' => $this->t('All'),
'latest' => $this->t('Latest'),
'serial' => $this->t('Submission number'),
'sid' => $this->t('Submission ID'),
'date' => $this->t('Date'),
],
'#default_value' => $export_options['range_type'],
];
$form['export']['download']['latest'] = [
'#type' => 'container',
'#attributes' => ['class' => ['container-inline']],
'#states' => [
'visible' => [
':input[name="range_type"]' => ['value' => 'latest'],
],
],
'range_latest' => [
'#type' => 'number',
'#title' => $this->t('Number of submissions'),
'#min' => 1,
'#default_value' => $export_options['range_latest'],
],
];
$ranges = [
'serial' => ['#type' => 'number'],
'sid' => ['#type' => 'number'],
'date' => ['#type' => 'date'],
];
foreach ($ranges as $key => $range_element) {
$form['export']['download'][$key] = [
'#type' => 'container',
'#attributes' => ['class' => ['container-inline']],
'#tree' => TRUE,
'#states' => [
'visible' => [
':input[name="range_type"]' => ['value' => $key],
],
],
];
$form['export']['download'][$key]['range_start'] = $range_element + [
'#title' => $this->t('From'),
'#parents' => [$key, 'range_start'],
'#default_value' => $export_options['range_start'],
];
$form['export']['download'][$key]['range_end'] = $range_element + [
'#title' => $this->t('To'),
'#parents' => [$key, 'range_end'],
'#default_value' => $export_options['range_end'],
];
}
$form['export']['download']['sticky'] = [
'#type' => 'checkbox',
'#title' => $this->t('Starred/flagged submissions'),
'#description' => $this->t('If checked, only starred/flagged submissions will be downloaded. If unchecked, all submissions will downloaded.'),
'#return_value' => TRUE,
'#default_value' => $export_options['sticky'],
];
// If drafts are allowed, provide options to filter download based on
// submission state.
$form['export']['download']['state'] = [
'#type' => 'radios',
'#title' => $this->t('Submission state'),
'#default_value' => $export_options['state'],
'#options' => [
'all' => $this->t('Completed and draft submissions'),
'completed' => $this->t('Completed submissions only'),
'draft' => $this->t('Drafts only'),
],
'#access' => ($webform->getSetting('draft') != WebformInterface::DRAFT_NONE),
];
}
/**
* {@inheritdoc}
*/
public function getValuesFromInput(array $values) {
if (isset($values['range_type'])) {
$range_type = $values['range_type'];
$values['range_type'] = $range_type;
if (isset($values[$range_type])) {
$values += $values[$range_type];
}
}
// Make sure only support options are returned.
$values = array_intersect_key($values, $this->getDefaultExportOptions());
return $values;
}
/****************************************************************************/
// Generate and write.
/****************************************************************************/
/**
* {@inheritdoc}
*/
public function generate() {
$entity_ids = $this->getQuery()->execute();
$webform_submissions = WebformSubmission::loadMultiple($entity_ids);
$this->writeHeader();
$this->writeRecords($webform_submissions);
$this->writeFooter();
}
/**
* {@inheritdoc}
*/
public function writeHeader() {
// If building a new archive make sure to delete the exist archive.
if ($this->isArchive()) {
@unlink($this->getArchiveFilePath());
}
$this->getExporter()->createExport();
$this->getExporter()->writeHeader();
$this->getExporter()->closeExport();
}
/**
* {@inheritdoc}
*/
public function writeRecords(array $webform_submissions) {
$export_options = $this->getExportOptions();
$webform = $this->getWebform();
$is_archive = ($this->isArchive() && $export_options['files']);
$files_directories = [];
if ($is_archive) {
$archiver = new ArchiveTar($this->getArchiveFilePath(), 'gz');
$stream_wrappers = array_keys($this->streamWrapperManager->getNames(StreamWrapperInterface::WRITE_VISIBLE));
foreach ($stream_wrappers as $stream_wrapper) {
$files_directory = $this->fileSystem->realpath($stream_wrapper . '://webform/' . $webform->id());
$files_directories[] = $files_directory;
}
}
$this->getExporter()->openExport();
foreach ($webform_submissions as $webform_submission) {
if ($is_archive) {
foreach ($files_directories as $files_directory) {
$submission_directory = $files_directory . '/' . $webform_submission->id();
if (file_exists($submission_directory)) {
$file_name = $this->getSubmissionBaseName($webform_submission);
$archiver->addModify($submission_directory, $file_name, $submission_directory);
}
}
}
$this->getExporter()->writeSubmission($webform_submission);
}
$this->getExporter()->closeExport();
}
/**
* {@inheritdoc}
*/
public function writeFooter() {
$this->getExporter()->openExport();
$this->getExporter()->writeFooter();
$this->getExporter()->closeExport();
}
/**
* {@inheritdoc}
*/
public function writeExportToArchive() {
$export_file_path = $this->getExportFilePath();
if (file_exists($export_file_path)) {
$archive_file_path = $this->getArchiveFilePath();
$archiver = new ArchiveTar($archive_file_path, 'gz');
$archiver->addModify($export_file_path, $this->getBaseFileName(), $this->getFileTempDirectory());
@unlink($export_file_path);
}
}
/**
* {@inheritdoc}
*/
public function getQuery() {
$export_options = $this->getExportOptions();
$webform = $this->getWebform();
$source_entity = $this->getSourceEntity();
$query = $this->entityStorage->getQuery()->condition('webform_id', $webform->id());
// Filter by source entity or submitted to.
if ($source_entity) {
$query->condition('entity_type', $source_entity->getEntityTypeId());
$query->condition('entity_id', $source_entity->id());
}
elseif ($export_options['entity_type']) {
$query->condition('entity_type', $export_options['entity_type']);
if ($export_options['entity_id']) {
$query->condition('entity_id', $export_options['entity_id']);
}
}
// Filter by sid or date range.
switch ($export_options['range_type']) {
case 'serial':
if ($export_options['range_start']) {
$query->condition('serial', $export_options['range_start'], '>=');
}
if ($export_options['range_end']) {
$query->condition('serial', $export_options['range_end'], '<=');
}
break;
case 'sid':
if ($export_options['range_start']) {
$query->condition('sid', $export_options['range_start'], '>=');
}
if ($export_options['range_end']) {
$query->condition('sid', $export_options['range_end'], '<=');
}
break;
case 'date':
if ($export_options['range_start']) {
$query->condition('created', strtotime($export_options['range_start']), '>=');
}
if ($export_options['range_end']) {
$query->condition('created', strtotime('+1 day', strtotime($export_options['range_end'])), '<');
}
break;
}
// Filter by (completion) state.
switch ($export_options['state']) {
case 'draft':
$query->condition('in_draft', 1);
break;
case 'completed':
$query->condition('in_draft', 0);
break;
}
// Filter by sticky.
if ($export_options['sticky']) {
$query->condition('sticky', 1);
}
// Filter by latest.
if ($export_options['range_type'] == 'latest' && $export_options['range_latest']) {
// Clone the query and use it to get latest sid starting sid.
$latest_query = clone $query;
$latest_query->sort('sid', 'DESC');
$latest_query->range(0, (int) $export_options['range_latest']);
if ($latest_query_entity_ids = $latest_query->execute()) {
$query->condition('sid', end($latest_query_entity_ids), '>=');
}
}
// Sort by sid with the oldest one first.
$query->sort('sid', 'ASC');
return $query;
}
/**
* Get element types from a webform.
*
* @return array
* An array of element types from a webform.
*/
protected function getWebformElementTypes() {
if (isset($this->elementTypes)) {
return $this->elementTypes;
}
// If the webform is not set which only occurs on the admin settings webform,
// return an empty array.
if (!isset($this->webform)) {
return [];
}
$this->elementTypes = [];
$elements = $this->webform->getElementsDecodedAndFlattened();
// Always include 'entity_autocomplete' export settings which is used to
// expand a webform submission's entity references.
$this->elementTypes['entity_autocomplete'] = 'entity_autocomplete';
foreach ($elements as $element) {
if (isset($element['#type'])) {
$type = $this->elementManager->getElementPluginId($element);
$this->elementTypes[$type] = $type;
}
}
return $this->elementTypes;
}
/****************************************************************************/
// Summary and download.
/****************************************************************************/
/**
* {@inheritdoc}
*/
public function getTotal() {
return $this->getQuery()->count()->execute();
}
/**
* {@inheritdoc}
*/
public function getBatchLimit() {
return $this->configFactory->get('webform.settings')->get('batch.default_batch_export_size') ?: 500;
}
/**
* {@inheritdoc}
*/
public function requiresBatch() {
return ($this->getTotal() > $this->getBatchLimit()) ? TRUE : FALSE;
}
/**
* {@inheritdoc}
*/
public function getFileTempDirectory() {
return file_directory_temp();
}
/**
* {@inheritdoc}
*/
public function getSubmissionBaseName(WebformSubmissionInterface $webform_submission) {
return $this->getExporter()->getSubmissionBaseName($webform_submission);
}
/**
* {@inheritdoc}
*/
protected function getBaseFileName() {
return $this->getExporter()->getBaseFileName();
}
/**
* {@inheritdoc}
*/
public function getExportFilePath() {
return $this->getExporter()->getExportFilePath();
}
/**
* {@inheritdoc}
*/
public function getExportFileName() {
return $this->getExporter()->getExportFileName();
}
/**
* {@inheritdoc}
*/
public function getArchiveFilePath() {
return $this->getExporter()->getArchiveFilePath();
}
/**
* {@inheritdoc}
*/
public function getArchiveFileName() {
return $this->getExporter()->getArchiveFileName();
}
/**
* {@inheritdoc}
*/
public function isArchive() {
if ($this->getExporter()->isArchive()) {
return TRUE;
}
else {
$export_options = $this->getExportOptions();
return ($export_options['download'] && $export_options['files']);
}
}
/**
* {@inheritdoc}
*/
public function isBatch() {
return ($this->isArchive() || ($this->getTotal() >= $this->getBatchLimit()));
}
}
| msbtterswrth/mdspca-fosters | modules/webform/src/WebformSubmissionExporter.php | PHP | gpl-2.0 | 27,760 |
//-----------------------------------------------------------------------------
// Class: DummyAnimInstance
// Authors: Li, Xizhi
// Emails: LiXizhi@yeah.net
// Company: ParaEngine
// Date: 2014.9.21
//-----------------------------------------------------------------------------
#include "ParaEngine.h"
#include "ParaXModel/AnimTable.h"
#include "DummyAnimInstance.h"
/** @def default walking speed when no model is found. */
#define DEFAULT_WALK_SPEED 4.f
using namespace ParaEngine;
ParaEngine::CDummyAnimInstance::CDummyAnimInstance()
{
// since it is a singleton, we will never reference count it.
addref();
}
CDummyAnimInstance* ParaEngine::CDummyAnimInstance::GetInstance()
{
static CDummyAnimInstance s_instance;
return &s_instance;
}
void ParaEngine::CDummyAnimInstance::LoadAnimation(int nAnimID, float * fSpeed, bool bAppend /*= false*/)
{
if (fSpeed)
{
if (nAnimID == ANIM_STAND)
*fSpeed = 0.f;
else if (nAnimID == ANIM_WALK)
*fSpeed = DEFAULT_WALK_SPEED;
else if (nAnimID == ANIM_RUN)
*fSpeed = DEFAULT_WALK_SPEED*1.5f;
else if (nAnimID == ANIM_FLY)
*fSpeed = DEFAULT_WALK_SPEED*2.f;
else
*fSpeed = 0.f;
}
}
bool ParaEngine::CDummyAnimInstance::HasAnimId(int nAnimID)
{
return (nAnimID == ANIM_STAND || nAnimID == ANIM_WALK || nAnimID == ANIM_RUN || nAnimID == ANIM_FLY);
}
void ParaEngine::CDummyAnimInstance::GetSpeedOf(const char * sName, float * fSpeed)
{
int nAnimID = CAnimTable::GetAnimIDByName(sName);
if (fSpeed)
{
if (nAnimID == ANIM_STAND)
*fSpeed = 0.f;
else if (nAnimID == ANIM_WALK)
*fSpeed = DEFAULT_WALK_SPEED;
else if (nAnimID == ANIM_RUN)
*fSpeed = DEFAULT_WALK_SPEED*1.5f;
else if (nAnimID == ANIM_FLY)
*fSpeed = DEFAULT_WALK_SPEED*2.f;
else
*fSpeed = 0.f;
}
}
| hetter/NPLRuntime | Client/trunk/ParaEngineClient/3dengine/DummyAnimInstance.cpp | C++ | gpl-2.0 | 1,763 |
package emu.project64.input;
import java.util.Set;
import emu.project64.AndroidDevice;
import emu.project64.input.map.TouchMap;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.graphics.Point;
import android.os.Vibrator;
import android.util.SparseIntArray;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
/**
* A class for generating N64 controller commands from a touchscreen.
*/
public class TouchController extends AbstractController implements OnTouchListener
{
public interface OnStateChangedListener
{
/**
* Called after the analog stick values have changed.
*
* @param axisFractionX The x-axis fraction, between -1 and 1, inclusive.
* @param axisFractionY The y-axis fraction, between -1 and 1, inclusive.
*/
public void onAnalogChanged( float axisFractionX, float axisFractionY );
/**
* Called after auto-hold button state changed.
*
* @param pressed The auto-hold state.
* @param index The index of the auto-hold mask.
*/
public void onAutoHold( boolean pressed, int index );
}
public static final int AUTOHOLD_METHOD_DISABLED = 0;
public static final int AUTOHOLD_METHOD_LONGPRESS = 1;
public static final int AUTOHOLD_METHOD_SLIDEOUT = 2;
/** The number of milliseconds to wait before auto-holding (long-press method). */
private static final int AUTOHOLD_LONGPRESS_TIME = 1000;
/** The pattern vibration when auto-hold is engaged. */
private static final long[] AUTOHOLD_VIBRATE_PATTERN = { 0, 50, 50, 50 };
/** The number of milliseconds of vibration when pressing a key. */
private static final int FEEDBACK_VIBRATE_TIME = 50;
/** The maximum number of pointers to query. */
private static final int MAX_POINTER_IDS = 256;
/** The state change listener. */
private final OnStateChangedListener mListener;
/** The map from screen coordinates to N64 controls. */
private final TouchMap mTouchMap;
/** The map from pointer ids to N64 controls. */
private final SparseIntArray mPointerMap = new SparseIntArray();
/** The method used for auto-holding buttons. */
private final int mAutoHoldMethod;
/** The set of auto-holdable buttons. */
private final Set<Integer> mAutoHoldables;
/** Whether touchscreen feedback is enabled. */
private final boolean mTouchscreenFeedback;
/** The touch state of each pointer. True indicates down, false indicates up. */
private final boolean[] mTouchState = new boolean[MAX_POINTER_IDS];
/** The x-coordinate of each pointer, between 0 and (screenwidth-1), inclusive. */
private final int[] mPointerX = new int[MAX_POINTER_IDS];
/** The y-coordinate of each pointer, between 0 and (screenheight-1), inclusive. */
private final int[] mPointerY = new int[MAX_POINTER_IDS];
/** The pressed start time of each pointer. */
private final long[] mStartTime = new long[MAX_POINTER_IDS];
/** The time between press and release of each pointer. */
private final long[] mElapsedTime = new long[MAX_POINTER_IDS];
/**
* The identifier of the pointer associated with the analog stick. -1 indicates the stick has
* been released.
*/
private int mAnalogPid = -1;
/** The touch event source to listen to, or 0 to listen to all sources. */
private int mSourceFilter = 0;
private Vibrator mVibrator = null;
/**
* Instantiates a new touch controller.
*
* @param touchMap The map from touch coordinates to N64 controls.
* @param view The view receiving touch event data.
* @param listener The listener for controller state changes.
* @param vibrator The haptic feedback device. MUST BE NULL if vibrate permission not granted.
* @param autoHoldMethod The method for auto-holding buttons.
* @param touchscreenFeedback True if haptic feedback should be used.
* @param autoHoldableButtons The N64 commands that correspond to auto-holdable buttons.
*/
public TouchController( TouchMap touchMap, View view, OnStateChangedListener listener,
Vibrator vibrator, int autoHoldMethod, boolean touchscreenFeedback,
Set<Integer> autoHoldableButtons )
{
mListener = listener;
mTouchMap = touchMap;
mVibrator = vibrator;
mAutoHoldMethod = autoHoldMethod;
mTouchscreenFeedback = touchscreenFeedback;
mAutoHoldables = autoHoldableButtons;
view.setOnTouchListener( this );
}
/**
* Sets the touch event source filter.
*
* @param source The source to listen to, or 0 to listen to all sources.
*/
public void setSourceFilter( int source )
{
mSourceFilter = source;
}
/*
* (non-Javadoc)
*
* @see android.view.View.OnTouchListener#onTouch(android.view.View, android.view.MotionEvent)
*/
@SuppressLint( "ClickableViewAccessibility" )
@Override
@TargetApi( 9 )
public boolean onTouch( View view, MotionEvent event )
{
// Filter by source, if applicable
int source = AndroidDevice.IS_GINGERBREAD ? event.getSource() : 0;
if( mSourceFilter != 0 && mSourceFilter != source )
return false;
int action = event.getAction();
int actionCode = action & MotionEvent.ACTION_MASK;
int pid = -1;
switch( actionCode )
{
case MotionEvent.ACTION_POINTER_DOWN:
// A non-primary touch has been made
pid = event.getPointerId( action >> MotionEvent.ACTION_POINTER_INDEX_SHIFT );
mStartTime[pid] = System.currentTimeMillis();
mTouchState[pid] = true;
break;
case MotionEvent.ACTION_POINTER_UP:
// A non-primary touch has been released
pid = event.getPointerId( action >> MotionEvent.ACTION_POINTER_INDEX_SHIFT );
mElapsedTime[pid] = System.currentTimeMillis() - mStartTime[pid];
mTouchState[pid] = false;
break;
case MotionEvent.ACTION_DOWN:
// A touch gesture has started (e.g. analog stick movement)
for( int i = 0; i < event.getPointerCount(); i++ )
{
pid = event.getPointerId( i );
mStartTime[pid] = System.currentTimeMillis();
mTouchState[pid] = true;
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
// A touch gesture has ended or canceled (e.g. analog stick movement)
for( int i = 0; i < event.getPointerCount(); i++ )
{
pid = event.getPointerId( i );
mElapsedTime[pid] = System.currentTimeMillis() - mStartTime[pid];
mTouchState[pid] = false;
}
break;
default:
break;
}
// Update the coordinates of down pointers and record max PID for speed
int maxPid = -1;
for( int i = 0; i < event.getPointerCount(); i++ )
{
pid = event.getPointerId( i );
if( pid > maxPid )
maxPid = pid;
if( mTouchState[pid] )
{
mPointerX[pid] = (int) event.getX( i );
mPointerY[pid] = (int) event.getY( i );
}
}
// Process each touch
processTouches( mTouchState, mPointerX, mPointerY, mElapsedTime, maxPid );
return true;
}
/**
* Sets the N64 controller state based on where the screen is (multi-) touched. Values outside
* the ranges listed below are safe.
*
* @param touchstate The touch state of each pointer. True indicates down, false indicates up.
* @param pointerX The x-coordinate of each pointer, between 0 and (screenwidth-1), inclusive.
* @param pointerY The y-coordinate of each pointer, between 0 and (screenheight-1), inclusive.
* @param maxPid Maximum ID of the pointers that have changed (speed optimization).
*/
private void processTouches( boolean[] touchstate, int[] pointerX, int[] pointerY,
long[] elapsedTime, int maxPid )
{
boolean analogMoved = false;
// Process each pointer in sequence
for( int pid = 0; pid <= maxPid; pid++ )
{
// Release analog if its pointer is not touching the screen
if( pid == mAnalogPid && !touchstate[pid] )
{
analogMoved = true;
mAnalogPid = -1;
mState.axisFractionX = 0;
mState.axisFractionY = 0;
}
// Process button inputs
if( pid != mAnalogPid )
processButtonTouch( touchstate[pid], pointerX[pid], pointerY[pid],
elapsedTime[pid], pid );
// Process analog inputs
if( touchstate[pid] && processAnalogTouch( pid, pointerX[pid], pointerY[pid] ) )
analogMoved = true;
}
// Call the super method to send the input to the core
notifyChanged();
// Update the skin if the virtual analog stick moved
if( analogMoved && mListener != null )
mListener.onAnalogChanged( mState.axisFractionX, mState.axisFractionY );
}
/**
* Process a touch as if intended for a button. Values outside the ranges listed below are safe.
*
* @param touched Whether the button is pressed or not.
* @param xLocation The x-coordinate of the touch, between 0 and (screenwidth-1), inclusive.
* @param yLocation The y-coordinate of the touch, between 0 and (screenheight-1), inclusive.
* @param pid The identifier of the touch pointer.
*/
private void processButtonTouch( boolean touched, int xLocation, int yLocation,
long timeElapsed, int pid )
{
// Determine the index of the button that was pressed
int index = touched
? mTouchMap.getButtonPress( xLocation, yLocation )
: mPointerMap.get( pid, TouchMap.UNMAPPED );
// Update the pointer map
if( !touched )
{
// Finger lifted off screen, forget what this pointer was touching
mPointerMap.delete( pid );
}
else
{
// Determine where the finger came from if is was slid
int prevIndex = mPointerMap.get( pid, TouchMap.UNMAPPED );
// Finger touched somewhere on screen, remember what this pointer is touching
mPointerMap.put( pid, index );
if( prevIndex != index )
{
// Finger slid from somewhere else, act accordingly
// There are three possibilities:
// - old button --> new button
// - nothing --> new button
// - old button --> nothing
// Reset this pointer's start time
mStartTime[pid] = System.currentTimeMillis();
if( prevIndex != TouchMap.UNMAPPED )
{
// Slid off a valid button
if( !isAutoHoldable( prevIndex ) || mAutoHoldMethod == AUTOHOLD_METHOD_DISABLED )
{
// Slid off a non-auto-hold button
setTouchState( prevIndex, false );
}
else
{
// Slid off an auto-hold button
switch( mAutoHoldMethod )
{
case AUTOHOLD_METHOD_LONGPRESS:
// Using long-press method, release auto-hold button
if( mListener != null )
mListener.onAutoHold( false, prevIndex );
setTouchState( prevIndex, false );
break;
case AUTOHOLD_METHOD_SLIDEOUT:
// Using slide-off method, engage auto-hold button
if( mVibrator != null )
{
mVibrator.cancel();
mVibrator.vibrate( AUTOHOLD_VIBRATE_PATTERN, -1 );
}
if( mListener != null )
mListener.onAutoHold( true, prevIndex );
setTouchState( prevIndex, true );
break;
}
}
}
}
}
if( index != TouchMap.UNMAPPED )
{
// Finger is on a valid button
// Provide simple vibration feedback for any valid button when first touched
if( touched && mTouchscreenFeedback && mVibrator != null )
{
boolean firstTouched;
if( index < NUM_N64_BUTTONS )
{
// Single button pressed
firstTouched = !mState.buttons[index];
}
else
{
// Two d-pad buttons pressed simultaneously
switch( index )
{
case TouchMap.DPD_RU:
firstTouched = !( mState.buttons[DPD_R] && mState.buttons[DPD_U] );
break;
case TouchMap.DPD_RD:
firstTouched = !( mState.buttons[DPD_R] && mState.buttons[DPD_D] );
break;
case TouchMap.DPD_LD:
firstTouched = !( mState.buttons[DPD_L] && mState.buttons[DPD_D] );
break;
case TouchMap.DPD_LU:
firstTouched = !( mState.buttons[DPD_L] && mState.buttons[DPD_U] );
break;
default:
firstTouched = false;
break;
}
}
if( firstTouched )
{
mVibrator.cancel();
mVibrator.vibrate( FEEDBACK_VIBRATE_TIME );
}
}
// Set the controller state accordingly
if( touched || !isAutoHoldable( index ) || mAutoHoldMethod == AUTOHOLD_METHOD_DISABLED )
{
// Finger just touched a button (any kind) OR
// Finger just lifted off non-auto-holdable button
setTouchState( index, touched );
// Do not provide auto-hold feedback yet
}
else
{
// Finger just lifted off an auto-holdable button
switch( mAutoHoldMethod )
{
case AUTOHOLD_METHOD_SLIDEOUT:
// Release auto-hold button if using slide-off method
if( mListener != null )
mListener.onAutoHold( false, index );
setTouchState( index, false );
break;
case AUTOHOLD_METHOD_LONGPRESS:
if( timeElapsed < AUTOHOLD_LONGPRESS_TIME )
{
// Release auto-hold if short-pressed
if( mListener != null )
mListener.onAutoHold( false, index );
setTouchState( index, false );
}
else
{
// Engage auto-hold if long-pressed
if( mVibrator != null )
{
mVibrator.cancel();
mVibrator.vibrate( AUTOHOLD_VIBRATE_PATTERN, -1 );
}
if( mListener != null )
mListener.onAutoHold( true, index );
setTouchState( index, true );
}
break;
}
}
}
}
/**
* Checks if the button mapped to an N64 command is auto-holdable.
*
* @param commandIndex The index to the N64 command.
*
* @return True if the button mapped to the command is auto-holdable.
*/
private boolean isAutoHoldable( int commandIndex )
{
return mAutoHoldables != null && mAutoHoldables.contains( commandIndex );
}
/**
* Sets the state of a button, and handles the D-Pad diagonals.
*
* @param index Which button is affected.
* @param touched Whether the button is pressed or not.
*/
private void setTouchState( int index, boolean touched )
{
// Set the button state
if( index < AbstractController.NUM_N64_BUTTONS )
{
// A single button was pressed
mState.buttons[index] = touched;
}
else
{
// Two d-pad buttons pressed simultaneously
switch( index )
{
case TouchMap.DPD_RU:
mState.buttons[DPD_R] = touched;
mState.buttons[DPD_U] = touched;
break;
case TouchMap.DPD_RD:
mState.buttons[DPD_R] = touched;
mState.buttons[DPD_D] = touched;
break;
case TouchMap.DPD_LD:
mState.buttons[DPD_L] = touched;
mState.buttons[DPD_D] = touched;
break;
case TouchMap.DPD_LU:
mState.buttons[DPD_L] = touched;
mState.buttons[DPD_U] = touched;
break;
default:
break;
}
}
}
/**
* Process a touch as if intended for the analog stick. Values outside the ranges listed below
* are safe.
*
* @param pointerId The pointer identifier.
* @param xLocation The x-coordinate of the touch, between 0 and (screenwidth-1), inclusive.
* @param yLocation The y-coordinate of the touch, between 0 and (screenheight-1), inclusive.
*
* @return True, if the analog state changed.
*/
private boolean processAnalogTouch( int pointerId, int xLocation, int yLocation )
{
// Get the cartesian displacement of the analog stick
Point point = mTouchMap.getAnalogDisplacement( xLocation, yLocation );
// Compute the pythagorean displacement of the stick
int dX = point.x;
int dY = point.y;
float displacement = (float) Math.sqrt( ( dX * dX ) + ( dY * dY ) );
// "Capture" the analog control
if( mTouchMap.isInCaptureRange( displacement ) )
mAnalogPid = pointerId;
if( pointerId == mAnalogPid )
{
// User is controlling the analog stick
// Limit range of motion to an octagon (like the real N64 controller)
point = mTouchMap.getConstrainedDisplacement( dX, dY );
dX = point.x;
dY = point.y;
displacement = (float) Math.sqrt( ( dX * dX ) + ( dY * dY ) );
// Fraction of full-throttle, between 0 and 1, inclusive
float p = mTouchMap.getAnalogStrength( displacement );
// Store the axis values in the super fields (screen y is inverted)
mState.axisFractionX = p * dX / displacement;
mState.axisFractionY = -p * dY / displacement;
// Analog state changed
return true;
}
// Analog state did not change
return false;
}
}
| shygoo/project64 | Android/app/src/main/java/emu/project64/input/TouchController.java | Java | gpl-2.0 | 20,746 |
/*
* Copyright 2008 ZXing authors
*
* 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.google.zxing.aztec;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.common.AbstractBlackBoxTestCase;
/**
* @author David Olivier
*/
public final class AztecBlackBox1TestCase extends AbstractBlackBoxTestCase {
public AztecBlackBox1TestCase() {
super("test/data/blackbox/aztec-1", new AztecReader(), BarcodeFormat.AZTEC);
addTest(12, 12, 0.0f);
addTest(12, 12, 90.0f);
addTest(12, 12, 180.0f);
addTest(12, 12, 270.0f);
}
} | faarwa/EngSocP5 | zxing/core/test/src/com/google/zxing/aztec/AztecBlackBox1TestCase.java | Java | gpl-3.0 | 1,076 |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace src\loader\utils;
defined('MOODLE_INTERNAL') || die();
class curl {
// This is just a dummy file to avoid failures in CI.
}
| CinecaElearning/moodle-logstore_xapi | src/loader/utils/filelib.php | PHP | gpl-3.0 | 830 |
/*
===========================================================================
Copyright (c) 2010-2014 Darkstar Dev Teams
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/
This file is part of DarkStar-server source code.
===========================================================================
*/
#include "../../common/socket.h"
#include <string.h>
#include "char_jobs.h"
#include "../entities/charentity.h"
CCharJobsPacket::CCharJobsPacket(CCharEntity * PChar)
{
this->type = 0x1B;
this->size = 0x32;
WBUFB(data,(0x04)-4) = PChar->look.race;
WBUFB(data,(0x08)-4) = PChar->GetMJob(); // подсвечиваем желтым главную профессию
WBUFB(data,(0x0B)-4) = PChar->GetSJob(); // подсвечиваем синим дополнительную профессию
memcpy(data+(0x0C)-4, &PChar->jobs, 22);
memcpy(data+(0x20)-4, &PChar->stats,14);
memcpy(data+(0x44)-4, &PChar->jobs, 27);
WBUFL(data,(0x3C)-4) = PChar->health.hp;
WBUFL(data,(0x40)-4) = PChar->health.mp;
WBUFL(data,(0x44)-4) = PChar->jobs.unlocked & 1; // первый бит в unlocked отвечает за дополнительную профессию
WBUFW(data,(0x60)-4) = PChar->m_EquipBlock; // заблокированные ячейки экипировки
//WBUFW(data,(0x62)-4) = blok; // битовое поле. занижение физических характеристик, характеристика становится красной и рядом появляется красная стрелка.
}
| FFXIOrgins/FFXIOrgins | src/map/packets/char_jobs.cpp | C++ | gpl-3.0 | 2,247 |
int r;
void turn(int i, int j, int x, int y, int z,int x0, int y0, int L, int W, int H) {
if (z==0) { int R = x*x+y*y; if (R<r) r=R;
} else {
if(i>=0 && i< 2) turn(i+1, j, x0+L+z, y, x0+L-x, x0+L, y0, H, W, L);
if(j>=0 && j< 2) turn(i, j+1, x, y0+W+z, y0+W-y, x0, y0+W, L, H, W);
if(i<=0 && i>-2) turn(i-1, j, x0-z, y, x-x0, x0-H, y0, H, W, L);
if(j<=0 && j>-2) turn(i, j-1, x, y0-z, y-y0, x0, y0-H, L, H, W);
}
}
int main(){
int L, H, W, x1, y1, z1, x2, y2, z2;
cin >> L >> W >> H >> x1 >> y1 >> z1 >> x2 >> y2 >> z2;
if (z1!=0 && z1!=H) if (y1==0 || y1==W)
swap(y1,z1), std::swap(y2,z2), std::swap(W,H);
else swap(x1,z1), std::swap(x2,z2), std::swap(L,H);
if (z1==H) z1=0, z2=H-z2;
r=0x3fffffff;
turn(0,0,x2-x1,y2-y1,z2,-x1,-y1,L,W,H);
cout<<r<<endl;
}
| kzoacn/Grimoire | Template/source/hints/长方体表面两点最短距离.cpp | C++ | gpl-3.0 | 802 |
/*
* 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.io.filefilter;
import java.io.File;
import java.io.Serializable;
import java.util.List;
import org.apache.commons.io.IOCase;
/**
* Filters filenames for a certain prefix.
* <p>
* For example, to print all files and directories in the
* current directory whose name starts with <code>Test</code>:
*
* <pre>
* File dir = new File(".");
* String[] files = dir.list( new PrefixFileFilter("Test") );
* for ( int i = 0; i < files.length; i++ ) {
* System.out.println(files[i]);
* }
* </pre>
*
* @since Commons IO 1.0
* @version $Revision: 1005099 $ $Date: 2010-10-06 17:13:01 +0100 (Wed, 06 Oct 2010) $
*
* @author Stephen Colebourne
* @author Federico Barbieri
* @author Serge Knystautas
* @author Peter Donald
* @see FileFilterUtils#prefixFileFilter(String)
* @see FileFilterUtils#prefixFileFilter(String, IOCase)
*/
public class PrefixFileFilter extends AbstractFileFilter implements Serializable {
/** The filename prefixes to search for */
private final String[] prefixes;
/** Whether the comparison is case sensitive. */
private final IOCase caseSensitivity;
/**
* Constructs a new Prefix file filter for a single prefix.
*
* @param prefix the prefix to allow, must not be null
* @throws IllegalArgumentException if the prefix is null
*/
public PrefixFileFilter(String prefix) {
this(prefix, IOCase.SENSITIVE);
}
/**
* Constructs a new Prefix file filter for a single prefix
* specifying case-sensitivity.
*
* @param prefix the prefix to allow, must not be null
* @param caseSensitivity how to handle case sensitivity, null means case-sensitive
* @throws IllegalArgumentException if the prefix is null
* @since Commons IO 1.4
*/
public PrefixFileFilter(String prefix, IOCase caseSensitivity) {
if (prefix == null) {
throw new IllegalArgumentException("The prefix must not be null");
}
this.prefixes = new String[] {prefix};
this.caseSensitivity = (caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity);
}
/**
* Constructs a new Prefix file filter for any of an array of prefixes.
* <p>
* The array is not cloned, so could be changed after constructing the
* instance. This would be inadvisable however.
*
* @param prefixes the prefixes to allow, must not be null
* @throws IllegalArgumentException if the prefix array is null
*/
public PrefixFileFilter(String[] prefixes) {
this(prefixes, IOCase.SENSITIVE);
}
/**
* Constructs a new Prefix file filter for any of an array of prefixes
* specifying case-sensitivity.
* <p>
* The array is not cloned, so could be changed after constructing the
* instance. This would be inadvisable however.
*
* @param prefixes the prefixes to allow, must not be null
* @param caseSensitivity how to handle case sensitivity, null means case-sensitive
* @throws IllegalArgumentException if the prefix is null
* @since Commons IO 1.4
*/
public PrefixFileFilter(String[] prefixes, IOCase caseSensitivity) {
if (prefixes == null) {
throw new IllegalArgumentException("The array of prefixes must not be null");
}
this.prefixes = new String[prefixes.length];
System.arraycopy(prefixes, 0, this.prefixes, 0, prefixes.length);
this.caseSensitivity = (caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity);
}
/**
* Constructs a new Prefix file filter for a list of prefixes.
*
* @param prefixes the prefixes to allow, must not be null
* @throws IllegalArgumentException if the prefix list is null
* @throws ClassCastException if the list does not contain Strings
*/
public PrefixFileFilter(List<String> prefixes) {
this(prefixes, IOCase.SENSITIVE);
}
/**
* Constructs a new Prefix file filter for a list of prefixes
* specifying case-sensitivity.
*
* @param prefixes the prefixes to allow, must not be null
* @param caseSensitivity how to handle case sensitivity, null means case-sensitive
* @throws IllegalArgumentException if the prefix list is null
* @throws ClassCastException if the list does not contain Strings
* @since Commons IO 1.4
*/
public PrefixFileFilter(List<String> prefixes, IOCase caseSensitivity) {
if (prefixes == null) {
throw new IllegalArgumentException("The list of prefixes must not be null");
}
this.prefixes = prefixes.toArray(new String[prefixes.size()]);
this.caseSensitivity = (caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity);
}
/**
* Checks to see if the filename starts with the prefix.
*
* @param file the File to check
* @return true if the filename starts with one of our prefixes
*/
@Override
public boolean accept(File file) {
String name = file.getName();
for (String prefix : this.prefixes) {
if (caseSensitivity.checkStartsWith(name, prefix)) {
return true;
}
}
return false;
}
/**
* Checks to see if the filename starts with the prefix.
*
* @param file the File directory
* @param name the filename
* @return true if the filename starts with one of our prefixes
*/
@Override
public boolean accept(File file, String name) {
for (String prefix : prefixes) {
if (caseSensitivity.checkStartsWith(name, prefix)) {
return true;
}
}
return false;
}
/**
* Provide a String representaion of this file filter.
*
* @return a String representaion
*/
@Override
public String toString() {
StringBuilder buffer = new StringBuilder();
buffer.append(super.toString());
buffer.append("(");
if (prefixes != null) {
for (int i = 0; i < prefixes.length; i++) {
if (i > 0) {
buffer.append(",");
}
buffer.append(prefixes[i]);
}
}
buffer.append(")");
return buffer.toString();
}
}
| tr4656/Hungry | src/org/apache/commons/io/filefilter/PrefixFileFilter.java | Java | gpl-3.0 | 7,155 |
/**
* This file is part of muCommander, http://www.mucommander.com
* Copyright (C) 2002-2010 Maxence Bernard
*
* muCommander is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* muCommander is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mucommander.commons.file.filter;
/**
* <code>PathFilter</code> is a {@link FileFilter} that operates on absolute file paths.
*
* @see AbstractPathFilter
* @author Maxence Bernard
*/
public interface PathFilter extends StringCriterionFilter {
}
| jorgevasquezp/mucommander | src/main/com/mucommander/commons/file/filter/PathFilter.java | Java | gpl-3.0 | 1,047 |
<?php
// Text
$_['text_title'] = 'Credit or Debit Card (Processed securely by Perpetual Payments)';
$_['text_credit_card'] = 'Credit Card Details';
$_['text_transaction'] = 'Transaction ID:';
$_['text_avs'] = 'AVS/CVV:';
$_['text_avs_full_match'] = 'Full match';
$_['text_avs_not_match'] = 'Not matched';
$_['text_authorisation'] = 'Authorisation code:';
// Entry
$_['entry_cc_number'] = 'Card Number';
$_['entry_cc_start_date'] = 'Card Valid From Date';
$_['entry_cc_expire_date'] = 'Card Expiry Date';
$_['entry_cc_cvv2'] = 'Card Security Code (CVV2)';
$_['entry_cc_issue'] = 'Card Issue Number';
// Help
$_['help_start_date'] = '(if available)';
$_['help_issue'] = '(for Maestro and Solo cards only)';
| mgraph/opencart | upload/catalog/language/english/payment/perpetual_payments.php | PHP | gpl-3.0 | 776 |
/**
* @file Visual mapping.
*/
define(function (require) {
var zrUtil = require('zrender/core/util');
var zrColor = require('zrender/tool/color');
var linearMap = require('../util/number').linearMap;
var each = zrUtil.each;
var isObject = zrUtil.isObject;
var CATEGORY_DEFAULT_VISUAL_INDEX = -1;
/**
* @param {Object} option
* @param {string} [option.type] See visualHandlers.
* @param {string} [option.mappingMethod] 'linear' or 'piecewise' or 'category' or 'fixed'
* @param {Array.<number>=} [option.dataExtent] [minExtent, maxExtent],
* required when mappingMethod is 'linear'
* @param {Array.<Object>=} [option.pieceList] [
* {value: someValue},
* {interval: [min1, max1], visual: {...}},
* {interval: [min2, max2]}
* ],
* required when mappingMethod is 'piecewise'.
* Visual for only each piece can be specified.
* @param {Array.<string|Object>=} [option.categories] ['cate1', 'cate2']
* required when mappingMethod is 'category'.
* If no option.categories, categories is set
* as [0, 1, 2, ...].
* @param {boolean} [option.loop=false] Whether loop mapping when mappingMethod is 'category'.
* @param {(Array|Object|*)} [option.visual] Visual data.
* when mappingMethod is 'category',
* visual data can be array or object
* (like: {cate1: '#222', none: '#fff'})
* or primary types (which represents
* defualt category visual), otherwise visual
* can be array or primary (which will be
* normalized to array).
*
*/
var VisualMapping = function (option) {
var mappingMethod = option.mappingMethod;
var visualType = option.type;
/**
* @readOnly
* @type {Object}
*/
var thisOption = this.option = zrUtil.clone(option);
/**
* @readOnly
* @type {string}
*/
this.type = visualType;
/**
* @readOnly
* @type {string}
*/
this.mappingMethod = mappingMethod;
/**
* @private
* @type {Function}
*/
this._normalizeData = normalizers[mappingMethod];
var visualHandler = visualHandlers[visualType];
/**
* @public
* @type {Function}
*/
this.applyVisual = visualHandler.applyVisual;
/**
* @public
* @type {Function}
*/
this.getColorMapper = visualHandler.getColorMapper;
/**
* @private
* @type {Function}
*/
this._doMap = visualHandler._doMap[mappingMethod];
if (mappingMethod === 'piecewise') {
normalizeVisualRange(thisOption);
preprocessForPiecewise(thisOption);
}
else if (mappingMethod === 'category') {
thisOption.categories
? preprocessForSpecifiedCategory(thisOption)
// categories is ordinal when thisOption.categories not specified,
// which need no more preprocess except normalize visual.
: normalizeVisualRange(thisOption, true);
}
else { // mappingMethod === 'linear' or 'fixed'
zrUtil.assert(mappingMethod !== 'linear' || thisOption.dataExtent);
normalizeVisualRange(thisOption);
}
};
VisualMapping.prototype = {
constructor: VisualMapping,
mapValueToVisual: function (value) {
var normalized = this._normalizeData(value);
return this._doMap(normalized, value);
},
getNormalizer: function () {
return zrUtil.bind(this._normalizeData, this);
}
};
var visualHandlers = VisualMapping.visualHandlers = {
color: {
applyVisual: makeApplyVisual('color'),
/**
* Create a mapper function
* @return {Function}
*/
getColorMapper: function () {
var thisOption = this.option;
return zrUtil.bind(
thisOption.mappingMethod === 'category'
? function (value, isNormalized) {
!isNormalized && (value = this._normalizeData(value));
return doMapCategory.call(this, value);
}
: function (value, isNormalized, out) {
// If output rgb array
// which will be much faster and useful in pixel manipulation
var returnRGBArray = !!out;
!isNormalized && (value = this._normalizeData(value));
out = zrColor.fastMapToColor(value, thisOption.parsedVisual, out);
return returnRGBArray ? out : zrColor.stringify(out, 'rgba');
},
this
);
},
_doMap: {
linear: function (normalized) {
return zrColor.stringify(
zrColor.fastMapToColor(normalized, this.option.parsedVisual),
'rgba'
);
},
category: doMapCategory,
piecewise: function (normalized, value) {
var result = getSpecifiedVisual.call(this, value);
if (result == null) {
result = zrColor.stringify(
zrColor.fastMapToColor(normalized, this.option.parsedVisual),
'rgba'
);
}
return result;
},
fixed: doMapFixed
}
},
colorHue: makePartialColorVisualHandler(function (color, value) {
return zrColor.modifyHSL(color, value);
}),
colorSaturation: makePartialColorVisualHandler(function (color, value) {
return zrColor.modifyHSL(color, null, value);
}),
colorLightness: makePartialColorVisualHandler(function (color, value) {
return zrColor.modifyHSL(color, null, null, value);
}),
colorAlpha: makePartialColorVisualHandler(function (color, value) {
return zrColor.modifyAlpha(color, value);
}),
opacity: {
applyVisual: makeApplyVisual('opacity'),
_doMap: makeDoMap([0, 1])
},
symbol: {
applyVisual: function (value, getter, setter) {
var symbolCfg = this.mapValueToVisual(value);
if (zrUtil.isString(symbolCfg)) {
setter('symbol', symbolCfg);
}
else if (isObject(symbolCfg)) {
for (var name in symbolCfg) {
if (symbolCfg.hasOwnProperty(name)) {
setter(name, symbolCfg[name]);
}
}
}
},
_doMap: {
linear: doMapToArray,
category: doMapCategory,
piecewise: function (normalized, value) {
var result = getSpecifiedVisual.call(this, value);
if (result == null) {
result = doMapToArray.call(this, normalized);
}
return result;
},
fixed: doMapFixed
}
},
symbolSize: {
applyVisual: makeApplyVisual('symbolSize'),
_doMap: makeDoMap([0, 1])
}
};
function preprocessForPiecewise(thisOption) {
var pieceList = thisOption.pieceList;
thisOption.hasSpecialVisual = false;
zrUtil.each(pieceList, function (piece, index) {
piece.originIndex = index;
// piece.visual is "result visual value" but not
// a visual range, so it does not need to be normalized.
if (piece.visual != null) {
thisOption.hasSpecialVisual = true;
}
});
}
function preprocessForSpecifiedCategory(thisOption) {
// Hash categories.
var categories = thisOption.categories;
var visual = thisOption.visual;
var categoryMap = thisOption.categoryMap = {};
each(categories, function (cate, index) {
categoryMap[cate] = index;
});
// Process visual map input.
if (!zrUtil.isArray(visual)) {
var visualArr = [];
if (zrUtil.isObject(visual)) {
each(visual, function (v, cate) {
var index = categoryMap[cate];
visualArr[index != null ? index : CATEGORY_DEFAULT_VISUAL_INDEX] = v;
});
}
else { // Is primary type, represents default visual.
visualArr[CATEGORY_DEFAULT_VISUAL_INDEX] = visual;
}
visual = setVisualToOption(thisOption, visualArr);
}
// Remove categories that has no visual,
// then we can mapping them to CATEGORY_DEFAULT_VISUAL_INDEX.
for (var i = categories.length - 1; i >= 0; i--) {
if (visual[i] == null) {
delete categoryMap[categories[i]];
categories.pop();
}
}
}
function normalizeVisualRange(thisOption, isCategory) {
var visual = thisOption.visual;
var visualArr = [];
if (zrUtil.isObject(visual)) {
each(visual, function (v) {
visualArr.push(v);
});
}
else if (visual != null) {
visualArr.push(visual);
}
var doNotNeedPair = {color: 1, symbol: 1};
if (!isCategory
&& visualArr.length === 1
&& !doNotNeedPair.hasOwnProperty(thisOption.type)
) {
// Do not care visualArr.length === 0, which is illegal.
visualArr[1] = visualArr[0];
}
setVisualToOption(thisOption, visualArr);
}
function makePartialColorVisualHandler(applyValue) {
return {
applyVisual: function (value, getter, setter) {
value = this.mapValueToVisual(value);
// Must not be array value
setter('color', applyValue(getter('color'), value));
},
_doMap: makeDoMap([0, 1])
};
}
function doMapToArray(normalized) {
var visual = this.option.visual;
return visual[
Math.round(linearMap(normalized, [0, 1], [0, visual.length - 1], true))
] || {};
}
function makeApplyVisual(visualType) {
return function (value, getter, setter) {
setter(visualType, this.mapValueToVisual(value));
};
}
function doMapCategory(normalized) {
var visual = this.option.visual;
return visual[
(this.option.loop && normalized !== CATEGORY_DEFAULT_VISUAL_INDEX)
? normalized % visual.length
: normalized
];
}
function doMapFixed() {
return this.option.visual[0];
}
function makeDoMap(sourceExtent) {
return {
linear: function (normalized) {
return linearMap(normalized, sourceExtent, this.option.visual, true);
},
category: doMapCategory,
piecewise: function (normalized, value) {
var result = getSpecifiedVisual.call(this, value);
if (result == null) {
result = linearMap(normalized, sourceExtent, this.option.visual, true);
}
return result;
},
fixed: doMapFixed
};
}
function getSpecifiedVisual(value) {
var thisOption = this.option;
var pieceList = thisOption.pieceList;
if (thisOption.hasSpecialVisual) {
var pieceIndex = VisualMapping.findPieceIndex(value, pieceList);
var piece = pieceList[pieceIndex];
if (piece && piece.visual) {
return piece.visual[this.type];
}
}
}
function setVisualToOption(thisOption, visualArr) {
thisOption.visual = visualArr;
if (thisOption.type === 'color') {
thisOption.parsedVisual = zrUtil.map(visualArr, function (item) {
return zrColor.parse(item);
});
}
return visualArr;
}
/**
* Normalizers by mapping methods.
*/
var normalizers = {
linear: function (value) {
return linearMap(value, this.option.dataExtent, [0, 1], true);
},
piecewise: function (value) {
var pieceList = this.option.pieceList;
var pieceIndex = VisualMapping.findPieceIndex(value, pieceList, true);
if (pieceIndex != null) {
return linearMap(pieceIndex, [0, pieceList.length - 1], [0, 1], true);
}
},
category: function (value) {
var index = this.option.categories
? this.option.categoryMap[value]
: value; // ordinal
return index == null ? CATEGORY_DEFAULT_VISUAL_INDEX : index;
},
fixed: zrUtil.noop
};
/**
* List available visual types.
*
* @public
* @return {Array.<string>}
*/
VisualMapping.listVisualTypes = function () {
var visualTypes = [];
zrUtil.each(visualHandlers, function (handler, key) {
visualTypes.push(key);
});
return visualTypes;
};
/**
* @public
*/
VisualMapping.addVisualHandler = function (name, handler) {
visualHandlers[name] = handler;
};
/**
* @public
*/
VisualMapping.isValidType = function (visualType) {
return visualHandlers.hasOwnProperty(visualType);
};
/**
* Convinent method.
* Visual can be Object or Array or primary type.
*
* @public
*/
VisualMapping.eachVisual = function (visual, callback, context) {
if (zrUtil.isObject(visual)) {
zrUtil.each(visual, callback, context);
}
else {
callback.call(context, visual);
}
};
VisualMapping.mapVisual = function (visual, callback, context) {
var isPrimary;
var newVisual = zrUtil.isArray(visual)
? []
: zrUtil.isObject(visual)
? {}
: (isPrimary = true, null);
VisualMapping.eachVisual(visual, function (v, key) {
var newVal = callback.call(context, v, key);
isPrimary ? (newVisual = newVal) : (newVisual[key] = newVal);
});
return newVisual;
};
/**
* @public
* @param {Object} obj
* @return {Oject} new object containers visual values.
* If no visuals, return null.
*/
VisualMapping.retrieveVisuals = function (obj) {
var ret = {};
var hasVisual;
obj && each(visualHandlers, function (h, visualType) {
if (obj.hasOwnProperty(visualType)) {
ret[visualType] = obj[visualType];
hasVisual = true;
}
});
return hasVisual ? ret : null;
};
/**
* Give order to visual types, considering colorSaturation, colorAlpha depends on color.
*
* @public
* @param {(Object|Array)} visualTypes If Object, like: {color: ..., colorSaturation: ...}
* IF Array, like: ['color', 'symbol', 'colorSaturation']
* @return {Array.<string>} Sorted visual types.
*/
VisualMapping.prepareVisualTypes = function (visualTypes) {
if (isObject(visualTypes)) {
var types = [];
each(visualTypes, function (item, type) {
types.push(type);
});
visualTypes = types;
}
else if (zrUtil.isArray(visualTypes)) {
visualTypes = visualTypes.slice();
}
else {
return [];
}
visualTypes.sort(function (type1, type2) {
// color should be front of colorSaturation, colorAlpha, ...
// symbol and symbolSize do not matter.
return (type2 === 'color' && type1 !== 'color' && type1.indexOf('color') === 0)
? 1 : -1;
});
return visualTypes;
};
/**
* 'color', 'colorSaturation', 'colorAlpha', ... are depends on 'color'.
* Other visuals are only depends on themself.
*
* @public
* @param {string} visualType1
* @param {string} visualType2
* @return {boolean}
*/
VisualMapping.dependsOn = function (visualType1, visualType2) {
return visualType2 === 'color'
? !!(visualType1 && visualType1.indexOf(visualType2) === 0)
: visualType1 === visualType2;
};
/**
* @param {number} value
* @param {Array.<Object>} pieceList [{value: ..., interval: [min, max]}, ...]
* Always from small to big.
* @param {boolean} [findClosestWhenOutside=false]
* @return {number} index
*/
VisualMapping.findPieceIndex = function (value, pieceList, findClosestWhenOutside) {
var possibleI;
var abs = Infinity;
// value has the higher priority.
for (var i = 0, len = pieceList.length; i < len; i++) {
var pieceValue = pieceList[i].value;
if (pieceValue != null) {
if (pieceValue === value
// FIXME
// It is supposed to compare value according to value type of dimension,
// but currently value type can exactly be string or number.
// Compromise for numeric-like string (like '12'), especially
// in the case that visualMap.categories is ['22', '33'].
|| (typeof pieceValue === 'string' && pieceValue === value + '')
) {
return i;
}
findClosestWhenOutside && updatePossible(pieceValue, i);
}
}
for (var i = 0, len = pieceList.length; i < len; i++) {
var piece = pieceList[i];
var interval = piece.interval;
var close = piece.close;
if (interval) {
if (interval[0] === -Infinity) {
if (littleThan(close[1], value, interval[1])) {
return i;
}
}
else if (interval[1] === Infinity) {
if (littleThan(close[0], interval[0], value)) {
return i;
}
}
else if (
littleThan(close[0], interval[0], value)
&& littleThan(close[1], value, interval[1])
) {
return i;
}
findClosestWhenOutside && updatePossible(interval[0], i);
findClosestWhenOutside && updatePossible(interval[1], i);
}
}
if (findClosestWhenOutside) {
return value === Infinity
? pieceList.length - 1
: value === -Infinity
? 0
: possibleI;
}
function updatePossible(val, index) {
var newAbs = Math.abs(val - value);
if (newAbs < abs) {
abs = newAbs;
possibleI = index;
}
}
};
function littleThan(close, a, b) {
return close ? a <= b : a < b;
}
return VisualMapping;
}); | mo-norant/FinHeartBel | website/node_modules/echarts/src/visual/VisualMapping.js | JavaScript | gpl-3.0 | 20,627 |
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.codeassist.impl;
import java.util.Iterator;
import java.util.Map;
import org.eclipse.jdt.core.compiler.CharOperation;
public class AssistOptions {
/**
* Option IDs
*/
public static final String OPTION_PerformVisibilityCheck =
"org.eclipse.jdt.core.codeComplete.visibilityCheck"; //$NON-NLS-1$
public static final String OPTION_ForceImplicitQualification =
"org.eclipse.jdt.core.codeComplete.forceImplicitQualification"; //$NON-NLS-1$
public static final String OPTION_FieldPrefixes =
"org.eclipse.jdt.core.codeComplete.fieldPrefixes"; //$NON-NLS-1$
public static final String OPTION_StaticFieldPrefixes =
"org.eclipse.jdt.core.codeComplete.staticFieldPrefixes"; //$NON-NLS-1$
public static final String OPTION_LocalPrefixes =
"org.eclipse.jdt.core.codeComplete.localPrefixes"; //$NON-NLS-1$
public static final String OPTION_ArgumentPrefixes =
"org.eclipse.jdt.core.codeComplete.argumentPrefixes"; //$NON-NLS-1$
public static final String OPTION_FieldSuffixes =
"org.eclipse.jdt.core.codeComplete.fieldSuffixes"; //$NON-NLS-1$
public static final String OPTION_StaticFieldSuffixes =
"org.eclipse.jdt.core.codeComplete.staticFieldSuffixes"; //$NON-NLS-1$
public static final String OPTION_LocalSuffixes =
"org.eclipse.jdt.core.codeComplete.localSuffixes"; //$NON-NLS-1$
public static final String OPTION_ArgumentSuffixes =
"org.eclipse.jdt.core.codeComplete.argumentSuffixes"; //$NON-NLS-1$
public static final String ENABLED = "enabled"; //$NON-NLS-1$
public static final String DISABLED = "disabled"; //$NON-NLS-1$
public boolean checkVisibility = false;
public boolean forceImplicitQualification = false;
public char[][] fieldPrefixes = null;
public char[][] staticFieldPrefixes = null;
public char[][] localPrefixes = null;
public char[][] argumentPrefixes = null;
public char[][] fieldSuffixes = null;
public char[][] staticFieldSuffixes = null;
public char[][] localSuffixes = null;
public char[][] argumentSuffixes = null;
/**
* Initializing the assist options with default settings
*/
public AssistOptions() {
// Initializing the assist options with default settings
}
/**
* Initializing the assist options with external settings
*/
public AssistOptions(Map settings) {
if (settings == null)
return;
// filter options which are related to the assist component
Iterator entries = settings.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry)entries.next();
if (!(entry.getKey() instanceof String))
continue;
if (!(entry.getValue() instanceof String))
continue;
String optionID = (String) entry.getKey();
String optionValue = (String) entry.getValue();
if (optionID.equals(OPTION_PerformVisibilityCheck)) {
if (optionValue.equals(ENABLED)) {
this.checkVisibility = true;
} else
if (optionValue.equals(DISABLED)) {
this.checkVisibility = false;
}
continue;
} else if (optionID.equals(OPTION_ForceImplicitQualification)) {
if (optionValue.equals(ENABLED)) {
this.forceImplicitQualification = true;
} else
if (optionValue.equals(DISABLED)) {
this.forceImplicitQualification = false;
}
continue;
} else if(optionID.equals(OPTION_FieldPrefixes)){
if (optionValue.length() == 0) {
this.fieldPrefixes = null;
} else {
this.fieldPrefixes = CharOperation.splitAndTrimOn(',', optionValue.toCharArray());
}
continue;
} else if(optionID.equals(OPTION_StaticFieldPrefixes)){
if (optionValue.length() == 0) {
this.staticFieldPrefixes = null;
} else {
this.staticFieldPrefixes = CharOperation.splitAndTrimOn(',', optionValue.toCharArray());
}
continue;
} else if(optionID.equals(OPTION_LocalPrefixes)){
if (optionValue.length() == 0) {
this.localPrefixes = null;
} else {
this.localPrefixes = CharOperation.splitAndTrimOn(',', optionValue.toCharArray());
}
continue;
} else if(optionID.equals(OPTION_ArgumentPrefixes)){
if (optionValue.length() == 0) {
this.argumentPrefixes = null;
} else {
this.argumentPrefixes = CharOperation.splitAndTrimOn(',', optionValue.toCharArray());
}
continue;
} else if(optionID.equals(OPTION_FieldSuffixes)){
if (optionValue.length() == 0) {
this.fieldSuffixes = null;
} else {
this.fieldSuffixes = CharOperation.splitAndTrimOn(',', optionValue.toCharArray());
}
continue;
} else if(optionID.equals(OPTION_StaticFieldSuffixes)){
if (optionValue.length() == 0) {
this.staticFieldSuffixes = null;
} else {
this.staticFieldSuffixes = CharOperation.splitAndTrimOn(',', optionValue.toCharArray());
}
continue;
} else if(optionID.equals(OPTION_LocalSuffixes)){
if (optionValue.length() == 0) {
this.localSuffixes = null;
} else {
this.localSuffixes = CharOperation.splitAndTrimOn(',', optionValue.toCharArray());
}
continue;
} else if(optionID.equals(OPTION_ArgumentSuffixes)){
if (optionValue.length() == 0) {
this.argumentSuffixes = null;
} else {
this.argumentSuffixes = CharOperation.splitAndTrimOn(',', optionValue.toCharArray());
}
continue;
}
}
}
} | Niky4000/UsefulUtils | projects/others/eclipse-platform-parent/eclipse.jdt.core-master/org.eclipse.jdt.core.tests.model/workspace/Formatter/test133/A_in.java | Java | gpl-3.0 | 5,799 |
var express = require('express')
var app = module.exports = express()
app.get('/404', require('lib/site/layout'))
app.get('*', function (req, res) {
res.redirect('/404')
})
| democracy-os-fr/democracyos | lib/site/error-pages/not-found/index.js | JavaScript | gpl-3.0 | 176 |
/**
* Copyright (C) 2013 - 2016 Johannes Taelman
*
* This file is part of Axoloti.
*
* Axoloti 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.
*
* Axoloti 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
* Axoloti. If not, see <http://www.gnu.org/licenses/>.
*/
package axoloti.menus;
import axoloti.MainFrame;
import java.io.File;
import java.io.FilenameFilter;
import java.util.Arrays;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
/**
*
* @author jtaelman
*/
public class PopulatePatchMenu {
static void PopulatePatchMenu(JMenu parent, String path, String ext) {
File dir = new File(path);
if (!dir.isDirectory()) {
JMenuItem mi = new JMenuItem("no help patches found");
mi.setEnabled(false);
parent.add(mi);
return;
}
final String extension = ext;
File[] files = dir.listFiles(new java.io.FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.isDirectory();
}
});
Arrays.sort(files);
for (File subdir : files) {
JMenu fm = new JMenu(subdir.getName());
PopulatePatchMenu(fm, subdir.getPath(), extension);
if (fm.getItemCount() > 0) {
parent.add(fm);
}
}
String filenames[] = dir.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return (name.endsWith(extension));
}
});
Arrays.sort(filenames);
for (String fn : filenames) {
String fn2 = fn.substring(0, fn.length() - 4);
JMenuItem fm = new JMenuItem(fn2);
fm.setActionCommand("open:" + path + File.separator + fn);
fm.addActionListener(MainFrame.mainframe);
parent.add(fm);
}
}
}
| dkmorb/axoloti | src/main/java/axoloti/menus/PopulatePatchMenu.java | Java | gpl-3.0 | 2,367 |
<?php
require_once($GLOBALS['g_campsiteDir'].'/classes/Input.php');
require_once($GLOBALS['g_campsiteDir'].'/classes/Attachment.php');
require_once($GLOBALS['g_campsiteDir'].'/classes/Log.php');
require_once LIBS_DIR . '/MediaList/MediaList.php';
require_once LIBS_DIR . '/MediaPlayer/MediaPlayer.php';
$f_attachment_id = Input::Get('f_attachment_id', 'int', 0);
$translator = \Zend_Registry::get('container')->getService('translator');
if (!Input::IsValid()) {
camp_html_goto_page("/$ADMIN/media-archive/index.php#files");
}
$em = \Zend_Registry::get('container')->getService('em');
$attachment = $em->getRepository('Newscoop\Entity\Attachment')->findOneById($f_attachment_id);
$attachmentService = \Zend_Registry::get('container')->getService('attachment');
$label_text = '';
$crumbs = array();
$crumbs[] = array($translator->trans('Content'), "");
$crumbs[] = array($translator->trans('Media Archive', array(), 'home'), "/$ADMIN/media-archive/index.php#files");
if ($g_user->hasPermission('ChangeImage')) {
$label_text = $translator->trans('Change attachment information', array(), 'media_archive');
}
else {
$label_text = $translator->trans('View attachment', array(), 'media_archive');
}
$crumbs[] = array($label_text, '');
$breadcrumbs = camp_html_breadcrumbs($crumbs);
$controller->view->headTitle($label_text.' - Newscoop Admin', 'SET');
echo $breadcrumbs;
?>
<?php camp_html_display_msgs(); ?>
<div class="wrapper"><div class="main-content-wrapper">
<h2><?php echo $attachment->getName(); ?></h2>
<p class="dates"><?php echo $translator->trans('Created', array(), 'media_archive'); ?>: <?php echo $attachment->getCreated()->format('Y-m-d H:i:s'); ?>, <?php echo $translator->trans('Last modified', array(), 'media_archive'); ?>: <?php echo $attachment->getUpdated()->format('Y-m-d H:i:s'); ?></p>
<?php echo new MediaPlayer($attachmentService->getAttachmentUrl($attachment) . '?g_show_in_browser=1', $attachment->getMimeType()); ?>
<dl class="attachment">
<dt><?php echo $translator->trans('Type'); ?>:</dt>
<dd><?php echo $attachment->getMimeType(); ?></dd>
<dt><?php echo $translator->trans('Size', array(), 'media_archive'); ?>:</dt>
<dd><?php echo MediaList::FormatFileSize($attachment->getSizeInBytes()); ?></dd>
<?php if ($attachment->getHttpCharset()) { ?>
<dt><?php echo $translator->trans('Charset', array(), 'media_archive'); ?>:</dt>
<dd><?php echo $attachment->getHttpCharset(); ?></dd>
<?php } ?>
</dl>
<form name="edit" method="POST" action="/<?php echo $ADMIN; ?>/media-archive/do_edit-attachment.php">
<?php echo SecurityToken::FormParameter(); ?>
<input type="hidden" name="f_attachment_id" value="<?php echo $attachment->getId(); ?>" />
<div class="ui-widget-content big-block block-shadow padded-strong">
<fieldset class="plain">
<legend><?php echo $translator->trans('Change attachment information', array(), 'media_archive'); ?></legend>
<ul>
<li>
<label for="description"><?php echo $translator->trans("Description"); ?>:</label>
<input id="description" type="text" name="f_description" value="<?php echo htmlspecialchars($attachment->getDescription()); ?>" size="50" maxlength="255" class="input_text" />
</li>
<li>
<label><?php echo $translator->trans("Do you want this file to open in the users browser, or to automatically download?", array(), 'media_archive'); ?></label>
<input id="disposition0" class="input_radio" type="radio" name="f_content_disposition" value=""<?php if ($attachment->getContentDisposition() == NULL) { echo ' checked="checked"'; } ?> />
<label for="disposition0" class="inline-style left-floated" style="padding-right:15px"><?php echo $translator->trans("Open in the browser", array(), 'media_archive'); ?></label>
<input id="disposition1" class="input_radio" type="radio" name="f_content_disposition" value="attachment"<?php if ($attachment->getContentDisposition() == 'attachment') { echo ' checked="checked"'; } ?> />
<label for="disposition1" class="inline-style left-floated"><?php echo $translator->trans("Automatically download", array(), 'media_archive'); ?></label>
</li>
<li>
<label> </label>
<input type="submit" name="Save" value="<?php echo $translator->trans('Save'); ?>" class="button" />
</li>
</ul>
</fieldset>
</div>
</form>
</div></div><!-- /.main-content-wrapper /.wrapper -->
<?php camp_html_copyright_notice(); ?>
</body>
</html>
| danielhjames/Newscoop | newscoop/admin-files/media-archive/edit-attachment.php | PHP | gpl-3.0 | 4,566 |
<?php
/**
* Hoa
*
*
* @license
*
* New BSD License
*
* Copyright © 2007-2017, Hoa community. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Hoa nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
namespace Hoa\Stream\Wrapper;
use Hoa\Stream;
/**
* Class \Hoa\Stream\Wrapper\Exception.
*
* Extending the \Hoa\Stream\Exception class.
*
* @copyright Copyright © 2007-2017 Hoa community
* @license New BSD License
*/
class Exception extends Stream\Exception
{
}
| collectiveaccess/providence | vendor/hoa/stream/Wrapper/Exception.php | PHP | gpl-3.0 | 1,926 |
<?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
class Google_Service_CloudKMS_AsymmetricSignResponse extends Google_Model
{
public $name;
public $signature;
public $signatureCrc32c;
public $verifiedDigestCrc32c;
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
public function setSignature($signature)
{
$this->signature = $signature;
}
public function getSignature()
{
return $this->signature;
}
public function setSignatureCrc32c($signatureCrc32c)
{
$this->signatureCrc32c = $signatureCrc32c;
}
public function getSignatureCrc32c()
{
return $this->signatureCrc32c;
}
public function setVerifiedDigestCrc32c($verifiedDigestCrc32c)
{
$this->verifiedDigestCrc32c = $verifiedDigestCrc32c;
}
public function getVerifiedDigestCrc32c()
{
return $this->verifiedDigestCrc32c;
}
}
| ftisunpar/BlueTape | vendor/google/apiclient-services/src/Google/Service/CloudKMS/AsymmetricSignResponse.php | PHP | gpl-3.0 | 1,469 |
using System.IO;
using System.Collections.Generic;
using System.Xml;
using PDollarGestureRecognizer;
namespace PDollarDemo
{
public class GestureIO
{
/// <summary>
/// Reads a multistroke gesture from an string representation of xml
/// </summary>
/// <param name="xml"></param>
/// <returns></returns>
public static Gesture ReadXMLGesture(string xml)
{
List<Point> points = new List<Point>();
XmlTextReader xmlReader = null;
int currentStrokeIndex = -1;
string gestureName = "";
try
{
xmlReader = new XmlTextReader(new StringReader(xml));
while (xmlReader.Read())
{
if (xmlReader.NodeType != XmlNodeType.Element) continue;
switch (xmlReader.Name)
{
case "Gesture":
gestureName = xmlReader["Name"];
if (gestureName.Contains("~")) // '~' character is specific to the naming convention of the MMG set
gestureName = gestureName.Substring(0, gestureName.LastIndexOf('~'));
if (gestureName.Contains("_")) // '_' character is specific to the naming convention of the MMG set
gestureName = gestureName.Replace('_', ' ');
break;
case "Stroke":
currentStrokeIndex++;
break;
case "Point":
points.Add(new Point(
float.Parse(xmlReader["X"]),
float.Parse(xmlReader["Y"]),
currentStrokeIndex
));
break;
}
}
}
finally
{
if (xmlReader != null)
xmlReader.Close();
}
return new Gesture(points.ToArray(), gestureName);
}
/// <summary>
/// Reads a multistroke gesture from an XML file
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public static Gesture ReadGesture(string fileName)
{
List<Point> points = new List<Point>();
XmlTextReader xmlReader = null;
int currentStrokeIndex = -1;
string gestureName = "";
try
{
xmlReader = new XmlTextReader(File.OpenText(fileName));
while (xmlReader.Read())
{
if (xmlReader.NodeType != XmlNodeType.Element) continue;
switch (xmlReader.Name)
{
case "Gesture":
gestureName = xmlReader["Name"];
if (gestureName.Contains("~")) // '~' character is specific to the naming convention of the MMG set
gestureName = gestureName.Substring(0, gestureName.LastIndexOf('~'));
if (gestureName.Contains("_")) // '_' character is specific to the naming convention of the MMG set
gestureName = gestureName.Replace('_', ' ');
break;
case "Stroke":
currentStrokeIndex++;
break;
case "Point":
points.Add(new Point(
float.Parse(xmlReader["X"]),
float.Parse(xmlReader["Y"]),
currentStrokeIndex
));
break;
}
}
}
finally
{
if (xmlReader != null)
xmlReader.Close();
}
return new Gesture(points.ToArray(), gestureName);
}
/// <summary>
/// Writes a multistroke gesture to an XML file
/// </summary>
public static void WriteGesture(PDollarGestureRecognizer.Point[] points, string gestureName, string fileName)
{
using (StreamWriter sw = new StreamWriter(fileName))
{
sw.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>");
sw.WriteLine("<Gesture Name = \"{0}\">", gestureName);
int currentStroke = -1;
for (int i = 0; i < points.Length; i++)
{
if (points[i].StrokeID != currentStroke)
{
if (i > 0)
sw.WriteLine("\t</Stroke>");
sw.WriteLine("\t<Stroke>");
currentStroke = points[i].StrokeID;
}
sw.WriteLine("\t\t<Point X = \"{0}\" Y = \"{1}\" T = \"0\" Pressure = \"0\" />",
points[i].X, points[i].Y
);
}
sw.WriteLine("\t</Stroke>");
sw.WriteLine("</Gesture>");
}
}
}
} | vmohan7/NaviTouch | NaviTouch/Assets/NaviSDK/PDollarGestureRecognizer/GestureIO.cs | C# | gpl-3.0 | 4,722 |
/**
* L2FProd.com Common Components 7.3 License.
*
* Copyright 2005-2007 L2FProd.com
*
* 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.l2fprod.common.swing.plaf;
/**
* Each new component type of the library will contribute an addon to
* the LookAndFeelAddons. A <code>ComponentAddon</code> is the
* equivalent of a {@link javax.swing.LookAndFeel}but focused on one
* component. <br>
*
* @author <a href="mailto:fred@L2FProd.com">Frederic Lavigne</a>
*/
public interface ComponentAddon {
/**
* @return the name of this addon
*/
String getName();
/**
* Initializes this addon (i.e register UI classes, colors, fonts,
* borders, any UIResource used by the component class). When
* initializing, the addon can register different resources based on
* the addon or the current look and feel.
*
* @param addon the current addon
*/
void initialize(LookAndFeelAddons addon);
/**
* Uninitializes this addon.
*
* @param addon
*/
void uninitialize(LookAndFeelAddons addon);
} | pabalexa/calibre2opds | OpdsOutput/src/main/java/com/l2fprod/common/swing/plaf/ComponentAddon.java | Java | gpl-3.0 | 1,604 |
<?php
/* ----------------------------------------------------------------------
* themes/default/views/ca_objects_browse_html.php :
* ----------------------------------------------------------------------
* CollectiveAccess
* Open-source collections management software
* ----------------------------------------------------------------------
*
* Software by Whirl-i-Gig (http://www.whirl-i-gig.com)
* Copyright 2009-2010 Whirl-i-Gig
*
* For more information visit http://www.CollectiveAccess.org
*
* This program is free software; you may redistribute it and/or modify it under
* the terms of the provided license as published by Whirl-i-Gig
*
* CollectiveAccess is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTIES whatsoever, including any implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* This source code is free and modifiable under the terms of
* GNU General Public License. (http://www.gnu.org/copyleft/gpl.html). See
* the "license.txt" file for details, or visit the CollectiveAccess web site at
* http://www.CollectiveAccess.org
*
* ----------------------------------------------------------------------
*/
$va_facets = $this->getVar('available_facets');
$va_facets_with_content = $this->getVar('facets_with_content');
$va_facet_info = $this->getVar('facet_info');
$va_criteria = is_array($this->getVar('criteria')) ? $this->getVar('criteria') : array();
$va_results = $this->getVar('result');
$vs_browse_ui_style = $this->request->config->get('browse_ui_style');
$vs_browse_target = $this->getVar('target');
?>
<div id="browse"><div id="resultBox">
<?php
# --- we need to calculate the height of the box using the number of facets.
$vn_num_facets = sizeof($va_facets_with_content)-1;
$vn_boxHeight = "";
$vn_boxHeight = 20 + ($vn_num_facets * 15);
?>
<div class="browseTargetSelect"><?php print _t('Browsing By:').' '.$this->getVar('browse_selector'); ?></div>
<div style="clear: both;"><!-- empty --></div>
<div style="position: relative;">
<div id="browseCriteria">
<?php
if (sizeof($va_criteria)) {
$vn_x = 0;
foreach($va_criteria as $vs_facet_name => $va_row_ids) {
foreach($va_row_ids as $vn_row_id => $vs_label) {
$vs_facet_label = (isset($va_facet_info[$vs_facet_name]['label_singular'])) ? unicode_ucfirst($va_facet_info[$vs_facet_name]['label_singular']) : '???';
?>
<div class="browseBox" ">
<div class="heading"><?php print $vs_facet_label; ?>:</div>
<?php
print "<div class='browsingBy'>{$vs_label}".caNavLink($this->request, 'x', 'close', '', 'Browse', 'removeCriteria', array('facet' => $vs_facet_name, 'id' => $vn_row_id))."</div>\n";
?>
</div>
<?php
$vn_x++;
if($vn_x < sizeof($va_criteria)){
?>
<div class="browseWith" >with</div>
<?php
}
}
}
if (sizeof($va_facets)) {
?>
<div class="browseArrow" ><img src='<?php print $this->request->getThemeUrlPath(); ?>/graphics/browseArrow.gif' width='24' height='16' border='0'></div>
<div class="browseBoxRefine" style="height:<?php print $vn_boxHeight; ?>px;">
<div class='heading'>Refine results by:</div>
<?php
$va_available_facets = $this->getVar('available_facets');
foreach($va_available_facets as $vs_facet_code => $va_facet_info) {
print "<div class='browseFacetLink'><a href='#' onclick='caUIBrowsePanel.showBrowsePanel(\"{$vs_facet_code}\");'>".$va_facet_info['label_plural']."</a></div>\n";
}
?>
<div class="startOver">or <?php print caNavLink($this->request, _t('start over'), '', '', 'Browse', 'clearCriteria', array()); ?></div>
</div>
<?php
} else {
?>
<div class="browseArrow" style="margin-top:<?php print ($vn_boxHeight/2)-4; ?>px;"><img src='<?php print $this->request->getThemeUrlPath(); ?>/graphics/browseArrow.gif' width='24' height='16' border='0'></div>
<div class="browseBoxRefine" style="height:<?php print $vn_boxHeight; ?>px;">
<div class="startOver" style="margin-top:0px;"><?php print caNavLink($this->request, _t('start over'), '', '', 'Browse', 'clearCriteria', array()); ?></div>
</div>
<?php
}
} else {
if (sizeof($va_facets)) {
?>
<div class="browseBoxRefine" style="height:<?php print $vn_boxHeight; ?>px;">
<div class="heading">Start browsing by:</div>
<?php
$va_available_facets = $this->getVar('available_facets');
foreach($va_available_facets as $vs_facet_code => $va_facet_info) {
print "<div class='browseFacetLink'><a href='#' onclick='caUIBrowsePanel.showBrowsePanel(\"{$vs_facet_code}\");'>".$va_facet_info['label_plural']."</a></div>\n";
}
?>
</div>
<?php
}
}
?>
<div style='clear:both;'><!-- empty --></div></div><!-- end browseCriteria -->
</div><!-- end position:relative -->
<?php
if (sizeof($va_criteria) == 0) {
print $this->render('Browse/browse_start_html.php');
} else {
print ($vs_paging_controls = $this->render('Results/paging_controls_html.php'));
print $this->render('Search/search_controls_html.php');
print "<div class='sectionBox'>";
print $this->render('Results/'.$vs_browse_target.'_results_'.$this->getVar('current_view').'_html.php');
print "</div>";
}
?>
</div><!-- end resultbox --></div><!-- end browse -->
<div id="splashBrowsePanel" class="browseSelectPanel" style="z-index:1000;">
<a href="#" onclick="caUIBrowsePanel.hideBrowsePanel()" class="browseSelectPanelButton"> </a>
<div id="splashBrowsePanelContent">
</div>
</div>
<script type="text/javascript">
var caUIBrowsePanel = caUI.initBrowsePanel({ facetUrl: '<?php print caNavUrl($this->request, '', 'Browse', 'getFacet'); ?>'});
//
// Handle browse header scrolling
//
jQuery(document).ready(function() {
jQuery("div.scrollableBrowseController").scrollable();
});
</script> | collectiveaccess/pawtucket | themes/white/views/Browse/browse_controls_html.php | PHP | gpl-3.0 | 5,886 |
#region netDxf library, Copyright (C) 2009-2018 Daniel Carvajal (haplokuon@gmail.com)
// netDxf library
// Copyright (C) 2009-2018 Daniel Carvajal (haplokuon@gmail.com)
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#endregion
using netDxf.Tables;
namespace netDxf.Objects
{
/// <summary>
/// Represents an underlay definition.
/// </summary>
public abstract class UnderlayDefinition :
TableObject
{
#region private fields
private readonly UnderlayType type;
private readonly string file;
#endregion
#region constructor
/// <summary>
/// Initializes a new instance of the <c>UnderlayDefinition</c> class.
/// </summary>
/// <param name="name">Underlay name.</param>
/// <param name="file">Underlay file name with full or relative path.</param>
/// <param name="type">Underlay type.</param>
protected UnderlayDefinition(string name, string file, UnderlayType type)
: base(name, DxfObjectCode.UnderlayDefinition, false)
{
this.file = file;
this.type = type;
switch (type)
{
case UnderlayType.DGN:
this.CodeName = DxfObjectCode.UnderlayDgnDefinition;
break;
case UnderlayType.DWF:
this.CodeName = DxfObjectCode.UnderlayDwfDefinition;
break;
case UnderlayType.PDF:
this.CodeName = DxfObjectCode.UnderlayPdfDefinition;
break;
}
}
#endregion
#region public properties
/// <summary>
/// Get the underlay type.
/// </summary>
public UnderlayType Type
{
get { return this.type; }
}
/// <summary>
/// Gets the underlay file.
/// </summary>
public string File
{
get { return this.file; }
}
#endregion
}
} | virtualrobotix/MissionPlanner | ExtLibs/netDxf/Objects/UnderlayDefinition.cs | C# | gpl-3.0 | 2,898 |
/*
* Copyright (C) 2010 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "core/html/forms/URLInputType.h"
#include "core/InputTypeNames.h"
#include "core/html/HTMLInputElement.h"
#include "core/html/parser/HTMLParserIdioms.h"
#include "platform/text/PlatformLocale.h"
namespace blink {
InputType* URLInputType::create(HTMLInputElement& element) {
return new URLInputType(element);
}
void URLInputType::countUsage() {
countUsageIfVisible(UseCounter::InputTypeURL);
}
const AtomicString& URLInputType::formControlType() const {
return InputTypeNames::url;
}
bool URLInputType::typeMismatchFor(const String& value) const {
return !value.isEmpty() && !KURL(KURL(), value).isValid();
}
bool URLInputType::typeMismatch() const {
return typeMismatchFor(element().value());
}
String URLInputType::typeMismatchText() const {
return locale().queryString(WebLocalizedString::ValidationTypeMismatchForURL);
}
String URLInputType::sanitizeValue(const String& proposedValue) const {
return BaseTextInputType::sanitizeValue(
stripLeadingAndTrailingHTMLSpaces(proposedValue));
}
String URLInputType::sanitizeUserInputValue(const String& proposedValue) const {
// Do not call URLInputType::sanitizeValue.
return BaseTextInputType::sanitizeValue(proposedValue);
}
} // namespace blink
| geminy/aidear | oss/qt/qt-everywhere-opensource-src-5.9.0/qtwebengine/src/3rdparty/chromium/third_party/WebKit/Source/core/html/forms/URLInputType.cpp | C++ | gpl-3.0 | 2,803 |
/*
* Copyright (c) 2011 Matthew Francis
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.itadaki.bzip2;
/**
* An in-place, length restricted Canonical Huffman code length allocator
*
* Based on the algorithm proposed by R. L. Milidiú, A. A. Pessoa and E. S. Laber in "In-place
* Length-Restricted Prefix Coding" (see: http://www-di.inf.puc-rio.br/~laber/public/spire98.ps)
* and incorporating additional ideas from the implementation of "shcodec" by Simakov Alexander
* (see: http://webcenter.ru/~xander/)
*/
public class HuffmanAllocator {
/**
* FIRST() function
* @param array The code length array
* @param i The input position
* @param nodesToMove The number of internal nodes to be relocated
* @return The smallest {@code k} such that {@code nodesToMove <= k <= i} and
* {@code i <= (array[k] % array.length)}
*/
private static int first (final int[] array, int i, final int nodesToMove) {
final int length = array.length;
final int limit = i;
int k = array.length - 2;
while ((i >= nodesToMove) && ((array[i] % length) > limit)) {
k = i;
i -= (limit - i + 1);
}
i = Math.max (nodesToMove - 1, i);
while (k > (i + 1)) {
int temp = (i + k) >> 1;
if ((array[temp] % length) > limit) {
k = temp;
} else {
i = temp;
}
}
return k;
}
/**
* Fills the code array with extended parent pointers
* @param array The code length array
*/
private static void setExtendedParentPointers (final int[] array) {
final int length = array.length;
array[0] += array[1];
for (int headNode = 0, tailNode = 1, topNode = 2; tailNode < (length - 1); tailNode++) {
int temp;
if ((topNode >= length) || (array[headNode] < array[topNode])) {
temp = array[headNode];
array[headNode++] = tailNode;
} else {
temp = array[topNode++];
}
if ((topNode >= length) || ((headNode < tailNode) && (array[headNode] < array[topNode]))) {
temp += array[headNode];
array[headNode++] = tailNode + length;
} else {
temp += array[topNode++];
}
array[tailNode] = temp;
}
}
/**
* Finds the number of nodes to relocate in order to achieve a given code length limit
* @param array The code length array
* @param maximumLength The maximum bit length for the generated codes
* @return The number of nodes to relocate
*/
private static int findNodesToRelocate (final int[] array, final int maximumLength) {
int currentNode = array.length - 2;
for (int currentDepth = 1; (currentDepth < (maximumLength - 1)) && (currentNode > 1); currentDepth++) {
currentNode = first (array, currentNode - 1, 0);
}
return currentNode;
}
/**
* A final allocation pass with no code length limit
* @param array The code length array
*/
private static void allocateNodeLengths (final int[] array) {
int firstNode = array.length - 2;
int nextNode = array.length - 1;
for (int currentDepth = 1, availableNodes = 2; availableNodes > 0; currentDepth++) {
final int lastNode = firstNode;
firstNode = first (array, lastNode - 1, 0);
for (int i = availableNodes - (lastNode - firstNode); i > 0; i--) {
array[nextNode--] = currentDepth;
}
availableNodes = (lastNode - firstNode) << 1;
}
}
/**
* A final allocation pass that relocates nodes in order to achieve a maximum code length limit
* @param array The code length array
* @param nodesToMove The number of internal nodes to be relocated
* @param insertDepth The depth at which to insert relocated nodes
*/
private static void allocateNodeLengthsWithRelocation (final int[] array, final int nodesToMove, final int insertDepth) {
int firstNode = array.length - 2;
int nextNode = array.length - 1;
int currentDepth = (insertDepth == 1) ? 2 : 1;
int nodesLeftToMove = (insertDepth == 1) ? nodesToMove - 2 : nodesToMove;
for (int availableNodes = currentDepth << 1; availableNodes > 0; currentDepth++) {
final int lastNode = firstNode;
firstNode = (firstNode <= nodesToMove) ? firstNode : first (array, lastNode - 1, nodesToMove);
int offset = 0;
if (currentDepth >= insertDepth) {
offset = Math.min (nodesLeftToMove, 1 << (currentDepth - insertDepth));
} else if (currentDepth == (insertDepth - 1)) {
offset = 1;
if ((array[firstNode]) == lastNode) {
firstNode++;
}
}
for (int i = availableNodes - (lastNode - firstNode + offset); i > 0; i--) {
array[nextNode--] = currentDepth;
}
nodesLeftToMove -= offset;
availableNodes = (lastNode - firstNode + offset) << 1;
}
}
/**
* Allocates Canonical Huffman code lengths in place based on a sorted frequency array
* @param array On input, a sorted array of symbol frequencies; On output, an array of Canonical
* Huffman code lengths
* @param maximumLength The maximum code length. Must be at least {@code ceil(log2(array.length))}
*/
public static void allocateHuffmanCodeLengths (final int[] array, final int maximumLength) {
switch (array.length) {
case 2:
array[1] = 1;
case 1:
array[0] = 1;
return;
}
/* Pass 1 : Set extended parent pointers */
setExtendedParentPointers (array);
/* Pass 2 : Find number of nodes to relocate in order to achieve maximum code length */
int nodesToRelocate = findNodesToRelocate (array, maximumLength);
/* Pass 3 : Generate code lengths */
if ((array[0] % array.length) >= nodesToRelocate) {
allocateNodeLengths (array);
} else {
int insertDepth = maximumLength - (32 - Integer.numberOfLeadingZeros (nodesToRelocate - 1));
allocateNodeLengthsWithRelocation (array, nodesToRelocate, insertDepth);
}
}
/**
* Non-instantiable
*/
private HuffmanAllocator() { }
}
| routeKIT/routeKIT | src/org/itadaki/bzip2/HuffmanAllocator.java | Java | gpl-3.0 | 6,762 |
/*
* #%~
* org.overture.ide.core
* %%
* Copyright (C) 2008 - 2014 Overture
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #~%
*/
package org.overture.ide.core.resources;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Vector;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.overture.ide.core.VdmCore;
import org.overture.ide.internal.core.ResourceManager;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class ModelBuildPath
{
final IVdmProject vdmProject;
final IProject project;
final File modelPathFile;
List<IContainer> srcPaths = new Vector<IContainer>();
IContainer output;
IContainer library;
public ModelBuildPath(IVdmProject project)
{
this.vdmProject = project;
this.project = (IProject) this.vdmProject.getAdapter(IProject.class);
IPath base = this.project.getLocation();
base = base.append(".modelpath");
this.modelPathFile = base.toFile();
this.output = this.project.getFolder("generated");
this.library = this.project.getFolder("lib");
parse();
}
private boolean hasModelPath()
{
return this.modelPathFile.exists();
}
private IContainer getDefaultModelSrcPath()
{
return this.project;
}
public List<IContainer> getModelSrcPaths()
{
List<IContainer> tmp = new Vector<IContainer>(srcPaths.size());
tmp.addAll(srcPaths);
return tmp;
}
public synchronized IContainer getOutput()
{
return this.output;
}
public synchronized IContainer getLibrary()
{
return this.library;
}
private synchronized void parse()
{
if (!hasModelPath())
{
srcPaths.add(getDefaultModelSrcPath());
return;
}
try
{
File file = this.modelPathFile;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
doc.getDocumentElement().normalize();
NodeList nodeLst = doc.getElementsByTagName("modelpathentry");
for (int s = 0; s < nodeLst.getLength(); s++)
{
Node fstNode = nodeLst.item(s);
if (fstNode.getNodeType() == Node.ELEMENT_NODE)
{
Node kindAttribute = fstNode.getAttributes().getNamedItem("kind");
String kindValue = kindAttribute.getNodeValue();
if (kindValue != null)
{
if (kindValue.equals("src"))
{
Node pathAttribute = fstNode.getAttributes().getNamedItem("path");
String pathValue = pathAttribute.getNodeValue();
if(pathValue.equals("."))
{
add(getDefaultModelSrcPath());
}else
{
add(this.project.getFolder(pathValue));
}
} else if (kindValue.equals("output"))
{
Node pathAttribute = fstNode.getAttributes().getNamedItem("path");
String pathValue = pathAttribute.getNodeValue();
output = this.project.getFolder(pathValue);
} else if (kindValue.equals("library"))
{
Node pathAttribute = fstNode.getAttributes().getNamedItem("path");
String pathValue = pathAttribute.getNodeValue();
library = this.project.getFolder(pathValue);
}
}
}
}
if(srcPaths.isEmpty())
{
srcPaths.add(getDefaultModelSrcPath());
}
} catch (Exception e)
{
VdmCore.log("Faild to parse .modelpath file", e);
}
}
public synchronized void setOutput(IContainer container)
{
this.output = container;
}
public synchronized void setLibrary(IContainer container)
{
this.library = container;
}
public synchronized void add(IContainer container)
{
if(container instanceof IProject)
{
srcPaths.clear();
}
else if(container instanceof IFolder)
{
String fullPath = container.getProjectRelativePath().toString();
boolean flag = true;
for (IContainer s : srcPaths)
{
flag = flag && s.getProjectRelativePath().toString().startsWith(fullPath);
}
if(flag)
srcPaths.clear();
}
if (!srcPaths.contains(container))
{
srcPaths.add(container);
}
}
public synchronized void remove(IContainer container)
{
if (srcPaths.contains(container))
{
srcPaths.remove(container);
}
}
public synchronized boolean contains(IContainer container)
{
return srcPaths.contains(container);
}
public synchronized void save() throws CoreException
{
StringBuffer sb = new StringBuffer();
sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
sb.append("<modelpath>\n");
for (IContainer src : srcPaths)
{
if (src.getProjectRelativePath().toString().length() > 0)
{
sb.append("\t<modelpathentry kind=\"src\" path=\""
+ src.getProjectRelativePath() + "\"/>\n");
}else if (src instanceof IProject)
{
sb.append("\t<modelpathentry kind=\"src\" path=\".\"/>\n");
}
}
if (output != null
&& output.getProjectRelativePath().toString().length() > 0)
{
sb.append("\t<modelpathentry kind=\"output\" path=\""
+ output.getProjectRelativePath() + "\"/>\n");
}
if (library != null
&& library.getProjectRelativePath().toString().length() > 0)
{
sb.append("\t<modelpathentry kind=\"library\" path=\""
+ library.getProjectRelativePath() + "\"/>\n");
}
sb.append("</modelpath>");
PrintWriter out = null;
try
{
FileWriter outFile = new FileWriter(this.modelPathFile);
out = new PrintWriter(outFile);
out.println(sb.toString());
} catch (IOException e)
{
VdmCore.log("Faild to save .modelpath file", e);
} finally
{
if (out != null)
{
out.close();
}
}
ResourceManager.getInstance().syncBuildPath(vdmProject);
}
/**
* Reload the build path and discard any un-saved changes
*/
public void reload()
{
parse();
}
}
| jmcPereira/overture | ide/core/src/main/java/org/overture/ide/core/resources/ModelBuildPath.java | Java | gpl-3.0 | 6,618 |
/* -*- c++ -*- */
/*
* Copyright 2013-2014 Free Software Foundation, Inc.
*
* This file is part of GNU Radio
*
* GNU Radio 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, or (at your option)
* any later version.
*
* GNU Radio is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GNU Radio; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "encoder_impl.h"
#include <gnuradio/io_signature.h>
#include <stdio.h>
namespace gr {
namespace fec {
encoder::sptr
encoder::make(generic_encoder::sptr my_encoder,
size_t input_item_size,
size_t output_item_size)
{
return gnuradio::get_initial_sptr
(new encoder_impl(my_encoder, input_item_size,
output_item_size));
}
encoder_impl::encoder_impl(generic_encoder::sptr my_encoder,
size_t input_item_size,
size_t output_item_size)
: block("fec_encoder",
io_signature::make(1, 1, input_item_size),
io_signature::make(1, 1, output_item_size)),
d_input_item_size(input_item_size),
d_output_item_size(output_item_size)
{
set_fixed_rate(true);
set_relative_rate((double)my_encoder->get_output_size()/(double)my_encoder->get_input_size());
set_output_multiple(my_encoder->get_output_size());
d_encoder = my_encoder;
d_input_size = d_encoder->get_input_size()*d_input_item_size;
d_output_size = d_encoder->get_output_size()*d_output_item_size;
}
encoder_impl::~encoder_impl()
{
}
int
encoder_impl::fixed_rate_ninput_to_noutput(int ninput)
{
return (int)(0.5 + ninput*relative_rate());
}
int
encoder_impl::fixed_rate_noutput_to_ninput(int noutput)
{
return (int)(0.5 + noutput/relative_rate());
}
void
encoder_impl::forecast(int noutput_items,
gr_vector_int& ninput_items_required)
{
ninput_items_required[0] = fixed_rate_noutput_to_ninput(noutput_items);
}
int
encoder_impl::general_work(int noutput_items,
gr_vector_int& ninput_items,
gr_vector_const_void_star &input_items,
gr_vector_void_star &output_items)
{
char *inbuffer = (char*)input_items[0];
char *outbuffer = (char*)output_items[0];
//GR_LOG_DEBUG(d_debug_logger, boost::format("%1%, %2%, %3%") \
// % noutput_items % ninput_items[0] % (noutput_items/output_multiple()));
for(int i = 0; i < noutput_items/output_multiple(); i++) {
d_encoder->generic_work((void*)(inbuffer+(i*d_input_size)),
(void*)(outbuffer+(i*d_output_size)));
}
//GR_LOG_DEBUG(d_debug_logger, boost::format("consuming: %1%") \
// % (fixed_rate_noutput_to_ninput(noutput_items)));
//GR_LOG_DEBUG(d_debug_logger, boost::format("returning: %1%") \
// % (noutput_items));
consume_each(fixed_rate_noutput_to_ninput(noutput_items));
return noutput_items;
}
} /* namespace fec */
} /* namespace gr */
| surligas/cs436-gnuradio | gr-fec/lib/encoder_impl.cc | C++ | gpl-3.0 | 3,746 |