repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
vitorbal/eslint
lib/rules/eol-last.js
1852
/** * @fileoverview Require file to end with single newline. * @author Nodeca Team <https://github.com/nodeca> */ "use strict"; //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ module.exports = { meta: { docs: { description: "enforce at least one newline at the end of files", category: "Stylistic Issues", recommended: false }, fixable: "whitespace", schema: [ { enum: ["unix", "windows"] } ] }, create: function(context) { //-------------------------------------------------------------------------- // Public //-------------------------------------------------------------------------- return { Program: function checkBadEOF(node) { const sourceCode = context.getSourceCode(), src = sourceCode.getText(), location = {column: 1}, linebreakStyle = context.options[0] || "unix", linebreak = linebreakStyle === "unix" ? "\n" : "\r\n"; if (src[src.length - 1] !== "\n") { // file is not newline-terminated location.line = src.split(/\n/g).length; context.report({ node: node, loc: location, message: "Newline required at end of file but not found.", fix: function(fixer) { return fixer.insertTextAfterRange([0, src.length], linebreak); } }); } } }; } };
mit
buksy/jnlua
src/main/java/com/naef/jnlua/script/LuaScriptEngineFactory.java
4298
/* * $Id: LuaScriptEngineFactory.java 38 2012-01-04 22:44:15Z andre@naef.com $ * See LICENSE.txt for license terms. */ package com.naef.jnlua.script; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.script.ScriptEngine; import javax.script.ScriptEngineFactory; import com.naef.jnlua.LuaState; /** * Lua script engine factory implementation conforming to JSR 223: Scripting for * the Java Platform. */ public class LuaScriptEngineFactory implements ScriptEngineFactory { // -- Static private static final String ENGINE_NAME = "JNLua"; private static final String LANGUAGE_NAME = "Lua"; private static final List<String> EXTENSIONS; private static final List<String> MIME_TYPES; private static final List<String> NAMES; static { // Extensions List<String> extensions = new ArrayList<String>(); extensions.add("lua"); EXTENSIONS = Collections.unmodifiableList(extensions); // MIME types List<String> mimeTypes = new ArrayList<String>(); mimeTypes.add("application/x-lua"); mimeTypes.add("text/x-lua"); MIME_TYPES = Collections.unmodifiableList(mimeTypes); // Names List<String> names = new ArrayList<String>(); names.add("lua"); names.add("Lua"); names.add("jnlua"); names.add("JNLua"); NAMES = Collections.unmodifiableList(names); } // -- Construction /** * Creates a new instance. */ public LuaScriptEngineFactory() { } // -- ScriptEngineFactory methods @Override public String getEngineName() { return ENGINE_NAME; } @Override public String getEngineVersion() { return LuaState.VERSION; } @Override public List<String> getExtensions() { return EXTENSIONS; } @Override public List<String> getMimeTypes() { return MIME_TYPES; } @Override public List<String> getNames() { return NAMES; } @Override public String getLanguageName() { return LANGUAGE_NAME; } @Override public String getLanguageVersion() { return LuaState.LUA_VERSION; } @Override public Object getParameter(String key) { if (key.equals(ScriptEngine.ENGINE)) { return getEngineName(); } if (key.equals(ScriptEngine.ENGINE_VERSION)) { return getEngineVersion(); } if (key.equals(ScriptEngine.NAME)) { return getNames().get(0); } if (key.equals(ScriptEngine.LANGUAGE)) { return getLanguageName(); } if (key.equals(ScriptEngine.LANGUAGE_VERSION)) { return getLanguageVersion(); } if (key.equals("THREADING")) { return "MULTITHREADED"; } return null; } @Override public String getMethodCallSyntax(String obj, String m, String... args) { StringBuffer sb = new StringBuffer(); sb.append(obj); sb.append(':'); sb.append(m); sb.append('('); for (int i = 0; i < args.length; i++) { if (i > 0) { sb.append(", "); } sb.append(args[i]); } sb.append(')'); return sb.toString(); } @Override public String getOutputStatement(String toDisplay) { StringBuffer sb = new StringBuffer(); sb.append("print("); quoteString(sb, toDisplay); sb.append(')'); return sb.toString(); } @Override public String getProgram(String... statements) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < statements.length; i++) { sb.append(statements[i]); sb.append("\n"); } return sb.toString(); } @Override public ScriptEngine getScriptEngine() { return new LuaScriptEngine(this); } // --Private methods /** * Quotes a string in double quotes. */ private void quoteString(StringBuffer sb, String s) { sb.append('"'); for (int i = 0; i < s.length(); i++) { switch (s.charAt(i)) { case '\u0007': sb.append("\\a"); break; case '\b': sb.append("\\b"); break; case '\f': sb.append("\\f"); break; case '\n': sb.append("\\n"); break; case '\r': sb.append("\\r"); break; case '\t': sb.append("\\t"); break; case '\u000b': sb.append("\\v"); break; case '\\': sb.append("\\\\"); break; case '"': sb.append("\\\""); break; default: sb.append(s.charAt(i)); } } sb.append('"'); } }
mit
Djamy/platform
src/Oro/Bundle/IntegrationBundle/Tests/Functional/Entity/IntegrationProcessTest.php
3913
<?php namespace Oro\Bundle\IntegrationBundle\Tests\Functional\Entity\Repository; use Doctrine\ORM\EntityManagerInterface; use Oro\Bundle\IntegrationBundle\Async\Topics; use Oro\Bundle\IntegrationBundle\Entity\Channel as Integration; use Oro\Bundle\IntegrationBundle\Tests\Functional\DataFixtures\LoadChannelData; use Oro\Bundle\MessageQueueBundle\Test\Functional\MessageQueueExtension; use Oro\Bundle\TestFrameworkBundle\Test\WebTestCase; use Oro\Bundle\UserBundle\Migrations\Data\ORM\LoadAdminUserData; use Oro\Component\MessageQueue\Client\MessagePriority; /** * @dbIsolationPerTest */ class IntegrationProcessTest extends WebTestCase { use MessageQueueExtension; public function setUp() { parent::setUp(); $this->initClient(); $this->loadFixtures([LoadChannelData::class]); } /** * test for schedule_integration process */ public function testShouldScheduleIntegrationSyncMessageOnCreate() { $userManager = self::getContainer()->get('oro_user.manager'); $admin = $userManager->findUserByEmail(LoadAdminUserData::DEFAULT_ADMIN_EMAIL); $integration = new Integration(); $integration->setName('aName'); $integration->setType('aType'); $integration->setEnabled(true); $integration->setDefaultUserOwner($admin); $integration->setOrganization($admin->getOrganization()); $this->getEntityManager()->persist($integration); $this->getEntityManager()->flush(); $traces = self::getMessageCollector()->getTopicSentMessages(Topics::SYNC_INTEGRATION); self::assertCount(1, $traces); self::assertEquals([ 'integration_id' => $integration->getId(), 'connector_parameters' => [], 'connector' => null, 'transport_batch_size' => 100, ], $traces[0]['message']->getBody()); self::assertEquals(MessagePriority::VERY_LOW, $traces[0]['message']->getPriority()); } /** * test for schedule_integration process */ public function testShouldNotScheduleIntegrationSyncMessageWhenChangongEnabledToFalse() { /** @var Integration $integration */ $integration = $this->getReference('oro_integration:foo_integration'); // guard self::assertTrue($integration->isEnabled()); $integration->setEnabled(false); $this->getEntityManager()->persist($integration); $this->getEntityManager()->flush(); $traces = self::getMessageCollector()->getTopicSentMessages(Topics::SYNC_INTEGRATION); self::assertCount(0, $traces); } /** * test for schedule_integration process */ public function testShouldNotScheduleIntegrationSyncMessageWhenChangongEnabledToTrue() { /** @var Integration $integration */ $integration = $this->getReference('oro_integration:foo_integration'); $integration->setEnabled(false); $this->getEntityManager()->persist($integration); $this->getEntityManager()->flush(); self::getMessageCollector()->clear(); $integration->setEnabled(true); $this->getEntityManager()->persist($integration); $this->getEntityManager()->flush(); $traces = self::getMessageCollector()->getTopicSentMessages(Topics::SYNC_INTEGRATION); self::assertCount(1, $traces); self::assertEquals([ 'integration_id' => $integration->getId(), 'connector_parameters' => [], 'connector' => null, 'transport_batch_size' => 100, ], $traces[0]['message']->getBody()); self::assertEquals(MessagePriority::VERY_LOW, $traces[0]['message']->getPriority()); } /** * @return EntityManagerInterface */ private function getEntityManager() { return self::getContainer()->get('doctrine.orm.entity_manager'); } }
mit
eldarion/braintree_python
tests/unit/test_subscription_search.py
1938
from tests.test_helper import * class TestSubscriptionSearch(unittest.TestCase): def test_billing_cycles_remaining_is_a_range_node(self): self.assertEquals(Search.RangeNodeBuilder, type(SubscriptionSearch.billing_cycles_remaining)) def test_days_past_due_is_a_range_node(self): self.assertEquals(Search.RangeNodeBuilder, type(SubscriptionSearch.days_past_due)) def test_id_is_a_text_node(self): self.assertEquals(Search.TextNodeBuilder, type(SubscriptionSearch.id)) def test_merchant_account_id_is_a_multiple_value_node(self): self.assertEquals(Search.MultipleValueNodeBuilder, type(SubscriptionSearch.merchant_account_id)) def test_plan_id_is_a_multiple_value_or_text_node(self): self.assertEquals(Search.MultipleValueOrTextNodeBuilder, type(SubscriptionSearch.plan_id)) def test_price_is_a_range_node(self): self.assertEquals(Search.RangeNodeBuilder, type(SubscriptionSearch.price)) def test_status_is_a_multiple_value_node(self): self.assertEquals(Search.MultipleValueNodeBuilder, type(SubscriptionSearch.status)) def test_in_trial_period_is_multiple_value_node(self): self.assertEquals(Search.MultipleValueNodeBuilder, type(SubscriptionSearch.in_trial_period)) def test_status_whitelist(self): SubscriptionSearch.status.in_list( Subscription.Status.Active, Subscription.Status.Canceled, Subscription.Status.Expired, Subscription.Status.PastDue ) @raises(AttributeError) def test_status_not_in_whitelist(self): SubscriptionSearch.status.in_list( Subscription.Status.Active, Subscription.Status.Canceled, Subscription.Status.Expired, "not a status" ) def test_ids_is_a_multiple_value_node(self): self.assertEquals(Search.MultipleValueNodeBuilder, type(SubscriptionSearch.ids))
mit
MontealegreLuis/php-testing-tools
ui/messaging/rector.php
1588
<?php declare(strict_types=1); /** * PHP version 7.4 * * This source file is subject to the license that is bundled with this package in the file LICENSE. */ use Rector\Core\Configuration\Option; use Rector\Set\ValueObject\SetList; use Rector\SOLID\Rector\Class_\ChangeReadOnlyVariableWithDefaultValueToConstantRector; use Rector\SOLID\Rector\ClassMethod\UseInterfaceOverImplementationInConstructorRector; use Rector\CodeQuality\Rector\If_\ExplicitBoolCompareRector; use Rector\SOLID\Rector\Class_\RepeatedLiteralToClassConstantRector; use Rector\SOLID\Rector\Property\ChangeReadOnlyPropertyWithDefaultValueToConstantRector; use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator; return static function (ContainerConfigurator $containerConfigurator): void { $parameters = $containerConfigurator->parameters(); $parameters->set(Option::PATHS, [ __DIR__ . '/src', ]); $parameters->set(Option::PHP_VERSION_FEATURES, '7.4'); $parameters->set(Option::AUTO_IMPORT_NAMES, true); // here we can define, what sets of rules will be applied $parameters->set(Option::SETS, [ SetList::CODE_QUALITY, SetList::PHP_74, SetList::SOLID, ]); $parameters->set(Option::EXCLUDE_RECTORS, [ UseInterfaceOverImplementationInConstructorRector::class, ExplicitBoolCompareRector::class, RepeatedLiteralToClassConstantRector::class, ChangeReadOnlyPropertyWithDefaultValueToConstantRector::class, ChangeReadOnlyVariableWithDefaultValueToConstantRector::class, ]); };
mit
michael-e/symphony-2
symphony/lib/core/class.configuration.php
9278
<?php /** * @package core */ /** * The Configuration class acts as a property => value store for settings * used throughout Symphony. The result of this class is a string containing * a PHP representation of the properties (and their values) set by the Configuration. * Symphony's configuration file is saved at `CONFIG`. The initial * file is generated by the Symphony installer, and then subsequent use of Symphony * loads in this file for each page view. Like minded properties can be grouped. */ class Configuration { /** * An associative array of the properties for this Configuration object * @var array */ private $_properties = array(); /** * Whether all properties and group keys will be forced to be lowercase. * By default this is false, which makes all properties case sensitive * @var boolean */ private $_forceLowerCase = false; /** * The string representing the tab characters used to serialize the configuration * @var string */ const TAB = ' '; /** * The constructor for the Configuration class takes one parameter, * `$forceLowerCase` which will make all property and * group names lowercase or not. By default they are left to the case * the user provides * * @param boolean $forceLowerCase * False by default, if true this will make all property and group names * lowercase */ public function __construct($forceLowerCase = false) { $this->_forceLowerCase = $forceLowerCase; } /** * Setter for the `$this->_properties`. The properties array * can be grouped to be an 'array' of an 'array' of properties. For instance * a 'region' key may be an array of 'properties' (that is name/value), or it * may be a 'value' itself. * * @param string $name * The name of the property to set, eg 'timezone' * @param array|string|integer|float|boolean $value * The value for the property to set, eg. '+10:00' * @param string $group * The group for this property, eg. 'region' */ public function set($name, $value, $group = null) { if ($this->_forceLowerCase) { $name = strtolower($name); $group = strtolower($group); } if ($group) { $this->_properties[$group][$name] = $value; } else { $this->_properties[$name] = $value; } } /** * A quick way to set a large number of properties. Given an associative * array or a nested associative array (where the key will be the group), * this function will merge the `$array` with the existing configuration. * By default the given `$array` will overwrite any existing keys unless * the `$overwrite` parameter is passed as false. * * @since Symphony 2.3.2 The `$overwrite` parameter is available * @param array $array * An associative array of properties, 'property' => 'value' or * 'group' => array('property' => 'value') * @param boolean $overwrite * An optional boolean parameter to indicate if it is safe to use array_merge * or if the provided array should be integrated using the 'set()' method * to avoid possible change collision. Defaults to false. */ public function setArray(array $array, $overwrite = false) { if ($overwrite) { $this->_properties = array_merge($this->_properties, $array); } else { foreach ($array as $set => $values) { foreach ($values as $key => $val) { self::set($key, $val, $set); } } } } /** * Accessor function for the `$this->_properties`. * * @param string $name * The name of the property to retrieve * @param string $group * The group that this property will be in * @return array|string|integer|float|boolean * If `$name` or `$group` are not * provided this function will return the full `$this->_properties` * array. */ public function get($name = null, $group = null) { // Return the whole array if no name or index is requested if (!$name && !$group) { return $this->_properties; } if ($this->_forceLowerCase) { $name = strtolower($name); $group = strtolower($group); } if ($group) { return (isset($this->_properties[$group][$name]) ? $this->_properties[$group][$name] : null); } return (isset($this->_properties[$name]) ? $this->_properties[$name] : null); } /** * The remove function will unset a property by `$name`. * It is possible to remove an entire 'group' by passing the group * name as the `$name` * * @param string $name * The name of the property to unset. This can also be the group name * @param string $group * The group of the property to unset */ public function remove($name, $group = null) { if ($this->_forceLowerCase) { $name = strtolower($name); $group = strtolower($group); } if ($group && isset($this->_properties[$group][$name])) { unset($this->_properties[$group][$name]); } elseif ($this->_properties[$name]) { unset($this->_properties[$name]); } } /** * Empties all the Configuration values by setting `$this->_properties` * to an empty array */ public function flush() { $this->_properties = array(); } /** * This magic `__toString` function converts the internal `$this->_properties` * array into a string representation. Symphony generates the `MANIFEST/config.php` * file in this manner. * @see Configuration::serializeArray() * @return string * A string that contains a array representation of `$this->_properties`. * This is used by Symphony to write the `config.php` file. */ public function __toString() { $string = 'array('; $tab = static::TAB; foreach ($this->_properties as $group => $data) { $string .= str_repeat(PHP_EOL, 3) . "$tab$tab###### ".strtoupper($group)." ######"; $group = addslashes($group); $string .= PHP_EOL . "$tab$tab'$group' => "; $string .= $this->serializeArray($data, 3, $tab); $string .= ","; $string .= PHP_EOL . "$tab$tab########"; } $string .= PHP_EOL . "$tab)"; return $string; } /** * The `serializeArray` function will properly format and indent multidimensional * arrays using recursivity. * * `__toString()` call `serializeArray` to use the recursive condition. * The keys (int) in array won't have apostrophe. * Array without multidimensional array will be output with normal indentation. * @return string * A string that contains a array representation of the '$data parameter'. * @param array $arr * A array of properties to serialize. * @param integer $indentation * The current level of indentation. * @param string $tab * A horizontal tab */ protected function serializeArray(array $arr, $indentation = 0, $tab = self::TAB) { $tabs = ''; $closeTabs = ''; for ($i = 0; $i < $indentation; $i++) { $tabs .= $tab; if ($i < $indentation - 1) { $closeTabs .= $tab; } } $string = 'array('; foreach ($arr as $key => $value) { $key = addslashes($key); $string .= (is_numeric($key) ? PHP_EOL . "$tabs $key => " : PHP_EOL . "$tabs'$key' => "); if (is_array($value)) { if (empty($value)) { $string .= 'array()'; } else { $string .= $this->serializeArray($value, $indentation + 1, $tab); } } else { $string .= (General::strlen($value) > 0 ? var_export($value, true) : 'null'); } $string .= ","; } $string .= PHP_EOL . "$closeTabs)"; return $string; } /** * Function will write the current Configuration object to * a specified `$file` with the given `$permissions`. * * @param string $file * the path of the file to write. * @param integer|null $permissions (optional) * the permissions as an octal number to set set on the resulting file. * If this is not provided it will use the permissions defined in [`write_mode`][`file`] * @return boolean */ public function write($file = null, $permissions = null) { if (is_null($permissions) && isset($this->_properties['file']['write_mode'])) { $permissions = $this->_properties['file']['write_mode']; } if (is_null($file)) { $file = CONFIG; } $tab = static::TAB; $eol = PHP_EOL; $string = "<?php$eol$tab\$settings = " . (string)$this . ";$eol"; return General::writeFile($file, $string, $permissions); } }
mit
mlennox/OpenNlp
SharpEntropy/IContextGenerator.cs
2590
//Copyright (C) 2005 Richard J. Northedge // // 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. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 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, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. //This file is based on the ContextGenerator.java source file found in the //original java implementation of MaxEnt. That source file contains the following header: // Copyright (C) 2001 Jason Baldridge and Gann Bierner // // 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. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU 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, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. using System; namespace SharpEntropy { /// <summary> /// Generate contexts for maximum entropy decisions. /// </summary> /// <author> /// Jason Baldridge /// </author> /// <author> /// Richard J. Northedge /// </author> /// <version> /// based on ContextGenerator.java, $Revision: 1.1.1.1 $, $Date: 2001/10/23 14:06:53 $ /// </version> public interface IContextGenerator { /// <summary> /// Builds up the list of contextual predicates given an object. /// </summary> string[] GetContext(object input); } /// <summary> /// Generate contexts for maximum entropy decisions. /// </summary> public interface IContextGenerator<T> { /// <summary> /// Builds up the list of contextual predicates given an object of type T. /// </summary> string[] GetContext(T input); } }
mit
MetaMemoryT/OTMql4Zmq
MQL4/Python/OTMql427/ZmqChart.py
2329
# -*-mode: python; py-indent-offset: 4; indent-tabs-mode: nil; encoding: utf-8-dos; coding: utf-8 -*- """ A ZmqChart object is a simple abstraction to encapsulate a Mt4 chart that has a ZeroMQ context on it. There should be only one context for the whole application, so it is set as the module variable oCONTEXT. """ import sys, logging import time import traceback oLOG = logging from Mq4Chart import Mq4Chart from ZmqListener import ZmqMixin # There's only one context in zmq oCONTEXT = None class ZmqChart(Mq4Chart, ZmqMixin): def __init__(self, sChartId, **dParams): global oCONTEXT self.sChartId = sChartId Mq4Chart.__init__(self, sChartId, **dParams) ZmqMixin.__init__(self, sChartId, **dParams) oCONTEXT = self.oContext assert oCONTEXT def eHeartBeat(self, iTimeout=0): """ The heartbeat is usually called from the Mt4 OnTimer. We push a simple Print exec command onto the queue of things for Mt4 to do if there's nothing else happening. This way we get a message in the Mt4 Log, but with a string made in Python. """ # while we are here flush stdout so we can read the log file # whilst the program is running print "receiving on the listener " sys.stdout.flush() if self.oReqRepSocket is None: self.eBindToRep() try: # default is zmq.NOBLOCK sBody = self.sRecvOnReqRep() except Exception as e: print "Error eHeartBeat on the listener " +str(e) print traceback.format_exc() sys.stdout.flush() raise if sBody: print "pushing eHeartBeat on the queue " + sBody self.eMq4PushQueue(sBody) elif self.oQueue.empty(): sTopic = 'ignore' sMark = "%15.5f" % time.time() sMess = "%s|%s|0|%s|Print|PY: %s" % (sTopic, self.sChartId, sMark, sMark,) print "only pushing on the queue as there is nothing to do" sys.stdout.flush() self.eMq4PushQueue(sMess) def iMain(): # OTZmqPublish is in OTMql4Zmq/bin from OTZmqPublish import iMain as iOTZmqPublishMain return iOTZmqPublishMain()
mit
leschzinerlab/AWS
external_software/relion/src/transformations.cpp
7407
/*************************************************************************** * * Author: "Sjors H.W. Scheres" * MRC Laboratory of Molecular Biology * * 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. * * This complete copyright notice must be included in any revised version of the * source code. Additional authorship citations may be added, but existing * author citations must be preserved. ***************************************************************************/ /*************************************************************************** * * Authors: Carlos Oscar S. Sorzano (coss@cnb.csic.es) * Sjors H.W. Scheres * * Unidad de Bioinformatica of Centro Nacional de Biotecnologia , CSIC * * 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 * * All comments concerning this program package may be sent to the * e-mail address 'xmipp@cnb.csic.es' ***************************************************************************/ #include "src/transformations.h" /* Rotation 2D ------------------------------------------------------------- */ void rotation2DMatrix(RFLOAT ang, Matrix2D< RFLOAT > &result, bool homogeneous) { RFLOAT cosine, sine; ang = DEG2RAD(ang); cosine = cos(ang); sine = sin(ang); if (homogeneous) { if (MAT_XSIZE(result)!=3 || MAT_YSIZE(result)!=3) result.resize(3,3); MAT_ELEM(result,0, 2) = 0; MAT_ELEM(result,1, 2) = 0; MAT_ELEM(result,2, 0) = 0; MAT_ELEM(result,2, 1) = 0; MAT_ELEM(result,2, 2) = 1; } else if (MAT_XSIZE(result)!=2 || MAT_YSIZE(result)!=2) result.resize(2,2); MAT_ELEM(result,0, 0) = cosine; MAT_ELEM(result,0, 1) = -sine; MAT_ELEM(result,1, 0) = sine; MAT_ELEM(result,1, 1) = cosine; } /* Translation 2D ---------------------------------------------------------- */ void translation2DMatrix(const Matrix1D<RFLOAT> &v, Matrix2D< RFLOAT > &result) { // if (VEC_XSIZE(v) != 2) // REPORT_ERROR("Translation2D_matrix: vector is not in R2"); result.initIdentity(3); MAT_ELEM(result,0, 2) = XX(v); MAT_ELEM(result,1, 2) = YY(v); } /* Rotation 3D around the system axes -------------------------------------- */ void rotation3DMatrix(RFLOAT ang, char axis, Matrix2D< RFLOAT > &result, bool homogeneous) { if (homogeneous) { result.initZeros(4,4); MAT_ELEM(result,3, 3) = 1; } else result.initZeros(3,3); RFLOAT cosine, sine; ang = DEG2RAD(ang); cosine = cos(ang); sine = sin(ang); switch (axis) { case 'Z': MAT_ELEM(result,0, 0) = cosine; MAT_ELEM(result,0, 1) = -sine; MAT_ELEM(result,1, 0) = sine; MAT_ELEM(result,1, 1) = cosine; MAT_ELEM(result,2, 2) = 1; break; case 'Y': MAT_ELEM(result,0, 0) = cosine; MAT_ELEM(result,0, 2) = -sine; MAT_ELEM(result,2, 0) = sine; MAT_ELEM(result,2, 2) = cosine; MAT_ELEM(result,1, 1) = 1; break; case 'X': MAT_ELEM(result,1, 1) = cosine; MAT_ELEM(result,1, 2) = -sine; MAT_ELEM(result,2, 1) = sine; MAT_ELEM(result,2, 2) = cosine; MAT_ELEM(result,0, 0) = 1; break; default: REPORT_ERROR("rotation3DMatrix: Unknown axis"); } } /* Align a vector with Z axis */ void alignWithZ(const Matrix1D<RFLOAT> &axis, Matrix2D<RFLOAT>& result, bool homogeneous) { if (axis.size() != 3) REPORT_ERROR("alignWithZ: Axis is not in R3"); if (homogeneous) { result.initZeros(4,4); MAT_ELEM(result,3, 3) = 1; } else result.initZeros(3,3); Matrix1D<RFLOAT> Axis(axis); Axis.selfNormalize(); // Compute length of the projection on YZ plane RFLOAT proj_mod = sqrt(YY(Axis) * YY(Axis) + ZZ(Axis) * ZZ(Axis)); if (proj_mod > XMIPP_EQUAL_ACCURACY) { // proj_mod!=0 // Build Matrix result, which makes the turning axis coincident with Z MAT_ELEM(result,0, 0) = proj_mod; MAT_ELEM(result,0, 1) = -XX(Axis) * YY(Axis) / proj_mod; MAT_ELEM(result,0, 2) = -XX(Axis) * ZZ(Axis) / proj_mod; MAT_ELEM(result,1, 0) = 0; MAT_ELEM(result,1, 1) = ZZ(Axis) / proj_mod; MAT_ELEM(result,1, 2) = -YY(Axis) / proj_mod; MAT_ELEM(result,2, 0) = XX(Axis); MAT_ELEM(result,2, 1) = YY(Axis); MAT_ELEM(result,2, 2) = ZZ(Axis); } else { // I know that the Axis is the X axis MAT_ELEM(result,0, 0) = 0; MAT_ELEM(result,0, 1) = 0; MAT_ELEM(result,0, 2) = -1; MAT_ELEM(result,1, 0) = 0; MAT_ELEM(result,1, 1) = 1; MAT_ELEM(result,1, 2) = 0; MAT_ELEM(result,2, 0) = 1; MAT_ELEM(result,2, 1) = 0; MAT_ELEM(result,2, 2) = 0; } } /* Rotation 3D around any axis -------------------------------------------- */ void rotation3DMatrix(RFLOAT ang, const Matrix1D<RFLOAT> &axis, Matrix2D<RFLOAT> &result, bool homogeneous) { // Compute a matrix which makes the turning axis coincident with Z // And turn around this axis Matrix2D<RFLOAT> A,R; alignWithZ(axis,A,homogeneous); rotation3DMatrix(ang, 'Z', R, homogeneous); result=A.transpose() * R * A; } /* Translation 3D ---------------------------------------------------------- */ void translation3DMatrix(const Matrix1D<RFLOAT> &v, Matrix2D<RFLOAT> &result) { if (VEC_XSIZE(v) != 3) REPORT_ERROR("Translation3D_matrix: vector is not in R3"); result.initIdentity(4); MAT_ELEM(result,0, 3) = XX(v); MAT_ELEM(result,1, 3) = YY(v); MAT_ELEM(result,2, 3) = ZZ(v); } /* Scale 3D ---------------------------------------------------------------- */ void scale3DMatrix(const Matrix1D<RFLOAT> &sc, Matrix2D<RFLOAT>& result, bool homogeneous) { if (VEC_XSIZE(sc) != 3) REPORT_ERROR("Scale3D_matrix: vector is not in R3"); if (homogeneous) { result.initZeros(4,4); MAT_ELEM(result,3, 3) = 1; } else result.initZeros(3,3); MAT_ELEM(result,0, 0) = XX(sc); MAT_ELEM(result,1, 1) = YY(sc); MAT_ELEM(result,2, 2) = ZZ(sc); }
mit
tagalpha/library
app/code/core/Mage/CatalogInventory/Helper/Minsaleqty.php
6224
<?php /** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@magento.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magento.com for more information. * * @category Mage * @package Mage_CatalogInventory * @copyright Copyright (c) 2006-2017 X.commerce, Inc. and affiliates (http://www.magento.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ /** * MinSaleQty value manipulation helper */ class Mage_CatalogInventory_Helper_Minsaleqty { /** * Retrieve fixed qty value * * @param mixed $qty * @return float|null */ protected function _fixQty($qty) { return (!empty($qty) ? (float)$qty : null); } /** * Generate a storable representation of a value * * @param mixed $value * @return string */ protected function _serializeValue($value) { if (is_numeric($value)) { $data = (float)$value; return (string)$data; } else if (is_array($value)) { $data = array(); foreach ($value as $groupId => $qty) { if (!array_key_exists($groupId, $data)) { $data[$groupId] = $this->_fixQty($qty); } } if (count($data) == 1 && array_key_exists(Mage_Customer_Model_Group::CUST_GROUP_ALL, $data)) { return (string)$data[Mage_Customer_Model_Group::CUST_GROUP_ALL]; } return serialize($data); } else { return ''; } } /** * Create a value from a storable representation * * @param mixed $value * @return array */ protected function _unserializeValue($value) { if (is_numeric($value)) { return array( Mage_Customer_Model_Group::CUST_GROUP_ALL => $this->_fixQty($value) ); } else if (is_string($value) && !empty($value)) { try { return Mage::helper('core/unserializeArray')->unserialize($value); } catch (Exception $e) { return array(); } } else { return array(); } } /** * Check whether value is in form retrieved by _encodeArrayFieldValue() * * @param mixed * @return bool */ protected function _isEncodedArrayFieldValue($value) { if (!is_array($value)) { return false; } unset($value['__empty']); foreach ($value as $_id => $row) { if (!is_array($row) || !array_key_exists('customer_group_id', $row) || !array_key_exists('min_sale_qty', $row)) { return false; } } return true; } /** * Encode value to be used in Mage_Adminhtml_Block_System_Config_Form_Field_Array_Abstract * * @param array * @return array */ protected function _encodeArrayFieldValue(array $value) { $result = array(); foreach ($value as $groupId => $qty) { $_id = Mage::helper('core')->uniqHash('_'); $result[$_id] = array( 'customer_group_id' => $groupId, 'min_sale_qty' => $this->_fixQty($qty), ); } return $result; } /** * Decode value from used in Mage_Adminhtml_Block_System_Config_Form_Field_Array_Abstract * * @param array * @return array */ protected function _decodeArrayFieldValue(array $value) { $result = array(); unset($value['__empty']); foreach ($value as $_id => $row) { if (!is_array($row) || !array_key_exists('customer_group_id', $row) || !array_key_exists('min_sale_qty', $row)) { continue; } $groupId = $row['customer_group_id']; $qty = $this->_fixQty($row['min_sale_qty']); $result[$groupId] = $qty; } return $result; } /** * Retrieve min_sale_qty value from config * * @param int $customerGroupId * @param mixed $store * @return float|null */ public function getConfigValue($customerGroupId, $store = null) { $value = Mage::getStoreConfig(Mage_CatalogInventory_Model_Stock_Item::XML_PATH_MIN_SALE_QTY, $store); $value = $this->_unserializeValue($value); if ($this->_isEncodedArrayFieldValue($value)) { $value = $this->_decodeArrayFieldValue($value); } $result = null; foreach ($value as $groupId => $qty) { if ($groupId == $customerGroupId) { $result = $qty; break; } else if ($groupId == Mage_Customer_Model_Group::CUST_GROUP_ALL) { $result = $qty; } } return $this->_fixQty($result); } /** * Make value readable by Mage_Adminhtml_Block_System_Config_Form_Field_Array_Abstract * * @param mixed $value * @return array */ public function makeArrayFieldValue($value) { $value = $this->_unserializeValue($value); if (!$this->_isEncodedArrayFieldValue($value)) { $value = $this->_encodeArrayFieldValue($value); } return $value; } /** * Make value ready for store * * @param mixed $value * @return string */ public function makeStorableArrayFieldValue($value) { if ($this->_isEncodedArrayFieldValue($value)) { $value = $this->_decodeArrayFieldValue($value); } $value = $this->_serializeValue($value); return $value; } }
mit
rdavaillaud/sfMediaLibraryPlugin-1.3
modules/sfMediaLibrary/templates/_files.php
464
<?php foreach ($files as $file => $info): $count++ ?> <div id="block_<?php echo $count ?>" class="assetImage"> <?php include_partial('sfMediaLibrary/block', array( 'name' => $file, 'current_path' => $currentDir, 'web_abs_current_path' => $webAbsCurrentDir, 'type' => 'file', 'info' => $info, 'count' => $count, )) ?> </div> <?php endforeach; ?>
mit
lexor90/node-compiler
node/test/parallel/test-stream-pipe-after-end.js
2506
// 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. 'use strict'; const common = require('../common'); const assert = require('assert'); const Readable = require('_stream_readable'); const Writable = require('_stream_writable'); const util = require('util'); util.inherits(TestReadable, Readable); function TestReadable(opt) { if (!(this instanceof TestReadable)) return new TestReadable(opt); Readable.call(this, opt); this._ended = false; } TestReadable.prototype._read = function() { if (this._ended) this.emit('error', new Error('_read called twice')); this._ended = true; this.push(null); }; util.inherits(TestWritable, Writable); function TestWritable(opt) { if (!(this instanceof TestWritable)) return new TestWritable(opt); Writable.call(this, opt); this._written = []; } TestWritable.prototype._write = function(chunk, encoding, cb) { this._written.push(chunk); cb(); }; // this one should not emit 'end' until we read() from it later. const ender = new TestReadable(); // what happens when you pipe() a Readable that's already ended? const piper = new TestReadable(); // pushes EOF null, and length=0, so this will trigger 'end' piper.read(); setTimeout(common.mustCall(function() { ender.on('end', common.mustCall()); const c = ender.read(); assert.strictEqual(c, null); const w = new TestWritable(); w.on('finish', common.mustCall()); piper.pipe(w); }), 1);
mit
ncarrillo/Perspex
src/Perspex.Themes.Default/TreeViewStyle.cs
2443
// Copyright (c) The Perspex Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System.Linq; using Perspex.Controls; using Perspex.Controls.Presenters; using Perspex.Controls.Primitives; using Perspex.Controls.Templates; using Perspex.Media; using Perspex.Styling; namespace Perspex.Themes.Default { /// <summary> /// The default style for the <see cref="TreeView"/> control. /// </summary> public class TreeViewStyle : Styles { /// <summary> /// Initializes a new instance of the <see cref="TreeViewStyle"/> class. /// </summary> public TreeViewStyle() { AddRange(new[] { new Style(x => x.OfType<TreeView>()) { Setters = new[] { new Setter(TemplatedControl.TemplateProperty, new ControlTemplate<TreeView>(Template)), new Setter(TemplatedControl.BorderBrushProperty, Brushes.Black), new Setter(TemplatedControl.BorderThicknessProperty, 1.0), }, }, }); } /// <summary> /// The default template for the <see cref="TreeView"/> control. /// </summary> /// <param name="control">The control being styled.</param> /// <returns>The root of the instantiated template.</returns> public static Control Template(TreeView control) { return new Border { Padding = new Thickness(4), [~Border.BackgroundProperty] = control[~TemplatedControl.BackgroundProperty], [~Border.BorderBrushProperty] = control[~TemplatedControl.BorderBrushProperty], [~Border.BorderThicknessProperty] = control[~TemplatedControl.BorderThicknessProperty], Child = new ScrollViewer { CanScrollHorizontally = true, Content = new ItemsPresenter { Name = "itemsPresenter", [~ItemsPresenter.ItemsProperty] = control[~ItemsControl.ItemsProperty], [~ItemsPresenter.ItemsPanelProperty] = control[~ItemsControl.ItemsPanelProperty], } } }; } } }
mit
ryanmcoble/LiveCoding.tv-Chat-Bot
node_modules/lctvbot/node_modules/node-xmpp-core/test/Connection.js
5259
'use strict' var assert = require('assert') , Connection = require('..').Connection , sinon = require('sinon') , net = require('net') , ltx = require('ltx') var PORT = 8084 //Tests create a server on this port to attach sockets to describe('Connection', function () { describe('socket config', function () { it('allows a socket to be provided', function () { var socket = new net.Socket() var conn = new Connection() conn.connect({socket: socket}) assert.equal(conn.socket, socket) }) it('allows a socket to be provided lazily', function () { var socket = new net.Socket() var socketFunc = function () { return socket } var conn = new Connection() conn.connect({ socket: socketFunc }) assert.equal(conn.socket, socket) }) it('defaults to using a net.Socket', function () { var conn = new Connection() conn.connect({}) assert.equal(conn.socket instanceof net.Socket, true) }) }) describe('streamOpen', function() { it('defaults to stream:stream', function() { var conn = new Connection() assert.equal(conn.streamOpen, 'stream:stream') }) it('is configurable', function() { var conn = new Connection({streamOpen: 'open'}) assert.equal(conn.streamOpen, 'open') }) }) describe('streamClose', function() { it('defaults to </stream:stream>', function() { var conn = new Connection() assert.equal(conn.streamClose, '</stream:stream>') }) it('is configurable', function() { var conn = new Connection({streamClose: '<close/>'}) assert.equal(conn.streamClose, '<close/>') }) }) // http://xmpp.org/rfcs/rfc6120.html#streams-open describe('openStream', function() { it('calls send with <streamOpen >', function() { var conn = new Connection() conn.streamOpen = 'foo' var send = sinon.stub(conn, 'send') conn.openStream() assert(send.calledOnce) assert.equal(send.args[0][0].indexOf('<' + conn.streamOpen + ' '), 0) }) it('alias to startStream', function() { var conn = new Connection() assert.equal(conn.startStream, conn.openStream) }) }) // http://xmpp.org/rfcs/rfc6120.html#streams-close describe('closeStream', function() { it('calls sends with streamClose', function() { var conn = new Connection() conn.openStream() conn.streamClose = '</bar>' var send = sinon.stub(conn, 'send') conn.closeStream() assert(send.calledOnce) assert(send.calledWith(conn.streamClose)) }) it('alias to endStream', function() { var conn = new Connection() assert.equal(conn.endStream, conn.closeStream) }) }) describe('<stream> handling', function () { var conn var server var serverSocket beforeEach(function (done) { serverSocket = null server = net.createServer(function (c) { if (serverSocket) { assert.fail('Multiple connections to server; test case fail') } serverSocket = c done() }) server.listen(PORT) conn = new Connection() var socket = new net.Socket() conn.connect({socket: socket}) socket.connect(PORT) }) afterEach(function (done) { serverSocket.end() server.close(done) }) it('sends <stream:stream > to start the stream', function (done) { conn.openStream() serverSocket.on('data', function(data) { assert.equal(data.toString().indexOf('<stream:stream '), 0) done() }) }) it('sends </stream:stream> to close the stream when the connection is ended', function (done) { serverSocket.on('data', function (data) { var parsed = ltx.parse(data) assert.equal(parsed.name, 'stream:stream') done() }) conn.openStream() conn.end() }) it('sends </stream:stream> to close the stream when the socket is ended from the other side', function (done) { //If we don't allow halfOpen, the socket will close before it can send </stream> conn.socket.allowHalfOpen = true conn.socket.on('end', function () { conn.socket.end() }) serverSocket.on('data', function (data) { if(data.toString().indexOf('<stream:stream ') === 0) { serverSocket.end() } else { assert.equal(data.toString(), '</stream:stream>') done() } }) conn.startStream() }) }) })
mit
PaulienVa/JavaMasters
2014/NLJUG-Masters-of-Java/2_Befunged/BefungedCase/BefungedImpl.java
2592
import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * The main implementation class of Duke's Befunge interpreter. * * @author Jaap Coomans */ public class BefungedImpl { private List<ProgramListener> listeners = new ArrayList<ProgramListener>(); /** * Creates a new instance with an {@link InfiniteLoopDetector} attached to it. */ public BefungedImpl() { this.addProgramListener(new InfiniteLoopDetector()); } /** * Evaluates and executes the given Befunge program. * * @param program * The program to execute. Newline characters are interpreted as the break between two rows in the * playfield. * @return The resulting output of the program as a String. * @throws IOException * @throws InfiniteLoopException * When the program gets stuck in an infinite loop. */ public String eval(String program) throws IOException { ExecutionContext context = new ExecutionContext(program); this.execute(context); return context.getOutput(); } /** * Executes the commands of the program loaded in the given context, until either the program is terminated or an * exception has occurred. * * @param context * The context in which the program and it's current state are loaded. */ private void execute(ExecutionContext context) { while (context.isActive()) { this.executeCommand(context); context.getProgramCounter().move(); } } /** * Executes the next command of the program represented in the context. * * @param context * The context to execute the next command of. */ private void executeCommand(ExecutionContext context) { try { char rawCommand = context.getCurrentCommand(); Command command = Command.createCommand(rawCommand, context.getProgramCounter().isStringMode()); command.execute(context); } catch (RuntimeException rte) { context.terminate(); String message = "Failed while executing command at " + context.getProgramCounter(); throw new RuntimeException(message, rte); } this.fireAfterStep(context); } /** * Fires an {@link ProgramListener#afterStep(ProgramState)} event to each listener bound to this instance. * * @param context * The context of the program. */ private void fireAfterStep(ExecutionContext context) { for (ProgramListener listener : this.listeners) { listener.afterStep(new ProgramState(context.getProgramCounter(), context.getStack())); } } public void addProgramListener(ProgramListener listener) { this.listeners.add(listener); } }
mit
moazzemi/HAMEX
cpu/gem5/src/gpu-compute/dispatcher.hh
5220
/* * Copyright (c) 2011-2015 Advanced Micro Devices, Inc. * All rights reserved. * * For use for simulation and test purposes only * * 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 list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder 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 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. * * Author: Brad Beckmann, Marc Orr */ #ifndef __GPU_DISPATCHER_HH__ #define __GPU_DISPATCHER_HH__ #include <queue> #include <vector> #include "base/statistics.hh" #include "dev/dma_device.hh" #include "gpu-compute/compute_unit.hh" #include "gpu-compute/ndrange.hh" #include "gpu-compute/qstruct.hh" #include "mem/port.hh" #include "params/GpuDispatcher.hh" class BaseCPU; class Shader; class GpuDispatcher : public DmaDevice { public: typedef GpuDispatcherParams Params; class TickEvent : public Event { private: GpuDispatcher *dispatcher; public: TickEvent(GpuDispatcher *); void process(); const char *description() const; }; MasterID masterId() { return _masterId; } protected: MasterID _masterId; // Base and length of PIO register space Addr pioAddr; Addr pioSize; Tick pioDelay; HsaQueueEntry curTask; std::unordered_map<int, NDRange> ndRangeMap; NDRange ndRange; // list of kernel_ids to launch std::queue<int> execIds; // list of kernel_ids that have finished std::queue<int> doneIds; uint64_t dispatchCount; // is there a kernel in execution? bool dispatchActive; BaseCPU *cpu; Shader *shader; ClDriver *driver; TickEvent tickEvent; static GpuDispatcher *instance; // sycall emulation mode can have only 1 application running(?) // else we have to do some pid based tagging // unused typedef std::unordered_map<uint64_t, uint64_t> TranslationBuffer; TranslationBuffer tlb; public: /*statistics*/ Stats::Scalar num_kernelLaunched; GpuDispatcher(const Params *p); ~GpuDispatcher() { } void exec(); virtual void serialize(CheckpointOut &cp) const; virtual void unserialize(CheckpointIn &cp); void notifyWgCompl(Wavefront *w); void scheduleDispatch(); void accessUserVar(BaseCPU *cpu, uint64_t addr, int val, int off); // using singleton so that glue code can pass pointer locations // to the dispatcher. when there are multiple dispatchers, we can // call something like getInstance(index) static void setInstance(GpuDispatcher *_instance) { instance = _instance; } static GpuDispatcher* getInstance() { return instance; } class TLBPort : public MasterPort { public: TLBPort(const std::string &_name, GpuDispatcher *_dispatcher) : MasterPort(_name, _dispatcher), dispatcher(_dispatcher) { } protected: GpuDispatcher *dispatcher; virtual bool recvTimingResp(PacketPtr pkt) { return true; } virtual Tick recvAtomic(PacketPtr pkt) { return 0; } virtual void recvFunctional(PacketPtr pkt) { } virtual void recvRangeChange() { } virtual void recvReqRetry() { } }; TLBPort *tlbPort; virtual BaseMasterPort& getMasterPort(const std::string &if_name, PortID idx); AddrRangeList getAddrRanges() const; Tick read(PacketPtr pkt); Tick write(PacketPtr pkt); // helper functions to retrieve/set GPU attributes int getNumCUs(); void setFuncargsSize(int funcargs_size); }; #endif // __GPU_DISPATCHER_HH__
mit
cesar1000/robolectric
robolectric-annotations/src/main/java/org/robolectric/annotation/Implements.java
2146
package org.robolectric.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Indicates that a class declaration is intended to shadow an Android class declaration. * The Robolectric runtime searches classes with this annotation for methods with the * {@link Implementation} annotation and calls them in place of the methods on the Android * class. */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) public @interface Implements { /** * The Android class to be shadowed. * * @return Android class to shadow. */ Class<?> value() default void.class; /** * Android class name (if the Class object is not accessible). * * @return Android class name. */ String className() default ""; /** * Denotes that this type exists in the public Android SDK. When this value is true, the * annotation processor will generate a shadowOf method. * * @return True if the type is exposed in the Android SDK. */ boolean isInAndroidSdk() default true; /** * If true, Robolectric will invoke the actual Android code for any method that isn't shadowed. * * @return True to invoke the underlying method. */ boolean callThroughByDefault() default true; /** * If true, Robolectric will invoke @Implementation methods from superclasses. * * @return True to invoke superclass methods. */ boolean inheritImplementationMethods() default false; /** * If true, when an exact method signature match isn't found, Robolectric will look for a method * with the same name but with all argument types replaced with java.lang.Object. * * @return True to disable strict signature matching. */ boolean looseSignatures() default false; /** * If specified, the shadow class will be applied only for this SDK or greater. */ int minSdk() default -1; /** * If specified, the shadow class will be applied only for this SDK or lesser. */ int maxSdk() default -1; }
mit
OhmzTech/AppInspector
app/test/siesta-2.0.5-lite/lib/Siesta/Harness/Browser/UI/AssertionGrid.js
9213
/* Siesta 2.0.5 Copyright(c) 2009-2013 Bryntum AB http://bryntum.com/contact http://bryntum.com/products/siesta/license */ Ext.define('Siesta.Harness.Browser.UI.AssertionGrid', { alias : 'widget.assertiongrid', extend : 'Ext.tree.Panel', mixins : [ 'Siesta.Harness.Browser.UI.CanFillAssertionsStore' ], // requires : [ // 'Siesta.Harness.Browser.Model.AssertionTreeStore', // 'Siesta.Harness.Browser.UI.FilterableTreeView', // 'Siesta.Harness.Browser.UI.TreeColumn' // ], cls : 'siesta-assertion-grid hide-simulated', enableColumnHide : false, enableColumnMove : false, enableColumnResize : false, sortableColumns : false, border : false, forceFit : true, minWidth : 100, trackMouseOver : false, autoScrollToBottom : true, hideHeaders : true, resultTpl : null, rowLines : false, isStandalone : false, rootVisible : false, collapseDirection : 'left', test : null, testListeners : null, viewType : 'filterabletreeview', initComponent : function() { var me = this; this.testListeners = [] if (!this.store) this.store = new Siesta.Harness.Browser.Model.AssertionTreeStore({ proxy : { type : 'memory', reader : { type: 'json' } }, root : { id : '__ROOT__', expanded : true, loaded : true } }) Ext.apply(this, { resultTpl : new Ext.XTemplate( '<span class="assertion-text">{[this.getDescription(values.result)]}</span>{[this.getAnnotation(values)]}', { getDescription : function (result) { if (result instanceof Siesta.Result.Summary) return result.description.join('<br>') else return result.isWarning ? 'WARN: ' + result.description : result.description }, getAnnotation : function (data) { var annotation = data.result.annotation if (annotation) { return '<pre style="margin-left:' + data.depth * 16 + 'px" class="tr-assert-row-annontation">' + Ext.String.htmlEncode(annotation) + '</pre>' } else return ''; } } ), columns : [ { xtype : 'assertiontreecolumn', flex : 1, dataIndex : 'folderStatus', renderer : this.resultRenderer, scope : this, menuDisabled : true, sortable : false } ], viewConfig : { enableTextSelection : true, stripeRows : false, disableSelection : true, markDirty : false, // Animation is disabled until: http://www.sencha.com/forum/showthread.php?265901-4.2.0-Animation-breaks-the-order-of-nodes-in-the-tree-view&p=974172 // is resolved animate : false, trackOver : false, // dummy store to be re-defined before showing each test store : new Ext.data.NodeStore({ fields : [], data : [] }), onAdd : function (store, records, index) { this.refreshSize = Ext.emptyFn; var val = Ext.tree.View.prototype.onAdd.apply(this, arguments); this.refreshSize = Ext.tree.View.prototype.refreshSize; // Scroll to bottom if (me.autoScrollToBottom) { var el = this.getEl().dom; el.scrollTop = el.scrollHeight; } return val; }, onUpdate : function () { this.refreshSize = Ext.emptyFn; var val = Ext.tree.View.prototype.onUpdate.apply(this, arguments); this.refreshSize = Ext.tree.View.prototype.refreshSize; return val; }, // this should be kept `false` - otherwise assertion grid goes crazy, see #477 deferInitialRefresh : false, getRowClass : this.getRowClass } }); this.callParent(arguments); }, getRowClass : function (record, rowIndex, rowParams, store) { var result = record.getResult() var cls = '' // TODO switch to "instanceof" switch (result.meta.name) { case 'Siesta.Result.Diagnostic': return 'tr-diagnostic-row ' + (result.isWarning ? 'tr-warning-row' : ''); case 'Siesta.Result.Summary': return 'tr-summary-row ' + (result.isFailed ? ' tr-summary-failure' : ''); case 'Siesta.Result.SubTest': cls = 'tr-subtest-row tr-subtest-row-' + record.get('folderStatus') if (result.test.specType == 'describe') cls += ' tr-subtest-row-describe' if (result.test.specType == 'it') cls += ' tr-subtest-row-it' return cls; case 'Siesta.Result.Assertion': cls += 'tr-assertion-row ' if (result.isWaitFor) cls += 'tr-waiting-row ' + (result.completed ? (result.passed ? 'tr-waiting-row-passed' : 'tr-assertion-row-failed tr-waiting-row-failed') : '') else if (result.isException) cls += result.isTodo ? 'tr-exception-todo-row' : 'tr-exception-row' else if (result.isTodo) cls += result.passed ? 'tr-todo-row-passed' : 'tr-todo-row-failed' else cls += result.passed ? 'tr-assertion-row-passed' : 'tr-assertion-row-failed' return cls default: throw "Unknown result class" } }, showTest : function (test, assertionsStore) { if (this.test) { Joose.A.each(this.testListeners, function (listener) { listener.remove() }) this.testListeners = [] } this.test = test this.testListeners = [].concat( this.isStandalone ? [ test.on('testupdate', this.onTestUpdate, this), test.on('testendbubbling', this.onEveryTestEnd, this) ] : [] ) Ext.suspendLayouts() if (assertionsStore) this.reconfigure(assertionsStore) else this.store.removeAll() Ext.resumeLayouts() }, onTestUpdate : function (event, test, result, parentResult) { this.processNewResult(this.store, test, result, parentResult) }, // is bubbling and thus triggered for all tests (including sub-tests) onEveryTestEnd : function (event, test) { this.processEveryTestEnd(this.store, test) }, resultRenderer : function (value, metaData, record, rowIndex, colIndex, store) { return this.resultTpl.apply(record.data); }, bindStore : function (treeStore, isInitial, prop) { this.callParent(arguments) this.store = treeStore; if (treeStore && treeStore.nodeStore) { this.getView().dataSource = treeStore.nodeStore // passing the tree store instance to the underlying `filterabletreeview` // the view will re-bind the tree store listeners this.getView().bindStore(treeStore, isInitial, prop) } }, destroy : function () { Joose.A.each(this.testListeners, function (listener) { listener.remove() }) this.testListeners = [] this.test = null this.callParent(arguments) }, clear : function () { Ext.suspendLayouts() this.store.removeAll(); this.getView().getEl().update('<div class="assertiongrid-initializing">Initializing test...</div>'); Ext.resumeLayouts(true) } })
mit
filipinotutor/public_html
tutor/test/school.php
2089
<html> <head> <script src="http://code.jquery.com/jquery-latest.js"></script> <script> function getdetails(){ var name = $('#name').val(); var rno = $('#rno').val(); $.ajax({ type: "POST", url: "details.php", data: {fname:name, id:rno} }).done(function( result ) { $("#msg").html( " Address of Roll no " +rno +" is "+result ); }); } </script> <!-- -------------------------------- --> <script type="text/javascript"> $(document).ready(function() { $("#villa_submit").click(function() { var action = $("#villa_choose").attr('action'); //var form_data = { 'vid[]' : []};$("input:checked").each(function() {data['vid[]'].push($(this).val());}); var form_data = $('#villa_choose').serialize(); //suggested by Kev Price $.ajax({ type: "POST", url: "details.php", data: {chosen:form_data} beforeSend:function(){ $('#villa_result').html('<center>loading</center>'); }, success: function(data){ $('#test_result').html(data); } }); return false; }); }); </script> <!-- -------------------------------- --> </head> <body> <form name="villa_choose" id="villa_choose" method="post" action=""> <input type="checkbox" name="vid[]" id="vid1" value="1" /> <input type="checkbox" name="vid[]" id="vid2" value="2" /> <input type="checkbox" name="vid[]" id="vid3" value="3" /> <input type="checkbox" name="vid[]" id="vid4" value="4" /> <input type="checkbox" name="vid[]" id="vid5" value="5" /> <input type="button" name="submit" id="villa_submit" value="submit" onClick = "getdetails()" /> </form> <div id="test_result"></div> <div id="villa_result"></div> <table> <tr> <td>Your Name:</td> <td><input type="text" name="name" id="name" /><td> </tr> <tr> <td>Roll Number:</td> <td><input type="text" name="rno" id="rno" /><td> </tr> <tr> <td></td> <td><input type="button" name="submit" id="submit" value="submit" onClick = "getdetails()" /></td> </tr> </table> <div id="msg"></div> </body> </html>
mit
augustash/d8.dev
core/modules/system/lib/Drupal/system/Tests/Authentication/HttpBasicTest.php
2914
<?php /** * @file * Contains \Drupal\system\Tests\Authentication\HttpBasicTest. */ namespace Drupal\system\Tests\Authentication; use Drupal\Core\Authentication\Provider\HttpBasic; use Drupal\simpletest\WebTestBase; use Symfony\Component\HttpFoundation\Request; /** * Test for http basic authentication. */ class HttpBasicTest extends WebTestBase { /** * Modules enabled for all tests. * * @var array */ public static $modules = array('router_test'); public static function getInfo() { return array( 'name' => 'HttpBasic authentication', 'description' => 'Tests for HttpBasic authentication provider.', 'group' => 'Authentication', ); } /** * Test http basic authentication. */ public function testHttpBasic() { $account = $this->drupalCreateUser(); $this->basicAuthGet('router_test/test11', $account->getUsername(), $account->pass_raw); $this->assertText($account->getUsername(), 'Account name is displayed.'); $this->assertResponse('200', 'HTTP response is OK'); $this->curlClose(); $this->basicAuthGet('router_test/test11', $account->getUsername(), $this->randomName()); $this->assertNoText($account->getUsername(), 'Bad basic auth credentials do not authenticate the user.'); $this->assertResponse('403', 'Access is not granted.'); $this->curlClose(); $this->drupalGet('router_test/test11'); $this->assertResponse('401', 'Not authenticated on the route that allows only http_basic. Prompt to authenticate received.'); $this->drupalGet('admin'); $this->assertResponse('403', 'No authentication prompt for routes not explicitly defining authentication providers.'); $account = $this->drupalCreateUser(array('access administration pages')); $this->basicAuthGet('admin', $account->getUsername(), $account->pass_raw); $this->assertNoLink('Log out', 0, 'User is not logged in'); $this->assertResponse('403', 'No basic authentication for routes not explicitly defining authentication providers.'); $this->curlClose(); } /** * Does HTTP basic auth request. * * We do not use \Drupal\simpletest\WebTestBase::drupalGet because we need to * set curl settings for basic authentication. * * @param string $path * The request path. * @param string $username * The user name to authenticate with. * @param string $password * The password. * * @return string * Curl output. */ protected function basicAuthGet($path, $username, $password) { $out = $this->curlExec( array( CURLOPT_HTTPGET => TRUE, CURLOPT_URL => url($path, array('absolute' => TRUE)), CURLOPT_NOBODY => FALSE, CURLOPT_HTTPAUTH => CURLAUTH_BASIC, CURLOPT_USERPWD => $username . ':' . $password, ) ); $this->verbose('GET request to: ' . $path . '<hr />' . $out); return $out; } }
mit
nitirohilla/upm
examples/javascript/lsm303.js
2833
/* * Author: Zion Orent <zorent@ics.com> * Copyright (c) 2014 Intel Corporation. * * 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. */ var accelrCompassSensor = require('jsupm_lsm303'); // Instantiate LSM303 compass on I2C var myAccelrCompass = new accelrCompassSensor.LSM303(0); var successFail, coords, outputStr, accel; var myInterval = setInterval(function() { // Load coordinates into LSM303 object successFail = myAccelrCompass.getCoordinates(); // in XYZ order. The sensor returns XZY, // but the driver compensates and makes it XYZ coords = myAccelrCompass.getRawCoorData(); // Print out the X, Y, and Z coordinate data using two different methods outputStr = "coor: rX " + coords.getitem(0) + " - rY " + coords.getitem(1) + " - rZ " + coords.getitem(2); console.log(outputStr); outputStr = "coor: gX " + myAccelrCompass.getCoorX() + " - gY " + myAccelrCompass.getCoorY() + " - gZ " + myAccelrCompass.getCoorZ(); console.log(outputStr); // Get and print out the heading console.log("heading: " + myAccelrCompass.getHeading()); // Get the acceleration myAccelrCompass.getAcceleration(); accel = myAccelrCompass.getRawAccelData(); // Print out the X, Y, and Z acceleration data using two different methods outputStr = "acc: rX " + accel.getitem(0) + " - rY " + accel.getitem(1) + " - Z " + accel.getitem(2); console.log(outputStr); outputStr = "acc: gX " + myAccelrCompass.getAccelX() + " - gY " + myAccelrCompass.getAccelY() + " - gZ " + myAccelrCompass.getAccelZ(); console.log(outputStr); console.log(" "); }, 1000); // Print message when exiting process.on('SIGINT', function() { clearInterval(myInterval); myAccelrCompass = null; accelrCompassSensor.cleanUp(); accelrCompassSensor = null; console.log("Exiting"); process.exit(0); });
mit
shiren1118/grape
lib/grape.rb
2089
require 'rack' require 'rack/builder' module Grape autoload :API, 'grape/api' autoload :Endpoint, 'grape/endpoint' autoload :Route, 'grape/route' autoload :Entity, 'grape/entity' autoload :Cookies, 'grape/cookies' autoload :Validations, 'grape/validations' module Exceptions autoload :Base, 'grape/exceptions/base' autoload :ValidationError, 'grape/exceptions/validation_error' end module ErrorFormatter autoload :Base, 'grape/error_formatter/base' autoload :Json, 'grape/error_formatter/json' autoload :Txt, 'grape/error_formatter/txt' autoload :Xml, 'grape/error_formatter/xml' end module Formatter autoload :Base, 'grape/formatter/base' autoload :Json, 'grape/formatter/json' autoload :SerializableHash, 'grape/formatter/serializable_hash' autoload :Txt, 'grape/formatter/txt' autoload :Xml, 'grape/formatter/xml' end module Parser autoload :Base, 'grape/parser/base' autoload :Json, 'grape/parser/json' autoload :Xml, 'grape/parser/xml' end module Middleware autoload :Base, 'grape/middleware/base' autoload :Versioner, 'grape/middleware/versioner' autoload :Formatter, 'grape/middleware/formatter' autoload :Error, 'grape/middleware/error' module Auth autoload :OAuth2, 'grape/middleware/auth/oauth2' autoload :Basic, 'grape/middleware/auth/basic' autoload :Digest, 'grape/middleware/auth/digest' end module Versioner autoload :Path, 'grape/middleware/versioner/path' autoload :Header, 'grape/middleware/versioner/header' autoload :Param, 'grape/middleware/versioner/param' end end module Util autoload :HashStack, 'grape/util/hash_stack' end end require 'grape/version'
mit
unboxed/e-petitions
db/migrate/20190411174307_add_postcode_indexes_to_archived_signatures.rb
1154
class AddPostcodeIndexesToArchivedSignatures < ActiveRecord::Migration[4.2] disable_ddl_transaction! def up unless index_exists?(:archived_signatures, [:postcode, :petition_id]) execute <<-SQL CREATE INDEX CONCURRENTLY index_archived_signatures_on_postcode_and_petition_id ON archived_signatures USING btree (postcode, petition_id); SQL end unless index_exists?(:archived_signatures, [:postcode, :state, :petition_id]) execute <<-SQL CREATE INDEX CONCURRENTLY index_archived_signatures_on_postcode_and_state_and_petition_id ON archived_signatures USING btree (postcode, state, petition_id); SQL end end def down if index_exists?(:archived_signatures, [:postcode, :state, :petition_id]) remove_index :archived_signatures, [:postcode, :state, :petition_id] end if index_exists?(:archived_signatures, [:postcode, :petition_id]) remove_index :archived_signatures, [:postcode, :petition_id] end end private def index_exists?(table, names) select_value("SELECT to_regclass('index_#{table}_on_#{Array(names).join('_and_')}')") end end
mit
Bernardo-MG/CWR-Validator
data_validator/accessor.py
1902
# -*- coding: utf-8 -*- import os """ Facades for accessing the configuration data. """ __author__ = 'Bernardo Martínez Garrido' __license__ = 'MIT' __status__ = 'Development' class _FileReader(object): """ Offers methods to read the data files. """ # Singleton control object __shared_state = {} def __init__(self): self.__dict__ = self.__shared_state def __path(self): """ Returns the path to the folder in which this class is contained. As this class is to be on the same folder as the data files, this will be the data files folder. :return: path to the data files folder. """ return os.path.dirname(__file__) def read_properties(self, file_name): config = {} with open(os.path.join(self.__path(), os.path.basename(file_name)), 'rt') as f: for line in f: line = line.rstrip() # removes trailing whitespace and '\n' chars if "=" not in line: continue # skips blanks and comments w/o = if line.startswith( "#"): continue # skips comments which contain = k, v = line.split("=", 1) config[k] = v return config class CWRValidatorConfiguration(object): """ Offers methods to access the CWR web application configuration data. """ def __init__(self): # Reader for the files self._reader = _FileReader() # Files containing the CWR info self._file_config = 'config.properties' # Configuration self._config = None def get_config(self): """ Loads the configuration file. :return: the webapp configuration """ if not self._config: self._config = self._reader.read_properties(self._file_config) return self._config
mit
cidadedemocratica/cidadedemocratica
app/models/general_report/general_report_locals.rb
939
class GeneralReportLocals < GeneralReportBase def initialize(local_scoped) super() @local_scoped = local_scoped end def add(name, model) topic_model(model).locais.map(&@local_scoped[:field]).uniq.each do |local_id| @store[local_id]["total"] += 1 @store[local_id]["users"] << model.user @store[local_id][name + "_count"] += 1 count_activities_and_types_of_topics(name, local_id, model) end end def data @store.sort_by { |k,v| v["total"] }.reverse[0..9].map do |local, data| data["users"].uniq! data["users_stats"] = users_stats(data["users"]) local = (local ? @local_scoped[:model].find(local).nome : "Não definido") unless local == "all" [local , data] end end private def count_activities_and_types_of_topics(name, local_id, model) if name == "topicos" @store[local_id][model.type.pluralize.downcase + "_count"] += 1 end end end
mit
SweetLakePHP/SweetLakePHP
src/SWP/BackendBundle/DependencyInjection/SWPBackendExtension.php
761
<?php namespace SWP\BackendBundle\DependencyInjection; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\FileLocator; use Symfony\Component\HttpKernel\DependencyInjection\Extension; use Symfony\Component\DependencyInjection\Loader; /** * This is the class that loads and manages your bundle configuration * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html} */ class SWPBackendExtension extends Extension { /** * {@inheritDoc} */ public function load(array $configs, ContainerBuilder $container) { $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config')); $loader->load('services.yml'); } }
mit
imperodesign/clever-v0-system
controllers/system-admin.js
2973
'use strict'; // Module dependencies. const config = require('clever-core').loadConfig(); const mongoose = require('mongoose'); const Setting = mongoose.model('Setting'); const async = require('async'); const util = require('../util'); // DASHBOARD exports.showDashboard = function(SystemPackage, req, res) { // Always use Package.render() res.send(SystemPackage.render('admin/dashboard', { packages: SystemPackage.getCleverCore().getInstance().exportablePkgList, user: req.user })); }; // SETTINGS exports.showSettings = function(SettingPackage, req, res, next) { let page = Number.parseInt(req.query.page); page = Number.isNaN(page) ? 0 : page; const skip = page * 10; function renderSettingList(settings, nSettings) { res.send(SettingPackage.render('admin/settings/list', { packages: SettingPackage.getCleverCore().getInstance().exportablePkgList, user: req.user, settings: settings, nSettings: nSettings, activePage: page, csrfToken: req.csrfToken() })); } async.parallel([ function getSettings(cb){ Setting.getSettings(skip, 10) .then(function(settings) { cb(null, settings); }) .catch(util.passNext.bind(null, cb)); }, function countSettings(cb){ Setting.countSettings() .then(function(nSettings) { cb(null, nSettings); }) .catch(util.passNext.bind(null, cb)); } ], function(err, options){ if(err) return util.passNext.bind(null, next); renderSettingList.apply(null, options); }); }; exports.showSetting = function(SettingPackage, req, res, next) { function render(settingToShow) { res.send(SettingPackage.render('admin/settings/details', { packages: SettingPackage.getCleverCore().getInstance().exportablePkgList, user: req.user, settingToShow: settingToShow, csrfToken: req.csrfToken() })); } Setting.getSettingById(req.params.id) .then(render) .catch(util.passNext.bind(null, next)); }; exports.createSetting = function(SettingPackage, req, res, next) { res.send(SettingPackage.render('admin/settings/create', { packages: SettingPackage.getCleverCore().getInstance().exportablePkgList, user: req.user, csrfToken: req.csrfToken() })); }; exports.editSetting = function(SettingPackage, req, res, next) { function render(settingToEdit) { res.send(SettingPackage.render(`admin/settings/edit`, { packages: SettingPackage.getCleverCore().getInstance().exportablePkgList, user: req.user, settingToEdit: settingToEdit, csrfToken: req.csrfToken() })); } Setting.getSettingById(req.params.id) .then(render) .catch(util.passNext.bind(null, next)); }; // HELP exports.showHelp = function(SystemPackage, req, res) { res.send(SystemPackage.render('admin/help', { packages: SystemPackage.getCleverCore().getInstance().exportablePkgList, user: req.user })); };
mit
sircommitsalot/wikitree
client/js/angular/services/Search.service.js
3139
(function() { angular.module('wikitree'). factory('Search', ['$http', 'Articles', 'Categories', 'Searches', function($http, Articles, Categories, Searches) { var search = {}; search.get_suggestions = function (term) { console.log('Fetching suggestions...', term); return $http.jsonp('https://en.wikipedia.org/w/api.php', { params: { action: 'opensearch', search: term, callback: 'JSON_CALLBACK' } }).then(function(response) { return response.data[1]; }); }; search.findOrAddArticle = function (title) { // is this a category? if (title.match(/^Category:/)) { // skip to special handler return search.findOrAddCategory(title); } return Articles.getByUnsafeTitle(title). then(function (article) { return{ type: 'article', name: article.title, title: article.title }; }). catch(function (err) { console.log('In findOrAddArticle', err); // no result? try searching return search.findOrAddSearch(title); }); }; search.findOrAddCategory = function (title) { return Categories.getByUnsafeTitle(title). then(function (category) { return { type: 'category', name: category.title, title: category.title }; }). catch(function (err) { console.log('In findOrAddCategory', err); // no result? try searching return findOrAddSearch(title); }); }; search.findOrAddSearch = function (query) { return Searches.getByQuery(query). then(function (search) { return { type: 'search', name: 'Search "' + query + '"', query: query }; }). catch(function (err) { console.log('In findOrAddSearch', err); // no dice return null; }); }; return search; }]); })();
mit
codefresh/node-examples
angular/node_modules/grunt-express/node_modules/forever-monitor/test/monitor/env-spawn-test.js
3484
/* * env-spawn-test.js: Tests for supporting environment variables in the forever module * * (C) 2010 Nodejitsu Inc. * MIT LICENCE * */ var assert = require('assert'), path = require('path'), vows = require('vows'), fmonitor = require('../../lib'); vows.describe('forever-monitor/monitor/spawn-options').addBatch({ "When using forever-monitor": { "an instance of Monitor with valid options": { "passing environment variables to env-vars.js": { topic: function () { var that = this, child; this.env = { FOO: 'foo', BAR: 'bar' }; child = new (fmonitor.Monitor)(path.join(__dirname, '..', '..', 'examples', 'env-vars.js'), { max: 1, silent: true, minUptime: 0, env: this.env }); child.on('stdout', function (data) { that.stdout = data.toString(); }); child.on('exit', this.callback.bind({}, null)); child.start(); }, "should pass the environment variables to the child": function (err, child) { assert.equal(child.times, 1); assert.equal(this.stdout, JSON.stringify(this.env)); } }, "passing a custom cwd to custom-cwd.js": { topic: function () { var that = this, child; this.cwd = path.join(__dirname, '..'); child = new (fmonitor.Monitor)(path.join(__dirname, '..', '..', 'examples', 'custom-cwd.js'), { max: 1, silent: true, minUptime: 0, cwd: this.cwd }); child.on('stdout', function (data) { that.stdout = data.toString(); }); child.on('exit', this.callback.bind({}, null)); child.start(); }, "should setup the child to run in the target directory": function (err, child) { assert.equal(child.times, 1); assert.equal(this.stdout, this.cwd); } }, "setting `hideEnv` when spawning all-env-vars.js": { topic: function () { var that = this, all = '', confirmed, child; this.hideEnv = [ 'USER', 'OLDPWD' ]; // // Remark (indexzero): This may be a symptom of a larger bug. // This test only fails when run under `npm test` (e.g. vows --spec -i). // function tryCallback() { if (confirmed) { return that.callback(null, child); } confirmed = true; } child = new (fmonitor.Monitor)(path.join(__dirname, '..', '..', 'examples', 'all-env-vars.js'), { max: 1, silent: true, minUptime: 0, hideEnv: this.hideEnv }); child.on('stdout', function (data) { all += data; try { that.env = Object.keys(JSON.parse(all)); } catch (ex) { } tryCallback(); }); child.on('exit', tryCallback); child.start(); }, "should hide the environment variables passed to the child": function (err, child) { var that = this; assert.equal(child.times, 1); this.hideEnv.forEach(function (key) { assert.isTrue(that.env.indexOf(key) === -1); }); } }, } } }).export(module);
mit
Blackbaud-StacyCarlos/skyux
js/sky/palette/template.js
272
/*jshint unused: false */ /*global angular, bbPaletteConfig */ (function () { 'use strict'; var bbPaletteConfig; /* LINES BELOW ARE AUTO GENERATED */ /*PALETTE_CONFIG*/ angular.module('sky.palette.config', []) .constant('bbPaletteConfig', bbPaletteConfig); }());
mit
NikolayPianikov/nunit
src/NUnitFramework/tests/Constraints/ThrowsConstraintTests.cs
6098
// *********************************************************************** // Copyright (c) 2009 Charlie Poole, Rob Prouse // // 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. // *********************************************************************** using System; using NUnit.Framework.Internal; using NUnit.TestUtilities; namespace NUnit.Framework.Constraints { [TestFixture] public class ThrowsConstraintTest_ExactType : ThrowsConstraintTestBase { [SetUp] public void SetUp() { theConstraint = new ThrowsConstraint( new ExceptionTypeConstraint(typeof(ArgumentException))); expectedDescription = "<System.ArgumentException>"; stringRepresentation = "<throws <typeof System.ArgumentException>>"; } static readonly object[] SuccessData = { new TestDelegate( TestDelegates.ThrowsArgumentException ) }; static readonly object[] FailureData = { new TestCaseData( new TestDelegate( TestDelegates.ThrowsNullReferenceException ), "<System.NullReferenceException: my message" + Environment.NewLine ), new TestCaseData( new TestDelegate( TestDelegates.ThrowsNothing ), "no exception thrown" ), new TestCaseData( new TestDelegate( TestDelegates.ThrowsSystemException ), "<System.Exception: my message" + Environment.NewLine ) }; } [TestFixture] public class ThrowsConstraintTest_InstanceOfType : ThrowsConstraintTestBase { [SetUp] public void SetUp() { theConstraint = new ThrowsConstraint( new InstanceOfTypeConstraint(typeof(TestDelegates.BaseException))); expectedDescription = "instance of <NUnit.TestUtilities.TestDelegates+BaseException>"; stringRepresentation = "<throws <instanceof NUnit.TestUtilities.TestDelegates+BaseException>>"; } static object[] SuccessData = new object[] { new TestDelegate( TestDelegates.ThrowsBaseException ), new TestDelegate( TestDelegates.ThrowsDerivedException ) }; static object[] FailureData = new object[] { new TestCaseData( new TestDelegate( TestDelegates.ThrowsArgumentException ), $"<System.ArgumentException: myMessage{Environment.NewLine}Parameter name: myParam" ), new TestCaseData( new TestDelegate( TestDelegates.ThrowsNothing ), "no exception thrown" ), new TestCaseData( new TestDelegate( TestDelegates.ThrowsNullReferenceException ), "<System.NullReferenceException: my message" ) }; } public class ThrowsConstraintTest_WithConstraint : ThrowsConstraintTestBase { [SetUp] public void SetUp() { theConstraint = new ThrowsConstraint( new AndConstraint( new ExceptionTypeConstraint(typeof(ArgumentException)), new PropertyConstraint("ParamName", new EqualConstraint("myParam")))); expectedDescription = @"<System.ArgumentException> and property ParamName equal to ""myParam"""; stringRepresentation = @"<throws <and <typeof System.ArgumentException> <property ParamName <equal ""myParam"">>>>"; } static readonly object[] SuccessData = { new TestDelegate( TestDelegates.ThrowsArgumentException ) }; static readonly object[] FailureData = { new TestCaseData( new TestDelegate( TestDelegates.ThrowsNullReferenceException ), "<System.NullReferenceException: my message" + Environment.NewLine ), new TestCaseData( new TestDelegate( TestDelegates.ThrowsNothing ), "no exception thrown" ), new TestCaseData( new TestDelegate( TestDelegates.ThrowsSystemException ), "<System.Exception: my message" + Environment.NewLine ) }; } public abstract class ThrowsConstraintTestBase : ConstraintTestBaseNoData { [Test, TestCaseSource("SuccessData")] public void SucceedsWithGoodValues(object value) { var constraintResult = theConstraint.ApplyTo(value); if (!constraintResult.IsSuccess) { MessageWriter writer = new TextMessageWriter(); constraintResult.WriteMessageTo(writer); Assert.Fail(writer.ToString()); } } [Test, TestCaseSource("FailureData"), SetUICulture("en-US")] public void FailsWithBadValues(object badValue, string message) { string NL = Environment.NewLine; var constraintResult = theConstraint.ApplyTo(badValue); Assert.IsFalse(constraintResult.IsSuccess); TextMessageWriter writer = new TextMessageWriter(); constraintResult.WriteMessageTo(writer); Assert.That(writer.ToString(), Does.StartWith( TextMessageWriter.Pfx_Expected + expectedDescription + NL + TextMessageWriter.Pfx_Actual + message)); } } }
mit
kataras/gapi
_examples/database/mysql/service/product_service.go
3012
package service import ( "context" "fmt" "reflect" "strings" "myapp/entity" "myapp/sql" ) // ProductService represents the product entity service. // Note that the given entity (request) should be already validated // before service's calls. type ProductService struct { *sql.Service rec sql.Record } // NewProductService returns a new product service to communicate with the database. func NewProductService(db sql.Database) *ProductService { return &ProductService{Service: sql.NewService(db, new(entity.Product))} } // Insert stores a product to the database and returns its ID. func (s *ProductService) Insert(ctx context.Context, e entity.Product) (int64, error) { if !e.ValidateInsert() { return 0, sql.ErrUnprocessable } q := fmt.Sprintf(`INSERT INTO %s (category_id, title, image_url, price, description) VALUES (?,?,?,?,?);`, e.TableName()) res, err := s.DB().Exec(ctx, q, e.CategoryID, e.Title, e.ImageURL, e.Price, e.Description) if err != nil { return 0, err } return res.LastInsertId() } // BatchInsert inserts one or more products at once and returns the total length created. func (s *ProductService) BatchInsert(ctx context.Context, products []entity.Product) (int, error) { if len(products) == 0 { return 0, nil } var ( valuesLines []string args []interface{} ) for _, p := range products { if !p.ValidateInsert() { // all products should be "valid", we don't skip, we cancel. return 0, sql.ErrUnprocessable } valuesLines = append(valuesLines, "(?,?,?,?,?)") args = append(args, []interface{}{p.CategoryID, p.Title, p.ImageURL, p.Price, p.Description}...) } q := fmt.Sprintf("INSERT INTO %s (category_id, title, image_url, price, description) VALUES %s;", s.RecordInfo().TableName(), strings.Join(valuesLines, ", ")) res, err := s.DB().Exec(ctx, q, args...) if err != nil { return 0, err } n := sql.GetAffectedRows(res) return n, nil } // Update updates a product based on its `ID` from the database // and returns the affected numbrer (0 when nothing changed otherwise 1). func (s *ProductService) Update(ctx context.Context, e entity.Product) (int, error) { q := fmt.Sprintf(`UPDATE %s SET category_id = ?, title = ?, image_url = ?, price = ?, description = ? WHERE %s = ?;`, e.TableName(), e.PrimaryKey()) res, err := s.DB().Exec(ctx, q, e.CategoryID, e.Title, e.ImageURL, e.Price, e.Description, e.ID) if err != nil { return 0, err } n := sql.GetAffectedRows(res) return n, nil } var productUpdateSchema = map[string]reflect.Kind{ "category_id": reflect.Int, "title": reflect.String, "image_url": reflect.String, "price": reflect.Float32, "description": reflect.String, } // PartialUpdate accepts a key-value map to // update the record based on the given "id". func (s *ProductService) PartialUpdate(ctx context.Context, id int64, attrs map[string]interface{}) (int, error) { return s.Service.PartialUpdate(ctx, id, productUpdateSchema, attrs) }
mit
tylerhasman/MapleStory
scripts/npc/legacy/2101003.js
186
/* Ardin Ariant */ function start() { cm.sendNext ("Hey hey, don't try to start trouble with anyone. I want nothing to do with you."); } function action() { cm.dispose(); }
mit
TABuApp/tabu-admin
assets/themes/admin/layout.js
4491
$(document).ready(function() { body_sizer(); $("div[id='#fixed-sidebar']").on('click', function() { if ($(this).hasClass("switch-on")) { var windowHeight = $(window).height(); var headerHeight = $('#page-header').height(); var contentHeight = windowHeight - headerHeight; $('#page-sidebar').css('height', contentHeight); $('.scroll-sidebar').css('height', contentHeight); $('.scroll-sidebar').slimscroll({ height: '100%', color: 'rgba(155, 164, 169, 0.68)', size: '6px' }); var headerBg = $('#page-header').attr('class'); $('#header-logo').addClass(headerBg); } else { var windowHeight = $(document).height(); var headerHeight = $('#page-header').height(); var contentHeight = windowHeight - headerHeight; $('#page-sidebar').css('height', contentHeight); $('.scroll-sidebar').css('height', contentHeight); $(".scroll-sidebar").slimScroll({ destroy: true }); $('#header-logo').removeClass('bg-gradient-9'); } }); }); $(window).on('resize', function() { body_sizer(); }); function body_sizer() { if ($('body').hasClass('fixed-sidebar')) { var windowHeight = $(window).height(); var headerHeight = $('#page-header').height(); var contentHeight = windowHeight - headerHeight; $('#page-sidebar').css('height', contentHeight); $('.scroll-sidebar').css('height', contentHeight); $('#page-content').css('min-height', contentHeight); } else { var windowHeight = $(document).height(); var headerHeight = $('#page-header').height(); var contentHeight = windowHeight - headerHeight; $('#page-sidebar').css('height', contentHeight); $('.scroll-sidebar').css('height', contentHeight); $('#page-content').css('min-height', contentHeight); } }; function pageTransitions() { var transitions = ['.pt-page-moveFromLeft', 'pt-page-moveFromRight', 'pt-page-moveFromTop', 'pt-page-moveFromBottom', 'pt-page-fade', 'pt-page-moveFromLeftFade', 'pt-page-moveFromRightFade', 'pt-page-moveFromTopFade', 'pt-page-moveFromBottomFade', 'pt-page-scaleUp', 'pt-page-scaleUpCenter', 'pt-page-flipInLeft', 'pt-page-flipInRight', 'pt-page-flipInBottom', 'pt-page-flipInTop', 'pt-page-rotatePullRight', 'pt-page-rotatePullLeft', 'pt-page-rotatePullTop', 'pt-page-rotatePullBottom', 'pt-page-rotateUnfoldLeft', 'pt-page-rotateUnfoldRight', 'pt-page-rotateUnfoldTop', 'pt-page-rotateUnfoldBottom']; for (var i in transitions) { var transition_name = transitions[i]; if ($('.add-transition').hasClass(transition_name)) { $('.add-transition').addClass(transition_name + '-init page-transition'); setTimeout(function() { $('.add-transition').removeClass(transition_name + ' ' + transition_name + '-init page-transition'); }, 1200); return; } } }; $(document).ready(function() { pageTransitions(); // ADD SLIDEDOWN ANIMATION TO DROPDOWN // $('.dropdown').on('show.bs.dropdown', function(e){ $(this).find('.dropdown-menu').first().stop(true, true).slideDown(); }); // ADD SLIDEUP ANIMATION TO DROPDOWN // $('.dropdown').on('hide.bs.dropdown', function(e){ $(this).find('.dropdown-menu').first().stop(true, true).slideUp(); }); /* Sidebar menu */ $(function() { $('#sidebar-menu').superclick({ animation: { height: 'show' }, animationOut: { height: 'hide' } }); //automatically open the current path var path = window.location.pathname.split('/'); path = path[path.length-1]; if (path !== undefined) { $("#sidebar-menu").find("a[href$='" + path + "']").addClass('sfActive'); $("#sidebar-menu").find("a[href$='" + path + "']").parents().eq(3).superclick('show'); } }); /* Colapse sidebar */ $(function() { $('#close-sidebar').click(function() { $('body').toggleClass('closed-sidebar'); $('.glyph-icon', this).toggleClass('icon-angle-right').toggleClass('icon-angle-left'); }); }); /* Sidebar scroll */ });
mit
gef756/meta
src/analyzers/analyzer.cpp
4415
/** * @file analyzer.cpp */ #include "analyzers/analyzer_factory.h" #include "analyzers/filter_factory.h" #include "analyzers/multi_analyzer.h" #include "analyzers/token_stream.h" #include "analyzers/filters/alpha_filter.h" #include "analyzers/filters/empty_sentence_filter.h" #include "analyzers/filters/length_filter.h" #include "analyzers/filters/list_filter.h" #include "analyzers/filters/lowercase_filter.h" #include "analyzers/filters/porter2_stemmer.h" #include "analyzers/tokenizers/icu_tokenizer.h" #include "corpus/document.h" #include "cpptoml.h" #include "io/mmap_file.h" #include "util/shim.h" #include "utf/utf.h" namespace meta { namespace analyzers { std::string analyzer::get_content(const corpus::document& doc) { if (doc.contains_content()) return utf::to_utf8(doc.content(), doc.encoding()); io::mmap_file file{doc.path()}; return utf::to_utf8({file.begin(), file.size()}, doc.encoding()); } io::parser analyzer::create_parser(const corpus::document& doc, const std::string& extension, const std::string& delims) { if (doc.contains_content()) return io::parser{doc.content(), delims, io::parser::input_type::String}; else return io::parser{doc.path() + extension, delims, io::parser::input_type::File}; } namespace { std::unique_ptr<token_stream> add_default_filters(std::unique_ptr<token_stream> tokenizer, const cpptoml::table& config) { auto stopwords = config.get_as<std::string>("stop-words"); std::unique_ptr<token_stream> result; result = make_unique<filters::lowercase_filter>(std::move(tokenizer)); result = make_unique<filters::alpha_filter>(std::move(result)); result = make_unique<filters::length_filter>(std::move(result), 2, 35); result = make_unique<filters::list_filter>(std::move(result), *stopwords); result = make_unique<filters::porter2_stemmer>(std::move(result)); return result; } } std::unique_ptr<token_stream> analyzer::default_filter_chain(const cpptoml::table& config) { auto tokenizer = make_unique<tokenizers::icu_tokenizer>(); auto result = add_default_filters(std::move(tokenizer), config); result = make_unique<filters::empty_sentence_filter>(std::move(result)); return result; } std::unique_ptr<token_stream> analyzer::default_unigram_chain(const cpptoml::table& config) { // suppress "<s>", "</s>" auto tokenizer = make_unique<tokenizers::icu_tokenizer>(true); return add_default_filters(std::move(tokenizer), config); } std::unique_ptr<token_stream> analyzer::load_filter(std::unique_ptr<token_stream> src, const cpptoml::table& config) { auto type = config.get_as<std::string>("type"); if (!type) throw analyzer_exception{"filter type missing in config file"}; return filter_factory::get().create(*type, std::move(src), config); } std::unique_ptr<token_stream> analyzer::load_filters(const cpptoml::table& global, const cpptoml::table& config) { auto check = config.get_as<std::string>("filter"); if (check) { if (*check == "default-chain") return default_filter_chain(global); else if (*check == "default-unigram-chain") return default_unigram_chain(global); else throw analyzer_exception{"unknown filter option: " + *check}; } auto filters = config.get_table_array("filter"); if (!filters) throw analyzer_exception{"analyzer group missing filter configuration"}; std::unique_ptr<token_stream> result; for (const auto filter : filters->get()) result = load_filter(std::move(result), *filter); return result; } std::unique_ptr<analyzer> analyzer::load(const cpptoml::table& config) { using namespace analyzers; std::vector<std::unique_ptr<analyzer>> toks; auto analyzers = config.get_table_array("analyzers"); for (auto group : analyzers->get()) { auto method = group->get_as<std::string>("method"); if (!method) throw analyzer_exception{"failed to find analyzer method"}; toks.emplace_back( analyzer_factory::get().create(*method, config, *group)); } return make_unique<multi_analyzer>(std::move(toks)); } } }
mit
diogogmt/Ghost
core/client/app/models/setting.js
771
import DS from 'ember-data'; import ValidationEngine from 'ghost/mixins/validation-engine'; var Setting = DS.Model.extend(ValidationEngine, { validationType: 'setting', title: DS.attr('string'), description: DS.attr('string'), email: DS.attr('string'), logo: DS.attr('string'), cover: DS.attr('string'), defaultLang: DS.attr('string'), postsPerPage: DS.attr('number'), forceI18n: DS.attr('boolean'), permalinks: DS.attr('string'), activeTheme: DS.attr('string'), availableThemes: DS.attr(), ghost_head: DS.attr('string'), ghost_foot: DS.attr('string'), labs: DS.attr('string'), navigation: DS.attr('string'), isPrivate: DS.attr('boolean'), password: DS.attr('string') }); export default Setting;
mit
SabotageAndi/gherkin
python/setup.py
780
# coding: utf-8 from distutils.core import setup setup(name='gherkin-official', packages=['gherkin', 'gherkin.pickles'], version='4.0.0', description='Gherkin parser (official, by Cucumber team)', author='Cucumber Ltd and Björn Rasmusson', author_email='cukes@googlegroups.com', url='https://github.com/cucumber/gherkin-python', license='MIT', download_url='https://github.com/cucumber/gherkin-python/archive/v4.0.0.tar.gz', keywords=['gherkin', 'cucumber', 'bdd'], classifiers=['Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ], package_data={'gherkin': ['gherkin-languages.json']}, )
mit
yogeshsaroya/new-cdnjs
ajax/libs/yui/3.14.1/file/file-coverage.js
129
version https://git-lfs.github.com/spec/v1 oid sha256:7ecbf517637009b3ec86649ed30c98e36ae35dc89718fdb38e3c996d1838b9fd size 2924
mit
elpd/coop
library/Zend/Layout/Controller/Action/Helper/Layout.php
5086
<?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_Controller * @subpackage Zend_Controller_Action * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @version $Id: Layout.php 23775 2011-03-01 17:25:24Z ralph $ * @license http://framework.zend.com/license/new-bsd New BSD License */ /** Zend_Controller_Action_Helper_Abstract */ require_once 'Zend/Controller/Action/Helper/Abstract.php'; /** * Helper for interacting with Zend_Layout objects * * @uses Zend_Controller_Action_Helper_Abstract * @category Zend * @package Zend_Controller * @subpackage Zend_Controller_Action * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Layout_Controller_Action_Helper_Layout extends Zend_Controller_Action_Helper_Abstract { /** * @var Zend_Controller_Front */ protected $_frontController; /** * @var Zend_Layout */ protected $_layout; /** * @var bool */ protected $_isActionControllerSuccessful = false; /** * Constructor * * @param Zend_Layout $layout * @return void */ public function __construct(Zend_Layout $layout = null) { if (null !== $layout) { $this->setLayoutInstance($layout); } else { /** * @see Zend_Layout */ require_once 'Zend/Layout.php'; $layout = Zend_Layout::getMvcInstance(); } if (null !== $layout) { $pluginClass = $layout->getPluginClass(); $front = $this->getFrontController(); if ($front->hasPlugin($pluginClass)) { $plugin = $front->getPlugin($pluginClass); $plugin->setLayoutActionHelper($this); } } } public function init() { $this->_isActionControllerSuccessful = false; } /** * Get front controller instance * * @return Zend_Controller_Front */ public function getFrontController() { if (null === $this->_frontController) { /** * @see Zend_Controller_Front */ require_once 'Zend/Controller/Front.php'; $this->_frontController = Zend_Controller_Front::getInstance(); } return $this->_frontController; } /** * Get layout object * * @return Zend_Layout */ public function getLayoutInstance() { if (null === $this->_layout) { /** * @see Zend_Layout */ require_once 'Zend/Layout.php'; if (null === ($this->_layout = Zend_Layout::getMvcInstance())) { $this->_layout = new Zend_Layout(); } } return $this->_layout; } /** * Set layout object * * @param Zend_Layout $layout * @return Zend_Layout_Controller_Action_Helper_Layout */ public function setLayoutInstance(Zend_Layout $layout) { $this->_layout = $layout; return $this; } /** * Mark Action Controller (according to this plugin) as Running successfully * * @return Zend_Layout_Controller_Action_Helper_Layout */ public function postDispatch() { $this->_isActionControllerSuccessful = true; return $this; } /** * Did the previous action successfully complete? * * @return bool */ public function isActionControllerSuccessful() { return $this->_isActionControllerSuccessful; } /** * Strategy pattern; call object as method * * Returns layout object * * @return Zend_Layout */ public function direct() { return $this->getLayoutInstance(); } /** * Proxy method calls to layout object * * @param string $method * @param array $args * @return mixed */ public function __call($method, $args) { $layout = $this->getLayoutInstance(); if (method_exists($layout, $method)) { return call_user_func_array(array($layout, $method), $args); } require_once 'Zend/Layout/Exception.php'; throw new Zend_Layout_Exception(sprintf("Invalid method '%s' called on layout action helper", $method)); } }
mit
CGX-GROUP/DotSpatial
Source/DotSpatial.Tools.Tests/Properties/AssemblyInfo.cs
1445
// <autogenerated /> using System.Reflection; 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("DotSpatial.Tools.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DotSpatial.Tools.Tests")] [assembly: AssemblyCopyright("Copyright © DotSpatial Team 2012-2016")] [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("90dff2be-fc97-4e5a-9045-19101471a9ef")] // 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")] [assembly: AssemblyFileVersion("1.0")]
mit
ermshiperete/icu-dotnet
source/icu.net/Collation/AlternateHandling.cs
709
// Copyright (c) 2013 SIL International // This software is licensed under the MIT license (http://opensource.org/licenses/MIT) namespace Icu.Collation { /// <summary> /// Attribute for handling variable elements. /// </summary> public enum AlternateHandling { /// <summary> /// Default value that does nothing. /// </summary> Default = -1, /// <summary> /// causes codepoints with primary weights that are equal or below the variable top value ///to be ignored on primary level and moved to the quaternary level. /// </summary> Shifted = 20, /// <summary> /// treats all the codepoints with non-ignorable primary weights in the same way /// </summary> NonIgnorable = 21, } }
mit
asimbilaladil/waara-project
includes/website/assets/scripts/slick.js
70277
/* _ _ _ _ ___| (_) ___| | __ (_)___ / __| | |/ __| |/ / | / __| \__ \ | | (__| < _ | \__ \ |___/_|_|\___|_|\_(_)/ |___/ |__/ Version: 1.5.0 Author: Ken Wheeler Website: http://kenwheeler.github.io Docs: http://kenwheeler.github.io/slick Repo: http://github.com/kenwheeler/slick Issues: http://github.com/kenwheeler/slick/issues */ /* global window, document, define, jQuery, setInterval, clearInterval */ (function(factory) { 'use strict'; if (typeof define === 'function' && define.amd) { define(['jquery'], factory); } else if (typeof exports !== 'undefined') { module.exports = factory(require('jquery')); } else { factory(jQuery); } }(function($) { 'use strict'; var Slick = window.Slick || {}; Slick = (function() { var instanceUid = 0; function Slick(element, settings) { var _ = this, dataSettings, responsiveSettings, breakpoint; _.defaults = { accessibility: true, adaptiveHeight: false, appendArrows: $(element), appendDots: $(element), arrows: true, asNavFor: null, prevArrow: '<button type="button" data-role="none" class="slick-prev" aria-label="previous">Previous</button>', nextArrow: '<button type="button" data-role="none" class="slick-next" aria-label="next">Next</button>', autoplay: false, autoplaySpeed: 3000, centerMode: false, centerPadding: '50px', cssEase: 'ease', customPaging: function(slider, i) { return '<button type="button" data-role="none">' + (i + 1) + '</button>'; }, dots: false, dotsClass: 'slick-dots', draggable: true, easing: 'linear', edgeFriction: 0.35, fade: false, focusOnSelect: false, infinite: true, initialSlide: 0, lazyLoad: 'ondemand', mobileFirst: false, pauseOnHover: true, pauseOnDotsHover: false, respondTo: 'window', responsive: null, rows: 1, rtl: false, slide: '', slidesPerRow: 1, slidesToShow: 1, slidesToScroll: 1, speed: 500, swipe: true, swipeToSlide: false, touchMove: true, touchThreshold: 5, useCSS: true, variableWidth: false, vertical: false, verticalSwiping: false, waitForAnimate: true }; _.initials = { animating: false, dragging: false, autoPlayTimer: null, currentDirection: 0, currentLeft: null, currentSlide: 0, direction: 1, $dots: null, listWidth: null, listHeight: null, loadIndex: 0, $nextArrow: null, $prevArrow: null, slideCount: null, slideWidth: null, $slideTrack: null, $slides: null, sliding: false, slideOffset: 0, swipeLeft: null, $list: null, touchObject: {}, transformsEnabled: false }; $.extend(_, _.initials); _.activeBreakpoint = null; _.animType = null; _.animProp = null; _.breakpoints = []; _.breakpointSettings = []; _.cssTransitions = false; _.hidden = 'hidden'; _.paused = false; _.positionProp = null; _.respondTo = null; _.rowCount = 1; _.shouldClick = true; _.$slider = $(element); _.$slidesCache = null; _.transformType = null; _.transitionType = null; _.visibilityChange = 'visibilitychange'; _.windowWidth = 0; _.windowTimer = null; dataSettings = $(element).data('slick') || {}; _.options = $.extend({}, _.defaults, dataSettings, settings); _.currentSlide = _.options.initialSlide; _.originalSettings = _.options; responsiveSettings = _.options.responsive || null; if (responsiveSettings && responsiveSettings.length > -1) { _.respondTo = _.options.respondTo || 'window'; for (breakpoint in responsiveSettings) { if (responsiveSettings.hasOwnProperty(breakpoint)) { _.breakpoints.push(responsiveSettings[ breakpoint].breakpoint); _.breakpointSettings[responsiveSettings[ breakpoint].breakpoint] = responsiveSettings[breakpoint].settings; } } _.breakpoints.sort(function(a, b) { if (_.options.mobileFirst === true) { return a - b; } else { return b - a; } }); } if (typeof document.mozHidden !== 'undefined') { _.hidden = 'mozHidden'; _.visibilityChange = 'mozvisibilitychange'; } else if (typeof document.msHidden !== 'undefined') { _.hidden = 'msHidden'; _.visibilityChange = 'msvisibilitychange'; } else if (typeof document.webkitHidden !== 'undefined') { _.hidden = 'webkitHidden'; _.visibilityChange = 'webkitvisibilitychange'; } _.autoPlay = $.proxy(_.autoPlay, _); _.autoPlayClear = $.proxy(_.autoPlayClear, _); _.changeSlide = $.proxy(_.changeSlide, _); _.clickHandler = $.proxy(_.clickHandler, _); _.selectHandler = $.proxy(_.selectHandler, _); _.setPosition = $.proxy(_.setPosition, _); _.swipeHandler = $.proxy(_.swipeHandler, _); _.dragHandler = $.proxy(_.dragHandler, _); _.keyHandler = $.proxy(_.keyHandler, _); _.autoPlayIterator = $.proxy(_.autoPlayIterator, _); _.instanceUid = instanceUid++; // A simple way to check for HTML strings // Strict HTML recognition (must start with <) // Extracted from jQuery v1.11 source _.htmlExpr = /^(?:\s*(<[\w\W]+>)[^>]*)$/; _.init(); _.checkResponsive(true); } return Slick; }()); Slick.prototype.addSlide = Slick.prototype.slickAdd = function(markup, index, addBefore) { var _ = this; if (typeof(index) === 'boolean') { addBefore = index; index = null; } else if (index < 0 || (index >= _.slideCount)) { return false; } _.unload(); if (typeof(index) === 'number') { if (index === 0 && _.$slides.length === 0) { $(markup).appendTo(_.$slideTrack); } else if (addBefore) { $(markup).insertBefore(_.$slides.eq(index)); } else { $(markup).insertAfter(_.$slides.eq(index)); } } else { if (addBefore === true) { $(markup).prependTo(_.$slideTrack); } else { $(markup).appendTo(_.$slideTrack); } } _.$slides = _.$slideTrack.children(this.options.slide); _.$slideTrack.children(this.options.slide).detach(); _.$slideTrack.append(_.$slides); _.$slides.each(function(index, element) { $(element).attr('data-slick-index', index); }); _.$slidesCache = _.$slides; _.reinit(); }; Slick.prototype.animateHeight = function() { var _ = this; if (_.options.slidesToShow === 1 && _.options.adaptiveHeight === true && _.options.vertical === false) { var targetHeight = _.$slides.eq(_.currentSlide).outerHeight(true); _.$list.animate({ height: targetHeight }, _.options.speed); } }; Slick.prototype.animateSlide = function(targetLeft, callback) { var animProps = {}, _ = this; _.animateHeight(); if (_.options.rtl === true && _.options.vertical === false) { targetLeft = -targetLeft; } if (_.transformsEnabled === false) { if (_.options.vertical === false) { _.$slideTrack.animate({ left: targetLeft }, _.options.speed, _.options.easing, callback); } else { _.$slideTrack.animate({ top: targetLeft }, _.options.speed, _.options.easing, callback); } } else { if (_.cssTransitions === false) { if (_.options.rtl === true) { _.currentLeft = -(_.currentLeft); } $({ animStart: _.currentLeft }).animate({ animStart: targetLeft }, { duration: _.options.speed, easing: _.options.easing, step: function(now) { now = Math.ceil(now); if (_.options.vertical === false) { animProps[_.animType] = 'translate(' + now + 'px, 0px)'; _.$slideTrack.css(animProps); } else { animProps[_.animType] = 'translate(0px,' + now + 'px)'; _.$slideTrack.css(animProps); } }, complete: function() { if (callback) { callback.call(); } } }); } else { _.applyTransition(); targetLeft = Math.ceil(targetLeft); if (_.options.vertical === false) { animProps[_.animType] = 'translate3d(' + targetLeft + 'px, 0px, 0px)'; } else { animProps[_.animType] = 'translate3d(0px,' + targetLeft + 'px, 0px)'; } _.$slideTrack.css(animProps); if (callback) { setTimeout(function() { _.disableTransition(); callback.call(); }, _.options.speed); } } } }; Slick.prototype.asNavFor = function(index) { var _ = this, asNavFor = _.options.asNavFor !== null ? $(_.options.asNavFor).slick('getSlick') : null; if (asNavFor !== null) asNavFor.slideHandler(index, true); }; Slick.prototype.applyTransition = function(slide) { var _ = this, transition = {}; if (_.options.fade === false) { transition[_.transitionType] = _.transformType + ' ' + _.options.speed + 'ms ' + _.options.cssEase; } else { transition[_.transitionType] = 'opacity ' + _.options.speed + 'ms ' + _.options.cssEase; } if (_.options.fade === false) { _.$slideTrack.css(transition); } else { _.$slides.eq(slide).css(transition); } }; Slick.prototype.autoPlay = function() { var _ = this; if (_.autoPlayTimer) { clearInterval(_.autoPlayTimer); } if (_.slideCount > _.options.slidesToShow && _.paused !== true) { _.autoPlayTimer = setInterval(_.autoPlayIterator, _.options.autoplaySpeed); } }; Slick.prototype.autoPlayClear = function() { var _ = this; if (_.autoPlayTimer) { clearInterval(_.autoPlayTimer); } }; Slick.prototype.autoPlayIterator = function() { var _ = this; if (_.options.infinite === false) { if (_.direction === 1) { if ((_.currentSlide + 1) === _.slideCount - 1) { _.direction = 0; } _.slideHandler(_.currentSlide + _.options.slidesToScroll); } else { if ((_.currentSlide - 1 === 0)) { _.direction = 1; } _.slideHandler(_.currentSlide - _.options.slidesToScroll); } } else { _.slideHandler(_.currentSlide + _.options.slidesToScroll); } }; Slick.prototype.buildArrows = function() { var _ = this; if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) { _.$prevArrow = $(_.options.prevArrow); _.$nextArrow = $(_.options.nextArrow); if (_.htmlExpr.test(_.options.prevArrow)) { _.$prevArrow.appendTo(_.options.appendArrows); } if (_.htmlExpr.test(_.options.nextArrow)) { _.$nextArrow.appendTo(_.options.appendArrows); } if (_.options.infinite !== true) { _.$prevArrow.addClass('slick-disabled'); } } }; Slick.prototype.buildDots = function() { var _ = this, i, dotString; if (_.options.dots === true && _.slideCount > _.options.slidesToShow) { dotString = '<ul class="' + _.options.dotsClass + '">'; for (i = 0; i <= _.getDotCount(); i += 1) { dotString += '<li>' + _.options.customPaging.call(this, _, i) + '</li>'; } dotString += '</ul>'; _.$dots = $(dotString).appendTo( _.options.appendDots); _.$dots.find('li').first().addClass('slick-active').attr('aria-hidden', 'false'); } }; Slick.prototype.buildOut = function() { var _ = this; _.$slides = _.$slider.children( ':not(.slick-cloned)').addClass( 'slick-slide'); _.slideCount = _.$slides.length; _.$slides.each(function(index, element) { $(element).attr('data-slick-index', index); }); _.$slidesCache = _.$slides; _.$slider.addClass('slick-slider'); _.$slideTrack = (_.slideCount === 0) ? $('<div class="slick-track"/>').appendTo(_.$slider) : _.$slides.wrapAll('<div class="slick-track"/>').parent(); _.$list = _.$slideTrack.wrap( '<div aria-live="polite" class="slick-list"/>').parent(); _.$slideTrack.css('opacity', 0); if (_.options.centerMode === true || _.options.swipeToSlide === true) { _.options.slidesToScroll = 1; } $('img[data-lazy]', _.$slider).not('[src]').addClass('slick-loading'); _.setupInfinite(); _.buildArrows(); _.buildDots(); _.updateDots(); if (_.options.accessibility === true) { _.$list.prop('tabIndex', 0); } _.setSlideClasses(typeof this.currentSlide === 'number' ? this.currentSlide : 0); if (_.options.draggable === true) { _.$list.addClass('draggable'); } }; Slick.prototype.buildRows = function() { var _ = this, a, b, c, newSlides, numOfSlides, originalSlides,slidesPerSection; newSlides = document.createDocumentFragment(); originalSlides = _.$slider.children(); if(_.options.rows > 1) { slidesPerSection = _.options.slidesPerRow * _.options.rows; numOfSlides = Math.ceil( originalSlides.length / slidesPerSection ); for(a = 0; a < numOfSlides; a++){ var slide = document.createElement('div'); for(b = 0; b < _.options.rows; b++) { var row = document.createElement('div'); for(c = 0; c < _.options.slidesPerRow; c++) { var target = (a * slidesPerSection + ((b * _.options.slidesPerRow) + c)); if (originalSlides.get(target)) { row.appendChild(originalSlides.get(target)); } } slide.appendChild(row); } newSlides.appendChild(slide); }; _.$slider.html(newSlides); _.$slider.children().children().children() .width((100 / _.options.slidesPerRow) + "%") .css({'display': 'inline-block'}); }; }; Slick.prototype.checkResponsive = function(initial) { var _ = this, breakpoint, targetBreakpoint, respondToWidth; var sliderWidth = _.$slider.width(); var windowWidth = window.innerWidth || $(window).width(); if (_.respondTo === 'window') { respondToWidth = windowWidth; } else if (_.respondTo === 'slider') { respondToWidth = sliderWidth; } else if (_.respondTo === 'min') { respondToWidth = Math.min(windowWidth, sliderWidth); } if (_.originalSettings.responsive && _.originalSettings .responsive.length > -1 && _.originalSettings.responsive !== null) { targetBreakpoint = null; for (breakpoint in _.breakpoints) { if (_.breakpoints.hasOwnProperty(breakpoint)) { if (_.originalSettings.mobileFirst === false) { if (respondToWidth < _.breakpoints[breakpoint]) { targetBreakpoint = _.breakpoints[breakpoint]; } } else { if (respondToWidth > _.breakpoints[breakpoint]) { targetBreakpoint = _.breakpoints[breakpoint]; } } } } if (targetBreakpoint !== null) { if (_.activeBreakpoint !== null) { if (targetBreakpoint !== _.activeBreakpoint) { _.activeBreakpoint = targetBreakpoint; if (_.breakpointSettings[targetBreakpoint] === 'unslick') { _.unslick(); } else { _.options = $.extend({}, _.originalSettings, _.breakpointSettings[ targetBreakpoint]); if (initial === true) _.currentSlide = _.options.initialSlide; _.refresh(); } } } else { _.activeBreakpoint = targetBreakpoint; if (_.breakpointSettings[targetBreakpoint] === 'unslick') { _.unslick(); } else { _.options = $.extend({}, _.originalSettings, _.breakpointSettings[ targetBreakpoint]); if (initial === true) _.currentSlide = _.options.initialSlide; _.refresh(); } } } else { if (_.activeBreakpoint !== null) { _.activeBreakpoint = null; _.options = _.originalSettings; if (initial === true) _.currentSlide = _.options.initialSlide; _.refresh(); } } } }; Slick.prototype.changeSlide = function(event, dontAnimate) { var _ = this, $target = $(event.target), indexOffset, slideOffset, unevenOffset; // If target is a link, prevent default action. $target.is('a') && event.preventDefault(); unevenOffset = (_.slideCount % _.options.slidesToScroll !== 0); indexOffset = unevenOffset ? 0 : (_.slideCount - _.currentSlide) % _.options.slidesToScroll; switch (event.data.message) { case 'previous': slideOffset = indexOffset === 0 ? _.options.slidesToScroll : _.options.slidesToShow - indexOffset; if (_.slideCount > _.options.slidesToShow) { _.slideHandler(_.currentSlide - slideOffset, false, dontAnimate); } break; case 'next': slideOffset = indexOffset === 0 ? _.options.slidesToScroll : indexOffset; if (_.slideCount > _.options.slidesToShow) { _.slideHandler(_.currentSlide + slideOffset, false, dontAnimate); } break; case 'index': var index = event.data.index === 0 ? 0 : event.data.index || $(event.target).parent().index() * _.options.slidesToScroll; _.slideHandler(_.checkNavigable(index), false, dontAnimate); break; default: return; } }; Slick.prototype.checkNavigable = function(index) { var _ = this, navigables, prevNavigable; navigables = _.getNavigableIndexes(); prevNavigable = 0; if (index > navigables[navigables.length - 1]) { index = navigables[navigables.length - 1]; } else { for (var n in navigables) { if (index < navigables[n]) { index = prevNavigable; break; } prevNavigable = navigables[n]; } } return index; }; Slick.prototype.cleanUpEvents = function() { var _ = this; if (_.options.dots === true && _.slideCount > _.options.slidesToShow) { $('li', _.$dots).off('click.slick', _.changeSlide); } if (_.options.dots === true && _.options.pauseOnDotsHover === true && _.options.autoplay === true) { $('li', _.$dots) .off('mouseenter.slick', _.setPaused.bind(_, true)) .off('mouseleave.slick', _.setPaused.bind(_, false)); } if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) { _.$prevArrow && _.$prevArrow.off('click.slick', _.changeSlide); _.$nextArrow && _.$nextArrow.off('click.slick', _.changeSlide); } _.$list.off('touchstart.slick mousedown.slick', _.swipeHandler); _.$list.off('touchmove.slick mousemove.slick', _.swipeHandler); _.$list.off('touchend.slick mouseup.slick', _.swipeHandler); _.$list.off('touchcancel.slick mouseleave.slick', _.swipeHandler); _.$list.off('click.slick', _.clickHandler); if (_.options.autoplay === true) { $(document).off(_.visibilityChange, _.visibility); } _.$list.off('mouseenter.slick', _.setPaused.bind(_, true)); _.$list.off('mouseleave.slick', _.setPaused.bind(_, false)); if (_.options.accessibility === true) { _.$list.off('keydown.slick', _.keyHandler); } if (_.options.focusOnSelect === true) { $(_.$slideTrack).children().off('click.slick', _.selectHandler); } $(window).off('orientationchange.slick.slick-' + _.instanceUid, _.orientationChange); $(window).off('resize.slick.slick-' + _.instanceUid, _.resize); $('[draggable!=true]', _.$slideTrack).off('dragstart', _.preventDefault); $(window).off('load.slick.slick-' + _.instanceUid, _.setPosition); $(document).off('ready.slick.slick-' + _.instanceUid, _.setPosition); }; Slick.prototype.cleanUpRows = function() { var _ = this, originalSlides; if(_.options.rows > 1) { originalSlides = _.$slides.children().children(); originalSlides.removeAttr('style'); _.$slider.html(originalSlides); } }; Slick.prototype.clickHandler = function(event) { var _ = this; if (_.shouldClick === false) { event.stopImmediatePropagation(); event.stopPropagation(); event.preventDefault(); } }; Slick.prototype.destroy = function() { var _ = this; _.autoPlayClear(); _.touchObject = {}; _.cleanUpEvents(); $('.slick-cloned', _.$slider).remove(); if (_.$dots) { _.$dots.remove(); } if (_.$prevArrow && (typeof _.options.prevArrow !== 'object')) { _.$prevArrow.remove(); } if (_.$nextArrow && (typeof _.options.nextArrow !== 'object')) { _.$nextArrow.remove(); } if (_.$slides) { _.$slides.removeClass('slick-slide slick-active slick-center slick-visible') .attr('aria-hidden', 'true') .removeAttr('data-slick-index') .css({ position: '', left: '', top: '', zIndex: '', opacity: '', width: '' }); _.$slider.html(_.$slides); } _.cleanUpRows(); _.$slider.removeClass('slick-slider'); _.$slider.removeClass('slick-initialized'); }; Slick.prototype.disableTransition = function(slide) { var _ = this, transition = {}; transition[_.transitionType] = ''; if (_.options.fade === false) { _.$slideTrack.css(transition); } else { _.$slides.eq(slide).css(transition); } }; Slick.prototype.fadeSlide = function(slideIndex, callback) { var _ = this; if (_.cssTransitions === false) { _.$slides.eq(slideIndex).css({ zIndex: 1000 }); _.$slides.eq(slideIndex).animate({ opacity: 1 }, _.options.speed, _.options.easing, callback); } else { _.applyTransition(slideIndex); _.$slides.eq(slideIndex).css({ opacity: 1, zIndex: 1000 }); if (callback) { setTimeout(function() { _.disableTransition(slideIndex); callback.call(); }, _.options.speed); } } }; Slick.prototype.filterSlides = Slick.prototype.slickFilter = function(filter) { var _ = this; if (filter !== null) { _.unload(); _.$slideTrack.children(this.options.slide).detach(); _.$slidesCache.filter(filter).appendTo(_.$slideTrack); _.reinit(); } }; Slick.prototype.getCurrent = Slick.prototype.slickCurrentSlide = function() { var _ = this; return _.currentSlide; }; Slick.prototype.getDotCount = function() { var _ = this; var breakPoint = 0; var counter = 0; var pagerQty = 0; if (_.options.infinite === true) { pagerQty = Math.ceil(_.slideCount / _.options.slidesToScroll); } else if (_.options.centerMode === true) { pagerQty = _.slideCount; } else { while (breakPoint < _.slideCount) { ++pagerQty; breakPoint = counter + _.options.slidesToShow; counter += _.options.slidesToScroll <= _.options.slidesToShow ? _.options.slidesToScroll : _.options.slidesToShow; } } return pagerQty - 1; }; Slick.prototype.getLeft = function(slideIndex) { var _ = this, targetLeft, verticalHeight, verticalOffset = 0, targetSlide; _.slideOffset = 0; verticalHeight = _.$slides.first().outerHeight(); if (_.options.infinite === true) { if (_.slideCount > _.options.slidesToShow) { _.slideOffset = (_.slideWidth * _.options.slidesToShow) * -1; verticalOffset = (verticalHeight * _.options.slidesToShow) * -1; } if (_.slideCount % _.options.slidesToScroll !== 0) { if (slideIndex + _.options.slidesToScroll > _.slideCount && _.slideCount > _.options.slidesToShow) { if (slideIndex > _.slideCount) { _.slideOffset = ((_.options.slidesToShow - (slideIndex - _.slideCount)) * _.slideWidth) * -1; verticalOffset = ((_.options.slidesToShow - (slideIndex - _.slideCount)) * verticalHeight) * -1; } else { _.slideOffset = ((_.slideCount % _.options.slidesToScroll) * _.slideWidth) * -1; verticalOffset = ((_.slideCount % _.options.slidesToScroll) * verticalHeight) * -1; } } } } else { if (slideIndex + _.options.slidesToShow > _.slideCount) { _.slideOffset = ((slideIndex + _.options.slidesToShow) - _.slideCount) * _.slideWidth; verticalOffset = ((slideIndex + _.options.slidesToShow) - _.slideCount) * verticalHeight; } } if (_.slideCount <= _.options.slidesToShow) { _.slideOffset = 0; verticalOffset = 0; } if (_.options.centerMode === true && _.options.infinite === true) { _.slideOffset += _.slideWidth * Math.floor(_.options.slidesToShow / 2) - _.slideWidth; } else if (_.options.centerMode === true) { _.slideOffset = 0; _.slideOffset += _.slideWidth * Math.floor(_.options.slidesToShow / 2); } if (_.options.vertical === false) { targetLeft = ((slideIndex * _.slideWidth) * -1) + _.slideOffset; } else { targetLeft = ((slideIndex * verticalHeight) * -1) + verticalOffset; } if (_.options.variableWidth === true) { if (_.slideCount <= _.options.slidesToShow || _.options.infinite === false) { targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex); } else { targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex + _.options.slidesToShow); } targetLeft = targetSlide[0] ? targetSlide[0].offsetLeft * -1 : 0; if (_.options.centerMode === true) { if (_.options.infinite === false) { targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex); } else { targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex + _.options.slidesToShow + 1); } targetLeft = targetSlide[0] ? targetSlide[0].offsetLeft * -1 : 0; targetLeft += (_.$list.width() - targetSlide.outerWidth()) / 2; } } return targetLeft; }; Slick.prototype.getOption = Slick.prototype.slickGetOption = function(option) { var _ = this; return _.options[option]; }; Slick.prototype.getNavigableIndexes = function() { var _ = this, breakPoint = 0, counter = 0, indexes = [], max; if (_.options.infinite === false) { max = _.slideCount - _.options.slidesToShow + 1; if (_.options.centerMode === true) max = _.slideCount; } else { breakPoint = _.options.slidesToScroll * -1; counter = _.options.slidesToScroll * -1; max = _.slideCount * 2; } while (breakPoint < max) { indexes.push(breakPoint); breakPoint = counter + _.options.slidesToScroll; counter += _.options.slidesToScroll <= _.options.slidesToShow ? _.options.slidesToScroll : _.options.slidesToShow; } return indexes; }; Slick.prototype.getSlick = function() { return this; }; Slick.prototype.getSlideCount = function() { var _ = this, slidesTraversed, swipedSlide, centerOffset; centerOffset = _.options.centerMode === true ? _.slideWidth * Math.floor(_.options.slidesToShow / 2) : 0; if (_.options.swipeToSlide === true) { _.$slideTrack.find('.slick-slide').each(function(index, slide) { if (slide.offsetLeft - centerOffset + ($(slide).outerWidth() / 2) > (_.swipeLeft * -1)) { swipedSlide = slide; return false; } }); slidesTraversed = Math.abs($(swipedSlide).attr('data-slick-index') - _.currentSlide) || 1; return slidesTraversed; } else { return _.options.slidesToScroll; } }; Slick.prototype.goTo = Slick.prototype.slickGoTo = function(slide, dontAnimate) { var _ = this; _.changeSlide({ data: { message: 'index', index: parseInt(slide) } }, dontAnimate); }; Slick.prototype.init = function() { var _ = this; if (!$(_.$slider).hasClass('slick-initialized')) { $(_.$slider).addClass('slick-initialized'); _.buildRows(); _.buildOut(); _.setProps(); _.startLoad(); _.loadSlider(); _.initializeEvents(); _.updateArrows(); _.updateDots(); } _.$slider.trigger('init', [_]); }; Slick.prototype.initArrowEvents = function() { var _ = this; if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) { _.$prevArrow.on('click.slick', { message: 'previous' }, _.changeSlide); _.$nextArrow.on('click.slick', { message: 'next' }, _.changeSlide); } }; Slick.prototype.initDotEvents = function() { var _ = this; if (_.options.dots === true && _.slideCount > _.options.slidesToShow) { $('li', _.$dots).on('click.slick', { message: 'index' }, _.changeSlide); } if (_.options.dots === true && _.options.pauseOnDotsHover === true && _.options.autoplay === true) { $('li', _.$dots) .on('mouseenter.slick', _.setPaused.bind(_, true)) .on('mouseleave.slick', _.setPaused.bind(_, false)); } }; Slick.prototype.initializeEvents = function() { var _ = this; _.initArrowEvents(); _.initDotEvents(); _.$list.on('touchstart.slick mousedown.slick', { action: 'start' }, _.swipeHandler); _.$list.on('touchmove.slick mousemove.slick', { action: 'move' }, _.swipeHandler); _.$list.on('touchend.slick mouseup.slick', { action: 'end' }, _.swipeHandler); _.$list.on('touchcancel.slick mouseleave.slick', { action: 'end' }, _.swipeHandler); _.$list.on('click.slick', _.clickHandler); if (_.options.autoplay === true) { $(document).on(_.visibilityChange, _.visibility.bind(_)); } _.$list.on('mouseenter.slick', _.setPaused.bind(_, true)); _.$list.on('mouseleave.slick', _.setPaused.bind(_, false)); if (_.options.accessibility === true) { _.$list.on('keydown.slick', _.keyHandler); } if (_.options.focusOnSelect === true) { $(_.$slideTrack).children().on('click.slick', _.selectHandler); } $(window).on('orientationchange.slick.slick-' + _.instanceUid, _.orientationChange.bind(_)); $(window).on('resize.slick.slick-' + _.instanceUid, _.resize.bind(_)); $('[draggable!=true]', _.$slideTrack).on('dragstart', _.preventDefault); $(window).on('load.slick.slick-' + _.instanceUid, _.setPosition); $(document).on('ready.slick.slick-' + _.instanceUid, _.setPosition); }; Slick.prototype.initUI = function() { var _ = this; if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) { _.$prevArrow.show(); _.$nextArrow.show(); } if (_.options.dots === true && _.slideCount > _.options.slidesToShow) { _.$dots.show(); } if (_.options.autoplay === true) { _.autoPlay(); } }; Slick.prototype.keyHandler = function(event) { var _ = this; if (event.keyCode === 37 && _.options.accessibility === true) { _.changeSlide({ data: { message: 'previous' } }); } else if (event.keyCode === 39 && _.options.accessibility === true) { _.changeSlide({ data: { message: 'next' } }); } }; Slick.prototype.lazyLoad = function() { var _ = this, loadRange, cloneRange, rangeStart, rangeEnd; function loadImages(imagesScope) { $('img[data-lazy]', imagesScope).each(function() { var image = $(this), imageSource = $(this).attr('data-lazy'), imageToLoad = document.createElement('img'); imageToLoad.onload = function() { image.animate({ opacity: 1 }, 200); }; imageToLoad.src = imageSource; image .css({ opacity: 0 }) .attr('src', imageSource) .removeAttr('data-lazy') .removeClass('slick-loading'); }); } if (_.options.centerMode === true) { if (_.options.infinite === true) { rangeStart = _.currentSlide + (_.options.slidesToShow / 2 + 1); rangeEnd = rangeStart + _.options.slidesToShow + 2; } else { rangeStart = Math.max(0, _.currentSlide - (_.options.slidesToShow / 2 + 1)); rangeEnd = 2 + (_.options.slidesToShow / 2 + 1) + _.currentSlide; } } else { rangeStart = _.options.infinite ? _.options.slidesToShow + _.currentSlide : _.currentSlide; rangeEnd = rangeStart + _.options.slidesToShow; if (_.options.fade === true) { if (rangeStart > 0) rangeStart--; if (rangeEnd <= _.slideCount) rangeEnd++; } } loadRange = _.$slider.find('.slick-slide').slice(rangeStart, rangeEnd); loadImages(loadRange); if (_.slideCount <= _.options.slidesToShow) { cloneRange = _.$slider.find('.slick-slide'); loadImages(cloneRange); } else if (_.currentSlide >= _.slideCount - _.options.slidesToShow) { cloneRange = _.$slider.find('.slick-cloned').slice(0, _.options.slidesToShow); loadImages(cloneRange); } else if (_.currentSlide === 0) { cloneRange = _.$slider.find('.slick-cloned').slice(_.options.slidesToShow * -1); loadImages(cloneRange); } }; Slick.prototype.loadSlider = function() { var _ = this; _.setPosition(); _.$slideTrack.css({ opacity: 1 }); _.$slider.removeClass('slick-loading'); _.initUI(); if (_.options.lazyLoad === 'progressive') { _.progressiveLazyLoad(); } }; Slick.prototype.next = Slick.prototype.slickNext = function() { var _ = this; _.changeSlide({ data: { message: 'next' } }); }; Slick.prototype.orientationChange = function() { var _ = this; _.checkResponsive(); _.setPosition(); }; Slick.prototype.pause = Slick.prototype.slickPause = function() { var _ = this; _.autoPlayClear(); _.paused = true; }; Slick.prototype.play = Slick.prototype.slickPlay = function() { var _ = this; _.paused = false; _.autoPlay(); }; Slick.prototype.postSlide = function(index) { var _ = this; _.$slider.trigger('afterChange', [_, index]); _.animating = false; _.setPosition(); _.swipeLeft = null; if (_.options.autoplay === true && _.paused === false) { _.autoPlay(); } }; Slick.prototype.prev = Slick.prototype.slickPrev = function() { var _ = this; _.changeSlide({ data: { message: 'previous' } }); }; Slick.prototype.preventDefault = function(e) { e.preventDefault(); }; Slick.prototype.progressiveLazyLoad = function() { var _ = this, imgCount, targetImage; imgCount = $('img[data-lazy]', _.$slider).length; if (imgCount > 0) { targetImage = $('img[data-lazy]', _.$slider).first(); targetImage.attr('src', targetImage.attr('data-lazy')).removeClass('slick-loading').load(function() { targetImage.removeAttr('data-lazy'); _.progressiveLazyLoad(); if (_.options.adaptiveHeight === true) { _.setPosition(); } }) .error(function() { targetImage.removeAttr('data-lazy'); _.progressiveLazyLoad(); }); } }; Slick.prototype.refresh = function() { var _ = this, currentSlide = _.currentSlide; _.destroy(); $.extend(_, _.initials); _.init(); _.changeSlide({ data: { message: 'index', index: currentSlide } }, false); }; Slick.prototype.reinit = function() { var _ = this; _.$slides = _.$slideTrack.children(_.options.slide).addClass( 'slick-slide'); _.slideCount = _.$slides.length; if (_.currentSlide >= _.slideCount && _.currentSlide !== 0) { _.currentSlide = _.currentSlide - _.options.slidesToScroll; } if (_.slideCount <= _.options.slidesToShow) { _.currentSlide = 0; } _.setProps(); _.setupInfinite(); _.buildArrows(); _.updateArrows(); _.initArrowEvents(); _.buildDots(); _.updateDots(); _.initDotEvents(); if (_.options.focusOnSelect === true) { $(_.$slideTrack).children().on('click.slick', _.selectHandler); } _.setSlideClasses(0); _.setPosition(); _.$slider.trigger('reInit', [_]); }; Slick.prototype.resize = function() { var _ = this; if ($(window).width() !== _.windowWidth) { clearTimeout(_.windowDelay); _.windowDelay = window.setTimeout(function() { _.windowWidth = $(window).width(); _.checkResponsive(); _.setPosition(); }, 50); } }; Slick.prototype.removeSlide = Slick.prototype.slickRemove = function(index, removeBefore, removeAll) { var _ = this; if (typeof(index) === 'boolean') { removeBefore = index; index = removeBefore === true ? 0 : _.slideCount - 1; } else { index = removeBefore === true ? --index : index; } if (_.slideCount < 1 || index < 0 || index > _.slideCount - 1) { return false; } _.unload(); if (removeAll === true) { _.$slideTrack.children().remove(); } else { _.$slideTrack.children(this.options.slide).eq(index).remove(); } _.$slides = _.$slideTrack.children(this.options.slide); _.$slideTrack.children(this.options.slide).detach(); _.$slideTrack.append(_.$slides); _.$slidesCache = _.$slides; _.reinit(); }; Slick.prototype.setCSS = function(position) { var _ = this, positionProps = {}, x, y; if (_.options.rtl === true) { position = -position; } x = _.positionProp == 'left' ? Math.ceil(position) + 'px' : '0px'; y = _.positionProp == 'top' ? Math.ceil(position) + 'px' : '0px'; positionProps[_.positionProp] = position; if (_.transformsEnabled === false) { _.$slideTrack.css(positionProps); } else { positionProps = {}; if (_.cssTransitions === false) { positionProps[_.animType] = 'translate(' + x + ', ' + y + ')'; _.$slideTrack.css(positionProps); } else { positionProps[_.animType] = 'translate3d(' + x + ', ' + y + ', 0px)'; _.$slideTrack.css(positionProps); } } }; Slick.prototype.setDimensions = function() { var _ = this; if (_.options.vertical === false) { if (_.options.centerMode === true) { _.$list.css({ padding: ('0px ' + _.options.centerPadding) }); } } else { _.$list.height(_.$slides.first().outerHeight(true) * _.options.slidesToShow); if (_.options.centerMode === true) { _.$list.css({ padding: (_.options.centerPadding + ' 0px') }); } } _.listWidth = _.$list.width(); _.listHeight = _.$list.height(); if (_.options.vertical === false && _.options.variableWidth === false) { _.slideWidth = Math.ceil(_.listWidth / _.options.slidesToShow); _.$slideTrack.width(Math.ceil((_.slideWidth * _.$slideTrack.children('.slick-slide').length))); } else if (_.options.variableWidth === true) { _.$slideTrack.width(5000 * _.slideCount); } else { _.slideWidth = Math.ceil(_.listWidth); _.$slideTrack.height(Math.ceil((_.$slides.first().outerHeight(true) * _.$slideTrack.children('.slick-slide').length))); } var offset = _.$slides.first().outerWidth(true) - _.$slides.first().width(); if (_.options.variableWidth === false) _.$slideTrack.children('.slick-slide').width(_.slideWidth - offset); }; Slick.prototype.setFade = function() { var _ = this, targetLeft; _.$slides.each(function(index, element) { targetLeft = (_.slideWidth * index) * -1; if (_.options.rtl === true) { $(element).css({ position: 'relative', right: targetLeft, top: 0, zIndex: 800, opacity: 0 }); } else { $(element).css({ position: 'relative', left: targetLeft, top: 0, zIndex: 800, opacity: 0 }); } }); _.$slides.eq(_.currentSlide).css({ zIndex: 900, opacity: 1 }); }; Slick.prototype.setHeight = function() { var _ = this; if (_.options.slidesToShow === 1 && _.options.adaptiveHeight === true && _.options.vertical === false) { var targetHeight = _.$slides.eq(_.currentSlide).outerHeight(true); _.$list.css('height', targetHeight); } }; Slick.prototype.setOption = Slick.prototype.slickSetOption = function(option, value, refresh) { var _ = this; _.options[option] = value; if (refresh === true) { _.unload(); _.reinit(); } }; Slick.prototype.setPosition = function() { var _ = this; _.setDimensions(); _.setHeight(); if (_.options.fade === false) { _.setCSS(_.getLeft(_.currentSlide)); } else { _.setFade(); } _.$slider.trigger('setPosition', [_]); }; Slick.prototype.setProps = function() { var _ = this, bodyStyle = document.body.style; _.positionProp = _.options.vertical === true ? 'top' : 'left'; if (_.positionProp === 'top') { _.$slider.addClass('slick-vertical'); } else { _.$slider.removeClass('slick-vertical'); } if (bodyStyle.WebkitTransition !== undefined || bodyStyle.MozTransition !== undefined || bodyStyle.msTransition !== undefined) { if (_.options.useCSS === true) { _.cssTransitions = true; } } if (bodyStyle.OTransform !== undefined) { _.animType = 'OTransform'; _.transformType = '-o-transform'; _.transitionType = 'OTransition'; if (bodyStyle.perspectiveProperty === undefined && bodyStyle.webkitPerspective === undefined) _.animType = false; } if (bodyStyle.MozTransform !== undefined) { _.animType = 'MozTransform'; _.transformType = '-moz-transform'; _.transitionType = 'MozTransition'; if (bodyStyle.perspectiveProperty === undefined && bodyStyle.MozPerspective === undefined) _.animType = false; } if (bodyStyle.webkitTransform !== undefined) { _.animType = 'webkitTransform'; _.transformType = '-webkit-transform'; _.transitionType = 'webkitTransition'; if (bodyStyle.perspectiveProperty === undefined && bodyStyle.webkitPerspective === undefined) _.animType = false; } if (bodyStyle.msTransform !== undefined) { _.animType = 'msTransform'; _.transformType = '-ms-transform'; _.transitionType = 'msTransition'; if (bodyStyle.msTransform === undefined) _.animType = false; } if (bodyStyle.transform !== undefined && _.animType !== false) { _.animType = 'transform'; _.transformType = 'transform'; _.transitionType = 'transition'; } _.transformsEnabled = (_.animType !== null && _.animType !== false); }; Slick.prototype.setSlideClasses = function(index) { var _ = this, centerOffset, allSlides, indexOffset, remainder; _.$slider.find('.slick-slide').removeClass('slick-active').attr('aria-hidden', 'true').removeClass('slick-center'); allSlides = _.$slider.find('.slick-slide'); if (_.options.centerMode === true) { centerOffset = Math.floor(_.options.slidesToShow / 2); if (_.options.infinite === true) { if (index >= centerOffset && index <= (_.slideCount - 1) - centerOffset) { _.$slides.slice(index - centerOffset, index + centerOffset + 1).addClass('slick-active').attr('aria-hidden', 'false'); } else { indexOffset = _.options.slidesToShow + index; allSlides.slice(indexOffset - centerOffset + 1, indexOffset + centerOffset + 2).addClass('slick-active').attr('aria-hidden', 'false'); } if (index === 0) { allSlides.eq(allSlides.length - 1 - _.options.slidesToShow).addClass('slick-center'); } else if (index === _.slideCount - 1) { allSlides.eq(_.options.slidesToShow).addClass('slick-center'); } } _.$slides.eq(index).addClass('slick-center'); } else { if (index >= 0 && index <= (_.slideCount - _.options.slidesToShow)) { _.$slides.slice(index, index + _.options.slidesToShow).addClass('slick-active').attr('aria-hidden', 'false'); } else if (allSlides.length <= _.options.slidesToShow) { allSlides.addClass('slick-active').attr('aria-hidden', 'false'); } else { remainder = _.slideCount % _.options.slidesToShow; indexOffset = _.options.infinite === true ? _.options.slidesToShow + index : index; if (_.options.slidesToShow == _.options.slidesToScroll && (_.slideCount - index) < _.options.slidesToShow) { allSlides.slice(indexOffset - (_.options.slidesToShow - remainder), indexOffset + remainder).addClass('slick-active').attr('aria-hidden', 'false'); } else { allSlides.slice(indexOffset, indexOffset + _.options.slidesToShow).addClass('slick-active').attr('aria-hidden', 'false'); } } } if (_.options.lazyLoad === 'ondemand') { _.lazyLoad(); } }; Slick.prototype.setupInfinite = function() { var _ = this, i, slideIndex, infiniteCount; if (_.options.fade === true) { _.options.centerMode = false; } if (_.options.infinite === true && _.options.fade === false) { slideIndex = null; if (_.slideCount > _.options.slidesToShow) { if (_.options.centerMode === true) { infiniteCount = _.options.slidesToShow + 1; } else { infiniteCount = _.options.slidesToShow; } for (i = _.slideCount; i > (_.slideCount - infiniteCount); i -= 1) { slideIndex = i - 1; $(_.$slides[slideIndex]).clone(true).attr('id', '') .attr('data-slick-index', slideIndex - _.slideCount) .prependTo(_.$slideTrack).addClass('slick-cloned'); } for (i = 0; i < infiniteCount; i += 1) { slideIndex = i; $(_.$slides[slideIndex]).clone(true).attr('id', '') .attr('data-slick-index', slideIndex + _.slideCount) .appendTo(_.$slideTrack).addClass('slick-cloned'); } _.$slideTrack.find('.slick-cloned').find('[id]').each(function() { $(this).attr('id', ''); }); } } }; Slick.prototype.setPaused = function(paused) { var _ = this; if (_.options.autoplay === true && _.options.pauseOnHover === true) { _.paused = paused; _.autoPlayClear(); } }; Slick.prototype.selectHandler = function(event) { var _ = this; var targetElement = $(event.target).is('.slick-slide') ? $(event.target) : $(event.target).parents('.slick-slide'); var index = parseInt(targetElement.attr('data-slick-index')); if (!index) index = 0; if (_.slideCount <= _.options.slidesToShow) { _.$slider.find('.slick-slide').removeClass('slick-active').attr('aria-hidden', 'true'); _.$slides.eq(index).addClass('slick-active').attr("aria-hidden", "false"); if (_.options.centerMode === true) { _.$slider.find('.slick-slide').removeClass('slick-center'); _.$slides.eq(index).addClass('slick-center'); } _.asNavFor(index); return; } _.slideHandler(index); }; Slick.prototype.slideHandler = function(index, sync, dontAnimate) { var targetSlide, animSlide, oldSlide, slideLeft, targetLeft = null, _ = this; sync = sync || false; if (_.animating === true && _.options.waitForAnimate === true) { return; } if (_.options.fade === true && _.currentSlide === index) { return; } if (_.slideCount <= _.options.slidesToShow) { return; } if (sync === false) { _.asNavFor(index); } targetSlide = index; targetLeft = _.getLeft(targetSlide); slideLeft = _.getLeft(_.currentSlide); _.currentLeft = _.swipeLeft === null ? slideLeft : _.swipeLeft; if (_.options.infinite === false && _.options.centerMode === false && (index < 0 || index > _.getDotCount() * _.options.slidesToScroll)) { if (_.options.fade === false) { targetSlide = _.currentSlide; if (dontAnimate !== true) { _.animateSlide(slideLeft, function() { _.postSlide(targetSlide); }); } else { _.postSlide(targetSlide); } } return; } else if (_.options.infinite === false && _.options.centerMode === true && (index < 0 || index > (_.slideCount - _.options.slidesToScroll))) { if (_.options.fade === false) { targetSlide = _.currentSlide; if (dontAnimate !== true) { _.animateSlide(slideLeft, function() { _.postSlide(targetSlide); }); } else { _.postSlide(targetSlide); } } return; } if (_.options.autoplay === true) { clearInterval(_.autoPlayTimer); } if (targetSlide < 0) { if (_.slideCount % _.options.slidesToScroll !== 0) { animSlide = _.slideCount - (_.slideCount % _.options.slidesToScroll); } else { animSlide = _.slideCount + targetSlide; } } else if (targetSlide >= _.slideCount) { if (_.slideCount % _.options.slidesToScroll !== 0) { animSlide = 0; } else { animSlide = targetSlide - _.slideCount; } } else { animSlide = targetSlide; } _.animating = true; _.$slider.trigger("beforeChange", [_, _.currentSlide, animSlide]); oldSlide = _.currentSlide; _.currentSlide = animSlide; _.setSlideClasses(_.currentSlide); _.updateDots(); _.updateArrows(); if (_.options.fade === true) { if (dontAnimate !== true) { _.fadeSlide(animSlide, function() { _.postSlide(animSlide); }); } else { _.postSlide(animSlide); } _.animateHeight(); return; } if (dontAnimate !== true) { _.animateSlide(targetLeft, function() { _.postSlide(animSlide); }); } else { _.postSlide(animSlide); } }; Slick.prototype.startLoad = function() { var _ = this; if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) { _.$prevArrow.hide(); _.$nextArrow.hide(); } if (_.options.dots === true && _.slideCount > _.options.slidesToShow) { _.$dots.hide(); } _.$slider.addClass('slick-loading'); }; Slick.prototype.swipeDirection = function() { var xDist, yDist, r, swipeAngle, _ = this; xDist = _.touchObject.startX - _.touchObject.curX; yDist = _.touchObject.startY - _.touchObject.curY; r = Math.atan2(yDist, xDist); swipeAngle = Math.round(r * 180 / Math.PI); if (swipeAngle < 0) { swipeAngle = 360 - Math.abs(swipeAngle); } if ((swipeAngle <= 45) && (swipeAngle >= 0)) { return (_.options.rtl === false ? 'left' : 'right'); } if ((swipeAngle <= 360) && (swipeAngle >= 315)) { return (_.options.rtl === false ? 'left' : 'right'); } if ((swipeAngle >= 135) && (swipeAngle <= 225)) { return (_.options.rtl === false ? 'right' : 'left'); } if (_.options.verticalSwiping === true) { if ((swipeAngle >= 35) && (swipeAngle <= 135)) { return 'left'; } else { return 'right'; } } return 'vertical'; }; Slick.prototype.swipeEnd = function(event) { var _ = this, slideCount; _.dragging = false; _.shouldClick = (_.touchObject.swipeLength > 10) ? false : true; if (_.touchObject.curX === undefined) { return false; } if (_.touchObject.edgeHit === true) { _.$slider.trigger("edge", [_, _.swipeDirection()]); } if (_.touchObject.swipeLength >= _.touchObject.minSwipe) { switch (_.swipeDirection()) { case 'left': slideCount = _.options.swipeToSlide ? _.checkNavigable(_.currentSlide + _.getSlideCount()) : _.currentSlide + _.getSlideCount(); _.slideHandler(slideCount); _.currentDirection = 0; _.touchObject = {}; _.$slider.trigger("swipe", [_, "left"]); break; case 'right': slideCount = _.options.swipeToSlide ? _.checkNavigable(_.currentSlide - _.getSlideCount()) : _.currentSlide - _.getSlideCount(); _.slideHandler(slideCount); _.currentDirection = 1; _.touchObject = {}; _.$slider.trigger("swipe", [_, "right"]); break; } } else { if (_.touchObject.startX !== _.touchObject.curX) { _.slideHandler(_.currentSlide); _.touchObject = {}; } } }; Slick.prototype.swipeHandler = function(event) { var _ = this; if ((_.options.swipe === false) || ('ontouchend' in document && _.options.swipe === false)) { return; } else if (_.options.draggable === false && event.type.indexOf('mouse') !== -1) { return; } _.touchObject.fingerCount = event.originalEvent && event.originalEvent.touches !== undefined ? event.originalEvent.touches.length : 1; _.touchObject.minSwipe = _.listWidth / _.options .touchThreshold; if (_.options.verticalSwiping === true) { _.touchObject.minSwipe = _.listHeight / _.options .touchThreshold; } switch (event.data.action) { case 'start': _.swipeStart(event); break; case 'move': _.swipeMove(event); break; case 'end': _.swipeEnd(event); break; } }; Slick.prototype.swipeMove = function(event) { var _ = this, edgeWasHit = false, curLeft, swipeDirection, swipeLength, positionOffset, touches; touches = event.originalEvent !== undefined ? event.originalEvent.touches : null; if (!_.dragging || touches && touches.length !== 1) { return false; } curLeft = _.getLeft(_.currentSlide); _.touchObject.curX = touches !== undefined ? touches[0].pageX : event.clientX; _.touchObject.curY = touches !== undefined ? touches[0].pageY : event.clientY; _.touchObject.swipeLength = Math.round(Math.sqrt( Math.pow(_.touchObject.curX - _.touchObject.startX, 2))); if (_.options.verticalSwiping === true) { _.touchObject.swipeLength = Math.round(Math.sqrt( Math.pow(_.touchObject.curY - _.touchObject.startY, 2))); } swipeDirection = _.swipeDirection(); if (swipeDirection === 'vertical') { return; } if (event.originalEvent !== undefined && _.touchObject.swipeLength > 4) { event.preventDefault(); } positionOffset = (_.options.rtl === false ? 1 : -1) * (_.touchObject.curX > _.touchObject.startX ? 1 : -1); if (_.options.verticalSwiping === true) { positionOffset = _.touchObject.curY > _.touchObject.startY ? 1 : -1; } swipeLength = _.touchObject.swipeLength; _.touchObject.edgeHit = false; if (_.options.infinite === false) { if ((_.currentSlide === 0 && swipeDirection === "right") || (_.currentSlide >= _.getDotCount() && swipeDirection === "left")) { swipeLength = _.touchObject.swipeLength * _.options.edgeFriction; _.touchObject.edgeHit = true; } } if (_.options.vertical === false) { _.swipeLeft = curLeft + swipeLength * positionOffset; } else { _.swipeLeft = curLeft + (swipeLength * (_.$list.height() / _.listWidth)) * positionOffset; } if (_.options.verticalSwiping === true) { _.swipeLeft = curLeft + swipeLength * positionOffset; } if (_.options.fade === true || _.options.touchMove === false) { return false; } if (_.animating === true) { _.swipeLeft = null; return false; } _.setCSS(_.swipeLeft); }; Slick.prototype.swipeStart = function(event) { var _ = this, touches; if (_.touchObject.fingerCount !== 1 || _.slideCount <= _.options.slidesToShow) { _.touchObject = {}; return false; } if (event.originalEvent !== undefined && event.originalEvent.touches !== undefined) { touches = event.originalEvent.touches[0]; } _.touchObject.startX = _.touchObject.curX = touches !== undefined ? touches.pageX : event.clientX; _.touchObject.startY = _.touchObject.curY = touches !== undefined ? touches.pageY : event.clientY; _.dragging = true; }; Slick.prototype.unfilterSlides = Slick.prototype.slickUnfilter = function() { var _ = this; if (_.$slidesCache !== null) { _.unload(); _.$slideTrack.children(this.options.slide).detach(); _.$slidesCache.appendTo(_.$slideTrack); _.reinit(); } }; Slick.prototype.unload = function() { var _ = this; $('.slick-cloned', _.$slider).remove(); if (_.$dots) { _.$dots.remove(); } if (_.$prevArrow && (typeof _.options.prevArrow !== 'object')) { _.$prevArrow.remove(); } if (_.$nextArrow && (typeof _.options.nextArrow !== 'object')) { _.$nextArrow.remove(); } _.$slides.removeClass('slick-slide slick-active slick-visible').attr("aria-hidden", "true").css('width', ''); }; Slick.prototype.unslick = function() { var _ = this; _.destroy(); }; Slick.prototype.updateArrows = function() { var _ = this, centerOffset; centerOffset = Math.floor(_.options.slidesToShow / 2); if (_.options.arrows === true && _.options.infinite !== true && _.slideCount > _.options.slidesToShow) { _.$prevArrow.removeClass('slick-disabled'); _.$nextArrow.removeClass('slick-disabled'); if (_.currentSlide === 0) { _.$prevArrow.addClass('slick-disabled'); _.$nextArrow.removeClass('slick-disabled'); } else if (_.currentSlide >= _.slideCount - _.options.slidesToShow && _.options.centerMode === false) { _.$nextArrow.addClass('slick-disabled'); _.$prevArrow.removeClass('slick-disabled'); } else if (_.currentSlide >= _.slideCount - 1 && _.options.centerMode === true) { _.$nextArrow.addClass('slick-disabled'); _.$prevArrow.removeClass('slick-disabled'); } } }; Slick.prototype.updateDots = function() { var _ = this; if (_.$dots !== null) { _.$dots.find('li').removeClass('slick-active').attr("aria-hidden", "true"); _.$dots.find('li').eq(Math.floor(_.currentSlide / _.options.slidesToScroll)).addClass('slick-active').attr("aria-hidden", "false"); } }; Slick.prototype.visibility = function() { var _ = this; if (document[_.hidden]) { _.paused = true; _.autoPlayClear(); } else { _.paused = false; _.autoPlay(); } }; $.fn.slick = function() { var _ = this, opt = arguments[0], args = Array.prototype.slice.call(arguments, 1), l = _.length, i = 0, ret; for (i; i < l; i++) { if (typeof opt == 'object' || typeof opt == 'undefined') _[i].slick = new Slick(_[i], opt); else ret = _[i].slick[opt].apply(_[i].slick, args); if (typeof ret != 'undefined') return ret; } return _; }; }));
mit
zk-ruby/zookeeper
cause-abort.rb
2541
#!/usr/bin/env ruby require 'zookeeper' require File.expand_path('../spec/support/zookeeper_spec_helpers', __FILE__) class CauseAbort include Zookeeper::Logger include Zookeeper::SpecHelpers attr_reader :path, :pids_root, :data def initialize @path = "/_zktest_" @pids_root = "#{@path}/pids" @data = 'underpants' end def before @zk = Zookeeper.new('localhost:2181') rm_rf(@zk, path) logger.debug { "----------------< BEFORE: END >-------------------" } end def process_alive?(pid) Process.kill(0, @pid) true rescue Errno::ESRCH false end def wait_for_child_safely(pid, timeout=5) time_to_stop = Time.now + timeout until Time.now > time_to_stop if a = Process.wait2(@pid, Process::WNOHANG) return a.last else sleep(0.01) end end nil end def try_pause_and_resume @zk.pause logger.debug { "paused" } @zk.resume logger.debug { "resumed" } @zk.close logger.debug { "closed" } end def run_test logger.debug { "----------------< TEST: BEGIN >-------------------" } @zk.wait_until_connected mkdir_p(@zk, pids_root) # the parent's pid path @zk.create(:path => "#{pids_root}/#{$$}", :data => $$.to_s) @latch = Zookeeper::Latch.new @event = nil cb = proc do |h| logger.debug { "watcher called back: #{h.inspect}" } @event = h @latch.release end @zk.stat(:path => "#{pids_root}/child", :watcher => cb) logger.debug { "-------------------> FORK <---------------------------" } @pid = fork do rand_sleep = rand() $stderr.puts "sleeping for rand_sleep: #{rand_sleep}" sleep(rand_sleep) logger.debug { "reopening connection in child: #{$$}" } @zk.reopen logger.debug { "creating path" } rv = @zk.create(:path => "#{pids_root}/child", :data => $$.to_s) logger.debug { "created path #{rv[:path]}" } @zk.close logger.debug { "close finished" } exit!(0) end event_waiter_th = Thread.new do @latch.await(5) unless @event @event end logger.debug { "waiting on child #{@pid}" } status = wait_for_child_safely(@pid) raise "Child process did not exit, likely hung" unless status if event_waiter_th.join(5) == event_waiter_th logger.warn { "event waiter has not received events" } end exit(@event.nil? ? 1 : 0) end def run before run_test # try_pause_and_resume end end CauseAbort.new.run
mit
NateBrady23/faithwraps
vendor/league/oauth2-facebook/src/Provider/FacebookUser.php
3075
<?php namespace League\OAuth2\Client\Provider; class FacebookUser implements ResourceOwnerInterface { /** * @var array */ protected $data; /** * @param array $response */ public function __construct(array $response) { $this->data = $response; if (!empty($response['picture']['data']['url'])) { $this->data['picture_url'] = $response['picture']['data']['url']; } } /** * Returns the ID for the user as a string if present. * * @return string|null */ public function getId() { return $this->getField('id'); } /** * Returns the name for the user as a string if present. * * @return string|null */ public function getName() { return $this->getField('name'); } /** * Returns the first name for the user as a string if present. * * @return string|null */ public function getFirstName() { return $this->getField('first_name'); } /** * Returns the last name for the user as a string if present. * * @return string|null */ public function getLastName() { return $this->getField('last_name'); } /** * Returns the email for the user as a string if present. * * @return string|null */ public function getEmail() { return $this->getField('email'); } /** * Returns the current location of the user as an array. * * @return array|null */ public function getHometown() { return $this->getField('hometown'); } /** * Returns the "about me" bio for the user as a string if present. * * @return string|null */ public function getBio() { return $this->getField('bio'); } /** * Returns the picture of the user as a GraphPicture * * @return array|null */ public function getPictureUrl() { return $this->getField('picture_url'); } /** * Returns the gender for the user as a string if present. * * @return string|null */ public function getGender() { return $this->getField('gender'); } /** * Returns the locale of the user as a string if available. * * @return string|null */ public function getLocale() { return $this->getField('locale'); } /** * Returns the Facebook URL for the user as a string if available. * * @return string|null */ public function getLink() { return $this->getField('link'); } /** * Returns all the data obtained about the user. * * @return array */ public function toArray() { return $this->data; } /** * Returns a field from the Graph node data. * * @param string $key * * @return mixed|null */ private function getField($key) { return isset($this->data[$key]) ? $this->data[$key] : null; } }
mit
zbrad/nuproj
src/NuProj.Tests/Infrastructure/MSBuild.cs
13497
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Build.Execution; using Microsoft.Build.Framework; using Microsoft.Build.Logging; using Xunit; using Xunit.Abstractions; namespace NuProj.Tests.Infrastructure { public static class MSBuild { public static Task<BuildResultAndLogs> RebuildAsync(string projectPath, string projectName = null, IDictionary<string, string> properties = null, ITestOutputHelper testLogger = null) { var target = string.IsNullOrEmpty(projectName) ? "Rebuild" : projectName.Replace('.', '_') + ":Rebuild"; return MSBuild.ExecuteAsync(projectPath, new[] { target }, properties, testLogger); } public static Task<BuildResultAndLogs> ExecuteAsync(string projectPath, string targetToBuild, IDictionary<string, string> properties = null, ITestOutputHelper testLogger = null) { return MSBuild.ExecuteAsync(projectPath, new[] { targetToBuild }, properties, testLogger); } /// <summary> /// Builds a project. /// </summary> /// <param name="projectPath">The absolute path to the project.</param> /// <param name="targetsToBuild">The targets to build. If not specified, the project's default target will be invoked.</param> /// <param name="properties">The optional global properties to pass to the project. May come from the <see cref="MSBuild.Properties"/> static class.</param> /// <returns>A task whose result is the result of the build.</returns> public static async Task<BuildResultAndLogs> ExecuteAsync(string projectPath, string[] targetsToBuild = null, IDictionary<string, string> properties = null, ITestOutputHelper testLogger = null) { targetsToBuild = targetsToBuild ?? new string[0]; var logger = new EventLogger(); var logLines = new List<string>(); var parameters = new BuildParameters { Loggers = new List<ILogger> { new ConsoleLogger(LoggerVerbosity.Detailed, logLines.Add, null, null), new ConsoleLogger(LoggerVerbosity.Minimal, v => testLogger?.WriteLine(v.TrimEnd()), null, null), logger, }, }; BuildResult result; using (var buildManager = new BuildManager()) { buildManager.BeginBuild(parameters); try { var requestData = new BuildRequestData(projectPath, properties ?? Properties.Default, null, targetsToBuild, null); var submission = buildManager.PendBuildRequest(requestData); result = await submission.ExecuteAsync(); } finally { buildManager.EndBuild(); } } return new BuildResultAndLogs(result, logger.LogEvents, logLines); } /// <summary> /// Builds a project. /// </summary> /// <param name="projectInstance">The project to build.</param> /// <param name="targetsToBuild">The targets to build. If not specified, the project's default target will be invoked.</param> /// <returns>A task whose result is the result of the build.</returns> public static async Task<BuildResultAndLogs> ExecuteAsync(ProjectInstance projectInstance, ITestOutputHelper testLogger = null, params string[] targetsToBuild) { targetsToBuild = (targetsToBuild == null || targetsToBuild.Length == 0) ? projectInstance.DefaultTargets.ToArray() : targetsToBuild; var logger = new EventLogger(); var logLines = new List<string>(); var parameters = new BuildParameters { Loggers = new List<ILogger> { new ConsoleLogger(LoggerVerbosity.Detailed, logLines.Add, null, null), new ConsoleLogger(LoggerVerbosity.Minimal, v => testLogger?.WriteLine(v.TrimEnd()), null, null), logger, }, }; BuildResult result; using (var buildManager = new BuildManager()) { buildManager.BeginBuild(parameters); try { var brdFlags = BuildRequestDataFlags.ProvideProjectStateAfterBuild; var requestData = new BuildRequestData(projectInstance, targetsToBuild, null, brdFlags); var submission = buildManager.PendBuildRequest(requestData); result = await submission.ExecuteAsync(); } finally { buildManager.EndBuild(); } } return new BuildResultAndLogs(result, logger.LogEvents, logLines); } private static Task<BuildResult> ExecuteAsync(this BuildSubmission submission) { var tcs = new TaskCompletionSource<BuildResult>(); submission.ExecuteAsync(s => tcs.SetResult(s.BuildResult), null); return tcs.Task; } /// <summary> /// Common properties to pass to a build request. /// </summary> public static class Properties { /// <summary> /// No properties. The project will be built in its default configuration. /// </summary> private static readonly ImmutableDictionary<string, string> Empty = ImmutableDictionary.Create<string, string>(StringComparer.OrdinalIgnoreCase); /// <summary> /// Gets the global properties to pass to indicate where NuProj imports can be found. /// </summary> /// <remarks> /// For purposes of true verifications, this map of global properties should /// NOT include any that are propagated by project references from NuProj /// or else their presence here (which does not reflect what the user's solution /// typically builds with) may mask over-build errors that would otherwise /// be caught by our BuildResultAndLogs.AssertNoTargetsExecutedTwice method. /// </remarks> public static readonly ImmutableDictionary<string, string> Default = Empty .Add("NuProjPath", Assets.NuProjPath) .Add("NuProjTasksPath", Assets.NuProjTasksPath) .Add("NuGetToolPath", Assets.NuGetToolPath) .Add("CustomAfterMicrosoftCommonTargets", Assets.MicrosoftCommonNuProjTargetsPath); /// <summary> /// The project will build in the same manner as if it were building inside Visual Studio. /// </summary> public static readonly ImmutableDictionary<string, string> BuildingInsideVisualStudio = Default .Add("BuildingInsideVisualStudio", "true"); } public class BuildResultAndLogs { internal BuildResultAndLogs(BuildResult result, List<BuildEventArgs> events, IReadOnlyList<string> logLines) { Result = result; LogEvents = events; LogLines = logLines; } public BuildResult Result { get; private set; } public List<BuildEventArgs> LogEvents { get; private set; } public IEnumerable<BuildErrorEventArgs> ErrorEvents { get { return LogEvents.OfType<BuildErrorEventArgs>(); } } public IEnumerable<BuildWarningEventArgs> WarningEvents { get { return LogEvents.OfType<BuildWarningEventArgs>(); } } public IReadOnlyList<string> LogLines { get; private set; } public string EntireLog { get { return string.Join(string.Empty, LogLines); } } public void AssertSuccessfulBuild() { Assert.False(ErrorEvents.Any(), ErrorEvents.Select(e => e.Message).FirstOrDefault()); this.AssertNoTargetsExecutedTwice(); Assert.Equal(BuildResultCode.Success, Result.OverallResult); } public void AssertUnsuccessfulBuild() { Assert.Equal(BuildResultCode.Failure, Result.OverallResult); Assert.True(ErrorEvents.Any(), ErrorEvents.Select(e => e.Message).FirstOrDefault()); } /// <summary> /// Verifies that we don't have multi-proc build bugs that may cause /// build failures as a result of projects building multiple times. /// </summary> private void AssertNoTargetsExecutedTwice() { var projectPathToId = new Dictionary<string, long>(StringComparer.OrdinalIgnoreCase); var configurations = new Dictionary<long, ProjectStartedEventArgs>(); foreach (var projectStarted in this.LogEvents.OfType<ProjectStartedEventArgs>()) { if (!configurations.ContainsKey(projectStarted.BuildEventContext.ProjectInstanceId)) { configurations.Add(projectStarted.BuildEventContext.ProjectInstanceId, projectStarted); } long existingId; if (projectPathToId.TryGetValue(projectStarted.ProjectFile, out existingId)) { if (existingId != projectStarted.BuildEventContext.ProjectInstanceId) { var originalProjectStarted = configurations[existingId]; var originalRequestingProject = configurations[originalProjectStarted.ParentProjectBuildEventContext.ProjectInstanceId].ProjectFile; var requestingProject = configurations[projectStarted.ParentProjectBuildEventContext.ProjectInstanceId].ProjectFile; var globalPropertiesFirst = originalProjectStarted.GlobalProperties.Select(kv => $"{kv.Key}={kv.Value}").ToImmutableHashSet(); var globalPropertiesSecond = projectStarted.GlobalProperties.Select(kv => $"{kv.Key}={kv.Value}").ToImmutableHashSet(); var inFirstNotSecond = globalPropertiesFirst.Except(globalPropertiesSecond); var inSecondNotFirst = globalPropertiesSecond.Except(globalPropertiesFirst); var messageBuilder = new StringBuilder(); messageBuilder.AppendLine($@"Project ""{projectStarted.ProjectFile}"" was built twice. "); messageBuilder.Append($@"The first build request came from ""{originalRequestingProject}"""); if (inFirstNotSecond.IsEmpty) { messageBuilder.AppendLine(); } else { messageBuilder.AppendLine($" and defined these unique global properties: {string.Join(",", inFirstNotSecond)}"); } messageBuilder.Append($@"The subsequent build request came from ""{requestingProject}"""); if (inSecondNotFirst.IsEmpty) { messageBuilder.AppendLine(); } else { messageBuilder.AppendLine($" and defined these unique global properties: {string.Join(",", inSecondNotFirst)}"); } Assert.False(true, messageBuilder.ToString()); } } else { projectPathToId.Add(projectStarted.ProjectFile, projectStarted.BuildEventContext.ProjectInstanceId); } } } private static string SerializeProperties(IDictionary<string, string> properties) { return string.Join(",", properties.Select(kv => $"{kv.Key}={kv.Value}")); } } private class EventLogger : ILogger { private IEventSource _eventSource; internal EventLogger() { Verbosity = LoggerVerbosity.Normal; LogEvents = new List<BuildEventArgs>(); } public LoggerVerbosity Verbosity { get; set; } public string Parameters { get; set; } public List<BuildEventArgs> LogEvents { get; set; } public void Initialize(IEventSource eventSource) { _eventSource = eventSource; _eventSource.AnyEventRaised += EventSourceAnyEventRaised; } private void EventSourceAnyEventRaised(object sender, BuildEventArgs e) { LogEvents.Add(e); } public void Shutdown() { _eventSource.AnyEventRaised -= EventSourceAnyEventRaised; } } } }
mit
dmitriy-sqrt/thor-language
tests/testcases/RouterTestCase.php
3003
<?php namespace Thor\Language; class RouterTestCase extends PackageTestCase { public function testRouteFacadeIsSwapped() { $this->assertArrayHasKey('router', $this->app); $this->assertArrayHasKey('thor.router', $this->app); $this->assertInstanceOf('Thor\\Language\\Router', $this->app['router']); } /** * @covers \Thor\Language\Router::langGroup * @dataProvider langCodeProvider */ public function testLangGroup($langCode) { $this->prepareRequest('/' . $langCode . '/'); $router = $this->app['router']; $this->app['router']->langGroup(function () use ($router) { $router->get('foobar', 'foobar'); }); foreach($this->app['router']->getRoutes() as $r) { $route = $r; break; } $this->assertEquals($langCode . '/foobar', $route->getPath()); } /** * @covers \Thor\Language\Router::langGroup * @dataProvider langCodeProvider */ public function testLangGroupWithPrefix($langCode) { $this->prepareRequest('/' . $langCode . '/'); $router = $this->app['router']; $this->app['router']->langGroup(array('prefix' => 'xx'), function () use ($router) { $router->get('foobar', 'foobar'); }); foreach($this->app['router']->getRoutes() as $r) { $route = $r; break; } $this->assertEquals($langCode . '/xx/foobar', $route->getPath()); } /** * @covers \Thor\Language\Router::langGroup * @expectedException \InvalidArgumentException */ public function testInvalidArgument() { $this->app['router']->langGroup('foobar'); } /** * @covers \Thor\Language\Router::langGroup */ public function testRootPath() { $this->prepareRequest('/'); $app = $this->app; $this->app['router']->get('/', function() use($app) { return $app['translator']->locale(); }); $resp = $this->call('GET', '/'); $this->assertResponseOk(); $this->assertEquals('en_US', $resp->getContent()); } /** * @covers \Thor\Language\Router::langGroup */ public function testRootPathWithHeaderFallback() { $this->app['config']->set('language::use_header', true); $this->prepareRequest('/', 'GET', array(), array(), array( 'HTTP_ACCEPT_LANGUAGE' => 'it,it-it,fr,es;' )); $app = $this->app; $this->app['router']->get('/', function() use($app) { return $app['translator']->locale(); }); $resp = $this->call('GET', '/'); $this->assertResponseOk(); $this->assertEquals('it_IT', $resp->getContent()); } public function langCodeProvider() { return array( array('en'), array('es'), array('fr'), array('de'), array('it') ); } }
mit
BoazFrancis/grafana-event-map
node_modules/babel-plugin-transform-cjs-system-wrapper/test/fixtures/set-deps/expected.js
146
System.registerDynamic(["foo", "bar"], true, function ($__require, exports, module) { var global = this || self, GLOBAL = global; });
mit
ivanceras/iup-mirror
html/examples/Lua/image.lua
4731
-- IupImage Example in IupLua -- Creates a button, a label, a toggle and a radio using an image. -- Uses an image for the cursor as well. require( "iuplua" ) -- Defines an "X" image img_x = iup.image{ { 1,2,3,3,3,3,3,3,3,2,1 }, { 2,1,2,3,3,3,3,3,2,1,2 }, { 3,2,1,2,3,3,3,2,1,2,3 }, { 3,3,2,1,2,3,2,1,2,3,3 }, { 3,3,3,2,1,2,1,2,3,3,3 }, { 3,3,3,3,2,1,2,3,3,3,3 }, { 3,3,3,2,1,2,1,2,3,3,3 }, { 3,3,2,1,2,3,2,1,2,3,3 }, { 3,2,1,2,3,3,3,2,1,2,3 }, { 2,1,2,3,3,3,3,3,2,1,2 }, { 1,2,3,3,3,3,3,3,3,2,1 } -- Sets "X" image colors ; colors = { "0 1 0", "255 0 0", "255 255 0" } } -- Defines a cursor image img_cursor = iup.image{ { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,2,2,2,2,0,0,0,0,0,0,0,0,0,0,0 }, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,1,1,1,1,2,0,0,0,0,0,0,0,0,0,0,0 }, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,1,1,1,1,2,0,0,0,0,0,0,0,0,0,0,0 }, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,1,1,1,1,1,2,0,0,0,0,0,0,0,0,0,0,0 }, { 0,0,0,0,0,0,0,0,0,0,0,0,0,2,1,1,1,1,1,1,2,0,0,0,0,0,0,0,0,0,0,0 }, { 0,0,0,0,0,0,0,0,0,0,0,0,2,1,1,1,1,1,2,2,2,0,0,0,0,0,0,0,0,0,0,0 }, { 0,0,0,0,0,0,0,0,0,0,0,2,1,1,1,1,1,2,0,0,2,0,0,0,0,0,0,0,0,0,0,0 }, { 0,0,0,0,0,0,0,0,0,0,0,0,2,1,1,1,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, { 0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } -- Sets cursor image colors ; colors = { "255 0 0", "128 0 0" }, hotspot = "21:10" } -- Creates a button and associates image img_x to it btn = iup.button{ image = img_x, title = "btn" } -- Creates a label and associates image img_x to it lbl = iup.label{ image = img_x, title = "lbl" } -- Creates toggle and associates image img_x to it tgl = iup.toggle{ image = img_x, title = "tgl" } -- Creates two toggles and associates image img_x to them tgl_radio_1 = iup.toggle{ image = img_x, title = "tgl_radio_1" } tgl_radio_2 = iup.toggle{ image = img_x, title = "tgl_radio_2" } -- Creates label showing image size lbl_size = iup.label{ title = '"X" image width = '..img_x.width..'; "X" image height = '..img_x.height } -- Creates frames around the elements frm_btn = iup.frame{btn; title="button"} frm_lbl = iup.frame{lbl; title="label" } frm_tgl = iup.frame{tgl; title="toggle"} frm_tgl_radio = iup.frame{ iup.radio{ iup.vbox { tgl_radio_1, tgl_radio_2 } }; title="radio", size="EIGHTHxEIGHTH" } -- Creates dialog dlg with an hbox containing a button, a label, and a toggle dlg = iup.dialog { iup.vbox { iup.hbox{frm_btn, frm_lbl, frm_tgl, frm_tgl_radio}, iup.fill{}, iup.hbox{iup.fill{}, lbl_size, iup.fill{}} }; title = "IupImage Example", size = "HALFxQUARTER", cursor = img_cursor } -- Shows dialog in the center of the screen dlg:showxy(iup.CENTER, iup.CENTER) if (iup.MainLoopLevel()==0) then iup.MainLoop() end
mit
redpelicans/aurelia-material-sample
jspm_packages/npm/babel-core@5.7.4/lib/types/index.js
10735
/* */ "format cjs"; "use strict"; exports.__esModule = true; exports.is = is; exports.isType = isType; exports.shallowEqual = shallowEqual; exports.appendToMemberExpression = appendToMemberExpression; exports.prependToMemberExpression = prependToMemberExpression; exports.ensureBlock = ensureBlock; exports.clone = clone; exports.cloneDeep = cloneDeep; exports.buildMatchMemberExpression = buildMatchMemberExpression; exports.removeComments = removeComments; exports.inheritsComments = inheritsComments; exports.inherits = inherits; // istanbul ignore next function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var _toFastProperties = require("to-fast-properties"); var _toFastProperties2 = _interopRequireDefault(_toFastProperties); var _lodashArrayCompact = require("lodash/array/compact"); var _lodashArrayCompact2 = _interopRequireDefault(_lodashArrayCompact); var _lodashObjectAssign = require("lodash/object/assign"); var _lodashObjectAssign2 = _interopRequireDefault(_lodashObjectAssign); var _lodashCollectionEach = require("lodash/collection/each"); var _lodashCollectionEach2 = _interopRequireDefault(_lodashCollectionEach); var _lodashArrayUniq = require("lodash/array/uniq"); var _lodashArrayUniq2 = _interopRequireDefault(_lodashArrayUniq); require("./definitions/init"); var _definitions = require("./definitions"); var t = exports; /** * Registers `is[Type]` and `assert[Type]` generated functions for a given `type`. * Pass `skipAliasCheck` to force it to directly compare `node.type` with `type`. */ function registerType(type, skipAliasCheck) { var is = t["is" + type] = function (node, opts) { return t.is(type, node, opts, skipAliasCheck); }; t["assert" + type] = function (node, opts) { opts = opts || {}; if (!is(node, opts)) { throw new Error("Expected type " + JSON.stringify(type) + " with option " + JSON.stringify(opts)); } }; } /** * Constants. */ var STATEMENT_OR_BLOCK_KEYS = ["consequent", "body", "alternate"]; exports.STATEMENT_OR_BLOCK_KEYS = STATEMENT_OR_BLOCK_KEYS; var FLATTENABLE_KEYS = ["body", "expressions"]; exports.FLATTENABLE_KEYS = FLATTENABLE_KEYS; var FOR_INIT_KEYS = ["left", "init"]; exports.FOR_INIT_KEYS = FOR_INIT_KEYS; var COMMENT_KEYS = ["leadingComments", "trailingComments"]; exports.COMMENT_KEYS = COMMENT_KEYS; var BOOLEAN_NUMBER_BINARY_OPERATORS = [">", "<", ">=", "<="]; exports.BOOLEAN_NUMBER_BINARY_OPERATORS = BOOLEAN_NUMBER_BINARY_OPERATORS; var COMPARISON_BINARY_OPERATORS = ["==", "===", "!=", "!==", "in", "instanceof"]; exports.COMPARISON_BINARY_OPERATORS = COMPARISON_BINARY_OPERATORS; var BOOLEAN_BINARY_OPERATORS = [].concat(COMPARISON_BINARY_OPERATORS, BOOLEAN_NUMBER_BINARY_OPERATORS); exports.BOOLEAN_BINARY_OPERATORS = BOOLEAN_BINARY_OPERATORS; var NUMBER_BINARY_OPERATORS = ["-", "/", "*", "**", "&", "|", ">>", ">>>", "<<", "^"]; exports.NUMBER_BINARY_OPERATORS = NUMBER_BINARY_OPERATORS; var BOOLEAN_UNARY_OPERATORS = ["delete", "!"]; exports.BOOLEAN_UNARY_OPERATORS = BOOLEAN_UNARY_OPERATORS; var NUMBER_UNARY_OPERATORS = ["+", "-", "++", "--", "~"]; exports.NUMBER_UNARY_OPERATORS = NUMBER_UNARY_OPERATORS; var STRING_UNARY_OPERATORS = ["typeof"]; exports.STRING_UNARY_OPERATORS = STRING_UNARY_OPERATORS; exports.VISITOR_KEYS = _definitions.VISITOR_KEYS; exports.BUILDER_KEYS = _definitions.BUILDER_KEYS; exports.ALIAS_KEYS = _definitions.ALIAS_KEYS; /** * Registers `is[Type]` and `assert[Type]` for all types. */ _lodashCollectionEach2["default"](t.VISITOR_KEYS, function (keys, type) { registerType(type, true); }); /** * Flip `ALIAS_KEYS` for faster access in the reverse direction. */ t.FLIPPED_ALIAS_KEYS = {}; _lodashCollectionEach2["default"](t.ALIAS_KEYS, function (aliases, type) { _lodashCollectionEach2["default"](aliases, function (alias) { var types = t.FLIPPED_ALIAS_KEYS[alias] = t.FLIPPED_ALIAS_KEYS[alias] || []; types.push(type); }); }); /** * Registers `is[Alias]` and `assert[Alias]` functions for all aliases. */ _lodashCollectionEach2["default"](t.FLIPPED_ALIAS_KEYS, function (types, type) { t[type.toUpperCase() + "_TYPES"] = types; registerType(type, false); }); var TYPES = Object.keys(t.VISITOR_KEYS).concat(Object.keys(t.FLIPPED_ALIAS_KEYS)); exports.TYPES = TYPES; /** * Returns whether `node` is of given `type`. * * For better performance, use this instead of `is[Type]` when `type` is unknown. * Optionally, pass `skipAliasCheck` to directly compare `node.type` with `type`. */ // @TODO should `skipAliasCheck` be removed? function is(type, node, opts, skipAliasCheck) { if (!node) return false; var matches = isType(node.type, type); if (!matches) return false; if (typeof opts === "undefined") { return true; } else { return t.shallowEqual(node, opts); } } /** * Test if a `nodeType` is a `targetType` or if `targetType` is an alias of `nodeType`. */ function isType(nodeType, targetType) { if (nodeType === targetType) return true; var aliases = t.FLIPPED_ALIAS_KEYS[targetType]; if (aliases) { if (aliases[0] === nodeType) return true; var _arr = aliases; for (var _i = 0; _i < _arr.length; _i++) { var alias = _arr[_i]; if (nodeType === alias) return true; } } return false; } /** * [Please add a description.] */ _lodashCollectionEach2["default"](t.VISITOR_KEYS, function (keys, type) { if (t.BUILDER_KEYS[type]) return; var defs = {}; _lodashCollectionEach2["default"](keys, function (key) { defs[key] = null; }); t.BUILDER_KEYS[type] = defs; }); /** * [Please add a description.] */ _lodashCollectionEach2["default"](t.BUILDER_KEYS, function (keys, type) { var builder = function builder() { var node = {}; node.start = null; node.type = type; var i = 0; for (var key in keys) { var arg = arguments[i++]; if (arg === undefined) arg = keys[key]; node[key] = arg; } return node; }; t[type] = builder; t[type[0].toLowerCase() + type.slice(1)] = builder; }); /** * Test if an object is shallowly equal. */ function shallowEqual(actual, expected) { var keys = Object.keys(expected); var _arr2 = keys; for (var _i2 = 0; _i2 < _arr2.length; _i2++) { var key = _arr2[_i2]; if (actual[key] !== expected[key]) { return false; } } return true; } /** * Append a node to a member expression. */ function appendToMemberExpression(member, append, computed) { member.object = t.memberExpression(member.object, member.property, member.computed); member.property = append; member.computed = !!computed; return member; } /** * Prepend a node to a member expression. */ function prependToMemberExpression(member, prepend) { member.object = t.memberExpression(prepend, member.object); return member; } /** * Ensure the `key` (defaults to "body") of a `node` is a block. * Casting it to a block if it is not. */ function ensureBlock(node) { var key = arguments.length <= 1 || arguments[1] === undefined ? "body" : arguments[1]; return node[key] = t.toBlock(node[key], node); } /** * Create a shallow clone of a `node` excluding `_private` properties. */ function clone(node) { var newNode = {}; for (var key in node) { if (key[0] === "_") continue; newNode[key] = node[key]; } return newNode; } /** * Create a deep clone of a `node` and all of it's child nodes * exluding `_private` properties. */ function cloneDeep(node) { var newNode = {}; for (var key in node) { if (key[0] === "_") continue; var val = node[key]; if (val) { if (val.type) { val = t.cloneDeep(val); } else if (Array.isArray(val)) { val = val.map(t.cloneDeep); } } newNode[key] = val; } return newNode; } /** * Build a function that when called will return whether or not the * input `node` `MemberExpression` matches the input `match`. * * For example, given the match `React.createClass` it would match the * parsed nodes of `React.createClass` and `React["createClass"]`. */ function buildMatchMemberExpression(match, allowPartial) { var parts = match.split("."); return function (member) { // not a member expression if (!t.isMemberExpression(member)) return false; var search = [member]; var i = 0; while (search.length) { var node = search.shift(); if (allowPartial && i === parts.length) { return true; } if (t.isIdentifier(node)) { // this part doesn't match if (parts[i] !== node.name) return false; } else if (t.isLiteral(node)) { // this part doesn't match if (parts[i] !== node.value) return false; } else if (t.isMemberExpression(node)) { if (node.computed && !t.isLiteral(node.property)) { // we can't deal with this return false; } else { search.push(node.object); search.push(node.property); continue; } } else { // we can't deal with this return false; } // too many parts if (++i > parts.length) { return false; } } return true; }; } /** * Remove comment properties from a node. */ function removeComments(node) { var _arr3 = COMMENT_KEYS; for (var _i3 = 0; _i3 < _arr3.length; _i3++) { var key = _arr3[_i3]; delete node[key]; } return node; } /** * Inherit all unique comments from `parent` node to `child` node. */ function inheritsComments(child, parent) { if (child && parent) { var _arr4 = COMMENT_KEYS; for (var _i4 = 0; _i4 < _arr4.length; _i4++) { var key = _arr4[_i4]; child[key] = _lodashArrayUniq2["default"](_lodashArrayCompact2["default"]([].concat(child[key], parent[key]))); } } return child; } /** * Inherit all contextual properties from `parent` node to `child` node. */ function inherits(child, parent) { if (!child || !parent) return child; child._scopeInfo = parent._scopeInfo; child._paths = parent._paths; child.range = parent.range; child.start = parent.start; child.loc = parent.loc; child.end = parent.end; child.typeAnnotation = parent.typeAnnotation; child.returnType = parent.returnType; t.inheritsComments(child, parent); return child; } // Optimize property access. _toFastProperties2["default"](t); _toFastProperties2["default"](t.VISITOR_KEYS); // Export all type checkers from other files. _lodashObjectAssign2["default"](t, require("./retrievers")); _lodashObjectAssign2["default"](t, require("./validators")); _lodashObjectAssign2["default"](t, require("./converters")); _lodashObjectAssign2["default"](t, require("./flow"));
mit
tropp/acq4
acq4/analysis/modules/IVCurve_mbk/IVCurve.py
3687
##Needs to: ## output set of parameters: Ih current, rectification, FI plots (and analysis based on) ## load IV directory, plot raw data, sends data to a function(flowchart) which returns a list of parameters. from PyQt4 import QtGui, QtCore from acq4.analysis.AnalysisModule import AnalysisModule from acq4.util.pyqtgraph.functions import mkPen from acq4.util.flowchart import * import os from collections import OrderedDict import acq4.util.debug as debug import acq4.util.FileLoader as FileLoader import acq4.util.DatabaseGui as DatabaseGui import FeedbackButton class IVCurve(AnalysisModule): def __init__(self, host, flowchartDir=None): AnalysisModule.__init__(self, host) self.dbIdentity = "IVCurveAnalyzer" ## how we identify to the database; this determines which tables we own if flowchartDir is None: flowchartDir = os.path.join(os.path.abspath(os.path.split(__file__)[0]), "flowcharts") self.flowchart = Flowchart(filePath=flowchartDir) self.flowchart.addInput("dataIn") #self.flowchart.addOutput('events') self.flowchart.addOutput('regions', multi=True) #self.flowchart.sigChartLoaded.connect(self.connectPlots) ### DBCtrl class is from EventDetector -- need to make my own here #self.dbCtrl = DBCtrl(self, identity=self.dbIdentity) #self.dbCtrl.storeBtn.clicked.connect(self.storeClicked) self.ctrl = self.flowchart.widget() self._elements_ = OrderedDict([ ('File Loader', {'type': 'fileInput', 'size': (200, 300), 'host': self}), #('Database', {'type': 'ctrl', 'object': self.dbCtrl, 'size': (200,300), 'pos': ('bottom', 'File Loader')}), ('Data Plot', {'type': 'plot', 'pos': ('right',), 'size': (800, 300)}), ('Detection Opts', {'type': 'ctrl', 'object': self.ctrl, 'pos': ('bottom', 'File Loader'), 'size': (200, 500)}), ('IV Plot', {'type': 'plot', 'pos': ('bottom', 'Data Plot'), 'size': (400, 300)}), ('Output Table', {'type': 'table', 'pos': ('bottom', 'IV Plot'), 'optional': True, 'size': (800,200)}), ('FI Plot', {'type': 'plot', 'pos': ('right', 'IV Plot'), 'size': (400, 300)}), ]) self.initializeElements() try: ## load default chart self.flowchart.loadFile(os.path.join(flowchartDir, 'default.fc')) except: debug.printExc('Error loading default flowchart:') #self.flowchart.sigOutputChanged.connect(self.outputChanged) def loadFileRequested(self, fh): """Called by file loader when a file load is requested.""" ### This should load a whole directory of cciv, plot them, put traces into one array and send that array to the flowchart. if fh.isDir(): dirs = [d for d in fh.subDirs()] else: dirs = [fh] dataPlot = self.getElement('Data Plot') ## Attempt to stick all the traces into one big away -- not sure I like this because you lose the metaInfo. a = fh[dirs[0]]['Clamp1.ma'].read() data = np.empty((a.shape[0], a.shape[1], len(dirs)), dtype=np.float) n=0 for d in dirs: trace = fh[d]['Clamp1.ma'].read() data[:,:,n] = trace color = float(n)/(len(dirs))*0.7 pen = mkPen(hsv=[color, 0.8, 0.7]) dataPlot.plot(trace['Channel':'primary'], pen=pen) n += 1 self.flowchart.setInput(dataIn=data) self.currentFile = fh return True
mit
ysekky/chainer
tests/chainer_tests/links_tests/activation_tests/test_simplified_dropconnect.py
6620
import os import tempfile import unittest import numpy import chainer from chainer import cuda from chainer import gradient_check from chainer import links from chainer.serializers import npz from chainer import testing from chainer.testing import attr from chainer.testing import condition from chainer.utils import type_check def gen_mask(ratio, shape): return numpy.random.rand(*shape) >= ratio @testing.parameterize(*testing.product({ 'in_shape': [(3,), (3, 2, 2)], 'x_dtype': [numpy.float16, numpy.float32, numpy.float64], 'W_dtype': [numpy.float16, numpy.float32, numpy.float64], })) class TestSimplifiedDropconnect(unittest.TestCase): out_size = 2 ratio = 0.5 def setUp(self): in_size = numpy.prod(self.in_shape) self.link = links.SimplifiedDropconnect( in_size, self.out_size, initialW=chainer.initializers.Normal(1, self.W_dtype), initial_bias=chainer.initializers.Normal(1, self.x_dtype)) self.link.cleargrads() x_shape = (4,) + self.in_shape self.x = numpy.random.uniform(-1, 1, x_shape).astype(self.x_dtype) self.gy = numpy.random.uniform( -1, 1, (4, self.out_size)).astype(self.x_dtype) W = self.link.W.data b = self.link.b.data mask_shape = (4, ) + self.link.W.shape self.mask = gen_mask(self.ratio, mask_shape) W = (W * self.mask) * (1. / (1 - self.ratio)) x = self.x.reshape(4, -1) # numpy 1.9 does not support matmul. # So we use numpy.einsum instead of numpy.matmul. self.y_expect = numpy.einsum('ijk,ikl->ijl', W, x[:, :, None]).reshape(4, -1) + b self.check_forward_options = {} self.check_backward_options = {} if self.x_dtype == numpy.float16: self.check_forward_options = {'atol': 1e-3, 'rtol': 1e-2} self.check_backward_options = {'atol': 1e-2, 'rtol': 5e-2} elif self.W_dtype == numpy.float16: self.check_backward_options = {'atol': 1e-3, 'rtol': 1e-2} def check_forward(self, x_data, mask): x = chainer.Variable(x_data) y = self.link(x, True, mask) self.assertEqual(y.data.dtype, self.x_dtype) testing.assert_allclose(self.y_expect, y.data, **self.check_forward_options) def test_forward_cpu(self): self.check_forward(self.x, self.mask) @attr.gpu def test_forward_gpu(self): self.link.to_gpu() self.check_forward(cuda.to_gpu(self.x), cuda.to_gpu(self.mask)) def link_wrapper(self, *data): return self.link(data[0], True, data[1]) def check_backward(self, x_data, y_grad, mask): gradient_check.check_backward( self.link_wrapper, (x_data, mask), y_grad, (self.link.W, self.link.b), eps=2 ** -3, no_grads=(False, True), **self.check_backward_options) @condition.retry(3) def test_backward_cpu(self): self.check_backward(self.x, self.gy, self.mask) @attr.gpu @condition.retry(3) def test_backward_gpu(self): self.link.to_gpu() self.check_backward(cuda.to_gpu(self.x), cuda.to_gpu(self.gy), cuda.to_gpu(self.mask)) class TestSimplifiedDropconnectParameterShapePlaceholder(unittest.TestCase): in_size = 3 in_shape = (in_size,) out_size = 2 in_size_or_none = None ratio = 0.5 def setUp(self): self.link = links.SimplifiedDropconnect(self.in_size_or_none, self.out_size) temp_x = numpy.random.uniform(-1, 1, (4, self.in_size)).astype(numpy.float32) self.link(chainer.Variable(temp_x)) W = self.link.W.data W[...] = numpy.random.uniform(-1, 1, W.shape) b = self.link.b.data b[...] = numpy.random.uniform(-1, 1, b.shape) self.link.cleargrads() mask_shape = (4, self.out_size, self.in_size) self.mask = gen_mask(self.ratio, mask_shape) x_shape = (4,) + self.in_shape self.x = numpy.random.uniform(-1, 1, x_shape).astype(numpy.float32) self.gy = numpy.random.uniform( -1, 1, (4, self.out_size)).astype(numpy.float32) W = (W * self.mask) * (1. / (1 - self.ratio)) # numpy 1.9 does not support matmul. # So we use numpy.einsum instead of numpy.matmul. self.y_expect = numpy.einsum('ijk,ikl->ijl', W, self.x[:, :, None]).reshape(4, -1) + b def check_forward(self, x_data, mask): x = chainer.Variable(x_data) y = self.link(x, True, mask) self.assertEqual(y.data.dtype, numpy.float32) testing.assert_allclose(self.y_expect, y.data) def test_forward_cpu(self): self.check_forward(self.x, self.mask) @attr.gpu def test_forward_gpu(self): self.link.to_gpu() self.check_forward(cuda.to_gpu(self.x), cuda.to_gpu(self.mask)) def link_wrapper(self, *data): return self.link(data[0], True, data[1]) def check_backward(self, x_data, y_grad, mask): gradient_check.check_backward( self.link_wrapper, (x_data, mask), y_grad, (self.link.W, self.link.b), eps=1e-2, no_grads=(False, True)) @condition.retry(3) def test_backward_cpu(self): self.check_backward(self.x, self.gy, self.mask) @attr.gpu @condition.retry(3) def test_backward_gpu(self): self.link.to_gpu() self.check_backward(cuda.to_gpu(self.x), cuda.to_gpu(self.gy), cuda.to_gpu(self.mask)) def test_serialization(self): lin1 = links.SimplifiedDropconnect(None, self.out_size) x = chainer.Variable(self.x) # Must call the link to initialize weights. lin1(x) w1 = lin1.W.data fd, temp_file_path = tempfile.mkstemp() os.close(fd) npz.save_npz(temp_file_path, lin1) lin2 = links.SimplifiedDropconnect(None, self.out_size) npz.load_npz(temp_file_path, lin2) w2 = lin2.W.data self.assertEqual((w1 == w2).all(), True) class TestInvalidSimplifiedDropconnect(unittest.TestCase): def setUp(self): self.link = links.SimplifiedDropconnect(3, 2) self.x = numpy.random.uniform(-1, 1, (4, 1, 2)).astype(numpy.float32) def test_invalid_size(self): with self.assertRaises(type_check.InvalidType): self.link(chainer.Variable(self.x)) testing.run_module(__name__, __file__)
mit
georgemarshall/DefinitelyTyped
types/vhtml/index.d.ts
58052
// Type definitions for vhtml 2.2 // Project: https://github.com/developit/vhtml // Definitions by: pastelmind <https://github.com/pastelmind> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export = vhtml; /** * Converts Hyperscript/JSX to a plain string. * @param name Element name * @param attrs Attributes * @param children Child elements */ declare function vhtml<T extends string>(name: T, attrs?: HtmlElementAttr<T> | null, ...children: any[]): string; /** * Converts Hyperscript/JSX to a plain string. * @param component Functional pseudo-component * @param attrs Attributes * @param children Child elements */ declare function vhtml<Props, Children extends any[]>( component: (props: Props & { children: Children }) => string, attrs?: Props | null, ...children: Children ): string; /** * @internal * Attributes supported on HTML tags. * This type alias allows custom tags to have any attribute, while still * enforcing type-checks on known HTML attributes. * * Notes: * - Because TypeScript forbids unknown tag names in JSX, custom string tags * can be used only with hyperscript-style code. * - There is no need to add `{ [attr: string]: any }` to known attributes, * since TypeScript already supports arbitrary `data-*` attributes in JSX * (see "Note" in https://www.typescriptlang.org/docs/handbook/jsx.html#attribute-type-checking) */ type HtmlElementAttr<Tag extends string> = (Tag extends keyof vhtml.JSX.IntrinsicElements ? vhtml.JSX.IntrinsicElements[Tag] : {}) & { dangerouslySetInnerHTML?: { __html: string }; [attr: string]: any; }; /** * @internal * Empty mapped types (`Pick<{}, never>`) are almost identical to the empty * object type (`{}`). However, TypeScript seems to treat them differently for * the purposes of checking `JSX.LibraryManagedAttributes`. * * This type alias converts any empty-ish type to a plain empty object type, so * that we can work around said behavior. */ type SafeEmptyType<T> = {} extends T ? {} : T; /** * @internal * Same as `Omit<T, K>` introduced in TypeScript 3.4. * Added here so that we can support older versions of TypeScript. */ type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>; /** * @internal * Type alias that transforms the type of `props.children` of a vhtml component * to a type that TypeScript expects. * * Currently, this supports: * - Empty components (no props.children) * - Empty components (props.children is an empty tuple) * - Components with exactly one child (props.children is a 1-length tuple) * - Components with exactly zero or one child * - Components with arbitrary number of children (props.children is an array) * - Forbidding components whose props.children is not an array */ type ComponentPropTransform<TComp, TProps> = SafeEmptyType<Omit<TProps, "children">> & (TProps extends { children: [] } ? {} : TProps extends { children: [infer ChildType] } ? { children: ChildType } : TProps extends { children: [(infer ChildType)?] } ? { children?: ChildType } : TProps extends { children: Array<infer ChildrenType> } ? { children?: ChildrenType | ChildrenType[] } : TProps extends { children: any } ? never : {}); declare namespace vhtml { namespace JSX { type Element = string; // Enable component children type checks interface ElementChildrenAttribute { children: {}; } type LibraryManagedAttributes<TComp, TProps> = ComponentPropTransform<TComp, TProps>; interface IntrinsicAttributes { // This property is not used by vhtml, but is required to enforce // type checking of function components that accept no children. // // To explain: TypeScript checks JSX attributes (and children, // apprently) as though they are object literal assignments for a // component's props. // The only information I could find about this behavior was this: // - https://github.com/microsoft/TypeScript/issues/15463#issuecomment-299263157 // // If this property did not exist, TypeScript would treat this // interface as the empty object type (`{}`). Since TypeScript // allows objects with arbitrary attributes to be assigned to the // empty object type, it would allow `{ children: any }` to be // passed to a component, even if the component was childless. // Defining this dummy property prevents this behavior, so that // passing children to a childless component would correctly cause a // type error. // // Note that other JSX frameworks like React do not need this hack // because they use actual intrinsic properties, such as `key`. __dummy_dont_use?: any; } // The following interfaces were generated by transforming large sections of // JSX type definitions in @types/react 17.0.3. Those type definitions were // produced by multiple contributors, including, but not limited to: // // AssureSign <http://www.assuresign.com> // Microsoft <https://microsoft.com> // John Reilly <https://github.com/johnnyreilly> // Benoit Benezech <https://github.com/bbenezech> // Patricio Zavolinsky <https://github.com/pzavolinsky> // Digiguru <https://github.com/digiguru> // Eric Anderson <https://github.com/ericanderson> // Dovydas Navickas <https://github.com/DovydasNavickas> // Josh Rutherford <https://github.com/theruther4d> // Guilherme Hübner <https://github.com/guilhermehubner> // Ferdy Budhidharma <https://github.com/ferdaber> // Johann Rakotoharisoa <https://github.com/jrakotoharisoa> // Olivier Pascal <https://github.com/pascaloliv> // Martin Hochel <https://github.com/hotell> // Frank Li <https://github.com/franklixuefei> // Jessica Franco <https://github.com/Jessidhia> // Saransh Kataria <https://github.com/saranshkataria> // Kanitkorn Sujautra <https://github.com/lukyth> // Sebastian Silbermann <https://github.com/eps1lon> // Kyle Scully <https://github.com/zieka> // Cong Zhang <https://github.com/dancerphil> // Dimitri Mitropoulos <https://github.com/dimitropoulos> // JongChan Choi <https://github.com/disjukr> // Victor Magalhães <https://github.com/vhfmag> // Dale Tan <https://github.com/hellatan> // // See https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react/index.d.ts // for the up-to-date list of contributors to @types/react interface IntrinsicElements { a: AnchorHTMLAttributes; abbr: HTMLAttributes; address: HTMLAttributes; area: AreaHTMLAttributes; article: HTMLAttributes; aside: HTMLAttributes; audio: AudioHTMLAttributes; b: HTMLAttributes; base: BaseHTMLAttributes; bdi: HTMLAttributes; bdo: HTMLAttributes; big: HTMLAttributes; blockquote: BlockquoteHTMLAttributes; body: HTMLAttributes; br: HTMLAttributes; button: ButtonHTMLAttributes; canvas: CanvasHTMLAttributes; caption: HTMLAttributes; cite: HTMLAttributes; code: HTMLAttributes; col: ColHTMLAttributes; colgroup: ColgroupHTMLAttributes; data: DataHTMLAttributes; datalist: HTMLAttributes; dd: HTMLAttributes; del: DelHTMLAttributes; details: DetailsHTMLAttributes; dfn: HTMLAttributes; dialog: DialogHTMLAttributes; div: HTMLAttributes; dl: HTMLAttributes; dt: HTMLAttributes; em: HTMLAttributes; embed: EmbedHTMLAttributes; fieldset: FieldsetHTMLAttributes; figcaption: HTMLAttributes; figure: HTMLAttributes; footer: HTMLAttributes; form: FormHTMLAttributes; h1: HTMLAttributes; h2: HTMLAttributes; h3: HTMLAttributes; h4: HTMLAttributes; h5: HTMLAttributes; h6: HTMLAttributes; head: HTMLAttributes; header: HTMLAttributes; hgroup: HTMLAttributes; hr: HTMLAttributes; html: HtmlHTMLAttributes; i: HTMLAttributes; iframe: IframeHTMLAttributes; img: ImgHTMLAttributes; input: InputHTMLAttributes; ins: InsHTMLAttributes; kbd: HTMLAttributes; keygen: KeygenHTMLAttributes; label: LabelHTMLAttributes; legend: HTMLAttributes; li: LiHTMLAttributes; link: LinkHTMLAttributes; main: HTMLAttributes; map: MapHTMLAttributes; mark: HTMLAttributes; menu: MenuHTMLAttributes; menuitem: HTMLAttributes; meta: MetaHTMLAttributes; meter: MeterHTMLAttributes; nav: HTMLAttributes; noindex: HTMLAttributes; noscript: HTMLAttributes; object: ObjectHTMLAttributes; ol: OlHTMLAttributes; optgroup: OptgroupHTMLAttributes; option: OptionHTMLAttributes; output: OutputHTMLAttributes; p: HTMLAttributes; param: ParamHTMLAttributes; picture: HTMLAttributes; pre: HTMLAttributes; progress: ProgressHTMLAttributes; q: QuoteHTMLAttributes; rp: HTMLAttributes; rt: HTMLAttributes; ruby: HTMLAttributes; s: HTMLAttributes; samp: HTMLAttributes; slot: SlotHTMLAttributes; script: ScriptHTMLAttributes; section: HTMLAttributes; select: SelectHTMLAttributes; small: HTMLAttributes; source: SourceHTMLAttributes; span: HTMLAttributes; strong: HTMLAttributes; style: StyleHTMLAttributes; sub: HTMLAttributes; summary: HTMLAttributes; sup: HTMLAttributes; table: TableHTMLAttributes; template: HTMLAttributes; tbody: HTMLAttributes; td: TdHTMLAttributes; textarea: TextareaHTMLAttributes; tfoot: HTMLAttributes; th: ThHTMLAttributes; thead: HTMLAttributes; time: TimeHTMLAttributes; title: HTMLAttributes; tr: HTMLAttributes; track: TrackHTMLAttributes; u: HTMLAttributes; ul: HTMLAttributes; var: HTMLAttributes; video: VideoHTMLAttributes; wbr: HTMLAttributes; webview: WebViewHTMLAttributes; svg: SVGProps; animate: SVGProps; animateMotion: SVGProps; animateTransform: SVGProps; circle: SVGProps; clipPath: SVGProps; defs: SVGProps; desc: SVGProps; ellipse: SVGProps; feBlend: SVGProps; feColorMatrix: SVGProps; feComponentTransfer: SVGProps; feComposite: SVGProps; feConvolveMatrix: SVGProps; feDiffuseLighting: SVGProps; feDisplacementMap: SVGProps; feDistantLight: SVGProps; feDropShadow: SVGProps; feFlood: SVGProps; feFuncA: SVGProps; feFuncB: SVGProps; feFuncG: SVGProps; feFuncR: SVGProps; feGaussianBlur: SVGProps; feImage: SVGProps; feMerge: SVGProps; feMergeNode: SVGProps; feMorphology: SVGProps; feOffset: SVGProps; fePointLight: SVGProps; feSpecularLighting: SVGProps; feSpotLight: SVGProps; feTile: SVGProps; feTurbulence: SVGProps; filter: SVGProps; foreignObject: SVGProps; g: SVGProps; image: SVGProps; line: SVGProps; linearGradient: SVGProps; marker: SVGProps; mask: SVGProps; metadata: SVGProps; mpath: SVGProps; path: SVGProps; pattern: SVGProps; polygon: SVGProps; polyline: SVGProps; radialGradient: SVGProps; rect: SVGProps; stop: SVGProps; switch: SVGProps; symbol: SVGProps; text: SVGProps; textPath: SVGProps; tspan: SVGProps; use: SVGProps; view: SVGProps; } type SVGProps = SVGAttributes; interface DOMAttributes { children?: any; dangerouslySetInnerHTML?: { __html: string; }; // Clipboard Events oncopy?: string; oncopycapture?: string; oncut?: string; oncutcapture?: string; onpaste?: string; onpastecapture?: string; // Composition Events oncompositionend?: string; oncompositionendcapture?: string; oncompositionstart?: string; oncompositionstartcapture?: string; oncompositionupdate?: string; oncompositionupdatecapture?: string; // Focus Events onfocus?: string; onfocuscapture?: string; onblur?: string; onblurcapture?: string; // Form Events onchange?: string; onchangecapture?: string; onbeforeinput?: string; onbeforeinputcapture?: string; oninput?: string; oninputcapture?: string; onreset?: string; onresetcapture?: string; onsubmit?: string; onsubmitcapture?: string; oninvalid?: string; oninvalidcapture?: string; // Image Events onload?: string; onloadcapture?: string; onerror?: string; // also a Media Event onerrorcapture?: string; // also a Media Event // Keyboard Events onkeydown?: string; onkeydowncapture?: string; onkeypress?: string; onkeypresscapture?: string; onkeyup?: string; onkeyupcapture?: string; // Media Events onabort?: string; onabortcapture?: string; oncanplay?: string; oncanplaycapture?: string; oncanplaythrough?: string; oncanplaythroughcapture?: string; ondurationchange?: string; ondurationchangecapture?: string; onemptied?: string; onemptiedcapture?: string; onencrypted?: string; onencryptedcapture?: string; onended?: string; onendedcapture?: string; onloadeddata?: string; onloadeddatacapture?: string; onloadedmetadata?: string; onloadedmetadatacapture?: string; onloadstart?: string; onloadstartcapture?: string; onpause?: string; onpausecapture?: string; onplay?: string; onplaycapture?: string; onplaying?: string; onplayingcapture?: string; onprogress?: string; onprogresscapture?: string; onratechange?: string; onratechangecapture?: string; onseeked?: string; onseekedcapture?: string; onseeking?: string; onseekingcapture?: string; onstalled?: string; onstalledcapture?: string; onsuspend?: string; onsuspendcapture?: string; ontimeupdate?: string; ontimeupdatecapture?: string; onvolumechange?: string; onvolumechangecapture?: string; onwaiting?: string; onwaitingcapture?: string; // MouseEvents onauxclick?: string; onauxclickcapture?: string; onclick?: string; onclickcapture?: string; oncontextmenu?: string; oncontextmenucapture?: string; ondoubleclick?: string; ondoubleclickcapture?: string; ondrag?: string; ondragcapture?: string; ondragend?: string; ondragendcapture?: string; ondragenter?: string; ondragentercapture?: string; ondragexit?: string; ondragexitcapture?: string; ondragleave?: string; ondragleavecapture?: string; ondragover?: string; ondragovercapture?: string; ondragstart?: string; ondragstartcapture?: string; ondrop?: string; ondropcapture?: string; onmousedown?: string; onmousedowncapture?: string; onmouseenter?: string; onmouseleave?: string; onmousemove?: string; onmousemovecapture?: string; onmouseout?: string; onmouseoutcapture?: string; onmouseover?: string; onmouseovercapture?: string; onmouseup?: string; onmouseupcapture?: string; // Selection Events onselect?: string; onselectcapture?: string; // Touch Events ontouchcancel?: string; ontouchcancelcapture?: string; ontouchend?: string; ontouchendcapture?: string; ontouchmove?: string; ontouchmovecapture?: string; ontouchstart?: string; ontouchstartcapture?: string; // Pointer Events onpointerdown?: string; onpointerdowncapture?: string; onpointermove?: string; onpointermovecapture?: string; onpointerup?: string; onpointerupcapture?: string; onpointercancel?: string; onpointercancelcapture?: string; onpointerenter?: string; onpointerentercapture?: string; onpointerleave?: string; onpointerleavecapture?: string; onpointerover?: string; onpointerovercapture?: string; onpointerout?: string; onpointeroutcapture?: string; ongotpointercapture?: string; ongotpointercapturecapture?: string; onlostpointercapture?: string; onlostpointercapturecapture?: string; // UI Events onscroll?: string; onscrollcapture?: string; // Wheel Events onwheel?: string; onwheelcapture?: string; // Animation Events onanimationstart?: string; onanimationstartcapture?: string; onanimationend?: string; onanimationendcapture?: string; onanimationiteration?: string; onanimationiterationcapture?: string; // Transition Events ontransitionend?: string; ontransitionendcapture?: string; } interface AriaAttributes { /** Identifies the currently active element when DOM focus is on a composite widget, textbox, group, or application. */ 'aria-activedescendant'?: string; /** Indicates whether assistive technologies will present all, or only parts of, the changed region based on the change notifications defined by the aria-relevant attribute. */ 'aria-atomic'?: boolean | 'false' | 'true'; /** * Indicates whether inputting text could trigger display of one or more predictions of the user's intended value for an input and specifies how predictions would be * presented if they are made. */ 'aria-autocomplete'?: 'none' | 'inline' | 'list' | 'both'; /** Indicates an element is being modified and that assistive technologies MAY want to wait until the modifications are complete before exposing them to the user. */ 'aria-busy'?: boolean | 'false' | 'true'; /** * Indicates the current "checked" state of checkboxes, radio buttons, and other widgets. * @see aria-pressed * @see aria-selected. */ 'aria-checked'?: boolean | 'false' | 'mixed' | 'true'; /** * Defines the total number of columns in a table, grid, or treegrid. * @see aria-colindex. */ 'aria-colcount'?: number; /** * Defines an element's column index or position with respect to the total number of columns within a table, grid, or treegrid. * @see aria-colcount * @see aria-colspan. */ 'aria-colindex'?: number; /** * Defines the number of columns spanned by a cell or gridcell within a table, grid, or treegrid. * @see aria-colindex * @see aria-rowspan. */ 'aria-colspan'?: number; /** * Identifies the element (or elements) whose contents or presence are controlled by the current element. * @see aria-owns. */ 'aria-controls'?: string; /** Indicates the element that represents the current item within a container or set of related elements. */ 'aria-current'?: boolean | 'false' | 'true' | 'page' | 'step' | 'location' | 'date' | 'time'; /** * Identifies the element (or elements) that describes the object. * @see aria-labelledby */ 'aria-describedby'?: string; /** * Identifies the element that provides a detailed, extended description for the object. * @see aria-describedby. */ 'aria-details'?: string; /** * Indicates that the element is perceivable but disabled, so it is not editable or otherwise operable. * @see aria-hidden * @see aria-readonly. */ 'aria-disabled'?: boolean | 'false' | 'true'; /** * Indicates what functions can be performed when a dragged object is released on the drop target. * @deprecated in ARIA 1.1 */ 'aria-dropeffect'?: 'none' | 'copy' | 'execute' | 'link' | 'move' | 'popup'; /** * Identifies the element that provides an error message for the object. * @see aria-invalid * @see aria-describedby. */ 'aria-errormessage'?: string; /** Indicates whether the element, or another grouping element it controls, is currently expanded or collapsed. */ 'aria-expanded'?: boolean | 'false' | 'true'; /** * Identifies the next element (or elements) in an alternate reading order of content which, at the user's discretion, * allows assistive technology to override the general default of reading in document source order. */ 'aria-flowto'?: string; /** * Indicates an element's "grabbed" state in a drag-and-drop operation. * @deprecated in ARIA 1.1 */ 'aria-grabbed'?: boolean | 'false' | 'true'; /** Indicates the availability and type of interactive popup element, such as menu or dialog, that can be triggered by an element. */ 'aria-haspopup'?: boolean | 'false' | 'true' | 'menu' | 'listbox' | 'tree' | 'grid' | 'dialog'; /** * Indicates whether the element is exposed to an accessibility API. * @see aria-disabled. */ 'aria-hidden'?: boolean | 'false' | 'true'; /** * Indicates the entered value does not conform to the format expected by the application. * @see aria-errormessage. */ 'aria-invalid'?: boolean | 'false' | 'true' | 'grammar' | 'spelling'; /** Indicates keyboard shortcuts that an author has implemented to activate or give focus to an element. */ 'aria-keyshortcuts'?: string; /** * Defines a string value that labels the current element. * @see aria-labelledby. */ 'aria-label'?: string; /** * Identifies the element (or elements) that labels the current element. * @see aria-describedby. */ 'aria-labelledby'?: string; /** Defines the hierarchical level of an element within a structure. */ 'aria-level'?: number; /** Indicates that an element will be updated, and describes the types of updates the user agents, assistive technologies, and user can expect from the live region. */ 'aria-live'?: 'off' | 'assertive' | 'polite'; /** Indicates whether an element is modal when displayed. */ 'aria-modal'?: boolean | 'false' | 'true'; /** Indicates whether a text box accepts multiple lines of input or only a single line. */ 'aria-multiline'?: boolean | 'false' | 'true'; /** Indicates that the user may select more than one item from the current selectable descendants. */ 'aria-multiselectable'?: boolean | 'false' | 'true'; /** Indicates whether the element's orientation is horizontal, vertical, or unknown/ambiguous. */ 'aria-orientation'?: 'horizontal' | 'vertical'; /** * Identifies an element (or elements) in order to define a visual, functional, or contextual parent/child relationship * between DOM elements where the DOM hierarchy cannot be used to represent the relationship. * @see aria-controls. */ 'aria-owns'?: string; /** * Defines a short hint (a word or short phrase) intended to aid the user with data entry when the control has no value. * A hint could be a sample value or a brief description of the expected format. */ 'aria-placeholder'?: string; /** * Defines an element's number or position in the current set of listitems or treeitems. Not required if all elements in the set are present in the DOM. * @see aria-setsize. */ 'aria-posinset'?: number; /** * Indicates the current "pressed" state of toggle buttons. * @see aria-checked * @see aria-selected. */ 'aria-pressed'?: boolean | 'false' | 'mixed' | 'true'; /** * Indicates that the element is not editable, but is otherwise operable. * @see aria-disabled. */ 'aria-readonly'?: boolean | 'false' | 'true'; /** * Indicates what notifications the user agent will trigger when the accessibility tree within a live region is modified. * @see aria-atomic. */ 'aria-relevant'?: | 'additions' | 'additions removals' | 'additions text' | 'all' | 'removals' | 'removals additions' | 'removals text' | 'text' | 'text additions' | 'text removals'; /** Indicates that user input is required on the element before a form may be submitted. */ 'aria-required'?: boolean | 'false' | 'true'; /** Defines a human-readable, author-localized description for the role of an element. */ 'aria-roledescription'?: string; /** * Defines the total number of rows in a table, grid, or treegrid. * @see aria-rowindex. */ 'aria-rowcount'?: number; /** * Defines an element's row index or position with respect to the total number of rows within a table, grid, or treegrid. * @see aria-rowcount * @see aria-rowspan. */ 'aria-rowindex'?: number; /** * Defines the number of rows spanned by a cell or gridcell within a table, grid, or treegrid. * @see aria-rowindex * @see aria-colspan. */ 'aria-rowspan'?: number; /** * Indicates the current "selected" state of various widgets. * @see aria-checked * @see aria-pressed. */ 'aria-selected'?: boolean | 'false' | 'true'; /** * Defines the number of items in the current set of listitems or treeitems. Not required if all elements in the set are present in the DOM. * @see aria-posinset. */ 'aria-setsize'?: number; /** Indicates if items in a table or grid are sorted in ascending or descending order. */ 'aria-sort'?: 'none' | 'ascending' | 'descending' | 'other'; /** Defines the maximum allowed value for a range widget. */ 'aria-valuemax'?: number; /** Defines the minimum allowed value for a range widget. */ 'aria-valuemin'?: number; /** * Defines the current value for a range widget. * @see aria-valuetext. */ 'aria-valuenow'?: number; /** Defines the human readable text alternative of aria-valuenow for a range widget. */ 'aria-valuetext'?: string; } interface HTMLAttributes extends AriaAttributes, DOMAttributes { // React-specific Attributes // Standard HTML Attributes accesskey?: string; className?: string; contenteditable?: (boolean | 'true' | 'false') | 'inherit'; contextmenu?: string; dir?: string; draggable?: boolean | 'true' | 'false'; hidden?: boolean; id?: string; lang?: string; placeholder?: string; slot?: string; spellcheck?: boolean | 'true' | 'false'; style?: string; tabindex?: number; title?: string; translate?: 'yes' | 'no'; // Unknown radiogroup?: string; // <command>, <menuitem> // WAI-ARIA role?: string; // RDFa Attributes about?: string; datatype?: string; inlist?: any; prefix?: string; property?: string; resource?: string; typeof?: string; vocab?: string; // Non-standard Attributes autocapitalize?: string; autocorrect?: string; autosave?: string; color?: string; itemprop?: string; itemscope?: boolean; itemtype?: string; itemid?: string; itemref?: string; results?: number; security?: string; unselectable?: 'on' | 'off'; // Living Standard /** * Hints at the type of data that might be entered by the user while editing the element or its contents * @see https://html.spec.whatwg.org/multipage/interaction.html#input-modalities:-the-inputmode-attribute */ inputmode?: 'none' | 'text' | 'tel' | 'url' | 'email' | 'numeric' | 'decimal' | 'search'; /** * Specify that a standard HTML element should behave like a defined custom built-in element * @see https://html.spec.whatwg.org/multipage/custom-elements.html#attr-is */ is?: string; class?: string; } type HTMLAttributeReferrerPolicy = | '' | 'no-referrer' | 'no-referrer-when-downgrade' | 'origin' | 'origin-when-cross-origin' | 'same-origin' | 'strict-origin' | 'strict-origin-when-cross-origin' | 'unsafe-url'; interface AnchorHTMLAttributes extends HTMLAttributes { download?: any; href?: string; hreflang?: string; media?: string; ping?: string; rel?: string; target?: string; type?: string; referrerpolicy?: HTMLAttributeReferrerPolicy; } type AudioHTMLAttributes = MediaHTMLAttributes; interface AreaHTMLAttributes extends HTMLAttributes { alt?: string; coords?: string; download?: any; href?: string; hreflang?: string; media?: string; referrerpolicy?: HTMLAttributeReferrerPolicy; rel?: string; shape?: string; target?: string; } interface BaseHTMLAttributes extends HTMLAttributes { href?: string; target?: string; } interface BlockquoteHTMLAttributes extends HTMLAttributes { cite?: string; } interface ButtonHTMLAttributes extends HTMLAttributes { autofocus?: boolean; disabled?: boolean; form?: string; formaction?: string; formenctype?: string; formmethod?: string; formnovalidate?: boolean; formtarget?: string; name?: string; type?: 'submit' | 'reset' | 'button'; value?: string | ReadonlyArray<string> | number; } interface CanvasHTMLAttributes extends HTMLAttributes { height?: number | string; width?: number | string; } interface ColHTMLAttributes extends HTMLAttributes { span?: number; width?: number | string; } interface ColgroupHTMLAttributes extends HTMLAttributes { span?: number; } interface DataHTMLAttributes extends HTMLAttributes { value?: string | ReadonlyArray<string> | number; } interface DetailsHTMLAttributes extends HTMLAttributes { open?: boolean; ontoggle?: string; } interface DelHTMLAttributes extends HTMLAttributes { cite?: string; datetime?: string; } interface DialogHTMLAttributes extends HTMLAttributes { open?: boolean; } interface EmbedHTMLAttributes extends HTMLAttributes { height?: number | string; src?: string; type?: string; width?: number | string; } interface FieldsetHTMLAttributes extends HTMLAttributes { disabled?: boolean; form?: string; name?: string; } interface FormHTMLAttributes extends HTMLAttributes { acceptcharset?: string; action?: string; autocomplete?: string; enctype?: string; method?: string; name?: string; novalidate?: boolean; target?: string; } interface HtmlHTMLAttributes extends HTMLAttributes { manifest?: string; } interface IframeHTMLAttributes extends HTMLAttributes { allow?: string; allowfullscreen?: boolean; allowtransparency?: boolean; /** @deprecated */ frameborder?: number | string; height?: number | string; loading?: 'eager' | 'lazy'; /** @deprecated */ marginheight?: number; /** @deprecated */ marginwidth?: number; name?: string; referrerpolicy?: HTMLAttributeReferrerPolicy; sandbox?: string; /** @deprecated */ scrolling?: string; seamless?: boolean; src?: string; srcdoc?: string; width?: number | string; } interface ImgHTMLAttributes extends HTMLAttributes { alt?: string; crossorigin?: 'anonymous' | 'use-credentials' | ''; decoding?: 'async' | 'auto' | 'sync'; height?: number | string; loading?: 'eager' | 'lazy'; referrerpolicy?: HTMLAttributeReferrerPolicy; sizes?: string; src?: string; srcset?: string; usemap?: string; width?: number | string; } interface InsHTMLAttributes extends HTMLAttributes { cite?: string; datetime?: string; } interface InputHTMLAttributes extends HTMLAttributes { accept?: string; alt?: string; autocomplete?: string; autofocus?: boolean; capture?: boolean | string; // https://www.w3.org/TR/html-media-capture/#the-capture-attribute checked?: boolean; crossorigin?: string; disabled?: boolean; enterkeyhint?: 'enter' | 'done' | 'go' | 'next' | 'previous' | 'search' | 'send'; form?: string; formaction?: string; formenctype?: string; formmethod?: string; formnovalidate?: boolean; formtarget?: string; height?: number | string; list?: string; max?: number | string; maxlength?: number; min?: number | string; minlength?: number; multiple?: boolean; name?: string; pattern?: string; placeholder?: string; readonly?: boolean; required?: boolean; size?: number; src?: string; step?: number | string; type?: string; value?: string | ReadonlyArray<string> | number; width?: number | string; onchange?: string; } interface KeygenHTMLAttributes extends HTMLAttributes { autofocus?: boolean; challenge?: string; disabled?: boolean; form?: string; keytype?: string; keyparams?: string; name?: string; } interface LabelHTMLAttributes extends HTMLAttributes { form?: string; htmlFor?: string; for?: string; } interface LiHTMLAttributes extends HTMLAttributes { value?: string | ReadonlyArray<string> | number; } interface LinkHTMLAttributes extends HTMLAttributes { as?: string; crossorigin?: string; href?: string; hreflang?: string; integrity?: string; media?: string; referrerpolicy?: HTMLAttributeReferrerPolicy; rel?: string; sizes?: string; type?: string; charset?: string; } interface MapHTMLAttributes extends HTMLAttributes { name?: string; } interface MenuHTMLAttributes extends HTMLAttributes { type?: string; } interface MediaHTMLAttributes extends HTMLAttributes { autoplay?: boolean; controls?: boolean; controlslist?: string; crossorigin?: string; loop?: boolean; mediagroup?: string; muted?: boolean; playsinline?: boolean; preload?: string; src?: string; } interface MetaHTMLAttributes extends HTMLAttributes { charset?: string; content?: string; httpequiv?: string; name?: string; } interface MeterHTMLAttributes extends HTMLAttributes { form?: string; high?: number; low?: number; max?: number | string; min?: number | string; optimum?: number; value?: string | ReadonlyArray<string> | number; } interface QuoteHTMLAttributes extends HTMLAttributes { cite?: string; } interface ObjectHTMLAttributes extends HTMLAttributes { classid?: string; data?: string; form?: string; height?: number | string; name?: string; type?: string; usemap?: string; width?: number | string; wmode?: string; } interface OlHTMLAttributes extends HTMLAttributes { reversed?: boolean; start?: number; type?: '1' | 'a' | 'A' | 'i' | 'I'; } interface OptgroupHTMLAttributes extends HTMLAttributes { disabled?: boolean; label?: string; } interface OptionHTMLAttributes extends HTMLAttributes { disabled?: boolean; label?: string; selected?: boolean; value?: string | ReadonlyArray<string> | number; } interface OutputHTMLAttributes extends HTMLAttributes { form?: string; htmlFor?: string; name?: string; for?: string; } interface ParamHTMLAttributes extends HTMLAttributes { name?: string; value?: string | ReadonlyArray<string> | number; } interface ProgressHTMLAttributes extends HTMLAttributes { max?: number | string; value?: string | ReadonlyArray<string> | number; } interface SlotHTMLAttributes extends HTMLAttributes { name?: string; } interface ScriptHTMLAttributes extends HTMLAttributes { async?: boolean; /** @deprecated */ charset?: string; crossorigin?: string; defer?: boolean; integrity?: string; nomodule?: boolean; nonce?: string; referrerpolicy?: HTMLAttributeReferrerPolicy; src?: string; type?: string; } interface SelectHTMLAttributes extends HTMLAttributes { autocomplete?: string; autofocus?: boolean; disabled?: boolean; form?: string; multiple?: boolean; name?: string; required?: boolean; size?: number; value?: string | ReadonlyArray<string> | number; onchange?: string; } interface SourceHTMLAttributes extends HTMLAttributes { media?: string; sizes?: string; src?: string; srcset?: string; type?: string; } interface StyleHTMLAttributes extends HTMLAttributes { media?: string; nonce?: string; scoped?: boolean; type?: string; } interface TableHTMLAttributes extends HTMLAttributes { cellpadding?: number | string; cellspacing?: number | string; summary?: string; width?: number | string; } interface TextareaHTMLAttributes extends HTMLAttributes { autocomplete?: string; autofocus?: boolean; cols?: number; dirname?: string; disabled?: boolean; form?: string; maxlength?: number; minlength?: number; name?: string; placeholder?: string; readonly?: boolean; required?: boolean; rows?: number; value?: string | ReadonlyArray<string> | number; wrap?: string; onchange?: string; } interface TdHTMLAttributes extends HTMLAttributes { align?: 'left' | 'center' | 'right' | 'justify' | 'char'; colspan?: number; headers?: string; rowspan?: number; scope?: string; abbr?: string; height?: number | string; width?: number | string; valign?: 'top' | 'middle' | 'bottom' | 'baseline'; } interface ThHTMLAttributes extends HTMLAttributes { align?: 'left' | 'center' | 'right' | 'justify' | 'char'; colspan?: number; headers?: string; rowspan?: number; scope?: string; abbr?: string; } interface TimeHTMLAttributes extends HTMLAttributes { datetime?: string; } interface TrackHTMLAttributes extends HTMLAttributes { default?: boolean; kind?: string; label?: string; src?: string; srclang?: string; } interface VideoHTMLAttributes extends MediaHTMLAttributes { height?: number | string; playsinline?: boolean; poster?: string; width?: number | string; disablepictureinpicture?: boolean; disableremoteplayback?: boolean; } interface SVGAttributes extends AriaAttributes, DOMAttributes { // Attributes which also defined in HTMLAttributes // See comment in SVGDOMPropertyConfig.js className?: string; color?: string; height?: number | string; id?: string; lang?: string; max?: number | string; media?: string; method?: string; min?: number | string; name?: string; style?: string; target?: string; type?: string; width?: number | string; // Other HTML properties supported by SVG elements in browsers role?: string; tabindex?: number; crossorigin?: 'anonymous' | 'use-credentials' | ''; // SVG Specific attributes accentheight?: number | string; accumulate?: 'none' | 'sum'; additive?: 'replace' | 'sum'; alignmentbaseline?: | 'auto' | 'baseline' | 'before-edge' | 'text-before-edge' | 'middle' | 'central' | 'after-edge' | 'text-after-edge' | 'ideographic' | 'alphabetic' | 'hanging' | 'mathematical' | 'inherit'; allowreorder?: 'no' | 'yes'; alphabetic?: number | string; amplitude?: number | string; arabicform?: 'initial' | 'medial' | 'terminal' | 'isolated'; ascent?: number | string; attributename?: string; attributetype?: string; autoreverse?: boolean | 'true' | 'false'; azimuth?: number | string; basefrequency?: number | string; baselineshift?: number | string; baseprofile?: number | string; bbox?: number | string; begin?: number | string; bias?: number | string; by?: number | string; calcmode?: number | string; capheight?: number | string; clip?: number | string; clippath?: string; clippathunits?: number | string; cliprule?: number | string; colorinterpolation?: number | string; colorinterpolationfilters?: 'auto' | 'sRGB' | 'linearRGB' | 'inherit'; colorprofile?: number | string; colorrendering?: number | string; contentscripttype?: number | string; contentstyletype?: number | string; cursor?: number | string; cx?: number | string; cy?: number | string; d?: string; decelerate?: number | string; descent?: number | string; diffuseconstant?: number | string; direction?: number | string; display?: number | string; divisor?: number | string; dominantbaseline?: number | string; dur?: number | string; dx?: number | string; dy?: number | string; edgemode?: number | string; elevation?: number | string; enablebackground?: number | string; end?: number | string; exponent?: number | string; externalresourcesrequired?: boolean | 'true' | 'false'; fill?: string; fillopacity?: number | string; fillrule?: 'nonzero' | 'evenodd' | 'inherit'; filter?: string; filterres?: number | string; filterunits?: number | string; floodcolor?: number | string; floodopacity?: number | string; focusable?: (boolean | 'true' | 'false') | 'auto'; fontfamily?: string; fontsize?: number | string; fontsizeadjust?: number | string; fontstretch?: number | string; fontstyle?: number | string; fontvariant?: number | string; fontweight?: number | string; format?: number | string; from?: number | string; fx?: number | string; fy?: number | string; g1?: number | string; g2?: number | string; glyphname?: number | string; glyphorientationhorizontal?: number | string; glyphorientationvertical?: number | string; glyphref?: number | string; gradienttransform?: string; gradientunits?: string; hanging?: number | string; horizadvx?: number | string; horizoriginx?: number | string; href?: string; ideographic?: number | string; imagerendering?: number | string; in2?: number | string; in?: string; intercept?: number | string; k1?: number | string; k2?: number | string; k3?: number | string; k4?: number | string; k?: number | string; kernelmatrix?: number | string; kernelunitlength?: number | string; kerning?: number | string; keypoints?: number | string; keysplines?: number | string; keytimes?: number | string; lengthadjust?: number | string; letterspacing?: number | string; lightingcolor?: number | string; limitingconeangle?: number | string; local?: number | string; markerend?: string; markerheight?: number | string; markermid?: string; markerstart?: string; markerunits?: number | string; markerwidth?: number | string; mask?: string; maskcontentunits?: number | string; maskunits?: number | string; mathematical?: number | string; mode?: number | string; numoctaves?: number | string; offset?: number | string; opacity?: number | string; operator?: number | string; order?: number | string; orient?: number | string; orientation?: number | string; origin?: number | string; overflow?: number | string; overlineposition?: number | string; overlinethickness?: number | string; paintorder?: number | string; panose1?: number | string; path?: string; pathlength?: number | string; patterncontentunits?: string; patterntransform?: number | string; patternunits?: string; pointerevents?: number | string; points?: string; pointsatx?: number | string; pointsaty?: number | string; pointsatz?: number | string; preservealpha?: boolean | 'true' | 'false'; preserveaspectratio?: string; primitiveunits?: number | string; r?: number | string; radius?: number | string; refx?: number | string; refy?: number | string; renderingintent?: number | string; repeatcount?: number | string; repeatdur?: number | string; requiredextensions?: number | string; requiredfeatures?: number | string; restart?: number | string; result?: string; rotate?: number | string; rx?: number | string; ry?: number | string; scale?: number | string; seed?: number | string; shaperendering?: number | string; slope?: number | string; spacing?: number | string; specularconstant?: number | string; specularexponent?: number | string; speed?: number | string; spreadmethod?: string; startoffset?: number | string; stddeviation?: number | string; stemh?: number | string; stemv?: number | string; stitchtiles?: number | string; stopcolor?: string; stopopacity?: number | string; strikethroughposition?: number | string; strikethroughthickness?: number | string; string?: number | string; stroke?: string; strokedasharray?: string | number; strokedashoffset?: string | number; strokelinecap?: 'butt' | 'round' | 'square' | 'inherit'; strokelinejoin?: 'miter' | 'round' | 'bevel' | 'inherit'; strokemiterlimit?: number | string; strokeopacity?: number | string; strokewidth?: number | string; surfacescale?: number | string; systemlanguage?: number | string; tablevalues?: number | string; targetx?: number | string; targety?: number | string; textanchor?: string; textdecoration?: number | string; textlength?: number | string; textrendering?: number | string; to?: number | string; transform?: string; u1?: number | string; u2?: number | string; underlineposition?: number | string; underlinethickness?: number | string; unicode?: number | string; unicodebidi?: number | string; unicoderange?: number | string; unitsperem?: number | string; valphabetic?: number | string; values?: string; vectoreffect?: number | string; version?: string; vertadvy?: number | string; vertoriginx?: number | string; vertoriginy?: number | string; vhanging?: number | string; videographic?: number | string; viewbox?: string; viewtarget?: number | string; visibility?: number | string; vmathematical?: number | string; widths?: number | string; wordspacing?: number | string; writingmode?: number | string; x1?: number | string; x2?: number | string; x?: number | string; xchannelselector?: string; xheight?: number | string; xlinkactuate?: string; xlinkarcrole?: string; xlinkhref?: string; xlinkrole?: string; xlinkshow?: string; xlinktitle?: string; xlinktype?: string; xmlbase?: string; xmllang?: string; xmlns?: string; xmlnsxlink?: string; xmlspace?: string; y1?: number | string; y2?: number | string; y?: number | string; ychannelselector?: string; z?: number | string; zoomandpan?: string; class?: string; } interface WebViewHTMLAttributes extends HTMLAttributes { allowfullscreen?: boolean; allowpopups?: boolean; autofocus?: boolean; autosize?: boolean; blinkfeatures?: string; disableblinkfeatures?: string; disableguestresize?: boolean; disablewebsecurity?: boolean; guestinstance?: string; httpreferrer?: string; nodeintegration?: boolean; partition?: string; plugins?: boolean; preload?: string; src?: string; useragent?: string; webpreferences?: string; } } }
mit
mathnet/mathnet-numerics
src/Numerics.Tests/LinearAlgebraTests/Complex/UserDefinedMatrixTests.cs
2522
// <copyright file="UserDefinedMatrixTests.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // Copyright (c) 2009-2010 Math.NET // 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. // </copyright> using MathNet.Numerics.LinearAlgebra; using NUnit.Framework; namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Complex { using Complex = System.Numerics.Complex; /// <summary> /// Test class for user-defined matrix. /// </summary> [TestFixture, Category("LA")] public class UserDefinedMatrixTests : MatrixTests { /// <summary> /// Creates a matrix for the given number of rows and columns. /// </summary> /// <param name="rows">The number of rows.</param> /// <param name="columns">The number of columns.</param> /// <returns>A matrix with the given dimensions.</returns> protected override Matrix<Complex> CreateMatrix(int rows, int columns) { return new UserDefinedMatrix(rows, columns); } /// <summary> /// Creates a matrix from a 2D array. /// </summary> /// <param name="data">The 2D array to create this matrix from.</param> /// <returns>A matrix with the given values.</returns> protected override Matrix<Complex> CreateMatrix(Complex[,] data) { return new UserDefinedMatrix(data); } } }
mit
hsimpson/three.js
editor/js/Sidebar.Geometry.TubeGeometry.js
4868
/** * @author Temdog007 / http://github.com/Temdog007 */ Sidebar.Geometry.TubeGeometry = function ( editor, object ) { var strings = editor.strings; var signals = editor.signals; var container = new UI.Row(); var geometry = object.geometry; var parameters = geometry.parameters; // points var lastPointIdx = 0; var pointsUI = []; var pointsRow = new UI.Row(); pointsRow.add( new UI.Text( strings.getKey( 'sidebar/geometry/tube_geometry/path' ) ).setWidth( '90px' ) ); var points = new UI.Span().setDisplay( 'inline-block' ); pointsRow.add( points ); var pointsList = new UI.Div(); points.add( pointsList ); var parameterPoints = parameters.path.points; for ( var i = 0; i < parameterPoints.length; i ++ ) { var point = parameterPoints[ i ]; pointsList.add( createPointRow( point.x, point.y, point.z ) ); } var addPointButton = new UI.Button( '+' ).onClick( function () { if ( pointsUI.length === 0 ) { pointsList.add( createPointRow( 0, 0, 0 ) ); } else { var point = pointsUI[ pointsUI.length - 1 ]; pointsList.add( createPointRow( point.x.getValue(), point.y.getValue(), point.z.getValue() ) ); } update(); } ); points.add( addPointButton ); container.add( pointsRow ); // radius var radiusRow = new UI.Row(); var radius = new UI.Number( parameters.radius ).onChange( update ); radiusRow.add( new UI.Text( strings.getKey( 'sidebar/geometry/tube_geometry/radius' ) ).setWidth( '90px' ) ); radiusRow.add( radius ); container.add( radiusRow ); // tubularSegments var tubularSegmentsRow = new UI.Row(); var tubularSegments = new UI.Integer( parameters.tubularSegments ).onChange( update ); tubularSegmentsRow.add( new UI.Text( strings.getKey( 'sidebar/geometry/tube_geometry/tubularsegments' ) ).setWidth( '90px' ) ); tubularSegmentsRow.add( tubularSegments ); container.add( tubularSegmentsRow ); // radialSegments var radialSegmentsRow = new UI.Row(); var radialSegments = new UI.Integer( parameters.radialSegments ).onChange( update ); radialSegmentsRow.add( new UI.Text( strings.getKey( 'sidebar/geometry/tube_geometry/radialsegments' ) ).setWidth( '90px' ) ); radialSegmentsRow.add( radialSegments ); container.add( radialSegmentsRow ); // closed var closedRow = new UI.Row(); var closed = new UI.Checkbox( parameters.closed ).onChange( update ); closedRow.add( new UI.Text( strings.getKey( 'sidebar/geometry/tube_geometry/closed' ) ).setWidth( '90px' ) ); closedRow.add( closed ); container.add( closedRow ); // curveType var curveTypeRow = new UI.Row(); var curveType = new UI.Select().setOptions( { centripetal: 'centripetal', chordal: 'chordal', catmullrom: 'catmullrom' } ).setValue( parameters.path.curveType ).onChange( update ); curveTypeRow.add( new UI.Text( strings.getKey( 'sidebar/geometry/tube_geometry/curvetype' ) ).setWidth( '90px' ), curveType ); container.add( curveTypeRow ); // tension var tensionRow = new UI.Row().setDisplay( curveType.getValue() == 'catmullrom' ? '' : 'none' ); var tension = new UI.Number( parameters.path.tension ).setStep( 0.01 ).onChange( update ); tensionRow.add( new UI.Text( strings.getKey( 'sidebar/geometry/tube_geometry/tension' ) ).setWidth( '90px' ), tension ); container.add( tensionRow ); // function update() { var points = []; var count = 0; for ( var i = 0; i < pointsUI.length; i ++ ) { var pointUI = pointsUI[ i ]; if ( ! pointUI ) continue; points.push( new THREE.Vector3( pointUI.x.getValue(), pointUI.y.getValue(), pointUI.z.getValue() ) ); count ++; pointUI.lbl.setValue( count ); } tensionRow.setDisplay( curveType.getValue() == 'catmullrom' ? '' : 'none' ); editor.execute( new SetGeometryCommand( object, new THREE[ geometry.type ]( new THREE.CatmullRomCurve3( points, closed.getValue(), curveType.getValue(), tension.getValue() ), tubularSegments.getValue(), radius.getValue(), radialSegments.getValue(), closed.getValue() ) ) ); } function createPointRow( x, y, z ) { var pointRow = new UI.Div(); var lbl = new UI.Text( lastPointIdx + 1 ).setWidth( '20px' ); var txtX = new UI.Number( x ).setWidth( '30px' ).onChange( update ); var txtY = new UI.Number( y ).setWidth( '30px' ).onChange( update ); var txtZ = new UI.Number( z ).setWidth( '30px' ).onChange( update ); var idx = lastPointIdx; var btn = new UI.Button( '-' ).onClick( function () { deletePointRow( idx ); } ); pointsUI.push( { row: pointRow, lbl: lbl, x: txtX, y: txtY, z: txtZ } ); lastPointIdx ++; pointRow.add( lbl, txtX, txtY, txtZ, btn ); return pointRow; } function deletePointRow( idx ) { if ( ! pointsUI[ idx ] ) return; pointsList.remove( pointsUI[ idx ].row ); pointsUI[ idx ] = null; update(); } return container; }; Sidebar.Geometry.TubeBufferGeometry = Sidebar.Geometry.TubeGeometry;
mit
spirom/LearningSpark
src/main/scala/special/HashJoin.scala
2394
package special import org.apache.spark.rdd.RDD import org.apache.spark.{SparkContext, SparkConf} import scala.collection.mutable // This gives is access to the PairRDDFunctions import org.apache.spark.SparkContext._ // encapsulate a small sequence of pairs to be joined with pair RDDs -- // making this serializable effectively allows the hash table to be // broadcast to each worker // Reference: http://en.wikipedia.org/wiki/Hash_join // (this is specifically an inner equi-join on pairs) class HashJoiner[K,V](small: Seq[(K,V)]) extends java.io.Serializable { // stash it as a hash table, remembering that the keys may not be unique, // so we need to collect values for each key in a list val m = new mutable.HashMap[K, mutable.ListBuffer[V]]() small.foreach { case (k, v) => if (m.contains(k)) m(k) += v else m(k) = mutable.ListBuffer(v) } // when joining the RDD, remember that each key in it may or may not have // a matching key in the array, and we need a result tuple for each value // in the list contained in the corresponding hash table entry def joinOnLeft[U](large: RDD[(K,U)]) : RDD[(K, (U,V))] = { large.flatMap { case (k, u) => m.get(k).flatMap(ll => Some(ll.map(v => (k, (u, v))))).getOrElse(mutable.ListBuffer()) } } } object HashJoin { def main (args: Array[String]) { val conf = new SparkConf().setAppName("HashJoin").setMaster("local[4]") val sc = new SparkContext(conf) val smallRDD = sc.parallelize( Seq((1, 'a'), (1, 'c'), (2, 'a'), (3,'x'), (3,'y'), (4,'a')), 4) val largeRDD = sc.parallelize( for (x <- 1 to 10000) yield (x % 4, x), 4 ) // simply joining the two RDDs will be slow as it requires // lots of communication val joined = largeRDD.join(smallRDD) joined.collect().foreach(println) // If the smaller RDD is small enough we're better of with it not // being an RDD -- and we can implement a hash join by hand, effectively // broadcasting the hash table to each worker println("hash join result") // NOTE: it may be tempting to use "collectAsMap" below instead of "collect", // and simplify the joiner accordingly, but that only works if the keys // are unique val joiner = new HashJoiner(smallRDD.collect()) val hashJoined = joiner.joinOnLeft(largeRDD) hashJoined.collect().foreach(println) } }
mit
BlessingDev/When-we-lost-our-home
Assets/HOMI/NGUI/Scripts/Editor/NGUIEditorTools.cs
60122
//---------------------------------------------- // NGUI: Next-Gen UI kit // Copyright © 2011-2014 Tasharen Entertainment //---------------------------------------------- using UnityEditor; using UnityEngine; using System.Collections.Generic; using System.Reflection; /// <summary> /// Tools for the editor /// </summary> public static class NGUIEditorTools { static Texture2D mBackdropTex; static Texture2D mContrastTex; static Texture2D mGradientTex; static GameObject mPrevious; /// <summary> /// Returns a blank usable 1x1 white texture. /// </summary> static public Texture2D blankTexture { get { return EditorGUIUtility.whiteTexture; } } /// <summary> /// Returns a usable texture that looks like a dark checker board. /// </summary> static public Texture2D backdropTexture { get { if (mBackdropTex == null) mBackdropTex = CreateCheckerTex( new Color(0.1f, 0.1f, 0.1f, 0.5f), new Color(0.2f, 0.2f, 0.2f, 0.5f)); return mBackdropTex; } } /// <summary> /// Returns a usable texture that looks like a high-contrast checker board. /// </summary> static public Texture2D contrastTexture { get { if (mContrastTex == null) mContrastTex = CreateCheckerTex( new Color(0f, 0.0f, 0f, 0.5f), new Color(1f, 1f, 1f, 0.5f)); return mContrastTex; } } /// <summary> /// Gradient texture is used for title bars / headers. /// </summary> static public Texture2D gradientTexture { get { if (mGradientTex == null) mGradientTex = CreateGradientTex(); return mGradientTex; } } /// <summary> /// Create a white dummy texture. /// </summary> static Texture2D CreateDummyTex () { Texture2D tex = new Texture2D(1, 1); tex.name = "[Generated] Dummy Texture"; tex.hideFlags = HideFlags.DontSave; tex.filterMode = FilterMode.Point; tex.SetPixel(0, 0, Color.white); tex.Apply(); return tex; } /// <summary> /// Create a checker-background texture /// </summary> static Texture2D CreateCheckerTex (Color c0, Color c1) { Texture2D tex = new Texture2D(16, 16); tex.name = "[Generated] Checker Texture"; tex.hideFlags = HideFlags.DontSave; for (int y = 0; y < 8; ++y) for (int x = 0; x < 8; ++x) tex.SetPixel(x, y, c1); for (int y = 8; y < 16; ++y) for (int x = 0; x < 8; ++x) tex.SetPixel(x, y, c0); for (int y = 0; y < 8; ++y) for (int x = 8; x < 16; ++x) tex.SetPixel(x, y, c0); for (int y = 8; y < 16; ++y) for (int x = 8; x < 16; ++x) tex.SetPixel(x, y, c1); tex.Apply(); tex.filterMode = FilterMode.Point; return tex; } /// <summary> /// Create a gradient texture /// </summary> static Texture2D CreateGradientTex () { Texture2D tex = new Texture2D(1, 16); tex.name = "[Generated] Gradient Texture"; tex.hideFlags = HideFlags.DontSave; Color c0 = new Color(1f, 1f, 1f, 0f); Color c1 = new Color(1f, 1f, 1f, 0.4f); for (int i = 0; i < 16; ++i) { float f = Mathf.Abs((i / 15f) * 2f - 1f); f *= f; tex.SetPixel(0, i, Color.Lerp(c0, c1, f)); } tex.Apply(); tex.filterMode = FilterMode.Bilinear; return tex; } /// <summary> /// Draws the tiled texture. Like GUI.DrawTexture() but tiled instead of stretched. /// </summary> static public void DrawTiledTexture (Rect rect, Texture tex) { GUI.BeginGroup(rect); { int width = Mathf.RoundToInt(rect.width); int height = Mathf.RoundToInt(rect.height); for (int y = 0; y < height; y += tex.height) { for (int x = 0; x < width; x += tex.width) { GUI.DrawTexture(new Rect(x, y, tex.width, tex.height), tex); } } } GUI.EndGroup(); } /// <summary> /// Draw a single-pixel outline around the specified rectangle. /// </summary> static public void DrawOutline (Rect rect) { if (Event.current.type == EventType.Repaint) { Texture2D tex = contrastTexture; GUI.color = Color.white; DrawTiledTexture(new Rect(rect.xMin, rect.yMax, 1f, -rect.height), tex); DrawTiledTexture(new Rect(rect.xMax, rect.yMax, 1f, -rect.height), tex); DrawTiledTexture(new Rect(rect.xMin, rect.yMin, rect.width, 1f), tex); DrawTiledTexture(new Rect(rect.xMin, rect.yMax, rect.width, 1f), tex); } } /// <summary> /// Draw a single-pixel outline around the specified rectangle. /// </summary> static public void DrawOutline (Rect rect, Color color) { if (Event.current.type == EventType.Repaint) { Texture2D tex = blankTexture; GUI.color = color; GUI.DrawTexture(new Rect(rect.xMin, rect.yMin, 1f, rect.height), tex); GUI.DrawTexture(new Rect(rect.xMax, rect.yMin, 1f, rect.height), tex); GUI.DrawTexture(new Rect(rect.xMin, rect.yMin, rect.width, 1f), tex); GUI.DrawTexture(new Rect(rect.xMin, rect.yMax, rect.width, 1f), tex); GUI.color = Color.white; } } /// <summary> /// Draw a selection outline around the specified rectangle. /// </summary> static public void DrawOutline (Rect rect, Rect relative, Color color) { if (Event.current.type == EventType.Repaint) { // Calculate where the outer rectangle would be float x = rect.xMin + rect.width * relative.xMin; float y = rect.yMax - rect.height * relative.yMin; float width = rect.width * relative.width; float height = -rect.height * relative.height; relative = new Rect(x, y, width, height); // Draw the selection DrawOutline(relative, color); } } /// <summary> /// Draw a selection outline around the specified rectangle. /// </summary> static public void DrawOutline (Rect rect, Rect relative) { if (Event.current.type == EventType.Repaint) { // Calculate where the outer rectangle would be float x = rect.xMin + rect.width * relative.xMin; float y = rect.yMax - rect.height * relative.yMin; float width = rect.width * relative.width; float height = -rect.height * relative.height; relative = new Rect(x, y, width, height); // Draw the selection DrawOutline(relative); } } /// <summary> /// Draw a 9-sliced outline. /// </summary> static public void DrawOutline (Rect rect, Rect outer, Rect inner) { if (Event.current.type == EventType.Repaint) { Color green = new Color(0.4f, 1f, 0f, 1f); DrawOutline(rect, new Rect(outer.x, inner.y, outer.width, inner.height)); DrawOutline(rect, new Rect(inner.x, outer.y, inner.width, outer.height)); DrawOutline(rect, outer, green); } } /// <summary> /// Draw a checkered background for the specified texture. /// </summary> static public Rect DrawBackground (Texture2D tex, float ratio) { Rect rect = GUILayoutUtility.GetRect(0f, 0f); rect.width = Screen.width - rect.xMin; rect.height = rect.width * ratio; GUILayout.Space(rect.height); if (Event.current.type == EventType.Repaint) { Texture2D blank = blankTexture; Texture2D check = backdropTexture; // Lines above and below the texture rectangle GUI.color = new Color(0f, 0f, 0f, 0.2f); GUI.DrawTexture(new Rect(rect.xMin, rect.yMin - 1, rect.width, 1f), blank); GUI.DrawTexture(new Rect(rect.xMin, rect.yMax, rect.width, 1f), blank); GUI.color = Color.white; // Checker background DrawTiledTexture(rect, check); } return rect; } /// <summary> /// Draw a visible separator in addition to adding some padding. /// </summary> static public void DrawSeparator () { GUILayout.Space(12f); if (Event.current.type == EventType.Repaint) { Texture2D tex = blankTexture; Rect rect = GUILayoutUtility.GetLastRect(); GUI.color = new Color(0f, 0f, 0f, 0.25f); GUI.DrawTexture(new Rect(0f, rect.yMin + 6f, Screen.width, 4f), tex); GUI.DrawTexture(new Rect(0f, rect.yMin + 6f, Screen.width, 1f), tex); GUI.DrawTexture(new Rect(0f, rect.yMin + 9f, Screen.width, 1f), tex); GUI.color = Color.white; } } /// <summary> /// Convenience function that displays a list of sprites and returns the selected value. /// </summary> static public string DrawList (string field, string[] list, string selection, params GUILayoutOption[] options) { if (list != null && list.Length > 0) { int index = 0; if (string.IsNullOrEmpty(selection)) selection = list[0]; // We need to find the sprite in order to have it selected if (!string.IsNullOrEmpty(selection)) { for (int i = 0; i < list.Length; ++i) { if (selection.Equals(list[i], System.StringComparison.OrdinalIgnoreCase)) { index = i; break; } } } // Draw the sprite selection popup index = string.IsNullOrEmpty(field) ? EditorGUILayout.Popup(index, list, options) : EditorGUILayout.Popup(field, index, list, options); return list[index]; } return null; } /// <summary> /// Convenience function that displays a list of sprites and returns the selected value. /// </summary> static public string DrawAdvancedList (string field, string[] list, string selection, params GUILayoutOption[] options) { if (list != null && list.Length > 0) { int index = 0; if (string.IsNullOrEmpty(selection)) selection = list[0]; // We need to find the sprite in order to have it selected if (!string.IsNullOrEmpty(selection)) { for (int i = 0; i < list.Length; ++i) { if (selection.Equals(list[i], System.StringComparison.OrdinalIgnoreCase)) { index = i; break; } } } // Draw the sprite selection popup index = string.IsNullOrEmpty(field) ? DrawPrefixList(index, list, options) : DrawPrefixList(field, index, list, options); return list[index]; } return null; } /// <summary> /// Helper function that returns the selected root object. /// </summary> static public GameObject SelectedRoot () { return SelectedRoot(false); } /// <summary> /// Helper function that returns the selected root object. /// </summary> static public GameObject SelectedRoot (bool createIfMissing) { GameObject go = Selection.activeGameObject; // Only use active objects if (go != null && !NGUITools.GetActive(go)) go = null; // Try to find a panel UIPanel p = (go != null) ? NGUITools.FindInParents<UIPanel>(go) : null; // No selection? Try to find the root automatically if (p == null) { UIPanel[] panels = NGUITools.FindActive<UIPanel>(); if (panels.Length > 0) go = panels[0].gameObject; } if (createIfMissing && go == null) { // No object specified -- find the first panel if (go == null) { UIPanel panel = GameObject.FindObjectOfType(typeof(UIPanel)) as UIPanel; if (panel != null) go = panel.gameObject; } // No UI present -- create a new one if (go == null) go = UICreateNewUIWizard.CreateNewUI(UICreateNewUIWizard.CameraType.Simple2D); } return go; } /// <summary> /// Helper function that checks to see if this action would break the prefab connection. /// </summary> static public bool WillLosePrefab (GameObject root) { if (root == null) return false; if (root.transform != null) { // Check if the selected object is a prefab instance and display a warning PrefabType type = PrefabUtility.GetPrefabType(root); if (type == PrefabType.PrefabInstance) { return EditorUtility.DisplayDialog("Losing prefab", "This action will lose the prefab connection. Are you sure you wish to continue?", "Continue", "Cancel"); } } return true; } /// <summary> /// Change the import settings of the specified texture asset, making it readable. /// </summary> static public bool MakeTextureReadable (string path, bool force) { if (string.IsNullOrEmpty(path)) return false; TextureImporter ti = AssetImporter.GetAtPath(path) as TextureImporter; if (ti == null) return false; TextureImporterSettings settings = new TextureImporterSettings(); ti.ReadTextureSettings(settings); if (force || !settings.readable || settings.npotScale != TextureImporterNPOTScale.None #if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_1 || settings.alphaIsTransparency #endif ) { settings.readable = true; if (NGUISettings.trueColorAtlas) settings.textureFormat = TextureImporterFormat.ARGB32; settings.npotScale = TextureImporterNPOTScale.None; #if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_1 settings.alphaIsTransparency = false; #endif ti.SetTextureSettings(settings); AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate | ImportAssetOptions.ForceSynchronousImport); } return true; } /// <summary> /// Change the import settings of the specified texture asset, making it suitable to be used as a texture atlas. /// </summary> static bool MakeTextureAnAtlas (string path, bool force, bool alphaTransparency) { if (string.IsNullOrEmpty(path)) return false; TextureImporter ti = AssetImporter.GetAtPath(path) as TextureImporter; if (ti == null) return false; TextureImporterSettings settings = new TextureImporterSettings(); ti.ReadTextureSettings(settings); if (force || settings.readable || settings.maxTextureSize < 4096 || settings.wrapMode != TextureWrapMode.Clamp || settings.npotScale != TextureImporterNPOTScale.ToNearest) { settings.readable = false; settings.maxTextureSize = 4096; settings.wrapMode = TextureWrapMode.Clamp; settings.npotScale = TextureImporterNPOTScale.ToNearest; if (NGUISettings.trueColorAtlas) { settings.textureFormat = TextureImporterFormat.ARGB32; settings.filterMode = FilterMode.Trilinear; } settings.aniso = 4; settings.alphaIsTransparency = alphaTransparency; ti.SetTextureSettings(settings); AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate | ImportAssetOptions.ForceSynchronousImport); } return true; } /// <summary> /// Fix the import settings for the specified texture, re-importing it if necessary. /// </summary> static public Texture2D ImportTexture (string path, bool forInput, bool force, bool alphaTransparency) { if (!string.IsNullOrEmpty(path)) { if (forInput) { if (!MakeTextureReadable(path, force)) return null; } else if (!MakeTextureAnAtlas(path, force, alphaTransparency)) return null; //return AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D)) as Texture2D; Texture2D tex = AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D)) as Texture2D; AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport); return tex; } return null; } /// <summary> /// Fix the import settings for the specified texture, re-importing it if necessary. /// </summary> static public Texture2D ImportTexture (Texture tex, bool forInput, bool force, bool alphaTransparency) { if (tex != null) { string path = AssetDatabase.GetAssetPath(tex.GetInstanceID()); return ImportTexture(path, forInput, force, alphaTransparency); } return null; } /// <summary> /// Figures out the saveable filename for the texture of the specified atlas. /// </summary> static public string GetSaveableTexturePath (UIAtlas atlas) { // Path where the texture atlas will be saved string path = ""; // If the atlas already has a texture, overwrite its texture if (atlas.texture != null) { path = AssetDatabase.GetAssetPath(atlas.texture.GetInstanceID()); if (!string.IsNullOrEmpty(path)) { int dot = path.LastIndexOf('.'); return path.Substring(0, dot) + ".png"; } } // No texture to use -- figure out a name using the atlas path = AssetDatabase.GetAssetPath(atlas.GetInstanceID()); path = string.IsNullOrEmpty(path) ? "Assets/" + atlas.name + ".png" : path.Replace(".prefab", ".png"); return path; } /// <summary> /// Helper function that returns the folder where the current selection resides. /// </summary> static public string GetSelectionFolder () { if (Selection.activeObject != null) { string path = AssetDatabase.GetAssetPath(Selection.activeObject.GetInstanceID()); if (!string.IsNullOrEmpty(path)) { int dot = path.LastIndexOf('.'); int slash = Mathf.Max(path.LastIndexOf('/'), path.LastIndexOf('\\')); if (slash > 0) return (dot > slash) ? path.Substring(0, slash + 1) : path + "/"; } } return "Assets/"; } /// <summary> /// Struct type for the integer vector field below. /// </summary> public struct IntVector { public int x; public int y; } /// <summary> /// Integer vector field. /// </summary> static public IntVector IntPair (string prefix, string leftCaption, string rightCaption, int x, int y) { GUILayout.BeginHorizontal(); if (string.IsNullOrEmpty(prefix)) { GUILayout.Space(82f); } else { GUILayout.Label(prefix, GUILayout.Width(74f)); } NGUIEditorTools.SetLabelWidth(48f); IntVector retVal; retVal.x = EditorGUILayout.IntField(leftCaption, x, GUILayout.MinWidth(30f)); retVal.y = EditorGUILayout.IntField(rightCaption, y, GUILayout.MinWidth(30f)); NGUIEditorTools.SetLabelWidth(80f); GUILayout.EndHorizontal(); return retVal; } /// <summary> /// Integer rectangle field. /// </summary> static public Rect IntRect (string prefix, Rect rect) { int left = Mathf.RoundToInt(rect.xMin); int top = Mathf.RoundToInt(rect.yMin); int width = Mathf.RoundToInt(rect.width); int height = Mathf.RoundToInt(rect.height); NGUIEditorTools.IntVector a = NGUIEditorTools.IntPair(prefix, "Left", "Top", left, top); NGUIEditorTools.IntVector b = NGUIEditorTools.IntPair(null, "Width", "Height", width, height); return new Rect(a.x, a.y, b.x, b.y); } /// <summary> /// Integer vector field. /// </summary> static public Vector4 IntPadding (string prefix, Vector4 v) { int left = Mathf.RoundToInt(v.x); int top = Mathf.RoundToInt(v.y); int right = Mathf.RoundToInt(v.z); int bottom = Mathf.RoundToInt(v.w); NGUIEditorTools.IntVector a = NGUIEditorTools.IntPair(prefix, "Left", "Top", left, top); NGUIEditorTools.IntVector b = NGUIEditorTools.IntPair(null, "Right", "Bottom", right, bottom); return new Vector4(a.x, a.y, b.x, b.y); } /// <summary> /// Find all scene components, active or inactive. /// </summary> static public List<T> FindAll<T> () where T : Component { T[] comps = Resources.FindObjectsOfTypeAll(typeof(T)) as T[]; List<T> list = new List<T>(); foreach (T comp in comps) { if (comp.gameObject.hideFlags == 0) { string path = AssetDatabase.GetAssetPath(comp.gameObject); if (string.IsNullOrEmpty(path)) list.Add(comp); } } return list; } static public bool DrawPrefixButton (string text) { return GUILayout.Button(text, "DropDown", GUILayout.Width(76f)); } static public bool DrawPrefixButton (string text, params GUILayoutOption[] options) { return GUILayout.Button(text, "DropDown", options); } static public int DrawPrefixList (int index, string[] list, params GUILayoutOption[] options) { return EditorGUILayout.Popup(index, list, "DropDown", options); } static public int DrawPrefixList (string text, int index, string[] list, params GUILayoutOption[] options) { return EditorGUILayout.Popup(text, index, list, "DropDown", options); } /// <summary> /// Draw a sprite preview. /// </summary> static public void DrawSprite (Texture2D tex, Rect rect, UISpriteData sprite, Color color) { DrawSprite(tex, rect, sprite, color, null); } /// <summary> /// Draw a sprite preview. /// </summary> static public void DrawSprite (Texture2D tex, Rect drawRect, UISpriteData sprite, Color color, Material mat) { if (!tex || sprite == null) return; DrawSprite(tex, drawRect, color, mat, sprite.x, sprite.y, sprite.width, sprite.height, sprite.borderLeft, sprite.borderBottom, sprite.borderRight, sprite.borderTop); } /// <summary> /// Draw a sprite preview. /// </summary> static public void DrawSprite (Texture2D tex, Rect drawRect, Color color, Rect textureRect, Vector4 border) { NGUIEditorTools.DrawSprite(tex, drawRect, color, null, Mathf.RoundToInt(textureRect.x), Mathf.RoundToInt(tex.height - textureRect.y - textureRect.height), Mathf.RoundToInt(textureRect.width), Mathf.RoundToInt(textureRect.height), Mathf.RoundToInt(border.x), Mathf.RoundToInt(border.y), Mathf.RoundToInt(border.z), Mathf.RoundToInt(border.w)); } /// <summary> /// Draw a sprite preview. /// </summary> static public void DrawSprite (Texture2D tex, Rect drawRect, Color color, Material mat, int x, int y, int width, int height, int borderLeft, int borderBottom, int borderRight, int borderTop) { if (!tex) return; // Create the texture rectangle that is centered inside rect. Rect outerRect = drawRect; outerRect.width = width; outerRect.height = height; if (width > 0) { float f = drawRect.width / outerRect.width; outerRect.width *= f; outerRect.height *= f; } if (drawRect.height > outerRect.height) { outerRect.y += (drawRect.height - outerRect.height) * 0.5f; } else if (outerRect.height > drawRect.height) { float f = drawRect.height / outerRect.height; outerRect.width *= f; outerRect.height *= f; } if (drawRect.width > outerRect.width) outerRect.x += (drawRect.width - outerRect.width) * 0.5f; // Draw the background NGUIEditorTools.DrawTiledTexture(outerRect, NGUIEditorTools.backdropTexture); // Draw the sprite GUI.color = color; if (mat == null) { Rect uv = new Rect(x, y, width, height); uv = NGUIMath.ConvertToTexCoords(uv, tex.width, tex.height); GUI.DrawTextureWithTexCoords(outerRect, tex, uv, true); } else { // NOTE: There is an issue in Unity that prevents it from clipping the drawn preview // using BeginGroup/EndGroup, and there is no way to specify a UV rect... le'suq. UnityEditor.EditorGUI.DrawPreviewTexture(outerRect, tex, mat); } if (Selection.activeGameObject == null || Selection.gameObjects.Length == 1) { // Draw the border indicator lines GUI.BeginGroup(outerRect); { tex = NGUIEditorTools.contrastTexture; GUI.color = Color.white; if (borderLeft > 0) { float x0 = (float)borderLeft / width * outerRect.width - 1; NGUIEditorTools.DrawTiledTexture(new Rect(x0, 0f, 1f, outerRect.height), tex); } if (borderRight > 0) { float x1 = (float)(width - borderRight) / width * outerRect.width - 1; NGUIEditorTools.DrawTiledTexture(new Rect(x1, 0f, 1f, outerRect.height), tex); } if (borderBottom > 0) { float y0 = (float)(height - borderBottom) / height * outerRect.height - 1; NGUIEditorTools.DrawTiledTexture(new Rect(0f, y0, outerRect.width, 1f), tex); } if (borderTop > 0) { float y1 = (float)borderTop / height * outerRect.height - 1; NGUIEditorTools.DrawTiledTexture(new Rect(0f, y1, outerRect.width, 1f), tex); } } GUI.EndGroup(); // Draw the lines around the sprite Handles.color = Color.black; Handles.DrawLine(new Vector3(outerRect.xMin, outerRect.yMin), new Vector3(outerRect.xMin, outerRect.yMax)); Handles.DrawLine(new Vector3(outerRect.xMax, outerRect.yMin), new Vector3(outerRect.xMax, outerRect.yMax)); Handles.DrawLine(new Vector3(outerRect.xMin, outerRect.yMin), new Vector3(outerRect.xMax, outerRect.yMin)); Handles.DrawLine(new Vector3(outerRect.xMin, outerRect.yMax), new Vector3(outerRect.xMax, outerRect.yMax)); // Sprite size label string text = string.Format("Sprite Size: {0}x{1}", Mathf.RoundToInt(width), Mathf.RoundToInt(height)); EditorGUI.DropShadowLabel(GUILayoutUtility.GetRect(Screen.width, 18f), text); } } /// <summary> /// Draw the specified sprite. /// </summary> public static void DrawTexture (Texture2D tex, Rect rect, Rect uv, Color color) { DrawTexture(tex, rect, uv, color, null); } /// <summary> /// Draw the specified sprite. /// </summary> public static void DrawTexture (Texture2D tex, Rect rect, Rect uv, Color color, Material mat) { int w = Mathf.RoundToInt(tex.width * uv.width); int h = Mathf.RoundToInt(tex.height * uv.height); // Create the texture rectangle that is centered inside rect. Rect outerRect = rect; outerRect.width = w; outerRect.height = h; if (outerRect.width > 0f) { float f = rect.width / outerRect.width; outerRect.width *= f; outerRect.height *= f; } if (rect.height > outerRect.height) { outerRect.y += (rect.height - outerRect.height) * 0.5f; } else if (outerRect.height > rect.height) { float f = rect.height / outerRect.height; outerRect.width *= f; outerRect.height *= f; } if (rect.width > outerRect.width) outerRect.x += (rect.width - outerRect.width) * 0.5f; // Draw the background NGUIEditorTools.DrawTiledTexture(outerRect, NGUIEditorTools.backdropTexture); // Draw the sprite GUI.color = color; if (mat == null) { GUI.DrawTextureWithTexCoords(outerRect, tex, uv, true); } else { // NOTE: There is an issue in Unity that prevents it from clipping the drawn preview // using BeginGroup/EndGroup, and there is no way to specify a UV rect... le'suq. UnityEditor.EditorGUI.DrawPreviewTexture(outerRect, tex, mat); } GUI.color = Color.white; // Draw the lines around the sprite Handles.color = Color.black; Handles.DrawLine(new Vector3(outerRect.xMin, outerRect.yMin), new Vector3(outerRect.xMin, outerRect.yMax)); Handles.DrawLine(new Vector3(outerRect.xMax, outerRect.yMin), new Vector3(outerRect.xMax, outerRect.yMax)); Handles.DrawLine(new Vector3(outerRect.xMin, outerRect.yMin), new Vector3(outerRect.xMax, outerRect.yMin)); Handles.DrawLine(new Vector3(outerRect.xMin, outerRect.yMax), new Vector3(outerRect.xMax, outerRect.yMax)); // Sprite size label string text = string.Format("Texture Size: {0}x{1}", w, h); EditorGUI.DropShadowLabel(GUILayoutUtility.GetRect(Screen.width, 18f), text); } /// <summary> /// Draw a sprite selection field. /// </summary> static public void DrawSpriteField (string label, UIAtlas atlas, string spriteName, SpriteSelector.Callback callback, params GUILayoutOption[] options) { GUILayout.BeginHorizontal(); GUILayout.Label(label, GUILayout.Width(76f)); if (GUILayout.Button(spriteName, "MiniPullDown", options)) { NGUISettings.atlas = atlas; NGUISettings.selectedSprite = spriteName; SpriteSelector.Show(callback); } GUILayout.EndHorizontal(); } /// <summary> /// Draw a sprite selection field. /// </summary> static public void DrawPaddedSpriteField (string label, UIAtlas atlas, string spriteName, SpriteSelector.Callback callback, params GUILayoutOption[] options) { GUILayout.BeginHorizontal(); GUILayout.Label(label, GUILayout.Width(76f)); if (GUILayout.Button(spriteName, "MiniPullDown", options)) { NGUISettings.atlas = atlas; NGUISettings.selectedSprite = spriteName; SpriteSelector.Show(callback); } NGUIEditorTools.DrawPadding(); GUILayout.EndHorizontal(); } /// <summary> /// Draw a sprite selection field. /// </summary> static public void DrawSpriteField (string label, string caption, UIAtlas atlas, string spriteName, SpriteSelector.Callback callback, params GUILayoutOption[] options) { GUILayout.BeginHorizontal(); GUILayout.Label(label, GUILayout.Width(76f)); if (atlas.GetSprite(spriteName) == null) spriteName = ""; if (GUILayout.Button(spriteName, "MiniPullDown", options)) { NGUISettings.atlas = atlas; NGUISettings.selectedSprite = spriteName; SpriteSelector.Show(callback); } if (!string.IsNullOrEmpty(caption)) { GUILayout.Space(20f); GUILayout.Label(caption); } GUILayout.EndHorizontal(); } /// <summary> /// Draw a simple sprite selection button. /// </summary> static public bool DrawSpriteField (UIAtlas atlas, string spriteName, SpriteSelector.Callback callback, params GUILayoutOption[] options) { if (atlas.GetSprite(spriteName) == null) spriteName = ""; if (NGUIEditorTools.DrawPrefixButton(spriteName, options)) { NGUISettings.atlas = atlas; NGUISettings.selectedSprite = spriteName; SpriteSelector.Show(callback); return true; } return false; } static string mEditedName = null; static string mLastSprite = null; /// <summary> /// Draw a sprite selection field. /// </summary> static public void DrawSpriteField (string label, SerializedObject ob, string spriteField, params GUILayoutOption[] options) { DrawSpriteField(label, ob, ob.FindProperty("atlas"), ob.FindProperty(spriteField), 82f, false, false, options); } /// <summary> /// Draw a sprite selection field. /// </summary> static public void DrawSpriteField (string label, SerializedObject ob, SerializedProperty atlas, SerializedProperty sprite, params GUILayoutOption[] options) { DrawSpriteField(label, ob, atlas, sprite, 72f, false, false, options); } /// <summary> /// Draw a sprite selection field. /// </summary> static public void DrawSpriteField (string label, SerializedObject ob, SerializedProperty atlas, SerializedProperty sprite, bool removable, params GUILayoutOption[] options) { DrawSpriteField(label, ob, atlas, sprite, 72f, false, removable, options); } /// <summary> /// Draw a sprite selection field. /// </summary> static public void DrawSpriteField (string label, SerializedObject ob, SerializedProperty atlas, SerializedProperty sprite, float width, bool padded, bool removable, params GUILayoutOption[] options) { if (atlas != null && atlas.objectReferenceValue != null) { GUILayout.BeginHorizontal(); GUILayout.Label(label, GUILayout.Width(width)); if (sprite == null) { GUILayout.Label("Invalid field name"); } else { string spriteName = sprite.hasMultipleDifferentValues ? "-" : sprite.stringValue; GUILayout.BeginHorizontal(); EditorGUI.BeginDisabledGroup(atlas.hasMultipleDifferentValues); { if (GUILayout.Button(spriteName, "MiniPullDown", options)) SpriteSelector.Show(ob, sprite, atlas.objectReferenceValue as UIAtlas); } EditorGUI.EndDisabledGroup(); EditorGUI.BeginDisabledGroup(!removable); if (GUILayout.Button("", "ToggleMixed", GUILayout.Width(20f))) sprite.stringValue = ""; EditorGUI.EndDisabledGroup(); if (padded) GUILayout.Space(12f); else GUILayout.Space(-6f); GUILayout.EndHorizontal(); } GUILayout.EndHorizontal(); } } /// <summary> /// Convenience function that displays a list of sprites and returns the selected value. /// </summary> static public void DrawAdvancedSpriteField (UIAtlas atlas, string spriteName, SpriteSelector.Callback callback, bool editable, params GUILayoutOption[] options) { if (atlas == null) return; // Give the user a warning if there are no sprites in the atlas if (atlas.spriteList.Count == 0) { EditorGUILayout.HelpBox("No sprites found", MessageType.Warning); return; } // Sprite selection drop-down list GUILayout.BeginHorizontal(); { if (NGUIEditorTools.DrawPrefixButton("Sprite")) { NGUISettings.atlas = atlas; NGUISettings.selectedSprite = spriteName; SpriteSelector.Show(callback); } if (editable) { if (!string.Equals(spriteName, mLastSprite)) { mLastSprite = spriteName; mEditedName = null; } string newName = GUILayout.TextField(string.IsNullOrEmpty(mEditedName) ? spriteName : mEditedName); if (newName != spriteName) { mEditedName = newName; if (GUILayout.Button("Rename", GUILayout.Width(60f))) { UISpriteData sprite = atlas.GetSprite(spriteName); if (sprite != null) { NGUIEditorTools.RegisterUndo("Edit Sprite Name", atlas); sprite.name = newName; List<UISprite> sprites = FindAll<UISprite>(); for (int i = 0; i < sprites.Count; ++i) { UISprite sp = sprites[i]; if (sp.atlas == atlas && sp.spriteName == spriteName) { NGUIEditorTools.RegisterUndo("Edit Sprite Name", sp); sp.spriteName = newName; } } mLastSprite = newName; spriteName = newName; mEditedName = null; NGUISettings.atlas = atlas; NGUISettings.selectedSprite = spriteName; } } } } else { GUILayout.BeginHorizontal(); GUILayout.Label(spriteName, "HelpBox", GUILayout.Height(18f)); NGUIEditorTools.DrawPadding(); GUILayout.EndHorizontal(); if (GUILayout.Button("Edit", GUILayout.Width(40f))) { NGUISettings.atlas = atlas; NGUISettings.selectedSprite = spriteName; Select(atlas.gameObject); } } } GUILayout.EndHorizontal(); } /// <summary> /// Repaints all inspector windows related to sprite drawing. /// </summary> static public void RepaintSprites () { if (UIAtlasInspector.instance != null) UIAtlasInspector.instance.Repaint(); if (UIAtlasMaker.instance != null) UIAtlasMaker.instance.Repaint(); if (SpriteSelector.instance != null) SpriteSelector.instance.Repaint(); } /// <summary> /// Select the specified sprite within the currently selected atlas. /// </summary> static public void SelectSprite (string spriteName) { if (NGUISettings.atlas != null) { NGUISettings.selectedSprite = spriteName; NGUIEditorTools.Select(NGUISettings.atlas.gameObject); RepaintSprites(); } } /// <summary> /// Select the specified atlas and sprite. /// </summary> static public void SelectSprite (UIAtlas atlas, string spriteName) { if (atlas != null) { NGUISettings.atlas = atlas; NGUISettings.selectedSprite = spriteName; NGUIEditorTools.Select(atlas.gameObject); RepaintSprites(); } } /// <summary> /// Select the specified game object and remember what was selected before. /// </summary> static public void Select (GameObject go) { mPrevious = Selection.activeGameObject; Selection.activeGameObject = go; } /// <summary> /// Select the previous game object. /// </summary> static public void SelectPrevious () { if (mPrevious != null) { Selection.activeGameObject = mPrevious; mPrevious = null; } } /// <summary> /// Previously selected game object. /// </summary> static public GameObject previousSelection { get { return mPrevious; } } /// <summary> /// Helper function that checks to see if the scale is uniform. /// </summary> static public bool IsUniform (Vector3 scale) { return Mathf.Approximately(scale.x, scale.y) && Mathf.Approximately(scale.x, scale.z); } /// <summary> /// Check to see if the specified game object has a uniform scale. /// </summary> static public bool IsUniform (GameObject go) { if (go == null) return true; if (go.GetComponent<UIWidget>() != null) { Transform parent = go.transform.parent; return parent == null || IsUniform(parent.gameObject); } return IsUniform(go.transform.lossyScale); } /// <summary> /// Fix uniform scaling of the specified object. /// </summary> static public void FixUniform (GameObject go) { Transform t = go.transform; while (t != null && t.gameObject.GetComponent<UIRoot>() == null) { if (!NGUIEditorTools.IsUniform(t.localScale)) { NGUIEditorTools.RegisterUndo("Uniform scaling fix", t); t.localScale = Vector3.one; EditorUtility.SetDirty(t); } t = t.parent; } } /// <summary> /// Draw a distinctly different looking header label /// </summary> static public bool DrawMinimalisticHeader (string text) { return DrawHeader(text, text, false, true); } /// <summary> /// Draw a distinctly different looking header label /// </summary> static public bool DrawHeader (string text) { return DrawHeader(text, text, false, NGUISettings.minimalisticLook); } /// <summary> /// Draw a distinctly different looking header label /// </summary> static public bool DrawHeader (string text, string key) { return DrawHeader(text, key, false, NGUISettings.minimalisticLook); } /// <summary> /// Draw a distinctly different looking header label /// </summary> static public bool DrawHeader (string text, bool detailed) { return DrawHeader(text, text, detailed, !detailed); } /// <summary> /// Draw a distinctly different looking header label /// </summary> static public bool DrawHeader (string text, string key, bool forceOn, bool minimalistic) { bool state = EditorPrefs.GetBool(key, true); if (!minimalistic) GUILayout.Space(3f); if (!forceOn && !state) GUI.backgroundColor = new Color(0.8f, 0.8f, 0.8f); GUILayout.BeginHorizontal(); GUI.changed = false; if (minimalistic) { if (state) text = "\u25BC" + (char)0x200a + text; else text = "\u25BA" + (char)0x200a + text; GUILayout.BeginHorizontal(); GUI.contentColor = EditorGUIUtility.isProSkin ? new Color(1f, 1f, 1f, 0.7f) : new Color(0f, 0f, 0f, 0.7f); if (!GUILayout.Toggle(true, text, "PreToolbar2", GUILayout.MinWidth(20f))) state = !state; GUI.contentColor = Color.white; GUILayout.EndHorizontal(); } else { text = "<b><size=11>" + text + "</size></b>"; if (state) text = "\u25BC " + text; else text = "\u25BA " + text; if (!GUILayout.Toggle(true, text, "dragtab", GUILayout.MinWidth(20f))) state = !state; } if (GUI.changed) EditorPrefs.SetBool(key, state); if (!minimalistic) GUILayout.Space(2f); GUILayout.EndHorizontal(); GUI.backgroundColor = Color.white; if (!forceOn && !state) GUILayout.Space(3f); return state; } /// <summary> /// Begin drawing the content area. /// </summary> static public void BeginContents () { BeginContents(NGUISettings.minimalisticLook); } static bool mEndHorizontal = false; /// <summary> /// Begin drawing the content area. /// </summary> static public void BeginContents (bool minimalistic) { if (!minimalistic) { mEndHorizontal = true; GUILayout.BeginHorizontal(); EditorGUILayout.BeginHorizontal("AS TextArea", GUILayout.MinHeight(10f)); } else { mEndHorizontal = false; EditorGUILayout.BeginHorizontal(GUILayout.MinHeight(10f)); GUILayout.Space(10f); } GUILayout.BeginVertical(); GUILayout.Space(2f); } /// <summary> /// End drawing the content area. /// </summary> static public void EndContents () { GUILayout.Space(3f); GUILayout.EndVertical(); EditorGUILayout.EndHorizontal(); if (mEndHorizontal) { GUILayout.Space(3f); GUILayout.EndHorizontal(); } GUILayout.Space(3f); } /// <summary> /// Draw a list of fields for the specified list of delegates. /// </summary> static public void DrawEvents (string text, Object undoObject, List<EventDelegate> list) { DrawEvents(text, undoObject, list, null, null, false); } /// <summary> /// Draw a list of fields for the specified list of delegates. /// </summary> static public void DrawEvents (string text, Object undoObject, List<EventDelegate> list, bool minimalistic) { DrawEvents(text, undoObject, list, null, null, minimalistic); } /// <summary> /// Draw a list of fields for the specified list of delegates. /// </summary> static public void DrawEvents (string text, Object undoObject, List<EventDelegate> list, string noTarget, string notValid, bool minimalistic) { if (!NGUIEditorTools.DrawHeader(text, text, false, minimalistic)) return; if (!minimalistic) { NGUIEditorTools.BeginContents(minimalistic); GUILayout.BeginHorizontal(); GUILayout.BeginVertical(); EventDelegateEditor.Field(undoObject, list, notValid, notValid, minimalistic); GUILayout.EndVertical(); GUILayout.EndHorizontal(); NGUIEditorTools.EndContents(); } else EventDelegateEditor.Field(undoObject, list, notValid, notValid, minimalistic); } /// <summary> /// Helper function that draws a serialized property. /// </summary> static public SerializedProperty DrawProperty (SerializedObject serializedObject, string property, params GUILayoutOption[] options) { return DrawProperty(null, serializedObject, property, false, options); } /// <summary> /// Helper function that draws a serialized property. /// </summary> static public SerializedProperty DrawProperty (string label, SerializedObject serializedObject, string property, params GUILayoutOption[] options) { return DrawProperty(label, serializedObject, property, false, options); } /// <summary> /// Helper function that draws a serialized property. /// </summary> static public SerializedProperty DrawPaddedProperty (SerializedObject serializedObject, string property, params GUILayoutOption[] options) { return DrawProperty(null, serializedObject, property, true, options); } /// <summary> /// Helper function that draws a serialized property. /// </summary> static public SerializedProperty DrawPaddedProperty (string label, SerializedObject serializedObject, string property, params GUILayoutOption[] options) { return DrawProperty(label, serializedObject, property, true, options); } /// <summary> /// Helper function that draws a serialized property. /// </summary> static public SerializedProperty DrawProperty (string label, SerializedObject serializedObject, string property, bool padding, params GUILayoutOption[] options) { SerializedProperty sp = serializedObject.FindProperty(property); if (sp != null) { if (NGUISettings.minimalisticLook) padding = false; if (padding) EditorGUILayout.BeginHorizontal(); if (label != null) EditorGUILayout.PropertyField(sp, new GUIContent(label), options); else EditorGUILayout.PropertyField(sp, options); if (padding) { NGUIEditorTools.DrawPadding(); EditorGUILayout.EndHorizontal(); } } return sp; } /// <summary> /// Helper function that draws a serialized property. /// </summary> static public void DrawProperty (string label, SerializedProperty sp, params GUILayoutOption[] options) { DrawProperty(label, sp, true, options); } /// <summary> /// Helper function that draws a serialized property. /// </summary> static public void DrawProperty (string label, SerializedProperty sp, bool padding, params GUILayoutOption[] options) { if (sp != null) { if (padding) EditorGUILayout.BeginHorizontal(); if (label != null) EditorGUILayout.PropertyField(sp, new GUIContent(label), options); else EditorGUILayout.PropertyField(sp, options); if (padding) { NGUIEditorTools.DrawPadding(); EditorGUILayout.EndHorizontal(); } } } /// <summary> /// Helper function that draws a compact Vector4. /// </summary> static public void DrawBorderProperty (string name, SerializedObject serializedObject, string field) { if (serializedObject.FindProperty(field) != null) { GUILayout.BeginHorizontal(); { GUILayout.Label(name, GUILayout.Width(75f)); NGUIEditorTools.SetLabelWidth(50f); GUILayout.BeginVertical(); NGUIEditorTools.DrawProperty("Left", serializedObject, field + ".x", GUILayout.MinWidth(80f)); NGUIEditorTools.DrawProperty("Bottom", serializedObject, field + ".y", GUILayout.MinWidth(80f)); GUILayout.EndVertical(); GUILayout.BeginVertical(); NGUIEditorTools.DrawProperty("Right", serializedObject, field + ".z", GUILayout.MinWidth(80f)); NGUIEditorTools.DrawProperty("Top", serializedObject, field + ".w", GUILayout.MinWidth(80f)); GUILayout.EndVertical(); NGUIEditorTools.SetLabelWidth(80f); } GUILayout.EndHorizontal(); } } /// <summary> /// Helper function that draws a compact Rect. /// </summary> static public void DrawRectProperty (string name, SerializedObject serializedObject, string field) { DrawRectProperty(name, serializedObject, field, 56f, 18f); } /// <summary> /// Helper function that draws a compact Rect. /// </summary> static public void DrawRectProperty (string name, SerializedObject serializedObject, string field, float labelWidth, float spacing) { if (serializedObject.FindProperty(field) != null) { GUILayout.BeginHorizontal(); { GUILayout.Label(name, GUILayout.Width(labelWidth)); NGUIEditorTools.SetLabelWidth(20f); GUILayout.BeginVertical(); NGUIEditorTools.DrawProperty("X", serializedObject, field + ".x", GUILayout.MinWidth(50f)); NGUIEditorTools.DrawProperty("Y", serializedObject, field + ".y", GUILayout.MinWidth(50f)); GUILayout.EndVertical(); NGUIEditorTools.SetLabelWidth(50f); GUILayout.BeginVertical(); NGUIEditorTools.DrawProperty("Width", serializedObject, field + ".width", GUILayout.MinWidth(80f)); NGUIEditorTools.DrawProperty("Height", serializedObject, field + ".height", GUILayout.MinWidth(80f)); GUILayout.EndVertical(); NGUIEditorTools.SetLabelWidth(80f); if (spacing != 0f) GUILayout.Space(spacing); } GUILayout.EndHorizontal(); } } /// <summary> /// Determine the distance from the mouse position to the world rectangle specified by the 4 points. /// </summary> static public float SceneViewDistanceToRectangle (Vector3[] worldPoints, Vector2 mousePos) { Vector2[] screenPoints = new Vector2[4]; for (int i = 0; i < 4; ++i) screenPoints[i] = HandleUtility.WorldToGUIPoint(worldPoints[i]); return NGUIMath.DistanceToRectangle(screenPoints, mousePos); } /// <summary> /// Raycast into the specified panel, returning a list of widgets. /// Just like NGUIMath.Raycast, but doesn't rely on having a camera. /// </summary> static public BetterList<UIWidget> SceneViewRaycast (Vector2 mousePos) { BetterList<UIWidget> list = new BetterList<UIWidget>(); for (int i = 0; i < UIPanel.list.size; ++i) { UIPanel p = UIPanel.list.buffer[i]; for (int b = 0; b < p.widgets.size; ++b) { UIWidget w = p.widgets.buffer[b]; Vector3[] corners = w.worldCorners; if (SceneViewDistanceToRectangle(corners, mousePos) == 0f) list.Add(w); } } list.Sort(UIWidget.FullCompareFunc); return list; } /// <summary> /// Select the topmost widget underneath the specified screen coordinate. /// </summary> static public bool SelectWidget (Vector2 pos) { return SelectWidget(null, pos, true); } /// <summary> /// Select the next widget in line. /// </summary> static public bool SelectWidget (GameObject start, Vector2 pos, bool inFront) { GameObject go = null; BetterList<UIWidget> widgets = SceneViewRaycast(pos); if (widgets == null || widgets.size == 0) return false; bool found = false; if (!inFront) { if (start != null) { for (int i = 0; i < widgets.size; ++i) { UIWidget w = widgets[i]; if (w.cachedGameObject == start) { found = true; break; } go = w.cachedGameObject; } } if (!found) go = widgets[0].cachedGameObject; } else { if (start != null) { for (int i = widgets.size; i > 0; ) { UIWidget w = widgets[--i]; if (w.cachedGameObject == start) { found = true; break; } go = w.cachedGameObject; } } if (!found) go = widgets[widgets.size - 1].cachedGameObject; } if (go != null && go != start) { Selection.activeGameObject = go; return true; } return false; } /// <summary> /// Unity 4.3 changed the way LookLikeControls works. /// </summary> static public void SetLabelWidth (float width) { EditorGUIUtility.labelWidth = width; } /// <summary> /// Create an undo point for the specified objects. /// </summary> static public void RegisterUndo (string name, params Object[] objects) { if (objects != null && objects.Length > 0) { UnityEditor.Undo.RecordObjects(objects, name); foreach (Object obj in objects) { if (obj == null) continue; EditorUtility.SetDirty(obj); } } } /// <summary> /// Unity 4.5+ makes it possible to hide the move tool. /// </summary> static public void HideMoveTool (bool hide) { #if !UNITY_4_3 UnityEditor.Tools.hidden = hide && (UnityEditor.Tools.current == UnityEditor.Tool.Move) && UIWidget.showHandlesWithMoveTool && !NGUISettings.showTransformHandles; #endif } /// <summary> /// Gets the internal class ID of the specified type. /// </summary> static public int GetClassID (System.Type type) { GameObject go = EditorUtility.CreateGameObjectWithHideFlags("Temp", HideFlags.HideAndDontSave); Component uiSprite = go.AddComponent(type); SerializedObject ob = new SerializedObject(uiSprite); int classID = ob.FindProperty("m_Script").objectReferenceInstanceIDValue; NGUITools.DestroyImmediate(go); return classID; } /// <summary> /// Gets the internal class ID of the specified type. /// </summary> static public int GetClassID<T> () where T : MonoBehaviour { return GetClassID(typeof(T)); } /// <summary> /// Convenience function that replaces the specified MonoBehaviour with one of specified type. /// </summary> static public SerializedObject ReplaceClass (MonoBehaviour mb, System.Type type) { int id = GetClassID(type); SerializedObject ob = new SerializedObject(mb); ob.Update(); ob.FindProperty("m_Script").objectReferenceInstanceIDValue = id; ob.ApplyModifiedProperties(); ob.Update(); return ob; } /// <summary> /// Convenience function that replaces the specified MonoBehaviour with one of specified class ID. /// </summary> static public SerializedObject ReplaceClass (MonoBehaviour mb, int classID) { SerializedObject ob = new SerializedObject(mb); ob.Update(); ob.FindProperty("m_Script").objectReferenceInstanceIDValue = classID; ob.ApplyModifiedProperties(); ob.Update(); return ob; } /// <summary> /// Convenience function that replaces the specified MonoBehaviour with one of specified class ID. /// </summary> static public void ReplaceClass (SerializedObject ob, int classID) { ob.FindProperty("m_Script").objectReferenceInstanceIDValue = classID; ob.ApplyModifiedProperties(); ob.Update(); } /// <summary> /// Convenience function that replaces the specified MonoBehaviour with one of specified class ID. /// </summary> static public void ReplaceClass (SerializedObject ob, System.Type type) { ob.FindProperty("m_Script").objectReferenceInstanceIDValue = GetClassID(type); ob.ApplyModifiedProperties(); ob.Update(); } /// <summary> /// Convenience function that replaces the specified MonoBehaviour with one of specified type. /// </summary> static public T ReplaceClass<T> (MonoBehaviour mb) where T : MonoBehaviour { return ReplaceClass(mb, typeof(T)).targetObject as T; } /// <summary> /// Automatically upgrade all of the UITextures in the scene to Sprites if they can be found within the specified atlas. /// </summary> static public void UpgradeTexturesToSprites (UIAtlas atlas) { if (atlas == null) return; List<UITexture> uits = FindAll<UITexture>(); if (uits.Count > 0) { UIWidget selectedTex = (UIWidgetInspector.instance != null && UIWidgetInspector.instance.target != null) ? UIWidgetInspector.instance.target as UITexture : null; // Determine the object instance ID of the UISprite class int spriteID = GetClassID<UISprite>(); // Run through all the UI textures and change them to sprites for (int i = 0; i < uits.Count; ++i) { UIWidget uiTexture = uits[i]; if (uiTexture != null && uiTexture.mainTexture != null) { UISpriteData atlasSprite = atlas.GetSprite(uiTexture.mainTexture.name); if (atlasSprite != null) { SerializedObject ob = ReplaceClass(uiTexture, spriteID); ob.FindProperty("mSpriteName").stringValue = uiTexture.mainTexture.name; ob.FindProperty("mAtlas").objectReferenceValue = NGUISettings.atlas; ob.ApplyModifiedProperties(); } } } if (selectedTex != null) { // Repaint() doesn't work in this case because Unity doesn't realize that the underlying // script type has changed and that a new editor script needs to be chosen. //UIWidgetInspector.instance.Repaint(); Selection.activeGameObject = null; } } } class MenuEntry { public string name; public GameObject go; public MenuEntry (string name, GameObject go) { this.name = name; this.go = go; } } /// <summary> /// Show a sprite selection context menu listing all sprites under the specified screen position. /// </summary> static public void ShowSpriteSelectionMenu (Vector2 screenPos) { BetterList<UIWidget> widgets = NGUIEditorTools.SceneViewRaycast(screenPos); BetterList<UIWidgetContainer> containers = new BetterList<UIWidgetContainer>(); BetterList<MenuEntry> entries = new BetterList<MenuEntry>(); BetterList<UIPanel> panels = new BetterList<UIPanel>(); bool divider = false; UIWidget topWidget = null; UIPanel topPanel = null; // Process widgets and their containers in the raycast order for (int i = 0; i < widgets.size; ++i) { UIWidget w = widgets[i]; if (topWidget == null) topWidget = w; UIPanel panel = w.panel; if (topPanel == null) topPanel = panel; if (panel != null && !panels.Contains(panel)) { panels.Add(panel); if (!divider) { entries.Add(null); divider = true; } entries.Add(new MenuEntry(panel.name + " (panel)", panel.gameObject)); } UIWidgetContainer wc = NGUITools.FindInParents<UIWidgetContainer>(w.cachedGameObject); // If we get a new container, we should add it to the list if (wc != null && !containers.Contains(wc)) { containers.Add(wc); // Only proceed if there is no widget on the container if (wc.gameObject != w.cachedGameObject) { if (!divider) { entries.Add(null); divider = true; } entries.Add(new MenuEntry(wc.name + " (container)", wc.gameObject)); } } string name = (i + 1 == widgets.size) ? (w.name + " (top-most)") : w.name; entries.Add(new MenuEntry(name, w.gameObject)); divider = false; } // Common items used by NGUI NGUIContextMenu.AddCommonItems(Selection.activeGameObject); // Add widgets to the menu in the reverse order so that they are shown with the top-most widget first (on top) for (int i = entries.size; i > 0; ) { MenuEntry ent = entries[--i]; if (ent != null) { NGUIContextMenu.AddItem("Select/" + ent.name, Selection.activeGameObject == ent.go, delegate(object go) { Selection.activeGameObject = (GameObject)go; }, ent.go); } else if (!divider) { NGUIContextMenu.AddSeparator("Select/"); } } NGUIContextMenu.AddHelp(Selection.activeGameObject, true); NGUIContextMenu.Show(); } /// <summary> /// Load the asset at the specified path. /// </summary> static public Object LoadAsset (string path) { if (string.IsNullOrEmpty(path)) return null; return AssetDatabase.LoadMainAssetAtPath(path); } /// <summary> /// Convenience function to load an asset of specified type, given the full path to it. /// </summary> static public T LoadAsset<T> (string path) where T: Object { Object obj = LoadAsset(path); if (obj == null) return null; T val = obj as T; if (val != null) return val; if (typeof(T).IsSubclassOf(typeof(Component))) { if (obj.GetType() == typeof(GameObject)) { GameObject go = obj as GameObject; return go.GetComponent(typeof(T)) as T; } } return null; } /// <summary> /// Get the specified object's GUID. /// </summary> static public string ObjectToGUID (Object obj) { string path = AssetDatabase.GetAssetPath(obj); return (!string.IsNullOrEmpty(path)) ? AssetDatabase.AssetPathToGUID(path) : null; } static MethodInfo s_GetInstanceIDFromGUID; /// <summary> /// Convert the specified GUID to an object reference. /// </summary> static public Object GUIDToObject (string guid) { if (string.IsNullOrEmpty(guid)) return null; if (s_GetInstanceIDFromGUID == null) s_GetInstanceIDFromGUID = typeof(AssetDatabase).GetMethod("GetInstanceIDFromGUID", BindingFlags.Static | BindingFlags.NonPublic); int id = (int)s_GetInstanceIDFromGUID.Invoke(null, new object[] { guid }); if (id != 0) return EditorUtility.InstanceIDToObject(id); string path = AssetDatabase.GUIDToAssetPath(guid); if (string.IsNullOrEmpty(path)) return null; return AssetDatabase.LoadAssetAtPath(path, typeof(Object)); } /// <summary> /// Convert the specified GUID to an object reference of specified type. /// </summary> static public T GUIDToObject<T> (string guid) where T : Object { Object obj = GUIDToObject(guid); if (obj == null) return null; System.Type objType = obj.GetType(); if (objType == typeof(T) || objType.IsSubclassOf(typeof(T))) return obj as T; if (objType == typeof(GameObject) && typeof(T).IsSubclassOf(typeof(Component))) { GameObject go = obj as GameObject; return go.GetComponent(typeof(T)) as T; } return null; } /// <summary> /// Add a border around the specified color buffer with the width and height of a single pixel all around. /// The returned color buffer will have its width and height increased by 2. /// </summary> static public Color32[] AddBorder (Color32[] colors, int width, int height) { int w2 = width + 2; int h2 = height + 2; Color32[] c2 = new Color32[w2 * h2]; for (int y2 = 0; y2 < h2; ++y2) { int y1 = NGUIMath.ClampIndex(y2 - 1, height); for (int x2 = 0; x2 < w2; ++x2) { int x1 = NGUIMath.ClampIndex(x2 - 1, width); int i2 = x2 + y2 * w2; c2[i2] = colors[x1 + y1 * width]; if (x2 == 0 || x2 + 1 == w2 || y2 == 0 || y2 + 1 == h2) c2[i2].a = 0; } } return c2; } /// <summary> /// Add a soft shadow to the specified color buffer. /// The buffer must have some padding around the edges in order for this to work properly. /// </summary> static public void AddShadow (Color32[] colors, int width, int height, Color shadow) { Color sh = shadow; sh.a = 1f; for (int y2 = 0; y2 < height; ++y2) { for (int x2 = 0; x2 < width; ++x2) { int index = x2 + y2 * width; Color32 uc = colors[index]; if (uc.a == 255) continue; Color original = uc; float val = original.a; int count = 1; float div1 = 1f / 255f; float div2 = 2f / 255f; float div3 = 3f / 255f; // Left if (x2 != 0) { val += colors[x2 - 1 + y2 * width].a * div1; count += 1; } // Top if (y2 + 1 != height) { val += colors[x2 + (y2 + 1) * width].a * div2; count += 2; } // Top-left if (x2 != 0 && y2 + 1 != height) { val += colors[x2 - 1 + (y2 + 1) * width].a * div3; count += 3; } val /= count; Color c = Color.Lerp(original, sh, shadow.a * val); colors[index] = Color.Lerp(c, original, original.a); } } } /// <summary> /// Add a visual depth effect to the specified color buffer. /// The buffer must have some padding around the edges in order for this to work properly. /// </summary> static public void AddDepth (Color32[] colors, int width, int height, Color shadow) { Color sh = shadow; sh.a = 1f; for (int y2 = 0; y2 < height; ++y2) { for (int x2 = 0; x2 < width; ++x2) { int index = x2 + y2 * width; Color32 uc = colors[index]; if (uc.a == 255) continue; Color original = uc; float val = original.a * 4f; int count = 4; float div1 = 1f / 255f; float div2 = 2f / 255f; if (x2 != 0) { val += colors[x2 - 1 + y2 * width].a * div2; count += 2; } if (x2 + 1 != width) { val += colors[x2 + 1 + y2 * width].a * div2; count += 2; } if (y2 != 0) { val += colors[x2 + (y2 - 1) * width].a * div2; count += 2; } if (y2 + 1 != height) { val += colors[x2 + (y2 + 1) * width].a * div2; count += 2; } if (x2 != 0 && y2 != 0) { val += colors[x2 - 1 + (y2 - 1) * width].a * div1; ++count; } if (x2 != 0 && y2 + 1 != height) { val += colors[x2 - 1 + (y2 + 1) * width].a * div1; ++count; } if (x2 + 1 != width && y2 != 0) { val += colors[x2 + 1 + (y2 - 1) * width].a * div1; ++count; } if (x2 + 1 != width && y2 + 1 != height) { val += colors[x2 + 1 + (y2 + 1) * width].a * div1; ++count; } val /= count; Color c = Color.Lerp(original, sh, shadow.a * val); colors[index] = Color.Lerp(c, original, original.a); } } } /// <summary> /// Draw 18 pixel padding on the right-hand side. Used to align fields. /// </summary> static public void DrawPadding () { if (!NGUISettings.minimalisticLook) GUILayout.Space(18f); } }
mit
FranckW/projet1_opl
server/lib/slf4j-1.7.21/integration/src/test/java/org/slf4j/MissingSingletonMethodAssertionTest.java
3022
/** * Copyright (c) 2004-2016 QOS.ch * All rights reserved. * * 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.slf4j; import java.io.PrintStream; import java.util.Random; import junit.framework.TestCase; public class MissingSingletonMethodAssertionTest extends TestCase { StringPrintStream sps = new StringPrintStream(System.err); PrintStream old = System.err; int diff = 1024 + new Random().nextInt(10000); public MissingSingletonMethodAssertionTest(String name) { super(name); } protected void setUp() throws Exception { super.setUp(); System.setErr(sps); } protected void tearDown() throws Exception { super.tearDown(); System.setErr(old); } public void test() throws Exception { try { Logger logger = LoggerFactory.getLogger(this.getClass()); String msg = "hello world " + diff; logger.info(msg); fail("NoSuchMethodError expected"); } catch (NoSuchMethodError e) { } int lineCount = sps.stringList.size(); assertTrue("number of lines should be 3 but was " + lineCount, lineCount == 3); // expected output: // SLF4J: slf4j-api 1.6.x (or later) is incompatible with this binding. // SLF4J: Your binding is version 1.4.x or earlier. // SLF4J: Upgrade your binding to version 1.6.x. or 2.0.x { String s = (String) sps.stringList.get(0); assertTrue(s.contains("SLF4J: slf4j-api 1.6.x (or later) is incompatible with this binding.")); } { String s = (String) sps.stringList.get(1); assertTrue(s.contains("SLF4J: Your binding is version 1.5.5 or earlier.")); } { String s = (String) sps.stringList.get(2); assertTrue(s.contains("SLF4J: Upgrade your binding to version 1.6.x.")); } } }
mit
kwhinnery/twilio-parse
cloud/twilio/resources/IncomingPhoneNumbers.js
1066
/** @module resources/AvailablePhoneNumbers The Twilio "AvailablePhoneNumbers" Resource. */ var generate = require('cloud/twilio/resources/generate'), ListInstanceResource = require('cloud/twilio/resources/ListInstanceResource'); module.exports = function (client, accountSid) { var IncomingPhoneNumbers = ListInstanceResource(client, accountSid, 'IncomingPhoneNumbers', ['GET', 'POST', 'PUT', 'DELETE', { update:'PUT' }], ['GET', 'POST', { create:'POST' }] ); //Add local and toll-free subresources IncomingPhoneNumbers.local = {}; generate.restFunctions(IncomingPhoneNumbers.local, client, ['GET', 'POST'], IncomingPhoneNumbers.baseResourceUrl+'/Local'); IncomingPhoneNumbers.local.create = IncomingPhoneNumbers.local.post; IncomingPhoneNumbers.tollFree = {}; generate.restFunctions(IncomingPhoneNumbers.tollFree, client, ['GET', 'POST'], IncomingPhoneNumbers.baseResourceUrl+'/TollFree'); IncomingPhoneNumbers.tollFree.create = IncomingPhoneNumbers.tollFree.post; return IncomingPhoneNumbers; };
mit
bristweb/wp-plugins-submodule
scripts-n-styles/js/settings-page.js
538
// Options JavaScript jQuery( document ).ready( function( $ ) { var theme = codemirror_options.theme ? codemirror_options.theme: 'default'; var editor = CodeMirror.fromTextArea(document.getElementById("codemirror_demo"), { lineNumbers: true, matchBrackets: true, mode: "application/x-httpd-php", indentUnit: 4, indentWithTabs: true, enterMode: "keep", tabMode: "shift", theme: theme }); $('input[name="SnS_options[cm_theme]"]').change( function(){ editor.setOption("theme", $(this).val()); }); });
mit
gilyclem/larVolumeToObj
larVolumeToObjG/computation/step_mergemesh.py
2767
import time as tm import gc import getopt, sys import os import traceback import glob # ------------------------------------------------------------ # Logging & Timer # ------------------------------------------------------------ logging_level = 1; # 0 = no_logging # 1 = few details # 2 = many details # 3 = many many details def log(n, l): if __name__=="__main__" and n <= logging_level: for s in l: print "Log:", s; timer = 1; timer_last = tm.time() def timer_start(s): global timer_last; if __name__=="__main__" and timer == 1: log(3, ["Timer start:" + s]); timer_last = tm.time(); def timer_stop(): global timer_last; if __name__=="__main__" and timer == 1: log(3, ["Timer stop :" + str(tm.time() - timer_last)]); # ------------------------------------------------------------ # ------------------------------------------------------------ def mergeFiles(listFile, outDir): with file(outDir+'/mergedMesh-Vtx.lst', 'w') as outVtxFile: with file(outDir+'/mergedMesh-Faces.lst', 'w') as outFacesFile: vertexEnum = 0 for currentMesh in listFile: with file(currentMesh) as currFile: currOffset = vertexEnum for currLine in currFile: if currLine.startswith("v"): vertexEnum = vertexEnum + 1 outVtxFile.write(currLine) elif currLine.startswith("f"): triFace = currLine.split() outFacesFile.write(triFace[0] + ' ' + str(int(triFace[1])+currOffset) + ' ' + str(int(triFace[2])+currOffset) + ' ' + str(int(triFace[3])+currOffset)+ '\n') # log log(1, [ "VtxCount: " + str(vertexEnum) ]) with file(outDir+'/mergedMesh.obj', 'w') as finalMesh: with file(outDir+'/mergedMesh-Vtx.lst', 'r') as outVtxFile: finalMesh.write(outVtxFile.read()) with file(outDir+'/mergedMesh-Faces.lst', 'r') as outFacesFile: finalMesh.write(outFacesFile.read()) os.remove(outDir+'/mergedMesh-Vtx.lst') os.remove(outDir+'/mergedMesh-Faces.lst') def main(argv): ARGS_STRING = 'Args: -i <inputdir> -o <outdir>' try: opts, args = getopt.getopt(argv,"i:o:") except getopt.GetoptError: print ARGS_STRING sys.exit(2) mandatory = 2 #Files IN_DIR = '' OUT_DIR = '' for opt, arg in opts: if opt == '-i': IN_DIR = arg mandatory = mandatory - 1 elif opt == '-o': OUT_DIR = arg mandatory = mandatory - 1 if mandatory != 0: print 'Not all arguments where given' print ARGS_STRING sys.exit(2) try: listFile = glob.glob(IN_DIR+'/*.obj') mergeFiles(listFile,OUT_DIR) except: exc_type, exc_value, exc_traceback = sys.exc_info() lines = traceback.format_exception(exc_type, exc_value, exc_traceback) log(1, [ "Error: " + ''.join('!! ' + line for line in lines) ]) sys.exit(2) if __name__ == "__main__": main(sys.argv[1:])
mit
EOL/capstone_eol
vendor/plugins/simple_auto_complete/lib/grosser/autocomplete.rb
2924
module Grosser module Autocomplete #Example: # # # Controller # class BlogController < ApplicationController # autocomplete_for :post, :title # end # # # View # <%= text_field :post, title, :class => 'autocomplete', 'autocomplete_url'=>autocomplete_for_post_title_posts_path %> # # #routes.rb # map.resources :users, :collection => { :autocomplete_for_user_name => :get} # # # Options # By default, autocomplete_for limits the results to 10 entries, # and sorts by the given field. # # autocomplete_for takes a third parameter, an options hash to # the find method used to search for the records: # # autocomplete_for :post, :title, :limit => 15, :order => 'created_at DESC' # # # Block # with a block you can generate any output you need(passed into render :inline): # autocomplete_for :post, :title do |items| # items.map{|item| "#{item.title} -- #{item.id}"}.join("\n") # end module ControllerMethods def autocomplete_for(object, method, options = {}) define_method("autocomplete_for_#{object}_#{method}") do find_options = { :conditions => [ "LOWER(#{method}) LIKE ?", '%'+params['q'].to_s.downcase + '%' ], :order => "#{method} ASC", :limit => 10 }.merge!(options) @items = object.to_s.camelize.constantize.find(:all, find_options) if block_given? out = yield(@items) else out = %Q[<%= @items.map {|item| h(item.#{method})}.join("\n")%>] end render :inline => out end end end # Store the value of the autocomplete field as record # autocomplete_for('user','name') # -> the auto_user_name field will be resolved to a User, using User.find_by_autocomplete_name(value) # -> Post has autocomplete_for('user','name') # -> User has find_by_autocomplete('name') module RecordMethods def autocomplete_for(object,method) name = object.to_s.underscore object = object.to_s.camelize.constantize #auto_user_name= define_method("auto_#{name}_#{method}=") do |value| found = object.send("find_by_autocomplete_"+method,value) self.send(name+'=', found) end #auto_user_name define_method("auto_#{name}_#{method}") do return send(name).send(method) if send(name) "" end end def find_by_autocomplete(attr) class_eval <<-end_eval def self.find_by_autocomplete_#{attr}(value) return nil if value.blank? self.find( :first, :conditions => [ "LOWER(#{attr}) = ?", value.to_s.downcase ] ) end end_eval end end end end
mit
rockmandew/pongnub
assets/conversion.js
9217
(function(){var f=this,h=function(a){var b=typeof a;if("object"==b)if(a){if(a instanceof Array)return"array";if(a instanceof Object)return b;var d=Object.prototype.toString.call(a);if("[object Window]"==d)return"object";if("[object Array]"==d||"number"==typeof a.length&&"undefined"!=typeof a.splice&&"undefined"!=typeof a.propertyIsEnumerable&&!a.propertyIsEnumerable("splice"))return"array";if("[object Function]"==d||"undefined"!=typeof a.call&&"undefined"!=typeof a.propertyIsEnumerable&&!a.propertyIsEnumerable("call"))return"function"}else return"null"; else if("function"==b&&"undefined"==typeof a.call)return"object";return b};var k=function(a){k[" "](a);return a};k[" "]=function(){};var m=function(a,b){for(var d in a)Object.prototype.hasOwnProperty.call(a,d)&&b.call(null,a[d],d,a)};var n=parseFloat("0.06"),p=isNaN(n)||1<n||0>n?0:n;var q;e:{var r=f.navigator;if(r){var s=r.userAgent;if(s){q=s;break e}}q=""};var t=-1!=q.indexOf("Opera")||-1!=q.indexOf("OPR"),u=-1!=q.indexOf("Trident")||-1!=q.indexOf("MSIE"),v=-1!=q.indexOf("Gecko")&&-1==q.toLowerCase().indexOf("webkit")&&!(-1!=q.indexOf("Trident")||-1!=q.indexOf("MSIE")),w=-1!=q.toLowerCase().indexOf("webkit"); (function(){var a="",b;if(t&&f.opera)return a=f.opera.version,"function"==h(a)?a():a;v?b=/rv\:([^\);]+)(\)|;)/:u?b=/\b(?:MSIE|rv)[: ]([^\);]+)(\)|;)/:w&&(b=/WebKit\/(\S+)/);b&&(a=(a=b.exec(q))?a[1]:"");return u&&(b=(b=f.document)?b.documentMode:void 0,b>parseFloat(a))?String(b):a})();var x=function(a){this.b=[];this.a={};for(var b=0,d=arguments.length;b<d;++b)this.a[arguments[b]]=""},z=function(){var a=y,b="317150500 317150501 317150502 317150503 317150504 317150505".split(" ");if(a.a.hasOwnProperty(1)&&""==a.a[1]){e:{if(!(1E-4>Math.random())){var d=Math.random();if(d<p){try{var c=new Uint16Array(1);window.crypto.getRandomValues(c);d=c[0]/65536}catch(e){d=Math.random()}b=b[Math.floor(d*b.length)];break e}}b=null}b&&""!=b&&a.a.hasOwnProperty(1)&&(a.a[1]=b)}}; x.prototype.c=function(a){return this.a.hasOwnProperty(a)?this.a[a]:""};x.prototype.geil=x.prototype.c;var A=function(){var a=y,b=[];m(a.a,function(a){""!=a&&b.push(a)});return 0<a.b.length&&0<b.length?a.b.join(",")+","+b.join(","):a.b.join(",")+b.join(",")};var y,B="google_conversion_id google_conversion_format google_conversion_type google_conversion_order_id google_conversion_language google_conversion_value google_conversion_currency google_conversion_domain google_conversion_label google_conversion_color google_disable_viewthrough google_remarketing_only google_remarketing_for_search google_conversion_items google_custom_params google_conversion_date google_conversion_time google_conversion_js_version onload_callback opt_image_generator google_is_call google_conversion_page_url".split(" "); function C(a){return null!=a?escape(a.toString()):""}function D(a){return null!=a?a.toString().substring(0,512):""}function E(a,b){var d=C(b);if(""!=d){var c=C(a);if(""!=c)return"&".concat(c,"=",d)}return""}function F(a){var b=typeof a;return null==a||"object"==b||"function"==b?null:String(a).replace(/,/g,"\\,").replace(/;/g,"\\;").replace(/=/g,"\\=")} function G(a){var b;if((a=a.google_custom_params)&&"object"==typeof a&&"function"!=typeof a.join){var d=[];for(b in a)if(Object.prototype.hasOwnProperty.call(a,b)){var c=a[b];if(c&&"function"==typeof c.join){for(var e=[],g=0;g<c.length;++g){var l=F(c[g]);null!=l&&e.push(l)}c=0==e.length?null:e.join(",")}else c=F(c);(e=F(b))&&null!=c&&d.push(e+"="+c)}b=d.join(";")}else b="";return""==b?"":"&".concat("data=",encodeURIComponent(b))} function H(a){return"number"!=typeof a&&"string"!=typeof a?"":C(a.toString())}function I(a){if(!a)return"";a=a.google_conversion_items;if(!a)return"";for(var b=[],d=0,c=a.length;d<c;d++){var e=a[d],g=[];e&&(g.push(H(e.value)),g.push(H(e.quantity)),g.push(H(e.item_id)),g.push(H(e.adwords_grouping)),g.push(H(e.sku)),b.push("("+g.join("*")+")"))}return 0<b.length?"&item="+b.join(""):""} function J(a,b,d){var c=[];if(a){var e=a.screen;e&&(c.push(E("u_h",e.height)),c.push(E("u_w",e.width)),c.push(E("u_ah",e.availHeight)),c.push(E("u_aw",e.availWidth)),c.push(E("u_cd",e.colorDepth)));a.history&&c.push(E("u_his",a.history.length))}d&&"function"==typeof d.getTimezoneOffset&&c.push(E("u_tz",-d.getTimezoneOffset()));b&&("function"==typeof b.javaEnabled&&c.push(E("u_java",b.javaEnabled())),b.plugins&&c.push(E("u_nplug",b.plugins.length)),b.mimeTypes&&c.push(E("u_nmime",b.mimeTypes.length))); return c.join("")}function K(a,b,d){var c="";if(b){var e;if(a.top==a)e=0;else{var g=a.location.ancestorOrigins;if(g)e=g[g.length-1]==a.location.origin?1:2;else{g=a.top;try{var l;if(l=!!g&&null!=g.location.href)n:{try{k(g.foo);l=!0;break n}catch(fa){}l=!1}e=l}catch(ga){e=!1}e=e?1:2}}l="";l=d?d:1==e?a.top.location.href:a.location.href;c+=E("frm",e);c+=E("url",D(l));c+=E("ref",D(b.referrer))}return c} function L(a){return a&&a.location&&a.location.protocol&&"https:"==a.location.protocol.toString().toLowerCase()?"https:":"http:"}function M(a){return a.google_remarketing_only?"googleads.g.doubleclick.net":a.google_conversion_domain||"www.googleadservices.com"} function N(a,b,d,c){var e="/?";"landing"==c.google_conversion_type&&(e="/extclk?");var e=L(a)+"//"+M(c)+"/pagead/"+[c.google_remarketing_only?"viewthroughconversion/":"conversion/",C(c.google_conversion_id),e,"random=",C(c.google_conversion_time)].join(""),g;e:{g=c.google_conversion_language;if(null!=g){g=g.toString();if(2==g.length){g=E("hl",g);break e}if(5==g.length){g=E("hl",g.substring(0,2))+E("gl",g.substring(3,5));break e}}g=""}a=[E("cv",c.google_conversion_js_version),E("fst",c.google_conversion_first_time), E("num",c.google_conversion_snippets),E("fmt",c.google_conversion_format),E("value",c.google_conversion_value),E("currency_code",c.google_conversion_currency),E("label",c.google_conversion_label),E("oid",c.google_conversion_order_id),E("bg",c.google_conversion_color),g,E("guid","ON"),E("disvt",c.google_disable_viewthrough),E("is_call",c.google_is_call),E("eid",A()),I(c),J(a,b,c.google_conversion_date),G(c),K(a,d,c.google_conversion_page_url),c.google_remarketing_for_search&&!c.google_conversion_domain? "&srr=n":""].join("");return e+a}function O(a){return{ar:1,bg:1,cs:1,da:1,de:1,el:1,en_AU:1,en_US:1,en_GB:1,es:1,et:1,fi:1,fr:1,hi:1,hr:1,hu:1,id:1,is:1,it:1,iw:1,ja:1,ko:1,lt:1,nl:1,no:1,pl:1,pt_BR:1,pt_PT:1,ro:1,ru:1,sk:1,sl:1,sr:1,sv:1,th:1,tl:1,tr:1,vi:1,zh_CN:1,zh_TW:1}[a]?a+".html":"en_US.html"} function P(){var a=Q,b=navigator,d=document,c=Q;3!=c.google_conversion_format||c.google_remarketing_only||c.google_conversion_domain||y&&z();var e=y?y.c(1):"",b=N(a,b,d,c),d=function(a,b,c){return'<img height="'+c+'" width="'+b+'" border="0" alt="" src="'+a+'" />'};return 0==c.google_conversion_format&&null==c.google_conversion_domain?'<a href="'+(L(a)+"//services.google.com/sitestats/"+O(c.google_conversion_language)+"?cid="+C(c.google_conversion_id))+'" target="_blank">'+d(b,135,27)+"</a>":1<c.google_conversion_snippets|| 3==c.google_conversion_format?"317150501"==e||"317150502"==e||"317150503"==e||"317150504"==e||"317150505"==e?d(b,1,1)+('<script src="'+b.replace(/(&|\?)fmt=3(&|$)/,"$1fmt=4&adtest=on$2")+'">\x3c/script>'):d(b,1,1):'<iframe name="google_conversion_frame" title="Google conversion frame" width="'+(2==c.google_conversion_format?200:300)+'" height="'+(2==c.google_conversion_format?26:13)+'" src="'+b+'" frameborder="0" marginwidth="0" marginheight="0" vspace="0" hspace="0" allowtransparency="true" scrolling="no">'+ d(b.replace(/\?random=/,"?frame=0&random="),1,1)+"</iframe>"}function aa(){return new Image}function ba(){var a=R,b=S,d=aa;"function"===typeof a.opt_image_generator&&(d=a.opt_image_generator);a=d();b+=E("async","1");a.src=b;a.onload=function(){}};var Q=window; if(Q)if(null!=/[\?&;]google_debug/.exec(document.URL)){var ca=Q,T=document.getElementsByTagName("head")[0];T||(T=document.createElement("head"),document.getElementsByTagName("html")[0].insertBefore(T,document.getElementsByTagName("body")[0]));var U=document.createElement("script");U.src=L(window)+"//"+M(ca)+"/pagead/conversion_debug_overlay.js";T.appendChild(U)}else{try{var V;var W=Q;"landing"==W.google_conversion_type||!W.google_conversion_id||W.google_remarketing_only&&W.google_disable_viewthrough?V= !1:(W.google_conversion_date=new Date,W.google_conversion_time=W.google_conversion_date.getTime(),W.google_conversion_snippets="number"==typeof W.google_conversion_snippets&&0<W.google_conversion_snippets?W.google_conversion_snippets+1:1,"number"!=typeof W.google_conversion_first_time&&(W.google_conversion_first_time=W.google_conversion_time),W.google_conversion_js_version="7",0!=W.google_conversion_format&&1!=W.google_conversion_format&&2!=W.google_conversion_format&&3!=W.google_conversion_format&& (W.google_conversion_format=1),y=new x(1),V=!0);if(V&&(document.write(P()),Q.google_remarketing_for_search&&!Q.google_conversion_domain)){var X=Q,R=Q,S,da=S=L(X)+"//www.google.com/ads/user-lists/"+[C(R.google_conversion_id),"/?random=",Math.floor(1E9*Math.random())].join(""),Y,Z=R;Y=[E("label",Z.google_conversion_label),E("fmt","3"),K(X,document,Z.google_conversion_page_url)].join("");S=da+Y;ba()}}catch(ea){}for(var ha=Q,$=0;$<B.length;$++)ha[B[$]]=null};})();
mit
jmorse/cyanide
tests/js/search.spec.js
189
var search = require('../../web/javascript/search.js'); describe("The search page", function() { it("should be defined", function() { expect(search.SearchPage).toBeDefined(); }); });
mit
AlanJAS/turtleart
TurtleArt/util/codegen.py
18799
# -*- coding: utf-8 -*- # Copyright (c) 2008, Armin Ronacher # 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. # # 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 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. """ codegen ~~~~~~~ Extension to ast that allow ast -> python code generation. :copyright: Copyright 2008 by Armin Ronacher. :license: BSD. Modified by Marion Zepf. """ import ast def to_source(node, indent_with=' ' * 4, add_line_information=False): """This function can convert a node tree back into python sourcecode. This is useful for debugging purposes, especially if you're dealing with custom asts not generated by python itself. It could be that the sourcecode is evaluable when the AST itself is not compilable / evaluable. The reason for this is that the AST contains some more data than regular sourcecode does, which is dropped during conversion. Each level of indentation is replaced with `indent_with`. Per default this parameter is equal to four spaces as suggested by PEP 8, but it might be adjusted to match the application's styleguide. If `add_line_information` is set to `True` comments for the line numbers of the nodes are added to the output. This can be used to spot wrong line number information of statement nodes. """ generator = SourceGenerator(indent_with, add_line_information) generator.visit(node) return ''.join(generator.result) class SourceGenerator(ast.NodeVisitor): """This visitor is able to transform a well formed syntax tree into python sourcecode. For more details have a look at the docstring of the `node_to_source` function. """ UNARYOP_SYMBOLS = { ast.Invert: "~", ast.Not: "not", ast.UAdd: "+", ast.USub: "-"} # TODO use parentheses around expressions only where necessary BINOP_SYMBOLS = { ast.Add: "+", ast.Sub: "-", ast.Mult: "*", ast.Div: "/", ast.Mod: "%", ast.LShift: "<<", ast.RShift: ">>", ast.BitOr: "|", ast.BitXor: "^", ast.BitAnd: "&", ast.FloorDiv: "//", ast.Pow: "**"} BOOLOP_SYMBOLS = {ast.And: "and", ast.Or: "or"} CMPOP_SYMBOLS = { ast.Eq: "==", ast.NotEq: "!=", ast.Lt: "<", ast.LtE: "<=", ast.Gt: ">", ast.GtE: ">=", ast.Is: "is", ast.IsNot: "is not", ast.In: "in", ast.NotIn: "not in"} def __init__(self, indent_with, add_line_information=False): self.result = [] self.indent_with = indent_with self.add_line_information = add_line_information self.indentation = 0 self.new_lines = 0 def write(self, x): if self.new_lines: if self.result: self.result.append('\n' * self.new_lines) self.result.append(self.indent_with * self.indentation) self.new_lines = 0 self.result.append(x) def newline(self, node=None, extra=0): self.new_lines = max(self.new_lines, 1 + extra) if node is not None and self.add_line_information: self.write('# line: %s' % node.lineno) self.new_lines = 1 def body(self, statements, do_indent=True): if do_indent: self.indentation += 1 for stmt in statements: self.newline() self.visit(stmt) if do_indent: self.indentation -= 1 def body_or_else(self, node): self.body(node.body) if node.orelse: self.newline() self.write('else:') self.body(node.orelse) def signature(self, node): want_comma = [] def write_comma(): if want_comma: self.write(', ') else: want_comma.append(True) padding = [None] * (len(node.args) - len(node.defaults)) for arg, default in zip(node.args, padding + node.defaults): write_comma() self.visit(arg) if default is not None: self.write('=') self.visit(default) if node.vararg is not None: write_comma() self.write('*' + node.vararg) if node.kwarg is not None: write_comma() self.write('**' + node.kwarg) def decorators(self, node): for decorator in node.decorator_list: self.newline(decorator) self.write('@') self.visit(decorator) # Statements def visit_Assign(self, node): self.newline(node) for idx, target in enumerate(node.targets): if idx: self.write(', ') self.visit(target) self.write(' = ') self.visit(node.value) def visit_AugAssign(self, node): self.newline(node) self.visit(node.target) self.write(self.BINOP_SYMBOLS[node.op] + '=') self.visit(node.value) def visit_ImportFrom(self, node): self.newline(node) self.write('from %s%s import ' % ('.' * node.level, node.module)) for idx, item in enumerate(node.names): if idx: self.write(', ') self.visit(item) def visit_Import(self, node): self.newline(node) for item in node.names: self.write('import ') self.visit(item) def visit_Expr(self, node): self.newline(node) self.generic_visit(node) def visit_Module(self, node): self.body(node.body, do_indent=False) def visit_FunctionDef(self, node): self.newline(extra=1) self.decorators(node) self.newline(node) self.write('def %s(' % node.name) self.signature(node.args) self.write('):') self.body(node.body) def visit_ClassDef(self, node): have_args = [] def paren_or_comma(): if have_args: self.write(', ') else: have_args.append(True) self.write('(') self.newline(extra=2) self.decorators(node) self.newline(node) self.write('class %s' % node.name) for base in node.bases: paren_or_comma() self.visit(base) # XXX: the if here is used to keep this module compatible # with python 2.6. if hasattr(node, 'keywords'): for keyword in node.keywords: paren_or_comma() self.write(keyword.arg + '=') self.visit(keyword.value) if node.starargs is not None: paren_or_comma() self.write('*') self.visit(node.starargs) if node.kwargs is not None: paren_or_comma() self.write('**') self.visit(node.kwargs) self.write(have_args and '):' or ':') self.body(node.body) def visit_If(self, node): self.newline(node) self.write('if ') self.visit(node.test) self.write(':') self.body(node.body) while True: else_ = node.orelse if len(else_) == 1 and isinstance(else_[0], ast.If): node = else_[0] self.newline() self.write('elif ') self.visit(node.test) self.write(':') self.body(node.body) elif else_: self.newline() self.write('else:') self.body(else_) break else: break def visit_For(self, node): self.newline(node) self.write('for ') self.visit(node.target) self.write(' in ') self.visit(node.iter) self.write(':') self.body_or_else(node) def visit_While(self, node): self.newline(node) self.write('while ') self.visit(node.test) self.write(':') self.body_or_else(node) def visit_With(self, node): self.newline(node) self.write('with ') self.visit(node.context_expr) if node.optional_vars is not None: self.write(' as ') self.visit(node.optional_vars) self.write(':') self.body(node.body) def visit_Pass(self, node): self.newline(node) self.write('pass') def visit_Print(self, node): # XXX: python 2.6 only self.newline(node) self.write('print ') want_comma = False if node.dest is not None: self.write(' >> ') self.visit(node.dest) want_comma = True for value in node.values: if want_comma: self.write(', ') self.visit(value) want_comma = True if not node.nl: self.write(',') def visit_Delete(self, node): self.newline(node) self.write('del ') for idx, target in enumerate(node): if idx: self.write(', ') self.visit(target) def visit_TryExcept(self, node): self.newline(node) self.write('try:') self.body(node.body) for handler in node.handlers: self.visit(handler) def visit_TryFinally(self, node): self.newline(node) self.write('try:') self.body(node.body) self.newline(node) self.write('finally:') self.body(node.finalbody) def visit_Global(self, node): self.newline(node) self.write('global ' + ', '.join(node.names)) def visit_Nonlocal(self, node): self.newline(node) self.write('nonlocal ' + ', '.join(node.names)) def visit_Return(self, node): self.newline(node) self.write('return') if hasattr(node, "value") and node.value is not None: self.write(' ') self.visit(node.value) def visit_Break(self, node): self.newline(node) self.write('break') def visit_Continue(self, node): self.newline(node) self.write('continue') def visit_Raise(self, node): # XXX: Python 2.6 / 3.0 compatibility self.newline(node) self.write('raise') if hasattr(node, 'exc') and node.exc is not None: self.write(' ') self.visit(node.exc) if node.cause is not None: self.write(' from ') self.visit(node.cause) elif hasattr(node, 'type') and node.type is not None: self.visit(node.type) if node.inst is not None: self.write(', ') self.visit(node.inst) if node.tback is not None: self.write(', ') self.visit(node.tback) def visit_Comment(self, node): self.newline(node) self.write('#' + str(node.text)) def visit_ExtraCode(self, node): self.newline(node) self.write(str(node.text)) # Expressions def visit_Attribute(self, node): self.visit(node.value) self.write('.' + node.attr) def visit_Call(self, node): want_comma = [] def write_comma(): if want_comma: self.write(', ') else: want_comma.append(True) self.visit(node.func) self.write('(') for arg in node.args: write_comma() self.visit(arg) for keyword in node.keywords: write_comma() self.write(keyword.arg + '=') self.visit(keyword.value) if node.starargs is not None: write_comma() self.write('*') self.visit(node.starargs) if node.kwargs is not None: write_comma() self.write('**') self.visit(node.kwargs) self.write(')') visit_TypedCall = visit_Call def visit_Name(self, node): self.write(node.id) visit_TypedName = visit_Name def visit_Str(self, node): self.write(repr(node.s)) def visit_Bytes(self, node): self.write(repr(node.s)) def visit_Num(self, node): self.write(repr(node.n)) def visit_Tuple(self, node): self.write('(') idx = -1 for idx, item in enumerate(node.elts): if idx: self.write(', ') self.visit(item) self.write(idx and ')' or ',)') def sequence_visit(left, right): def visit(self, node): self.write(left) for idx, item in enumerate(node.elts): if idx: self.write(', ') self.visit(item) self.write(right) return visit visit_List = sequence_visit('[', ']') visit_Set = sequence_visit('{', '}') del sequence_visit def visit_Dict(self, node): self.write('{') for idx, (key, value) in enumerate(zip(node.keys, node.values)): if idx: self.write(', ') self.visit(key) self.write(': ') self.visit(value) self.write('}') def visit_BinOp(self, node): op = self.BINOP_SYMBOLS[node.op] # if op in ['+', '-']: self.write('(') self.visit(node.left) self.write(' %s ' % op) self.visit(node.right) # if op in ['+', '-']: self.write(')') def visit_BoolOp(self, node): self.write('(') for idx, value in enumerate(node.values): if idx: self.write(' %s ' % self.BOOLOP_SYMBOLS[node.op]) self.visit(value) self.write(')') def visit_Compare(self, node): self.write('(') self.visit(node.left) for op, right in zip(node.ops, node.comparators): self.write(' %s ' % self.CMPOP_SYMBOLS[op]) self.visit(right) self.write(')') def visit_UnaryOp(self, node): self.write('(') op = self.UNARYOP_SYMBOLS[node.op] self.write(op) if op == 'not': self.write(' ') self.visit(node.operand) self.write(')') def visit_Subscript(self, node): self.visit(node.value) self.write('[') self.visit(node.slice) self.write(']') visit_TypedSubscript = visit_Subscript def visit_Index(self, node): self.visit(node.value) def visit_Slice(self, node): if node.lower is not None: self.visit(node.lower) self.write(':') if node.upper is not None: self.visit(node.upper) if node.step is not None: self.write(':') if not (isinstance( node.step, ast.Name) and node.step.id == 'None'): self.visit(node.step) def visit_ExtSlice(self, node): for idx, item in node.dims: if idx: self.write(', ') self.visit(item) def visit_Yield(self, node): self.write('yield ') self.visit(node.value) def visit_Lambda(self, node): self.write('(lambda ') self.signature(node.args) self.write(': ') self.visit(node.body) self.write(')') def visit_LambdaWithStrBody(self, node): self.write('(lambda ') for idx, arg in enumerate(node.args): if idx: self.write(', ') self.visit(arg) self.write(': ') self.write(node.body_str) self.write(')') def visit_Ellipsis(self, node): self.write('Ellipsis') def generator_visit(left, right): def visit(self, node): self.write(left) self.visit(node.elt) for comprehension in node.generators: self.visit(comprehension) self.write(right) return visit visit_ListComp = generator_visit('[', ']') visit_GeneratorExp = generator_visit('(', ')') visit_SetComp = generator_visit('{', '}') del generator_visit def visit_DictComp(self, node): self.write('{') self.visit(node.key) self.write(': ') self.visit(node.value) for comprehension in node.generators: self.visit(comprehension) self.write('}') def visit_IfExp(self, node): self.visit(node.body) self.write(' if ') self.visit(node.test) self.write(' else ') self.visit(node.orelse) def visit_Starred(self, node): self.write('*') self.visit(node.value) def visit_Repr(self, node): # XXX: python 2.6 only self.write('`') self.visit(node.value) self.write('`') # Helper Nodes def visit_alias(self, node): self.write(node.name) if node.asname is not None: self.write(' as ' + node.asname) def visit_comprehension(self, node): self.write(' for ') self.visit(node.target) self.write(' in ') self.visit(node.iter) if node.ifs: for if_ in node.ifs: self.write(' if ') self.visit(if_) def visit_excepthandler(self, node): self.newline(node) self.write('except') if node.type is not None: self.write(' ') self.visit(node.type) if node.name is not None: self.write(' as ') self.visit(node.name) self.write(':') self.body(node.body)
mit
studionone/schale
tests/support/Mock/Model/Module/ArticleModel.php
506
<?php declare(strict_types=1); namespace Shale\Test\Support\Mock\Model\Module; use Shale\Annotation; use Shale\Traits\Accessors; /** * @Annotation\Model(name="article_module") */ class ArticleModel { use Accessors; /** * @Annotation\Id() */ protected $id; /** * @Annotation\Property(name="regionId", type="string", optional=true) */ protected $regionId; /** * @Annotation\TypedCollection(name="tags", type="tag") */ protected $tags = []; }
mit
zubie7a/Algorithms
CodeSignal/Arcade/Intro/Level_02/03_Make_Array_Consecutive.py
472
# https://app.codesignal.com/arcade/intro/level-2/bq2XnSr5kbHqpHGJC def makeArrayConsecutive2(statues): statues = sorted(statues) res = 0 # Make elements of the array be consecutive. If there's a # gap between two statues heights', then figure out how # many extra statues have to be added so that all resulting # statues increase in size by 1 unit. for i in range(1, len(statues)): res += statues[i] - statues[i-1] - 1 return res
mit
workshop/struct
lib/spec/builder/spec_builder_20X/spec_variant_dsl_20X.rb
1157
require_relative 'spec_target_dsl_20X' module StructCore class SpecVariantDSL20X def initialize @variant = nil @project_configurations = [] @project_base_dir = nil @project_target_names = [] @project = nil @current_scope = nil end attr_accessor :variant attr_accessor :project_configurations attr_accessor :project_base_dir attr_accessor :project_target_names attr_accessor :project def abstract @variant.abstract = true end def target(name = nil, &block) return unless name.is_a?(String) && !name.empty? && !block.nil? && @project_target_names.include?(name) dsl = StructCore::SpecTargetDSL20X.new dsl.project_configurations = @project_configurations dsl.project_base_dir = @project_base_dir dsl.target = StructCore::Specfile::Target.new(name, nil, [], [], [], [], [], [], [], []) dsl.project = @project @current_scope = dsl block.call @current_scope = nil @variant.targets << dsl.target end def respond_to_missing?(_, _) true end def method_missing(method, *args, &block) return if @current_scope.nil? @current_scope.send(method, *args, &block) end end end
mit
mjp41/corert
src/System.Private.Reflection.Core/src/System/Reflection/Runtime/Types/ShadowRuntimeInspectionOnlyNamedType.cs
1776
// 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. using global::System; using global::System.Reflection; using global::System.Diagnostics; using global::System.Collections.Generic; using global::System.Reflection.Runtime.General; using global::Internal.Reflection.Core.NonPortable; using global::Internal.Metadata.NativeFormat; namespace System.Reflection.Runtime.Types { // // This is a RuntimeInspectionOnlyNamedType type that's created "behind the scenes" for types that also have EETypes. // The type unification rules dictate that types that have both metadata and EEType be created as RuntimeEENamedTypes // as the public-facing "identity." However, if S.R.R. is loaded and metadata is present, the developer naturally expects the // Type object to be "fully functional." We accomplish this by creating this shadow type on-demand when // a RuntimeEENamedType cannot get what it needs from the raw EEType. In such cases, RuntimeEENamedType delegates // calls to this object. // // ! By necessity, shadow types break the type identity rules - thus, they must NEVER escape out into the wild. // internal sealed class ShadowRuntimeInspectionOnlyNamedType : RuntimeInspectionOnlyNamedType { internal ShadowRuntimeInspectionOnlyNamedType(MetadataReader metadataReader, TypeDefinitionHandle typeDefinitionHandle) : base(metadataReader, typeDefinitionHandle) { } public sealed override bool InternalViolatesTypeIdentityRules { get { return true; } } } }
mit
ttamminen/riotjs
lib/tag/vdom.js
1560
/* Virtual dom is an array of custom tags on the document. Updates and unmounts propagate downwards from parent to children. */ var virtual_dom = [], tag_impl = {} function getTag(dom) { return tag_impl[dom.tagName.toLowerCase()] } function injectStyle(css) { var node = document.createElement('style') node.innerHTML = css document.head.appendChild(node) } function mountTo(root, tagName, opts) { var tag = tag_impl[tagName] if (tag && root) tag = new Tag(tag, { root: root, opts: opts }) if (tag && tag.mount) { tag.mount() virtual_dom.push(tag) return tag.on('unmount', function() { virtual_dom.splice(virtual_dom.indexOf(tag), 1) }) } } riot.tag = function(name, html, css, fn) { if (typeof css == 'function') fn = css else if (css) injectStyle(css) tag_impl[name] = { name: name, tmpl: html, fn: fn } } riot.mount = function(selector, tagName, opts) { if (selector == '*') selector = Object.keys(tag_impl).join(', ') if (typeof tagName == 'object') { opts = tagName; tagName = 0 } var tags = [] function push(root) { var name = tagName || root.tagName.toLowerCase(), tag = mountTo(root, name, opts) if (tag) tags.push(tag) } // DOM node if (selector.tagName) { push(selector) return tags[0] // selector } else { each(document.querySelectorAll(selector), push) return tags } } // update everything riot.update = function() { return each(virtual_dom, function(tag) { tag.update() }) } // @deprecated riot.mountTo = riot.mount
mit
TelegramBots/telegram.bot
src/Telegram.Bot/Args/ApiResponseEventArgs.cs
528
using System.Net.Http; namespace Telegram.Bot.Args { /// <summary> /// Provides data for ApiResponseReceived event /// </summary> public class ApiResponseEventArgs { /// <summary> /// HTTP response received from API /// </summary> public HttpResponseMessage ResponseMessage { get; internal set; } /// <summary> /// Event arguments of this request /// </summary> public ApiRequestEventArgs ApiRequestEventArgs { get; internal set; } } }
mit
altimesh/hybridizer-basic-samples
HybridizerBasicSamples_CUDA100/2.Imaging/Sobel/Sobel/Program.cs
4157
using System.Collections.Generic; using System.Linq; using System.Text; using System; using System.Threading.Tasks; using System.Drawing; using Hybridizer.Runtime.CUDAImports; using System.Diagnostics; namespace Hybridizer.Basic.Imaging { class Program { static void Main(string[] args) { Bitmap baseImage = (Bitmap)Image.FromFile("lena512.bmp"); int height = baseImage.Height, width = baseImage.Width; Bitmap resImage = new Bitmap(width, height); byte[] inputPixels = new byte[width * height]; byte[] outputPixels = new byte[width * height]; ReadImage(inputPixels, baseImage, width, height); HybRunner runner = HybRunner.Cuda().SetDistrib(32, 32, 16, 16, 1, 0); dynamic wrapper = runner.Wrap(new Program()); wrapper.ComputeSobel(outputPixels, inputPixels, width, height, 0, height); SaveImage("lena-sobel.bmp", outputPixels, width, height); try { Process.Start("lena-sobel.bmp");} catch {} // catch exception for non interactives machines } public static void ReadImage(byte[] inputPixel, Bitmap image, int width, int height) { for (int i = 0; i < height; ++i) { for (int j = 0; j < width; ++j) { double greyPixel = (image.GetPixel(i, j).R * 0.2126 + image.GetPixel(i, j).G * 0.7152 + image.GetPixel(i, j).B * 0.0722); inputPixel[i * height + j] = Convert.ToByte(greyPixel); } } } [EntryPoint] public static void ComputeSobel(byte[] outputPixel, byte[] inputPixel, int width, int height, int from, int to) { for (int i = from + threadIdx.y + blockIdx.y * blockDim.y; i < to; i += blockDim.y * gridDim.y) { for (int j = threadIdx.x + blockIdx.x * blockDim.x; j < width; j += blockDim.x * gridDim.x) { int pixelId = i * width + j; int output = 0; if (i != 0 && j != 0 && i != height - 1 && j != width - 1) { byte topl = inputPixel[pixelId - width - 1]; byte top = inputPixel[pixelId - width]; byte topr = inputPixel[pixelId - width + 1]; byte l = inputPixel[pixelId - 1]; byte r = inputPixel[pixelId + 1]; byte botl = inputPixel[pixelId + width - 1]; byte bot = inputPixel[pixelId + width]; byte botr = inputPixel[pixelId + width + 1]; int sobelx = (topl) + (2 * l) + (botl) - (topr) - (2 * r) - (botr); int sobely = (topl + 2 * top + topr - botl - 2 * bot - botr); int squareSobelx = sobelx * sobelx; int squareSobely = sobely * sobely; output = (int)Math.Sqrt((squareSobelx + squareSobely)); if (output < 0) { output = -output; } if (output > 255) { output = 255; } outputPixel[pixelId] = (byte)output; } } } } public static void SaveImage(string nameImage, byte[] outputPixel, int width, int height) { Bitmap resImage = new Bitmap(width, height); int col = 0; for (int i = 0; i < height; ++i) { for (int j = 0; j < width; ++j) { col = outputPixel[i * height + j]; resImage.SetPixel(i, j, Color.FromArgb(col, col, col)); } } //store the result image. resImage.Save(nameImage, System.Drawing.Imaging.ImageFormat.Png); } } }
mit
PeppeL-G/bootstrap-3-modal
examples/modals/signUp.js
6387
if(Meteor.isClient){ var templateName = 'modal_signUp' // Store user input in the Session object so it survives code reloads. // The error "" means there is no error. var usernameKey = templateName+'_username' var usernameErrorKey = templateName+'_usernameError' var emailKey = templateName+'_email' var emailErrorKey = templateName+'_emailError' var password0Key = templateName+'_password0' var password0ErrorKey = templateName+'_password0Error' var password1Key = templateName+'_password1' var password1ErrorKey = templateName+'_password1Error' var acceptsUserAgreementKey = templateName+'_acceptsUserAgreement' var occupiedUsernamesKey = templateName+'_occupiedUsernames' Template[templateName].created = function(){ Session.setDefault(usernameKey, "") Session.setDefault(emailKey, "") Session.setDefault(password0Key, "") Session.setDefault(password1Key, "") Session.setDefault(acceptsUserAgreementKey, false) Session.setDefault(occupiedUsernamesKey, []) // The other sessions are set in the validation autoruns below. // The validation autoruns below are to be consistent with the settings in // the accounts-ui-unstyled package. // https://github.com/meteor/meteor/blob/556c0e28e94b9351cbf0b28e80a71a4e35f1362a/packages/accounts-ui-unstyled/login_buttons.js#L74 // Validate username. this.autorun(function(computation){ if(Session.equals(usernameKey, "")){ Session.set(usernameErrorKey, "Your username can't be empty.") }else{ var username = Session.get(usernameKey) if(username.length <= 2){ Session.set(usernameErrorKey, "Your username must be at least 2 characters long.") }else{ var occupiedUsernames = Session.get(occupiedUsernamesKey) if(occupiedUsernames.indexOf(username) != -1){ Session.set(usernameErrorKey, "This username is already taken by another member.") }else{ Session.set(usernameErrorKey, "") } } } }) // Validate email. this.autorun(function(computation){ if(Session.equals(emailKey, "")){ Session.set(emailErrorKey, "This is not a valid email.") }else{ var email = Session.get(emailKey) if(email.indexOf("@") == -1){ Session.set(emailErrorKey, "This is not a valid email.") }else{ Session.set(emailErrorKey, "") } } }) // Validate password0. this.autorun(function(computation){ if(Session.equals(password0Key, "")){ Session.set(password0ErrorKey, "You can't have an empty password.") }else{ var password0 = Session.get(password0Key) if(password0.length <= 5){ Session.set(password0ErrorKey, "The password needs to be a bit longer.") }else{ Session.set(password0ErrorKey, "") } } }) // Validate password1. this.autorun(function(computation){ var password0 = Session.get(password0Key) var password1 = Session.get(password1Key) if(password0 == password1){ Session.set(password1ErrorKey, "") }else{ Session.set(password1ErrorKey, "This password is not the same as the first.") } }) } Template[templateName].helpers({ username: function(){ return Session.get(usernameKey) }, usernameError: function(){ return Session.get(usernameErrorKey) }, email: function(){ return Session.get(emailKey) }, emailError: function(){ return Session.get(emailErrorKey) }, password0: function(){ return Session.get(password0Key) }, password0Error: function(){ return Session.get(password0ErrorKey) }, password1: function(){ return Session.get(password1Key) }, password1Error: function(){ return Session.get(password1ErrorKey) }, isUserAgrementAccepted: function(){ return Session.equals(acceptsUserAgreementKey, true) }, isAnythingWrong: function(){ return !(Session.equals(usernameErrorKey , "") && Session.equals(emailErrorKey , "") && Session.equals(password0ErrorKey, "") && Session.equals(password1ErrorKey, "") && Session.equals(acceptsUserAgreementKey, true)) } }) Template[templateName].events({ 'keyup #modal_signUp_username': function(event, template){ var username = event.currentTarget.value Session.set(usernameKey, username) }, 'keyup #modal_signUp_email': function(event, template){ var email = event.currentTarget.value Session.set(emailKey, email) }, 'keyup #modal_signUp_password0': function(event, template){ var password0 = event.currentTarget.value Session.set(password0Key, password0) }, 'keyup #modal_signUp_password1': function(event, template){ var password1 = event.currentTarget.value Session.set(password1Key, password1) }, 'change #modal_signUp_acceptsUserAgreement': function(event, template){ var acceptsUserAgreement = event.currentTarget.checked Session.set(acceptsUserAgreementKey, acceptsUserAgreement) }, 'click .clickRoutesToUserAgreement': function(event, template){ event.preventDefault() // Hide the modal... Modal.hide() // ...and go to the page with the user agreement. // (in this example, that does not exist). //Router.go('userAgreement') }, 'submit form': function(event, template){ event.preventDefault() var username = Session.get(usernameKey) var email = Session.get(emailKey) var password0 = template.find('#modal_signUp_password0').value var password1 = template.find('#modal_signUp_password1').value var options = { username: username, email: email, password: password0 } Accounts.createUser(options, function(error){ if(error){ switch(error.reason){ case "Username already exists.": var occupiedUsernames = Session.get(occupiedUsernamesKey) occupiedUsernames.push(username) Session.set(occupiedUsernamesKey, occupiedUsernames) break case "Email already exists.": Session.set(emailErrorKey, "There is a user registered with this email.") break default: Session.set(usernameErrorKey, "Unknown error reason '"+error.reason+"'. This is a bug, please report it.") } }else{ // Explicity remove the passwords, so no one can read them. Session.set(password0Key, "") Session.set(password1Key, "") Modal.hide() } }) } }) }
mit
kevhuang/rallie
client/public/js/components/App.js
12035
var React = require('react'), Router = require('react-router'), Navigation = Router.Navigation, State = Router.State, RouteHandler = Router.RouteHandler, AppActions = require('../actions/AppActions'), AppStore = require('../stores/AppStore'), cookie = require('react-cookie'); var App = React.createClass({ /* Mixins allows users to reuse code from different parts of the app even when their use cases are very different. Navigation allows us to dynamically create hrefs in the render section. State allows us to check what the current router state is, and if the user is in the event-create or event-detail routes, disable the button for toggling the mode. With the mixins property, we allow the entire React component to reference all the enclosed functionalities using "this". */ mixins: [Navigation, State], // The default mode for a new user is a sheep // Users are able to change to shepherd by clicking a toggle button getInitialState: function() { return { currentUser: undefined, mode: AppStore.getCurrentMode() }; }, //sets current user as logged in after they successfully log into facebook _loggedIn: function(){ this.setState({ currentUser: AppStore.getCurrentUser() }); }, // sets state of current user to undefined after they click the logout // button _loggedOut: function(){ this.setState({ currentUser: AppStore.getCurrentUser() }); }, //Relays information to Event Store so that current user information can //be set to be undefined removeCurrentUser: function(){ AppActions.removeCurrentUser(); }, //setup event listeners //Listens to App store for toggleMode, executes _changeStateMode componentDidMount: function() { AppStore.addEventListener('toggleMode', this._changeStateMode); AppStore.addEventListener('loggedIn', this._loggedIn); AppStore.addEventListener('loggedOut', this._loggedOut); var username = cookie.load("username"); var id = cookie.load('id'); var data = { username: username, id: id }; // console.log(data); AppActions.setCurrentUser(data); }, //removes event listener when the dom element is removed componentWillUnmount: function() { AppStore.removeEventListener('toggleMode', this._changeStateMode); AppStore.removeEventListener('loggedIn', this._loggedIn); AppStore.removeEventListener('loggedOut', this._loggedOut); }, //this.makeHref('home') can be replaced with #/home //Depending on if the user is logged in (based off the url) //the application will determine which parts of the render function //to be displayed render: function() { if (cookie.load("username") !== undefined) { var currentUserLi; if (this.state.currentUser && this.state.currentUser.username) { currentUserLi = <p className="navbar-text">Hi, {this.state.currentUser.username}</p> } return ( <div> <header> <nav className="navbar navbar-default"> <div className="container-fluid"> {/* Brand and toggle get grouped for better mobile display */} <div className="navbar-header"> <button type="button" className="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse-1"> <span className="sr-only">Toggle navigation</span> <span className="icon-bar"></span> <span className="icon-bar"></span> <span className="icon-bar"></span> </button> <a className="navbar-brand" href={this.makeHref('events')}><img className="navbar-logo" alt="Rallie Logo" src="/assets/images/megaphone.png"/></a> </div> {/* Collect the nav links for toggling */} <div className="collapse navbar-collapse" id="navbar-collapse-1"> <ul className="nav navbar-nav"> <p className={'navbar-text ' + (this.state.mode === 'shepherd' ? 'pink' : 'teal')}>{this.state.mode === 'shepherd' ? 'Host' : 'Participate'}</p> {/* This is the toggler for shepherd/sheep. It will be disabled when viewing the event-create and event-detail components */} <li> <button className={'btn navbar-btn btn-' + (this.state.mode === 'shepherd' ? 'teal' : 'pink')} onClick={this._changeMode} disabled={this.isActive('event-create') || this.isActive('event-detail') ? 'disabled' : false}> Change </button> </li> </ul> <ul className="nav navbar-nav navbar-right"> {currentUserLi} <li><a onClick={this.removeCurrentUser} href={this.makeHref('home')}>Logout</a></li> </ul> </div> </div> </nav> </header> <div className="container-fluid"> <div className="row"> <div className="col-lg-10 col-lg-offset-1"> {/* The RouteHandler component renders the active child route's handler */} <RouteHandler/> </div> </div> </div> </div> ); } else { this.transitionTo('/'); return ( <div> <header> <nav className="navbar navbar-default"> <div className="container-fluid"> {/* Brand and toggle get grouped for better mobile display */} <div className="navbar-header"> <button type="button" className="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse-1"> <span className="sr-only">Toggle navigation</span> <span className="icon-bar"></span> <span className="icon-bar"></span> <span className="icon-bar"></span> </button> <a className="navbar-brand" href="#"><img className="navbar-logo" alt="Rallie Logo" src="/assets/images/megaphone.png"/></a> </div> {/* Collect the nav links for toggling */} <div className="collapse navbar-collapse" id="navbar-collapse-1"> <ul className="nav navbar-nav"> <li><a id="brand" href="#">Rallie</a></li> </ul> <ul className="nav navbar-nav navbar-right"> {/* This is the toggler for shepherd/sheep. It will be disabled when viewing the event-create and event-detail components */} <li><a className="login" href="/auth/facebook">Login</a></li> </ul> </div> </div> </nav> </header> <div className="jumbotron"> <div className="container-fluid"> <div className="row"> <div className="col-md-6 megaphone"></div> <div className="col-md-6"> <h1>Rallie</h1> <p>Real-time event collaboration</p> <a className="login" href="/auth/facebook">Log In / Sign Up with Facebook</a> </div> </div> </div> </div> <div className="container-fluid"> <div className="row landing-page-description"> <div className="col-md-10 col-md-offset-1"> <div className="row"> <div className="col-md-4"> Rallie is a platform that makes creating and hosting events easier. It closes the communication gap between hosts and participants so they can collaborate on those events in real-time. Typically, this is hard; it is difficult to manage uncertainty. </div> <div className="col-md-4"> Event hosts put a great deal of effort into ensuring an event runs smoothly. Participants are not willing to get involved without a clear understanding of what’s going on. Once something unexpected happens, all hell could break loose. </div> <div className="col-md-4"> When participants and hosts can seamlessly share information, hosts can act and direct participants to respond accordingly. Rallie provides this communication channel so people can effectively rally together. </div> </div> </div> </div> </div> <div> <img className="how-it-works" src="/assets/images/how-it-works.png" alt="How it works"/> </div> <div className="team-row"> <div className="portraits-text">Team</div> <div className="container-fluid"> <div className="row team-images"> <div className="col-md-3" > <a href="https://www.linkedin.com/in/dmsakamoto"> <img className="portraits center-block" src="/assets/images/derek.png"/> <div className="portraits-name" >DEREK SAKAMOTO</div> </a> </div> <div className="col-md-3"> <a href="https://www.linkedin.com/in/ekong2"> <img className="portraits center-block" src="/assets/images/eddie.png"/> <div className="portraits-name">EDDIE KONG</div> </a> </div> <div className="col-md-3"> <a href="https://www.linkedin.com/in/kevhuang"> <img className="portraits center-block" src="/assets/images/kevin.png"/> <div className="portraits-name" >KEVIN HUANG</div> </a> </div> <div className="col-md-3"> <a href="https://www.linkedin.com/in/stevenshyun"> <img className="portraits center-block" src="/assets/images/steven.png"/> <div className="portraits-name" >STEVEN SHYUN</div> </a> </div> </div> </div> </div> <footer className="landing-page-footer"> <div className="container-fluid"> <div className="footer-powered-by text-center">Rallie is Powered By:</div> <div className="col-md-8 col-md-offset-2"> <div className="row"> <div className="col-md-3"> <img className="center-block" src="/assets/images/react-logo.png" alt="React"/> </div> <div className="col-md-3 flux-logo" > <img className="center-block" src="/assets/images/flux-logo.png" alt="Flux"/> </div> <div className="col-md-3"> <img className="center-block" src="/assets/images/node-logo.png" alt="Node.js"/> </div> <div className="col-md-3"> <img className="center-block" src="/assets/images/postgresql-logo.png" alt="PostgreSQL"/> </div> </div> </div> </div> </footer> </div> ); } }, // Notifies AppAction to change the state.mode _changeMode: function() { AppActions.toggleMode(this.state.mode === 'shepherd' ? 'sheep' : 'shepherd'); }, // Updates the views when the state mode changes from sheep to shepherd and vice versa _changeStateMode: function() { this.setState({ mode: AppStore.getCurrentMode() }); } }); module.exports = App;
mit
bburnett-cpf/react-intro
node_modules/prettier/src/doc-printer.js
8170
"use strict"; const MODE_BREAK = 1; const MODE_FLAT = 2; function rootIndent() { return { indent: 0, align: { spaces: 0, tabs: 0 } }; } function makeIndent(ind) { return { indent: ind.indent + 1, align: ind.align }; } function makeAlign(ind, n) { if (n === -Infinity) { return { indent: 0, align: { spaces: 0, tabs: 0 } }; } return { indent: ind.indent, align: { spaces: ind.align.spaces + n, tabs: ind.align.tabs + (n ? 1 : 0) } }; } function fits(next, restCommands, width) { let restIdx = restCommands.length; const cmds = [next]; while (width >= 0) { if (cmds.length === 0) { if (restIdx === 0) { return true; } else { cmds.push(restCommands[restIdx - 1]); restIdx--; continue; } } const x = cmds.pop(); const ind = x[0]; const mode = x[1]; const doc = x[2]; if (typeof doc === "string") { width -= doc.length; } else { switch (doc.type) { case "concat": for (var i = doc.parts.length - 1; i >= 0; i--) { cmds.push([ind, mode, doc.parts[i]]); } break; case "indent": cmds.push([makeIndent(ind), mode, doc.contents]); break; case "align": cmds.push([makeAlign(ind, doc.n), mode, doc.contents]); break; case "group": cmds.push([ind, doc.break ? MODE_BREAK : mode, doc.contents]); break; case "if-break": if (mode === MODE_BREAK) { if (doc.breakContents) { cmds.push([ind, mode, doc.breakContents]); } } if (mode === MODE_FLAT) { if (doc.flatContents) { cmds.push([ind, mode, doc.flatContents]); } } break; case "line": switch (mode) { // fallthrough case MODE_FLAT: if (!doc.hard) { if (!doc.soft) { width -= 1; } break; } case MODE_BREAK: return true; } break; } } } return false; } function printDocToString(doc, options) { let width = options.printWidth; let newLine = options.newLine || "\n"; let pos = 0; // cmds is basically a stack. We've turned a recursive call into a // while loop which is much faster. The while loop below adds new // cmds to the array instead of recursively calling `print`. let cmds = [[rootIndent(), MODE_BREAK, doc]]; let out = []; let shouldRemeasure = false; let lineSuffix = []; while (cmds.length !== 0) { const x = cmds.pop(); const ind = x[0]; const mode = x[1]; const doc = x[2]; if (typeof doc === "string") { out.push(doc); pos += doc.length; } else { switch (doc.type) { case "concat": for (var i = doc.parts.length - 1; i >= 0; i--) { cmds.push([ind, mode, doc.parts[i]]); } break; case "indent": cmds.push([makeIndent(ind), mode, doc.contents]); break; case "align": cmds.push([makeAlign(ind, doc.n), mode, doc.contents]); break; case "group": switch (mode) { // fallthrough case MODE_FLAT: if (!shouldRemeasure) { cmds.push([ ind, doc.break ? MODE_BREAK : MODE_FLAT, doc.contents ]); break; } case MODE_BREAK: shouldRemeasure = false; const next = [ind, MODE_FLAT, doc.contents]; let rem = width - pos; if (!doc.break && fits(next, cmds, rem)) { cmds.push(next); } else { // Expanded states are a rare case where a document // can manually provide multiple representations of // itself. It provides an array of documents // going from the least expanded (most flattened) // representation first to the most expanded. If a // group has these, we need to manually go through // these states and find the first one that fits. if (doc.expandedStates) { const mostExpanded = doc.expandedStates[doc.expandedStates.length - 1]; if (doc.break) { cmds.push([ind, MODE_BREAK, mostExpanded]); break; } else { for (var i = 1; i < doc.expandedStates.length + 1; i++) { if (i >= doc.expandedStates.length) { cmds.push([ind, MODE_BREAK, mostExpanded]); break; } else { const state = doc.expandedStates[i]; const cmd = [ind, MODE_FLAT, state]; if (fits(cmd, cmds, rem)) { cmds.push(cmd); break; } } } } } else { cmds.push([ind, MODE_BREAK, doc.contents]); } } break; } break; case "if-break": if (mode === MODE_BREAK) { if (doc.breakContents) { cmds.push([ind, mode, doc.breakContents]); } } if (mode === MODE_FLAT) { if (doc.flatContents) { cmds.push([ind, mode, doc.flatContents]); } } break; case "line-suffix": lineSuffix.push([ind, mode, doc.contents]); break; case "line-suffix-boundary": if (lineSuffix.length > 0) { cmds.push([ind, mode, { type: "line", hard: true }]); } break; case "line": switch (mode) { // fallthrough case MODE_FLAT: if (!doc.hard) { if (!doc.soft) { out.push(" "); pos += 1; } break; } else { // This line was forced into the output even if we // were in flattened mode, so we need to tell the next // group that no matter what, it needs to remeasure // because the previous measurement didn't accurately // capture the entire expression (this is necessary // for nested groups) shouldRemeasure = true; } case MODE_BREAK: if (lineSuffix.length) { cmds.push([ind, mode, doc]); [].push.apply(cmds, lineSuffix.reverse()); lineSuffix = []; break; } if (doc.literal) { out.push(newLine); pos = 0; } else { if (out.length > 0) { // Trim whitespace at the end of line while ( out.length > 0 && out[out.length - 1].match(/^[^\S\n]*$/) ) { out.pop(); } out[out.length - 1] = out[out.length - 1].replace( /[^\S\n]*$/, "" ); } let length = ind.indent * options.tabWidth + ind.align.spaces; let indentString = options.useTabs ? "\t".repeat(ind.indent + ind.align.tabs) : " ".repeat(length); out.push(newLine + indentString); pos = length; } break; } break; default: } } } return out.join(""); } module.exports = { printDocToString };
mit
sufuf3/cdnjs
ajax/libs/ag-grid/21.2.1/lib/valueService/valueService.js
13188
/** * ag-grid-community - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v21.2.1 * @link http://www.ag-grid.com/ * @license MIT */ "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var gridOptionsWrapper_1 = require("../gridOptionsWrapper"); var expressionService_1 = require("./expressionService"); var columnController_1 = require("../columnController/columnController"); var context_1 = require("../context/context"); var events_1 = require("../events"); var eventService_1 = require("../eventService"); var valueCache_1 = require("./valueCache"); var utils_1 = require("../utils"); var ValueService = /** @class */ (function () { function ValueService() { this.initialised = false; } ValueService.prototype.init = function () { this.cellExpressions = this.gridOptionsWrapper.isEnableCellExpressions(); this.initialised = true; }; ValueService.prototype.getValue = function (column, rowNode, forFilter, ignoreAggData) { // console.log(`turnActive = ${this.turnActive}`); if (forFilter === void 0) { forFilter = false; } if (ignoreAggData === void 0) { ignoreAggData = false; } // hack - the grid is getting refreshed before this bean gets initialised, race condition. // really should have a way so they get initialised in the right order??? if (!this.initialised) { this.init(); } if (!rowNode) { return; } // pull these out to make code below easier to read var colDef = column.getColDef(); var field = colDef.field; var colId = column.getId(); var data = rowNode.data; var result; // if there is a value getter, this gets precedence over a field var groupDataExists = rowNode.groupData && rowNode.groupData[colId] !== undefined; var aggDataExists = !ignoreAggData && rowNode.aggData && rowNode.aggData[colId] !== undefined; if (forFilter && colDef.filterValueGetter) { result = this.executeFilterValueGetter(colDef.filterValueGetter, data, column, rowNode); } else if (this.gridOptionsWrapper.isTreeData() && aggDataExists) { result = rowNode.aggData[colId]; } else if (this.gridOptionsWrapper.isTreeData() && colDef.valueGetter) { result = this.executeValueGetter(colDef.valueGetter, data, column, rowNode); } else if (this.gridOptionsWrapper.isTreeData() && (field && data)) { result = utils_1._.getValueUsingField(data, field, column.isFieldContainsDots()); } else if (groupDataExists) { result = rowNode.groupData[colId]; } else if (aggDataExists) { result = rowNode.aggData[colId]; } else if (colDef.valueGetter) { result = this.executeValueGetter(colDef.valueGetter, data, column, rowNode); } else if (field && data) { result = utils_1._.getValueUsingField(data, field, column.isFieldContainsDots()); } // the result could be an expression itself, if we are allowing cell values to be expressions if (this.cellExpressions && (typeof result === 'string') && result.indexOf('=') === 0) { var cellValueGetter = result.substring(1); result = this.executeValueGetter(cellValueGetter, data, column, rowNode); } return result; }; ValueService.prototype.setValue = function (rowNode, colKey, newValue, suppressCellValueChangedEvent) { var column = this.columnController.getPrimaryColumn(colKey); if (!rowNode || !column) { return; } // this will only happen if user is trying to paste into a group row, which doesn't make sense // the user should not be trying to paste into group rows var data = rowNode.data; if (utils_1._.missing(data)) { rowNode.data = {}; } // for backwards compatibility we are also retrieving the newValueHandler as well as the valueSetter var _a = column.getColDef(), field = _a.field, newValueHandler = _a.newValueHandler, valueSetter = _a.valueSetter; // need either a field or a newValueHandler for this to work if (utils_1._.missing(field) && utils_1._.missing(newValueHandler) && utils_1._.missing(valueSetter)) { // we don't tell user about newValueHandler, as that is deprecated console.warn("ag-Grid: you need either field or valueSetter set on colDef for editing to work"); return; } var params = { node: rowNode, data: rowNode.data, oldValue: this.getValue(column, rowNode), newValue: newValue, colDef: column.getColDef(), column: column, api: this.gridOptionsWrapper.getApi(), columnApi: this.gridOptionsWrapper.getColumnApi(), context: this.gridOptionsWrapper.getContext() }; params.newValue = newValue; var valueWasDifferent; if (newValueHandler && utils_1._.exists(newValueHandler)) { valueWasDifferent = newValueHandler(params); } else if (utils_1._.exists(valueSetter)) { valueWasDifferent = this.expressionService.evaluate(valueSetter, params); } else { valueWasDifferent = this.setValueUsingField(data, field, newValue, column.isFieldContainsDots()); } // in case user forgot to return something (possible if they are not using TypeScript // and just forgot, or using an old newValueHandler we didn't always expect a return // value here), we default the return value to true, so we always refresh. if (valueWasDifferent === undefined) { valueWasDifferent = true; } // if no change to the value, then no need to do the updating, or notifying via events. // otherwise the user could be tabbing around the grid, and cellValueChange would get called // all the time. if (!valueWasDifferent) { return; } // reset quick filter on this row rowNode.resetQuickFilterAggregateText(); this.valueCache.onDataChanged(); params.newValue = this.getValue(column, rowNode); var onCellValueChanged = column.getColDef().onCellValueChanged; if (typeof onCellValueChanged === 'function') { // to make callback async, do in a timeout setTimeout(function () { return onCellValueChanged(params); }, 0); } if (suppressCellValueChangedEvent) { return; } var event = { type: events_1.Events.EVENT_CELL_VALUE_CHANGED, event: null, rowIndex: rowNode.rowIndex, rowPinned: rowNode.rowPinned, column: params.column, api: params.api, colDef: params.colDef, columnApi: params.columnApi, context: params.context, data: rowNode.data, node: rowNode, oldValue: params.oldValue, newValue: params.newValue, value: params.newValue }; this.eventService.dispatchEvent(event); }; ValueService.prototype.setValueUsingField = function (data, field, newValue, isFieldContainsDots) { if (!field) { return false; } // if no '.', then it's not a deep value var valuesAreSame = false; if (!isFieldContainsDots) { data[field] = newValue; } else { // otherwise it is a deep value, so need to dig for it var fieldPieces = field.split('.'); var currentObject = data; while (fieldPieces.length > 0 && currentObject) { var fieldPiece = fieldPieces.shift(); if (fieldPieces.length === 0) { currentObject[fieldPiece] = newValue; } else { currentObject = currentObject[fieldPiece]; } } } return !valuesAreSame; }; ValueService.prototype.executeFilterValueGetter = function (valueGetter, data, column, rowNode) { var params = { data: data, node: rowNode, column: column, colDef: column.getColDef(), api: this.gridOptionsWrapper.getApi(), columnApi: this.gridOptionsWrapper.getColumnApi(), context: this.gridOptionsWrapper.getContext(), getValue: this.getValueCallback.bind(this, rowNode) }; return this.expressionService.evaluate(valueGetter, params); }; ValueService.prototype.executeValueGetter = function (valueGetter, data, column, rowNode) { var colId = column.getId(); // if inside the same turn, just return back the value we got last time var valueFromCache = this.valueCache.getValue(rowNode, colId); if (valueFromCache !== undefined) { return valueFromCache; } var params = { data: data, node: rowNode, column: column, colDef: column.getColDef(), api: this.gridOptionsWrapper.getApi(), columnApi: this.gridOptionsWrapper.getColumnApi(), context: this.gridOptionsWrapper.getContext(), getValue: this.getValueCallback.bind(this, rowNode) }; var result = this.expressionService.evaluate(valueGetter, params); // if a turn is active, store the value in case the grid asks for it again this.valueCache.setValue(rowNode, colId, result); return result; }; ValueService.prototype.getValueCallback = function (node, field) { var otherColumn = this.columnController.getPrimaryColumn(field); if (otherColumn) { return this.getValue(otherColumn, node); } return null; }; // used by row grouping and pivot, to get key for a row. col can be a pivot col or a row grouping col ValueService.prototype.getKeyForNode = function (col, rowNode) { var value = this.getValue(col, rowNode); var keyCreator = col.getColDef().keyCreator; var result = keyCreator ? keyCreator({ value: value }) : value; // if already a string, or missing, just return it if (typeof result === 'string' || result == null) { return result; } result = String(result); if (result === '[object Object]') { utils_1._.doOnce(function () { console.warn('ag-Grid: a column you are grouping or pivoting by has objects as values. If you want to group by complex objects then either a) use a colDef.keyCreator (se ag-Grid docs) or b) to toString() on the object to return a key'); }, 'getKeyForNode - warn about [object,object]'); } return result; }; __decorate([ context_1.Autowired('gridOptionsWrapper'), __metadata("design:type", gridOptionsWrapper_1.GridOptionsWrapper) ], ValueService.prototype, "gridOptionsWrapper", void 0); __decorate([ context_1.Autowired('expressionService'), __metadata("design:type", expressionService_1.ExpressionService) ], ValueService.prototype, "expressionService", void 0); __decorate([ context_1.Autowired('columnController'), __metadata("design:type", columnController_1.ColumnController) ], ValueService.prototype, "columnController", void 0); __decorate([ context_1.Autowired('eventService'), __metadata("design:type", eventService_1.EventService) ], ValueService.prototype, "eventService", void 0); __decorate([ context_1.Autowired('valueCache'), __metadata("design:type", valueCache_1.ValueCache) ], ValueService.prototype, "valueCache", void 0); __decorate([ context_1.PostConstruct, __metadata("design:type", Function), __metadata("design:paramtypes", []), __metadata("design:returntype", void 0) ], ValueService.prototype, "init", null); ValueService = __decorate([ context_1.Bean('valueService') ], ValueService); return ValueService; }()); exports.ValueService = ValueService;
mit
museways/makers
lib/makers/dsl/maker.rb
515
module Makers module Dsl class Maker < Trait def initialize(name, options={}, &block) @traits = Collections::Traits.new super end def maker(name, overrides={}, &block) options = @options.dup options.delete :aliases options.merge! overrides options.merge! parent: @name Makers.definitions.add Dsl::Maker.new(name, options, &block) end def trait(name, &block) @traits.add name, &block end end end end
mit
MikhailArkhipov/RTVS
src/Host/Client/Impl/Transports/WebSocketClient.cs
1815
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.WebSockets; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.WebSockets.Protocol; namespace Microsoft.R.Host.Client.Transports { internal sealed class WebSocketClient { private readonly ICredentials _serverCredentails; private readonly IEnumerable<string> _subProtocols; private readonly TimeSpan _keepAliveInterval; private readonly Uri _uri; public WebSocketClient(Uri uri, IEnumerable<string> subProtocols, TimeSpan keepAliveInterval, ICredentials serverCredentails = null) { _uri = uri; _subProtocols = subProtocols; _keepAliveInterval = keepAliveInterval; _serverCredentails = serverCredentails; } public async Task<WebSocket> ConnectAsync(CancellationToken cancellationToken) { var socket = new ClientWebSocket(); socket.Options.Credentials = _serverCredentails; socket.Options.KeepAliveInterval = _keepAliveInterval; socket.Options.SetRequestHeader(Constants.Headers.SecWebSocketVersion, Constants.Headers.SupportedVersion); if (_subProtocols.Any()) { socket.Options.SetRequestHeader(Constants.Headers.SecWebSocketProtocol, string.Join(", ", _subProtocols)); } foreach (var sb in _subProtocols) { socket.Options.AddSubProtocol(sb); } await socket.ConnectAsync(_uri, CancellationToken.None); return socket; } } }
mit
MikhailArkhipov/RTVS
src/Unix/Host/Broker/Impl/Services/Utility.cs
8626
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using Microsoft.Common.Core; using Microsoft.Common.Core.OS; using Microsoft.Extensions.Logging; using Microsoft.R.Host.Broker.Sessions; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Serialization; namespace Microsoft.R.Host.Broker.Services { public class Utility { private const string PamInfo = "pam-info"; private const string PamError = "pam-error"; private const string SysError = "unix-error"; private const string JsonError = "json-error"; private const string RtvsResult = "rtvs-result"; private const string RtvsError = "rtvs-error"; public static IProcess RunAsCurrentUser(ILogger<Session> logger, IProcessServices ps, string arguments, string rHomePath, string loadLibPath) { var psi = new ProcessStartInfo { FileName = PathConstants.RunHostBinPath, Arguments = arguments, RedirectStandardError = true, RedirectStandardInput = true, RedirectStandardOutput = true, WorkingDirectory = Environment.GetEnvironmentVariable("PWD") }; // All other should be same as the broker environment. Only these are set based on interpreters. // R_HOME is explictly set on the R-Host. psi.Environment.Add("R_HOME", rHomePath); psi.Environment.Add("LD_LIBRARY_PATH", loadLibPath); return ps.Start(psi); } public static IProcess AuthenticateAndRunAsUser(ILogger<Session> logger, IProcessServices ps, string username, string password, string profileDir, IEnumerable<string> arguments, IDictionary<string, string> environment) { var proc = CreateRunAsUserProcess(ps, true); using (var writer = new BinaryWriter(proc.StandardInput.BaseStream, Encoding.UTF8, true)) { var message = new AuthenticateAndRunMessage() { Username = GetUnixUserName(username), Password = password, Arguments = arguments, Environment = environment.Select(e => $"{e.Key}={e.Value}"), WorkingDirectory = profileDir }; var json = JsonConvert.SerializeObject(message, GetJsonSettings()); var jsonBytes = Encoding.UTF8.GetBytes(json); writer.Write(jsonBytes.Length); writer.Write(jsonBytes); writer.Flush(); } return proc; } public static bool AuthenticateUser(ILogger<IPlatformAuthenticationService> logger, IProcessServices ps, string username, string password, string allowedGroup, out string profileDir) { var retval = false; IProcess proc = null; var userDir = string.Empty; try { proc = CreateRunAsUserProcess(ps, false); using (var writer = new BinaryWriter(proc.StandardInput.BaseStream, Encoding.UTF8, true)) using (var reader = new BinaryReader(proc.StandardOutput.BaseStream, Encoding.UTF8, true)) { var message = new AuthenticationOnlyMessage() { Username = GetUnixUserName(username), Password = password, AllowedGroup = allowedGroup }; var json = JsonConvert.SerializeObject(message, GetJsonSettings()); var jsonBytes = Encoding.UTF8.GetBytes(json); writer.Write(jsonBytes.Length); writer.Write(jsonBytes); writer.Flush(); proc.WaitForExit(3000); if (proc.HasExited && proc.ExitCode == 0) { var size = reader.ReadInt32(); var bytes = reader.ReadBytes(size); var arr = JsonConvert.DeserializeObject<JArray>(Encoding.UTF8.GetString(bytes)); if(arr.Count > 1) { var respType = arr[0].Value<string>(); switch (respType) { case PamInfo: case PamError: var pam = arr[1].Value<string>(); logger.LogCritical(Resources.Error_PAMAuthenticationError.FormatInvariant(pam)); break; case JsonError: var jerror = arr[1].Value<string>(); logger.LogCritical(Resources.Error_RunAsUserJsonError.FormatInvariant(jerror)); break; case RtvsResult: userDir = arr[1].Value<string>(); retval = true; if (userDir.Length == 0) { logger.LogError(Resources.Error_NoProfileDir); } break; case RtvsError: var resource = arr[1].Value<string>(); logger.LogCritical(Resources.Error_RunAsUserFailed.FormatInvariant(Resources.ResourceManager.GetString(resource))); break; } } else { logger.LogCritical(Resources.Error_InvalidRunAsUserResponse); } } else { logger.LogCritical(Resources.Error_AuthFailed, GetRLaunchExitCodeMessage(proc.ExitCode)); } } } catch (Exception ex) { logger.LogCritical(Resources.Error_AuthFailed, ex.Message); } finally { if (proc != null && !proc.HasExited) { try { proc.Kill(); } catch (Exception ex) when (!ex.IsCriticalException()) { } } } profileDir = userDir; return retval; } private static string GetRLaunchExitCodeMessage(int exitcode) { switch (exitcode) { case 200: return Resources.Error_AuthInitFailed; case 201: return Resources.Error_AuthBadInput; case 202: return Resources.Error_AuthNoInput; default: return exitcode.ToString(); } } public static string GetUnixUserName(string source) { // This is needed because the windows credential UI uses domain\username format. // This will not be required if we can show generic credential UI for Linux remote. // <<unix>>\<username>, #unix\<username> or #local\<username> format should be used // to for local accounts only. const string unixPrefix = "<<unix>>\\"; const string unixPrefix2 = "#unix\\"; const string localPrefix = "#local\\"; if (source.StartsWithIgnoreCase(unixPrefix)) { return source.Substring(unixPrefix.Length); } else if (source.StartsWithIgnoreCase(unixPrefix2)) { return source.Substring(unixPrefix2.Length); } else if (source.StartsWithIgnoreCase(localPrefix)) { return source.Substring(localPrefix.Length); } return source; } private static JsonSerializerSettings GetJsonSettings() { return new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }; } private static IProcess CreateRunAsUserProcess(IProcessServices ps, bool quietMode) { var psi = new ProcessStartInfo { FileName = PathConstants.RunAsUserBinPath, Arguments = quietMode ? "-q" : "", RedirectStandardError = true, RedirectStandardInput = true, RedirectStandardOutput = true }; return ps.Start(psi); } } }
mit
MikhailArkhipov/RTVS
src/R/Editor/Impl/Validation/ValidationSentinel.cs
636
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System; using Microsoft.Languages.Core.Text; using Microsoft.R.Core.Parser; namespace Microsoft.R.Editor.Validation.Errors { public class ValidationSentinel : ValidationErrorBase { /// <summary> /// Constructs 'barrier' pseudo error that clears all messages for a given node. /// </summary> public ValidationSentinel() : base(TextRange.EmptyRange, String.Empty, ErrorLocation.Token, ErrorSeverity.Error) { } } }
mit
cdnjs/cdnjs
ajax/libs/material-ui/4.9.5/NativeSelect/NativeSelectInput.js
3329
"use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends")); var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties")); var React = _interopRequireWildcard(require("react")); var _propTypes = _interopRequireDefault(require("prop-types")); var _clsx = _interopRequireDefault(require("clsx")); var _utils = require("@material-ui/utils"); var _capitalize = _interopRequireDefault(require("../utils/capitalize")); /** * @ignore - internal component. */ var NativeSelectInput = React.forwardRef(function NativeSelectInput(props, ref) { var classes = props.classes, className = props.className, disabled = props.disabled, IconComponent = props.IconComponent, inputRef = props.inputRef, _props$variant = props.variant, variant = _props$variant === void 0 ? 'standard' : _props$variant, other = (0, _objectWithoutProperties2.default)(props, ["classes", "className", "disabled", "IconComponent", "inputRef", "variant"]); return React.createElement(React.Fragment, null, React.createElement("select", (0, _extends2.default)({ className: (0, _clsx.default)(classes.root, // TODO v5: merge root and select classes.select, classes[variant], className, disabled && classes.disabled), disabled: disabled, ref: inputRef || ref }, other)), props.multiple ? null : React.createElement(IconComponent, { className: (0, _clsx.default)(classes.icon, classes["icon".concat((0, _capitalize.default)(variant))]) })); }); process.env.NODE_ENV !== "production" ? NativeSelectInput.propTypes = { /** * The option elements to populate the select with. * Can be some `<option>` elements. */ children: _propTypes.default.node, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: _propTypes.default.object.isRequired, /** * The CSS class name of the select element. */ className: _propTypes.default.string, /** * If `true`, the select will be disabled. */ disabled: _propTypes.default.bool, /** * The icon that displays the arrow. */ IconComponent: _propTypes.default.elementType.isRequired, /** * Use that prop to pass a ref to the native select element. * @deprecated */ inputRef: _utils.refType, /** * @ignore */ multiple: _propTypes.default.bool, /** * Name attribute of the `select` or hidden `input` element. */ name: _propTypes.default.string, /** * Callback function fired when a menu item is selected. * * @param {object} event The event source of the callback. * You can pull out the new value by accessing `event.target.value` (string). */ onChange: _propTypes.default.func, /** * The input value. */ value: _propTypes.default.any, /** * The variant to use. */ variant: _propTypes.default.oneOf(['standard', 'outlined', 'filled']) } : void 0; var _default = NativeSelectInput; exports.default = _default;
mit
cdnjs/cdnjs
ajax/libs/material-ui/4.9.10/OutlinedInput/NotchedOutline.js
5416
"use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = exports.styles = void 0; var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty")); var _extends3 = _interopRequireDefault(require("@babel/runtime/helpers/extends")); var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties")); var React = _interopRequireWildcard(require("react")); var _propTypes = _interopRequireDefault(require("prop-types")); var _clsx = _interopRequireDefault(require("clsx")); var _withStyles = _interopRequireDefault(require("../styles/withStyles")); var _useTheme = _interopRequireDefault(require("../styles/useTheme")); var _capitalize = _interopRequireDefault(require("../utils/capitalize")); var styles = function styles(theme) { return { /* Styles applied to the root element. */ root: { position: 'absolute', bottom: 0, right: 0, top: -5, left: 0, margin: 0, padding: 0, paddingLeft: 8, pointerEvents: 'none', borderRadius: 'inherit', borderStyle: 'solid', borderWidth: 1 }, /* Styles applied to the legend element when `labelWidth` is provided. */ legend: { textAlign: 'left', padding: 0, lineHeight: '11px', // sync with `height` in `legend` styles transition: theme.transitions.create('width', { duration: 150, easing: theme.transitions.easing.easeOut }) }, /* Styles applied to the legend element. */ legendLabelled: { display: 'block', width: 'auto', textAlign: 'left', padding: 0, height: 11, // sync with `lineHeight` in `legend` styles fontSize: '0.75em', visibility: 'hidden', maxWidth: 0.01, transition: theme.transitions.create('max-width', { duration: 50, easing: theme.transitions.easing.easeOut }), '& > span': { paddingLeft: 5, paddingRight: 5, display: 'inline-block' } }, /* Styles applied to the legend element is notched. */ legendNotched: { maxWidth: 1000, transition: theme.transitions.create('max-width', { duration: 100, easing: theme.transitions.easing.easeOut, delay: 50 }) } }; }; /** * @ignore - internal component. */ exports.styles = styles; var NotchedOutline = React.forwardRef(function NotchedOutline(props, ref) { var children = props.children, classes = props.classes, className = props.className, label = props.label, labelWidthProp = props.labelWidth, notched = props.notched, style = props.style, other = (0, _objectWithoutProperties2.default)(props, ["children", "classes", "className", "label", "labelWidth", "notched", "style"]); var theme = (0, _useTheme.default)(); var align = theme.direction === 'rtl' ? 'right' : 'left'; if (label !== undefined) { return /*#__PURE__*/React.createElement("fieldset", (0, _extends3.default)({ "aria-hidden": true, className: (0, _clsx.default)(classes.root, className), ref: ref, style: style }, other), /*#__PURE__*/React.createElement("legend", { className: (0, _clsx.default)(classes.legendLabelled, notched && classes.legendNotched) }, label ? /*#__PURE__*/React.createElement("span", null, label) : /*#__PURE__*/React.createElement("span", { dangerouslySetInnerHTML: { __html: '&#8203;' } }))); } var labelWidth = labelWidthProp > 0 ? labelWidthProp * 0.75 + 8 : 0.01; return /*#__PURE__*/React.createElement("fieldset", (0, _extends3.default)({ "aria-hidden": true, style: (0, _extends3.default)((0, _defineProperty2.default)({}, "padding".concat((0, _capitalize.default)(align)), 8), style), className: (0, _clsx.default)(classes.root, className), ref: ref }, other), /*#__PURE__*/React.createElement("legend", { className: classes.legend, style: { // IE 11: fieldset with legend does not render // a border radius. This maintains consistency // by always having a legend rendered width: notched ? labelWidth : 0.01 } }, /*#__PURE__*/React.createElement("span", { dangerouslySetInnerHTML: { __html: '&#8203;' } }))); }); process.env.NODE_ENV !== "production" ? NotchedOutline.propTypes = { /** * The content of the component. */ children: _propTypes.default.node, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: _propTypes.default.object, /** * @ignore */ className: _propTypes.default.string, /** * The label. */ label: _propTypes.default.node, /** * The width of the label. */ labelWidth: _propTypes.default.number.isRequired, /** * If `true`, the outline is notched to accommodate the label. */ notched: _propTypes.default.bool.isRequired, /** * @ignore */ style: _propTypes.default.object } : void 0; var _default = (0, _withStyles.default)(styles, { name: 'PrivateNotchedOutline' })(NotchedOutline); exports.default = _default;
mit
maxeler/eclipse
eclipse.jdt.ui/org.eclipse.jdt.ui.tests.refactoring/resources/IntroduceFactory/Bugzilla/74759/Test.java
294
package p; public class Test { public/*[*/Test/*]*/(Test tal) { return; } public static void main(String[] args) { final Test test= new Test(new Test(null)); System.out.println(new Test(decorate(new Test(null)))); } private static Test decorate(Test test) { return test; } }
epl-1.0
echoes-tech/eclipse.jsdt.core
org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/SearchEngine.java
40469
/******************************************************************************* * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.wst.jsdt.core.search; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.wst.jsdt.core.IJavaScriptElement; import org.eclipse.wst.jsdt.core.IJavaScriptUnit; import org.eclipse.wst.jsdt.core.IType; import org.eclipse.wst.jsdt.core.JavaScriptModelException; import org.eclipse.wst.jsdt.core.WorkingCopyOwner; import org.eclipse.wst.jsdt.core.compiler.CharOperation; import org.eclipse.wst.jsdt.internal.compiler.env.AccessRuleSet; import org.eclipse.wst.jsdt.internal.compiler.util.SimpleSetOfCharArray; import org.eclipse.wst.jsdt.internal.core.JavaModelManager; import org.eclipse.wst.jsdt.internal.core.search.BasicSearchEngine; import org.eclipse.wst.jsdt.internal.core.search.IndexQueryRequestor; import org.eclipse.wst.jsdt.internal.core.search.JavaSearchParticipant; import org.eclipse.wst.jsdt.internal.core.search.PatternSearchJob; import org.eclipse.wst.jsdt.internal.core.search.TypeNameMatchRequestorWrapper; import org.eclipse.wst.jsdt.internal.core.search.TypeNameRequestorWrapper; import org.eclipse.wst.jsdt.internal.core.search.indexing.IIndexConstants; import org.eclipse.wst.jsdt.internal.core.search.indexing.IndexManager; import org.eclipse.wst.jsdt.internal.core.search.matching.TypeDeclarationPattern; import org.eclipse.wst.jsdt.internal.core.search.matching.TypeSynonymsPattern; /** * A {@link SearchEngine} searches for JavaScript elements following a search pattern. * The search can be limited to a search scope. * <p> * Various search patterns can be created using the factory methods * {@link SearchPattern#createPattern(String, int, int, int)}, {@link SearchPattern#createPattern(IJavaScriptElement, int)}, * {@link SearchPattern#createOrPattern(SearchPattern, SearchPattern)}. * </p> * <p>For example, one can search for references to a method in the hierarchy of a type, * or one can search for the declarations of types starting with "Abstract" in a project. * </p> * <p> * This class may be instantiated; it is not intended to be subclassed. * </p> * * Provisional API: This class/interface is part of an interim API that is still under development and expected to * change significantly before reaching stability. It is being made available at this early stage to solicit feedback * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken * (repeatedly) as the API evolves. */ public class SearchEngine { // Search engine now uses basic engine functionalities private BasicSearchEngine basicEngine; /** * Creates a new search engine. */ public SearchEngine() { this.basicEngine = new BasicSearchEngine(); } /** * Creates a new search engine with a list of working copies that will take precedence over * their original javascript unit s in the subsequent search operations. * <p> * Note that passing an empty working copy will be as if the original compilation * unit had been deleted.</p> * <p> * Since 3.0 the given working copies take precedence over primary working copies (if any). * * @param workingCopies the working copies that take precedence over their original javascript unit s * */ public SearchEngine(IJavaScriptUnit[] workingCopies) { this.basicEngine = new BasicSearchEngine(workingCopies); } /** * Creates a new search engine with the given working copy owner. * The working copies owned by this owner will take precedence over * the primary javascript unit s in the subsequent search operations. * * @param workingCopyOwner the owner of the working copies that take precedence over their original javascript unit s * */ public SearchEngine(WorkingCopyOwner workingCopyOwner) { this.basicEngine = new BasicSearchEngine(workingCopyOwner); } /** * Returns a JavaScript search scope limited to the hierarchy of the given type. * The JavaScript elements resulting from a search with this scope will * be types in this hierarchy, or members of the types in this hierarchy. * * @param type the focus of the hierarchy scope * @return a new hierarchy scope * @exception JavaScriptModelException if the hierarchy could not be computed on the given type */ public static IJavaScriptSearchScope createHierarchyScope(IType type) throws JavaScriptModelException { return BasicSearchEngine.createHierarchyScope(type); } /** * Returns a JavaScript search scope limited to the hierarchy of the given type. * When the hierarchy is computed, the types defined in the working copies owned * by the given owner take precedence over the original javascript unit s. * The JavaScript elements resulting from a search with this scope will * be types in this hierarchy, or members of the types in this hierarchy. * * @param type the focus of the hierarchy scope * @param owner the owner of working copies that take precedence over original javascript unit s * @return a new hierarchy scope * @exception JavaScriptModelException if the hierarchy could not be computed on the given type * */ public static IJavaScriptSearchScope createHierarchyScope(IType type, WorkingCopyOwner owner) throws JavaScriptModelException { return BasicSearchEngine.createHierarchyScope(type, owner); } /** * Returns a JavaScript search scope limited to the given JavaScript elements. * The JavaScript elements resulting from a search with this scope will * be children of the given elements. * <p> * If an element is an IJavaScriptProject, then the project's source folders, * its jars (external and internal) and its referenced projects (with their source * folders and jars, recursively) will be included. * If an element is an IPackageFragmentRoot, then only the package fragments of * this package fragment root will be included. * If an element is an IPackageFragment, then only the javascript unit and class * files of this package fragment will be included. Subpackages will NOT be * included.</p> * <p> * In other words, this is equivalent to using SearchEngine.createJavaSearchScope(elements, true).</p> * * @param elements the JavaScript elements the scope is limited to * @return a new JavaScript search scope * */ public static IJavaScriptSearchScope createJavaSearchScope(IJavaScriptElement[] elements) { return BasicSearchEngine.createJavaSearchScope(elements); } /** * Returns a JavaScript search scope limited to the given JavaScript elements. * The JavaScript elements resulting from a search with this scope will * be children of the given elements. * * If an element is an IJavaScriptProject, then the project's source folders, * its jars (external and internal) and - if specified - its referenced projects * (with their source folders and jars, recursively) will be included. * If an element is an IPackageFragmentRoot, then only the package fragments of * this package fragment root will be included. * If an element is an IPackageFragment, then only the javascript unit and class * files of this package fragment will be included. Subpackages will NOT be * included. * * @param elements the JavaScript elements the scope is limited to * @param includeReferencedProjects a flag indicating if referenced projects must be * recursively included * @return a new JavaScript search scope * */ public static IJavaScriptSearchScope createJavaSearchScope(IJavaScriptElement[] elements, boolean includeReferencedProjects) { return BasicSearchEngine.createJavaSearchScope(elements, includeReferencedProjects); } /** * Returns a JavaScript search scope limited to the given JavaScript elements. * The JavaScript elements resulting from a search with this scope will * be children of the given elements. * * If an element is an IJavaScriptProject, then it includes: * - its source folders if IJavaScriptSearchScope.SOURCES is specified, * - its application libraries (internal and external jars, class folders that are on the raw includepath, * or the ones that are coming from a includepath path variable, * or the ones that are coming from a includepath container with the K_APPLICATION kind) * if IJavaScriptSearchScope.APPLICATION_LIBRARIES is specified * - its system libraries (internal and external jars, class folders that are coming from an * IJsGlobalScopeContainer with the K_SYSTEM kind) * if IJavaScriptSearchScope.APPLICATION_LIBRARIES is specified * - its referenced projects (with their source folders and jars, recursively) * if IJavaScriptSearchScope.REFERENCED_PROJECTS is specified. * If an element is an IPackageFragmentRoot, then only the package fragments of * this package fragment root will be included. * If an element is an IPackageFragment, then only the javascript unit and class * files of this package fragment will be included. Subpackages will NOT be * included. * * @param elements the JavaScript elements the scope is limited to * @param includeMask the bit-wise OR of all include types of interest * @return a new JavaScript search scope * @see IJavaScriptSearchScope#SOURCES * @see IJavaScriptSearchScope#APPLICATION_LIBRARIES * @see IJavaScriptSearchScope#SYSTEM_LIBRARIES * @see IJavaScriptSearchScope#REFERENCED_PROJECTS * */ public static IJavaScriptSearchScope createJavaSearchScope(IJavaScriptElement[] elements, int includeMask) { return BasicSearchEngine.createJavaSearchScope(elements, includeMask); } /** * Create a type name match on a given type with specific modifiers. * * @param type The javascript model handle of the type * @param modifiers Modifiers of the type * @return A non-null match on the given type. * */ public static TypeNameMatch createTypeNameMatch(IType type, int modifiers) { return BasicSearchEngine.createTypeNameMatch(type, modifiers); } /** * Returns a JavaScript search scope with the workspace as the only limit. * * @return a new workspace scope */ public static IJavaScriptSearchScope createWorkspaceScope() { return BasicSearchEngine.createWorkspaceScope(); } /** * Returns a new default JavaScript search participant. * * @return a new default JavaScript search participant * */ public static SearchParticipant getDefaultSearchParticipant() { return BasicSearchEngine.getDefaultSearchParticipant(); } /** * Searches for matches of a given search pattern. Search patterns can be created using helper * methods (from a String pattern or a JavaScript element) and encapsulate the description of what is * being searched (for example, search method declarations in a case sensitive way). * * @param pattern the pattern to search * @param participants the particpants in the search * @param scope the search scope * @param requestor the requestor to report the matches to * @param monitor the progress monitor used to report progress * @exception CoreException if the search failed. Reasons include: * <ul> * <li>the includepath is incorrectly set</li> * </ul> * */ public void search(SearchPattern pattern, SearchParticipant[] participants, IJavaScriptSearchScope scope, SearchRequestor requestor, IProgressMonitor monitor) throws CoreException { this.basicEngine.search(pattern, participants, scope, requestor, monitor); } /** * Searches for all top-level types and member types in the given scope. * The search can be selecting specific types (given a package name using specific match mode * and/or a type name using another specific match mode). * * @param packageName the full name of the package of the searched types, or a prefix for this * package, or a wild-carded string for this package. * May be <code>null</code>, then any package name is accepted. * @param typeName the dot-separated qualified name of the searched type (the qualification include * the enclosing types if the searched type is a member type), or a prefix * for this type, or a wild-carded string for this type. * May be <code>null</code>, then any type name is accepted. * @param packageMatchRule ignored * @param typeMatchRule one of * <ul> * <li>{@link SearchPattern#R_EXACT_MATCH} if the package name and type name are the full names * of the searched types.</li> * <li>{@link SearchPattern#R_PREFIX_MATCH} if the package name and type name are prefixes of the names * of the searched types.</li> * <li>{@link SearchPattern#R_PATTERN_MATCH} if the package name and type name contain wild-cards.</li> * <li>{@link SearchPattern#R_CAMELCASE_MATCH} if type name are camel case of the names of the searched types.</li> * </ul> * combined with {@link SearchPattern#R_CASE_SENSITIVE}, * e.g. {@link SearchPattern#R_EXACT_MATCH} | {@link SearchPattern#R_CASE_SENSITIVE} if an exact and case sensitive match is requested, * or {@link SearchPattern#R_PREFIX_MATCH} if a prefix non case sensitive match is requested. * @param searchFor determines the nature of the searched elements * <ul> * <li>{@link IJavaScriptSearchConstants#CLASS}: only look for classes</li> * <li>{@link IJavaScriptSearchConstants#INTERFACE}: only look for interfaces</li> * <li>{@link IJavaScriptSearchConstants#ENUM}: only look for enumeration</li> * <li>{@link IJavaScriptSearchConstants#ANNOTATION_TYPE}: only look for annotation type</li> * <li>{@link IJavaScriptSearchConstants#CLASS_AND_ENUM}: only look for classes and enumerations</li> * <li>{@link IJavaScriptSearchConstants#CLASS_AND_INTERFACE}: only look for classes and interfaces</li> * <li>{@link IJavaScriptSearchConstants#TYPE}: look for all types (ie. classes, interfaces, enum and annotation types)</li> * </ul> * @param scope the scope to search in * @param nameRequestor the requestor that collects the results of the search * @param waitingPolicy one of * <ul> * <li>{@link IJavaScriptSearchConstants#FORCE_IMMEDIATE_SEARCH} if the search should start immediately</li> * <li>{@link IJavaScriptSearchConstants#CANCEL_IF_NOT_READY_TO_SEARCH} if the search should be cancelled if the * underlying indexer has not finished indexing the workspace</li> * <li>{@link IJavaScriptSearchConstants#WAIT_UNTIL_READY_TO_SEARCH} if the search should wait for the * underlying indexer to finish indexing the workspace</li> * </ul> * @param progressMonitor the progress monitor to report progress to, or <code>null</code> if no progress * monitor is provided * @exception JavaScriptModelException if the search failed. Reasons include: * <ul> * <li>the includepath is incorrectly set</li> * </ul> * */ public void searchAllTypeNames( final char[] packageName, final int packageMatchRule, //ignored final char[] typeName, final int typeMatchRule, int searchFor, IJavaScriptSearchScope scope, final TypeNameRequestor nameRequestor, int waitingPolicy, IProgressMonitor progressMonitor) throws JavaScriptModelException { TypeNameRequestorWrapper requestorWrapper = new TypeNameRequestorWrapper(nameRequestor); this.basicEngine.searchAllTypeNames(packageName, typeName, typeMatchRule, scope, requestorWrapper, waitingPolicy, progressMonitor); } /** * Searches for all top-level types and member types in the given scope. * <p> * Provided {@link TypeNameMatchRequestor} requestor will collect {@link TypeNameMatch} * matches found during the search. * </p> * * @param prefix The prefix could be part of the qualification or simple name for a type, * or it could be a camel case statement for a simple name of a type. * @param typeMatchRule one of * <ul> * <li>{@link SearchPattern#R_EXACT_MATCH} if the package name and type name are the full names * of the searched types.</li> * <li>{@link SearchPattern#R_PREFIX_MATCH} if the package name and type name are prefixes of the names * of the searched types.</li> * <li>{@link SearchPattern#R_PATTERN_MATCH} if the package name and type name contain wild-cards.</li> * <li>{@link SearchPattern#R_CAMELCASE_MATCH} if type name are camel case of the names of the searched types.</li> * </ul> * combined with {@link SearchPattern#R_CASE_SENSITIVE}, * e.g. {@link SearchPattern#R_EXACT_MATCH} | {@link SearchPattern#R_CASE_SENSITIVE} if an exact and case sensitive match is requested, * or {@link SearchPattern#R_PREFIX_MATCH} if a prefix non case sensitive match is requested. * @param searchFor determines the nature of the searched elements * <ul> * <li>{@link IJavaScriptSearchConstants#CLASS}: only look for classes</li> * <li>{@link IJavaScriptSearchConstants#INTERFACE}: only look for interfaces</li> * <li>{@link IJavaScriptSearchConstants#ENUM}: only look for enumeration</li> * <li>{@link IJavaScriptSearchConstants#ANNOTATION_TYPE}: only look for annotation type</li> * <li>{@link IJavaScriptSearchConstants#CLASS_AND_ENUM}: only look for classes and enumerations</li> * <li>{@link IJavaScriptSearchConstants#CLASS_AND_INTERFACE}: only look for classes and interfaces</li> * <li>{@link IJavaScriptSearchConstants#TYPE}: look for all types (ie. classes, interfaces, enum and annotation types)</li> * </ul> * @param scope the scope to search in * @param nameMatchRequestor the {@link TypeNameMatchRequestor requestor} that collects * {@link TypeNameMatch matches} of the search. * @param waitingPolicy one of * <ul> * <li>{@link IJavaScriptSearchConstants#FORCE_IMMEDIATE_SEARCH} if the search should start immediately</li> * <li>{@link IJavaScriptSearchConstants#CANCEL_IF_NOT_READY_TO_SEARCH} if the search should be cancelled if the * underlying indexer has not finished indexing the workspace</li> * <li>{@link IJavaScriptSearchConstants#WAIT_UNTIL_READY_TO_SEARCH} if the search should wait for the * underlying indexer to finish indexing the workspace</li> * </ul> * @param progressMonitor the progress monitor to report progress to, or <code>null</code> if no progress * monitor is provided * @exception JavaScriptModelException if the search failed. Reasons include: * <ul> * <li>the includepath is incorrectly set</li> * </ul> * */ public void searchAllTypeNames( final char[] prefix, final int typeMatchRule, int searchFor, IJavaScriptSearchScope scope, final TypeNameMatchRequestor nameMatchRequestor, int waitingPolicy, IProgressMonitor progressMonitor) throws JavaScriptModelException { TypeNameMatchRequestorWrapper requestorWrapper = new TypeNameMatchRequestorWrapper(nameMatchRequestor, scope); this.basicEngine.searchAllTypeNames(prefix, typeMatchRule, scope, requestorWrapper, waitingPolicy, progressMonitor); } /** * Searches for all top-level types and member types in the given scope. * The search can be selecting specific types (given a package name using specific match mode * and/or a type name using another specific match mode). * <p> * Provided {@link TypeNameMatchRequestor} requestor will collect {@link TypeNameMatch} * matches found during the search. * </p> * * @param packageName the full name of the package of the searched types, or a prefix for this * package, or a wild-carded string for this package. * May be <code>null</code>, then any package name is accepted. * @param packageMatchRule IGNORED * @param typeName the dot-separated qualified name of the searched type (the qualification include * the enclosing types if the searched type is a member type), or a prefix * for this type, or a wild-carded string for this type. * May be <code>null</code>, then any type name is accepted. * @param typeMatchRule one of * <ul> * <li>{@link SearchPattern#R_EXACT_MATCH} if the package name and type name are the full names * of the searched types.</li> * <li>{@link SearchPattern#R_PREFIX_MATCH} if the package name and type name are prefixes of the names * of the searched types.</li> * <li>{@link SearchPattern#R_PATTERN_MATCH} if the package name and type name contain wild-cards.</li> * <li>{@link SearchPattern#R_CAMELCASE_MATCH} if type name are camel case of the names of the searched types.</li> * </ul> * combined with {@link SearchPattern#R_CASE_SENSITIVE}, * e.g. {@link SearchPattern#R_EXACT_MATCH} | {@link SearchPattern#R_CASE_SENSITIVE} if an exact and case sensitive match is requested, * or {@link SearchPattern#R_PREFIX_MATCH} if a prefix non case sensitive match is requested. * @param searchFor determines the nature of the searched elements * <ul> * <li>{@link IJavaScriptSearchConstants#CLASS}: only look for classes</li> * <li>{@link IJavaScriptSearchConstants#INTERFACE}: only look for interfaces</li> * <li>{@link IJavaScriptSearchConstants#ENUM}: only look for enumeration</li> * <li>{@link IJavaScriptSearchConstants#ANNOTATION_TYPE}: only look for annotation type</li> * <li>{@link IJavaScriptSearchConstants#CLASS_AND_ENUM}: only look for classes and enumerations</li> * <li>{@link IJavaScriptSearchConstants#CLASS_AND_INTERFACE}: only look for classes and interfaces</li> * <li>{@link IJavaScriptSearchConstants#TYPE}: look for all types (ie. classes, interfaces, enum and annotation types)</li> * </ul> * @param scope the scope to search in * @param nameMatchRequestor the {@link TypeNameMatchRequestor requestor} that collects * {@link TypeNameMatch matches} of the search. * @param waitingPolicy one of * <ul> * <li>{@link IJavaScriptSearchConstants#FORCE_IMMEDIATE_SEARCH} if the search should start immediately</li> * <li>{@link IJavaScriptSearchConstants#CANCEL_IF_NOT_READY_TO_SEARCH} if the search should be cancelled if the * underlying indexer has not finished indexing the workspace</li> * <li>{@link IJavaScriptSearchConstants#WAIT_UNTIL_READY_TO_SEARCH} if the search should wait for the * underlying indexer to finish indexing the workspace</li> * </ul> * @param progressMonitor the progress monitor to report progress to, or <code>null</code> if no progress * monitor is provided * @exception JavaScriptModelException if the search failed. Reasons include: * <ul> * <li>the includepath is incorrectly set</li> * </ul> * */ public void searchAllTypeNames( final char[] packageName, final int packageMatchRule, //ignored final char[] typeName, final int typeMatchRule, int searchFor, IJavaScriptSearchScope scope, final TypeNameMatchRequestor nameMatchRequestor, int waitingPolicy, IProgressMonitor progressMonitor) throws JavaScriptModelException { TypeNameMatchRequestorWrapper requestorWrapper = new TypeNameMatchRequestorWrapper(nameMatchRequestor, scope); this.basicEngine.searchAllTypeNames(packageName, typeName, typeMatchRule, scope, requestorWrapper, waitingPolicy, progressMonitor); } /** * Searches for all top-level types and member types in the given scope matching any of the given qualifications * and type names in a case sensitive way. * * @param qualifications the qualified name of the package/enclosing type of the searched types. * May be <code>null</code>, then any package name is accepted. * @param typeNames the simple names of the searched types. * If this parameter is <code>null</code>, then no type will be found. * @param scope the scope to search in * @param nameRequestor the requestor that collects the results of the search * @param waitingPolicy one of * <ul> * <li>{@link IJavaScriptSearchConstants#FORCE_IMMEDIATE_SEARCH} if the search should start immediately</li> * <li>{@link IJavaScriptSearchConstants#CANCEL_IF_NOT_READY_TO_SEARCH} if the search should be cancelled if the * underlying indexer has not finished indexing the workspace</li> * <li>{@link IJavaScriptSearchConstants#WAIT_UNTIL_READY_TO_SEARCH} if the search should wait for the * underlying indexer to finish indexing the workspace</li> * </ul> * @param progressMonitor the progress monitor to report progress to, or <code>null</code> if no progress * monitor is provided * @exception JavaScriptModelException if the search failed. Reasons include: * <ul> * <li>the includepath is incorrectly set</li> * </ul> * */ public void searchAllTypeNames( final char[][] qualifications, final char[][] typeNames, IJavaScriptSearchScope scope, final TypeNameRequestor nameRequestor, int waitingPolicy, IProgressMonitor progressMonitor) throws JavaScriptModelException { TypeNameRequestorWrapper requestorWrapper = new TypeNameRequestorWrapper(nameRequestor); this.basicEngine.searchAllTypeNames( qualifications, typeNames, SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE, scope, requestorWrapper, waitingPolicy, progressMonitor); } /** * Searches for all top-level types and member types in the given scope matching any of the given qualifications * and type names in a case sensitive way. * <p> * Provided {@link TypeNameMatchRequestor} requestor will collect {@link TypeNameMatch} * matches found during the search. * </p> * * @param qualifications the qualified name of the package/enclosing type of the searched types. * May be <code>null</code>, then any package name is accepted. * @param typeNames the simple names of the searched types. * If this parameter is <code>null</code>, then no type will be found. * @param scope the scope to search in * @param nameMatchRequestor the {@link TypeNameMatchRequestor requestor} that collects * {@link TypeNameMatch matches} of the search. * @param waitingPolicy one of * <ul> * <li>{@link IJavaScriptSearchConstants#FORCE_IMMEDIATE_SEARCH} if the search should start immediately</li> * <li>{@link IJavaScriptSearchConstants#CANCEL_IF_NOT_READY_TO_SEARCH} if the search should be cancelled if the * underlying indexer has not finished indexing the workspace</li> * <li>{@link IJavaScriptSearchConstants#WAIT_UNTIL_READY_TO_SEARCH} if the search should wait for the * underlying indexer to finish indexing the workspace</li> * </ul> * @param progressMonitor the progress monitor to report progress to, or <code>null</code> if no progress * monitor is provided * @exception JavaScriptModelException if the search failed. Reasons include: * <ul> * <li>the includepath is incorrectly set</li> * </ul> * */ public void searchAllTypeNames( final char[][] qualifications, final char[][] typeNames, IJavaScriptSearchScope scope, final TypeNameMatchRequestor nameMatchRequestor, int waitingPolicy, IProgressMonitor progressMonitor) throws JavaScriptModelException { TypeNameMatchRequestorWrapper requestorWrapper = new TypeNameMatchRequestorWrapper(nameMatchRequestor, scope); this.basicEngine.searchAllTypeNames( qualifications, typeNames, SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE, scope, requestorWrapper, waitingPolicy, progressMonitor); } /** * Searches for all declarations of the fields accessed in the given element. * The element can be a javascript unit , a source type, or a source method. * Reports the field declarations using the given requestor. * <p> * Consider the following code: * <code> * <pre> * class A { * int field1; * } * class B extends A { * String value; * } * class X { * void test() { * B b = new B(); * System.out.println(b.value + b.field1); * }; * } * </pre> * </code> * then searching for declarations of accessed fields in method * <code>X.test()</code> would collect the fields * <code>B.value</code> and <code>A.field1</code>. * </p> * * @param enclosingElement the method, type, or javascript unit to be searched in * @param requestor a callback object to which each match is reported * @param monitor the progress monitor used to report progress * @exception JavaScriptModelException if the search failed. Reasons include: * <ul> * <li>the element doesn't exist</li> * <li>the includepath is incorrectly set</li> * </ul> * */ public void searchDeclarationsOfAccessedFields(IJavaScriptElement enclosingElement, SearchRequestor requestor, IProgressMonitor monitor) throws JavaScriptModelException { this.basicEngine.searchDeclarationsOfAccessedFields(enclosingElement, requestor, monitor); } /** * Searches for all declarations of the types referenced in the given element. * The element can be a javascript unit , a source type, or a source method. * Reports the type declarations using the given requestor. * <p> * Consider the following code: * <code> * <pre> * class A { * } * class B extends A { * } * interface I { * int VALUE = 0; * } * class X { * void test() { * B b = new B(); * this.foo(b, I.VALUE); * }; * } * </pre> * </code> * then searching for declarations of referenced types in method <code>X.test()</code> * would collect the class <code>B</code> and the interface <code>I</code>. * </p> * * @param enclosingElement the method, type, or javascript unit to be searched in * @param requestor a callback object to which each match is reported * @param monitor the progress monitor used to report progress * @exception JavaScriptModelException if the search failed. Reasons include: * <ul> * <li>the element doesn't exist</li> * <li>the includepath is incorrectly set</li> * </ul> * */ public void searchDeclarationsOfReferencedTypes(IJavaScriptElement enclosingElement, SearchRequestor requestor, IProgressMonitor monitor) throws JavaScriptModelException { this.basicEngine.searchDeclarationsOfReferencedTypes(enclosingElement, requestor, monitor); } /** * Searches for all declarations of the methods invoked in the given element. * The element can be a javascript unit , a source type, or a source method. * Reports the method declarations using the given requestor. * <p> * Consider the following code: * <code> * <pre> * class A { * void foo() {}; * void bar() {}; * } * class B extends A { * void foo() {}; * } * class X { * void test() { * A a = new B(); * a.foo(); * B b = (B)a; * b.bar(); * }; * } * </pre> * </code> * then searching for declarations of sent messages in method * <code>X.test()</code> would collect the methods * <code>A.foo()</code>, <code>B.foo()</code>, and <code>A.bar()</code>. * </p> * * @param enclosingElement the method, type, or javascript unit to be searched in * @param requestor a callback object to which each match is reported * @param monitor the progress monitor used to report progress * @exception JavaScriptModelException if the search failed. Reasons include: * <ul> * <li>the element doesn't exist</li> * <li>the includepath is incorrectly set</li> * </ul> * */ public void searchDeclarationsOfSentMessages(IJavaScriptElement enclosingElement, SearchRequestor requestor, IProgressMonitor monitor) throws JavaScriptModelException { this.basicEngine.searchDeclarationsOfSentMessages(enclosingElement, requestor, monitor); } /** * <p> * Gets all the names of subtypes of a given type name in the given * scope. * </p> * * @param typeName * name of the type whose subtype names will be found * @param scope * to search in for all the subtypes of the given type name * @param waitingPolicy * one of * <ul> * <li> * {@link IJavaScriptSearchConstants#FORCE_IMMEDIATE_SEARCH} if * the search should start immediately</li> * <li> * {@link IJavaScriptSearchConstants#CANCEL_IF_NOT_READY_TO_SEARCH} * if the search should be cancelled if the underlying indexer * has not finished indexing the workspace</li> * <li> * {@link IJavaScriptSearchConstants#WAIT_UNTIL_READY_TO_SEARCH} * if the search should wait for the underlying indexer to * finish indexing the workspace</li> * </ul> * @param progressMonitor * monitor to report progress to * * @return List of type names that are the subtypes of the given type * name, if there are no subtypes then the list will only contain * the given type name. The given type name is ALWAYS the first * element in the list. */ public static char[][] getAllSubtypeNames(char[] typeName, IJavaScriptSearchScope scope, int waitingPolicy, IProgressMonitor progressMonitor) { final IProgressMonitor monitor = progressMonitor != null ? progressMonitor : new NullProgressMonitor(); //list of found names final SimpleSetOfCharArray subtypeNames = new SimpleSetOfCharArray(); // queue of types to search for synonyms for final LinkedList searchQueue = new LinkedList(); searchQueue.add(typeName); IndexManager indexManager = JavaModelManager.getJavaModelManager().getIndexManager(); while (!searchQueue.isEmpty()) { char[] searchName = (char[]) searchQueue.remove(0); if (subtypeNames.includes(searchName)) continue; subtypeNames.add(searchName); char[][] synonyms = getAllSynonyms(searchName, scope, waitingPolicy, null); for (int i = 0; i < synonyms.length; i++) { if (!subtypeNames.includes(synonyms[i])) { searchQueue.add(synonyms[i]); } } /* * create pattern and job to search for subtypes of the parent * type */ TypeDeclarationPattern subtypePattern = new TypeDeclarationPattern(IIndexConstants.ONE_STAR, IIndexConstants.ONE_STAR, new char[][]{searchName}, SearchPattern.R_PATTERN_MATCH | SearchPattern.R_CASE_SENSITIVE); // run the search indexManager.performConcurrentJob(new PatternSearchJob(subtypePattern, new JavaSearchParticipant(), scope, new IndexQueryRequestor() { public boolean acceptIndexMatch(String documentPath, SearchPattern indexRecord, SearchParticipant participant, AccessRuleSet access) { TypeDeclarationPattern record = (TypeDeclarationPattern) indexRecord; char[] subtype = CharOperation.concat(record.qualification, record.simpleName, IIndexConstants.DOT); if (!subtypeNames.includes(subtype)) { searchQueue.add(subtype); } return true; } }), waitingPolicy, new NullProgressMonitor() { public void setCanceled(boolean value) { monitor.setCanceled(value); } public boolean isCanceled() { return monitor.isCanceled(); } }); } char[][] names = new char[subtypeNames.elementSize][]; subtypeNames.asArray(names); return names; } /** * <p> * Gets all the synonyms of a given type, including itself, in the given * scope. * </p> * * <p> * <b>NOTE:</b> It is guaranteed that itself will be the first synonym in * the list. * </p> * * @param typeName * name of the type to get all the synonyms for * @param scope * to search in for all the synonyms of the given type * @param waitingPolicy * one of * <ul> * <li> * {@link IJavaScriptSearchConstants#FORCE_IMMEDIATE_SEARCH} if * the search should start immediately</li> * <li> * {@link IJavaScriptSearchConstants#CANCEL_IF_NOT_READY_TO_SEARCH} * if the search should be cancelled if the underlying indexer * has not finished indexing the workspace</li> * <li> * {@link IJavaScriptSearchConstants#WAIT_UNTIL_READY_TO_SEARCH} * if the search should wait for the underlying indexer to * finish indexing the workspace</li> * </ul> * @param progressMonitor * monitor to report progress to * * @return List of type names that are the synonyms of the given type * name, if there are non synonyms then the list will only contain * the given type name. The given type name is ALWAYS the first * element in the list. */ public static char[][] getAllSynonyms(char[] typeName, IJavaScriptSearchScope scope, int waitingPolicy, IProgressMonitor progressMonitor) { final IProgressMonitor monitor = progressMonitor != null ? progressMonitor : new NullProgressMonitor(); //list of found synonyms final List allSynonyms = new ArrayList(); allSynonyms.add(typeName); //queue of types to search for synonyms for final LinkedList searchForSynonyms = new LinkedList(); searchForSynonyms.add(typeName); //for each synonyms search of synonyms of that synonym IndexManager indexManager = JavaModelManager.getJavaModelManager().getIndexManager(); while (!searchForSynonyms.isEmpty() && !monitor.isCanceled()) { char[] needle = (char[])searchForSynonyms.removeFirst(); //create pattern and job to search for type synonyms for the parent type that is being searched for TypeSynonymsPattern typeSynonymsPattern = new TypeSynonymsPattern(needle); //search for the type synonyms indexManager.performConcurrentJob(new PatternSearchJob( typeSynonymsPattern, new JavaSearchParticipant(), scope, new IndexQueryRequestor() { public boolean acceptIndexMatch(String documentPath, SearchPattern indexRecord, SearchParticipant participant, AccessRuleSet access) { TypeSynonymsPattern record = (TypeSynonymsPattern)indexRecord; char[][] patternSynonyms = record.getSynonyms(); if(patternSynonyms != null && patternSynonyms.length != 0) { for(int i = 0; i < patternSynonyms.length; ++i) { /* if new synonym add to list of synonyms to return and to * list of synonyms to check for more synonyms */ if(!listContains(allSynonyms, patternSynonyms[i])) { allSynonyms.add(patternSynonyms[i]); searchForSynonyms.add(patternSynonyms[i]); } } } return true; } } ), waitingPolicy, new NullProgressMonitor() { public void setCanceled(boolean value) { monitor.setCanceled(value); } public boolean isCanceled() { return monitor.isCanceled(); } } ); } return (char[][])allSynonyms.toArray(new char[allSynonyms.size()][]); } private static boolean listContains(List list, Object elem) { boolean contains = false; //need to do char equals if char array if(elem instanceof char[]) { char[] needle = (char[])elem; for(int i = 0; i < list.size() && !contains; ++i) { contains = list.get(i) instanceof char[] && CharOperation.equals((char[])list.get(i), needle); } } else { contains = list.contains(elem); } return contains; } }
epl-1.0
akervern/che
wsmaster/che-core-api-installer/src/main/java/org/eclipse/che/api/installer/server/jpa/JpaInstallerDao.java
6272
/* * Copyright (c) 2012-2018 Red Hat, Inc. * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 * which is available at https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Red Hat, Inc. - initial API and implementation */ package org.eclipse.che.api.installer.server.jpa; import static com.google.common.base.Preconditions.checkArgument; import static java.lang.String.format; import static java.util.Objects.requireNonNull; import com.google.inject.Singleton; import com.google.inject.persist.Transactional; import java.util.List; import java.util.stream.Collectors; import javax.inject.Inject; import javax.inject.Provider; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import org.eclipse.che.api.core.Page; import org.eclipse.che.api.installer.server.exception.InstallerAlreadyExistsException; import org.eclipse.che.api.installer.server.exception.InstallerException; import org.eclipse.che.api.installer.server.exception.InstallerNotFoundException; import org.eclipse.che.api.installer.server.impl.InstallerFqn; import org.eclipse.che.api.installer.server.model.impl.InstallerImpl; import org.eclipse.che.api.installer.server.spi.InstallerDao; import org.eclipse.che.core.db.DBInitializer; import org.eclipse.che.core.db.jpa.DuplicateKeyException; /** @author Anatolii Bazko */ @Singleton public class JpaInstallerDao implements InstallerDao { private final Provider<EntityManager> managerProvider; @Inject public JpaInstallerDao( @SuppressWarnings("unused") DBInitializer dbInitializer, Provider<EntityManager> managerProvider) { this.managerProvider = managerProvider; } @Override public void create(InstallerImpl installer) throws InstallerException { requireNonNull(installer, "Required non-null installer"); try { doCreate(installer); } catch (DuplicateKeyException x) { throw new InstallerAlreadyExistsException( format( "Installer with such fqn '%s:%s' already exists", installer.getId(), installer.getVersion())); } catch (RuntimeException x) { throw new InstallerException(x.getMessage(), x); } } @Override public void update(InstallerImpl installer) throws InstallerException { requireNonNull(installer, "Required non-null update"); try { doUpdate(installer); } catch (NoResultException e) { throw new InstallerNotFoundException( format("Installer with fqn '%s' doesn't exist", InstallerFqn.of(installer))); } catch (RuntimeException x) { throw new InstallerException(x.getMessage(), x); } } @Override public void remove(InstallerFqn fqn) throws InstallerException { requireNonNull(fqn, "Required non-null fqn"); try { doRemove(fqn); } catch (NoResultException e) { } catch (RuntimeException x) { throw new InstallerException(x.getMessage(), x); } } @Override @Transactional public InstallerImpl getByFqn(InstallerFqn fqn) throws InstallerException { requireNonNull(fqn, "Required non-null fqn"); try { InstallerImpl installer = managerProvider .get() .createNamedQuery("Inst.getByKey", InstallerImpl.class) .setParameter("id", fqn.getId()) .setParameter("version", fqn.getVersion()) .getSingleResult(); return new InstallerImpl(installer); } catch (NoResultException e) { throw new InstallerNotFoundException(format("Installer with fqn '%s' doesn't exist", fqn)); } catch (RuntimeException e) { throw new InstallerException(e.getMessage(), e); } } @Override @Transactional public List<String> getVersions(String id) throws InstallerException { try { return managerProvider .get() .createNamedQuery("Inst.getAllById", InstallerImpl.class) .setParameter("id", id) .getResultList() .stream() .map(InstallerImpl::getVersion) .collect(Collectors.toList()); } catch (RuntimeException x) { throw new InstallerException(x.getMessage(), x); } } @Override @Transactional public Page<InstallerImpl> getAll(int maxItems, long skipCount) throws InstallerException { checkArgument(maxItems >= 0, "The number of items to return can't be negative."); checkArgument( skipCount >= 0 && skipCount <= Integer.MAX_VALUE, "The number of items to skip can't be negative or greater than " + Integer.MAX_VALUE); try { final List<InstallerImpl> list = managerProvider .get() .createNamedQuery("Inst.getAll", InstallerImpl.class) .setMaxResults(maxItems) .setFirstResult((int) skipCount) .getResultList(); return new Page<>(list, skipCount, maxItems, getTotalCount()); } catch (RuntimeException x) { throw new InstallerException(x.getMessage(), x); } } @Transactional(rollbackOn = {RuntimeException.class, InstallerException.class}) protected void doCreate(InstallerImpl installer) throws InstallerException { EntityManager manage = managerProvider.get(); manage.persist(installer); manage.flush(); } @Transactional protected void doUpdate(InstallerImpl update) throws InstallerException { doRemove(InstallerFqn.of(update)); doCreate(update); } @Transactional protected void doRemove(InstallerFqn fqn) { final EntityManager manager = managerProvider.get(); InstallerImpl installer = manager .createNamedQuery("Inst.getByKey", InstallerImpl.class) .setParameter("id", fqn.getId()) .setParameter("version", fqn.getVersion()) .getSingleResult(); manager.remove(installer); manager.flush(); } @Override @Transactional public long getTotalCount() throws InstallerException { try { return managerProvider .get() .createNamedQuery("Inst.getTotalCount", Long.class) .getSingleResult(); } catch (RuntimeException x) { throw new InstallerException(x.getMessage(), x); } } }
epl-1.0
menghanli/ice
org.eclipse.ice.client.widgets/src/org/eclipse/ice/client/widgets/MeshElementTreeView.java
15267
/******************************************************************************* * Copyright (c) 2014 UT-Battelle, LLC. * 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: * Initial API and implementation and/or initial documentation - Jay Jay Billings, * Jordan H. Deyton, Dasha Gorin, Alexander J. McCaskey, Taylor Patterson, * Claire Saunders, Matthew Wang, Anna Wojtowicz *******************************************************************************/ package org.eclipse.ice.client.widgets; import java.util.ArrayList; import org.eclipse.ice.datastructures.ICEObject.IUpdateable; import org.eclipse.ice.datastructures.ICEObject.IUpdateableListener; import org.eclipse.ice.datastructures.form.Form; import org.eclipse.ice.datastructures.form.MeshComponent; import org.eclipse.ice.viz.service.datastructures.VizObject.VizObject; import org.eclipse.ice.viz.service.mesh.datastructures.Edge; import org.eclipse.ice.viz.service.mesh.datastructures.IMeshPart; import org.eclipse.ice.viz.service.mesh.datastructures.Polygon; import org.eclipse.ice.viz.service.mesh.datastructures.Vertex; import org.eclipse.ice.viz.service.mesh.properties.MeshSelection; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.swt.widgets.Composite; import org.eclipse.ui.IPartListener2; import org.eclipse.ui.ISelectionListener; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchPartReference; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.part.ViewPart; import org.eclipse.ui.part.WorkbenchPart; import org.eclipse.ui.views.properties.IPropertySheetPage; import org.eclipse.ui.views.properties.tabbed.ITabbedPropertySheetPageContributor; import org.eclipse.ui.views.properties.tabbed.TabbedPropertySheetPage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class extends ViewPart to create a tree of elements (polygons, edges, * vertices) in the MeshComponent. * * @author Taylor Patterson */ public class MeshElementTreeView extends ViewPart implements IUpdateableListener, IPartListener2, ISelectionListener, ITabbedPropertySheetPageContributor { /** * Logger for handling event messages and other information. */ private static final Logger logger = LoggerFactory .getLogger(MeshElementTreeView.class); /** * Eclipse view ID */ public static final String ID = "org.eclipse.ice.client.widgets.MeshElementTreeView"; /** * The MeshComponent managed by this view. */ private MeshComponent meshComponent; /** * The TreeViewer for mesh elements. */ private TreeViewer elementTreeViewer; /** * The ID of the most recently active item. */ private int lastFormItemID; /** * The constructor. */ public MeshElementTreeView() { // Call the super constructor super(); return; } /** * This operation sets the MeshComponent that should be used by the * MeshElementTreeView. It also registers the MeshElementTreeView with the * MeshComponent so that it can be notified of state changes through the * IUpdateableListener interface. * * @param component * The MeshComponent */ public void setMeshComponent(MeshComponent component) { // Make sure the MeshComponent exists if (component != null) { // Set the component reference meshComponent = component; // Register this view with the Component to receive updates component.register(this); // Update the view update(component); } return; } /** * This operation retrieves the MeshComponent that has been rendered by this * view or null if the component does not exist. * * @return The MeshComponent or null if the component was not previously * set. */ public MeshComponent getMeshComponent() { return meshComponent; } /** * This operation overrides the ViewPart.createPartControl method to create * and draw the TreeViewer before registering it as a selection provider and * part listener. * * @param parent * The Composite containing this view * * @see WorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite) */ @Override public void createPartControl(Composite parent) { // Initialize the TreeViewer elementTreeViewer = new TreeViewer(parent); // Create content and label providers initializeTreeViewer(elementTreeViewer); // Register this view's TreeViewer as a SelectionProvider getSite().setSelectionProvider(elementTreeViewer); // Register this view as a part listener getSite().getWorkbenchWindow().getPartService().addPartListener(this); // Register this view as a SelectionListener to the ICEMeshPage getSite().getWorkbenchWindow().getSelectionService() .addSelectionListener(ICEMeshPage.ID, this); return; } /** * This operation creates content and label providers for a TreeViewer. * * @param inputTreeViewer * The TreeViewer to have the providers added to. */ private void initializeTreeViewer(TreeViewer inputTreeViewer) { // Set the tree's content provider inputTreeViewer.setContentProvider(new ITreeContentProvider() { @Override public void dispose() { } @Override public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { } /** * This function retrieves the elements of the tree. * * @param inputElement * The structure containing all of the elements * * @see ITreeContentProvider#getElements(Object) */ @Override public Object[] getElements(Object inputElement) { // Local Declaration ArrayList<Polygon> allElements = (ArrayList<Polygon>) inputElement; ArrayList<MeshSelection> contents = new ArrayList<MeshSelection>(); // Wrap the Polygons into PropertySources and add them to // the array for (Polygon i : allElements) { contents.add(new MeshSelection(meshComponent.getMesh(), i)); } return contents.toArray(); } /** * This function retrieves the children of a given tree element. * * @param parentElement * The tree element for which children are being * requested * * @see ITreeContentProvider#getChildren(Object) */ @Override public Object[] getChildren(Object parentElement) { // If the element is a PropertySource if (parentElement instanceof MeshSelection) { MeshSelection selection = (MeshSelection) parentElement; // Load edges and vertices as children of polygons ArrayList<MeshSelection> children = new ArrayList<MeshSelection>(); if (selection.selectedMeshPart instanceof Polygon) { Polygon polygon = (Polygon) selection.selectedMeshPart; // Add new MeshSelections for the edges. for (Edge e : polygon.getEdges()) { children.add(new MeshSelection(meshComponent.getMesh(), e)); } // Add new MeshSelections for the vertices. for (Vertex v : polygon.getVertices()) { children.add(new MeshSelection(meshComponent.getMesh(), v)); } } return children.toArray(); } return null; } @Override public Object getParent(Object element) { return null; } /** * This function checks whether or not the tree element has any * children. This should only return true for Polygons. * * @param element * The tree element to investigate * * @return True if this is of type Polygon. False otherwise. * * @see ITreeContentProvider#hasChildren(Object) */ @Override public boolean hasChildren(Object element) { // Only selected Polygons will have children. return (element instanceof MeshSelection && ((MeshSelection) element).selectedMeshPart instanceof Polygon); } }); // Add a label provider to properly label the mesh elements inputTreeViewer.setLabelProvider(new LabelProvider() { /** * The String to contain the text of the label. */ String label = ""; /** * A function to create text labels for elements in the * MeshElementTreeView. * * @param element * The tree element to be labeled * * @return The String to serve as the tree element label * * @see LabelProvider#getText(Object) */ @Override public String getText(Object element) { // Only set a label if it is a PropertySource. Otherwise we // shouldn't need it.... I think. if (element instanceof MeshSelection) { // Get the wrapped IMeshPart. IMeshPart meshPart = ((MeshSelection) element).selectedMeshPart; // Cast the IMeshPart to an ICEObject and set the label text // from its name and ID. VizObject object = (VizObject) meshPart; label = object.getName() + " " + object.getId(); return label; } return element.toString(); } }); return; } /** * (non-Javadoc) * * @see WorkbenchPart#setFocus() */ @Override public void setFocus() { return; } /** * Update elementTreeViewer when new elements are added to the mesh. * * @param component * * @see IUpdateableListener#update(IUpdateable) */ @Override public void update(IUpdateable component) { logger.info("ICEMeshPage Message: " + "Mesh changed!"); // Sync with the display PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { @Override public void run() { // Just do a blanket update - no need to check // the component if (elementTreeViewer != null) { logger.info("MeshElementTreeView Message: " + "Updating element view."); // Set the tree content if (meshComponent != null) { elementTreeViewer.setInput(meshComponent.getPolygons()); } // Refresh the view elementTreeViewer.refresh(); elementTreeViewer.getTree().redraw(); } } }); return; } /** * This function is called whenever a Workbench part is closed. Here, we are * only interested if the part is an ICEFormEditor. Get the Form from the * editor. Clear the elements from the tree view. * * @param partRef * The workbench part calling this function. * * @see IPartListener2#partClosed(IWorkbenchPartReference) */ @Override public void partClosed(IWorkbenchPartReference partRef) { logger.info("MeshElementTreeView Message: Called partClosed(" + partRef.getId() + ")"); if (partRef.getId().equals(ICEFormEditor.ID)) { // Get the closed editor ICEFormEditor activeEditor = (ICEFormEditor) partRef.getPart(false); // Get the form from the editor Form activeForm = ((ICEFormInput) activeEditor.getEditorInput()) .getForm(); // If this is the most recently active form, clear the TreeViewer. if (activeForm.getItemID() == lastFormItemID) { elementTreeViewer.setInput(null); elementTreeViewer.refresh(); elementTreeViewer.getTree().redraw(); } } return; } /** * This function is called whenever a Workbench part gains focus. Here, we * are only interested if the part is an ICEFormEditor. A call to this * function will occur prior to a part being closed, so just keep track of * that form's id. * * @param partRef * The workbench part calling this function. * * @see IPartListener2#partActivated(IWorkbenchPartReference) */ @Override public void partActivated(IWorkbenchPartReference partRef) { logger.info("MeshElementTreeView Message: Called partActivated(" + partRef.getId() + ")"); if (partRef.getId().equals(ICEFormEditor.ID)) { // Get the activated editor ICEFormEditor activeEditor = (ICEFormEditor) partRef.getPart(false); // Pull the form from the editor Form activeForm = ((ICEFormInput) activeEditor.getEditorInput()) .getForm(); // Record the ID of this form lastFormItemID = activeForm.getItemID(); } return; } /** * This function is called whenever a Workbench part gains focus. Here, we * are only interested if the part is an ICEFormEditor. A call to this * function will occur prior to a part being closed, so just keep track of * that form's id. * * @param partRef * The workbench part calling this function. * * @see IPartListener2#partHidden(IWorkbenchPartReference) */ @Override public void partHidden(IWorkbenchPartReference partRef) { logger.info("MeshElementTreeView Message: Called partHidden(" + partRef.getId() + ")"); if (partRef.getId().equals(ICEFormEditor.ID)) { // Get the hidden editor ICEFormEditor activeEditor = (ICEFormEditor) partRef.getPart(false); // Get the form from the editor Form activeForm = ((ICEFormInput) activeEditor.getEditorInput()) .getForm(); // Record the ID of this form lastFormItemID = activeForm.getItemID(); } return; } /** * (non-Javadoc) * * @see IPartListener2#partBroughtToTop(IWorkbenchPartReference) */ @Override public void partBroughtToTop(IWorkbenchPartReference partRef) { // Do nothing return; } /** * (non-Javadoc) * * @see IPartListener2#partDeactivated(IWorkbenchPartReference) */ @Override public void partDeactivated(IWorkbenchPartReference partRef) { // Do nothing return; } /** * (non-Javadoc) * * @see IPartListener2#partOpened(IWorkbenchPartReference) */ @Override public void partOpened(IWorkbenchPartReference partRef) { // Do nothing return; } /** * (non-Javadoc) * * @see IPartListener2#partVisible(IWorkbenchPartReference) */ @Override public void partVisible(IWorkbenchPartReference partRef) { // Do nothing return; } /** * (non-Javadoc) * * @see IPartListener2#partInputChanged(IWorkbenchPartReference) */ @Override public void partInputChanged(IWorkbenchPartReference partRef) { // Do nothing return; } /** * This operation overrides the default/abstract implementation of * ISelectionListener.selectionChanged to capture selections made in the * ICEMeshPage and highlight the corresponding element in the * MeshElementTreeView. * * @param part * The IWorkbenchPart that called this function. * @param selection * The ISelection chosen in the part parameter. */ @Override public void selectionChanged(IWorkbenchPart part, ISelection selection) { // Get the selection made in the ICEMeshPage. return; } public void revealSelectedEdge(int id) { elementTreeViewer.expandAll(); } public void revealSelectedVertex(int id) { elementTreeViewer.expandAll(); } // ---- These methods are required for tabbed properties. ---- // @Override public String getContributorId() { return getSite().getId(); } @Override public Object getAdapter(Class adapter) { if (adapter == IPropertySheetPage.class) { return new TabbedPropertySheetPage(this); } return super.getAdapter(adapter); } // ----------------------------------------------------------- // }
epl-1.0
rrimmana/birt-1
chart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/type/LineChart.java
25123
/******************************************************************************* * Copyright (c) Oct 22, 2004 Actuate Corporation {ADD OTHER COPYRIGHT OWNERS}. * 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: Actuate Corporation - initial API and implementation {ADD * SUBSEQUENT AUTHOR & CONTRIBUTION} ******************************************************************************/ package org.eclipse.birt.chart.ui.swt.type; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Vector; import org.eclipse.birt.chart.exception.ChartException; import org.eclipse.birt.chart.model.Chart; import org.eclipse.birt.chart.model.ChartWithAxes; import org.eclipse.birt.chart.model.ChartWithoutAxes; import org.eclipse.birt.chart.model.attribute.Angle3D; import org.eclipse.birt.chart.model.attribute.AxisType; import org.eclipse.birt.chart.model.attribute.ChartDimension; import org.eclipse.birt.chart.model.attribute.Orientation; import org.eclipse.birt.chart.model.attribute.Text; import org.eclipse.birt.chart.model.attribute.impl.Angle3DImpl; import org.eclipse.birt.chart.model.attribute.impl.Rotation3DImpl; import org.eclipse.birt.chart.model.component.Axis; import org.eclipse.birt.chart.model.component.Series; import org.eclipse.birt.chart.model.component.impl.AxisImpl; import org.eclipse.birt.chart.model.component.impl.SeriesImpl; import org.eclipse.birt.chart.model.data.BaseSampleData; import org.eclipse.birt.chart.model.data.DataFactory; import org.eclipse.birt.chart.model.data.OrthogonalSampleData; import org.eclipse.birt.chart.model.data.SampleData; import org.eclipse.birt.chart.model.data.SeriesDefinition; import org.eclipse.birt.chart.model.data.impl.NumberDataElementImpl; import org.eclipse.birt.chart.model.data.impl.SeriesDefinitionImpl; import org.eclipse.birt.chart.model.impl.ChartWithAxesImpl; import org.eclipse.birt.chart.model.type.LineSeries; import org.eclipse.birt.chart.model.type.impl.LineSeriesImpl; import org.eclipse.birt.chart.model.util.ChartElementUtil; import org.eclipse.birt.chart.ui.extension.i18n.Messages; import org.eclipse.birt.chart.ui.swt.ChartPreviewPainter; import org.eclipse.birt.chart.ui.swt.DefaultChartSubTypeImpl; import org.eclipse.birt.chart.ui.swt.DefaultChartTypeImpl; import org.eclipse.birt.chart.ui.swt.HelpContentImpl; import org.eclipse.birt.chart.ui.swt.interfaces.IChartSubType; import org.eclipse.birt.chart.ui.swt.interfaces.IChartType; import org.eclipse.birt.chart.ui.swt.interfaces.IHelpContent; import org.eclipse.birt.chart.ui.swt.interfaces.ISelectDataComponent; import org.eclipse.birt.chart.ui.swt.interfaces.ISelectDataCustomizeUI; import org.eclipse.birt.chart.ui.swt.wizard.ChartWizardContext; import org.eclipse.birt.chart.ui.swt.wizard.data.DefaultBaseSeriesComponent; import org.eclipse.birt.chart.ui.util.ChartCacheManager; import org.eclipse.birt.chart.ui.util.ChartUIConstants; import org.eclipse.birt.chart.ui.util.ChartUIUtil; import org.eclipse.birt.chart.ui.util.UIHelper; import org.eclipse.emf.common.util.EList; import org.eclipse.swt.graphics.Image; /** * LineChart */ public class LineChart extends DefaultChartTypeImpl { /** * Comment for <code>TYPE_LITERAL</code> */ public static final String TYPE_LITERAL = ChartUIConstants.TYPE_LINE; protected static final String STACKED_SUBTYPE_LITERAL = "Stacked"; //$NON-NLS-1$ protected static final String PERCENTSTACKED_SUBTYPE_LITERAL = "Percent Stacked"; //$NON-NLS-1$ protected static final String OVERLAY_SUBTYPE_LITERAL = "Overlay"; //$NON-NLS-1$ public LineChart( ) { super.chartTitle = Messages.getString( "LineChart.Txt.DefaultLineChartTitle" ); //$NON-NLS-1$; } /* * (non-Javadoc) * * @see org.eclipse.birt.chart.ui.swt.IChartType#getName() */ public String getName( ) { return TYPE_LITERAL; } /* * (non-Javadoc) * * @see org.eclipse.birt.chart.ui.swt.IChartType#getImage() */ public Image getImage( ) { return UIHelper.getImage( "icons/obj16/linecharticon.gif" ); //$NON-NLS-1$; } /** * Returns the icons for subtypes. * * @param sDimension * @param orientation * @param subtype * @return */ protected Image getImageForSubtype( String sDimension, Orientation orientation, String subtype ) { String imagePath = null; if ( sDimension.equals( TWO_DIMENSION_TYPE ) || sDimension.equals( ChartDimension.TWO_DIMENSIONAL_LITERAL.getName( ) ) ) { if ( subtype.equals( OVERLAY_SUBTYPE_LITERAL ) ) { if ( orientation == Orientation.VERTICAL_LITERAL ) { imagePath = "icons/wizban/sidebysidelinechartimage.gif"; //$NON-NLS-1$ } else { imagePath = "icons/wizban/horizontalsidebysidelinechartimage.gif"; //$NON-NLS-1$ } } else if ( subtype.equals( STACKED_SUBTYPE_LITERAL ) ) { if ( orientation == Orientation.VERTICAL_LITERAL ) { imagePath = "icons/wizban/stackedlinechartimage.gif"; //$NON-NLS-1$ } else { imagePath = "icons/wizban/horizontalstackedlinechartimage.gif"; //$NON-NLS-1$ } } else if ( subtype.equals( PERCENTSTACKED_SUBTYPE_LITERAL ) ) { if ( orientation == Orientation.VERTICAL_LITERAL ) { imagePath = "icons/wizban/percentstackedlinechartimage.gif"; //$NON-NLS-1$ } else { imagePath = "icons/wizban/horizontalpercentstackedlinechartimage.gif"; //$NON-NLS-1$ } } } else if ( sDimension.equals( THREE_DIMENSION_TYPE ) || sDimension.equals( ChartDimension.THREE_DIMENSIONAL_LITERAL.getName( ) ) ) { imagePath = "icons/wizban/sidebysidelinechart3dimage.gif"; //$NON-NLS-1$ } if ( imagePath != null ) { return UIHelper.getImage( imagePath ); } return null; } protected String getDescriptionForSubtype( String subtypeLiteral ) { if ( OVERLAY_SUBTYPE_LITERAL.equals( subtypeLiteral ) ) { return Messages.getString( "LineChart.Txt.OverlayDescription" ); //$NON-NLS-1$ } if ( STACKED_SUBTYPE_LITERAL.equals( subtypeLiteral ) ) { return Messages.getString( "LineChart.Txt.StackedDescription" ); //$NON-NLS-1$ } if ( PERCENTSTACKED_SUBTYPE_LITERAL.equals( subtypeLiteral ) ) { return Messages.getString( "LineChart.Txt.PercentStackedDescription" ); //$NON-NLS-1$ } return null; } /* * (non-Javadoc) * * @see org.eclipse.birt.chart.ui.swt.IChartType#getHelp() */ public IHelpContent getHelp( ) { return new HelpContentImpl( TYPE_LITERAL, Messages.getString( "LineChart.Txt.HelpText" ) ); //$NON-NLS-1$ } /* * (non-Javadoc) * * @see * org.eclipse.birt.chart.ui.swt.interfaces.IChartType#getChartSubtypes( * java.lang.String) */ public Collection<IChartSubType> getChartSubtypes( String sDimension, Orientation orientation ) { Vector<IChartSubType> vSubTypes = new Vector<IChartSubType>( ); if ( sDimension.equals( TWO_DIMENSION_TYPE ) || sDimension.equals( ChartDimension.TWO_DIMENSIONAL_LITERAL.getName( ) ) ) { vSubTypes.add( new DefaultChartSubTypeImpl( OVERLAY_SUBTYPE_LITERAL, getImageForSubtype( sDimension, orientation, OVERLAY_SUBTYPE_LITERAL ), getDescriptionForSubtype( OVERLAY_SUBTYPE_LITERAL ), Messages.getString( "LineChart.SubType.Overlay" ) ) ); //$NON-NLS-1$ if ( isStackedSupported( ) ) { vSubTypes.add( new DefaultChartSubTypeImpl( STACKED_SUBTYPE_LITERAL, getImageForSubtype( sDimension, orientation, STACKED_SUBTYPE_LITERAL ), getDescriptionForSubtype( STACKED_SUBTYPE_LITERAL ), Messages.getString( "LineChart.SubType.Stacked" ) ) ); //$NON-NLS-1$ } if ( isPercentStackedSupported( ) ) { vSubTypes.add( new DefaultChartSubTypeImpl( PERCENTSTACKED_SUBTYPE_LITERAL, getImageForSubtype( sDimension, orientation, PERCENTSTACKED_SUBTYPE_LITERAL ), getDescriptionForSubtype( PERCENTSTACKED_SUBTYPE_LITERAL ), Messages.getString( "LineChart.SubType.PercentStacked" ) ) ); //$NON-NLS-1$ } } else if ( sDimension.equals( THREE_DIMENSION_TYPE ) || sDimension.equals( ChartDimension.THREE_DIMENSIONAL_LITERAL.getName( ) ) ) { vSubTypes.add( new DefaultChartSubTypeImpl( OVERLAY_SUBTYPE_LITERAL, getImageForSubtype( sDimension, orientation, OVERLAY_SUBTYPE_LITERAL ), getDescriptionForSubtype( OVERLAY_SUBTYPE_LITERAL ), Messages.getString( "LineChart.SubType.Overlay" ) ) ); //$NON-NLS-1$ } return vSubTypes; } /* * (non-Javadoc) * * @see * org.eclipse.birt.chart.ui.swt.interfaces.IChartType#getModel(java.lang * .String, java.lang.String, java.lang.String) */ public Chart getModel( String sSubType, Orientation orientation, String sDimension, Chart currentChart ) { ChartWithAxes newChart = null; if ( currentChart != null ) { newChart = (ChartWithAxes) getConvertedChart( currentChart, sSubType, orientation, sDimension ); if ( newChart != null ) { return newChart; } } newChart = ChartWithAxesImpl.createDefault( ); newChart.setType( TYPE_LITERAL ); newChart.setSubType( sSubType ); ChartElementUtil.setEObjectAttribute( newChart, "orientation", //$NON-NLS-1$ orientation, orientation == null ); ChartElementUtil.setEObjectAttribute( newChart, "dimension",//$NON-NLS-1$ ChartUIUtil.getDimensionType( sDimension ), sDimension == null ); try { ChartElementUtil.setDefaultValue( newChart.getAxes( ).get( 0 ), "categoryAxis", //$NON-NLS-1$ true ); } catch ( ChartException e ) { // Do nothing. } Axis xAxis = newChart.getAxes( ).get( 0 ); SeriesDefinition sdX = SeriesDefinitionImpl.createDefault( ); Series categorySeries = SeriesImpl.createDefault( ); sdX.getSeries( ).add( categorySeries ); xAxis.getSeriesDefinitions( ).add( sdX ); Axis yAxis = xAxis.getAssociatedAxes( ).get( 0 ); if ( sSubType.equalsIgnoreCase( STACKED_SUBTYPE_LITERAL ) ) { SeriesDefinition sdY = SeriesDefinitionImpl.createDefault( ); Series valueSeries = getSeries( false ); valueSeries.setStacked( true ); sdY.getSeries( ).add( valueSeries ); yAxis.getSeriesDefinitions( ).add( sdY ); } else if ( sSubType.equalsIgnoreCase( PERCENTSTACKED_SUBTYPE_LITERAL ) ) { SeriesDefinition sdY = SeriesDefinitionImpl.createDefault( ); Series valueSeries = getSeries( false ); valueSeries.setStacked( true ); sdY.getSeries( ).add( valueSeries ); yAxis.getSeriesDefinitions( ).add( sdY ); } else if ( sSubType.equalsIgnoreCase( OVERLAY_SUBTYPE_LITERAL ) ) { SeriesDefinition sdY = SeriesDefinitionImpl.createDefault( ); Series valueSeries = getSeries( false ); sdY.getSeries( ).add( valueSeries ); yAxis.getSeriesDefinitions( ).add( sdY ); } if ( sDimension != null && sDimension.equals( THREE_DIMENSION_TYPE ) ) { newChart.setRotation( Rotation3DImpl.createDefault( new Angle3D[]{ Angle3DImpl.createDefault( -20, 45, 0 ) } ) ); newChart.getPrimaryBaseAxes( )[0].getAncillaryAxes( ).clear( ); Axis zAxisAncillary = AxisImpl.createDefault( Axis.ANCILLARY_BASE ); zAxisAncillary.getOrigin( ) .setValue( NumberDataElementImpl.create( 0 ) ); newChart.getPrimaryBaseAxes( )[0].getAncillaryAxes( ) .add( zAxisAncillary ); SeriesDefinition sdZ = SeriesDefinitionImpl.createDefault( ); sdZ.getSeries( ).add( SeriesImpl.createDefault( ) ); zAxisAncillary.getSeriesDefinitions( ).add( sdZ ); } addSampleData( newChart ); return newChart; } private void addSampleData( Chart newChart ) { SampleData sd = DataFactory.eINSTANCE.createSampleData( ); sd.getBaseSampleData( ).clear( ); sd.getOrthogonalSampleData( ).clear( ); // Create Base Sample Data BaseSampleData sdBase = DataFactory.eINSTANCE.createBaseSampleData( ); sdBase.setDataSetRepresentation( "A, B, C" ); //$NON-NLS-1$ sd.getBaseSampleData( ).add( sdBase ); // Create Orthogonal Sample Data (with simulation count of 2) OrthogonalSampleData oSample = DataFactory.eINSTANCE.createOrthogonalSampleData( ); oSample.setDataSetRepresentation( "5,-4,12" ); //$NON-NLS-1$ oSample.setSeriesDefinitionIndex( 0 ); sd.getOrthogonalSampleData( ).add( oSample ); if ( newChart.getDimension( ) == ChartDimension.THREE_DIMENSIONAL_LITERAL ) { BaseSampleData sdAncillary = DataFactory.eINSTANCE.createBaseSampleData( ); sdAncillary.setDataSetRepresentation( "Series 1" ); //$NON-NLS-1$ sd.getAncillarySampleData( ).add( sdAncillary ); } newChart.setSampleData( sd ); } private Chart getConvertedChart( Chart currentChart, String sNewSubType, Orientation newOrientation, String sNewDimension ) { Chart helperModel = currentChart.copyInstance( ); helperModel.eAdapters( ).addAll( currentChart.eAdapters( ) ); ChartDimension oldDimension = currentChart.getDimension( ); // Cache series to keep attributes during conversion ChartCacheManager.getInstance( ) .cacheSeries( ChartUIUtil.getAllOrthogonalSeriesDefinitions( helperModel ) ); IChartType oldType = ChartUIUtil.getChartType( currentChart.getType( ) ); if ( ( currentChart instanceof ChartWithAxes ) ) { if ( currentChart.getType( ).equals( TYPE_LITERAL ) ) { currentChart.setSubType( sNewSubType ); EList<Axis> axes = ( (ChartWithAxes) currentChart ).getAxes( ) .get( 0 ) .getAssociatedAxes( ); for ( int i = 0, seriesIndex = 0; i < axes.size( ); i++ ) { if ( sNewSubType.equalsIgnoreCase( PERCENTSTACKED_SUBTYPE_LITERAL ) ) { if ( !ChartPreviewPainter.isLivePreviewActive( ) && !isNumbericAxis( axes.get( i ) ) ) { axes.get( i ).setType( AxisType.LINEAR_LITERAL ); } axes.get( i ).setPercent( true ); } else { axes.get( i ).setPercent( false ); } EList<SeriesDefinition> seriesdefinitions = axes.get( i ) .getSeriesDefinitions( ); Series firstSeries = seriesdefinitions.get( 0 ) .getDesignTimeSeries( ); for ( int j = 0; j < seriesdefinitions.size( ); j++ ) { Series series = seriesdefinitions.get( j ) .getDesignTimeSeries( ); if ( ( sNewSubType.equalsIgnoreCase( STACKED_SUBTYPE_LITERAL ) || sNewSubType.equalsIgnoreCase( PERCENTSTACKED_SUBTYPE_LITERAL ) ) ) { if ( j != 0 ) { series = getConvertedSeriesAsFirst( series, seriesIndex, firstSeries ); } seriesIndex++; if ( !ChartPreviewPainter.isLivePreviewActive( ) && axes.get( i ).isSetType( ) && !isNumbericAxis( axes.get( i ) ) ) { axes.get( i ).setType( AxisType.LINEAR_LITERAL ); } if ( series.canBeStacked( ) ) { series.setStacked( true ); } seriesdefinitions.get( j ).getSeries( ).clear( ); seriesdefinitions.get( j ) .getSeries( ) .add( series ); } else { series.setStacked( false ); } } } } else { currentChart.setType( TYPE_LITERAL ); currentChart.setSubType( sNewSubType ); Text title = currentChart.getTitle( ).getLabel( ).getCaption( ); if ( title.getValue( ) != null && ( title.getValue( ).trim( ).length( ) == 0 || title.getValue( ) .trim( ) .equals( oldType.getDefaultTitle( ).trim( ) ) ) ) { title.setValue( getDefaultTitle( ) ); } List<AxisType> axisTypes = new ArrayList<AxisType>( ); EList<Axis> axes = ( (ChartWithAxes) currentChart ).getAxes( ) .get( 0 ) .getAssociatedAxes( ); for ( int i = 0, seriesIndex = 0; i < axes.size( ); i++ ) { if ( !ChartPreviewPainter.isLivePreviewActive( ) && axes.get( i ).isSetType( ) && !isNumbericAxis( axes.get( i ) ) ) { axes.get( i ).setType( AxisType.LINEAR_LITERAL ); } axes.get( i ).setPercent( sNewSubType.equalsIgnoreCase( PERCENTSTACKED_SUBTYPE_LITERAL ) ); EList<SeriesDefinition> seriesdefinitions = axes.get( i ).getSeriesDefinitions( ); for ( int j = 0; j < seriesdefinitions.size( ); j++ ) { Series series = seriesdefinitions.get( j ) .getDesignTimeSeries( ); series = getConvertedSeries( series, seriesIndex++ ); if ( !ChartPreviewPainter.isLivePreviewActive( ) && axes.get( i ).isSetType( ) && !isNumbericAxis( axes.get( i ) ) ) { axes.get( i ).setType( AxisType.LINEAR_LITERAL ); } boolean isStacked = ( sNewSubType.equalsIgnoreCase( STACKED_SUBTYPE_LITERAL ) || sNewSubType.equalsIgnoreCase( PERCENTSTACKED_SUBTYPE_LITERAL ) ); series.setStacked( isStacked ); seriesdefinitions.get( j ).getSeries( ).clear( ); seriesdefinitions.get( j ).getSeries( ).add( series ); axisTypes.add( axes.get( i ).getType( ) ); } } currentChart.setSampleData( getConvertedSampleData( currentChart.getSampleData( ), ( (ChartWithAxes) currentChart ).getAxes( ) .get( 0 ) .getType( ), axisTypes ) ); } } else { // Create a new instance of the correct type and set initial // properties currentChart = ChartWithAxesImpl.createDefault( ); copyChartProperties( helperModel, currentChart ); currentChart.setType( TYPE_LITERAL ); currentChart.setSubType( sNewSubType ); ChartElementUtil.setEObjectAttribute( currentChart, "orientation", //$NON-NLS-1$ newOrientation, newOrientation == null ); ChartElementUtil.setEObjectAttribute( currentChart, "dimension",//$NON-NLS-1$ ChartUIUtil.getDimensionType( sNewDimension ), sNewDimension == null ); try { ChartElementUtil.setDefaultValue( ( (ChartWithAxes) currentChart ).getAxes( ) .get( 0 ), "categoryAxis", //$NON-NLS-1$ true ); } catch ( ChartException e ) { // Do nothing. } Axis xAxis = ( (ChartWithAxes) currentChart ).getAxes( ).get( 0 ); Axis yAxis = xAxis.getAssociatedAxes( ).get( 0 ); { // Clear existing series definitions xAxis.getSeriesDefinitions( ).clear( ); // Copy base series definitions xAxis.getSeriesDefinitions( ) .add( ( (ChartWithoutAxes) helperModel ).getSeriesDefinitions( ) .get( 0 ) ); // Clear existing series definitions yAxis.getSeriesDefinitions( ).clear( ); // Copy orthogonal series definitions yAxis.getSeriesDefinitions( ) .addAll( xAxis.getSeriesDefinitions( ) .get( 0 ) .getSeriesDefinitions( ) ); // Update the base series Series series = xAxis.getSeriesDefinitions( ) .get( 0 ) .getDesignTimeSeries( ); // series = getConvertedSeries( series ); // Clear existing series xAxis.getSeriesDefinitions( ).get( 0 ).getSeries( ).clear( ); // Add converted series xAxis.getSeriesDefinitions( ) .get( 0 ) .getSeries( ) .add( series ); // Update the orthogonal series EList<SeriesDefinition> seriesdefinitions = yAxis.getSeriesDefinitions( ); for ( int j = 0; j < seriesdefinitions.size( ); j++ ) { series = seriesdefinitions.get( j ).getDesignTimeSeries( ); series = getConvertedSeries( series, j ); if ( ( sNewSubType.equalsIgnoreCase( STACKED_SUBTYPE_LITERAL ) || sNewSubType.equalsIgnoreCase( PERCENTSTACKED_SUBTYPE_LITERAL ) ) ) { series.setStacked( true ); } else { series.setStacked( false ); } // Clear any existing series seriesdefinitions.get( j ).getSeries( ).clear( ); // Add the new series seriesdefinitions.get( j ).getSeries( ).add( series ); } } Text title = currentChart.getTitle( ).getLabel( ).getCaption( ); if ( title.getValue( ) != null && ( title.getValue( ).trim( ).length( ) == 0 || title.getValue( ) .trim( ) .equals( oldType.getDefaultTitle( ).trim( ) ) ) ) { title.setValue( getDefaultTitle( ) ); } } ChartElementUtil.setEObjectAttribute( currentChart, "orientation", //$NON-NLS-1$ newOrientation, newOrientation == null ); ChartElementUtil.setEObjectAttribute( currentChart, "dimension",//$NON-NLS-1$ ChartUIUtil.getDimensionType( sNewDimension ), sNewDimension == null ); if ( sNewDimension!= null && sNewDimension.equals( THREE_DIMENSION_TYPE ) && ChartUIUtil.getDimensionType( sNewDimension ) != oldDimension ) { ( (ChartWithAxes) currentChart ).setRotation( Rotation3DImpl.createDefault( new Angle3D[]{ Angle3DImpl.createDefault( -20, 45, 0 ) } ) ); ( (ChartWithAxes) currentChart ).getPrimaryBaseAxes( )[0].getAncillaryAxes( ) .clear( ); Axis zAxisAncillary = AxisImpl.createDefault( Axis.ANCILLARY_BASE ); zAxisAncillary.getOrigin( ) .setValue( NumberDataElementImpl.create( 0 ) ); ( (ChartWithAxes) currentChart ).getPrimaryBaseAxes( )[0].getAncillaryAxes( ) .add( zAxisAncillary ); SeriesDefinition sdZ = SeriesDefinitionImpl.createDefault( ); sdZ.getSeries( ).add( SeriesImpl.createDefault( ) ); zAxisAncillary.getSeriesDefinitions( ).add( sdZ ); if ( currentChart.getSampleData( ) .getAncillarySampleData( ) .isEmpty( ) ) { BaseSampleData sdAncillary = DataFactory.eINSTANCE.createBaseSampleData( ); sdAncillary.setDataSetRepresentation( "Series 1" ); //$NON-NLS-1$ currentChart.getSampleData( ) .getAncillarySampleData( ) .add( sdAncillary ); } EList<SeriesDefinition> seriesdefinitions = ChartUIUtil.getOrthogonalSeriesDefinitions( currentChart, 0 ); for ( int j = 0; j < seriesdefinitions.size( ); j++ ) { Series series = seriesdefinitions.get( j ).getDesignTimeSeries( ); series.setStacked( false );// Stacked is unsupported in 3D } } // Restore label position for different sub type of chart. ChartUIUtil.restoreLabelPositionFromCache( currentChart ); return currentChart; } private boolean isNumbericAxis( Axis axis ) { return ( axis.getType( ).getValue( ) == AxisType.LINEAR ) || ( axis.getType( ).getValue( ) == AxisType.LOGARITHMIC ); } private Series getConvertedSeries( Series series, int seriesIndex ) { // Do not convert base series if ( series.getClass( ).getName( ).equals( SeriesImpl.class.getName( ) ) ) { return series; } LineSeries lineseries = (LineSeries) ChartCacheManager.getInstance( ) .findSeries( LineSeriesImpl.class.getName( ), seriesIndex ); if ( lineseries == null ) { lineseries = (LineSeries) getSeries( false ); } // Copy generic series properties ChartUIUtil.copyGeneralSeriesAttributes( series, lineseries ); return lineseries; } /* * (non-Javadoc) * * @see * org.eclipse.birt.chart.ui.swt.interfaces.IChartType#getSupportedDimensions * () */ public String[] getSupportedDimensions( ) { return new String[]{ TWO_DIMENSION_TYPE, THREE_DIMENSION_TYPE }; } /* * (non-Javadoc) * * @see * org.eclipse.birt.chart.ui.swt.interfaces.IChartType#getDefaultDimension() */ public String getDefaultDimension( ) { return TWO_DIMENSION_TYPE; } /* * (non-Javadoc) * * @see * org.eclipse.birt.chart.ui.swt.interfaces.IChartType#supportsTransposition * () */ public boolean supportsTransposition( ) { return true; } /* * (non-Javadoc) * * @see * org.eclipse.birt.chart.ui.swt.interfaces.IChartType#supportsTransposition * (java.lang.String) */ public boolean supportsTransposition( String dimension ) { if ( ChartUIUtil.getDimensionType( dimension ) == ChartDimension.THREE_DIMENSIONAL_LITERAL ) { return false; } return supportsTransposition( ); } public ISelectDataComponent getBaseUI( Chart chart, ISelectDataCustomizeUI selectDataUI, ChartWizardContext context, String sTitle ) { return new DefaultBaseSeriesComponent( ChartUIUtil.getBaseSeriesDefinitions( chart ) .get( 0 ), context, sTitle ); } /* * (non-Javadoc) * * @see org.eclipse.birt.chart.ui.swt.DefaultChartTypeImpl#getDisplayName() */ public String getDisplayName( ) { return Messages.getString( "LineChart.Txt.DisplayName" ); //$NON-NLS-1$ } /* * (non-Javadoc) * * @see org.eclipse.birt.chart.ui.swt.interfaces.IChartType#getSeries() */ public Series getSeries( ) { return getSeries( true ); } /* (non-Javadoc) * @see org.eclipse.birt.chart.ui.swt.DefaultChartTypeImpl#getSeries(boolean) */ public Series getSeries( boolean needInitializing ) { if ( needInitializing ) { LineSeries series = (LineSeries) LineSeriesImpl.create( ); series.getMarkers( ).get( 0 ).setVisible( true ); series.setPaletteLineColor( true ); return series; } else { LineSeries series = (LineSeries) LineSeriesImpl.createDefault( ); return series; } } @Override public boolean canCombine( ) { return true; } protected boolean isStackedSupported( ) { return true; } protected boolean isPercentStackedSupported( ) { return true; } @Override public boolean canExpand( ) { return true; } }
epl-1.0
css-iter/cs-studio
applications/channel/channel-plugins/org.csstudio.utility.channel/src/org/csstudio/utility/channel/actions/InfoCommandHandler.java
1478
/** * */ package org.csstudio.utility.channel.actions; import gov.bnl.channelfinder.api.Channel; import java.util.Collection; import java.util.List; import org.csstudio.ui.util.AbstractAdaptedHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.handlers.HandlerUtil; /** * */ public class InfoCommandHandler extends AbstractAdaptedHandler<Channel> { public InfoCommandHandler() { super(Channel.class); } @Override protected void execute(List<Channel> channels, ExecutionEvent event) { try { Shell shell = HandlerUtil.getActiveShell(event); DisplayTreeDialog displayTreeDialog = new DisplayTreeDialog(shell, new ChannelTreeLabelProvider(), new ChannelTreeContentProvider()); displayTreeDialog.setInput(createChannelModel(channels)); displayTreeDialog.setBlockOnOpen(true); displayTreeDialog.setMessage(Messages.treeDialogMessage); displayTreeDialog.setTitle(Messages.treeDialogTitle); displayTreeDialog.open(); } catch (Exception e) { e.printStackTrace(); } } private Object createChannelModel(Collection<Channel> channels){ ChannelTreeModel root = new ChannelTreeModel(0,null); for (Channel channel : channels) { root.getChild().add(channel); } return root; } }
epl-1.0
willrogers/dawnsci
org.eclipse.dawnsci.hdf5/src/org/eclipse/dawnsci/hdf5/H5Utils.java
6359
/*- ******************************************************************************* * Copyright (c) 2011, 2014 Diamond Light Source Ltd. * 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: * Matthew Gerring - initial API and implementation and/or initial documentation *******************************************************************************/ package org.eclipse.dawnsci.hdf5; import ncsa.hdf.object.Datatype; import ncsa.hdf.object.h5.H5Datatype; import org.eclipse.dawnsci.analysis.api.dataset.IDataset; import org.eclipse.dawnsci.analysis.api.dataset.Slice; import org.eclipse.dawnsci.analysis.api.dataset.SliceND; import org.eclipse.dawnsci.analysis.dataset.impl.AbstractDataset; import org.eclipse.dawnsci.analysis.dataset.impl.Dataset; import org.eclipse.dawnsci.analysis.dataset.impl.DatasetFactory; import org.eclipse.dawnsci.analysis.dataset.impl.DatasetUtils; public class H5Utils { public static int getDataType(Datatype datatype) throws Exception { final int type = datatype.getDatatypeClass(); if (type == Datatype.CLASS_ARRAY) throw new Exception("Cannot read array type data sets!"); final int size = datatype.getDatatypeSize()*4; switch (size) { case 8: return Dataset.INT8; case 16: return Dataset.INT16; case 32: if (type==Datatype.CLASS_INTEGER) return Dataset.INT32; if (type==Datatype.CLASS_FLOAT) return Dataset.FLOAT32; //$FALL-THROUGH$ case 64: if (type==Datatype.CLASS_INTEGER) return Dataset.INT64; if (type==Datatype.CLASS_FLOAT) return Dataset.FLOAT64; } return Dataset.FLOAT; } public static Dataset getSet(final IHierarchicalDataFile file, String fullPath) throws Exception { @SuppressWarnings("deprecation") // We are allowed to use this method internally. ncsa.hdf.object.Dataset dataset = (ncsa.hdf.object.Dataset) file.getData(fullPath); return H5Utils.getSet(dataset.getData(), dataset); } /** * Gets a dataset from the complete dims. * @param val * @param set * @return dataset * @throws Exception */ public static Dataset getSet(final Object val, final ncsa.hdf.object.Dataset set) throws Exception { return H5Utils.getSet(val, set.getDims(), set); } /** * Used when dims are not the same as the entire set, for instance when doing a slice. * @param val * @param longShape * @param set * @return dataset * @throws Exception */ public static Dataset getSet(final Object val, final long[] longShape, final ncsa.hdf.object.Dataset set) throws Exception { final int[] intShape = getInt(longShape); Dataset ret = DatasetFactory.createFromObject(val); ret.setShape(intShape); if (set.getDatatype().isUnsigned()) { ret = DatasetUtils.makeUnsigned(ret); } return ret; } /** * Get a int[] from a long[] * @param longShape * @return int shape */ public static int[] getInt(long[] longShape) { final int[] intShape = new int[longShape.length]; for (int i = 0; i < intShape.length; i++) intShape[i] = (int)longShape[i]; return intShape; } /** * Get a long[] from a int[] * @param intShape * @return long shape */ public static long[] getLong(int[] intShape) { final long[] longShape = new long[intShape.length]; for (int i = 0; i < intShape.length; i++) longShape[i] = intShape[i]; return longShape; } /** * Determines the HDF5 Datatype for an abstract dataset. * @param a * @return data type */ public static Datatype getDatatype(IDataset a) throws Exception { // There is a smarter way of doing this, but am in a hurry... try { return getDatatype(AbstractDataset.getDType(a)); } catch (Exception ne) { throw new Exception("Cannot deal with data in form "+a.getClass().getName()); } } public static Datatype getDatatype(int dType) throws Exception { return getDatatype(dType, -1); } /** * * @param dType * @param size - used if the dType is a String only * @return */ public static Datatype getDatatype(int dType, int size) throws Exception { // There is a smarter way of doing this, but am in a hurry... if (dType==Dataset.INT8 || dType==Dataset.BOOL) { return new H5Datatype(Datatype.CLASS_INTEGER, 8/8, Datatype.NATIVE, Datatype.SIGN_NONE); } else if (dType==Dataset.INT16) { return new H5Datatype(Datatype.CLASS_INTEGER, 16/8, Datatype.NATIVE, Datatype.NATIVE); } else if (dType==Dataset.INT32) { return new H5Datatype(Datatype.CLASS_INTEGER, 32/8, Datatype.NATIVE, Datatype.NATIVE); } else if (dType==Dataset.INT64) { return new H5Datatype(Datatype.CLASS_INTEGER, 64/8, Datatype.NATIVE, Datatype.NATIVE); } else if (dType==Dataset.FLOAT32) { return new H5Datatype(Datatype.CLASS_FLOAT, 32/8, Datatype.NATIVE, Datatype.NATIVE); } else if (dType==Dataset.FLOAT64) { return new H5Datatype(Datatype.CLASS_FLOAT, 64/8, Datatype.NATIVE, Datatype.NATIVE); } else if (dType == Dataset.STRING) { if (size<0) size = 64; return new H5Datatype(Datatype.CLASS_STRING, size, Datatype.NATIVE, Datatype.NATIVE); } throw new Exception("Cannot deal with data type "+dType); } /** * Appends a to a dataset of the same name as a and parent Group of parent. * * @param file * @param parent * @param a * @throws Exception */ public static void appendDataset(IHierarchicalDataFile file, String parent, IDataset a) throws Exception { String s = file.appendDataset(a.getName(), a, parent); file.setNexusAttribute(s, Nexus.SDS); } public static void insertDataset(IHierarchicalDataFile file, String parent, IDataset a, Slice[] slice, long[] finalShape) throws Exception { int[] fShape = H5Utils.getInt(finalShape); file.insertSlice(a.getName(), a, parent, new SliceND(a.getShape(), fShape, slice)); } }
epl-1.0
akervern/che
ide/commons-gwt/src/test/java/org/eclipse/che/ide/util/ArraysTest.java
3758
/* * Copyright (c) 2012-2018 Red Hat, Inc. * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 * which is available at https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Red Hat, Inc. - initial API and implementation */ package org.eclipse.che.ide.util; import org.junit.Assert; import org.junit.Test; /** * Unit tests for the {@link Arrays}. * * @author Vlad Zhukovskyi */ public class ArraysTest { private static final Object O1 = new Object(); private static final Object O2 = new Object(); private static final Object O3 = new Object(); @Test public void arrayShouldCheckForEmptiness() throws Exception { Assert.assertTrue(Arrays.isNullOrEmpty(new Object[] {})); Assert.assertTrue(Arrays.isNullOrEmpty(null)); } @Test public void shouldCheckAddOperations() throws Exception { final Object[] arr1 = new Object[] {O1, O2}; final Object[] arr2 = Arrays.add(arr1, O3); Assert.assertTrue(arr1.length == 2); Assert.assertTrue(arr2.length == 3); Assert.assertTrue(arr1 != arr2); } @Test(expected = IllegalArgumentException.class) public void shouldCheckFailedAddOperations() throws Exception { Arrays.add(null, new Object()); } @Test public void shouldCheckContainsOperation() throws Exception { final Object[] arr1 = new Object[] {O1, O2}; Assert.assertTrue(Arrays.contains(arr1, O1)); Assert.assertTrue(Arrays.contains(arr1, O2)); Assert.assertFalse(Arrays.contains(arr1, O3)); } @Test(expected = IllegalArgumentException.class) public void shouldCheckFailedContainsOperations() throws Exception { Arrays.contains(null, new Object()); } @Test public void shouldCheckIndexOfOperations() throws Exception { final Object[] arr1 = new Object[] {O1, O2}; Assert.assertTrue(Arrays.indexOf(arr1, O1) == 0); Assert.assertTrue(Arrays.indexOf(arr1, O2) == 1); Assert.assertTrue(Arrays.indexOf(arr1, O3) == -1); } @Test(expected = IllegalArgumentException.class) public void shouldCheckFailedIndexOfOperations() throws Exception { Arrays.indexOf(null, new Object()); } @Test public void shouldCheckRemoveOperations() throws Exception { final Object[] arr1 = new Object[] {O1, O2, O3}; final Object[] arr2 = Arrays.remove(arr1, O3); Assert.assertTrue(arr1.length == 3); Assert.assertTrue(arr2.length == 2); Assert.assertTrue(arr1 != arr2); } @Test(expected = IllegalArgumentException.class) public void shouldCheckFailedRemoveOperations() throws Exception { Arrays.remove(null, new Object()); } @Test public void shouldCheckRetainOperations() throws Exception { final Object[] arr1 = new Object[] {O1, O2}; final Object[] arr2 = new Object[] {O2, O3}; final Object[] result = Arrays.removeAll(arr1, arr2, true); Assert.assertTrue(result.length == 1); Assert.assertTrue(Arrays.indexOf(result, O1) == -1); Assert.assertTrue(Arrays.indexOf(result, O2) == 0); Assert.assertTrue(Arrays.indexOf(result, O3) == -1); } @Test public void shouldCheckRemoveAllOperations() throws Exception { final Object[] arr1 = new Object[] {O1, O2}; final Object[] arr2 = new Object[] {O2, O3}; final Object[] result = Arrays.removeAll(arr1, arr2, false); Assert.assertTrue(result.length == 1); Assert.assertTrue(Arrays.indexOf(result, O1) == 0); Assert.assertTrue(Arrays.indexOf(result, O2) == -1); Assert.assertTrue(Arrays.indexOf(result, O3) == -1); } @Test(expected = IllegalArgumentException.class) public void shouldCheckFailedRetainOperations() throws Exception { Arrays.removeAll(null, null, false); } }
epl-1.0
openhab/openhab2
bundles/org.openhab.io.homekit/src/main/java/org/openhab/io/homekit/internal/accessories/HomekitFanImpl.java
2320
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.io.homekit.internal.accessories; import static org.openhab.io.homekit.internal.HomekitCharacteristicType.ACTIVE_STATUS; import java.util.List; import java.util.concurrent.CompletableFuture; import org.openhab.core.library.types.OnOffType; import org.openhab.core.library.types.OpenClosedType; import org.openhab.io.homekit.internal.HomekitAccessoryUpdater; import org.openhab.io.homekit.internal.HomekitSettings; import org.openhab.io.homekit.internal.HomekitTaggedItem; import io.github.hapjava.accessories.FanAccessory; import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; import io.github.hapjava.services.impl.FanService; /** * Implements Fan using an Item that provides an On/Off state * * @author Eugen Freiter - Initial contribution */ class HomekitFanImpl extends AbstractHomekitAccessoryImpl implements FanAccessory { private final BooleanItemReader activeReader; public HomekitFanImpl(HomekitTaggedItem taggedItem, List<HomekitTaggedItem> mandatoryCharacteristics, HomekitAccessoryUpdater updater, HomekitSettings settings) throws IncompleteAccessoryException { super(taggedItem, mandatoryCharacteristics, updater, settings); activeReader = createBooleanReader(ACTIVE_STATUS, OnOffType.ON, OpenClosedType.OPEN); this.getServices().add(new FanService(this)); } @Override public CompletableFuture<Boolean> isActive() { return CompletableFuture.completedFuture(activeReader.getValue()); } @Override public CompletableFuture<Void> setActive(boolean state) { activeReader.setValue(state); return CompletableFuture.completedFuture(null); } @Override public void subscribeActive(HomekitCharacteristicChangeCallback callback) { subscribe(ACTIVE_STATUS, callback); } @Override public void unsubscribeActive() { unsubscribe(ACTIVE_STATUS); } }
epl-1.0
Charling-Huang/birt
chart/org.eclipse.birt.chart.engine/src/org/eclipse/birt/chart/model/data/DataFactory.java
6795
/*********************************************************************** * Copyright (c) 2004 Actuate Corporation. * 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: * Actuate Corporation - initial API and implementation ***********************************************************************/ package org.eclipse.birt.chart.model.data; import org.eclipse.emf.ecore.EFactory; /** * <!-- begin-user-doc --> The <b>Factory </b> for the model. It provides a create method for each non-abstract class of * the model. <!-- end-user-doc --> * @see org.eclipse.birt.chart.model.data.DataPackage * @generated */ public interface DataFactory extends EFactory { /** * The singleton instance of the factory. * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ DataFactory eINSTANCE = org.eclipse.birt.chart.model.data.impl.DataFactoryImpl.init( ); /** * Returns a new object of class '<em>Action</em>'. * <!-- begin-user-doc --> <!-- end-user-doc --> * @return a new object of class '<em>Action</em>'. * @generated */ Action createAction( ); /** * Returns a new object of class '<em>Base Sample Data</em>'. * <!-- begin-user-doc --> <!-- end-user-doc --> * @return a new object of class '<em>Base Sample Data</em>'. * @generated */ BaseSampleData createBaseSampleData( ); /** * Returns a new object of class '<em>Big Number Data Element</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Big Number Data Element</em>'. * @generated */ BigNumberDataElement createBigNumberDataElement( ); /** * Returns a new object of class '<em>Bubble Data Set</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Bubble Data Set</em>'. * @generated */ BubbleDataSet createBubbleDataSet( ); /** * Returns a new object of class '<em>Element</em>'. * <!-- begin-user-doc --> <!-- end-user-doc --> * @return a new object of class '<em>Element</em>'. * @generated */ DataElement createDataElement( ); /** * Returns a new object of class '<em>Set</em>'. * <!-- begin-user-doc --> <!-- end-user-doc --> * @return a new object of class '<em>Set</em>'. * @generated */ DataSet createDataSet( ); /** * Returns a new object of class '<em>Date Time Data Element</em>'. <!-- begin-user-doc --> <!-- end-user-doc * --> * * @return a new object of class '<em>Date Time Data Element</em>'. * @generated */ DateTimeDataElement createDateTimeDataElement( ); /** * Returns a new object of class '<em>Date Time Data Set</em>'. * <!-- begin-user-doc --> <!-- end-user-doc --> * @return a new object of class '<em>Date Time Data Set</em>'. * @generated */ DateTimeDataSet createDateTimeDataSet( ); /** * Returns a new object of class '<em>Difference Data Set</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Difference Data Set</em>'. * @generated */ DifferenceDataSet createDifferenceDataSet( ); /** * Returns a new object of class '<em>Gantt Data Set</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Gantt Data Set</em>'. * @generated */ GanttDataSet createGanttDataSet( ); /** * Returns a new object of class '<em>Multiple Actions</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Multiple Actions</em>'. * @generated */ MultipleActions createMultipleActions( ); /** * Returns a new object of class '<em>Null Data Set</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Null Data Set</em>'. * @generated */ NullDataSet createNullDataSet( ); /** * Returns a new object of class '<em>Number Data Element</em>'. * <!-- begin-user-doc --> <!-- end-user-doc --> * @return a new object of class '<em>Number Data Element</em>'. * @generated */ NumberDataElement createNumberDataElement( ); /** * Returns a new object of class '<em>Number Data Set</em>'. * <!-- begin-user-doc --> <!-- end-user-doc --> * @return a new object of class '<em>Number Data Set</em>'. * @generated */ NumberDataSet createNumberDataSet( ); /** * Returns a new object of class '<em>Orthogonal Sample Data</em>'. <!-- begin-user-doc --> <!-- end-user-doc * --> * * @return a new object of class '<em>Orthogonal Sample Data</em>'. * @generated */ OrthogonalSampleData createOrthogonalSampleData( ); /** * Returns a new object of class '<em>Query</em>'. * <!-- begin-user-doc --> <!-- end-user-doc --> * @return a new object of class '<em>Query</em>'. * @generated */ Query createQuery( ); /** * Returns a new object of class '<em>Rule</em>'. * <!-- begin-user-doc --> <!-- end-user-doc --> * @return a new object of class '<em>Rule</em>'. * @deprecated only reserved for compatibility */ Rule createRule( ); /** * Returns a new object of class '<em>Sample Data</em>'. * <!-- begin-user-doc --> <!-- end-user-doc --> * @return a new object of class '<em>Sample Data</em>'. * @generated */ SampleData createSampleData( ); /** * Returns a new object of class '<em>Series Definition</em>'. * <!-- begin-user-doc --> <!-- end-user-doc --> * @return a new object of class '<em>Series Definition</em>'. * @generated */ SeriesDefinition createSeriesDefinition( ); /** * Returns a new object of class '<em>Series Grouping</em>'. * <!-- begin-user-doc --> <!-- end-user-doc --> * @return a new object of class '<em>Series Grouping</em>'. * @generated */ SeriesGrouping createSeriesGrouping( ); /** * Returns a new object of class '<em>Stock Data Set</em>'. * <!-- begin-user-doc --> <!-- end-user-doc --> * @return a new object of class '<em>Stock Data Set</em>'. * @generated */ StockDataSet createStockDataSet( ); /** * Returns a new object of class '<em>Text Data Set</em>'. * <!-- begin-user-doc --> <!-- end-user-doc --> * @return a new object of class '<em>Text Data Set</em>'. * @generated */ TextDataSet createTextDataSet( ); /** * Returns a new object of class '<em>Trigger</em>'. * <!-- begin-user-doc --> <!-- end-user-doc --> * @return a new object of class '<em>Trigger</em>'. * @generated */ Trigger createTrigger( ); /** * Returns the package supported by this factory. * <!-- begin-user-doc --> <!-- end-user-doc --> * @return the package supported by this factory. * @generated */ DataPackage getDataPackage( ); } //DataFactory
epl-1.0
maxeler/eclipse
eclipse.jdt.ui/org.eclipse.jdt.ui.tests.refactoring/resources/InlineMethodWorkspace/TestCases/operator_out/TestDivideDivide.java
176
package operator_out; public class TestTimesPlus { int result; public void foo() { result= /*]*/1 / (20 / 10)/*[*/; } public int inline(int x) { return 1 / x; } }
epl-1.0
rrimmana/birt-1
xtab/org.eclipse.birt.report.item.crosstab.ui/src/org/eclipse/birt/report/item/crosstab/ui/extension/IAggregationCellViewProvider.java
2037
/******************************************************************************* * Copyright (c) 2007 Actuate Corporation. * 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: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.report.item.crosstab.ui.extension; import org.eclipse.birt.report.item.crosstab.core.de.AggregationCellHandle; /** * This inteface is used to create alternative view for aggregation cell in * crosstab. */ public interface IAggregationCellViewProvider { public static final int SWITCH_VIEW_TYPE = 0; public static final int CHANGE_ORIENTATION_TYPE = 1; int defalutUpdateType = SWITCH_VIEW_TYPE; int getDefaultUpdateType(); /** * Return the name of this view */ String getViewName( ); /** * Return the display name of this view */ String getViewDisplayName( ); /** * Returns if the given aggregation cell matches this view */ boolean matchView( AggregationCellHandle cell ); /** * @deprecated use {@link #switchView(SwitchCellInfo)} */ void switchView( AggregationCellHandle cell ); /** * Switches given aggregation cell to this view */ void switchView( SwitchCellInfo info ); /** * Restores given aggregation cell to previous view */ void restoreView( AggregationCellHandle cell ); /** * Updates current view when necessary */ void updateView( AggregationCellHandle cell ); /** * Updates current view when necessary with specified type. */ void updateView( AggregationCellHandle cell, int type); /** * @deprecated use {@link #canSwitch(SwitchCellInfo)} */ boolean canSwitch( AggregationCellHandle cell ); /** * check whether can switch to this view */ boolean canSwitch(SwitchCellInfo info); }
epl-1.0
kevinmcgoldrick/Tank
web/web_support/src/main/java/com/intuit/tank/script/replace/LoggingKeyReplacement.java
1170
package com.intuit.tank.script.replace; /* * #%L * JSF Support Beans * %% * Copyright (C) 2011 - 2015 Intuit Inc. * %% * 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 * #L% */ import java.util.List; import com.intuit.tank.project.ScriptStep; import com.intuit.tank.script.ScriptConstants; import com.intuit.tank.search.script.RequestStepSection; public class LoggingKeyReplacement extends AbstractReplacement { public LoggingKeyReplacement() { super(RequestStepSection.logginKey, ScriptConstants.REQUEST); } @Override public List<ReplaceEntity> getReplacements(ScriptStep step, String searchQuery, String replaceString, SearchMode searchMode) { return getReplacementInValue(searchQuery, replaceString, step.getLoggingKey(), step.getType()); } @Override public void replace(ScriptStep step, String replaceString, String key, ReplaceMode replaceMode) { step.setLoggingKey(replaceString); } }
epl-1.0
css-iter/cs-studio
applications/scan/scan-plugins/org.csstudio.scan.ui.plot/src/org/csstudio/scan/ui/plot/OpenPlotHandler.java
2003
/******************************************************************************* * Copyright (c) 2012 Oak Ridge National Laboratory. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html ******************************************************************************/ package org.csstudio.scan.ui.plot; import org.csstudio.scan.server.ScanInfo; import org.csstudio.scan.ui.ScanHandlerUtil; import org.csstudio.scan.ui.ScanUIActivator; import org.csstudio.ui.util.dialogs.ExceptionDetailsErrorDialog; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.handlers.HandlerUtil; /** Command handler that opens a (new) plot for scan data * @author Kay Kasemir */ public class OpenPlotHandler extends AbstractHandler { /** {@inheritDoc} */ @Override public Object execute(final ExecutionEvent event) throws ExecutionException { final ScanInfo info = ScanHandlerUtil.getScanInfo(event); if (info == null) return null; final IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event); try { final IWorkbenchPage page = window.getActivePage(); final String secondary = ScanPlotView.getNextViewID(); final ScanPlotView view = (ScanPlotView) page.showView(ScanUIActivator.ID_SCAN_PLOT_VIEW, secondary, IWorkbenchPage.VIEW_ACTIVATE); view.selectScan(info.getName(), info.getId()); } catch (Exception ex) { ExceptionDetailsErrorDialog.openError(window.getShell(), Messages.Error, Messages.OpenPlotError, ex); } return null; } }
epl-1.0
openhab/openhab2
bundles/org.openhab.binding.sleepiq/src/main/java/org/openhab/binding/sleepiq/internal/config/SleepIQCloudConfiguration.java
849
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.sleepiq.internal.config; /** * Configuration class for the SleepIQ cloud. * * @author Gregory Moyer - Initial contribution */ public class SleepIQCloudConfiguration { public static final String USERNAME = "username"; public static final String PASSWORD = "password"; public static final String POLLING_INTERVAL = "pollingInterval"; public String username; public String password; public int pollingInterval; }
epl-1.0
alastrina123/debrief
org.mwc.cmap.legacy/src/MWC/GUI/JFreeChart/RelBearingFormatter.java
1234
/* * Debrief - the Open Source Maritime Analysis Application * http://debrief.info * * (C) 2000-2014, PlanetMayo Ltd * * This library is free software; you can redistribute it and/or * modify it under the terms of the Eclipse Public License v1.0 * (http://www.eclipse.org/legal/epl-v10.html) * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ package MWC.GUI.JFreeChart; import java.io.Serializable; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.plot.XYPlot; public class RelBearingFormatter implements formattingOperation, Serializable { /** * */ private static final long serialVersionUID = 1L; public void format(final XYPlot thePlot) { final NumberAxis theAxis = (NumberAxis) thePlot.getRangeAxis(); theAxis.setRange(-180, +180); theAxis.setLabel("(Red) " + theAxis.getLabel() + " (Green)"); // create some tick units suitable for degrees theAxis.setStandardTickUnits(CourseFormatter.getDegreeTickUnits()); theAxis.setAutoTickUnitSelection(true); } }
epl-1.0
akervern/che
ide/che-core-ide-api/src/main/java/org/eclipse/che/ide/api/command/CommandImpl.java
8088
/* * Copyright (c) 2012-2018 Red Hat, Inc. * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 * which is available at https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Red Hat, Inc. - initial API and implementation */ package org.eclipse.che.ide.api.command; import static java.util.Collections.unmodifiableSet; import static org.eclipse.che.api.workspace.shared.Constants.COMMAND_GOAL_ATTRIBUTE_NAME; import static org.eclipse.che.api.workspace.shared.Constants.COMMAND_PREVIEW_URL_ATTRIBUTE_NAME; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Objects; import java.util.Set; import org.eclipse.che.api.core.model.workspace.config.Command; import org.eclipse.che.commons.annotation.Nullable; /** Data object for {@link Command}. */ public class CommandImpl implements Command { private final String typeId; private final ApplicableContext context; private String name; private String commandLine; private Map<String, String> attributes; /** Creates new {@link CommandImpl} based on the given data. */ public CommandImpl(Command command, ApplicableContext context) { this( command.getName(), command.getCommandLine(), command.getType(), new HashMap<>(command.getAttributes()), context); } /** Creates new {@link CommandImpl} based on the provided data. */ public CommandImpl(String name, String commandLine, String typeId) { this(name, commandLine, typeId, new HashMap<>()); } /** Creates copy of the given {@link Command}. */ public CommandImpl(Command command) { this( command.getName(), command.getCommandLine(), command.getType(), new HashMap<>(command.getAttributes())); } /** Creates copy of the given {@code command}. */ public CommandImpl(CommandImpl command) { this( command.getName(), command.getCommandLine(), command.getType(), new HashMap<>(command.getAttributes()), new ApplicableContext(command.getApplicableContext())); } /** Creates new {@link CommandImpl} based on the provided data. */ public CommandImpl( String name, String commandLine, String typeId, Map<String, String> attributes) { this.name = name; this.commandLine = commandLine; this.typeId = typeId; this.attributes = attributes; this.context = new ApplicableContext(); } /** Creates new {@link CommandImpl} based on the provided data. */ public CommandImpl( String name, String commandLine, String typeId, Map<String, String> attributes, ApplicableContext context) { this.name = name; this.commandLine = commandLine; this.typeId = typeId; this.attributes = attributes; this.context = context; } @Override public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String getCommandLine() { return commandLine; } public void setCommandLine(String commandLine) { this.commandLine = commandLine; } @Override public String getType() { return typeId; } @Override public Map<String, String> getAttributes() { return attributes; } public void setAttributes(Map<String, String> attributes) { this.attributes = attributes; } /** Returns ID of the command's goal or {@code null} if none. */ @Nullable public String getGoal() { return getAttributes().get(COMMAND_GOAL_ATTRIBUTE_NAME); } /** Sets command's goal ID. */ public void setGoal(String goalId) { getAttributes().put(COMMAND_GOAL_ATTRIBUTE_NAME, goalId); } /** Returns command's preview URL or {@code null} if none. */ @Nullable public String getPreviewURL() { return getAttributes().get(COMMAND_PREVIEW_URL_ATTRIBUTE_NAME); } /** Sets command's preview URL. */ public void setPreviewURL(String previewURL) { getAttributes().put(COMMAND_PREVIEW_URL_ATTRIBUTE_NAME, previewURL); } /** Returns command's applicable context. */ public ApplicableContext getApplicableContext() { return context; } /** * {@inheritDoc} * * @see #equalsIgnoreContext(CommandImpl) */ @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof CommandImpl)) { return false; } CommandImpl other = (CommandImpl) o; return Objects.equals(getName(), other.getName()) && Objects.equals(typeId, other.typeId) && Objects.equals(commandLine, other.commandLine) && Objects.equals(getAttributes(), other.getAttributes()) && Objects.equals(getApplicableContext(), other.getApplicableContext()); } /** * Compares this {@link CommandImpl} to another {@link CommandImpl}, ignoring applicable context * considerations. * * @param anotherCommand the {@link CommandImpl} to compare this {@link CommandImpl} against * @return {@code true} if the argument represents an equivalent {@link CommandImpl} ignoring * applicable context; {@code false} otherwise */ public boolean equalsIgnoreContext(CommandImpl anotherCommand) { if (this == anotherCommand) { return true; } return Objects.equals(getName(), anotherCommand.getName()) && Objects.equals(typeId, anotherCommand.typeId) && Objects.equals(commandLine, anotherCommand.commandLine) && Objects.equals(getAttributes(), anotherCommand.getAttributes()); } @Override public int hashCode() { return Objects.hash(name, typeId, commandLine, getAttributes(), getApplicableContext()); } /** Defines the context in which command is applicable. */ public static class ApplicableContext { private boolean workspaceApplicable; private Set<String> projects; /** Creates new {@link ApplicableContext} which is workspace applicable. */ public ApplicableContext() { workspaceApplicable = true; projects = new HashSet<>(); } /** Creates new {@link ApplicableContext} which is applicable to the single project only. */ public ApplicableContext(String projectPath) { projects = new HashSet<>(); projects.add(projectPath); } /** Creates new {@link ApplicableContext} based on the provided data. */ public ApplicableContext(boolean workspaceApplicable, Set<String> projects) { this.workspaceApplicable = workspaceApplicable; this.projects = projects; } /** Creates copy of the given {@code context}. */ public ApplicableContext(ApplicableContext context) { this(context.isWorkspaceApplicable(), new HashSet<>(context.getApplicableProjects())); } /** * Returns {@code true} if command is applicable to the workspace and {@code false} otherwise. */ public boolean isWorkspaceApplicable() { return workspaceApplicable; } /** Sets whether the command should be applicable to the workspace or not. */ public void setWorkspaceApplicable(boolean applicable) { this.workspaceApplicable = applicable; } /** Returns <b>immutable</b> list of the paths of the applicable projects. */ public Set<String> getApplicableProjects() { return unmodifiableSet(projects); } /** Adds applicable project's path. */ public void addProject(String path) { projects.add(path); } /** Removes applicable project's path. */ public void removeProject(String path) { projects.remove(path); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof ApplicableContext)) { return false; } ApplicableContext other = (ApplicableContext) o; return workspaceApplicable == other.workspaceApplicable && Objects.equals(projects, other.projects); } @Override public int hashCode() { return Objects.hash(workspaceApplicable, projects); } } }
epl-1.0
sytone/ToDoList_Plugins
ImportExport/MarkdownImpExp/MarkdownLog/TableView.cs
2500
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MarkdownLog { public class TableView : MarkdownElement { private IEnumerable<TableViewSection> _sections = new List<TableViewSection>(); public TableView() { } public TableView(IEnumerable<IosTableViewCell> cells) { Sections = new[] {new TableViewSection {Cells = cells}}; } public IEnumerable<TableViewSection> Sections { get { return _sections; } set { _sections = value ?? Enumerable.Empty<TableViewSection>(); } } public override string ToMarkdown() { var builder = new StringBuilder(); var indent = new string(' ', 4); var rows = Sections .Where(i => i.Header != null).Select(i => i.Header.RequiredWidth) .Concat(Sections.SelectMany(i => i.Cells.Select(j => j.RequiredWidth))) .ToList(); if (!rows.Any()) return ""; var widestCell = rows.Max(); var horizontalLine = " " + new String('-', widestCell); var containedHorizontalLine = "|" + new String('-', widestCell) + "|"; builder.Append(indent); builder.AppendLine(horizontalLine); foreach (var section in Sections) { var isFirstSection = Sections.ElementAt(0) == section; if (!isFirstSection) { builder.Append(indent); builder.AppendLine(containedHorizontalLine); } if (section.Header != null) { builder.Append(indent); builder.AppendFormat("|{0}|", section.Header.BuildCodeFormattedString(widestCell).PadRight(widestCell)); builder.AppendLine(); builder.Append(indent); builder.AppendLine(containedHorizontalLine); } foreach (var cell in section.Cells) { builder.Append(indent); builder.AppendFormat("|{0}|", cell.BuildCodeFormattedString(widestCell).PadRight(widestCell)); builder.AppendLine(); } } builder.Append(indent); builder.AppendLine(horizontalLine); return builder.ToString(); } } }
epl-1.0
rfdrake/opennms
core/snmp/impl-snmp4j/src/main/java/org/opennms/netmgt/snmp/snmp4j/Snmp4JValueFactory.java
3130
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2011-2012 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * OpenNMS(R) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.netmgt.snmp.snmp4j; import java.math.BigInteger; import java.net.InetAddress; import org.opennms.netmgt.snmp.SnmpObjId; import org.opennms.netmgt.snmp.SnmpValue; import org.opennms.netmgt.snmp.SnmpValueFactory; import org.snmp4j.smi.Counter32; import org.snmp4j.smi.Counter64; import org.snmp4j.smi.Gauge32; import org.snmp4j.smi.Integer32; import org.snmp4j.smi.IpAddress; import org.snmp4j.smi.Null; import org.snmp4j.smi.OID; import org.snmp4j.smi.OctetString; import org.snmp4j.smi.Opaque; import org.snmp4j.smi.TimeTicks; public class Snmp4JValueFactory implements SnmpValueFactory { @Override public SnmpValue getOctetString(byte[] bytes) { return new Snmp4JValue(new OctetString(bytes)); } @Override public SnmpValue getCounter32(long val) { return new Snmp4JValue(new Counter32(val)); } @Override public SnmpValue getCounter64(BigInteger bigInt) { return new Snmp4JValue(new Counter64(bigInt.longValue())); } @Override public SnmpValue getGauge32(long val) { return new Snmp4JValue(new Gauge32(val)); } @Override public SnmpValue getInt32(int val) { return new Snmp4JValue(new Integer32(val)); } @Override public SnmpValue getIpAddress(InetAddress val) { return new Snmp4JValue(new IpAddress(val)); } @Override public SnmpValue getObjectId(SnmpObjId objId) { return new Snmp4JValue(new OID(objId.getIds())); } @Override public SnmpValue getTimeTicks(long val) { return new Snmp4JValue(new TimeTicks(val)); } @Override public SnmpValue getNull() { return new Snmp4JValue(new Null()); } @Override public SnmpValue getValue(int type, byte[] bytes) { return new Snmp4JValue(type, bytes); } @Override public SnmpValue getOpaque(byte[] bs) { return new Snmp4JValue(new Opaque(bs)); } }
gpl-2.0