code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30 values | license stringclasses 15 values | size int64 3 1.01M |
|---|---|---|---|---|---|
import os.path
from django.conf import settings
from django.test.utils import override_settings
import mock
from celery.result import AsyncResult
from olympia import amo
from olympia.amo.tests import TestCase, addon_factory, version_factory
from olympia.devhub import tasks, utils
from olympia.files.models import FileUpload
class TestValidatorBase(TestCase):
def setUp(self):
# Create File objects for version 1.0 and 1.1.
self.addon = addon_factory(
guid='test-desktop@nowhere', slug='test-amo-addon',
version_kw={'version': '1.0'})
self.version = self.addon.current_version
self.file = self.version.files.get()
self.version_1_1 = version_factory(addon=self.addon, version='1.1')
self.file_1_1 = self.version_1_1.files.get()
# Creating the files and versions above resets this.
self.addon.update(status=amo.STATUS_PUBLIC)
# Create a FileUpload object for an XPI containing version 1.1.
path = os.path.join(settings.ROOT,
'src/olympia/devhub/tests/addons/desktop.xpi')
self.file_upload = FileUpload.objects.create(path=path)
self.xpi_version = '1.1'
# Patch validation tasks that we expect the validator to call.
self.patchers = []
self.save_file = self.patch(
'olympia.devhub.tasks.handle_file_validation_result').subtask
self.save_upload = self.patch(
'olympia.devhub.tasks.handle_upload_validation_result').subtask
self.validate_file = self.patch(
'olympia.devhub.tasks.validate_file').subtask
self.validate_upload = self.patch(
'olympia.devhub.tasks.validate_file_path').subtask
def patch(self, thing):
"""Patch the given "thing", and revert the patch on test teardown."""
patcher = mock.patch(thing)
self.addCleanup(patcher.stop)
return patcher.start()
def check_upload(self, file_upload, listed=True):
"""Check that the given new file upload is validated properly."""
# Run validator.
utils.Validator(file_upload, listed=listed)
# We shouldn't be attempting to validate an existing file.
assert not self.validate_file.called
# Make sure we run the correct validation task for the upload.
self.validate_upload.assert_called_once_with(
[file_upload.path],
{'hash_': file_upload.hash, 'listed': listed,
'is_webextension': False})
# Make sure we run the correct save validation task, with a
# fallback error handler.
channel = (amo.RELEASE_CHANNEL_LISTED if listed
else amo.RELEASE_CHANNEL_UNLISTED)
self.save_upload.assert_has_calls([
mock.call([mock.ANY, file_upload.pk, channel, False],
immutable=True),
mock.call([file_upload.pk, channel, False], link_error=mock.ANY)])
def check_file(self, file_):
"""Check that the given file is validated properly."""
# Run validator.
utils.Validator(file_)
# We shouldn't be attempting to validate a bare upload.
assert not self.validate_upload.called
# Make sure we run the correct validation task.
self.validate_file.assert_called_once_with(
[file_.pk],
{'hash_': file_.original_hash, 'is_webextension': False})
# Make sure we run the correct save validation task, with a
# fallback error handler.
self.save_file.assert_has_calls([
mock.call([mock.ANY, file_.pk, file_.version.channel, False],
immutable=True),
mock.call([file_.pk, file_.version.channel, False],
link_error=mock.ANY)])
class TestValidatorListed(TestValidatorBase):
@mock.patch('olympia.devhub.utils.chain')
def test_run_once_per_file(self, chain):
"""Tests that only a single validation task is run for a given file."""
task = mock.Mock()
chain.return_value = task
task.delay.return_value = mock.Mock(task_id='42')
assert isinstance(tasks.validate(self.file), mock.Mock)
assert task.delay.call_count == 1
assert isinstance(tasks.validate(self.file), AsyncResult)
assert task.delay.call_count == 1
assert isinstance(tasks.validate(self.file_1_1), mock.Mock)
assert task.delay.call_count == 2
@mock.patch('olympia.devhub.utils.chain')
def test_run_once_file_upload(self, chain):
"""Tests that only a single validation task is run for a given file
upload."""
task = mock.Mock()
chain.return_value = task
task.delay.return_value = mock.Mock(task_id='42')
assert isinstance(
tasks.validate(self.file_upload, listed=True), mock.Mock)
assert task.delay.call_count == 1
assert isinstance(
tasks.validate(self.file_upload, listed=True), AsyncResult)
assert task.delay.call_count == 1
def test_cache_key(self):
"""Tests that the correct cache key is generated for a given object."""
assert (utils.Validator(self.file).cache_key ==
'validation-task:files.File:{0}:None'.format(self.file.pk))
assert (utils.Validator(self.file_upload, listed=False).cache_key ==
'validation-task:files.FileUpload:{0}:False'.format(
self.file_upload.pk))
@mock.patch('olympia.devhub.utils.parse_addon')
def test_search_plugin(self, parse_addon):
"""Test that search plugins are handled correctly."""
parse_addon.return_value = {
'guid': None,
'version': '20140103',
'is_webextension': False,
}
addon = addon_factory(type=amo.ADDON_SEARCH,
version_kw={'version': '20140101'})
assert addon.guid is None
self.check_upload(self.file_upload)
self.validate_upload.reset_mock()
self.save_file.reset_mock()
version = version_factory(addon=addon, version='20140102')
self.check_file(version.files.get())
class TestLimitValidationResults(TestCase):
"""Test that higher priority messages are truncated last."""
def make_validation(self, types):
"""Take a list of error types and make a
validation results dict."""
validation = {
'messages': [],
'errors': 0,
'warnings': 0,
'notices': 0,
}
severities = ['low', 'medium', 'high']
for type_ in types:
if type_ in severities:
type_ = 'warning'
validation[type_ + 's'] += 1
validation['messages'].append({'type': type_})
return validation
@override_settings(VALIDATOR_MESSAGE_LIMIT=2)
def test_errors_are_first(self):
validation = self.make_validation(
['error', 'warning', 'notice', 'error'])
utils.limit_validation_results(validation)
limited = validation['messages']
assert len(limited) == 3
assert '2 messages were truncated' in limited[0]['message']
assert limited[1]['type'] == 'error'
assert limited[2]['type'] == 'error'
class TestFixAddonsLinterOutput(TestCase):
def test_fix_output(self):
original_output = {
'count': 4,
'summary': {
'errors': 0,
'notices': 0,
'warnings': 4
},
'metadata': {
'manifestVersion': 2,
'name': 'My Dogs New Tab',
'type': 1,
'version': '2.13.15',
'architecture': 'extension',
'emptyFiles': [],
'jsLibs': {
'lib/vendor/jquery.js': 'jquery.2.1.4.jquery.js'
}
},
'errors': [],
'notices': [],
'warnings': [
{
'_type': 'warning',
'code': 'MANIFEST_PERMISSIONS',
'message': '/permissions: Unknown permissions ...',
'description': 'See https://mzl.la/1R1n1t0 ...',
'file': 'manifest.json'
},
{
'_type': 'warning',
'code': 'MANIFEST_PERMISSIONS',
'message': '/permissions: Unknown permissions ...',
'description': 'See https://mzl.la/1R1n1t0 ....',
'file': 'manifest.json'
},
{
'_type': 'warning',
'code': 'MANIFEST_CSP',
'message': '\'content_security_policy\' is ...',
'description': 'A custom content_security_policy ...'
},
{
'_type': 'warning',
'code': 'NO_DOCUMENT_WRITE',
'message': 'Use of document.write strongly discouraged.',
'description': 'document.write will fail in...',
'column': 13,
'file': 'lib/vendor/knockout.js',
'line': 5449
}
]
}
fixed = utils.fix_addons_linter_output(original_output)
assert fixed['success']
assert fixed['warnings'] == 4
assert 'uid' in fixed['messages'][0]
assert 'id' in fixed['messages'][0]
assert 'type' in fixed['messages'][0]
assert fixed['messages'][0]['tier'] == 1
assert fixed['compatibility_summary'] == {
'warnings': 0,
'errors': 0,
'notices': 0,
}
assert fixed['ending_tier'] == 5
assert fixed['metadata']['is_webextension'] is True
assert fixed['metadata']['processed_by_addons_linter'] is True
assert fixed['metadata']['listed'] is True
assert fixed['metadata']['identified_files'] == {
'lib/vendor/jquery.js': {'path': 'jquery.2.1.4.jquery.js'}
}
# Make sure original metadata was preserved.
for key, value in original_output['metadata'].items():
assert fixed['metadata'][key] == value
| lavish205/olympia | src/olympia/devhub/tests/test_utils.py | Python | bsd-3-clause | 10,323 |
"""
Test data sources
"""
from nose.tools import ok_, eq_
from carousel.tests import logging
from carousel.core import UREG
from carousel.core.data_sources import DataSource, DataParameter
from carousel.core.data_readers import XLRDReader
from carousel.tests import PROJ_PATH, TESTS_DIR
import os
LOGGER = logging.getLogger(__name__)
LOGGER.setLevel(logging.DEBUG)
TUSCON = os.path.join(PROJ_PATH, 'data', 'Tuscon.json')
XLRDREADER_TESTDATA = os.path.join(TESTS_DIR, 'xlrdreader_testdata.xlsx')
def test_datasource_metaclass():
"""
Test data source meta class.
"""
class DataSourceTest1(DataSource):
"""
Test data source with parameters in file.
"""
class Meta:
data_file = 'pvpower.json'
data_path = os.path.join(PROJ_PATH, 'data')
def __prepare_data__(self):
pass
data_test1 = DataSourceTest1(TUSCON)
ok_(isinstance(data_test1, DataSource))
eq_(data_test1.param_file, os.path.join(PROJ_PATH, 'data', 'pvpower.json'))
class DataSourceTest2(DataSource):
"""
Test data source with parameters in code.
"""
latitude = DataParameter(**{
"description": "latitude",
"units": "degrees",
"isconstant": True,
"dtype": "float",
"uncertainty": 1.0
})
longitude = DataParameter(**{
"description": "longitude",
"units": "degrees",
"isconstant": True,
"dtype": "float",
"uncertainty": 1.0
})
elevation = DataParameter(**{
"description": "altitude of site above sea level",
"units": "meters",
"isconstant": True,
"dtype": "float",
"uncertainty": 1.0
})
timestamp_start = DataParameter(**{
"description": "initial timestamp",
"isconstant": True,
"dtype": "datetime"
})
timestamp_count = DataParameter(**{
"description": "number of timesteps",
"isconstant": True,
"dtype": "int"
})
module = DataParameter(**{
"description": "PV module",
"isconstant": True,
"dtype": "str"
})
inverter = DataParameter(**{
"description": "PV inverter",
"isconstant": True,
"dtype": "str"
})
module_database = DataParameter(**{
"description": "module databases",
"isconstant": True,
"dtype": "str"
})
inverter_database = DataParameter(**{
"description": "inverter database",
"isconstant": True,
"dtype": "str"
})
Tamb = DataParameter(**{
"description": "average yearly ambient air temperature",
"units": "degC",
"isconstant": True,
"dtype": "float",
"uncertainty": 1.0
})
Uwind = DataParameter(**{
"description": "average yearly wind speed",
"units": "m/s",
"isconstant": True,
"dtype": "float",
"uncertainty": 1.0
})
surface_azimuth = DataParameter(**{
"description": "site rotation",
"units": "degrees",
"isconstant": True,
"dtype": "float",
"uncertainty": 1.0
})
timezone = DataParameter(**{
"description": "timezone",
"isconstant": True,
"dtype": "str"
})
def __prepare_data__(self):
pass
data_test2 = DataSourceTest2(TUSCON)
ok_(isinstance(data_test2, DataSource))
for k, val in data_test1.parameters.iteritems():
eq_(data_test2.parameters[k], val)
class DataSourceTest4(DataSource):
"""
Test data source with parameters in file.
"""
latitude = DataParameter(**{
"description": "latitude",
"units": "radians",
"isconstant": True,
"dtype": "float",
"uncertainty": 1.0
})
class Meta:
data_file = 'pvpower.json'
data_path = os.path.join(PROJ_PATH, 'data')
def __prepare_data__(self):
pass
data_test4 = DataSourceTest4(TUSCON)
ok_(isinstance(data_test4, DataSource))
eq_(data_test4['latitude'].u, UREG.radians)
eq_(data_test4.param_file, os.path.join(PROJ_PATH, 'data', 'pvpower.json'))
def test_xlrdreader_datasource():
"""
Test data source with xlrd reader.
"""
class DataSourceTest3(DataSource):
"""
Test data source with xlrd reader and params in file.
"""
class Meta:
data_reader = XLRDReader
data_file = 'xlrdreader_param.json'
data_path = TESTS_DIR
def __prepare_data__(self):
pass
data_test3 = DataSourceTest3(XLRDREADER_TESTDATA)
ok_(isinstance(data_test3, DataSource))
eq_(data_test3._meta.data_reader, XLRDReader)
os.remove(os.path.join(TESTS_DIR, 'xlrdreader_testdata.xlsx.json'))
LOGGER.debug('xlrdreader_testdata.xlsx.json has been cleaned')
if __name__ == '__main__':
test_datasource_metaclass()
test_xlrdreader_datasource()
| mikofski/Carousel | carousel/tests/test_data.py | Python | bsd-3-clause | 5,322 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_UI_VIEWS_LOCATION_BAR_LOCATION_BAR_CONTAINER_H_
#define CHROME_BROWSER_UI_VIEWS_LOCATION_BAR_LOCATION_BAR_CONTAINER_H_
#include "third_party/skia/include/core/SkColor.h"
#include "ui/views/view.h"
#include "ui/views/animation/bounds_animator.h"
#include "ui/views/animation/bounds_animator_observer.h"
class LocationBarView;
namespace views {
class NativeViewHost;
}
// LocationBarContainer contains the LocationBarView. Under aura it directly
// contains the LocationBarView, on windows an intermediary widget is used. The
// intermediary widget is used so that LocationBarContainer can be placed on top
// of other native views (such as web content).
// LocationBarContainer is positioned by ToolbarView, but it is a child of
// BrowserView. This is used when on the NTP.
class LocationBarContainer : public views::View,
public views::BoundsAnimatorObserver {
public:
// Creates a new LocationBarContainer as a child of |parent|.
LocationBarContainer(views::View* parent, bool instant_extended_api_enabled);
virtual ~LocationBarContainer();
// Sets whether the LocationBarContainer is in the toolbar.
void SetInToolbar(bool in_toolbar);
void SetLocationBarView(LocationBarView* view);
// Stacks this view at the top. More specifically stacks the layer (aura)
// or widget (windows) at the top of the stack. Used to ensure this is over
// web contents.
void StackAtTop();
// Animates to the specified position.
void AnimateTo(const gfx::Rect& bounds);
// Returns true if animating.
bool IsAnimating() const;
// Returns the target bounds if animating, or the actual bounds if not
// animating.
gfx::Rect GetTargetBounds();
// views::View overrides:
virtual std::string GetClassName() const OVERRIDE;
virtual gfx::Size GetPreferredSize() OVERRIDE;
virtual bool SkipDefaultKeyEventProcessing(
const views::KeyEvent& event) OVERRIDE;
virtual void GetAccessibleState(ui::AccessibleViewState* state) OVERRIDE;
// views::BoundsAnimatorObserver overrides:
virtual void OnBoundsAnimatorProgressed(
views::BoundsAnimator* animator) OVERRIDE {}
virtual void OnBoundsAnimatorDone(views::BoundsAnimator* animator) OVERRIDE;
protected:
virtual void OnFocus() OVERRIDE;
private:
// Sets up platform specific state.
void PlatformInit();
// Returns the background color.
static SkColor GetBackgroundColor();
// Returns animation duration in milliseconds.
static int GetAnimationDuration();
// Used to animate this view.
views::BoundsAnimator animator_;
// Parent the LocationBarView is added to.
views::View* view_parent_;
LocationBarView* location_bar_view_;
views::NativeViewHost* native_view_host_;
bool in_toolbar_;
DISALLOW_COPY_AND_ASSIGN(LocationBarContainer);
};
#endif // CHROME_BROWSER_UI_VIEWS_LOCATION_BAR_LOCATION_BAR_CONTAINER_H_
| keishi/chromium | chrome/browser/ui/views/location_bar/location_bar_container.h | C | bsd-3-clause | 3,070 |
<?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@magentocommerce.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.magentocommerce.com for more information.
*
* @category Mage
* @package Mage_Core
* @copyright Copyright (c) 2011 Magento Inc. (http://www.magentocommerce.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* Flag model
*
* @category Mage
* @package Mage_Core
* @author Magento Core Team <core@magentocommerce.com>
*/
class Mage_Core_Model_Resource_Flag extends Mage_Core_Model_Resource_Db_Abstract
{
/**
* Define main table
*
*/
protected function _construct()
{
$this->_init('core/flag', 'flag_id');
}
}
| 5452/durex | includes/src/Mage_Core_Model_Resource_Flag.php | PHP | bsd-3-clause | 1,322 |
Google Cloud Vision API for Ruby
=================================================
Google Cloud Vision API uses [Google API extensions][google-gax] to provide an
easy-to-use client library for the [Google Cloud Vision API][] (v1) defined in the [googleapis][] git repository
[googleapis]: https://github.com/googleapis/googleapis/tree/master/google/cloud/vision/v1
[google-gax]: https://github.com/googleapis/gax-ruby
[Google Cloud Vision API]: https://developers.google.com/apis-explorer/#p/vision/v1/
Getting started
---------------
google-cloud-vision will allow you to connect to the [Google Cloud Vision API][] and access all its methods.
In order to achieve so, you need to set up authentication, as well as install the library locally.
Setup Authentication
--------------------
To authenticate all of your API calls, first install and setup the [Google Cloud SDK][].
Once done, you can then run the following command in your terminal:
$ gcloud beta auth application-default login
or
$ gcloud auth login
Please see the [gcloud beta auth application-default login][] to find documentation showing the difference between these commands.
[Google Cloud SDK]: https://cloud.google.com/sdk/
[gcloud beta auth application-default login]: https://cloud.google.com/sdk/gcloud/reference/beta/auth/application-default/login
Installation
-------------------
Install this library using gem:
$ [sudo] gem install google-cloud-vision
At this point you are all set to continue. | landrito/api-client-staging | generated/ruby/google-cloud-ruby/google-cloud-vision/README.md | Markdown | bsd-3-clause | 1,498 |
###############################################################################
# Copyright (c) 2013 Potential Ventures Ltd
# Copyright (c) 2013 SolarFlare Communications Inc
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of Potential Ventures Ltd,
# SolarFlare Communications Inc nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL POTENTIAL VENTURES LTD 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.
###############################################################################
# Default to verilog
GPI_IMPL ?= vpi
WPWD=$(shell sh -c 'pwd -W')
PWD=$(shell pwd)
COCOTB=$(PWD)/../../..
ifeq ($(OS),Msys)
WPWD=$(shell sh -c 'pwd -W')
PYTHONPATH := $(PWD)/../cosim;$(PYTHONPATH)
else
WPWD=$(shell pwd)
PYTHONPATH := $(PWD)/../cosim:$(PYTHONPATH)
endif
export PYTHONPATH
ifeq ($(GPI_IMPL),vpi)
VERILOG_SOURCES = $(WPWD)/../hdl/endian_swapper.sv
TOPLEVEL = endian_swapper_sv
GPI_IMPL=vpi
endif
ifeq ($(GPI_IMPL),vhpi)
VHDL_SOURCES = $(WPWD)/../hdl/endian_swapper.vhdl
TOPLEVEL = endian_swapper_vhdl
GPI_IMPL=vhpi
endif
MODULE=test_endian_swapper
CUSTOM_COMPILE_DEPS = hal
LD_LIBRARY_PATH := $(PWD)/../cosim:$(LD_LIBRARY_PATH)
export LD_LIBRARY_PATH
include $(COCOTB)/makefiles/Makefile.inc
include $(COCOTB)/makefiles/Makefile.sim
.PHONY: hal
hal:
-cd ../cosim && make
# Stuff below is useful for profiling
# Need grof2dot from https://code.google.com/p/jrfonseca.gprof2dot/
test_profile.pstat: sim
callgraph.svg: test_profile.pstat
gprof2dot.py -f pstats $< | dot -Tsvg -o $@
.PHONY: profile
profile:
COCOTB_ENABLE_PROFILING=1 $(MAKE) callgraph.svg
clean::
-rm -rf test_profile.pstat
-rm -rf callgraph.svg
-cd ../cosim && make clean
| stuarthodgson/cocotb | examples/endian_swapper/tests/Makefile | Makefile | bsd-3-clause | 3,008 |
/*
Copyright (c) 2015, Apple Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
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(s) nor the names of any contributors
may be used to endorse or promote products derived from this software without
specific prior written permission. No license is granted to the trademarks of
the copyright holders even if such marks are included in this software.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import <ResearchKit/ResearchKit_Private.h>
#import "ORKConsentSection.h"
NS_ASSUME_NONNULL_BEGIN
NSURL *__nullable ORKMovieURLForConsentSectionType(ORKConsentSectionType type);
UIImage *__nullable ORKImageForConsentSectionType(ORKConsentSectionType type);
NS_ASSUME_NONNULL_END
| jianwoo/ResearchKit | ResearchKit/Consent/ORKConsentSection+AssetLoading.h | C | bsd-3-clause | 1,919 |
{-# LANGUAGE Haskell2010 #-}
{-# LINE 1 "System/Process/Common.hs" #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE RecordWildCards #-}
module System.Process.Common
( CreateProcess (..)
, CmdSpec (..)
, StdStream (..)
, ProcessHandle(..)
, ProcessHandle__(..)
, ProcRetHandles (..)
, withFilePathException
, PHANDLE
, modifyProcessHandle
, withProcessHandle
, fd_stdin
, fd_stdout
, fd_stderr
, mbFd
, mbPipe
, pfdToHandle
-- Avoid a warning on Windows
, CGid
) where
import Control.Concurrent
import Control.Exception
import Data.String
import Foreign.Ptr
import Foreign.Storable
import System.Posix.Internals
import GHC.IO.Exception
import GHC.IO.Encoding
import qualified GHC.IO.FD as FD
import GHC.IO.Device
import GHC.IO.Handle.FD
import GHC.IO.Handle.Internals
import GHC.IO.Handle.Types hiding (ClosedHandle)
import System.IO.Error
import Data.Typeable
import GHC.IO.IOMode
-- We do a minimal amount of CPP here to provide uniform data types across
-- Windows and POSIX.
import System.Posix.Types
type PHANDLE = CPid
data CreateProcess = CreateProcess{
cmdspec :: CmdSpec, -- ^ Executable & arguments, or shell command. If 'cwd' is 'Nothing', relative paths are resolved with respect to the current working directory. If 'cwd' is provided, it is implementation-dependent whether relative paths are resolved with respect to 'cwd' or the current working directory, so absolute paths should be used to ensure portability.
cwd :: Maybe FilePath, -- ^ Optional path to the working directory for the new process
env :: Maybe [(String,String)], -- ^ Optional environment (otherwise inherit from the current process)
std_in :: StdStream, -- ^ How to determine stdin
std_out :: StdStream, -- ^ How to determine stdout
std_err :: StdStream, -- ^ How to determine stderr
close_fds :: Bool, -- ^ Close all file descriptors except stdin, stdout and stderr in the new process (on Windows, only works if std_in, std_out, and std_err are all Inherit)
create_group :: Bool, -- ^ Create a new process group
delegate_ctlc:: Bool, -- ^ Delegate control-C handling. Use this for interactive console processes to let them handle control-C themselves (see below for details).
--
-- On Windows this has no effect.
--
-- @since 1.2.0.0
detach_console :: Bool, -- ^ Use the windows DETACHED_PROCESS flag when creating the process; does nothing on other platforms.
--
-- @since 1.3.0.0
create_new_console :: Bool, -- ^ Use the windows CREATE_NEW_CONSOLE flag when creating the process; does nothing on other platforms.
--
-- Default: @False@
--
-- @since 1.3.0.0
new_session :: Bool, -- ^ Use posix setsid to start the new process in a new session; does nothing on other platforms.
--
-- @since 1.3.0.0
child_group :: Maybe GroupID, -- ^ Use posix setgid to set child process's group id; does nothing on other platforms.
--
-- Default: @Nothing@
--
-- @since 1.4.0.0
child_user :: Maybe UserID, -- ^ Use posix setuid to set child process's user id; does nothing on other platforms.
--
-- Default: @Nothing@
--
-- @since 1.4.0.0
use_process_jobs :: Bool -- ^ On Windows systems this flag indicates that we should wait for the entire process tree
-- to finish before unblocking. On POSIX systems this flag is ignored.
--
-- Default: @False@
--
-- @since 1.5.0.0
} deriving (Show, Eq)
-- | contains the handles returned by a call to createProcess_Internal
data ProcRetHandles
= ProcRetHandles { hStdInput :: Maybe Handle
, hStdOutput :: Maybe Handle
, hStdError :: Maybe Handle
, procHandle :: ProcessHandle
}
data CmdSpec
= ShellCommand String
-- ^ A command line to execute using the shell
| RawCommand FilePath [String]
-- ^ The name of an executable with a list of arguments
--
-- The 'FilePath' argument names the executable, and is interpreted
-- according to the platform's standard policy for searching for
-- executables. Specifically:
--
-- * on Unix systems the
-- <http://pubs.opengroup.org/onlinepubs/9699919799/functions/execvp.html execvp(3)>
-- semantics is used, where if the executable filename does not
-- contain a slash (@/@) then the @PATH@ environment variable is
-- searched for the executable.
--
-- * on Windows systems the Win32 @CreateProcess@ semantics is used.
-- Briefly: if the filename does not contain a path, then the
-- directory containing the parent executable is searched, followed
-- by the current directory, then some standard locations, and
-- finally the current @PATH@. An @.exe@ extension is added if the
-- filename does not already have an extension. For full details
-- see the
-- <http://msdn.microsoft.com/en-us/library/windows/desktop/aa365527%28v=vs.85%29.aspx documentation>
-- for the Windows @SearchPath@ API.
deriving (Show, Eq)
-- | construct a `ShellCommand` from a string literal
--
-- @since 1.2.1.0
instance IsString CmdSpec where
fromString = ShellCommand
data StdStream
= Inherit -- ^ Inherit Handle from parent
| UseHandle Handle -- ^ Use the supplied Handle
| CreatePipe -- ^ Create a new pipe. The returned
-- @Handle@ will use the default encoding
-- and newline translation mode (just
-- like @Handle@s created by @openFile@).
| NoStream -- ^ No stream handle will be passed
deriving (Eq, Show)
-- ----------------------------------------------------------------------------
-- ProcessHandle type
{- | A handle to a process, which can be used to wait for termination
of the process using 'System.Process.waitForProcess'.
None of the process-creation functions in this library wait for
termination: they all return a 'ProcessHandle' which may be used
to wait for the process later.
On Windows a second wait method can be used to block for event
completion. This requires two handles. A process job handle and
a events handle to monitor.
-}
data ProcessHandle__ = OpenHandle PHANDLE
| OpenExtHandle PHANDLE PHANDLE PHANDLE
| ClosedHandle ExitCode
data ProcessHandle
= ProcessHandle { phandle :: !(MVar ProcessHandle__)
, mb_delegate_ctlc :: !Bool
, waitpidLock :: !(MVar ())
}
withFilePathException :: FilePath -> IO a -> IO a
withFilePathException fpath act = handle mapEx act
where
mapEx ex = ioError (ioeSetFileName ex fpath)
modifyProcessHandle
:: ProcessHandle
-> (ProcessHandle__ -> IO (ProcessHandle__, a))
-> IO a
modifyProcessHandle (ProcessHandle m _ _) io = modifyMVar m io
withProcessHandle
:: ProcessHandle
-> (ProcessHandle__ -> IO a)
-> IO a
withProcessHandle (ProcessHandle m _ _) io = withMVar m io
fd_stdin, fd_stdout, fd_stderr :: FD
fd_stdin = 0
fd_stdout = 1
fd_stderr = 2
mbFd :: String -> FD -> StdStream -> IO FD
mbFd _ _std CreatePipe = return (-1)
mbFd _fun std Inherit = return std
mbFd _fn _std NoStream = return (-2)
mbFd fun _std (UseHandle hdl) =
withHandle fun hdl $ \Handle__{haDevice=dev,..} ->
case cast dev of
Just fd -> do
-- clear the O_NONBLOCK flag on this FD, if it is set, since
-- we're exposing it externally (see #3316)
fd' <- FD.setNonBlockingMode fd False
return (Handle__{haDevice=fd',..}, FD.fdFD fd')
Nothing ->
ioError (mkIOError illegalOperationErrorType
"createProcess" (Just hdl) Nothing
`ioeSetErrorString` "handle is not a file descriptor")
mbPipe :: StdStream -> Ptr FD -> IOMode -> IO (Maybe Handle)
mbPipe CreatePipe pfd mode = fmap Just (pfdToHandle pfd mode)
mbPipe _std _pfd _mode = return Nothing
pfdToHandle :: Ptr FD -> IOMode -> IO Handle
pfdToHandle pfd mode = do
fd <- peek pfd
let filepath = "fd:" ++ show fd
(fD,fd_type) <- FD.mkFD (fromIntegral fd) mode
(Just (Stream,0,0)) -- avoid calling fstat()
False {-is_socket-}
False {-non-blocking-}
fD' <- FD.setNonBlockingMode fD True -- see #3316
enc <- getLocaleEncoding
mkHandleFromFD fD' fd_type filepath mode False {-is_socket-} (Just enc)
| phischu/fragnix | tests/packages/scotty/System.Process.Common.hs | Haskell | bsd-3-clause | 9,966 |
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 4.0.2
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info as _swig_python_version_info
if _swig_python_version_info < (2, 7, 0):
raise RuntimeError("Python 2.7 or later required")
# Import the low-level C/C++ module
if __package__ or "." in __name__:
from . import _stable3d
else:
import _stable3d
try:
import builtins as __builtin__
except ImportError:
import __builtin__
_swig_new_instance_method = _stable3d.SWIG_PyInstanceMethod_New
_swig_new_static_method = _stable3d.SWIG_PyStaticMethod_New
def _swig_repr(self):
try:
strthis = "proxy of " + self.this.__repr__()
except __builtin__.Exception:
strthis = ""
return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,)
def _swig_setattr_nondynamic_instance_variable(set):
def set_instance_attr(self, name, value):
if name == "thisown":
self.this.own(value)
elif name == "this":
set(self, name, value)
elif hasattr(self, name) and isinstance(getattr(type(self), name), property):
set(self, name, value)
else:
raise AttributeError("You cannot add instance attributes to %s" % self)
return set_instance_attr
def _swig_setattr_nondynamic_class_variable(set):
def set_class_attr(cls, name, value):
if hasattr(cls, name) and not isinstance(getattr(cls, name), property):
set(cls, name, value)
else:
raise AttributeError("You cannot add class attributes to %s" % cls)
return set_class_attr
def _swig_add_metaclass(metaclass):
"""Class decorator for adding a metaclass to a SWIG wrapped class - a slimmed down version of six.add_metaclass"""
def wrapper(cls):
return metaclass(cls.__name__, cls.__bases__, cls.__dict__.copy())
return wrapper
class _SwigNonDynamicMeta(type):
"""Meta class to enforce nondynamic attributes (no new attributes) for a class"""
__setattr__ = _swig_setattr_nondynamic_class_variable(type.__setattr__)
import weakref
import mfem._ser.element
import mfem._ser.globals
import mfem._ser.array
import mfem._ser.mem_manager
import mfem._ser.densemat
import mfem._ser.vector
import mfem._ser.operators
import mfem._ser.matrix
import mfem._ser.geom
import mfem._ser.intrules
import mfem._ser.table
import mfem._ser.hash
class STable3DNode(object):
r"""Proxy of C++ mfem::STable3DNode class."""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
__repr__ = _swig_repr
Prev = property(_stable3d.STable3DNode_Prev_get, _stable3d.STable3DNode_Prev_set, doc=r"""Prev : p.mfem::STable3DNode""")
Column = property(_stable3d.STable3DNode_Column_get, _stable3d.STable3DNode_Column_set, doc=r"""Column : int""")
Floor = property(_stable3d.STable3DNode_Floor_get, _stable3d.STable3DNode_Floor_set, doc=r"""Floor : int""")
Number = property(_stable3d.STable3DNode_Number_get, _stable3d.STable3DNode_Number_set, doc=r"""Number : int""")
def __init__(self):
r"""__init__(STable3DNode self) -> STable3DNode"""
_stable3d.STable3DNode_swiginit(self, _stable3d.new_STable3DNode())
__swig_destroy__ = _stable3d.delete_STable3DNode
# Register STable3DNode in _stable3d:
_stable3d.STable3DNode_swigregister(STable3DNode)
class STable3D(object):
r"""Proxy of C++ mfem::STable3D class."""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
__repr__ = _swig_repr
def __init__(self, nr):
r"""__init__(STable3D self, int nr) -> STable3D"""
_stable3d.STable3D_swiginit(self, _stable3d.new_STable3D(nr))
def Push(self, r, c, f):
r"""Push(STable3D self, int r, int c, int f) -> int"""
return _stable3d.STable3D_Push(self, r, c, f)
Push = _swig_new_instance_method(_stable3d.STable3D_Push)
def Index(self, r, c, f):
r"""Index(STable3D self, int r, int c, int f) -> int"""
return _stable3d.STable3D_Index(self, r, c, f)
Index = _swig_new_instance_method(_stable3d.STable3D_Index)
def Push4(self, r, c, f, t):
r"""Push4(STable3D self, int r, int c, int f, int t) -> int"""
return _stable3d.STable3D_Push4(self, r, c, f, t)
Push4 = _swig_new_instance_method(_stable3d.STable3D_Push4)
def __call__(self, *args):
r"""
__call__(STable3D self, int r, int c, int f) -> int
__call__(STable3D self, int r, int c, int f, int t) -> int
"""
return _stable3d.STable3D___call__(self, *args)
__call__ = _swig_new_instance_method(_stable3d.STable3D___call__)
def NumberOfElements(self):
r"""NumberOfElements(STable3D self) -> int"""
return _stable3d.STable3D_NumberOfElements(self)
NumberOfElements = _swig_new_instance_method(_stable3d.STable3D_NumberOfElements)
__swig_destroy__ = _stable3d.delete_STable3D
def Print(self, *args):
r"""
Print(STable3D self, std::ostream & out=out)
Print(STable3D self, char const * file, int precision=16)
"""
return _stable3d.STable3D_Print(self, *args)
Print = _swig_new_instance_method(_stable3d.STable3D_Print)
def PrintGZ(self, file, precision=16):
r"""PrintGZ(STable3D self, char const * file, int precision=16)"""
return _stable3d.STable3D_PrintGZ(self, file, precision)
PrintGZ = _swig_new_instance_method(_stable3d.STable3D_PrintGZ)
# Register STable3D in _stable3d:
_stable3d.STable3D_swigregister(STable3D)
| mfem/PyMFEM | mfem/_ser/stable3d.py | Python | bsd-3-clause | 5,714 |
<?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@magentocommerce.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.magentocommerce.com for more information.
*
* @category Mage
* @package Mage_Payment
* @copyright Copyright (c) 2011 Magento Inc. (http://www.magentocommerce.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
class Mage_Payment_Model_Method_Purchaseorder extends Mage_Payment_Model_Method_Abstract
{
protected $_code = 'purchaseorder';
protected $_formBlockType = 'payment/form_purchaseorder';
protected $_infoBlockType = 'payment/info_purchaseorder';
/**
* Assign data to info model instance
*
* @param mixed $data
* @return Mage_Payment_Model_Method_Purchaseorder
*/
public function assignData($data)
{
if (!($data instanceof Varien_Object)) {
$data = new Varien_Object($data);
}
$this->getInfoInstance()->setPoNumber($data->getPoNumber());
return $this;
}
}
| 5452/durex | includes/src/Mage_Payment_Model_Method_Purchaseorder.php | PHP | bsd-3-clause | 1,620 |
<?php
defined('SYSPATH') or die ('no tiene acceso');
//descripcion del modelo productos
class Model_Users extends ORM{
protected $_table_names_plural = false;
//un usuario genera varios documentos
protected $_has_many=array(
'documentos'=>array(
'model'=>'documentos',
'foreign_key'=>'id_user'
),
'tipo'=>array(
'model' =>'tipos',
'through' => 'usertipo',
'foreign_key' => 'id_user',
'far_key' => 'id_tipo',
),
'destinos'=>array(
'model'=>'destinos',
'through' => 'destinatarios',
'foreign_key'=>'id_usuario',
'fair_key'=>'id_destino'
),
);
// un usuario (funcionario) pertenece a una oficina
protected $_belongs_to=array(
'oficina'=>array(
'model'=>'oficinas',
'foreign_key'=>'id_oficina'
),
);
//propiedades de un usuario
public function property($id){
$sql="SELECT u.id, u.dependencia, u.nombre,u.cargo,o.nombre, u.genero, u.id_oficina
FROM users u INNER JOIN oficinas o ON u.id_oficina=o.id
WHERE u.id='$id'";
return db::query(Database::SELECT, $sql)->execute();
}
/*Administrador*/
//lista de usuarios excepto quien lo
public function usuarios($id){
$sql="SELECT u.id, u.id_oficina, o.oficina, u.username, u.nombre, u.last_login,u.mosca,u.cargo,u.email,u.logins, u.fecha_creacion,u.genero,n.nivel FROM users u
INNER JOIN oficinas o ON u.id_oficina=o.id
INNER JOIN niveles n ON u.nivel=n.id
WHERE u.id <> '$id'";
return $this->_db->query(Database::SELECT, $sql, TRUE);
}
public function todo($id){
}
}
?>
| fredd-for/codice.v.1.1 | application/classes/model/users.php | PHP | bsd-3-clause | 1,887 |
/*
* Texas Instruments DA8xx/OMAP-L1x "glue layer"
*
* Copyright (c) 2008-2009 MontaVista Software, Inc. <source@mvista.com>
*
* Based on the DaVinci "glue layer" code.
* Copyright (C) 2005-2006 by Texas Instruments
*
* This file is part of the Inventra Controller Driver for Linux.
*
* The Inventra Controller Driver for Linux is free software; you
* can redistribute it and/or modify it under the terms of the GNU
* General Public License version 2 as published by the Free Software
* Foundation.
*
* The Inventra Controller Driver for Linux 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 The Inventra Controller Driver for Linux ; if not,
* write to the Free Software Foundation, Inc., 59 Temple Place,
* Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <linux/init.h>
#include <linux/clk.h>
#include <linux/io.h>
#include <linux/platform_device.h>
#include <linux/dma-mapping.h>
#include <mach/da8xx.h>
#include <mach/usb.h>
#include "musb_core.h"
/*
* DA8XX specific definitions
*/
/* USB 2.0 OTG module registers */
#define DA8XX_USB_REVISION_REG 0x00
#define DA8XX_USB_CTRL_REG 0x04
#define DA8XX_USB_STAT_REG 0x08
#define DA8XX_USB_EMULATION_REG 0x0c
#define DA8XX_USB_MODE_REG 0x10 /* Transparent, CDC, [Generic] RNDIS */
#define DA8XX_USB_AUTOREQ_REG 0x14
#define DA8XX_USB_SRP_FIX_TIME_REG 0x18
#define DA8XX_USB_TEARDOWN_REG 0x1c
#define DA8XX_USB_INTR_SRC_REG 0x20
#define DA8XX_USB_INTR_SRC_SET_REG 0x24
#define DA8XX_USB_INTR_SRC_CLEAR_REG 0x28
#define DA8XX_USB_INTR_MASK_REG 0x2c
#define DA8XX_USB_INTR_MASK_SET_REG 0x30
#define DA8XX_USB_INTR_MASK_CLEAR_REG 0x34
#define DA8XX_USB_INTR_SRC_MASKED_REG 0x38
#define DA8XX_USB_END_OF_INTR_REG 0x3c
#define DA8XX_USB_GENERIC_RNDIS_EP_SIZE_REG(n) (0x50 + (((n) - 1) << 2))
/* Control register bits */
#define DA8XX_SOFT_RESET_MASK 1
#define DA8XX_USB_TX_EP_MASK 0x1f /* EP0 + 4 Tx EPs */
#define DA8XX_USB_RX_EP_MASK 0x1e /* 4 Rx EPs */
/* USB interrupt register bits */
#define DA8XX_INTR_USB_SHIFT 16
#define DA8XX_INTR_USB_MASK (0x1ff << DA8XX_INTR_USB_SHIFT) /* 8 Mentor */
/* interrupts and DRVVBUS interrupt */
#define DA8XX_INTR_DRVVBUS 0x100
#define DA8XX_INTR_RX_SHIFT 8
#define DA8XX_INTR_RX_MASK (DA8XX_USB_RX_EP_MASK << DA8XX_INTR_RX_SHIFT)
#define DA8XX_INTR_TX_SHIFT 0
#define DA8XX_INTR_TX_MASK (DA8XX_USB_TX_EP_MASK << DA8XX_INTR_TX_SHIFT)
#define DA8XX_MENTOR_CORE_OFFSET 0x400
#define CFGCHIP2 IO_ADDRESS(DA8XX_SYSCFG0_BASE + DA8XX_CFGCHIP2_REG)
struct da8xx_glue {
struct device *dev;
struct platform_device *musb;
struct clk *clk;
};
/*
* REVISIT (PM): we should be able to keep the PHY in low power mode most
* of the time (24 MHz oscillator and PLL off, etc.) by setting POWER.D0
* and, when in host mode, autosuspending idle root ports... PHY_PLLON
* (overriding SUSPENDM?) then likely needs to stay off.
*/
static inline void phy_on(void)
{
u32 cfgchip2 = __raw_readl(CFGCHIP2);
/*
* Start the on-chip PHY and its PLL.
*/
cfgchip2 &= ~(CFGCHIP2_RESET | CFGCHIP2_PHYPWRDN | CFGCHIP2_OTGPWRDN);
cfgchip2 |= CFGCHIP2_PHY_PLLON;
__raw_writel(cfgchip2, CFGCHIP2);
pr_info("Waiting for USB PHY clock good...\n");
while (!(__raw_readl(CFGCHIP2) & CFGCHIP2_PHYCLKGD))
cpu_relax();
}
static inline void phy_off(void)
{
u32 cfgchip2 = __raw_readl(CFGCHIP2);
/*
* Ensure that USB 1.1 reference clock is not being sourced from
* USB 2.0 PHY. Otherwise do not power down the PHY.
*/
if (!(cfgchip2 & CFGCHIP2_USB1PHYCLKMUX) &&
(cfgchip2 & CFGCHIP2_USB1SUSPENDM)) {
pr_warning("USB 1.1 clocked from USB 2.0 PHY -- "
"can't power it down\n");
return;
}
/*
* Power down the on-chip PHY.
*/
cfgchip2 |= CFGCHIP2_PHYPWRDN | CFGCHIP2_OTGPWRDN;
__raw_writel(cfgchip2, CFGCHIP2);
}
/*
* Because we don't set CTRL.UINT, it's "important" to:
* - not read/write INTRUSB/INTRUSBE (except during
* initial setup, as a workaround);
* - use INTSET/INTCLR instead.
*/
/**
* da8xx_musb_enable - enable interrupts
*/
static void da8xx_musb_enable(struct musb *musb)
{
void __iomem *reg_base = musb->ctrl_base;
u32 mask;
/* Workaround: setup IRQs through both register sets. */
mask = ((musb->epmask & DA8XX_USB_TX_EP_MASK) << DA8XX_INTR_TX_SHIFT) |
((musb->epmask & DA8XX_USB_RX_EP_MASK) << DA8XX_INTR_RX_SHIFT) |
DA8XX_INTR_USB_MASK;
musb_writel(reg_base, DA8XX_USB_INTR_MASK_SET_REG, mask);
/* Force the DRVVBUS IRQ so we can start polling for ID change. */
if (is_otg_enabled(musb))
musb_writel(reg_base, DA8XX_USB_INTR_SRC_SET_REG,
DA8XX_INTR_DRVVBUS << DA8XX_INTR_USB_SHIFT);
}
/**
* da8xx_musb_disable - disable HDRC and flush interrupts
*/
static void da8xx_musb_disable(struct musb *musb)
{
void __iomem *reg_base = musb->ctrl_base;
musb_writel(reg_base, DA8XX_USB_INTR_MASK_CLEAR_REG,
DA8XX_INTR_USB_MASK |
DA8XX_INTR_TX_MASK | DA8XX_INTR_RX_MASK);
musb_writeb(musb->mregs, MUSB_DEVCTL, 0);
musb_writel(reg_base, DA8XX_USB_END_OF_INTR_REG, 0);
}
#ifdef CONFIG_USB_MUSB_HDRC_HCD
#define portstate(stmt) stmt
#else
#define portstate(stmt)
#endif
static void da8xx_musb_set_vbus(struct musb *musb, int is_on)
{
WARN_ON(is_on && is_peripheral_active(musb));
}
#define POLL_SECONDS 2
static struct timer_list otg_workaround;
static void otg_timer(unsigned long _musb)
{
struct musb *musb = (void *)_musb;
void __iomem *mregs = musb->mregs;
u8 devctl;
unsigned long flags;
/*
* We poll because DaVinci's won't expose several OTG-critical
* status change events (from the transceiver) otherwise.
*/
devctl = musb_readb(mregs, MUSB_DEVCTL);
DBG(7, "Poll devctl %02x (%s)\n", devctl, otg_state_string(musb));
spin_lock_irqsave(&musb->lock, flags);
switch (musb->xceiv->state) {
case OTG_STATE_A_WAIT_BCON:
devctl &= ~MUSB_DEVCTL_SESSION;
musb_writeb(musb->mregs, MUSB_DEVCTL, devctl);
devctl = musb_readb(musb->mregs, MUSB_DEVCTL);
if (devctl & MUSB_DEVCTL_BDEVICE) {
musb->xceiv->state = OTG_STATE_B_IDLE;
MUSB_DEV_MODE(musb);
} else {
musb->xceiv->state = OTG_STATE_A_IDLE;
MUSB_HST_MODE(musb);
}
break;
case OTG_STATE_A_WAIT_VFALL:
/*
* Wait till VBUS falls below SessionEnd (~0.2 V); the 1.3
* RTL seems to mis-handle session "start" otherwise (or in
* our case "recover"), in routine "VBUS was valid by the time
* VBUSERR got reported during enumeration" cases.
*/
if (devctl & MUSB_DEVCTL_VBUS) {
mod_timer(&otg_workaround, jiffies + POLL_SECONDS * HZ);
break;
}
musb->xceiv->state = OTG_STATE_A_WAIT_VRISE;
musb_writel(musb->ctrl_base, DA8XX_USB_INTR_SRC_SET_REG,
MUSB_INTR_VBUSERROR << DA8XX_INTR_USB_SHIFT);
break;
case OTG_STATE_B_IDLE:
if (!is_peripheral_enabled(musb))
break;
/*
* There's no ID-changed IRQ, so we have no good way to tell
* when to switch to the A-Default state machine (by setting
* the DEVCTL.Session bit).
*
* Workaround: whenever we're in B_IDLE, try setting the
* session flag every few seconds. If it works, ID was
* grounded and we're now in the A-Default state machine.
*
* NOTE: setting the session flag is _supposed_ to trigger
* SRP but clearly it doesn't.
*/
musb_writeb(mregs, MUSB_DEVCTL, devctl | MUSB_DEVCTL_SESSION);
devctl = musb_readb(mregs, MUSB_DEVCTL);
if (devctl & MUSB_DEVCTL_BDEVICE)
mod_timer(&otg_workaround, jiffies + POLL_SECONDS * HZ);
else
musb->xceiv->state = OTG_STATE_A_IDLE;
break;
default:
break;
}
spin_unlock_irqrestore(&musb->lock, flags);
}
static void da8xx_musb_try_idle(struct musb *musb, unsigned long timeout)
{
static unsigned long last_timer;
if (!is_otg_enabled(musb))
return;
if (timeout == 0)
timeout = jiffies + msecs_to_jiffies(3);
/* Never idle if active, or when VBUS timeout is not set as host */
if (musb->is_active || (musb->a_wait_bcon == 0 &&
musb->xceiv->state == OTG_STATE_A_WAIT_BCON)) {
DBG(4, "%s active, deleting timer\n", otg_state_string(musb));
del_timer(&otg_workaround);
last_timer = jiffies;
return;
}
if (time_after(last_timer, timeout) && timer_pending(&otg_workaround)) {
DBG(4, "Longer idle timer already pending, ignoring...\n");
return;
}
last_timer = timeout;
DBG(4, "%s inactive, starting idle timer for %u ms\n",
otg_state_string(musb), jiffies_to_msecs(timeout - jiffies));
mod_timer(&otg_workaround, timeout);
}
static irqreturn_t da8xx_musb_interrupt(int irq, void *hci)
{
struct musb *musb = hci;
void __iomem *reg_base = musb->ctrl_base;
unsigned long flags;
irqreturn_t ret = IRQ_NONE;
u32 status;
spin_lock_irqsave(&musb->lock, flags);
/*
* NOTE: DA8XX shadows the Mentor IRQs. Don't manage them through
* the Mentor registers (except for setup), use the TI ones and EOI.
*/
/* Acknowledge and handle non-CPPI interrupts */
status = musb_readl(reg_base, DA8XX_USB_INTR_SRC_MASKED_REG);
if (!status)
goto eoi;
musb_writel(reg_base, DA8XX_USB_INTR_SRC_CLEAR_REG, status);
DBG(4, "USB IRQ %08x\n", status);
musb->int_rx = (status & DA8XX_INTR_RX_MASK) >> DA8XX_INTR_RX_SHIFT;
musb->int_tx = (status & DA8XX_INTR_TX_MASK) >> DA8XX_INTR_TX_SHIFT;
musb->int_usb = (status & DA8XX_INTR_USB_MASK) >> DA8XX_INTR_USB_SHIFT;
/*
* DRVVBUS IRQs are the only proxy we have (a very poor one!) for
* DA8xx's missing ID change IRQ. We need an ID change IRQ to
* switch appropriately between halves of the OTG state machine.
* Managing DEVCTL.Session per Mentor docs requires that we know its
* value but DEVCTL.BDevice is invalid without DEVCTL.Session set.
* Also, DRVVBUS pulses for SRP (but not at 5 V)...
*/
if (status & (DA8XX_INTR_DRVVBUS << DA8XX_INTR_USB_SHIFT)) {
int drvvbus = musb_readl(reg_base, DA8XX_USB_STAT_REG);
void __iomem *mregs = musb->mregs;
u8 devctl = musb_readb(mregs, MUSB_DEVCTL);
int err;
err = is_host_enabled(musb) && (musb->int_usb &
MUSB_INTR_VBUSERROR);
if (err) {
/*
* The Mentor core doesn't debounce VBUS as needed
* to cope with device connect current spikes. This
* means it's not uncommon for bus-powered devices
* to get VBUS errors during enumeration.
*
* This is a workaround, but newer RTL from Mentor
* seems to allow a better one: "re"-starting sessions
* without waiting for VBUS to stop registering in
* devctl.
*/
musb->int_usb &= ~MUSB_INTR_VBUSERROR;
musb->xceiv->state = OTG_STATE_A_WAIT_VFALL;
mod_timer(&otg_workaround, jiffies + POLL_SECONDS * HZ);
WARNING("VBUS error workaround (delay coming)\n");
} else if (is_host_enabled(musb) && drvvbus) {
MUSB_HST_MODE(musb);
musb->xceiv->default_a = 1;
musb->xceiv->state = OTG_STATE_A_WAIT_VRISE;
portstate(musb->port1_status |= USB_PORT_STAT_POWER);
del_timer(&otg_workaround);
} else {
musb->is_active = 0;
MUSB_DEV_MODE(musb);
musb->xceiv->default_a = 0;
musb->xceiv->state = OTG_STATE_B_IDLE;
portstate(musb->port1_status &= ~USB_PORT_STAT_POWER);
}
DBG(2, "VBUS %s (%s)%s, devctl %02x\n",
drvvbus ? "on" : "off",
otg_state_string(musb),
err ? " ERROR" : "",
devctl);
ret = IRQ_HANDLED;
}
if (musb->int_tx || musb->int_rx || musb->int_usb)
ret |= musb_interrupt(musb);
eoi:
/* EOI needs to be written for the IRQ to be re-asserted. */
if (ret == IRQ_HANDLED || status)
musb_writel(reg_base, DA8XX_USB_END_OF_INTR_REG, 0);
/* Poll for ID change */
if (is_otg_enabled(musb) && musb->xceiv->state == OTG_STATE_B_IDLE)
mod_timer(&otg_workaround, jiffies + POLL_SECONDS * HZ);
spin_unlock_irqrestore(&musb->lock, flags);
return ret;
}
static int da8xx_musb_set_mode(struct musb *musb, u8 musb_mode)
{
u32 cfgchip2 = __raw_readl(CFGCHIP2);
cfgchip2 &= ~CFGCHIP2_OTGMODE;
switch (musb_mode) {
#ifdef CONFIG_USB_MUSB_HDRC_HCD
case MUSB_HOST: /* Force VBUS valid, ID = 0 */
cfgchip2 |= CFGCHIP2_FORCE_HOST;
break;
#endif
#ifdef CONFIG_USB_GADGET_MUSB_HDRC
case MUSB_PERIPHERAL: /* Force VBUS valid, ID = 1 */
cfgchip2 |= CFGCHIP2_FORCE_DEVICE;
break;
#endif
#ifdef CONFIG_USB_MUSB_OTG
case MUSB_OTG: /* Don't override the VBUS/ID comparators */
cfgchip2 |= CFGCHIP2_NO_OVERRIDE;
break;
#endif
default:
DBG(2, "Trying to set unsupported mode %u\n", musb_mode);
}
__raw_writel(cfgchip2, CFGCHIP2);
return 0;
}
static int da8xx_musb_init(struct musb *musb)
{
void __iomem *reg_base = musb->ctrl_base;
u32 rev;
musb->mregs += DA8XX_MENTOR_CORE_OFFSET;
/* Returns zero if e.g. not clocked */
rev = musb_readl(reg_base, DA8XX_USB_REVISION_REG);
if (!rev)
goto fail;
usb_nop_xceiv_register();
musb->xceiv = otg_get_transceiver();
if (!musb->xceiv)
goto fail;
if (is_host_enabled(musb))
setup_timer(&otg_workaround, otg_timer, (unsigned long)musb);
/* Reset the controller */
musb_writel(reg_base, DA8XX_USB_CTRL_REG, DA8XX_SOFT_RESET_MASK);
/* Start the on-chip PHY and its PLL. */
phy_on();
msleep(5);
/* NOTE: IRQs are in mixed mode, not bypass to pure MUSB */
pr_debug("DA8xx OTG revision %08x, PHY %03x, control %02x\n",
rev, __raw_readl(CFGCHIP2),
musb_readb(reg_base, DA8XX_USB_CTRL_REG));
musb->isr = da8xx_musb_interrupt;
return 0;
fail:
return -ENODEV;
}
static int da8xx_musb_exit(struct musb *musb)
{
if (is_host_enabled(musb))
del_timer_sync(&otg_workaround);
phy_off();
otg_put_transceiver(musb->xceiv);
usb_nop_xceiv_unregister();
return 0;
}
static const struct musb_platform_ops da8xx_ops = {
.init = da8xx_musb_init,
.exit = da8xx_musb_exit,
.enable = da8xx_musb_enable,
.disable = da8xx_musb_disable,
.set_mode = da8xx_musb_set_mode,
.try_idle = da8xx_musb_try_idle,
.set_vbus = da8xx_musb_set_vbus,
};
static u64 da8xx_dmamask = DMA_BIT_MASK(32);
static int __init da8xx_probe(struct platform_device *pdev)
{
struct musb_hdrc_platform_data *pdata = pdev->dev.platform_data;
struct platform_device *musb;
struct da8xx_glue *glue;
struct clk *clk;
int ret = -ENOMEM;
glue = kzalloc(sizeof(*glue), GFP_KERNEL);
if (!glue) {
dev_err(&pdev->dev, "failed to allocate glue context\n");
goto err0;
}
musb = platform_device_alloc("musb-hdrc", -1);
if (!musb) {
dev_err(&pdev->dev, "failed to allocate musb device\n");
goto err1;
}
clk = clk_get(&pdev->dev, "usb20");
if (IS_ERR(clk)) {
dev_err(&pdev->dev, "failed to get clock\n");
ret = PTR_ERR(clk);
goto err2;
}
ret = clk_enable(clk);
if (ret) {
dev_err(&pdev->dev, "failed to enable clock\n");
goto err3;
}
musb->dev.parent = &pdev->dev;
musb->dev.dma_mask = &da8xx_dmamask;
musb->dev.coherent_dma_mask = da8xx_dmamask;
glue->dev = &pdev->dev;
glue->musb = musb;
glue->clk = clk;
pdata->platform_ops = &da8xx_ops;
platform_set_drvdata(pdev, glue);
ret = platform_device_add_resources(musb, pdev->resource,
pdev->num_resources);
if (ret) {
dev_err(&pdev->dev, "failed to add resources\n");
goto err4;
}
ret = platform_device_add_data(musb, pdata, sizeof(*pdata));
if (ret) {
dev_err(&pdev->dev, "failed to add platform_data\n");
goto err4;
}
ret = platform_device_add(musb);
if (ret) {
dev_err(&pdev->dev, "failed to register musb device\n");
goto err4;
}
return 0;
err4:
clk_disable(clk);
err3:
clk_put(clk);
err2:
platform_device_put(musb);
err1:
kfree(glue);
err0:
return ret;
}
static int __exit da8xx_remove(struct platform_device *pdev)
{
struct da8xx_glue *glue = platform_get_drvdata(pdev);
platform_device_del(glue->musb);
platform_device_put(glue->musb);
clk_disable(glue->clk);
clk_put(glue->clk);
kfree(glue);
return 0;
}
static struct platform_driver da8xx_driver = {
.remove = __exit_p(da8xx_remove),
.driver = {
.name = "musb-da8xx",
},
};
MODULE_DESCRIPTION("DA8xx/OMAP-L1x MUSB Glue Layer");
MODULE_AUTHOR("Sergei Shtylyov <sshtylyov@ru.mvista.com>");
MODULE_LICENSE("GPL v2");
static int __init da8xx_init(void)
{
return platform_driver_probe(&da8xx_driver, da8xx_probe);
}
subsys_initcall(da8xx_init);
static void __exit da8xx_exit(void)
{
platform_driver_unregister(&da8xx_driver);
}
module_exit(da8xx_exit);
| chaoling/test123 | linux-2.6.39/drivers/usb/musb/da8xx.c | C | gpl-2.0 | 16,317 |
package org.ripple.bouncycastle.asn1;
/**
* @deprecated use ASN1Boolean
*/
public class DERBoolean
extends ASN1Boolean
{
/**
* @deprecated use getInstance(boolean) method.
* @param value
*/
public DERBoolean(boolean value)
{
super(value);
}
DERBoolean(byte[] value)
{
super(value);
}
}
| ripple/ripple-lib-java | ripple-bouncycastle/src/main/java/org/ripple/bouncycastle/asn1/DERBoolean.java | Java | isc | 353 |
package org.alljoyn.ioe.controlpaneladapter;
/******************************************************************************
* Copyright AllSeen Alliance. All rights reserved.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
******************************************************************************/
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.alljoyn.ioe.controlpanelservice.ControlPanelException;
import org.alljoyn.ioe.controlpanelservice.ControlPanelService;
import org.alljoyn.ioe.controlpanelservice.ui.ActionWidget;
import org.alljoyn.ioe.controlpanelservice.ui.ActionWidgetHintsType;
import org.alljoyn.ioe.controlpanelservice.ui.AlertDialogWidget;
import org.alljoyn.ioe.controlpanelservice.ui.AlertDialogWidget.DialogButton;
import org.alljoyn.ioe.controlpanelservice.ui.ContainerWidget;
import org.alljoyn.ioe.controlpanelservice.ui.ErrorWidget;
import org.alljoyn.ioe.controlpanelservice.ui.LabelWidget;
import org.alljoyn.ioe.controlpanelservice.ui.LayoutHintsType;
import org.alljoyn.ioe.controlpanelservice.ui.PropertyWidget;
import org.alljoyn.ioe.controlpanelservice.ui.PropertyWidget.ConstrainToValues;
import org.alljoyn.ioe.controlpanelservice.ui.PropertyWidget.RangeConstraint;
import org.alljoyn.ioe.controlpanelservice.ui.PropertyWidget.ValueType;
import org.alljoyn.ioe.controlpanelservice.ui.PropertyWidgetHintsType;
import org.alljoyn.ioe.controlpanelservice.ui.UIElement;
import org.alljoyn.ioe.controlpanelservice.ui.UIElementType;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.TypedArray;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Layout;
import android.text.Spanned;
import android.text.format.DateFormat;
import android.util.Log;
import android.util.SparseArray;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.TimePicker;
public class ControlPanelAdapter {
private final static String TAG = "cpapp" + ControlPanelAdapter.class.getSimpleName();
private static final Object PROPERTY_VALUE = "property_value";
private static final Object PROPERTY_EDITOR = "property_editor";
/* a context for creating Views */
private final Context uiContext;
/* mapping of UIElements to Views that were created by this adapter */
private final Map<String, View> uiElementToView = new WeakHashMap<String, View>(10);
/*
* mapping of AlertDialogWidgets to AlertDialogs that were created by this
* adapter
*/
private final Map<String, AlertDialog> alertWidgetToDialog = new WeakHashMap<String, AlertDialog>(3);
/* App handler for control panel exceptions */
private final ControlPanelExceptionHandler exceptionHandler;
/*Time out value to call the ControlPanelService to retrieve a value*/
private long timeoutValue = 4;
/*Time out measurement unit to call the ControlPanelService to retrieve a value*/
private TimeUnit timeoutUnit = TimeUnit.SECONDS;
// =====================================================================================================================
/**
* Constructor
* @param uiContext The context of the {@link Activity} hosting the {@link ControlPanelAdapter}
* @param exceptionHandler Exceptions listener
*/
public ControlPanelAdapter(Context uiContext, ControlPanelExceptionHandler exceptionHandler) {
if ( uiContext == null || exceptionHandler == null) {
throw new IllegalArgumentException("uiContext or exceptionHandler are undefined");
}
if ( !(uiContext instanceof Activity) ) {
throw new IllegalArgumentException("uiContext should be instance of Activity");
}
this.uiContext = uiContext;
this.exceptionHandler = exceptionHandler;
}
// =====================================================================================================================
/**
* The maximum time to wait before timing out retrieving the control panel element's current value.
* @param timeoutValue The value of the timeout
* @param timeoutUnit The {@link TimeUnit} of the timeout value
*/
public void setTimeout(long timeoutValue, TimeUnit timeoutUnit) {
this.timeoutValue = timeoutValue;
this.timeoutUnit = timeoutUnit;
}
// =====================================================================================================================
/**
* Creates a {@link Layout} that corresponds with the given ContainerWidget.
* Then for each contained widget the corresponded {@link View} is created.
* @param container input widget defining a container.
* @return a resulting Layout.
* @deprecated Use the {@link ControlPanelAdapter#createContainerViewAsync(ContainerWidget, ContainerCreatedListener)}
* instead
*/
@Deprecated
public View createContainerView(ContainerWidget container) {
if (container == null) {
Log.e(TAG, "createContainerView(container==null)");
return null;
}
Log.w(TAG, "The deprecated createContainerView() methdod has been called, handling");
return createContainerViewImpl(container, new HashMap<String, Object>());
}
// =====================================================================================================================
/**
* Creates a {@link Layout} that corresponds with the given ContainerWidget.
* Then for each contained widget the corresponded {@link View} is created.
* The thread that calls this method is released immediately. Once the container {@link Layout} is created
* the caller is notified via the {@link ContainerCreatedListener#onContainerViewCreated(View)} method.
* @param container input widget defining a container.
* @return a resulting Layout.
*/
public void createContainerViewAsync(final ContainerWidget container, final ContainerCreatedListener contCreateListener) {
if (container == null || contCreateListener == null) {
throw new IllegalArgumentException("Received an undefined argument");
}
Log.i(TAG, "createContainerViewAsync() method has been called, handling");
Runnable task = new Runnable() {
@Override
public void run() {
Map<String, Object> initialData = new HashMap<String, Object>();
ServiceTasksExecutor exec = ServiceTasksExecutor.createExecutor();
traverseContainerElements(container, exec, initialData);
retrieveElementsValues(initialData);
exec.shutdown();
submitCreateContainerViewTask(container, contCreateListener, initialData);
}
};
Thread t = new Thread(task);
t.start();
}
// =====================================================================================================================
/**
* Creates a Layout that corresponds with the given ContainerWidget by
* iterating the contained widgets and creating the corresponding inner {@link View}s.
* The container elements are initialized with the given {@link Map} of the initialData
* @param container input widget defining a container.
* @param initialData Key: element's object path; Value: element's initial value or NULL
* @return a resulting Layout.
*/
private View createContainerViewImpl(ContainerWidget container, Map<String, Object> initialData) {
if (container == null) {
Log.e(TAG, "createContainerView(container==null)");
return null;
}
Log.d(TAG, "Received main container, objPath: '" + container.getObjectPath() + "'");
// the returned Layout object
ViewGroup scrollView;
LinearLayout containerLayout;
ViewGroup.LayoutParams layoutParams;
// initialize the container by type
List<LayoutHintsType> layoutHints = container.getLayoutHints();
Log.d(TAG, "Container has LayoutHints: " + layoutHints);
LayoutHintsType layoutHintsType = (layoutHints.size() == 0) ? LayoutHintsType.VERTICAL_LINEAR : layoutHints.get(0);
// set the layout
switch (layoutHintsType) {
case HORIZONTAL_LINEAR:
scrollView = new HorizontalScrollView(uiContext);
LinearLayout linearLayout = new LinearLayout(uiContext);
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
linearLayout.setGravity(Gravity.CENTER_VERTICAL);
containerLayout = linearLayout;
LinearLayout.LayoutParams hLinearLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
hLinearLayoutParams.setMargins(10, 10, 10, 10);
layoutParams = hLinearLayoutParams;
break;
case VERTICAL_LINEAR:
default:
scrollView = new ScrollView(uiContext);
containerLayout = new LinearLayout(uiContext);
containerLayout.setOrientation(LinearLayout.VERTICAL);
containerLayout.setGravity(Gravity.LEFT);
LinearLayout.LayoutParams vLinearLayoutParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
vLinearLayoutParams.setMargins(10, 10, 10, 10);
layoutParams = vLinearLayoutParams;
// set the inner label
if (container.getLabel() != null && container.getLabel().trim().length() > 0) {
Log.d(TAG, "Setting container label to: " + container.getLabel());
TextView titleTextView = new TextView(uiContext);
titleTextView.setText(container.getLabel());
LinearLayout.LayoutParams textLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
textLayoutParams.setMargins(20, 0, 20, 0);
containerLayout.addView(titleTextView, textLayoutParams);
}
break;
}
Log.d(TAG, "Initialized Layout of class: " + containerLayout.getClass().getSimpleName());
Log.d(TAG, "Container bgColor: " + container.getBgColor());
// if (container.getBgColor() != null)
// containerLayout.setBackgroundColor(container.getBgColor());
// recursively layout the items
List<UIElement> elements = container.getElements();
Log.d(TAG, String.format("Laying out %d elements", elements.size()));
int i = 0;
for (UIElement element : elements) {
i++;
View childView = createInnerView(element, initialData);
containerLayout.addView(childView, layoutParams);
if (layoutHintsType == LayoutHintsType.VERTICAL_LINEAR && i < elements.size()) {
// add a divider
containerLayout.addView(createDividerView(), layoutParams);
}
}// for :: elements
LinearLayout.LayoutParams linearLayoutParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
scrollView.addView(containerLayout, linearLayoutParams);
boolean enabled = container.isEnabled();
Log.d(TAG, "Container is enabled: '" + enabled + "'");
if (!enabled) {
enableViewGroup(scrollView, false); // Only if container is created
// as disabled, its children
// should be disabled
}
uiElementToView.put(container.getObjectPath(), scrollView);
return scrollView;
}
// =====================================================================================================================
/**
* Traverse container elements and use {@link ControlPanelService} to retrieve data required
* for creating the element's {@link View}s.
* @param container {@link ContainerWidget} containing the elements
* @param exec {@link ServiceTasksExecutor} which is responsible to retrieve the element's data and populate the
* {@link Future} object
* @param initialData The map that is populated with the element's object path as a key and {@link Future} as a value
*/
private void traverseContainerElements(ContainerWidget container, ServiceTasksExecutor exec, Map<String, Object> initialData) {
List<UIElement> elements = container.getElements();
for (UIElement element : elements) {
UIElementType elType = element.getElementType();
//Currently only PropertyWidgets need initial data retrieved by the ControlPanelService via AllJoyn
if ( elType == UIElementType.PROPERTY_WIDGET ) {
Log.d(TAG, "Found a PropertyWidget objPath: '" + element.getObjectPath() + "', retrieving Future value");
initialData.put(element.getObjectPath(), submitGetPropertyCurrentValueTask(exec, (PropertyWidget)element));
}
else if ( elType == UIElementType.CONTAINER ) {
traverseContainerElements((ContainerWidget)element, exec, initialData);
}
}
}
// =====================================================================================================================
/**
* Retrieves initial values of the elements from the {@link Future} object stored in the given initialData {@link Map}.
* The values are retrieved by the call {@link Future#get(long, TimeUnit)}.
* If an {@link Exception} is thrown while retrieving the value, NULL is stored in the initialData instead of the
* real value.
*/
private void retrieveElementsValues(Map<String, Object> initialData) {
Log.d(TAG, "Retrieving initial values of the elements with timeout: '" + timeoutValue + " " + timeoutUnit + "'");
for ( String objPath : initialData.keySet() ) {
Object fo = initialData.get(objPath);
if ( !(fo instanceof Future<?>) ) {
Log.w(TAG, "The objPath: '" + objPath + "' doesn't have a Future object");
initialData.put(objPath, null);
continue;
}
@SuppressWarnings("unchecked")
Future<Object> futureVal = (Future<Object>) fo;
Object realValue = null;
try {
//Blocking call with the given timeout
realValue = futureVal.get(timeoutValue, timeoutUnit);
Log.d(TAG, "Found an initial value of the element: '" + objPath + "', value: '" + realValue + "'");
}
catch(Exception e) {
Log.e(TAG, "Failed to retrieve the element's initial value objPath: '" + objPath + "'. Exception: ", e);
futureVal.cancel(true);
}
initialData.put(objPath, realValue);
}
}
// =====================================================================================================================
/**
* Submits the {@link PropertyWidget#getCurrentValue()} task to the {@link ServiceTasksExecutor}.
* @param exec The executor that executes the task
* @param property {@link PropertyWidget} to retrieve the current value
* @return {@link Future} of the initial {@link PropertyWidget} value or NULL if failed to submit the retrieval task
*/
private Future<Object> submitGetPropertyCurrentValueTask(ServiceTasksExecutor exec, final PropertyWidget property) {
Log.d(TAG, "Prepare a task to call PropertyWidget.getCurrentValue(), property: '" + property.getObjectPath() + "'");
Callable<Object> task = new Callable<Object>() {
@Override
public Object call() throws Exception {
return property.getCurrentValue();
}
};
Future<Object> future = null;
try {
future = exec.submit(task);
}
catch (Exception e){
Log.d(TAG, "Failed to submit the task to call PropertyWidget.getCurrentValue(), property: '" +
property.getObjectPath() + "'", e);
}
return future;
}
// =====================================================================================================================
/**
* Submit the method {@link ControlPanelAdapter#createContainerViewImpl(ContainerWidget, Map)} to run on UI thread
* @param container
* @param contCreateListener
* @param initialData
*/
private void submitCreateContainerViewTask(final ContainerWidget container, final ContainerCreatedListener contCreateListener,
final Map<String, Object> initialData) {
((Activity)uiContext).runOnUiThread( new Runnable() {
@Override
public void run() {
View containerView = createContainerViewImpl(container, initialData);
contCreateListener.onContainerViewCreated(containerView);
}
});
}
// =====================================================================================================================
/**
* Creates a list divider for vertical layout
* @return A list divider
*/
private View createDividerView() {
View listDivider = new View(uiContext);
TypedArray listDividerAttrs = uiContext.getTheme().obtainStyledAttributes(new int[] { android.R.attr.listDivider });
if (listDividerAttrs.length() > 0) {
// don't change this to setBackground() it'll fly on run time
listDivider.setBackgroundDrawable(listDividerAttrs.getDrawable(0));
}
listDividerAttrs.recycle();
return listDivider;
}
// =====================================================================================================================
/**
* Creates an Android View that corresponds with the given UIElement using the given initialData
* @param element The {@link UIElement} to create the corresponding {@link View}I
* @param initialData
* @return an Android View that corresponds with the given abstract UIElement
*/
private View createInnerView(UIElement element, Map<String, Object> initialData) {
UIElementType elementType = element.getElementType();
Log.d(TAG, "Creating an Android View for element of type: '" + elementType + "'");
View returnView = new TextView(uiContext);
switch (elementType) {
case ACTION_WIDGET: {
returnView = createActionView((ActionWidget) element);
break;
}// ACTION_WIDGET
case CONTAINER: {
returnView = createContainerViewImpl((ContainerWidget) element, initialData);
break;
}// CONTAINER
// case LIST_PROPERTY_WIDGET: {
// break;
// }//LIST_PROPERTY_WIDGET
case PROPERTY_WIDGET: {
//Currently only Properties require initial data for the creation
returnView = createPropertyViewImpl((PropertyWidget) element, initialData);
break;
}// PROPERTY_WIDGET
case LABEL_WIDGET: {
returnView = createLabelView((LabelWidget) element);
break;
}// PROPERTY_WIDGET
case ERROR_WIDGET: {
returnView = createErrorView((ErrorWidget) element);
break;
}// ERROR_WIDGET
default:
break;
}// switch :: elementType
return returnView;
}
// =====================================================================================================================
/**
* Creates an AlertDialog that corresponds with the given AlertDialogWidget
* @param alertDialogWidget input abstract widget defining a dialog.
* @return an AlertDialog with up to 3 actions. Each action executes a different DialogButton UIElement.
*/
public AlertDialog createAlertDialog(final AlertDialogWidget alertDialogWidget) {
final SparseArray<DialogButton> buttonToAction = new SparseArray<AlertDialogWidget.DialogButton>(3);
List<DialogButton> execButtons = alertDialogWidget.getExecButtons();
int numOfButtons = alertDialogWidget.getNumActions();
if (numOfButtons > 0) {
buttonToAction.put(DialogInterface.BUTTON_POSITIVE, execButtons.get(0));
if (numOfButtons > 1) {
buttonToAction.put(DialogInterface.BUTTON_NEGATIVE, execButtons.get(1));
if (numOfButtons > 2) {
buttonToAction.put(DialogInterface.BUTTON_NEUTRAL, execButtons.get(2));
}
}
}
// create a confirmation dialog
DialogInterface.OnClickListener confirmationListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, final int which) {
// handle user choice
final DialogButton actionButton = buttonToAction.get(which);
Log.d(TAG, "User selected: " + actionButton.getLabel());
// execute the action in a background task
ExecuteActionAsyncTask asyncTask = new ExecuteActionAsyncTask() {
@Override
protected void onFailure(ControlPanelException e) {
if (exceptionHandler != null) {
exceptionHandler.handleControlPanelException(e);
}
}
@Override
protected void onSuccess() {
}
};
asyncTask.execute(actionButton);
}
};
// show the confirmation dialog
Builder builder = new AlertDialog.Builder(uiContext).setMessage(alertDialogWidget.getMessage()).setTitle(alertDialogWidget.getLabel());
if (numOfButtons > 0) {
builder.setPositiveButton(buttonToAction.get(DialogInterface.BUTTON_POSITIVE).getLabel(), confirmationListener);
if (numOfButtons > 1) {
builder.setNegativeButton(buttonToAction.get(DialogInterface.BUTTON_NEGATIVE).getLabel(), confirmationListener);
if (numOfButtons > 2) {
builder.setNeutralButton(buttonToAction.get(DialogInterface.BUTTON_NEUTRAL).getLabel(), confirmationListener);
}
}
}
AlertDialog alertDialog = builder.create();
alertWidgetToDialog.put(alertDialogWidget.getObjectPath(), alertDialog);
return alertDialog;
}
// =====================================================================================================================
/**
* Creates a Button for an ActionWidget
* @param action the UIElement to be represented by this button.
* @return a Button with 2 optional flows corresponding with the ActionWidget definition:
* A button that executes an action. Or a button that popsup an "Are You Sure?" dialog.
*/
public View createActionView(final ActionWidget action) {
List<ActionWidgetHintsType> hints = action.getHints();
String label = action.getLabel();
Integer bgColor = action.getBgColor();
boolean isEnabled = action.isEnabled();
Log.d(TAG, "Create Action: " + label + " BGColor: " + bgColor + " actionMeta: " + hints + " isEnable: '" + isEnabled + "'");
Button actionButton = new Button(uiContext);
actionButton.setText(label);
actionButton.setEnabled(isEnabled);
// if (bgColor != null) {
// Unfortunately button loses its pressed behavior when background is
// set.
// actionButton.setBackgroundColor(bgColor);
// }
// register a click listener
OnClickListener actionButtonListener = new OnClickListener() {
@Override
public void onClick(View v) {
if ( !action.isEnabled() ) {
Log.i(TAG, "ActionWidget is disabled, objPath: '" + action.getObjectPath() + "', not reacting onClick");
return;
}
// check if action requires an extra confirmation
AlertDialogWidget alertDialogWidget = action.getAlertDialog();
if (alertDialogWidget != null) {
Log.d(TAG, "Showing confirmation: " + alertDialogWidget.getMessage() + "?");
// create a confirmation dialog
AlertDialog confirmationDialog = createAlertDialog(alertDialogWidget);
confirmationDialog.show();
} // Confirmation needed
else { // No confirmation needed
// execute the action in a background task
ExecuteActionAsyncTask asyncTask = new ExecuteActionAsyncTask() {
@Override
protected void onFailure(ControlPanelException e) {
if (exceptionHandler != null) {
exceptionHandler.handleControlPanelException(e);
}
}
@Override
protected void onSuccess() {
}
};
asyncTask.execute(action);
} // No confirmation needed
}
};// new OnClickListener()
actionButton.setOnClickListener(actionButtonListener);
uiElementToView.put(action.getObjectPath(), actionButton);
return actionButton;
}// createActionView
// =====================================================================================================================
/**
* Creates a TextView for a LabelWidget
* @param labelWidget the UIElement to be represented by this View
* @return a TextView displaying the contents of the LabelWidget
*/
public View createLabelView(final LabelWidget labelWidget) {
String label = labelWidget.getLabel();
Integer bgColor = labelWidget.getBgColor();
Log.d(TAG, "Creating Label: \"" + label + "\" BGColor: " + bgColor);
TextView labelView = new TextView(uiContext);
labelView.setText(label);
// if (bgColor != null)
// labelView.setBackgroundColor(bgColor);
uiElementToView.put(labelWidget.getObjectPath(), labelView);
return labelView;
}// createLabelView
// =====================================================================================================================
/**
* Creates a TextView for a ErrorWidget
* @param errorWidget the UIElement to be represented by this View
* @return a TextView displaying the label of the ErrorWidget
*/
public View createErrorView(final ErrorWidget errorWidget) {
String label = errorWidget.getLabel();
String errorMessage = errorWidget.getError();
Log.w(TAG, "Creating Error Label: \"" + label + "\" Error: '" + errorMessage + "', Original Element Type: " + errorWidget.getOriginalUIElement());
TextView errorView = new TextView(uiContext);
errorView.setText(label);
uiElementToView.put(errorWidget.getObjectPath(), errorView);
return errorView;
}// createErrorView
// =====================================================================================================================
// ============================================= PropertyWidget
// ========================================================
// =====================================================================================================================
/**
* A factory method for creating a View for a given PropertyWidget.
* @param propertyWidget the UIElement to be represented by this View
* @return a View that represents the property. The type of View corresponds
* with the property's hint.
*/
public View createPropertyView(PropertyWidget propertyWidget) {
return createPropertyViewImpl(propertyWidget, new HashMap<String, Object>());
}
/**
* A factory method for creating a View for a given PropertyWidget.
* @param propertyWidget the UIElement to be represented by this View
* @param initialData The initialData to initialize the {@link PropertyWidget}
* @return a View that represents the property. The type of View corresponds
* with the property's hint.
*/
private View createPropertyViewImpl(PropertyWidget propertyWidget, Map<String, Object> initialData) {
ValueType valueType = propertyWidget.getValueType();
List<PropertyWidgetHintsType> hints = propertyWidget.getHints();
PropertyWidgetHintsType hint = (hints == null || hints.size() == 0) ? null : hints.get(0);
Object initialValue = getPropertyInitialValue(propertyWidget, initialData);
Log.d(TAG, "Creating a View for property '" + propertyWidget.getLabel() + "', using UI hint: ;" + hint +
"', value type: '" + valueType + "' initial value: '" + initialValue + "', objPath: '" +
propertyWidget.getObjectPath() + "'");
// default view. just in case...
View returnView = new TextView(uiContext);
switch (valueType) {
case BOOLEAN:
// Boolean Property
returnView = createCheckBoxView(propertyWidget, initialValue);
break;
case DATE:
// Date Property
returnView = createDatePickerView(propertyWidget, initialValue);
break;
case TIME:
// Time Property
returnView = createTimePickerView(propertyWidget, initialValue);
break;
case BYTE:
case INT:
case SHORT:
case LONG:
case DOUBLE:
// Scalar Property
if (hint == null) {
Log.d(TAG, "No hint provided for property '" + propertyWidget.getLabel() + "', creating default: NumericView");
returnView = createNumericView(propertyWidget, initialValue);
} else {
switch (hint) {
case SPINNER:
returnView = createSpinnerView(propertyWidget, initialValue);
break;
case RADIO_BUTTON:
returnView = createRadioButtonView(propertyWidget, initialValue);
break;
case NUMERIC_VIEW:
returnView = createNumericView(propertyWidget, initialValue);
break;
case SLIDER:
returnView = createSliderView(propertyWidget, initialValue);
break;
case NUMERIC_KEYPAD:
returnView = createNumericKeypadView(propertyWidget, initialValue);
break;
default:
Log.d(TAG, "Unsupported hint provided for property '" + propertyWidget.getLabel() + "', creating default: NumericView");
returnView = createNumericView(propertyWidget, initialValue);
break;
}
}
break;
case STRING:
// String Property
if (hint == null) {
Log.d(TAG, "No hint provided for property '" + propertyWidget.getLabel() + "', creating default: TextView");
returnView = createTextView(propertyWidget, initialValue);
} else {
switch (hint) {
case SPINNER:
returnView = createSpinnerView(propertyWidget, initialValue);
break;
case RADIO_BUTTON:
returnView = createRadioButtonView(propertyWidget, initialValue);
break;
case EDIT_TEXT:
returnView = createEditTextView(propertyWidget, initialValue);
break;
case TEXT_VIEW:
returnView = createTextView(propertyWidget, initialValue);
break;
default:
Log.d(TAG, "Unsupported hint provided for property '" + propertyWidget.getLabel() + "', creating default: TextView");
returnView = createTextView(propertyWidget, initialValue);
break;
}
}
break;
default:
Log.d(TAG, "Received an unsupported ValueType: '" + valueType + "' , returning an empty view");
return returnView;
}
uiElementToView.put(propertyWidget.getObjectPath(), returnView);
return returnView;
}
/**
* Retrieves the initial value from the initialData Map.
* If the objectPath isn't stored as the key in the initialData Map, the method
* {@link ControlPanelAdapter#submitGetPropertyCurrentValueTask(ServiceTasksExecutor, PropertyWidget)}
* is called. Otherwise the value retrieved from the Map is returned.
* @param propertyWidget The property to look for in the {@link Map}.
* @param initialData The {@link Map} with the initial values
* @return Object to initialize the Property Widget {@link View} or NULL.
*/
private Object getPropertyInitialValue(PropertyWidget propertyWidget, Map<String, Object> initialData) {
String objPath = propertyWidget.getObjectPath();
Log.d(TAG, "Searching for the initial value of the property: '" + objPath + "'");
if ( !initialData.containsKey(objPath) ) {
//This code may be called when there is a use of the deprecated createContainerView method
Log.w(TAG, "The object path: '" + objPath + "' is unknown, submitting PropertyWidget.getCurrentValue()");
ServiceTasksExecutor exec = ServiceTasksExecutor.createExecutor(1);
Future<Object> fo = submitGetPropertyCurrentValueTask(exec, propertyWidget);
try {
if ( fo == null ) {
return null;
}
return fo.get(timeoutValue, timeoutUnit);
} catch (Exception e) {
Log.e(TAG, "Failed to retrieve property's initial value objPath: '" + objPath + "'. Exception: ", e);
fo.cancel(true);
return null;
}
finally {
exec.shutdown();
}
}
return initialData.get(objPath);
}
// =====================================================================================================================
private View createSpinnerView(final PropertyWidget propertyWidget, Object initialValue) {
Log.d(TAG, "Creating a spinner for propertyWidget " + propertyWidget.getLabel());
final LinearLayout layout = new LinearLayout(uiContext);
layout.setOrientation(LinearLayout.VERTICAL);
final TextView nameTextView = new TextView(uiContext);
nameTextView.setPadding(10, 0, 0, 0);
nameTextView.setText(propertyWidget.getLabel());
final Spinner spinner = new Spinner(uiContext);
LinearLayout.LayoutParams vLinearLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
layout.addView(nameTextView, vLinearLayoutParams);
layout.addView(spinner, vLinearLayoutParams);
spinner.setTag(PROPERTY_VALUE);
Log.d(TAG, "Property isWritable? " + propertyWidget.isWritable() + ", isEnabled? " + propertyWidget.isEnabled());
// spinner.setEnabled(propertyWidget.isEnabled() &&
// propertyWidget.isWritable());
enableViewGroup(layout, propertyWidget.isEnabled() && propertyWidget.isWritable());
// set the data model
final ArrayAdapter<LabelValuePair> adapter = new ArrayAdapter<LabelValuePair>(uiContext, android.R.layout.simple_spinner_item);
int selection = 0;
if (propertyWidget.getListOfConstraint() != null) {
// create a spinner model made of the given ConstrainToValues
// entries
int position = 0;
for (ConstrainToValues<?> valueCons : propertyWidget.getListOfConstraint()) {
boolean isDefault = valueCons.getValue().equals(initialValue);
Log.d(TAG, "Adding spinner item, Label: " + valueCons.getLabel() + " Value: " + valueCons.getValue() + (isDefault ? " (default)" : ""));
adapter.add(new LabelValuePair(valueCons.getLabel(), valueCons.getValue()));
if (isDefault) {
selection = position;
}
position++;
}
} else if (propertyWidget.getPropertyRangeConstraint() != null) {
// dynamically create a spinner model made of integers from min to
// max
RangeConstraint<?> propertyRangeConstraint = propertyWidget.getPropertyRangeConstraint();
ValueType valueType = propertyWidget.getValueType();
Object minT = propertyRangeConstraint.getMin();
int min = ValueType.SHORT.equals(valueType) ? ((Short) minT) : ValueType.INT.equals(valueType) ? ((Integer) minT) : 0;
Object maxT = propertyRangeConstraint.getMax();
int max = ValueType.SHORT.equals(valueType) ? ((Short) maxT) : ValueType.INT.equals(valueType) ? ((Integer) maxT) : 0;
Object incrementT = propertyRangeConstraint.getIncrement();
int increment = ValueType.SHORT.equals(valueType) ? ((Short) incrementT) : ValueType.INT.equals(valueType) ? ((Integer) incrementT) : 0;
int position = 0;
for (int i = min; i <= max; i += increment) {
boolean isDefault = false;
switch (valueType) {
case SHORT:
short shortI = (short) i;
adapter.add(new LabelValuePair(String.valueOf(i), shortI));
isDefault = Short.valueOf(shortI).equals(initialValue);
break;
case INT:
default: {
adapter.add(new LabelValuePair(String.valueOf(i), i));
isDefault = Integer.valueOf(i).equals(initialValue);
}
}
Log.d(TAG, "Added spinner item, Value: " + i + (isDefault ? " (default)" : ""));
if (isDefault) {
selection = position;
}
position++;
}
}
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setSelection(selection);
final int initialSelection = selection;
// Unfortunately spinner loses some of its UI components when background
// is set.
// spinner.setBackgroundColor(property.getBgColor());
// register a selection listener
OnItemSelectedListener listener = new OnItemSelectedListener() {
int currentSelection = initialSelection;
@Override
public void onItemSelected(AdapterView<?> parent, View view, final int pos, long id) {
if (pos == currentSelection) {
Log.d(TAG, String.format("Selected position %d already selected. No action required", pos));
} else {
LabelValuePair item = adapter.getItem(pos);
// set the property in a background task
SetPropertyAsyncTask asyncTask = new SetPropertyAsyncTask() {
@Override
protected void onFailure(ControlPanelException e) {
spinner.setSelection(currentSelection);
if (exceptionHandler != null) {
// An exception was thrown. Restore old value.
exceptionHandler.handleControlPanelException(e);
}
}
@Override
protected void onSuccess() {
// All went well. Store the new value.
currentSelection = pos;
}
};
asyncTask.execute(propertyWidget, item.value);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
};
spinner.setOnItemSelectedListener(listener);
return layout;
}
// =====================================================================================================================
private View createRadioButtonView(final PropertyWidget propertyWidget, Object initialValue) {
Log.d(TAG, "Creating a radio button group for property '" + propertyWidget.getLabel() + "'");
// Create external widget layout
final LinearLayout layout = new LinearLayout(uiContext);
layout.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams vLinearLayoutParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
// Create internal label/unit of measure layout
final LinearLayout innerLayout = new LinearLayout(uiContext);
innerLayout.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout.LayoutParams hLinearLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
hLinearLayoutParams.setMargins(10, 0, 0, 0);
layout.addView(innerLayout, vLinearLayoutParams);
final TextView nameTextView = new TextView(uiContext);
nameTextView.setPadding(10, 0, 0, 0);
nameTextView.setText(propertyWidget.getLabel());
innerLayout.addView(nameTextView, hLinearLayoutParams);
// Add unit of measure
String unitOfMeasure = propertyWidget.getUnitOfMeasure();
if (unitOfMeasure != null && unitOfMeasure.length() > 0) {
final TextView unitsOfMeasureTextView = new TextView(uiContext);
unitsOfMeasureTextView.setText(unitOfMeasure);
innerLayout.addView(unitsOfMeasureTextView, hLinearLayoutParams);
}
RadioGroup radioGroup = new RadioGroup(uiContext);
layout.addView(radioGroup, vLinearLayoutParams);
radioGroup.setTag(PROPERTY_VALUE);
final List<ConstrainToValues<?>> listOfConstraint = propertyWidget.getListOfConstraint();
if (listOfConstraint != null) {
for (ConstrainToValues<?> valueCons : listOfConstraint) {
boolean isDefault = valueCons.getValue().equals(initialValue);
Log.d(TAG, "Adding radio button, Label: " + valueCons.getLabel() + " Value: " + valueCons.getValue() + (isDefault ? " (default)" : ""));
RadioButton radioButton = new RadioButton(uiContext);
radioButton.setText(valueCons.getLabel());
LinearLayout.LayoutParams layoutParams = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT);
radioGroup.addView(radioButton, layoutParams);
// check the default value
if (isDefault && !radioButton.isChecked()) {
radioButton.toggle();
}
}
}// LOV constraints
Log.d(TAG, "Property isWritable? " + propertyWidget.isWritable() + ", isEnabled? " + propertyWidget.isEnabled());
enableViewGroup(layout, propertyWidget.isEnabled() && propertyWidget.isWritable());
// radioGroup.setBackgroundColor(propertyWidget.getBgColor());
final int initialCheckedId = radioGroup.getCheckedRadioButtonId();
// register selection listener
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
int currentCheckedId = initialCheckedId;
@Override
public void onCheckedChanged(final RadioGroup group, final int checkedId) {
int index = group.indexOfChild(group.findViewById(checkedId));
if (index > -1) {
// Avoid fast consecutive selections. The problem is with
// the valueChange events that a controllable device sends
// following each selection of the RadioButton.
// If a user selects different RadioButton(s) from the group
// very fast, the valueChange events start toggling the
// RadioGroup automatically
for (int i = 0; i < group.getChildCount(); i++) {
group.getChildAt(i).setEnabled(false);
}
group.postDelayed(new Runnable() {
@Override
public void run() {
for (int i = 0; i < group.getChildCount(); i++) {
group.getChildAt(i).setEnabled(true);
}
}
}, 1000);
ConstrainToValues<?> item = listOfConstraint.get(index);
Log.d(TAG, "Selected radio button, Label: '" + item.getLabel() + "' Value: " + item.getValue());
// set the property in a background task
SetPropertyAsyncTask asyncTask = new SetPropertyAsyncTask() {
@Override
protected void onFailure(ControlPanelException e) {
group.check(currentCheckedId);
if (exceptionHandler != null) {
// An exception was thrown. Restore old value.
exceptionHandler.handleControlPanelException(e);
}
}
@Override
protected void onSuccess() {
// All went well. Store the new value.
currentCheckedId = checkedId;
}
};
asyncTask.execute(propertyWidget, item.getValue());
}
}
});
return layout;
}
// =====================================================================================================================
private CheckBox createCheckBoxView(final PropertyWidget propertyWidget, Object initialValue) {
Log.d(TAG, "Creating a checkbox for property " + propertyWidget.getLabel());
CheckBox checkbox = new CheckBox(uiContext);
Log.d(TAG, "Property isWritable? " + propertyWidget.isWritable() + ", isEnabled? " + propertyWidget.isEnabled() + " InitialValue: '" + initialValue + "'");
// initialize meta data
checkbox.setEnabled(propertyWidget.isEnabled() && propertyWidget.isWritable());
// if (propertyWidget.getBgColor() != null)
// checkbox.setBackgroundColor(propertyWidget.getBgColor());
// initialize data
if (initialValue instanceof Boolean) {
checkbox.setChecked((Boolean) initialValue);
}
checkbox.setText(propertyWidget.getLabel());
// register selection listener
OnCheckedChangeListener listener = new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) {
// Avoid fast consecutive selections. The problem is with the
// valueChange events that a controllable device sends
// following each change of the Checkbox state.
// If a user selects/unselects checkbox fast, these valueChange
// events start toggle the Checkbox state automatically
buttonView.setEnabled(false);
buttonView.postDelayed(new Runnable() {
@Override
public void run() {
buttonView.setEnabled(true);
}
}, 1000);
// set the property in a background task
SetPropertyAsyncTask asyncTask = new SetPropertyAsyncTask() {
@Override
protected void onFailure(ControlPanelException e) {
buttonView.setChecked(!isChecked);
if (exceptionHandler != null) {
// An exception was thrown. Restore old value.
exceptionHandler.handleControlPanelException(e);
}
}
@Override
protected void onSuccess() {
// All went well.
}
};
asyncTask.execute(propertyWidget, isChecked);
}
};
checkbox.setOnCheckedChangeListener(listener);
return checkbox;
}
// =====================================================================================================================
private View createTextView(final PropertyWidget propertyWidget, Object initialValue) {
String label = propertyWidget.getLabel();
Integer bgColor = propertyWidget.getBgColor();
Log.d(TAG, "Creating TextView: \"" + label + "\" BGColor: " + bgColor);
final LinearLayout layout = new LinearLayout(uiContext);
layout.setOrientation(LinearLayout.HORIZONTAL);
final TextView nameTextView = new TextView(uiContext);
nameTextView.setText(label);
layout.addView(nameTextView);
final TextView valueTextView = new TextView(uiContext);
valueTextView.setTag(PROPERTY_VALUE);
LinearLayout.LayoutParams hLinearLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
hLinearLayoutParams.setMargins(10, 0, 0, 0);
layout.addView(valueTextView, hLinearLayoutParams);
// if (bgColor != null)
// labelView.setBackgroundColor(bgColor);
if (initialValue != null) {
Log.d(TAG, "Setting property value to: " + initialValue.toString());
valueTextView.setText(initialValue.toString());
}
return layout;
}// createTextView
// =====================================================================================================================
private View createEditTextView(final PropertyWidget propertyWidget, Object initialValue) {
Log.d(TAG, "Creating a text editor for property " + propertyWidget.getLabel());
// create the label
final LinearLayout layout = new LinearLayout(uiContext);
layout.setOrientation(LinearLayout.HORIZONTAL);
final TextView nameTextView = new TextView(uiContext);
nameTextView.setText(propertyWidget.getLabel());
final EditText valueEditText = new EditText(uiContext);
valueEditText.setImeOptions(EditorInfo.IME_ACTION_DONE);
valueEditText.setTag(PROPERTY_EDITOR);
layout.addView(nameTextView);
LinearLayout.LayoutParams hLinearLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
hLinearLayoutParams.setMargins(10, 0, 0, 0);
layout.addView(valueEditText, hLinearLayoutParams);
// initialize meta data
// if (propertyWidget.getBgColor() != null)
// valueEditText.setBackgroundColor(propertyWidget.getBgColor());
Log.d(TAG, "Property isWritable? " + propertyWidget.isWritable() + ", isEnabled? " + propertyWidget.isEnabled());
enableViewGroup(layout, propertyWidget.isEnabled() && propertyWidget.isWritable());
// valueEditText.setEnabled(propertyWidget.isEnabled() &&
// propertyWidget.isWritable());
// nameTextView.setEnabled(true);
final String initialValueStr = initialValue == null ? "" : initialValue.toString();
valueEditText.setText(initialValueStr);
// register edit listener
valueEditText.setInputType(InputType.TYPE_CLASS_TEXT);
// limit the number of characters
// editText.setFilters( new InputFilter[] {new
// InputFilter.LengthFilter(10)});
valueEditText.setOnEditorActionListener(new OnEditorActionListener() {
String currentText = initialValueStr;
@Override
public boolean onEditorAction(final TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
// set the property in a background task
SetPropertyAsyncTask asyncTask = new SetPropertyAsyncTask() {
@Override
protected void onFailure(ControlPanelException e) {
v.setText(currentText);
if (exceptionHandler != null) {
// An exception was thrown. Restore old value.
exceptionHandler.handleControlPanelException(e);
}
}
@Override
protected void onSuccess() {
// All went well. Store the new value.
currentText = v.getText().toString();
}
};
asyncTask.execute(propertyWidget, v.getText().toString());
}
// otherwise keyboard remains up
return false;
}
});
return layout;
}// createEditTextView
// =====================================================================================================================
private View createNumericKeypadView(final PropertyWidget propertyWidget, Object initialValue) {
Log.d(TAG, "Creating a number text editor for property " + propertyWidget.getLabel());
// create the label
final LinearLayout layout = new LinearLayout(uiContext);
layout.setOrientation(LinearLayout.HORIZONTAL);
final TextView nameTextView = new TextView(uiContext);
nameTextView.setText(propertyWidget.getLabel());
final EditText valueEditText = new EditText(uiContext);
valueEditText.setImeOptions(EditorInfo.IME_ACTION_DONE);
valueEditText.setTag(PROPERTY_EDITOR);
layout.addView(nameTextView);
LinearLayout.LayoutParams hLinearLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
hLinearLayoutParams.setMargins(10, 0, 0, 0);
layout.addView(valueEditText, hLinearLayoutParams);
// initialize meta data
// if (propertyWidget.getBgColor() != null)
// valueEditText.setBackgroundColor(propertyWidget.getBgColor());
Log.d(TAG, "Property isWritable? " + propertyWidget.isWritable() + ", isEnabled? " + propertyWidget.isEnabled());
enableViewGroup(layout, propertyWidget.isEnabled() && propertyWidget.isWritable());
final ValueType valueType = propertyWidget.getValueType();
final Number initialValueNum = (initialValue == null ? 0 : ValueType.SHORT.equals(valueType) ?
((Short) initialValue) : ValueType.INT.equals(valueType) ? ((Integer) initialValue) : 0);
valueEditText.setText(String.valueOf(initialValue));
// register edit listener
valueEditText.setInputType(InputType.TYPE_CLASS_NUMBER);
// limit to Short/Integer MAX_VALUE
InputFilter filter = new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
String insert = source.toString();
String insertInto = dest.toString();
Log.d(TAG, "Trying to insert ' " + insert + "' into '" + insertInto + "' between characters " + dstart + " and " + dend);
try {
String prefix = insertInto.substring(0, dstart);
String suffix = insertInto.substring(dend);
String result = prefix + insert + suffix;
if (ValueType.SHORT.equals(valueType)) {
short input = Short.parseShort(result);
Log.d(TAG, "Valid short entered: " + input);
// if we got here we're fine. Accept the editing by
// returning null
return null;
}
if (ValueType.INT.equals(valueType)) {
int input = Integer.parseInt(result);
Log.d(TAG, "Valid int entered: " + input);
// if we got here we're fine. Accept the editing by
// returning null
return null;
}
} catch (NumberFormatException nfe) {
Log.e(TAG, "Rejecting insert because'" + nfe.getMessage() + "'");
}
// returning "" will reject the editing action
return "";
}
};
valueEditText.setFilters(new InputFilter[] { filter });
valueEditText.setOnEditorActionListener(new OnEditorActionListener() {
Number currentValue = initialValueNum;
@Override
public boolean onEditorAction(final TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
Number readEnteredValue = null;
try {
if (ValueType.SHORT == valueType) {
readEnteredValue = Short.valueOf(v.getText().toString());
} else if (ValueType.INT == valueType) {
readEnteredValue = Integer.valueOf(v.getText().toString());
}
} catch (NumberFormatException nfe) {
if (ValueType.SHORT == valueType) {
Log.e(TAG, "Failed parsing Short: '" + nfe.getMessage() + "' returing to previous value");
} else if (ValueType.INT == valueType) {
Log.e(TAG, "Failed parsing Integer: '" + nfe.getMessage() + "' returing to previous value");
}
v.setText(String.valueOf(currentValue));
return true;
}
final Number enteredValue = readEnteredValue;
// set the property in a background task
SetPropertyAsyncTask asyncTask = new SetPropertyAsyncTask() {
@Override
protected void onFailure(ControlPanelException e) {
v.setText(String.valueOf(currentValue));
if (exceptionHandler != null) {
// An exception was thrown. Restore old value.
exceptionHandler.handleControlPanelException(e);
}
}
@Override
protected void onSuccess() {
// All went well. Store the new value.
currentValue = enteredValue;
}
};
asyncTask.execute(propertyWidget, enteredValue);
}
// otherwise keyboard remains up
return false;
}
});
return layout;
}// createEditTextView
// =====================================================================================================================
private View createTimePickerView(final PropertyWidget propertyWidget, Object initialValue) {
Log.d(TAG, "Creating a time picker for property " + propertyWidget.getLabel());
final LinearLayout layout = new LinearLayout(uiContext);
layout.setOrientation(LinearLayout.HORIZONTAL);
final TextView nameTextView = new TextView(uiContext);
nameTextView.setText(propertyWidget.getLabel());
final Button valueButton = new Button(uiContext);
valueButton.setTag(PROPERTY_VALUE);
layout.addView(nameTextView);
LinearLayout.LayoutParams hLinearLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
hLinearLayoutParams.setMargins(10, 0, 0, 0);
layout.addView(valueButton, hLinearLayoutParams);
// initialize meta data
// if (propertyWidget.getBgColor() != null)
// valueButton.setBackgroundColor(propertyWidget.getBgColor());
Log.d(TAG, "Property isWritable? " + propertyWidget.isWritable() + ", isEnabled? " + propertyWidget.isEnabled());
enableViewGroup(layout, propertyWidget.isEnabled() && propertyWidget.isWritable());
// set the current value
if (initialValue != null && (ValueType.TIME.equals(propertyWidget.getValueType()))) {
PropertyWidget.Time time = (PropertyWidget.Time) initialValue;
valueButton.setText(formatTime(time.getHour(), time.getMinute()));
} else {
Log.e(TAG, "TimePicker property.getValueType() is not TIME, initializing property without current value");
}
// register time picker dialog listener
final TimePickerDialog.OnTimeSetListener onTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
PropertyWidget.Time time = new PropertyWidget.Time();
time.setHour((short) hourOfDay);
time.setMinute((short) minute);
time.setSecond((short) 0);
// set the property in a background task
SetPropertyAsyncTask asyncTask = new SetPropertyAsyncTask() {
@Override
protected void onFailure(ControlPanelException e) {
if (exceptionHandler != null) {
// no need to restore value, it hasn't changed.
exceptionHandler.handleControlPanelException(e);
}
}
@Override
protected void onSuccess() {
// don't worry about the result, it will be broadcasted
// with ValueChanged
// All went well.
}
};
asyncTask.execute(propertyWidget, time);
}
};
// register click listener
OnClickListener onClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
// set the current value
ServiceTasksExecutor exec = ServiceTasksExecutor.createExecutor(1);
Future<Object> futCurrValue = submitGetPropertyCurrentValueTask(exec, propertyWidget);
Object currentValue = null;
PropertyWidget.Time time;
try {
if ( futCurrValue != null ) {
currentValue = futCurrValue.get(timeoutValue, timeoutUnit);
}
} catch (Exception e) {
Log.e(TAG, "TimePickerView property.getCurrentValue() failed, initializing picker without current value", e);
futCurrValue.cancel(true);
time = new PropertyWidget.Time();
}
if (currentValue != null && (ValueType.TIME.equals(propertyWidget.getValueType()))) {
time = (PropertyWidget.Time) currentValue;
} else {
Log.e(TAG, "TimePickerView property.getValueType() is not TIME, initializing picker without current value");
time = new PropertyWidget.Time();
}
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = currentValue == null ? c.get(Calendar.HOUR_OF_DAY) : time.getHour();
int minute = currentValue == null ? c.get(Calendar.MINUTE) : time.getMinute();
// Pop a TimePickerDialog
new TimePickerDialog(uiContext, onTimeSetListener, hour, minute, DateFormat.is24HourFormat(uiContext)).show();
}
};
valueButton.setOnClickListener(onClickListener);
return layout;
}// createTimePickerView
// =====================================================================================================================
private View createDatePickerView(final PropertyWidget propertyWidget, Object initialValue) {
Log.d(TAG, "Creating a date picker for property " + propertyWidget.getLabel());
// create the label
final LinearLayout layout = new LinearLayout(uiContext);
layout.setOrientation(LinearLayout.HORIZONTAL);
final TextView nameTextView = new TextView(uiContext);
nameTextView.setText(propertyWidget.getLabel());
final Button valueButton = new Button(uiContext);
valueButton.setTag(PROPERTY_VALUE);
layout.addView(nameTextView);
LinearLayout.LayoutParams hLinearLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
hLinearLayoutParams.setMargins(10, 0, 0, 0);
layout.addView(valueButton, hLinearLayoutParams);
// initialize meta data
// if (propertyWidget.getBgColor() != null)
// valueButton.setBackgroundColor(propertyWidget.getBgColor());
Log.d(TAG, "Property isWritable? " + propertyWidget.isWritable() + ", isEnabled? " + propertyWidget.isEnabled());
enableViewGroup(layout, propertyWidget.isEnabled() && propertyWidget.isWritable());
if (initialValue != null && (ValueType.DATE.equals(propertyWidget.getValueType()))) {
PropertyWidget.Date date = (PropertyWidget.Date) initialValue;
valueButton.setText(formatDate(date.getDay(), date.getMonth(), date.getYear()));
} else {
Log.e(TAG, "DatePicker property.getValueType() is not DATE, initializing property without current value");
}
// register time picker dialog listener
final DatePickerDialog.OnDateSetListener onDateSetListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int day) {
PropertyWidget.Date date = new PropertyWidget.Date();
// DatePicker enums months from 0..11 :(
month++;
date.setDay((short) day);
date.setMonth((short) month);
date.setYear((short) year);
// set the property in a background task
SetPropertyAsyncTask asyncTask = new SetPropertyAsyncTask() {
@Override
protected void onFailure(ControlPanelException e) {
if (exceptionHandler != null) {
// no need to restore value, it hasn't changed.
exceptionHandler.handleControlPanelException(e);
}
}
@Override
protected void onSuccess() {
// don't worry about the result, it will be broadcasted
// with ValueChanged
// All went well.
}
};
asyncTask.execute(propertyWidget, date);
}
};
// register click listener
OnClickListener onClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
// set the current value
ServiceTasksExecutor exec = ServiceTasksExecutor.createExecutor(1);
Future<Object> futCurrValue = submitGetPropertyCurrentValueTask(exec, propertyWidget);
Object currentValue = null;
PropertyWidget.Date date;
try {
if ( futCurrValue != null) {
currentValue = futCurrValue.get(timeoutValue, timeoutUnit);
}
} catch (Exception e) {
Log.e(TAG, "DatePickerView property.getCurrentValue() failed, initializing picker without current value", e);
futCurrValue.cancel(true);
date = new PropertyWidget.Date();
}
finally {
exec.shutdown();
}
if (currentValue != null && (ValueType.DATE.equals(propertyWidget.getValueType()))) {
date = (PropertyWidget.Date) currentValue;
} else {
Log.e(TAG, "property.getValueType() is not DATE, initializing picker without current value");
date = new PropertyWidget.Date();
}
// Use the current date as the default values for the picker
final Calendar c = Calendar.getInstance();
int day = currentValue == null ? c.get(Calendar.DAY_OF_MONTH) : date.getDay();
int month = currentValue == null ? c.get(Calendar.MONTH) : date.getMonth();
int year = currentValue == null ? c.get(Calendar.YEAR) : date.getYear();
// DatePicker enums months from 0..11 :(
month--;
// Pop a DatePickerDialog
new DatePickerDialog(uiContext, onDateSetListener, year, month, day).show();
}
};
valueButton.setOnClickListener(onClickListener);
return layout;
}// createTimePickerView
// =====================================================================================================================
private View createNumberPickerView(final PropertyWidget propertyWidget, Object initialValue) {
Log.d(TAG, "Creating a number picker for property " + propertyWidget.getLabel());
// create the label
final LinearLayout layout = new LinearLayout(uiContext);
layout.setOrientation(LinearLayout.HORIZONTAL);
final TextView nameTextView = new TextView(uiContext);
nameTextView.setText(propertyWidget.getLabel());
final TextView valueTextView = new TextView(uiContext);
layout.addView(nameTextView);
LinearLayout.LayoutParams hLinearLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
hLinearLayoutParams.setMargins(10, 0, 0, 0);
layout.addView(valueTextView, hLinearLayoutParams);
// initialize meta data
// if (propertyWidget.getBgColor() != null)
// valueTextView.setBackgroundColor(propertyWidget.getBgColor());
Log.d(TAG, "Property isWritable? " + propertyWidget.isWritable() + ", isEnabled? " + propertyWidget.isEnabled());
enableViewGroup(layout, propertyWidget.isEnabled() && propertyWidget.isWritable());
RangeConstraint<?> propertyRangeConstraint = propertyWidget.getPropertyRangeConstraint();
if (propertyRangeConstraint == null) {
Log.e(TAG, "Found null property-range. Disabling Number Picker. Returning a plain label.");
valueTextView.setEnabled(false);
return layout;
}
if (initialValue != null) {
valueTextView.setText(initialValue.toString());
}
// register touch listener
/*
* Only in honeycomb 3.0 final int min = (Integer)
* propertyRangeConstraint.getMin(); final int max = (Integer)
* propertyRangeConstraint.getMax(); //final int increment = (Integer)
* propertyRangeConstraint.getIncrement();
* numericTextView.setOnTouchListener(new OnTouchListener() {
*
* @Override public boolean onTouch (View v, MotionEvent event) { if
* (event.getAction() == MotionEvent.ACTION_DOWN) {
*
* final NumberPicker picker = new NumberPicker(uiContext);
* picker.setMaxValue(max); picker.setMinValue(min);
* picker.setValue(Integer
* .valueOf(numericTextView.getText().toString())); AlertDialog
* alertDialog = new AlertDialog.Builder(uiContext) .setView(picker)
* .setTitle(propertyWidget.getLabel())
* .setPositiveButton(R.string.dialog_set, new
* DialogInterface.OnClickListener() { public void
* onClick(DialogInterface dialog, int whichButton) {
* setPropertyValue(propertyWidget, picker.getValue());
* numericTextView.setText(String.valueOf(picker.getValue())); }})
* .setNegativeButton(R.string.dialog_cancel, null).create();
* alertDialog.show(); return true; } return false; } });
*/
return layout;
}
// =====================================================================================================================
private View createNumericView(final PropertyWidget propertyWidget, Object initialValue) {
Log.d(TAG, "Creating a numberic view for property " + propertyWidget.getLabel());
// create the label
final LinearLayout layout = new LinearLayout(uiContext);
layout.setOrientation(LinearLayout.HORIZONTAL);
final TextView nameTextView = new TextView(uiContext);
nameTextView.setText(propertyWidget.getLabel());
final TextView valueTextView = new TextView(uiContext);
valueTextView.setTag(PROPERTY_VALUE);
layout.addView(nameTextView);
LinearLayout.LayoutParams hLinearLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
hLinearLayoutParams.setMargins(10, 0, 0, 0);
layout.addView(valueTextView, hLinearLayoutParams);
// initialize meta data
// if (propertyWidget.getBgColor() != null)
// valueTextView.setBackgroundColor(propertyWidget.getBgColor());
Log.d(TAG, "Property isWritable? " + propertyWidget.isWritable() + ", isEnabled? " + propertyWidget.isEnabled());
enableViewGroup(layout, propertyWidget.isEnabled() && propertyWidget.isWritable());
if (initialValue != null) {
Log.d(TAG, "Setting property value to: " + initialValue.toString());
valueTextView.setText(initialValue.toString());
}
return layout;
}
// =====================================================================================================================
private View createSliderView(final PropertyWidget propertyWidget, Object initialValue) {
Log.d(TAG, "Creating a slider for property " + propertyWidget.getLabel());
// create the label
final LinearLayout layout = new LinearLayout(uiContext);
layout.setOrientation(LinearLayout.VERTICAL);
final LinearLayout innerLayout = new LinearLayout(uiContext);
innerLayout.setOrientation(LinearLayout.HORIZONTAL);
final TextView nameTextView = new TextView(uiContext);
nameTextView.setText(propertyWidget.getLabel());
final TextView valueTextView = new TextView(uiContext);
valueTextView.setTag(PROPERTY_VALUE);
final TextView unitsOfMeasureTextView = new TextView(uiContext);
final SeekBar slider = new SeekBar(uiContext);
slider.setTag(PROPERTY_EDITOR);
innerLayout.addView(nameTextView);
LinearLayout.LayoutParams hLinearLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
hLinearLayoutParams.setMargins(10, 0, 0, 0);
innerLayout.addView(valueTextView, hLinearLayoutParams);
innerLayout.addView(unitsOfMeasureTextView, hLinearLayoutParams);
LinearLayout.LayoutParams vLinearLayoutParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
layout.addView(innerLayout, vLinearLayoutParams);
layout.addView(slider, vLinearLayoutParams);
// initialize meta data
// valueTextView.setBackgroundColor(propertyWidget.getBgColor());
Log.d(TAG, "Property isWritable? " + propertyWidget.isWritable() + ", isEnabled? " + propertyWidget.isEnabled());
enableViewGroup(layout, propertyWidget.isEnabled() && propertyWidget.isWritable());
String unitOfMeasure = propertyWidget.getUnitOfMeasure();
Log.d(TAG, "Setting property units of measure to: " + unitOfMeasure);
unitsOfMeasureTextView.setText(unitOfMeasure);
RangeConstraint<?> propertyRangeConstraint = propertyWidget.getPropertyRangeConstraint();
if (propertyRangeConstraint == null) {
Log.e(TAG, "Found null property-range. Disabling Slider. Returning a plain label.");
return new TextView(uiContext);
}
// set the current value
ValueType valueType = propertyWidget.getValueType();
final int initialValueNum = (initialValue == null ? 0 : ValueType.SHORT.equals(valueType) ?
((Short) initialValue) : ValueType.INT.equals(valueType) ? ((Integer) initialValue) : 0);
// !!! Android sliders always start from 0 !!!
Object minT = propertyRangeConstraint.getMin();
final int min = ValueType.SHORT.equals(valueType) ? ((Short) minT) : ValueType.INT.equals(valueType) ? ((Integer) minT) : 0;
Object maxT = propertyRangeConstraint.getMax();
int max = ValueType.SHORT.equals(valueType) ? ((Short) maxT) : ValueType.INT.equals(valueType) ? ((Integer) maxT) : 0;
Object incrementT = propertyRangeConstraint.getIncrement();
final int increment = ValueType.SHORT.equals(valueType) ? ((Short) incrementT) : ValueType.INT.equals(valueType) ? ((Integer) incrementT) : 0;
// because the minimum value in android always starts from 0, we move
// the max value to persist the min,max range
max -= min;
slider.setMax(max);
slider.setKeyProgressIncrement(increment);
final int initialValueTrans = initialValueNum - min;
Log.d(TAG, "Setting property value to: " + String.valueOf(initialValueNum) + " Slider value: '" + initialValueTrans + "'");
slider.setProgress(initialValueTrans);
valueTextView.setText(String.valueOf(initialValueNum));
slider.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
int currentProgress = initialValueTrans;
final int listenMin = min;
@Override
public void onStopTrackingTouch(final SeekBar seekBar) {
// set the property in a background task
SetPropertyAsyncTask asyncTask = new SetPropertyAsyncTask() {
@Override
protected void onFailure(ControlPanelException e) {
seekBar.setProgress(currentProgress);
valueTextView.setText(String.valueOf(currentProgress + listenMin));
if (exceptionHandler != null) {
// An exception was thrown. Restore old value.
exceptionHandler.handleControlPanelException(e);
}
}
@Override
protected void onSuccess() {
// All went well. Store the new value.
currentProgress = seekBar.getProgress();
}
};
int progress = seekBar.getProgress();
int valueToUpdate = progress + listenMin;
Log.d(TAG, "The slider progress: '" + progress + "' valueToUpdate: '" + valueToUpdate + "'");
asyncTask.execute(propertyWidget, valueToUpdate);
}// onStopTrackingTouch
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
valueTextView.setText(String.valueOf(progress + listenMin));
}
});
return layout;
}
// =====================================================================================================================
/**
* A callback that is invoked when the meta data of a UIElement has changed.
* Refreshes the UIElement and the corresponding View.
*
* @param element
* the abstract UIElement
*/
public void onMetaDataChange(UIElement element) {
UIElementType elementType = element.getElementType();
Log.d(TAG, "Refreshing the Android View for element : '" + element.getObjectPath() + "'");
switch (elementType) {
case ACTION_WIDGET: {
onActionMetaDataChange((ActionWidget) element);
break;
}// ACTION_WIDGET
case CONTAINER: {
onContainerMetaDataChange((ContainerWidget) element);
break;
}// CONTAINER
// case LIST_PROPERTY_WIDGET: {
// break;
// }//LIST_PROPERTY_WIDGET
case PROPERTY_WIDGET: {
onPropertyMetaDataChange((PropertyWidget) element);
break;
}// PROPERTY_WIDGET
case ALERT_DIALOG: {
onAlertDialogMetaDataChange((AlertDialogWidget) element);
break;
}// PROPERTY_WIDGET
default:
break;
}// switch :: elementType
}
// =====================================================================================================================
private void onContainerMetaDataChange(ContainerWidget container) {
if (container == null) {
Log.e(TAG, "onContainerMetaDataChange");
return;
}
// get a handle to the corresponding view
ViewGroup containerLayout = (ViewGroup) uiElementToView.get(container.getObjectPath());
if (containerLayout == null) {
Log.d(TAG, "ViewGroup not found for widget " + container.getObjectPath());
return;
}
boolean enabled = container.isEnabled();
Log.d(TAG, "Refreshing ContainerWidget bgColor: " + container.getBgColor() + " enabled: " + enabled);
// if (container.getBgColor() != null)
// containerLayout.setBackgroundColor(container.getBgColor());
if (enabled && !containerLayout.isEnabled()) {
enableViewGroup(containerLayout, true);
} else if (!enabled && containerLayout.isEnabled()) {
enableViewGroup(containerLayout, false);
}
}
// =====================================================================================================================
private void onActionMetaDataChange(final ActionWidget actionWidget) {
// get a handle to the corresponding view
Button actionButton = (Button) uiElementToView.get(actionWidget.getObjectPath());
if (actionButton == null) {
Log.d(TAG, "Button not found for widget " + actionWidget.getObjectPath());
return;
}
String label = actionWidget.getLabel();
Integer bgColor = actionWidget.getBgColor();
boolean enabled = actionWidget.isEnabled();
Log.d(TAG, "Refreshing ActionWidget: Label: " + label + " BGColor: " + bgColor + " Enabled: " + enabled);
actionButton.setText(label);
actionButton.setEnabled(enabled);
// if (bgColor != null) {
// Unfortunately button loses its pressed behavior when background is
// set.
// actionButton.setBackgroundColor(bgColor);
// }
}// onActionMetaDataChange
// =====================================================================================================================
private void onAlertDialogMetaDataChange(final AlertDialogWidget alertDialogWidget) {
// get a handle to the corresponding AlertDialog
AlertDialog alertDialog = alertWidgetToDialog.get(alertDialogWidget.getObjectPath());
if (alertDialog == null) {
Log.d(TAG, "AlertDialog not found for widget " + alertDialogWidget.getObjectPath());
return;
}
if (!alertDialogWidget.isEnabled() && alertDialog.isShowing()) {
Log.d(TAG, "Dismissing AlertDialog");
alertDialog.dismiss();
}
}// onAlertDialogMetaDataChange
// =====================================================================================================================
private void onPropertyMetaDataChange(PropertyWidget propertyWidget) {
// get a handle to the corresponding view
View propertyView = uiElementToView.get(propertyWidget.getObjectPath());
if (propertyView == null) {
Log.d(TAG, "Property View not found for widget " + propertyWidget.getObjectPath());
return;
}
Log.d(TAG, "Refreshing the view of property '" + propertyWidget.getLabel() + "' isWritable? " + propertyWidget.isWritable() + ", isEnabled? " + propertyWidget.isEnabled());
// Set enable/disable property
if (propertyView instanceof ViewGroup) {
enableViewGroup(propertyView, propertyWidget.isEnabled() && propertyWidget.isWritable());
}// if :: ViewGroup
else {
propertyView.setEnabled(propertyWidget.isEnabled() && propertyWidget.isWritable());
}
// if (!(propertyView instanceof Spinner)) {
// if (propertyWidget.getBgColor() != null)
// propertyView.setBackgroundColor(propertyWidget.getBgColor());
// }
}
/**
* Iteration over the given {@link ViewGroup} and set it enable/disable state
* @param propertyView {@link ViewGroup} to set its enable/disable state
* @param enable
*/
private void enableViewGroup(View propertyView, boolean enable) {
if (!(propertyView instanceof ViewGroup)) {
Log.w(TAG, "The given propertyView is no intanceof ViewGroup");
return;
}
ViewGroup viewGroup = (ViewGroup) propertyView;
for (int i = 0; i < viewGroup.getChildCount(); ++i) {
View element = viewGroup.getChildAt(i);
if (element instanceof ViewGroup) {
enableViewGroup(element, enable);
}
if (PROPERTY_EDITOR.equals(element.getTag())) {
element.setEnabled(enable);
}
}// for :: viewGroup
viewGroup.setEnabled(enable);
}// enableViewGroup
// =====================================================================================================================
/**
* A callback that is invoked when a value of a UIElement has changed.
* Refreshes the UIElement and the corresponding View.
* @param element the abstract UIElement
* @param newValue the new value
*/
public void onValueChange(UIElement element, Object newValue) {
UIElementType elementType = element.getElementType();
Log.d(TAG, "Value changed for the Android View for element : '" + element.getObjectPath() + "', newValue: '" + newValue);
switch (elementType) {
case PROPERTY_WIDGET: {
onPropertyValueChange((PropertyWidget) element, newValue);
break;
}// PROPERTY_WIDGET
case ACTION_WIDGET: {
Log.d(TAG, "Ignoring change of value for action : '" + element.getObjectPath() + "'");
break;
}// ACTION_WIDGET
case CONTAINER: {
Log.d(TAG, "Ignoring change of value for container : '" + element.getObjectPath() + "'");
break;
}// CONTAINER
// case LIST_PROPERTY_WIDGET: {
// break;
// }//LIST_PROPERTY_WIDGET
default:
break;
}// switch :: elementType
}
// =====================================================================================================================
/**
* A callback that is invoked when a value of a property has changed.
* Refreshes the property and the corresponding View.
* @param propertyWidget the property whose value has changed.
* @param newValue new value for the property
*/
private void onPropertyValueChange(PropertyWidget propertyWidget, Object newValue) {
// get a handle to the corresponding view
View propertyView = uiElementToView.get(propertyWidget.getObjectPath());
if (propertyView == null) {
Log.d(TAG, "Property View not found for widget " + propertyWidget.getObjectPath());
return;
}
if (newValue == null) {
Log.e(TAG, "onPropertyValueChange() failed, new value is null");
// ====
return;
}
ValueType valueType = propertyWidget.getValueType();
List<PropertyWidgetHintsType> hints = propertyWidget.getHints();
PropertyWidgetHintsType hint = (hints == null || hints.size() == 0) ? null : hints.get(0);
Log.d(TAG, "Refreshing the View for property '" + propertyWidget.getLabel() + "' , using UI hint: " + hint + ", value type: '" + valueType + "', objPath: '" + propertyWidget.getObjectPath()
+ "'" + "', newValue: '" + newValue);
switch (valueType) {
case BOOLEAN:
// Boolean Property
onCheckBoxValueChange(propertyView, propertyWidget, newValue);
break;
case DATE:
// Date Property
onDateValueChange(propertyView, propertyWidget, newValue);
break;
case TIME:
// Time Property
onTimeValueChange(propertyView, propertyWidget, newValue);
break;
case BYTE:
case INT:
case SHORT:
case LONG:
case DOUBLE:
// Scalar Property
if (hint == null) {
onNumericViewValueChange(propertyView, propertyWidget, newValue);
} else {
switch (hint) {
case SPINNER:
onSpinnerValueChange(propertyView, propertyWidget, newValue);
break;
case RADIO_BUTTON:
onRadioButtonValueChange(propertyView, propertyWidget, newValue);
break;
case NUMERIC_VIEW:
onNumericViewValueChange(propertyView, propertyWidget, newValue);
break;
case SLIDER:
onSliderValueChange(propertyView, propertyWidget, newValue);
break;
case NUMERIC_KEYPAD:
onNumericKeypadValueChange(propertyView, propertyWidget, newValue);
break;
default:
onNumericViewValueChange(propertyView, propertyWidget, newValue);
break;
}
}
break;
case STRING:
// String Property
if (hint == null) {
Log.d(TAG, "No hint provided for property '" + propertyWidget.getLabel() + "', creating default: TextView");
onTextViewValueChange(propertyView, propertyWidget, newValue);
} else {
switch (hint) {
case SPINNER:
onSpinnerValueChange(propertyView, propertyWidget, newValue);
break;
case RADIO_BUTTON:
onRadioButtonValueChange(propertyView, propertyWidget, newValue);
break;
case EDIT_TEXT:
onEditTextValueChange(propertyView, propertyWidget, newValue);
break;
case TEXT_VIEW:
onTextViewValueChange(propertyView, propertyWidget, newValue);
break;
default:
onTextViewValueChange(propertyView, propertyWidget, newValue);
break;
}
}
break;
default:
Log.d(TAG, "Received an unsupported ValueType: '" + valueType + "' , not refreshing any view");
break;
}
}
// =====================================================================================================================
private void onSliderValueChange(View propertyView, PropertyWidget propertyWidget, Object newValue2) {
ViewGroup layout = (ViewGroup) propertyView;
final TextView valueTextView = (TextView) layout.findViewWithTag(PROPERTY_VALUE);
final SeekBar slider = (SeekBar) layout.findViewWithTag(PROPERTY_EDITOR);
Log.d(TAG, "Refreshing the value of property " + propertyWidget.getLabel());
// set the current value
ValueType valueType = propertyWidget.getValueType();
int newValue = -1;
switch (valueType) {
case SHORT:
newValue = (Short) newValue2;
break;
case INT:
newValue = (Integer) newValue2;
break;
default:
Log.e(TAG, "property.getValueType() has unexpected value type: " + valueType);
// ====
return;
}
// set value
RangeConstraint<?> rangeCons = propertyWidget.getPropertyRangeConstraint();
if (rangeCons == null) {
Log.e(TAG, "Found null property-range nothing to do with it...");
return;
}
Object minT = rangeCons.getMin();
final int min = ValueType.SHORT.equals(valueType) ? ((Short) minT) : ValueType.INT.equals(valueType) ? ((Integer) minT) : 0;
valueTextView.setText(String.valueOf(newValue));
slider.setProgress(newValue - min);
}
// =====================================================================================================================
private void onCheckBoxValueChange(View propertyView, PropertyWidget propertyWidget, Object newValue) {
Log.d(TAG, "Refreshing the CheckBox of property " + propertyWidget.getLabel());
CheckBox checkbox = (CheckBox) propertyView;
ValueType valueType = propertyWidget.getValueType();
// set checked
if (ValueType.BOOLEAN.equals(valueType)) {
checkbox.setChecked((Boolean) newValue);
} else {
Log.e(TAG, "property.getCurrentValue() failed, cannot update property with value: " + newValue);
}
}
// =====================================================================================================================
private void onTextViewValueChange(View propertyView, PropertyWidget propertyWidget, Object newValue) {
String label = propertyWidget.getLabel();
Log.d(TAG, "Refreshing the TextView of property '" + label + "'");
// extract the text view
final ViewGroup layout = (ViewGroup) propertyView;
final TextView valueTextView = (TextView) layout.findViewWithTag(PROPERTY_VALUE);
// set the current value
String newValueStr = newValue.toString();
Log.d(TAG, "Setting property value to: '" + newValueStr + "'");
valueTextView.setText(newValueStr);
}
// =====================================================================================================================
private void onNumericViewValueChange(View propertyView, PropertyWidget propertyWidget, Object newValue) {
Log.d(TAG, "Refreshing the NumericView of property " + propertyWidget.getLabel());
// extract the text view
final ViewGroup layout = (ViewGroup) propertyView;
final TextView valueTextView = (TextView) layout.findViewWithTag(PROPERTY_VALUE);
// set the current value
Log.d(TAG, "Setting property value to: " + newValue.toString());
valueTextView.setText(newValue.toString());
}
// =====================================================================================================================
private void onNumericKeypadValueChange(View propertyView, PropertyWidget propertyWidget, Object newValue) {
Log.d(TAG, "Refreshing the NumericKeypad View of property " + propertyWidget.getLabel());
// extract the text view
final ViewGroup layout = (ViewGroup) propertyView;
final EditText valueEditText = (EditText) layout.findViewWithTag(PROPERTY_EDITOR);
// set the current value
Log.d(TAG, "Setting property value to: " + newValue.toString());
valueEditText.setText(newValue.toString());
}
// =====================================================================================================================
private void onTimeValueChange(View propertyView, PropertyWidget propertyWidget, Object newValue) {
Log.d(TAG, "Refreshing the Time View of property " + propertyWidget.getLabel());
// extract the text view
final ViewGroup layout = (ViewGroup) propertyView;
final Button valueButton = (Button) layout.findViewWithTag(PROPERTY_VALUE);
// set the current value
if (ValueType.TIME.equals(propertyWidget.getValueType())) {
PropertyWidget.Time time = (PropertyWidget.Time) newValue;
String formattedTime = formatTime(time.getHour(), time.getMinute());
Log.d(TAG, "Setting property value to: " + formattedTime);
valueButton.setText(formattedTime);
} else {
Log.e(TAG, "property.getValueType() is not TIME, cannot update property with new value: " + newValue);
}
}
// =====================================================================================================================
private void onDateValueChange(View propertyView, PropertyWidget propertyWidget, Object newValue) {
Log.d(TAG, "Refreshing the Date View of property " + propertyWidget.getLabel());
// extract the text view
final ViewGroup layout = (ViewGroup) propertyView;
final Button valueButton = (Button) layout.findViewWithTag(PROPERTY_VALUE);
// set the current value
if (ValueType.DATE.equals(propertyWidget.getValueType())) {
PropertyWidget.Date date = (PropertyWidget.Date) newValue;
String formattedDate = formatDate(date.getDay(), date.getMonth(), date.getYear());
Log.d(TAG, "Setting property value to: " + formattedDate);
valueButton.setText(formattedDate);
} else {
Log.e(TAG, "property.getValueType() is not DATE, cannot update property with current value: " + newValue);
}
}
// =====================================================================================================================
private void onEditTextValueChange(View propertyView, PropertyWidget propertyWidget, Object newValue) {
Log.d(TAG, "Refreshing the EditText View of property " + propertyWidget.getLabel());
// extract the text view
final ViewGroup layout = (ViewGroup) propertyView;
final EditText valueEditText = (EditText) layout.findViewWithTag(PROPERTY_EDITOR);
// set the current value
Log.d(TAG, "Setting property value to: " + newValue.toString());
valueEditText.setText(newValue.toString());
}
// =====================================================================================================================
private void onSpinnerValueChange(View propertyView, PropertyWidget propertyWidget, Object newValue) {
// extract the text view
final ViewGroup layout = (ViewGroup) propertyView;
final Spinner spinner = (Spinner) layout.findViewWithTag(PROPERTY_VALUE);
Log.d(TAG, "Refreshing the spinner of property " + propertyWidget.getLabel());
// set the selected item
int selection = 0;
@SuppressWarnings("unchecked")
final ArrayAdapter<LabelValuePair> adapter = (ArrayAdapter<LabelValuePair>) spinner.getAdapter();
for (int i = 0; i < adapter.getCount(); i++) {
LabelValuePair item = adapter.getItem(i);
if (item != null && item.value.equals(newValue)) {
selection = i;
break;
}
}
spinner.setSelection(selection);
adapter.notifyDataSetChanged();
}
// =====================================================================================================================
private void onRadioButtonValueChange(View propertyView, PropertyWidget propertyWidget, Object newValue) {
Log.d(TAG, "Refreshing the RadioButton of property '" + propertyWidget.getLabel() + "', new value: " + newValue);
final ViewGroup layout = (ViewGroup) propertyView;
final RadioGroup radioGroup = (RadioGroup) layout.findViewWithTag(PROPERTY_VALUE);
// set the selected item
int selection = 0;
final List<ConstrainToValues<?>> listOfConstraint = propertyWidget.getListOfConstraint();
if (listOfConstraint != null) {
for (ConstrainToValues<?> valueCons : listOfConstraint) {
boolean selectThis = valueCons.getValue().equals(newValue);
// check the default value
if (selectThis) {
Log.d(TAG, "Selecting radio button, Label: " + valueCons.getLabel() + " Value: " + valueCons.getValue());
RadioButton radioButton = (RadioButton) radioGroup.getChildAt(selection);
if (!radioButton.isChecked()) {
radioButton.setChecked(true);
}
} else {
selection++;
}
}
}// LOV constraints
}
// =====================================================================================================================
/**
* A wrapper class for hosting a {label,value} pair inside an ArrayAdapter.
* So that the label is displayed, while practically the real value is used.
*/
class LabelValuePair {
final String label;
final Object value;
public LabelValuePair(String label, Object value) {
super();
this.value = value;
this.label = label;
}
@Override
// This does the trick of displaying the label and not the value in the
// Adapter
public String toString() {
return label;
}
}
/**
* A utility method that formats time for display, following the user's
* locale as given by context
* @param hour
* @param minute
* @return
*/
private String formatTime(short hour, short minute) {
Calendar calendar = new GregorianCalendar();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
return DateFormat.getTimeFormat(uiContext.getApplicationContext()).format(calendar.getTime());
// return String.format("%02d", hour) + ":" + String.format("%02d",
// minute);
}
/**
* A utility method that formats dates for display, following the user's
* locale as given by context
* @param day
* @param month
* @param year
* @return
*/
private String formatDate(short day, short month, short year) {
// GregorianCalendar enums months from 0..11
month--;
Calendar calendar = new GregorianCalendar(year, month, day);
return DateFormat.getDateFormat(uiContext.getApplicationContext()).format(calendar.getTime());
}
}
| octoblu/alljoyn | alljoyn/services/controlpanel/java/ControlPanelAdapter/src/org/alljoyn/ioe/controlpaneladapter/ControlPanelAdapter.java | Java | isc | 106,823 |
/*
* Copyright (c) 2018 Erik Nordstrøm <erik@nordstroem.no>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
use arrayvec::ArrayVec;
use std::ops::Deref;
use cards::Card;
impl_cardstack!(StockSlot, StockSlotArray, 21); // 52 - (1 + 2 + 3 + 4 + 5 + 6 + 7) = 21
impl_cardstack!(WastePileSlot, WastePileSlotArray, 21);
impl_cardstack!(FoundationSlot, FoundationSlotArray, 13);
impl_cardstack!(TableauSlot, TableauSlotArray, 19);
pub struct Table
{
pub stock: StockSlot,
pub waste_pile: WastePileSlot,
pub foundations: [FoundationSlot; 4],
pub tableau: [TableauSlot; 7],
}
| en90/klondike | server/src/klondike.rs | Rust | isc | 1,308 |
---
title: la unidad del evangelio
date: 08/07/2017
---
**Lee para el estudio de esta semana**
Gálatas 2:1-14; 1 Corintios 1:10-13; Génesis 17:1-21; Juan 8:31-36; Colosenses 3:11.
><p>Para memorizar</p>
>“Completad mi gozo, sintiendo lo mismo, teniendo el mismo amor, unánimes, sintiendo una misma cosa” (Fil. 2:2).
**El reformador protestante Juan Calvino** creía que la desunión y la división eran la estratagema principal del diablo contra la iglesia, y advirtió que los cristianos deberían evitar el cisma como la peste.
Pero ¿debería preservarse la unidad a costa de la verdad? Imagina si Martín Lutero, el padre de la Reforma protestante, hubiera escogido, en nombre de la unidad, retractarse de su postura sobre la salvación solo por la fe cuando fue llevado a juicio en la Dieta de Worms.
“Si el reformador hubiera cedido en un solo punto, Satanás y sus ejércitos habrían ganado la victoria. Pero la inquebrantable firmeza de él fue el medio de emancipar a la iglesia, y de iniciar una era nueva y mejor” *(CS 153)*.
En Gálatas 2:1 al 14, encontramos al apóstol haciendo todo lo que está en su poder para mantener la unidad del círculo apostólico en medio de los intentos de destruirlo por parte de algunos creyentes. Pero, por más importante que esa unidad haya sido para Pablo, se rehusó a permitir que la verdad del evangelio fuera traicionada para alcanzarla. Aunque hay lugar para la diversidad dentro de la unidad, el evangelio nunca debe ser traicionado en el proceso. | Adventech/sabbath-school-lessons | src/es/2017-03/03/01.md | Markdown | mit | 1,523 |
using System;
using System.Linq;
using System.Reflection;
using NUnit.Framework;
using Should;
namespace AutoMapper.UnitTests.Tests
{
public abstract class using_generic_configuration : AutoMapperSpecBase
{
protected override void Establish_context()
{
Mapper.CreateMap<Source, Destination>()
.ForMember(d => d.Ignored, o => o.Ignore())
.ForMember(d => d.RenamedField, o => o.MapFrom(s => s.NamedProperty))
.ForMember(d => d.IntField, o => o.ResolveUsing<FakeResolver>().FromMember(s => s.StringField))
.ForMember("IntProperty", o => o.ResolveUsing<FakeResolver>().FromMember("AnotherStringField"))
.ForMember(d => d.IntProperty3,
o => o.ResolveUsing(typeof (FakeResolver)).FromMember(s => s.StringField3))
.ForMember(d => d.IntField4, o => o.ResolveUsing(new FakeResolver()).FromMember("StringField4"));
}
protected class Source
{
public int PropertyWithMatchingName { get; set; }
public NestedSource NestedSource { get; set; }
public int NamedProperty { get; set; }
public string StringField;
public string AnotherStringField;
public string StringField3;
public string StringField4;
}
protected class NestedSource
{
public int SomeField;
}
protected class Destination
{
public int PropertyWithMatchingName { get; set; }
public string NestedSourceSomeField;
public string Ignored { get; set; }
public string RenamedField;
public int IntField;
public int IntProperty { get; set; }
public int IntProperty3 { get; set; }
public int IntField4;
}
class FakeResolver : ValueResolver<string, int>
{
protected override int ResolveCore(string source)
{
return default(int);
}
}
}
public class when_members_have_matching_names : using_generic_configuration
{
const string memberName = "PropertyWithMatchingName";
static MemberInfo sourceMember;
protected override void Because_of()
{
sourceMember =
Mapper.FindTypeMapFor<Source, Destination>()
.GetPropertyMaps()
.Single(pm => pm.DestinationProperty.Name == memberName)
.SourceMember;
}
[Test]
public void should_not_be_null()
{
sourceMember.ShouldNotBeNull();
}
[Test]
public void should_have_the_matching_member_of_the_source_type_as_value()
{
sourceMember.ShouldBeSameAs(typeof (Source).GetProperty(memberName));
}
}
public class when_the_destination_member_is_flattened : using_generic_configuration
{
static MemberInfo sourceMember;
protected override void Because_of()
{
sourceMember =
Mapper.FindTypeMapFor<Source, Destination>()
.GetPropertyMaps()
.Single(pm => pm.DestinationProperty.Name == "NestedSourceSomeField")
.SourceMember;
}
[Test] public void should_not_be_null()
{
sourceMember.ShouldNotBeNull();
}
[Test] public void should_have_the_member_of_the_nested_source_type_as_value()
{
sourceMember.ShouldBeSameAs(typeof (NestedSource).GetField("SomeField"));
}
}
public class when_the_destination_member_is_ignored : using_generic_configuration
{
static Exception exception;
static MemberInfo sourceMember;
protected override void Because_of()
{
try
{
sourceMember =
Mapper.FindTypeMapFor<Source, Destination>()
.GetPropertyMaps()
.Single(pm => pm.DestinationProperty.Name == "Ignored")
.SourceMember;
}
catch (Exception ex)
{
exception = ex;
}
}
[Test] public void should_not_throw_an_exception()
{
exception.ShouldBeNull();
}
[Test] public void should_be_null()
{
sourceMember.ShouldBeNull();
}
}
public class when_the_destination_member_is_projected : using_generic_configuration
{
static MemberInfo sourceMember;
protected override void Because_of()
{
sourceMember =
Mapper.FindTypeMapFor<Source, Destination>()
.GetPropertyMaps()
.Single(pm => pm.DestinationProperty.Name == "RenamedField")
.SourceMember;
}
[Test] public void should_not_be_null()
{
sourceMember.ShouldNotBeNull();
}
[Test] public void should_have_the_projected_member_of_the_source_type_as_value()
{
sourceMember.ShouldBeSameAs(typeof (Source).GetProperty("NamedProperty"));
}
}
public class when_the_destination_member_is_resolved_from_a_source_member : using_generic_configuration
{
static MemberInfo sourceMember;
protected override void Because_of()
{
sourceMember =
Mapper.FindTypeMapFor<Source, Destination>()
.GetPropertyMaps()
.Single(pm => pm.DestinationProperty.Name == "IntField")
.SourceMember;
}
[Test] public void should_not_be_null()
{
sourceMember.ShouldNotBeNull();
}
[Test] public void should_have_the_member_of_the_source_type_it_is_resolved_from_as_value()
{
sourceMember.ShouldBeSameAs(typeof (Source).GetField("StringField"));
}
}
public class when_the_destination_property_is_resolved_from_a_source_member_using_the_Magic_String_overload : using_generic_configuration
{
static MemberInfo sourceMember;
protected override void Because_of()
{
sourceMember =
Mapper.FindTypeMapFor<Source, Destination>()
.GetPropertyMaps()
.Single(pm => pm.DestinationProperty.Name == "IntProperty")
.SourceMember;
}
[Test] public void should_not_be_null()
{
sourceMember.ShouldNotBeNull();
}
[Test] public void should_have_the_member_of_the_source_type_it_is_resolved_from_as_value()
{
sourceMember.ShouldBeSameAs(typeof (Source).GetField("AnotherStringField"));
}
}
public class when_the_destination_property_is_resolved_from_a_source_member_using_the_non_generic_resolve_method : using_generic_configuration
{
static MemberInfo sourceMember;
protected override void Because_of()
{
sourceMember =
Mapper.FindTypeMapFor<Source, Destination>()
.GetPropertyMaps()
.Single(pm => pm.DestinationProperty.Name == "IntProperty3")
.SourceMember;
}
[Test] public void should_not_be_null()
{
sourceMember.ShouldNotBeNull();
}
[Test] public void should_have_the_member_of_the_source_type_it_is_resolved_from_as_value()
{
sourceMember.ShouldBeSameAs(typeof (Source).GetField("StringField3"));
}
}
public class when_the_destination_property_is_resolved_from_a_source_member_using_non_the_generic_resolve_method_and_the_Magic_String_overload : using_generic_configuration
{
static MemberInfo sourceMember;
protected override void Because_of()
{
sourceMember =
Mapper.FindTypeMapFor<Source, Destination>()
.GetPropertyMaps()
.Single(pm => pm.DestinationProperty.Name == "IntField4")
.SourceMember;
}
[Test] public void should_not_be_null()
{
sourceMember.ShouldNotBeNull();
}
[Test] public void should_have_the_member_of_the_source_type_it_is_resolved_from_as_value()
{
sourceMember.ShouldBeSameAs(typeof (Source).GetField("StringField4"));
}
}
public abstract class using_nongeneric_configuration : AutoMapperSpecBase
{
protected override void Establish_context()
{
Mapper.CreateMap(typeof (Source), typeof (Destination))
.ForMember("RenamedProperty", o => o.MapFrom("NamedProperty"));
}
protected class Source
{
public int NamedProperty { get; set; }
}
protected class Destination
{
public string RenamedProperty { get; set; }
}
}
public class when_the_destination_property_is_projected : using_nongeneric_configuration
{
static MemberInfo sourceMember;
protected override void Because_of()
{
sourceMember =
Mapper.FindTypeMapFor<Source, Destination>()
.GetPropertyMaps()
.Single(pm => pm.DestinationProperty.Name == "RenamedProperty")
.SourceMember;
}
[Test] public void should_not_be_null()
{
sourceMember.ShouldNotBeNull();
}
[Test]
public void should_have_the_projected_member_of_the_source_type_as_value()
{
sourceMember.ShouldBeSameAs(typeof (Source).GetProperty("NamedProperty"));
}
}
} | IanYates83/AutoMapper | src/UnitTests/Tests/PropertyMapSpecs.cs | C# | mit | 10,237 |
namespace GridDesktop.Examples.WorkingWithWorksheet
{
partial class ExportDataToDataTable
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.button2 = new System.Windows.Forms.Button();
this.gridDesktop1 = new Aspose.Cells.GridDesktop.GridDesktop();
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// button2
//
this.button2.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
this.button2.Location = new System.Drawing.Point(215, 428);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(157, 23);
this.button2.TabIndex = 8;
this.button2.Text = "Export To Specific DataTable";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// gridDesktop1
//
this.gridDesktop1.ActiveSheetIndex = 0;
this.gridDesktop1.ActiveSheetNameFont = null;
this.gridDesktop1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.gridDesktop1.CommentDisplayingFont = new System.Drawing.Font("Arial", 9F);
this.gridDesktop1.IsHorizontalScrollBarVisible = true;
this.gridDesktop1.IsVerticalScrollBarVisible = true;
this.gridDesktop1.Location = new System.Drawing.Point(12, 12);
this.gridDesktop1.Name = "gridDesktop1";
this.gridDesktop1.SheetNameFont = new System.Drawing.Font("Verdana", 8F);
this.gridDesktop1.SheetTabWidth = 400;
this.gridDesktop1.Size = new System.Drawing.Size(727, 410);
this.gridDesktop1.TabIndex = 7;
//
// button1
//
this.button1.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
this.button1.Location = new System.Drawing.Point(378, 428);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(157, 23);
this.button1.TabIndex = 9;
this.button1.Text = "Export To New DataTable";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// ExportDataToDataTable
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(751, 463);
this.Controls.Add(this.button1);
this.Controls.Add(this.button2);
this.Controls.Add(this.gridDesktop1);
this.Name = "ExportDataToDataTable";
this.Text = "Export Data To DataTable";
this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
this.Load += new System.EventHandler(this.ExportDataToDataTable_Load);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button button2;
private Aspose.Cells.GridDesktop.GridDesktop gridDesktop1;
private System.Windows.Forms.Button button1;
}
} | aspose-cells/Aspose.Cells-for-.NET | Examples_GridDesktop/CSharp/GridDesktop.Examples/WorkingWithWorksheet/ExportDataToDataTable.Designer.cs | C# | mit | 4,283 |
import leon.annotation._
import leon.lang._
import leon.lang.synthesis._
object Complete {
sealed abstract class List
case class Cons(head: Int, tail: List) extends List
case object Nil extends List
def size(l: List) : Int = (l match {
case Nil => 0
case Cons(_, t) => 1 + size(t)
}) ensuring(res => res >= 0)
def content(l: List): Set[Int] = l match {
case Nil => Set.empty[Int]
case Cons(i, t) => Set(i) ++ content(t)
}
def isSorted(list : List) : Boolean = list match {
case Nil => true
case Cons(_, Nil) => true
case Cons(x1, Cons(x2, _)) if(x1 >= x2) => false
case Cons(_, xs) => isSorted(xs)
}
def insert(in1: List, v: Int): List = {
require(isSorted(in1))
in1 match {
case Cons(h, t) =>
if (v < h) {
Cons(v, in1)
} else if (v == h) {
in1
} else {
Cons(h, insert(t, v))
}
case Nil =>
Cons(v, Nil)
}
} ensuring { res => (content(res) == content(in1) ++ Set(v)) && isSorted(res) }
def delete(in1: List, v: Int): List = {
require(isSorted(in1))
in1 match {
case Cons(h,t) =>
if (h < v) {
Cons(h, delete(t, v))
} else if (h == v) {
t
} else {
in1
}
case Nil =>
Nil
}
} ensuring { res => content(res) == content(in1) -- Set(v) && isSorted(res) }
//def union(in1: List, in2: List): List = {
// require(isSorted(in1) && isSorted(in2))
// in1 match {
// case Cons(h1, t1) =>
// union(t1, insert(in2, h1))
// case Nil =>
// in2
// }
//} ensuring { res => content(res) == content(in1) ++ content(in2) && isSorted(res) }
def union(in1: List, in2: List) = {
require(isSorted(in1) && isSorted(in2))
choose( (out : List) => (content(out) == content(in1) ++ content(in2)) &&
isSorted(out)
)
}
}
| ericpony/scala-examples | testcases/synthesis/oopsla2013/StrictSortedList/Union.scala | Scala | mit | 1,903 |
/**
* Solarized Light theme for reveal.js.
* Author: Achim Staebler
*/
@import url(../../lib/font/league-gothic/league-gothic.css);
@import url(https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic);
/**
* Solarized colors by Ethan Schoonover
*/
html * {
color-profile: sRGB;
rendering-intent: auto; }
/*********************************************
* GLOBAL STYLES
*********************************************/
body {
background: #fdf6e3;
background-color: #fdf6e3; }
.reveal {
font-family: "Lato", sans-serif;
font-size: 36px;
font-weight: normal;
color: #657b83; }
::selection {
color: #fff;
background: #d33682;
text-shadow: none; }
.reveal .slides > section,
.reveal .slides > section > section {
line-height: 1.3;
font-weight: inherit; }
/*********************************************
* HEADERS
*********************************************/
.reveal h1,
.reveal h2,
.reveal h3,
.reveal h4,
.reveal h5,
.reveal h6 {
margin: 0 0 20px 0;
color: #586e75;
font-family: "League Gothic", Impact, sans-serif;
font-weight: normal;
line-height: 1.2;
letter-spacing: normal;
text-transform: uppercase;
text-shadow: none;
word-wrap: break-word; }
.reveal h1 {
font-size: 3.77em; }
.reveal h2 {
font-size: 2.11em; }
.reveal h3 {
font-size: 1.55em; }
.reveal h4 {
font-size: 1em; }
.reveal h1 {
text-shadow: none; }
/*********************************************
* OTHER
*********************************************/
.reveal p {
margin: 20px 0;
line-height: 1.3; }
/* Ensure certain elements are never larger than the slide itself */
.reveal img,
.reveal video,
.reveal iframe {
max-width: 95%;
max-height: 95%; }
.reveal strong,
.reveal b {
font-weight: bold; }
.reveal em {
font-style: italic; }
.reveal ol,
.reveal dl,
.reveal ul {
display: inline-block;
text-align: left;
margin: 0 0 0 1em; }
.reveal ol {
list-style-type: decimal; }
.reveal ul {
list-style-type: disc; }
.reveal ul ul {
list-style-type: square; }
.reveal ul ul ul {
list-style-type: circle; }
.reveal ul ul,
.reveal ul ol,
.reveal ol ol,
.reveal ol ul {
display: block;
margin-left: 40px; }
.reveal dt {
font-weight: bold; }
.reveal dd {
margin-left: 40px; }
.reveal q,
.reveal blockquote {
quotes: none; }
.reveal blockquote {
display: block;
position: relative;
width: 70%;
margin: 20px auto;
padding: 5px;
font-style: italic;
background: rgba(255, 255, 255, 0.05);
box-shadow: 0px 0px 2px rgba(0, 0, 0, 0.2); }
.reveal blockquote p:first-child,
.reveal blockquote p:last-child {
display: inline-block; }
.reveal q {
font-style: italic; }
.reveal pre {
display: block;
position: relative;
width: 90%;
margin: 20px auto;
text-align: left;
font-size: 0.55em;
font-family: monospace;
line-height: 1.2em;
word-wrap: break-word;
box-shadow: 0px 0px 6px rgba(0, 0, 0, 0.3); }
.reveal code {
font-family: monospace; }
.reveal pre code {
display: block;
padding: 5px;
overflow: auto;
max-height: 400px;
word-wrap: normal;
background: #3F3F3F;
color: #DCDCDC; }
.reveal table {
margin: auto;
border-collapse: collapse;
border-spacing: 0; }
.reveal table th {
font-weight: bold; }
.reveal table th,
.reveal table td {
text-align: left;
padding: 0.2em 0.5em 0.2em 0.5em;
border-bottom: 1px solid; }
.reveal table th[align="center"],
.reveal table td[align="center"] {
text-align: center; }
.reveal table th[align="right"],
.reveal table td[align="right"] {
text-align: right; }
.reveal table tr:last-child td {
border-bottom: none; }
.reveal sup {
vertical-align: super; }
.reveal sub {
vertical-align: sub; }
.reveal small {
display: inline-block;
font-size: 0.6em;
line-height: 1.2em;
vertical-align: top; }
.reveal small * {
vertical-align: top; }
/*********************************************
* LINKS
*********************************************/
.reveal a {
color: #268bd2;
text-decoration: none;
-webkit-transition: color 0.15s ease;
-moz-transition: color 0.15s ease;
transition: color 0.15s ease; }
.reveal a:hover {
color: #78b9e6;
text-shadow: none;
border: none; }
.reveal .roll span:after {
color: #fff;
background: #1a6091; }
/*********************************************
* IMAGES
*********************************************/
.reveal section img {
margin: 15px 0px;
background: rgba(255, 255, 255, 0.12);
border: 4px solid #657b83;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.15); }
.reveal a img {
-webkit-transition: all 0.15s linear;
-moz-transition: all 0.15s linear;
transition: all 0.15s linear; }
.reveal a:hover img {
background: rgba(255, 255, 255, 0.2);
border-color: #268bd2;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.55); }
/*********************************************
* NAVIGATION CONTROLS
*********************************************/
.reveal .controls div.navigate-left,
.reveal .controls div.navigate-left.enabled {
border-right-color: #268bd2; }
.reveal .controls div.navigate-right,
.reveal .controls div.navigate-right.enabled {
border-left-color: #268bd2; }
.reveal .controls div.navigate-up,
.reveal .controls div.navigate-up.enabled {
border-bottom-color: #268bd2; }
.reveal .controls div.navigate-down,
.reveal .controls div.navigate-down.enabled {
border-top-color: #268bd2; }
.reveal .controls div.navigate-left.enabled:hover {
border-right-color: #78b9e6; }
.reveal .controls div.navigate-right.enabled:hover {
border-left-color: #78b9e6; }
.reveal .controls div.navigate-up.enabled:hover {
border-bottom-color: #78b9e6; }
.reveal .controls div.navigate-down.enabled:hover {
border-top-color: #78b9e6; }
/*********************************************
* PROGRESS BAR
*********************************************/
.reveal .progress {
background: rgba(0, 0, 0, 0.2); }
.reveal .progress span {
background: #268bd2;
-webkit-transition: width 800ms cubic-bezier(0.26, 0.86, 0.44, 0.985);
-moz-transition: width 800ms cubic-bezier(0.26, 0.86, 0.44, 0.985);
transition: width 800ms cubic-bezier(0.26, 0.86, 0.44, 0.985); }
/*********************************************
* SLIDE NUMBER
*********************************************/
.reveal .slide-number {
color: #268bd2; }
| loumontano/sassconf-maps | css/theme/solarized.css | CSS | mit | 6,303 |
package org.multibit.hd.ui.views.wizards.welcome.create_wallet;
import com.google.common.base.Optional;
import net.miginfocom.swing.MigLayout;
import org.multibit.hd.brit.core.seed_phrase.SeedPhraseGenerator;
import org.multibit.hd.ui.MultiBitUI;
import org.multibit.hd.ui.events.view.ViewEvents;
import org.multibit.hd.ui.languages.MessageKey;
import org.multibit.hd.ui.views.components.Components;
import org.multibit.hd.ui.views.components.Labels;
import org.multibit.hd.ui.views.components.ModelAndView;
import org.multibit.hd.ui.views.components.Panels;
import org.multibit.hd.ui.views.components.display_seed_phrase.DisplaySeedPhraseModel;
import org.multibit.hd.ui.views.components.display_seed_phrase.DisplaySeedPhraseView;
import org.multibit.hd.ui.views.components.panels.PanelDecorator;
import org.multibit.hd.ui.views.fonts.AwesomeIcon;
import org.multibit.hd.ui.views.wizards.AbstractWizard;
import org.multibit.hd.ui.views.wizards.AbstractWizardPanelView;
import org.multibit.hd.ui.views.wizards.WizardButton;
import org.multibit.hd.ui.views.wizards.welcome.WelcomeWizardModel;
import javax.swing.*;
import java.util.List;
/**
* <p>Wizard to provide the following to UI:</p>
* <ul>
* <li>Create wallet from seed phrase display</li>
* </ul>
*
* @since 0.0.1
*
*/
public class CreateWalletSeedPhrasePanelView extends AbstractWizardPanelView<WelcomeWizardModel, List<String>> {
private ModelAndView<DisplaySeedPhraseModel, DisplaySeedPhraseView> displaySeedPhraseMaV;
/**
* @param wizard The wizard managing the states
* @param panelName The panel name to filter events from components
*/
public CreateWalletSeedPhrasePanelView(AbstractWizard<WelcomeWizardModel> wizard, String panelName) {
super(wizard, panelName, AwesomeIcon.KEY, MessageKey.CREATE_WALLET_SEED_PHRASE_TITLE);
}
@Override
public void newPanelModel() {
SeedPhraseGenerator seedPhraseGenerator = getWizardModel().getSeedPhraseGenerator();
displaySeedPhraseMaV = Components.newDisplaySeedPhraseMaV(seedPhraseGenerator);
setPanelModel(displaySeedPhraseMaV.getModel().getValue());
getWizardModel().setCreateWalletSeedPhrase(displaySeedPhraseMaV.getModel().getSeedPhrase());
getWizardModel().setActualSeedTimestamp(displaySeedPhraseMaV.getModel().getSeedTimestamp());
// Register components
registerComponents(displaySeedPhraseMaV);
}
@Override
public void initialiseContent(JPanel contentPanel) {
contentPanel.setLayout(new MigLayout(
Panels.migXYLayout(),
"[]", // Column constraints
"[][]" // Row constraints
));
// Warning notes
contentPanel.add(Labels.newNoteLabel(MessageKey.SEED_WARNING_NOTE_1, null), MultiBitUI.WIZARD_MAX_WIDTH_MIG + ",wrap");
contentPanel.add(Labels.newNoteLabel(MessageKey.SEED_WARNING_NOTE_2, null), MultiBitUI.WIZARD_MAX_WIDTH_MIG + ",wrap");
contentPanel.add(Labels.newNoteLabel(MessageKey.SEED_WARNING_NOTE_3, null), MultiBitUI.WIZARD_MAX_WIDTH_MIG + ",wrap");
contentPanel.add(Labels.newNoteLabel(MessageKey.SEED_WARNING_NOTE_4, null), MultiBitUI.WIZARD_MAX_WIDTH_MIG + ",wrap");
contentPanel.add(displaySeedPhraseMaV.getView().newComponentPanel(), MultiBitUI.WIZARD_MAX_WIDTH_MIG + ",wrap");
}
@Override
protected void initialiseButtons(AbstractWizard<WelcomeWizardModel> wizard) {
PanelDecorator.addExitCancelPreviousNext(this, wizard);
}
@Override
public void fireInitialStateViewEvents() {
// Enable the "next" button
ViewEvents.fireWizardButtonEnabledEvent(getPanelName(), WizardButton.NEXT, true);
}
@Override
public void afterShow() {
displaySeedPhraseMaV.getView().requestInitialFocus();
// Ensure there is a new seed phrase each time to strongly urge the use of pen and paper
displaySeedPhraseMaV.getView().newSeedPhrase(displaySeedPhraseMaV.getModel().getCurrentSeedSize());
}
@Override
public void updateFromComponentModels(Optional componentModel) {
// Update the wizard model with the latest seed information
getWizardModel().setCreateWalletSeedPhrase(displaySeedPhraseMaV.getModel().getSeedPhrase());
getWizardModel().setActualSeedTimestamp(displaySeedPhraseMaV.getModel().getSeedTimestamp());
}
}
| bitcoin-solutions/multibit-hd | mbhd-swing/src/main/java/org/multibit/hd/ui/views/wizards/welcome/create_wallet/CreateWalletSeedPhrasePanelView.java | Java | mit | 4,231 |
<div id="HeadContent">
<meta name="description" content="View all career opportunities with MAQ Software's engineering centers in Redmond, Hyderabad and Mumbai. Contact the recruitment team today!" />
<meta name="keywords" content="MAQ Software, Jobs, .NET, Windows Phone 7, Windows Phone 8, iPhone, iPad, iPad2, careers, Azure, cloud, Careers in USA, Developer jobs, Tester jobs, Senior Software Developer, CRM Developer, Mobile Developer, Project Manager, Program Manager, Content Editor, Web Application Developer, Software Development Engineer in Test, Software Test Engineer, Programmer Analyst, Microsoft Jobs" />
</div>
<div id="MainContent">
<div class="dvLimitedWith dvBackground Pad40 PagePadding">
<h1 class="DataTitle SemiBold Color58585a">Join us. Explore your potential.</h1>
<aside class="LeftArticle CarrersDataSection FloatLeft">
<!-- Engineering Development Manager-->
<article data-post="0" style="display: none;">
<div class="SecondNav">
<a href="#Careers" class="BackLink MarginBoT25">Back to Openings</a><span> » </span><span class="JobTitle">Engineering Development Manager</span>
</div>
<p class="Datatagline SemiBold Clear">Engineering Development Manager</p>
<p class="DataSubContent">
MAQ Software has an opening for Engineering Development Manager at Redmond, WA.
Your key result areas as percentage of your overall work items will be:
</p>
<ul class="DataSubContent CircleBullets">
<li>
Manage resource, direct and coordinate technical activities to develop and deliver
web
application projects in Cloud Computing and Microsoft.Net platform to meet specific
client
needs and define the scope of each assigned project
</li>
<li>Direct, review and approve product design and changes</li>
<li>Responsible to track for multiple releases and deliveries for product groups</li>
<li>Direct Architecture development and provide IT solutions</li>
<li>
Resource management by recruiting, assigning, mentoring IT professionals to ensure
optimal
performance per scheduled deadlines
</li>
<li>Performance management including annual performance reviews and professional growth</li>
<li>
Review Request for Proposals, formulate project plan specifications and provide
cost
estimations
</li>
<li>
Provide technical pre-sales support to sales team to provide IT solutions to meet
client
demands
</li>
</ul>
<p class="SemiBold Color3f3f3f DataSubContent">Candidate Profile</p>
<ul class="DataSubContent CircleBullets">
<li>
Master’s Degree or foreign equivalent in Computer Science, CIS, Management, MIS,
Engineering (any), or related field plus 2 years’ experience or Bachelor’s degree
plus 5 years’
experience
</li>
<li>
Must be able to travel temporarily to client sites with expenses paid by the employer
and/or
relocate throughout the U.S.
</li>
</ul>
<p class="SemiBold Color3f3f3f DataSubContent">
Please send resume to MAQ Software, 15446 Bel Red Road, # 201, Redmond, WA 98052,
Attn: H.R.
Manager.
</p>
</article>
<!--Programmer Analyst-->
<article data-post="1" style="display: none;">
<div class="SecondNav">
<a href="#Careers" class="BackLink MarginBoT25">Back to Openings</a><span> » </span><span class="JobTitle">Programmer Analyst</span>
</div>
<p class="Datatagline SemiBold Clear">Programmer Analyst</p>
<p class="DataSubContent">
Programmer Analyst will be required to:
</p>
<ul class="DataSubContent CircleBullets">
<li>Analyze, develop and write codes to implement system applications</li>
<li>
Additionally, will assist in providing software support to projects that include programming, testing, debugging, and modifying software to meet
customer specifications
</li>
</ul>
<p class="DataSubContent SemiBold Color3f3f3f">Candidate Profile</p>
<ul class="CircleBullets DataSubContent">
<li>Requires Bachelor’s Degree or foreign equivalent in Computer Science, Computer Applications, Computer Information Systems, Electrical/Electronic Engineering or related field with 2 years of work experience in job offered, software engineer, system analyst or related work</li>
</ul>
<p class="DataSubContent">
May require travel to client sites within the U.S. with expenses paid by employer and or relocate throughout the U.S.
</p>
<p class="DataSubContent SemiBold Color3f3f3f">
Send resume to 15446 Bel Red Road, #201, Redmond, WA 98052, Attn: H.R. Manager.
</p>
</article>
<!--Localization Program Manager-->
<article data-post="2" style="display: none;">
<div class="SecondNav">
<a href="#Careers" class="BackLink MarginBoT25">Back to Openings</a><span> » </span><span class="JobTitle">Localization Program Manager</span>
</div>
<p class="Datatagline SemiBold Clear">Localization Program Manager</p>
<p class="DataSubContent">
Your key result areas as percentage of your overall work items will be:
</p>
<ul class="CircleBullets DataSubContent">
<li>
Analyzing web content and recommending which content is localized for various
markets; Ensuring the localizability of the content
</li>
<li>
Defining and documenting the international processes for new areas of the product
and website in the localization documentation
</li>
<li>
Supporting multiple release schedules throughout the project while handling all
PM
daily tasks
</li>
<li>Reviewing specs and ensuring our content is worldwide ready</li>
<li>
Influencing US content developers to plan upcoming content with international
requirements as a top priority
</li>
<li>
Constantly striving to improve processes and document tools requirements where
needed
</li>
</ul>
<p class="DataSubContent">
We are looking for a talented and enthusiastic international program manager to
join our
web development team. Our customer websites reach millions of customers every month
and are constantly evolving to improve the customer experience.
</p>
<p class="DataSubContent SemiBold Color3f3f3f">Candidate Profile</p>
<ul class="CircleBullets DataSubContent">
<li>
Excellent English written and verbal communication skills, detail-oriented, and
organizational skills are a must
</li>
<li>
Passion for technology and the web is essential; experience managing, designing
or maintaining websites is required
</li>
<li>
Ability to work independently, learn quickly, prioritize tasks, meet deadlines,
and solve problems required
</li>
<li>Experience using globalization and localization tools preferred </li>
<li>Familiarity with HTML/XML and web technologies a definite plus</li>
<li>Understanding of the software development lifecycle and processes preferred</li>
<li>Ability to work in large teams across time zones</li>
<li>Bachelor's degree required</li>
</ul>
<p class="DataSubContent SemiBold Color3f3f3f">
Please send resume to MAQ Software, 15446 Bel Red Road, # 201, Redmond, WA 98052,
Attn: H.R.
Manager.
</p>
</article>
<!--Program Manager-->
<article data-post="3" style="display: none;">
<div class="SecondNav">
<a href="#Careers" class="BackLink MarginBoT25">Back to Openings</a><span> » </span><span class="JobTitle">Program Manager</span>
</div>
<p class="Datatagline SemiBold Clear">Program Manager</p>
<p class="DataSubContent">
Your key result areas as percentage of your overall work items will be:
</p>
<ul class="CircleBullets DataSubContent">
<li>
Managing and working closely with the development and test team to help define the
requirements and feature sets
</li>
<li>
Analyzing customer data, gathering feedback and ensuring that the product meets
user requirements
</li>
<li>
Supporting multiple release schedules throughout the project while handling all
PM
daily tasks
</li>
</ul>
<p class="DataSubContent">
We are looking for an experienced and highly motivated Project Manager, with broad
experience in e-commerce based and/or smart client products, solid technical skills,
excellent communication skills, and a track record of shipping great products. Not
only
will this position require taking on a critical role on a high-performance team
but you will
help to develop an industry altering product with over a million hits a day.
</p>
<p class="DataSubContent SemiBold Color3f3f3f">Candidate Profile</p>
<ul class="CircleBullets DataSubContent">
<li>3 to 5 years as a Project Manager with strong leadership skills</li>
<li>Bachelor's or equivalent degree in related field desired</li>
<li>
Strong understanding of Project Management and the ability to handle multiple
projects and challenges
</li>
<li>
Strong technical background in .NET and Microsoft platform with the ability to
develop specifications and partner with development and test teams
</li>
<li>
Excellent communication skills, both verbal and written, with an ability to communicate
difficult technical and business concepts to both technical and non-technical users
</li>
<li>Previous Microsoft experience is a plus</li>
</ul>
<p class="DataSubContent SemiBold Color3f3f3f">
Please send resume to MAQ Software, 15446 Bel Red Road, # 201, Redmond, WA 98052,
Attn: H.R.
Manager.
</p>
</article>
<!--Content Editor-->
<article data-post="4" style="display: none;">
<div class="SecondNav">
<a href="#Careers" class="BackLink MarginBoT25">Back to Openings</a><span> » </span><span class="JobTitle">Content Editor</span>
</div>
<p class="Datatagline SemiBold Clear">Content Editor</p>
<p class="DataSubContent">
Your key result areas as percentage of your overall work items will be:
</p>
<ul class="CircleBullets DataSubContent">
<li>
Website Editing: Utilize knowledge of web architecture, user interface design, MS
editorial standards, and web publishing practices to build and implement new content
areas/site features/graphics, individually or in conjunction with other development
resources
</li>
<li>
Editing and proofing submitted content and ensuring compliance with corporate style
and legal guidelines
</li>
<li>
Utilize knowledge of web architecture to spec out and implement small content
areas/site features, individually or in conjunction with development resources
</li>
</ul>
<p class="DataSubContent">
We are seeking long-term contractor(s) to manage customer Internet sites for a large
Redmond software company. The website Producer/Editor will help develop and manage
content. This position is ideal for a strong website editor and content developer
with
previous experience interfacing with MSCOM and SharePoint.
</p>
<p class="DataSubContent SemiBold Color3f3f3f">Candidate Profile</p>
<ul class="CircleBullets DataSubContent">
<li>One year minimum experience writing or producing web content required</li>
<li>
Two years minimum editorial/writing experience and demonstrated knowledge of
grammar, spelling and style required
</li>
<li>Hands-on experience with HTML required. XML knowledge is useful </li>
<li>Knowledge of website architecture and user interface principles a plus </li>
<li>
Knowledge of the MS server platform and general knowledge of Microsoft
environment a plus
</li>
</ul>
<p class="DataSubContent SemiBold Color3f3f3f">
Please send resume to MAQ Software, 15446 Bel Red Road, # 201, Redmond, WA 98052,
Attn: H.R.
Manager.
</p>
</article>
<!--Web Application Developer-->
<article data-post="5" style="display: none;">
<div class="SecondNav">
<a href="#Careers" class="BackLink MarginBoT25">Back to Openings</a><span> » </span><span class="JobTitle">Web Application Developer</span>
</div>
<p class="Datatagline SemiBold Clear">Web Application Developer</p>
<p class="DataSubContent">
Your key result areas as percentage of your overall work items will be:
</p>
<ul class="DataSubContent CircleBullets">
<li>Web application development using C#, XML, .NET </li>
<li>Database design (advanced skills in writing queries and stored procedures)</li>
<li>Understand functional requirements </li>
<li>Interact with graphic designers</li>
<li>Write technical documentation such as design and design rationale documents</li>
<li>Participate in test case generation, design, and code reviews</li>
<li>Debug, handle client requests, etc.</li>
</ul>
<p class="DataSubContent">
Design and build enterprise web applications using C#, XML and .NET
</p>
<p class="DataSubContent SemiBold Color3f3f3f">Candidate Profile</p>
<ul class="DataSubContent CircleBullets">
<li>Computer Science engineering/MCA degree with excellent academic credentials</li>
<li>2-5 years experience in reputed software companies</li>
<li>Experience in C# language and .NET platform </li>
<li>Strong foundation in SDLC concepts and exposure to quality processes </li>
</ul>
<p class="DataSubContent SemiBold Color3f3f3f">
Please send resume to MAQ Software, 15446 Bel Red Road, # 201, Redmond, WA 98052,
Attn: H.R.
Manager.
</p>
</article>
<!--Software Development Engineer in Test-->
<article data-post="6" style="display: none;">
<div class="SecondNav">
<a href="#Careers" class="BackLink MarginBoT25">Back to Openings</a><span> » </span><span class="JobTitle">Software Development Engineer in Test</span>
</div>
<p class="Datatagline SemiBold Clear">Software Development Engineer in Test</p>
<p class="DataSubContent">
Your key result areas as percentage of your overall work items will be:
</p>
<ul class="DataSubContent CircleBullets">
<li>Understand functional requirements to prepare, design, and execute test cases</li>
<li>Develop test automation, execute and analyze code coverage</li>
<li>Self-direct investigation of system configuration issues, documentation, and resolution</li>
<li>Monitor and triage test bugs, assisting developers in identifying necessary fixes</li>
<li>Able to setup debugging for root cause analysis in underlying systems under test</li>
<li>System level testing with drivers and performance testing</li>
<li>Report test run results and regression testing</li>
<li>Monitor process implementation and compliance</li>
</ul>
<p class="DataSubContent">
We are looking for a dynamic individual to work extensively with our development team and lead the testing of web applications.
In addition, SDET will be responsible for interacting with our clients on all critical application designs and changes.
He/she will be responsible for reviewing functional specifications, hands-on testing and supporting application deployment.
</p>
<p class="DataSubContent SemiBold Color3f3f3f">Candidate Profile</p>
<ul class="DataSubContent CircleBullets">
<li>Bachelor's degree in Computer Science, engineering or a related field</li>
<li>Minimum four years experience in structured testing environments</li>
<li>Thorough knowledge of development, test, and release process essential</li>
<li>
Strong foundation in SDLC concepts and exposure to quality processes coding skills in
C++ and/or C#, SQL and experience with the .NET framework
</li>
<li>Knowledge of test methodologies and best practices</li>
<li>Experience with automation testing tools helpful</li>
<li>Analytical problem solving and statistical analysis</li>
<li>Superior verbal and written communication skills</li>
<li>Commitment to working in a team environment</li>
<li>Enjoy a fast-paced rewarding role in a dynamic environment</li>
</ul>
<p class="DataSubContent SemiBold Color3f3f3f">
Please send resume to MAQ Software, 15446 Bel Red Road, # 201, Redmond, WA 98052,
Attn: H.R.
Manager.
</p>
</article>
<!--Software Test Engineer -->
<article data-post="7" style="display: none;">
<div class="SecondNav">
<a href="#Careers" class="BackLink MarginBoT25">Back to Openings</a><span> » </span><span class="JobTitle">Software Test Engineer</span>
</div>
<p class="Datatagline SemiBold Clear">Software Test Engineer</p>
<p class="DataSubContent">
Your key result areas as percentage of your overall work items will be:
</p>
<ul class="DataSubContent CircleBullets">
<li>Understand functional requirement to help prepare a test plan</li>
<li>Design and execute test cases</li>
<li>Report test run results and regression testing</li>
<li>Help comply and monitor process implementation</li>
</ul>
<p class="DataSubContent">
You will work extensively with our development team and lead the testing of web applications.
</p>
<p class="DataSubContent SemiBold Color3f3f3f">Candidate Profile</p>
<ul class="DataSubContent CircleBullets">
<li>Bachelor's degree in Computer Science, engineering or a related field</li>
<li>Knowledge of test methodologies</li>
<li>Great communication skills</li>
</ul>
<p class="DataSubContent SemiBold Color3f3f3f">
Please send resume to MAQ Software, 15446 Bel Red Road, # 201, Redmond, WA 98052,
Attn: H.R.
Manager.
</p>
</article>
<!--Systems Engineer -->
<article data-post="8" style="display: none;">
<div class="SecondNav">
<a href="#Careers" class="BackLink MarginBoT25">Back to Openings</a><span> » </span><span class="JobTitle">Systems Engineer</span>
</div>
<p class="Datatagline SemiBold Clear">Systems Engineer</p>
<p class="DataSubContent">
Your key result areas as percentage of your overall work items will be:
</p>
<ul class="DataSubContent CircleBullets">
<li>Maintain and support IT systems based on Microsoft Windows XP, Microsoft Windows Vista, Windows Server 2003, SQL Server 2005, and .NET technology</li>
<li>Key areas of expertise will include IIS website management in production, Active Directory, security, server monitoring, and network infrastructure</li>
<li>Provide technical engineering support for the implementation, integration, and evolution of complex systems architectures</li>
<li>Design and maintain Internet services support strategies</li>
<li>
Provide systems statistical trending and analysis, server capacity and threshold testing, systems documentation maintenance,
and the analysis and evaluation of new systems designs and technical strategies
</li>
<li>Troubleshoot complex issues, identify root causes and develop mitigation options</li>
<li>Provide operations and production support to ensure continuous availability of systems</li>
<li>Utilize best practices to continually evaluate system performance for possible areas of improvement</li>
<li>Disaster recovery, automate backups, security analysis, and systems reviews</li>
<li>Create on-going documentation of the environments as they evolve</li>
</ul>
<p class="DataSubContent SemiBold Color3f3f3f">Candidate Profile</p>
<ul class="DataSubContent CircleBullets">
<li>A minimum of two-three years experience in supporting Windows Servers in a Microsoft platform based data center environment</li>
<li>Working knowledge of Active Directory, XML, .NET Framework, TCP/IP, and SQL Server</li>
<li>Knowledge of application hosting and support including basic security concepts</li>
<li>Strong interpersonal and communications skills</li>
<li>Bachelor's or equivalent degree in related field desired</li>
<li>Current Microsoft Certified System Engineer (MCSE) required</li>
</ul>
<p class="DataSubContent SemiBold Color3f3f3f">
Please send resume to MAQ Software, 15446 Bel Red Road, # 201, Redmond, WA 98052,
Attn: H.R.
Manager.
</p>
</article>
</aside>
<aside class="CareersRight FloatLeft">
<p class="pTagLine SemiBold m30">Contact Information</p>
<div class="m30">
<p>For positions in Redmond,</p>
<p>e-mail your resume to</p>
<p class="Colorred"><a id="RedMail" class="BackLink">RedmondJobs@MAQSoftware.com</a></p>
</div>
</aside>
</div>
</div> | maqgunupurum/maqgunupurum.github.io | CareerinUS.html | HTML | mit | 27,422 |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* Json library
* @class Logs_controller
* @version 07/05/2015 12:18:00
*/
class Logs_controller {
function read() {
$page = getVarClean('page','int',1);
$limit = getVarClean('rows','int',5);
$sidx = getVarClean('sidx','str','log_id');
$sord = getVarClean('sord','str','desc');
$data = array('rows' => array(), 'page' => 1, 'records' => 0, 'total' => 1, 'success' => false, 'message' => '');
$user_name = getVarClean('user_name','str','');
try {
$ci = & get_instance();
$ci->load->model('administration/logs');
$table = $ci->logs;
$req_param = array(
"sort_by" => $sidx,
"sord" => $sord,
"limit" => null,
"field" => null,
"where" => null,
"where_in" => null,
"where_not_in" => null,
"search" => $_REQUEST['_search'],
"search_field" => isset($_REQUEST['searchField']) ? $_REQUEST['searchField'] : null,
"search_operator" => isset($_REQUEST['searchOper']) ? $_REQUEST['searchOper'] : null,
"search_str" => isset($_REQUEST['searchString']) ? $_REQUEST['searchString'] : null
);
// Filter Table
$req_param['where'] = array("log.log_user ='".$user_name."'");
$table->setJQGridParam($req_param);
$count = $table->countAll();
if ($count > 0) $total_pages = ceil($count / $limit);
else $total_pages = 1;
if ($page > $total_pages) $page = $total_pages;
$start = $limit * $page - ($limit); // do not put $limit*($page - 1)
$req_param['limit'] = array(
'start' => $start,
'end' => $limit
);
$table->setJQGridParam($req_param);
if ($page == 0) $data['page'] = 1;
else $data['page'] = $page;
$data['total'] = $total_pages;
$data['records'] = $count;
$data['rows'] = $table->getAll();
$data['success'] = true;
logging('view data log');
}catch (Exception $e) {
$data['message'] = $e->getMessage();
}
return $data;
}
function crud() {
$data = array();
$oper = getVarClean('oper', 'str', '');
switch ($oper) {
default :
permission_check('can-view-log');
$data = $this->read();
break;
}
return $data;
}
}
/* End of file Modules_controller.php */ | wiliamdecosta/captrack | application/libraries/administration/Logs_controller.php | PHP | mit | 2,803 |
# coding: utf-8
# pylint: disable = invalid-name, W0105, C0301
from __future__ import absolute_import
import collections
from operator import gt, lt
from .compat import range_
class EarlyStopException(Exception):
"""Exception of early stopping.
Parameters
----------
best_iteration : int
The best iteration stopped.
"""
def __init__(self, best_iteration, best_score):
super(EarlyStopException, self).__init__()
self.best_iteration = best_iteration
self.best_score = best_score
# Callback environment used by callbacks
CallbackEnv = collections.namedtuple(
"LightGBMCallbackEnv",
["model",
"params",
"iteration",
"begin_iteration",
"end_iteration",
"evaluation_result_list"])
def _format_eval_result(value, show_stdv=True):
"""format metric string"""
if len(value) == 4:
return '%s\'s %s: %g' % (value[0], value[1], value[2])
elif len(value) == 5:
if show_stdv:
return '%s\'s %s: %g + %g' % (value[0], value[1], value[2], value[4])
else:
return '%s\'s %s: %g' % (value[0], value[1], value[2])
else:
raise ValueError("Wrong metric value")
def print_evaluation(period=1, show_stdv=True):
"""Create a callback that prints the evaluation results.
Parameters
----------
period : int, optional (default=1)
The period to print the evaluation results.
show_stdv : bool, optional (default=True)
Whether to show stdv (if provided).
Returns
-------
callback : function
The callback that prints the evaluation results every ``period`` iteration(s).
"""
def callback(env):
"""internal function"""
if period > 0 and env.evaluation_result_list and (env.iteration + 1) % period == 0:
result = '\t'.join([_format_eval_result(x, show_stdv) for x in env.evaluation_result_list])
print('[%d]\t%s' % (env.iteration + 1, result))
callback.order = 10
return callback
def record_evaluation(eval_result):
"""Create a callback that records the evaluation history into ``eval_result``.
Parameters
----------
eval_result : dict
A dictionary to store the evaluation results.
Returns
-------
callback : function
The callback that records the evaluation history into the passed dictionary.
"""
if not isinstance(eval_result, dict):
raise TypeError('Eval_result should be a dictionary')
eval_result.clear()
def init(env):
"""internal function"""
for data_name, _, _, _ in env.evaluation_result_list:
eval_result.setdefault(data_name, collections.defaultdict(list))
def callback(env):
"""internal function"""
if not eval_result:
init(env)
for data_name, eval_name, result, _ in env.evaluation_result_list:
eval_result[data_name][eval_name].append(result)
callback.order = 20
return callback
def reset_parameter(**kwargs):
"""Create a callback that resets the parameter after the first iteration.
Note
----
The initial parameter will still take in-effect on first iteration.
Parameters
----------
**kwargs: value should be list or function
List of parameters for each boosting round
or a customized function that calculates the parameter in terms of
current number of round (e.g. yields learning rate decay).
If list lst, parameter = lst[current_round].
If function func, parameter = func(current_round).
Returns
-------
callback : function
The callback that resets the parameter after the first iteration.
"""
def callback(env):
"""internal function"""
new_parameters = {}
for key, value in kwargs.items():
if key in ['num_class', 'boosting_type', 'metric']:
raise RuntimeError("cannot reset {} during training".format(repr(key)))
if isinstance(value, list):
if len(value) != env.end_iteration - env.begin_iteration:
raise ValueError("Length of list {} has to equal to 'num_boost_round'.".format(repr(key)))
new_param = value[env.iteration - env.begin_iteration]
else:
new_param = value(env.iteration - env.begin_iteration)
if new_param != env.params.get(key, None):
new_parameters[key] = new_param
if new_parameters:
env.model.reset_parameter(new_parameters)
env.params.update(new_parameters)
callback.before_iteration = True
callback.order = 10
return callback
def early_stopping(stopping_rounds, verbose=True):
"""Create a callback that activates early stopping.
Note
----
Activates early stopping.
Requires at least one validation data and one metric.
If there's more than one, will check all of them.
Parameters
----------
stopping_rounds : int
The possible number of rounds without the trend occurrence.
verbose : bool, optional (default=True)
Whether to print message with early stopping information.
Returns
-------
callback : function
The callback that activates early stopping.
"""
best_score = []
best_iter = []
best_score_list = []
cmp_op = []
def init(env):
"""internal function"""
if not env.evaluation_result_list:
raise ValueError('For early stopping, at least one dataset and eval metric is required for evaluation')
if verbose:
msg = "Training until validation scores don't improve for {} rounds."
print(msg.format(stopping_rounds))
for eval_ret in env.evaluation_result_list:
best_iter.append(0)
best_score_list.append(None)
if eval_ret[3]:
best_score.append(float('-inf'))
cmp_op.append(gt)
else:
best_score.append(float('inf'))
cmp_op.append(lt)
def callback(env):
"""internal function"""
if not cmp_op:
init(env)
for i in range_(len(env.evaluation_result_list)):
score = env.evaluation_result_list[i][2]
if cmp_op[i](score, best_score[i]):
best_score[i] = score
best_iter[i] = env.iteration
best_score_list[i] = env.evaluation_result_list
elif env.iteration - best_iter[i] >= stopping_rounds:
if verbose:
print('Early stopping, best iteration is:\n[%d]\t%s' % (
best_iter[i] + 1, '\t'.join([_format_eval_result(x) for x in best_score_list[i]])))
raise EarlyStopException(best_iter[i], best_score_list[i])
callback.order = 30
return callback
| Allardvm/LightGBM | python-package/lightgbm/callback.py | Python | mit | 6,890 |
/* Part of libhgfs - (c) 2009, D.C. van Moolenbroek */
/* Various macros used here and there */
#define MAKELONG(a,b) ((a) | ((b) << 16))
#define HIWORD(d) ((d) >> 16)
#define LOWORD(d) ((d) & 0xffff)
#define BYTES(a,b,c,d) ((a) | ((b) << 8) | ((c) << 16) | ((d) << 24))
/* Valid channel types for channel_open() */
#define CH_IN BYTES('T', 'C', 'L', 'O')
#define CH_OUT BYTES('R', 'P', 'C', 'I')
/* RPC constants */
#define RPC_BUF_SIZE 6134 /* max size of RPC request */
#define RPC_HDR_SIZE 10 /* RPC HGFS header size */
/* RPC macros. These NEED NOT be portable. VMware only does x86(-64) anyway. */
/* ..all this because ACK can't pack structures :( */
#define RPC_NEXT8 *(((u8_t*)(++rpc_ptr))-1) /* get/set next byte */
#define RPC_NEXT16 *(((u16_t*)(rpc_ptr+=2))-1) /* get/set next short */
#define RPC_NEXT32 *(((u32_t*)(rpc_ptr+=4))-1) /* get/set next long */
#define RPC_LEN (rpc_ptr - rpc_buf) /* request length thus far */
#define RPC_ADVANCE(n) rpc_ptr += n /* skip n bytes in buffer */
#define RPC_PTR (rpc_ptr) /* pointer to next data */
#define RPC_RESET rpc_ptr = rpc_buf /* start at beginning */
#define RPC_REQUEST(r) \
RPC_RESET; \
RPC_NEXT8 = 'f'; \
RPC_NEXT8 = ' '; \
RPC_NEXT32 = 0; \
RPC_NEXT32 = r; /* start a RPC request */
/* HGFS requests */
enum {
HGFS_REQ_OPEN,
HGFS_REQ_READ,
HGFS_REQ_WRITE,
HGFS_REQ_CLOSE,
HGFS_REQ_OPENDIR,
HGFS_REQ_READDIR,
HGFS_REQ_CLOSEDIR,
HGFS_REQ_GETATTR,
HGFS_REQ_SETATTR,
HGFS_REQ_MKDIR,
HGFS_REQ_UNLINK,
HGFS_REQ_RMDIR,
HGFS_REQ_RENAME,
HGFS_REQ_QUERYVOL
};
/* HGFS open types */
enum {
HGFS_OPEN_TYPE_O,
HGFS_OPEN_TYPE_OT,
HGFS_OPEN_TYPE_CO,
HGFS_OPEN_TYPE_C,
HGFS_OPEN_TYPE_COT
};
/* HGFS mode/perms conversion macros */
#define HGFS_MODE_TO_PERM(m) (((m) & S_IRWXU) >> 6)
#define HGFS_PERM_TO_MODE(p) (((p) << 6) & S_IRWXU)
| ducis/operating-system-labs | src.clean/lib/libhgfs/const.h | C | mit | 1,916 |
/*global require, module*/
var webpack = require('webpack');
var webpackConfig = require('./webpack.config.js');
webpackConfig.plugins = webpackConfig.plugins || [];
webpackConfig.plugins.push(new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
}));
module.exports = function(grunt) {
grunt.loadNpmTasks('grunt-webpack');
grunt.loadNpmTasks('grunt-karma');
grunt.initConfig({
webpack: {
options: webpackConfig,
build: {}
},
karma: {
singleRun: {
configFile: 'karma.conf.js',
singleRun: true
}
}
});
grunt.registerTask('build', ['webpack:build']);
grunt.registerTask('test', ['karma:singleRun']);
grunt.registerTask('default', ['build', 'test']);
};
| tf/pageflow-dependabot-test | node_package/Gruntfile.js | JavaScript | mit | 769 |
'''Todo:
* Add multiple thread support for async_process functions
* Potentially thread each handler function? idk
'''
import sys
import socket
import re
import threading
import logging
import time
if sys.hexversion < 0x03000000:
#Python 2
import Queue as queue
BlockingIOError = socket.error
else:
import queue
from .ircclient import IRCClient
logger = logging.getLogger(__name__)
#Somewhat complex regex that accurately matches nick!username@host, with named groups for easy parsing and usage
user_re = re.compile(r'(?P<nick>[\w\d<-\[\]\^\{\}\~]+)!(?P<user>[\w\d<-\[\]\^\{\}\~]+)@(?P<host>.+)')
class IRCBot(IRCClient):
'''See `IRCClient` for basic client usage, here is usage for the bot system
Handler notation:
on_join(self, nick, host, channel)
on_topic(self, nick, host, channel, topic)
on_part(self, nick, host, channel, message)
on_msg(self, nick, host, channel, message)
on_privmsg(self, nick, host, message)
on_chanmsg(self, nick, host, channel, message)
on_notice(self, nick, host, channel, message)
on_nick(self, nick, new_nick, host)
'''
_handlers = {
'join': [],
'part': [],
'kick': [],
'topic': [],
'msg': [],
'privmsg': [],
'chanmsg': [],
'notice': [],
'nick': []
}
_process_thread = None
def _async_process(self):
while not self._stop_event.is_set():
time.sleep(0.01)
try:
args = self._in_queue.get_nowait()
#These "msg"s will be raw irc received lines, which have several forms
# basically, we should be looking for
# :User!Name@host COMMAND <ARGS>
userhost = user_re.search(args[0][1:])
if userhost:
nick, host, user = userhost.groups()
command = args[1]
if command == 'JOIN':
channel = args[2][1:] #JOIN Channels are : prefixed
for handler in self._handlers['join']:
handler(self, nick, host, channel)
elif command == 'TOPIC':
channel = args[2]
topic = ' '.join(args[3:])
for handler in self._handlers['topic']:
handler(self, nick, host, channel, topic)
elif command == 'PART':
channel = args[2]
message = ' '.join(args[3:])
for handler in self._handlers['part']:
handler(self, nick, host, channel, message)
elif command == 'PRIVMSG':
channel = args[2]
message = ' '.join(args[3:])[1:]
for handler in self._handlers['msg']:
handler(self, nick, host, channel, message)
if channel[0] == '#':
#this is a channel
for handler in self._handlers['chanmsg']:
handler(self, nick, host, channel, message)
else:
#private message
for handler in self._handlers['privmsg']:
handler(self, nick, host, message)
elif command == 'KICK':
channel = args[2]
kicked_nick = args[3]
reason = ' '.join(args[4:])[1:]
for handler in self._handlers['kick']:
handler(self, nick, host, channel, kicked_nick, reason)
elif command == 'NICK':
new_nick = args[2][1:]
for handler in self._handlers['nick']:
handler(self, nick, new_nick, host)
elif command == 'NOTICE':
#:nick!user@host NOTICE <userchan> :message
channel = args[2]
message = ' '.join(args[3:])
for handler in self._handlers['notice']:
handler(self, nick, host, channel, message)
else:
logger.warning("Unhandled command %s" % command)
self._in_queue.task_done()
except queue.Empty as e: pass
except Exception as e:
logger.exception("Error while handling message " + str(args))
def start(self):
IRCClient.start(self)
self._process_thread = threading.Thread(target=self._async_process)
self._process_thread.start()
def on(self, type):
'''Decorator function'''
def decorator(self, func):
'''decorated functions should be written as class methods
@on('join')
def on_join(self, channel):
print("Joined channel %s" % channel)
'''
self._handlers[type].append(func)
return func
return decorator
def on_join(self, func):
self._handlers['join'].append(func)
return func
def on_part(self, func):
self._handlers['part'].append(func)
return func
def on_kick(self, func):
self._handlers['kick'].append(func)
return func
def on_msg(self, func):
self._handlers['msg'].append(func)
return func
def on_privmsg(self, func):
self._handlers['privmsg'].append(func)
return func
def on_chanmsg(self, func):
self._handlers['chanmsg'].append(func)
return func
def on_notice(self, func):
self._handlers['notice'].append(func)
return func
def on_nick(self, func):
self._handlers['nick'].append(func)
return func
__all__ = ['IRCBot']
| codetalkio/TelegramIRCImageProxy | asyncirc/ircbot.py | Python | mit | 5,983 |
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*
*/
package com.microsoft.azure.management.network.v2018_04_01.implementation;
import com.microsoft.azure.arm.model.implementation.WrapperImpl;
import com.microsoft.azure.management.network.v2018_04_01.Usages;
import rx.Observable;
import rx.functions.Func1;
import com.microsoft.azure.Page;
import com.microsoft.azure.management.network.v2018_04_01.Usage;
class UsagesImpl extends WrapperImpl<UsagesInner> implements Usages {
private final NetworkManager manager;
UsagesImpl(NetworkManager manager) {
super(manager.inner().usages());
this.manager = manager;
}
public NetworkManager manager() {
return this.manager;
}
private UsageImpl wrapModel(UsageInner inner) {
return new UsageImpl(inner, manager());
}
@Override
public Observable<Usage> listAsync(final String location) {
UsagesInner client = this.inner();
return client.listAsync(location)
.flatMapIterable(new Func1<Page<UsageInner>, Iterable<UsageInner>>() {
@Override
public Iterable<UsageInner> call(Page<UsageInner> page) {
return page.items();
}
})
.map(new Func1<UsageInner, Usage>() {
@Override
public Usage call(UsageInner inner) {
return wrapModel(inner);
}
});
}
}
| navalev/azure-sdk-for-java | sdk/network/mgmt-v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/UsagesImpl.java | Java | mit | 1,596 |
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import {accumulateEnterLeaveDispatches} from 'events/EventPropagators';
import {
TOP_MOUSE_OUT,
TOP_MOUSE_OVER,
TOP_POINTER_OUT,
TOP_POINTER_OVER,
} from './DOMTopLevelEventTypes';
import SyntheticMouseEvent from './SyntheticMouseEvent';
import SyntheticPointerEvent from './SyntheticPointerEvent';
import {
getClosestInstanceFromNode,
getNodeFromInstance,
} from '../client/ReactDOMComponentTree';
const eventTypes = {
mouseEnter: {
registrationName: 'onMouseEnter',
dependencies: [TOP_MOUSE_OUT, TOP_MOUSE_OVER],
},
mouseLeave: {
registrationName: 'onMouseLeave',
dependencies: [TOP_MOUSE_OUT, TOP_MOUSE_OVER],
},
pointerEnter: {
registrationName: 'onPointerEnter',
dependencies: [TOP_POINTER_OUT, TOP_POINTER_OVER],
},
pointerLeave: {
registrationName: 'onPointerLeave',
dependencies: [TOP_POINTER_OUT, TOP_POINTER_OVER],
},
};
const EnterLeaveEventPlugin = {
eventTypes: eventTypes,
/**
* For almost every interaction we care about, there will be both a top-level
* `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that
* we do not extract duplicate events. However, moving the mouse into the
* browser from outside will not fire a `mouseout` event. In this case, we use
* the `mouseover` top-level event.
*/
extractEvents: function(
topLevelType,
targetInst,
nativeEvent,
nativeEventTarget,
) {
const isOverEvent =
topLevelType === TOP_MOUSE_OVER || topLevelType === TOP_POINTER_OVER;
const isOutEvent =
topLevelType === TOP_MOUSE_OUT || topLevelType === TOP_POINTER_OUT;
if (isOverEvent && (nativeEvent.relatedTarget || nativeEvent.fromElement)) {
return null;
}
if (!isOutEvent && !isOverEvent) {
// Must not be a mouse or pointer in or out - ignoring.
return null;
}
let win;
if (nativeEventTarget.window === nativeEventTarget) {
// `nativeEventTarget` is probably a window object.
win = nativeEventTarget;
} else {
// TODO: Figure out why `ownerDocument` is sometimes undefined in IE8.
const doc = nativeEventTarget.ownerDocument;
if (doc) {
win = doc.defaultView || doc.parentWindow;
} else {
win = window;
}
}
let from;
let to;
if (isOutEvent) {
from = targetInst;
const related = nativeEvent.relatedTarget || nativeEvent.toElement;
to = related ? getClosestInstanceFromNode(related) : null;
} else {
// Moving to a node from outside the window.
from = null;
to = targetInst;
}
if (from === to) {
// Nothing pertains to our managed components.
return null;
}
let eventInterface, leaveEventType, enterEventType, eventTypePrefix;
if (topLevelType === TOP_MOUSE_OUT || topLevelType === TOP_MOUSE_OVER) {
eventInterface = SyntheticMouseEvent;
leaveEventType = eventTypes.mouseLeave;
enterEventType = eventTypes.mouseEnter;
eventTypePrefix = 'mouse';
} else if (
topLevelType === TOP_POINTER_OUT ||
topLevelType === TOP_POINTER_OVER
) {
eventInterface = SyntheticPointerEvent;
leaveEventType = eventTypes.pointerLeave;
enterEventType = eventTypes.pointerEnter;
eventTypePrefix = 'pointer';
}
const fromNode = from == null ? win : getNodeFromInstance(from);
const toNode = to == null ? win : getNodeFromInstance(to);
const leave = eventInterface.getPooled(
leaveEventType,
from,
nativeEvent,
nativeEventTarget,
);
leave.type = eventTypePrefix + 'leave';
leave.target = fromNode;
leave.relatedTarget = toNode;
const enter = eventInterface.getPooled(
enterEventType,
to,
nativeEvent,
nativeEventTarget,
);
enter.type = eventTypePrefix + 'enter';
enter.target = toNode;
enter.relatedTarget = fromNode;
accumulateEnterLeaveDispatches(leave, enter, from, to);
return [leave, enter];
},
};
export default EnterLeaveEventPlugin;
| krasimir/react | packages/react-dom/src/events/EnterLeaveEventPlugin.js | JavaScript | mit | 4,240 |
using Mono.Cecil;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Pumpkin {
public class Signature {
public string ClassName { get; set; }
public string MethodName { get; set; }
public bool IsStatic { get; set; }
public IList<ParameterDefinition> Parameters { get; set; }
public override bool Equals(object obj) {
var other = obj as Signature;
if (other == null)
return false;
return other.ClassName.Equals(ClassName) &&
other.MethodName.Equals(MethodName) &&
other.IsStatic == IsStatic &&
other.Parameters.Count == Parameters.Count &&
other.Parameters.
Zip(Parameters, (p1, p2) => p1.ParameterType.FullName.Equals(p2.ParameterType.FullName)).
All(p => p);
}
public override int GetHashCode() {
// TODO: review
return ClassName.GetHashCode() ^
MethodName.GetHashCode() ^
Parameters.Count;
}
}
} | ldematte/ManagedPumpkin | Pumpkin/Signature.cs | C# | mit | 1,124 |
/*
* Licensed to the University Corporation for Advanced Internet Development,
* Inc. (UCAID) under one or more contributor license agreements. See the
* NOTICE file distributed with this work for additional information regarding
* copyright ownership. The UCAID licenses this file to You under the Apache
* License, Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
*
*/
package org.opensaml.saml2.core.validator;
import org.opensaml.saml2.core.AuthnContextClassRef;
import org.opensaml.xml.util.DatatypeHelper;
import org.opensaml.xml.validation.ValidationException;
import org.opensaml.xml.validation.Validator;
/**
* Checks {@link org.opensaml.saml2.core.AuthnContextClassRef} for Schema compliance.
*/
public class AuthnContextClassRefSchemaValidator implements Validator<AuthnContextClassRef> {
/** Constructor */
public AuthnContextClassRefSchemaValidator() {
}
/** {@inheritDoc} */
public void validate(AuthnContextClassRef authnContextClassRef) throws ValidationException {
validateClassRef(authnContextClassRef);
}
/**
* Checks that the AuthnContextClassRef is present.
*
* @param authnCCR
* @throws ValidationException
*/
protected void validateClassRef(AuthnContextClassRef authnCCR) throws ValidationException {
if (DatatypeHelper.isEmpty(authnCCR.getAuthnContextClassRef())) {
throw new ValidationException("AuthnContextClassRef required");
}
}
} | Safewhere/kombit-web-java | kombit-opensaml-2.5.1/src/org/opensaml/saml2/core/validator/AuthnContextClassRefSchemaValidator.java | Java | mit | 1,953 |
---
layout: base
sitemap: false
---
<div class="illustration">
<div class="container">
<img src="{{ site.github.url | replace: 'http://', '//' }}/images/illustration-full.png" alt="Tech Blog">
</div>
</div>
<article class="container">
{% for post in paginator.posts %}
{% unless post.draft %}
<section class="index">
{% if post.author.image %}<img src="{{ site.github.url | replace: 'http://', '//' }}/images/{{ post.author.image }}" class="avatar">{% endif %}
{% if post.author.imageURL %}<img src="{{ post.author.imageURL }}" class="avatar">{% endif %}
<div>
<h2 class="title"><a href="{{ site.github.url | replace: 'http://', '//' }}{{ post.url }}" rel="prefetch">{{ post.title }}</a></h2>
<div class="meta">
Written By <address>{{ post.author.name }}</address> —
<time pubdate datetime="{{ post.date | date: "%Y-%d-%B" }}" title="{{ post.date | date: "%B %d, %Y" }}">{{ post.date | date: "%B %d, %Y" }}</time>
</div>
<div class="post_content">{{ post.excerpt }}</div>
<p class="readmore"><a href="{{ site.github.url | replace: 'http://', '//' }}{{ post.url }}" rel="prefetch">Read more...</a></p>
</div>
</section>
{% endunless %}
{% endfor %}
<section class="pagination" style="text-align:center">
{% if paginator.next_page %}
<a href="{{ site.github.url | replace: 'http://', '//' }}/page{{ paginator.next_page }}" class="btn btn-outline">< Older</a>
{% endif %}
{% if paginator.previous_page %}
{% if paginator.previous_page == 1 %}
<a href="{{ site.github.url | replace: 'http://', '//' }}" class="btn btn-outline">Newer ></a>
{% else %}
<a href="{{ site.github.url | replace: 'http://', '//' }}/page{{ paginator.previous_page }}" class="btn btn-outline">Newer ></a>
{% endif %}
{% endif %}
</section>
</article>
| Coveo/coveo.github.io | index.html | HTML | mit | 1,968 |
<?php
/*
* 2007-2015 PrestaShop
*
* 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@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2015 PrestaShop SA
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
function add_new_groups($french, $standard)
{
$res = Db::getInstance()->execute('INSERT INTO `'._DB_PREFIX_.'group` (`id_group`, `date_add`, `date_upd`) VALUES (NULL, NOW(), NOW())');
$last_id = Db::getInstance()->Insert_ID();
$languages = Db::getInstance()->executeS('SELECT id_lang, iso_code FROM `'._DB_PREFIX_.'lang`');
$sql = '';
foreach ($languages as $lang)
if (strtolower($lang['iso_code']) == 'fr')
$sql .= '('.(int)$last_id.', '.(int)$lang['id_lang'].', "'.pSQL($french).'"),';
else
$sql .= '('.(int)$last_id.', '.(int)$lang['id_lang'].', "'.pSQL($standard).'"),';
$sql = substr($sql, 0, strlen($sql) - 1);
$res &= Db::getInstance()->execute('INSERT INTO `'._DB_PREFIX_.'group_lang` (`id_group`, `id_lang`, `name`) VALUES '.$sql);
// we add the different id_group in the configuration
if (strtolower($standard) == 'visitor')
$res &= Db::getInstance()->execute('INSERT INTO `'._DB_PREFIX_.'configuration` (`id_configuration`, `name`, `value`, `date_add`, `date_upd`) VALUES (NULL, "PS_UNIDENTIFIED_GROUP", "'.(int)$last_id.'", NOW(), NOW())');
else if (strtolower($standard) == 'guest')
$res &= Db::getInstance()->execute('INSERT INTO `'._DB_PREFIX_.'configuration` (`id_configuration`, `name`, `value`, `date_add`, `date_upd`) VALUES (NULL, "PS_GUEST_GROUP", "'.(int)$last_id.'", NOW(), NOW())');
else if (strtolower($standard) == 'test')
$res &= Db::getInstance()->execute('INSERT INTO `'._DB_PREFIX_.'configuration` (`id_configuration`, `name`, `value`, `date_add`, `date_upd`) VALUES (NULL, "PS_TEST", "'.(int)$last_id.'", NOW(), NOW())');
// Add shop association
$res &= Db::getInstance()->execute('INSERT INTO `'._DB_PREFIX_.'group_shop` (`id_group`, `id_shop`) (SELECT '.(int)$last_id.', `value` FROM `'._DB_PREFIX_.'configuration` WHERE `name` = \'PS_SHOP_DEFAULT\')');
// Copy categories associations from the group of id 1 (default group for both visitors and customers in version 1.4) to the new group
$res &= Db::getInstance()->execute('INSERT INTO `'._DB_PREFIX_.'category_group` (`id_category`, `id_group`) (SELECT `id_category`, '.(int)$last_id.' FROM `'._DB_PREFIX_.'category_group` WHERE `id_group` = 1)');
return $res;
}
| klebercode/prestashop | rm-install/upgrade/php/add_new_groups.php | PHP | mit | 3,162 |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/1999/REC-html401-19991224/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
<title>Bericht van {shop_name}</title>
<style> @media only screen and (max-width: 300px){
body {
width:218px !important;
margin:auto !important;
}
.table {width:195px !important;margin:auto !important;}
.logo, .titleblock, .linkbelow, .box, .footer, .space_footer{width:auto !important;display: block !important;}
span.title{font-size:20px !important;line-height: 23px !important}
span.subtitle{font-size: 14px !important;line-height: 18px !important;padding-top:10px !important;display:block !important;}
td.box p{font-size: 12px !important;font-weight: bold !important;}
.table-recap table, .table-recap thead, .table-recap tbody, .table-recap th, .table-recap td, .table-recap tr {
display: block !important;
}
.table-recap{width: 200px!important;}
.table-recap tr td, .conf_body td{text-align:center !important;}
.address{display: block !important;margin-bottom: 10px !important;}
.space_address{display: none !important;}
}
@media only screen and (min-width: 301px) and (max-width: 500px) {
body {width:308px!important;margin:auto!important;}
.table {width:285px!important;margin:auto!important;}
.logo, .titleblock, .linkbelow, .box, .footer, .space_footer{width:auto!important;display: block!important;}
.table-recap table, .table-recap thead, .table-recap tbody, .table-recap th, .table-recap td, .table-recap tr {
display: block !important;
}
.table-recap{width: 295px !important;}
.table-recap tr td, .conf_body td{text-align:center !important;}
}
@media only screen and (min-width: 501px) and (max-width: 768px) {
body {width:478px!important;margin:auto!important;}
.table {width:450px!important;margin:auto!important;}
.logo, .titleblock, .linkbelow, .box, .footer, .space_footer{width:auto!important;display: block!important;}
}
@media only screen and (max-device-width: 480px) {
body {width:308px!important;margin:auto!important;}
.table {width:285px;margin:auto!important;}
.logo, .titleblock, .linkbelow, .box, .footer, .space_footer{width:auto!important;display: block!important;}
.table-recap{width: 295px!important;}
.table-recap tr td, .conf_body td{text-align:center!important;}
.address{display: block !important;margin-bottom: 10px !important;}
.space_address{display: none !important;}
}
</style>
</head>
<body style="-webkit-text-size-adjust:none;background-color:#fff;width:650px;font-family:Open-sans, sans-serif;color:#555454;font-size:13px;line-height:18px;margin:auto">
<table class="table table-mail" style="width:100%;margin-top:10px;-moz-box-shadow:0 0 5px #afafaf;-webkit-box-shadow:0 0 5px #afafaf;-o-box-shadow:0 0 5px #afafaf;box-shadow:0 0 5px #afafaf;filter:progid:DXImageTransform.Microsoft.Shadow(color=#afafaf,Direction=134,Strength=5)">
<tr>
<td class="space" style="width:20px;padding:7px 0"> </td>
<td align="center" style="padding:7px 0">
<table class="table" bgcolor="#ffffff" style="width:100%">
<tr>
<td align="center" class="logo" style="border-bottom:4px solid #333333;padding:7px 0">
<a title="{shop_name}" href="{shop_url}" style="color:#337ff1">
<img src="{shop_logo}" alt="{shop_name}" />
</a>
</td>
</tr>
<tr>
<td align="center" class="titleblock" style="padding:7px 0">
<font size="2" face="Open-sans, sans-serif" color="#555454">
<span class="title" style="font-weight:500;font-size:28px;text-transform:uppercase;line-height:33px">Hallo {firstname} {lastname},</span>
</font>
</td>
</tr>
<tr>
<td class="space_footer" style="padding:0!important"> </td>
</tr>
<tr>
<td class="box" style="border:1px solid #D6D4D4;background-color:#f8f8f8;padding:7px 0">
<table class="table" style="width:100%">
<tr>
<td width="10" style="padding:7px 0"> </td>
<td style="padding:7px 0">
<font size="2" face="Open-sans, sans-serif" color="#555454">
<p data-html-only="1" style="border-bottom:1px solid #D6D4D4;margin:3px 0 7px;text-transform:uppercase;font-weight:500;font-size:18px;padding-bottom:10px">
Bestelling {order_name} - Betaling afhandelingsfout </p>
<span style="color:#777">
Er is een probleem met uw betaling voor <strong><span style="color:#333">{shop_name}</span></strong> bestelling met referentie <strong><span style="color:#333">{order_name}</span></strong>. Neemt u a.u.b. contact met ons op.<br/>
<strong><span style="color:#333">Uw bestelling zal pas verwerkt worden als dit probleem is opgelost.</span></strong>
</span>
</font>
</td>
<td width="10" style="padding:7px 0"> </td>
</tr>
</table>
</td>
</tr>
<tr>
<td class="space_footer" style="padding:0!important"> </td>
</tr>
<tr>
<td class="linkbelow" style="padding:7px 0">
<font size="2" face="Open-sans, sans-serif" color="#555454">
<span>
U kunt uw bestelling bekijken en de factuur downloaden vanuit de sectie <a href="{history_url}" style="color:#337ff1">"Bestelgeschiedenis"</a> op de klantportal, door te klikken op de link <a href="{my_account_url}" style="color:#337ff1">"Mijn account"</a> in onze winkel. </span>
</font>
</td>
</tr>
<tr>
<td class="linkbelow" style="padding:7px 0">
<font size="2" face="Open-sans, sans-serif" color="#555454">
<span>
Indien u hebt afgerekend zonder het aanmaken van een account, dan kunt u deze bestelling volgen via <a href="{guest_tracking_url}?id_order={order_name}" style="color:#337ff1">"deze link"</a>. </span>
</font>
</td>
</tr>
<tr>
<td class="space_footer" style="padding:0!important"> </td>
</tr>
<tr>
<td class="footer" style="border-top:4px solid #333333;padding:7px 0">
<span><a href="{shop_url}" style="color:#337ff1">{shop_name}</a> gebouwd met <a href="http://www.prestashop.com/" style="color:#337ff1">PrestaShop™</a></span>
</td>
</tr>
</table>
</td>
<td class="space" style="width:20px;padding:7px 0"> </td>
</tr>
</table>
</body>
</html> | victorespnt/v-eshop | prestashop/mails/nl/payment_error.html | HTML | mit | 6,442 |
For the Changelog, please see [Releases](https://github.com/phusion/baseimage-docker/releases) on GitHub
| remeeting/baseimage-docker | Changelog.md | Markdown | mit | 105 |
FROM electronuserland/builder:wine
RUN wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - && \
echo "deb http://dl.google.com/linux/chrome/deb/ stable main" > /etc/apt/sources.list.d/google.list && \
apt-get update -y && apt-get install -y --no-install-recommends xvfb google-chrome-stable libgconf-2-4 && \
# clean
apt-get clean && rm -rf /var/lib/apt/lists/* | mastergberry/electron-builder | docker/wine-chrome/Dockerfile | Dockerfile | mit | 401 |
import { platformBrowser } from '@angular/platform-browser';
import { enableProdMode } from '@angular/core';
import { AppModuleNgFactory } from '../../../temp/app/navigationbar/keyboardnavigation/app.module.ngfactory';
enableProdMode();
platformBrowser().bootstrapModuleFactory(AppModuleNgFactory); | luissancheza/sice | js/jqwidgets/demos/angular/app/navigationbar/keyboardnavigation/main.ts | TypeScript | mit | 306 |
/*
* Copyright 2009 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.javascript.rhino.Node;
import junit.framework.TestCase;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.List;
/**
* Tests for {@link CommandLineRunner}.
*
* @author nicksantos@google.com (Nick Santos)
*/
public class CommandLineRunnerTest extends TestCase {
private Compiler lastCompiler = null;
private CommandLineRunner lastCommandLineRunner = null;
private List<Integer> exitCodes = null;
private ByteArrayOutputStream outReader = null;
private ByteArrayOutputStream errReader = null;
// If set to true, uses comparison by string instead of by AST.
private boolean useStringComparison = false;
private ModulePattern useModules = ModulePattern.NONE;
private enum ModulePattern {
NONE,
CHAIN,
STAR
}
private List<String> args = Lists.newArrayList();
/** Externs for the test */
private final List<JSSourceFile> DEFAULT_EXTERNS = ImmutableList.of(
JSSourceFile.fromCode("externs",
"var arguments;"
+ "/**\n"
+ " * @constructor\n"
+ " * @param {...*} var_args\n"
+ " */\n"
+ "function Function(var_args) {}\n"
+ "/**\n"
+ " * @param {...*} var_args\n"
+ " * @return {*}\n"
+ " */\n"
+ "Function.prototype.call = function(var_args) {};"
+ "/**\n"
+ " * @constructor\n"
+ " * @param {...*} var_args\n"
+ " * @return {!Array}\n"
+ " */\n"
+ "function Array(var_args) {}"
+ "/**\n"
+ " * @param {*=} opt_begin\n"
+ " * @param {*=} opt_end\n"
+ " * @return {!Array}\n"
+ " * @this {Object}\n"
+ " */\n"
+ "Array.prototype.slice = function(opt_begin, opt_end) {};"
+ "/** @constructor */ function Window() {}\n"
+ "/** @type {string} */ Window.prototype.name;\n"
+ "/** @type {Window} */ var window;"
+ "/** @nosideeffects */ function noSideEffects() {}")
);
private List<JSSourceFile> externs;
@Override
public void setUp() throws Exception {
super.setUp();
externs = DEFAULT_EXTERNS;
lastCompiler = null;
outReader = new ByteArrayOutputStream();
errReader = new ByteArrayOutputStream();
useStringComparison = false;
useModules = ModulePattern.NONE;
args.clear();
exitCodes = Lists.newArrayList();
}
@Override
public void tearDown() throws Exception {
super.tearDown();
}
public void testTypeCheckingOffByDefault() {
test("function f(x) { return x; } f();",
"function f(a) { return a; } f();");
}
public void testTypeCheckingOnWithVerbose() {
args.add("--warning_level=VERBOSE");
test("function f(x) { return x; } f();", TypeCheck.WRONG_ARGUMENT_COUNT);
}
public void testTypeCheckOverride1() {
args.add("--warning_level=VERBOSE");
args.add("--jscomp_off=checkTypes");
testSame("var x = x || {}; x.f = function() {}; x.f(3);");
}
public void testTypeCheckOverride2() {
args.add("--warning_level=DEFAULT");
testSame("var x = x || {}; x.f = function() {}; x.f(3);");
args.add("--jscomp_warning=checkTypes");
test("var x = x || {}; x.f = function() {}; x.f(3);",
TypeCheck.WRONG_ARGUMENT_COUNT);
}
public void testCheckSymbolsOffForDefault() {
args.add("--warning_level=DEFAULT");
test("x = 3; var y; var y;", "x=3; var y;");
}
public void testCheckSymbolsOnForVerbose() {
args.add("--warning_level=VERBOSE");
test("x = 3;", VarCheck.UNDEFINED_VAR_ERROR);
test("var y; var y;", SyntacticScopeCreator.VAR_MULTIPLY_DECLARED_ERROR);
}
public void testCheckSymbolsOverrideForVerbose() {
args.add("--warning_level=VERBOSE");
args.add("--jscomp_off=undefinedVars");
testSame("x = 3;");
}
public void testCheckUndefinedProperties1() {
args.add("--warning_level=VERBOSE");
args.add("--jscomp_error=missingProperties");
test("var x = {}; var y = x.bar;", TypeCheck.INEXISTENT_PROPERTY);
}
public void testCheckUndefinedProperties2() {
args.add("--warning_level=VERBOSE");
args.add("--jscomp_off=missingProperties");
test("var x = {}; var y = x.bar;", CheckGlobalNames.UNDEFINED_NAME_WARNING);
}
public void testCheckUndefinedProperties3() {
args.add("--warning_level=VERBOSE");
test("function f() {var x = {}; var y = x.bar;}",
TypeCheck.INEXISTENT_PROPERTY);
}
public void testDuplicateParams() {
test("function (a, a) {}", RhinoErrorReporter.DUPLICATE_PARAM);
assertTrue(lastCompiler.hasHaltingErrors());
}
public void testDefineFlag() {
args.add("--define=FOO");
args.add("--define=\"BAR=5\"");
args.add("--D"); args.add("CCC");
args.add("-D"); args.add("DDD");
test("/** @define {boolean} */ var FOO = false;" +
"/** @define {number} */ var BAR = 3;" +
"/** @define {boolean} */ var CCC = false;" +
"/** @define {boolean} */ var DDD = false;",
"var FOO = true, BAR = 5, CCC = true, DDD = true;");
}
public void testDefineFlag2() {
args.add("--define=FOO='x\"'");
test("/** @define {string} */ var FOO = \"a\";",
"var FOO = \"x\\\"\";");
}
public void testDefineFlag3() {
args.add("--define=FOO=\"x'\"");
test("/** @define {string} */ var FOO = \"a\";",
"var FOO = \"x'\";");
}
public void testScriptStrictModeNoWarning() {
test("'use strict';", "");
test("'no use strict';", CheckSideEffects.USELESS_CODE_ERROR);
}
public void testFunctionStrictModeNoWarning() {
test("function f() {'use strict';}", "function f() {}");
test("function f() {'no use strict';}",
CheckSideEffects.USELESS_CODE_ERROR);
}
public void testQuietMode() {
args.add("--warning_level=DEFAULT");
test("/** @type { not a type name } */ var x;",
RhinoErrorReporter.PARSE_ERROR);
args.add("--warning_level=QUIET");
testSame("/** @type { not a type name } */ var x;");
}
public void testProcessClosurePrimitives() {
test("var goog = {}; goog.provide('goog.dom');",
"var goog = {}; goog.dom = {};");
args.add("--process_closure_primitives=false");
testSame("var goog = {}; goog.provide('goog.dom');");
}
//////////////////////////////////////////////////////////////////////////////
// Integration tests
public void testIssue70() {
test("function foo({}) {}", RhinoErrorReporter.PARSE_ERROR);
}
public void testIssue81() {
args.add("--compilation_level=ADVANCED_OPTIMIZATIONS");
useStringComparison = true;
test("eval('1'); var x = eval; x('2');",
"eval(\"1\");(0,eval)(\"2\");");
}
public void testIssue115() {
args.add("--compilation_level=SIMPLE_OPTIMIZATIONS");
args.add("--warning_level=VERBOSE");
test("function f() { " +
" var arguments = Array.prototype.slice.call(arguments, 0);" +
" return arguments[0]; " +
"}",
"function f() { " +
" arguments = Array.prototype.slice.call(arguments, 0);" +
" return arguments[0]; " +
"}");
}
public void testIssue297() {
args.add("--compilation_level=SIMPLE_OPTIMIZATIONS");
test("function f(p) {" +
" var x;" +
" return ((x=p.id) && (x=parseInt(x.substr(1))) && x>0);" +
"}",
"function f(b) {" +
" var a;" +
" return ((a=b.id) && (a=parseInt(a.substr(1))) && a>0);" +
"}");
}
public void testDebugFlag1() {
args.add("--compilation_level=SIMPLE_OPTIMIZATIONS");
args.add("--debug=false");
test("function foo(a) {}",
"function foo() {}");
}
public void testDebugFlag2() {
args.add("--compilation_level=SIMPLE_OPTIMIZATIONS");
args.add("--debug=true");
test("function foo(a) {alert(a)}",
"function foo($a$$) {alert($a$$)}");
}
public void testDebugFlag3() {
args.add("--compilation_level=ADVANCED_OPTIMIZATIONS");
args.add("--warning_level=QUIET");
args.add("--debug=false");
test("function Foo() {}" +
"Foo.x = 1;" +
"function f() {throw new Foo().x;} f();",
"throw (new function() {}).a;");
}
public void testDebugFlag4() {
args.add("--compilation_level=ADVANCED_OPTIMIZATIONS");
args.add("--warning_level=QUIET");
args.add("--debug=true");
test("function Foo() {}" +
"Foo.x = 1;" +
"function f() {throw new Foo().x;} f();",
"throw (new function Foo() {}).$x$;");
}
public void testBooleanFlag1() {
args.add("--compilation_level=SIMPLE_OPTIMIZATIONS");
args.add("--debug");
test("function foo(a) {alert(a)}",
"function foo($a$$) {alert($a$$)}");
}
public void testBooleanFlag2() {
args.add("--debug");
args.add("--compilation_level=SIMPLE_OPTIMIZATIONS");
test("function foo(a) {alert(a)}",
"function foo($a$$) {alert($a$$)}");
}
public void testHelpFlag() {
args.add("--help");
assertFalse(
createCommandLineRunner(
new String[] {"function f() {}"}).shouldRunCompiler());
}
public void testExternsLifting1() throws Exception{
String code = "/** @externs */ function f() {}";
test(new String[] {code},
new String[] {});
assertEquals(2, lastCompiler.getExternsForTesting().size());
CompilerInput extern = lastCompiler.getExternsForTesting().get(1);
assertNull(extern.getModule());
assertTrue(extern.isExtern());
assertEquals(code, extern.getCode());
assertEquals(1, lastCompiler.getInputsForTesting().size());
CompilerInput input = lastCompiler.getInputsForTesting().get(0);
assertNotNull(input.getModule());
assertFalse(input.isExtern());
assertEquals("", input.getCode());
}
public void testExternsLifting2() {
args.add("--warning_level=VERBOSE");
test(new String[] {"/** @externs */ function f() {}", "f(3);"},
new String[] {"f(3);"},
TypeCheck.WRONG_ARGUMENT_COUNT);
}
public void testSourceSortingOff() {
test(new String[] {
"goog.require('beer');",
"goog.provide('beer');"
}, ProcessClosurePrimitives.LATE_PROVIDE_ERROR);
}
public void testSourceSortingOn() {
args.add("--manage_closure_dependencies=true");
test(new String[] {
"goog.require('beer');",
"goog.provide('beer');"
},
new String[] {
"var beer = {};",
""
});
}
public void testSourceSortingCircularDeps1() {
args.add("--manage_closure_dependencies=true");
test(new String[] {
"goog.provide('gin'); goog.require('tonic'); var gin = {};",
"goog.provide('tonic'); goog.require('gin'); var tonic = {};",
"goog.require('gin'); goog.require('tonic');"
},
JSModule.CIRCULAR_DEPENDENCY_ERROR);
}
public void testSourceSortingCircularDeps2() {
args.add("--manage_closure_dependencies=true");
test(new String[] {
"goog.provide('roses.lime.juice');",
"goog.provide('gin'); goog.require('tonic'); var gin = {};",
"goog.provide('tonic'); goog.require('gin'); var tonic = {};",
"goog.require('gin'); goog.require('tonic');",
"goog.provide('gimlet');" +
" goog.require('gin'); goog.require('roses.lime.juice');"
},
JSModule.CIRCULAR_DEPENDENCY_ERROR);
}
public void testSourcePruningOn1() {
args.add("--manage_closure_dependencies=true");
test(new String[] {
"goog.require('beer');",
"goog.provide('beer');",
"goog.provide('scotch'); var x = 3;"
},
new String[] {
"var beer = {};",
""
});
}
public void testSourcePruningOn2() {
args.add("--closure_entry_point=guinness");
test(new String[] {
"goog.provide('guinness');\ngoog.require('beer');",
"goog.provide('beer');",
"goog.provide('scotch'); var x = 3;"
},
new String[] {
"var beer = {};",
"var guinness = {};"
});
}
public void testSourcePruningOn3() {
args.add("--closure_entry_point=scotch");
test(new String[] {
"goog.provide('guinness');\ngoog.require('beer');",
"goog.provide('beer');",
"goog.provide('scotch'); var x = 3;"
},
new String[] {
"var scotch = {}, x = 3;",
});
}
public void testSourcePruningOn4() {
args.add("--closure_entry_point=scotch");
args.add("--closure_entry_point=beer");
test(new String[] {
"goog.provide('guinness');\ngoog.require('beer');",
"goog.provide('beer');",
"goog.provide('scotch'); var x = 3;"
},
new String[] {
"var beer = {};",
"var scotch = {}, x = 3;",
});
}
public void testSourcePruningOn5() {
args.add("--closure_entry_point=shiraz");
test(new String[] {
"goog.provide('guinness');\ngoog.require('beer');",
"goog.provide('beer');",
"goog.provide('scotch'); var x = 3;"
},
Compiler.MISSING_ENTRY_ERROR);
}
public void testSourcePruningOn6() {
args.add("--closure_entry_point=scotch");
test(new String[] {
"goog.require('beer');",
"goog.provide('beer');",
"goog.provide('scotch'); var x = 3;"
},
new String[] {
"var beer = {};",
"",
"var scotch = {}, x = 3;",
});
}
public void testForwardDeclareDroppedTypes() {
args.add("--manage_closure_dependencies=true");
args.add("--warning_level=VERBOSE");
test(new String[] {
"goog.require('beer');",
"goog.provide('beer'); /** @param {Scotch} x */ function f(x) {}",
"goog.provide('Scotch'); var x = 3;"
},
new String[] {
"var beer = {}; function f() {}",
""
});
test(new String[] {
"goog.require('beer');",
"goog.provide('beer'); /** @param {Scotch} x */ function f(x) {}"
},
new String[] {
"var beer = {}; function f() {}",
""
},
RhinoErrorReporter.PARSE_ERROR);
}
public void testSourceMapExpansion1() {
args.add("--js_output_file");
args.add("/path/to/out.js");
args.add("--create_source_map=%outname%.map");
testSame("var x = 3;");
assertEquals("/path/to/out.js.map",
lastCommandLineRunner.expandSourceMapPath(
lastCompiler.getOptions(), null));
}
public void testSourceMapExpansion2() {
useModules = ModulePattern.CHAIN;
args.add("--create_source_map=%outname%.map");
args.add("--module_output_path_prefix=foo");
testSame(new String[] {"var x = 3;", "var y = 5;"});
assertEquals("foo.map",
lastCommandLineRunner.expandSourceMapPath(
lastCompiler.getOptions(), null));
}
public void testSourceMapExpansion3() {
useModules = ModulePattern.CHAIN;
args.add("--create_source_map=%outname%.map");
args.add("--module_output_path_prefix=foo_");
testSame(new String[] {"var x = 3;", "var y = 5;"});
assertEquals("foo_m0.js.map",
lastCommandLineRunner.expandSourceMapPath(
lastCompiler.getOptions(),
lastCompiler.getModuleGraph().getRootModule()));
}
public void testSourceMapFormat1() {
args.add("--js_output_file");
args.add("/path/to/out.js");
testSame("var x = 3;");
assertEquals(SourceMap.Format.LEGACY,
lastCompiler.getOptions().sourceMapFormat);
}
public void testCharSetExpansion() {
testSame("");
assertEquals("US-ASCII", lastCompiler.getOptions().outputCharset);
args.add("--charset=UTF-8");
testSame("");
assertEquals("UTF-8", lastCompiler.getOptions().outputCharset);
}
public void testChainModuleManifest() throws Exception {
useModules = ModulePattern.CHAIN;
testSame(new String[] {
"var x = 3;", "var y = 5;", "var z = 7;", "var a = 9;"});
StringBuilder builder = new StringBuilder();
lastCommandLineRunner.printModuleGraphManifestTo(
lastCompiler.getModuleGraph(), builder);
assertEquals(
"{m0}\n" +
"i0\n" +
"\n" +
"{m1:m0}\n" +
"i1\n" +
"\n" +
"{m2:m1}\n" +
"i2\n" +
"\n" +
"{m3:m2}\n" +
"i3\n",
builder.toString());
}
public void testStarModuleManifest() throws Exception {
useModules = ModulePattern.STAR;
testSame(new String[] {
"var x = 3;", "var y = 5;", "var z = 7;", "var a = 9;"});
StringBuilder builder = new StringBuilder();
lastCommandLineRunner.printModuleGraphManifestTo(
lastCompiler.getModuleGraph(), builder);
assertEquals(
"{m0}\n" +
"i0\n" +
"\n" +
"{m1:m0}\n" +
"i1\n" +
"\n" +
"{m2:m0}\n" +
"i2\n" +
"\n" +
"{m3:m0}\n" +
"i3\n",
builder.toString());
}
public void testVersionFlag() {
args.add("--version");
testSame("");
assertEquals(
0,
new String(errReader.toByteArray()).indexOf(
"Closure Compiler (http://code.google.com/closure/compiler)\n" +
"Version: "));
}
public void testPrintAstFlag() {
args.add("--print_ast=true");
testSame("");
assertEquals(
"digraph AST {\n" +
" node [color=lightblue2, style=filled];\n" +
" node0 [label=\"BLOCK\"];\n" +
" node1 [label=\"SCRIPT\"];\n" +
" node0 -> node1 [weight=1];\n" +
" node1 -> RETURN [label=\"UNCOND\", fontcolor=\"red\", weight=0.01, color=\"red\"];\n" +
" node0 -> RETURN [label=\"SYN_BLOCK\", fontcolor=\"red\", weight=0.01, color=\"red\"];\n" +
" node0 -> node1 [label=\"UNCOND\", fontcolor=\"red\", weight=0.01, color=\"red\"];\n" +
"}\n\n",
new String(outReader.toByteArray()));
}
public void testSyntheticExterns() {
externs = ImmutableList.of(
JSSourceFile.fromCode("externs", "myVar.property;"));
test("var theirVar = {}; var myVar = {}; var yourVar = {};",
VarCheck.UNDEFINED_EXTERN_VAR_ERROR);
args.add("--jscomp_off=externsValidation");
args.add("--warning_level=VERBOSE");
test("var theirVar = {}; var myVar = {}; var yourVar = {};",
"var theirVar={},myVar={},yourVar={};");
args.add("--jscomp_off=externsValidation");
args.add("--warning_level=VERBOSE");
test("var theirVar = {}; var myVar = {}; var myVar = {};",
SyntacticScopeCreator.VAR_MULTIPLY_DECLARED_ERROR);
}
/* Helper functions */
private void testSame(String original) {
testSame(new String[] { original });
}
private void testSame(String[] original) {
test(original, original);
}
private void test(String original, String compiled) {
test(new String[] { original }, new String[] { compiled });
}
/**
* Asserts that when compiling with the given compiler options,
* {@code original} is transformed into {@code compiled}.
*/
private void test(String[] original, String[] compiled) {
test(original, compiled, null);
}
/**
* Asserts that when compiling with the given compiler options,
* {@code original} is transformed into {@code compiled}.
* If {@code warning} is non-null, we will also check if the given
* warning type was emitted.
*/
private void test(String[] original, String[] compiled,
DiagnosticType warning) {
Compiler compiler = compile(original);
if (warning == null) {
assertEquals("Expected no warnings or errors\n" +
"Errors: \n" + Joiner.on("\n").join(compiler.getErrors()) +
"Warnings: \n" + Joiner.on("\n").join(compiler.getWarnings()),
0, compiler.getErrors().length + compiler.getWarnings().length);
} else {
assertEquals(1, compiler.getWarnings().length);
assertEquals(warning, compiler.getWarnings()[0].getType());
}
Node root = compiler.getRoot().getLastChild();
if (useStringComparison) {
assertEquals(Joiner.on("").join(compiled), compiler.toSource());
} else {
Node expectedRoot = parse(compiled);
String explanation = expectedRoot.checkTreeEquals(root);
assertNull("\nExpected: " + compiler.toSource(expectedRoot) +
"\nResult: " + compiler.toSource(root) +
"\n" + explanation, explanation);
}
}
/**
* Asserts that when compiling, there is an error or warning.
*/
private void test(String original, DiagnosticType warning) {
test(new String[] { original }, warning);
}
/**
* Asserts that when compiling, there is an error or warning.
*/
private void test(String[] original, DiagnosticType warning) {
Compiler compiler = compile(original);
assertEquals("Expected exactly one warning or error " +
"Errors: \n" + Joiner.on("\n").join(compiler.getErrors()) +
"Warnings: \n" + Joiner.on("\n").join(compiler.getWarnings()),
1, compiler.getErrors().length + compiler.getWarnings().length);
assertTrue(exitCodes.size() > 0);
int lastExitCode = exitCodes.get(exitCodes.size() - 1);
if (compiler.getErrors().length > 0) {
assertEquals(1, compiler.getErrors().length);
assertEquals(warning, compiler.getErrors()[0].getType());
assertEquals(1, lastExitCode);
} else {
assertEquals(1, compiler.getWarnings().length);
assertEquals(warning, compiler.getWarnings()[0].getType());
assertEquals(0, lastExitCode);
}
}
private CommandLineRunner createCommandLineRunner(String[] original) {
for (int i = 0; i < original.length; i++) {
args.add("--js");
args.add("/path/to/input" + i + ".js");
if (useModules == ModulePattern.CHAIN) {
args.add("--module");
args.add("mod" + i + ":1" + (i > 0 ? (":mod" + (i - 1)) : ""));
} else if (useModules == ModulePattern.STAR) {
args.add("--module");
args.add("mod" + i + ":1" + (i > 0 ? ":mod0" : ""));
}
}
String[] argStrings = args.toArray(new String[] {});
return new CommandLineRunner(
argStrings,
new PrintStream(outReader),
new PrintStream(errReader));
}
private Compiler compile(String[] original) {
CommandLineRunner runner = createCommandLineRunner(original);
assertTrue(runner.shouldRunCompiler());
Supplier<List<JSSourceFile>> inputsSupplier = null;
Supplier<List<JSModule>> modulesSupplier = null;
if (useModules == ModulePattern.NONE) {
List<JSSourceFile> inputs = Lists.newArrayList();
for (int i = 0; i < original.length; i++) {
inputs.add(JSSourceFile.fromCode("input" + i, original[i]));
}
inputsSupplier = Suppliers.ofInstance(inputs);
} else if (useModules == ModulePattern.STAR) {
modulesSupplier = Suppliers.<List<JSModule>>ofInstance(
Lists.<JSModule>newArrayList(
CompilerTestCase.createModuleStar(original)));
} else if (useModules == ModulePattern.CHAIN) {
modulesSupplier = Suppliers.<List<JSModule>>ofInstance(
Lists.<JSModule>newArrayList(
CompilerTestCase.createModuleChain(original)));
} else {
throw new IllegalArgumentException("Unknown module type: " + useModules);
}
runner.enableTestMode(
Suppliers.<List<JSSourceFile>>ofInstance(externs),
inputsSupplier,
modulesSupplier,
new Function<Integer, Boolean>() {
@Override
public Boolean apply(Integer code) {
return exitCodes.add(code);
}
});
runner.run();
lastCompiler = runner.getCompiler();
lastCommandLineRunner = runner;
return lastCompiler;
}
private Node parse(String[] original) {
String[] argStrings = args.toArray(new String[] {});
CommandLineRunner runner = new CommandLineRunner(argStrings);
Compiler compiler = runner.createCompiler();
List<JSSourceFile> inputs = Lists.newArrayList();
for (int i = 0; i < original.length; i++) {
inputs.add(JSSourceFile.fromCode("input" + i, original[i]));
}
compiler.init(externs, inputs, new CompilerOptions());
Node all = compiler.parseInputs();
Node n = all.getLastChild();
return n;
}
}
| 110035/kissy | tools/module-compiler/tests/com/google/javascript/jscomp/CommandLineRunnerTest.java | Java | mit | 25,263 |
/**
* Tools.js
*
* Released under LGPL License.
* Copyright (c) 1999-2017 Ephox Corp. All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
/**
* This class contains various utlity functions. These are also exposed
* directly on the tinymce namespace.
*
* @class tinymce.util.Tools
*/
define(
'tinymce.core.util.Tools',
[
'global!window',
'tinymce.core.Env',
'tinymce.core.util.Arr'
],
function (window, Env, Arr) {
/**
* Removes whitespace from the beginning and end of a string.
*
* @method trim
* @param {String} s String to remove whitespace from.
* @return {String} New string with removed whitespace.
*/
var whiteSpaceRegExp = /^\s*|\s*$/g;
var trim = function (str) {
return (str === null || str === undefined) ? '' : ("" + str).replace(whiteSpaceRegExp, '');
};
/**
* Checks if a object is of a specific type for example an array.
*
* @method is
* @param {Object} obj Object to check type of.
* @param {string} type Optional type to check for.
* @return {Boolean} true/false if the object is of the specified type.
*/
var is = function (obj, type) {
if (!type) {
return obj !== undefined;
}
if (type == 'array' && Arr.isArray(obj)) {
return true;
}
return typeof obj == type;
};
/**
* Makes a name/object map out of an array with names.
*
* @method makeMap
* @param {Array/String} items Items to make map out of.
* @param {String} delim Optional delimiter to split string by.
* @param {Object} map Optional map to add items to.
* @return {Object} Name/value map of items.
*/
var makeMap = function (items, delim, map) {
var i;
items = items || [];
delim = delim || ',';
if (typeof items == "string") {
items = items.split(delim);
}
map = map || {};
i = items.length;
while (i--) {
map[items[i]] = {};
}
return map;
};
/**
* JavaScript does not protect hasOwnProperty method, so it is possible to overwrite it. This is
* object independent version.
*
* @param {Object} obj
* @param {String} prop
* @returns {Boolean}
*/
var hasOwnProperty = function (obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
};
/**
* Creates a class, subclass or static singleton.
* More details on this method can be found in the Wiki.
*
* @method create
* @param {String} s Class name, inheritance and prefix.
* @param {Object} p Collection of methods to add to the class.
* @param {Object} root Optional root object defaults to the global window object.
* @example
* // Creates a basic class
* tinymce.create('tinymce.somepackage.SomeClass', {
* SomeClass: function() {
* // Class constructor
* },
*
* method: function() {
* // Some method
* }
* });
*
* // Creates a basic subclass class
* tinymce.create('tinymce.somepackage.SomeSubClass:tinymce.somepackage.SomeClass', {
* SomeSubClass: function() {
* // Class constructor
* this.parent(); // Call parent constructor
* },
*
* method: function() {
* // Some method
* this.parent(); // Call parent method
* },
*
* 'static': {
* staticMethod: function() {
* // Static method
* }
* }
* });
*
* // Creates a singleton/static class
* tinymce.create('static tinymce.somepackage.SomeSingletonClass', {
* method: function() {
* // Some method
* }
* });
*/
var create = function (s, p, root) {
var self = this, sp, ns, cn, scn, c, de = 0;
// Parse : <prefix> <class>:<super class>
s = /^((static) )?([\w.]+)(:([\w.]+))?/.exec(s);
cn = s[3].match(/(^|\.)(\w+)$/i)[2]; // Class name
// Create namespace for new class
ns = self.createNS(s[3].replace(/\.\w+$/, ''), root);
// Class already exists
if (ns[cn]) {
return;
}
// Make pure static class
if (s[2] == 'static') {
ns[cn] = p;
if (this.onCreate) {
this.onCreate(s[2], s[3], ns[cn]);
}
return;
}
// Create default constructor
if (!p[cn]) {
p[cn] = function () { };
de = 1;
}
// Add constructor and methods
ns[cn] = p[cn];
self.extend(ns[cn].prototype, p);
// Extend
if (s[5]) {
sp = self.resolve(s[5]).prototype;
scn = s[5].match(/\.(\w+)$/i)[1]; // Class name
// Extend constructor
c = ns[cn];
if (de) {
// Add passthrough constructor
ns[cn] = function () {
return sp[scn].apply(this, arguments);
};
} else {
// Add inherit constructor
ns[cn] = function () {
this.parent = sp[scn];
return c.apply(this, arguments);
};
}
ns[cn].prototype[cn] = ns[cn];
// Add super methods
self.each(sp, function (f, n) {
ns[cn].prototype[n] = sp[n];
});
// Add overridden methods
self.each(p, function (f, n) {
// Extend methods if needed
if (sp[n]) {
ns[cn].prototype[n] = function () {
this.parent = sp[n];
return f.apply(this, arguments);
};
} else {
if (n != cn) {
ns[cn].prototype[n] = f;
}
}
});
}
// Add static methods
/*jshint sub:true*/
/*eslint dot-notation:0*/
self.each(p['static'], function (f, n) {
ns[cn][n] = f;
});
};
var extend = function (obj, ext) {
var i, l, name, args = arguments, value;
for (i = 1, l = args.length; i < l; i++) {
ext = args[i];
for (name in ext) {
if (ext.hasOwnProperty(name)) {
value = ext[name];
if (value !== undefined) {
obj[name] = value;
}
}
}
}
return obj;
};
/**
* Executed the specified function for each item in a object tree.
*
* @method walk
* @param {Object} o Object tree to walk though.
* @param {function} f Function to call for each item.
* @param {String} n Optional name of collection inside the objects to walk for example childNodes.
* @param {String} s Optional scope to execute the function in.
*/
var walk = function (o, f, n, s) {
s = s || this;
if (o) {
if (n) {
o = o[n];
}
Arr.each(o, function (o, i) {
if (f.call(s, o, i, n) === false) {
return false;
}
walk(o, f, n, s);
});
}
};
/**
* Creates a namespace on a specific object.
*
* @method createNS
* @param {String} n Namespace to create for example a.b.c.d.
* @param {Object} o Optional object to add namespace to, defaults to window.
* @return {Object} New namespace object the last item in path.
* @example
* // Create some namespace
* tinymce.createNS('tinymce.somepackage.subpackage');
*
* // Add a singleton
* var tinymce.somepackage.subpackage.SomeSingleton = {
* method: function() {
* // Some method
* }
* };
*/
var createNS = function (n, o) {
var i, v;
o = o || window;
n = n.split('.');
for (i = 0; i < n.length; i++) {
v = n[i];
if (!o[v]) {
o[v] = {};
}
o = o[v];
}
return o;
};
/**
* Resolves a string and returns the object from a specific structure.
*
* @method resolve
* @param {String} n Path to resolve for example a.b.c.d.
* @param {Object} o Optional object to search though, defaults to window.
* @return {Object} Last object in path or null if it couldn't be resolved.
* @example
* // Resolve a path into an object reference
* var obj = tinymce.resolve('a.b.c.d');
*/
var resolve = function (n, o) {
var i, l;
o = o || window;
n = n.split('.');
for (i = 0, l = n.length; i < l; i++) {
o = o[n[i]];
if (!o) {
break;
}
}
return o;
};
/**
* Splits a string but removes the whitespace before and after each value.
*
* @method explode
* @param {string} s String to split.
* @param {string} d Delimiter to split by.
* @example
* // Split a string into an array with a,b,c
* var arr = tinymce.explode('a, b, c');
*/
var explode = function (s, d) {
if (!s || is(s, 'array')) {
return s;
}
return Arr.map(s.split(d || ','), trim);
};
var _addCacheSuffix = function (url) {
var cacheSuffix = Env.cacheSuffix;
if (cacheSuffix) {
url += (url.indexOf('?') === -1 ? '?' : '&') + cacheSuffix;
}
return url;
};
return {
trim: trim,
/**
* Returns true/false if the object is an array or not.
*
* @method isArray
* @param {Object} obj Object to check.
* @return {boolean} true/false state if the object is an array or not.
*/
isArray: Arr.isArray,
is: is,
/**
* Converts the specified object into a real JavaScript array.
*
* @method toArray
* @param {Object} obj Object to convert into array.
* @return {Array} Array object based in input.
*/
toArray: Arr.toArray,
makeMap: makeMap,
/**
* Performs an iteration of all items in a collection such as an object or array. This method will execure the
* callback function for each item in the collection, if the callback returns false the iteration will terminate.
* The callback has the following format: cb(value, key_or_index).
*
* @method each
* @param {Object} o Collection to iterate.
* @param {function} cb Callback function to execute for each item.
* @param {Object} s Optional scope to execute the callback in.
* @example
* // Iterate an array
* tinymce.each([1,2,3], function(v, i) {
* console.debug("Value: " + v + ", Index: " + i);
* });
*
* // Iterate an object
* tinymce.each({a: 1, b: 2, c: 3], function(v, k) {
* console.debug("Value: " + v + ", Key: " + k);
* });
*/
each: Arr.each,
/**
* Creates a new array by the return value of each iteration function call. This enables you to convert
* one array list into another.
*
* @method map
* @param {Array} array Array of items to iterate.
* @param {function} callback Function to call for each item. It's return value will be the new value.
* @return {Array} Array with new values based on function return values.
*/
map: Arr.map,
/**
* Filters out items from the input array by calling the specified function for each item.
* If the function returns false the item will be excluded if it returns true it will be included.
*
* @method grep
* @param {Array} a Array of items to loop though.
* @param {function} f Function to call for each item. Include/exclude depends on it's return value.
* @return {Array} New array with values imported and filtered based in input.
* @example
* // Filter out some items, this will return an array with 4 and 5
* var items = tinymce.grep([1,2,3,4,5], function(v) {return v > 3;});
*/
grep: Arr.filter,
/**
* Returns an index of the item or -1 if item is not present in the array.
*
* @method inArray
* @param {any} item Item to search for.
* @param {Array} arr Array to search in.
* @return {Number} index of the item or -1 if item was not found.
*/
inArray: Arr.indexOf,
hasOwn: hasOwnProperty,
extend: extend,
create: create,
walk: walk,
createNS: createNS,
resolve: resolve,
explode: explode,
_addCacheSuffix: _addCacheSuffix
};
}
); | pvskand/addictionRemoval | tinymce/src/core/src/main/js/util/Tools.js | JavaScript | mit | 12,608 |
<div id="main-container" class="main-container jqx-rc-all">
<div style="float: left">
<div id="catalogue" class="catalogue jqx-rc-all">
</div>
</div>
<div id="options" class="options jqx-rc-all">
<div id="options-container" class="options-container">
<div class="label">
Price
</div>
<div class="options-value">
<div style="float: left" id="priceMin">
</div>
<div style="float: right" id="priceMax">
</div>
</div>
<br />
<jqxSlider filter="price" #priceSlider
(onChange)="priceSliderChange($event)"
[showButtons]="true"
[min]="500" [max]="4000" [step]="350"
[values]="[500, 4000]"
[mode]="'fixed'" [rangeSlider]="true"
[ticksFrequency]="350"
[height]="30" [width]="180">
</jqxSlider>
<div class="label">
Screen Size
</div>
<div class="options-value">
<div style="float: left" id="displayMin">
</div>
<div style="float: right" id="displayMax">
</div>
</div>
<br />
<jqxSlider filter="display" #displaySlider
(onChange)="displaySliderChange($event)"
[showButtons]="true"
[min]="9" [max]="19" [step]="1"
[values]="[9, 19]"
[mode]="'fixed'" [rangeSlider]="true"
[ticksFrequency]="1"
[height]="30" [width]="180">
</jqxSlider>
<div class="label">
RAM
</div>
<div class="options-value">
<div style="float: left" id="ramMin">
</div>
<div style="float: right" id="ramMax">
</div>
</div>
<br />
<jqxSlider filter="ram" #ramSlider
(onChange)="ramSliderChange($event)"
[showButtons]="true"
[min]="2" [max]="12" [step]="1"
[values]="[2, 12]"
[mode]="'fixed'" [rangeSlider]="true"
[ticksFrequency]="1"
[height]="30" [width]="180">
</jqxSlider>
<div class="label">
HDD
</div>
<div class="options-value">
<div style="float: left" id="hddMin">
</div>
<div style="float: right" id="hddMax">
</div>
</div>
<br />
<jqxSlider filter="hdd" #hddSlider
(onChange)="hddSliderChange($event)"
[showButtons]="true"
[min]="150" [max]="1500" [step]="135"
[values]="[150, 1500]"
[mode]="'fixed'" [rangeSlider]="true"
[ticksFrequency]="135"
[height]="30" [width]="180">
</jqxSlider>
<jqxButton [width]="100" #resetButton (onClick)="clickResetButton()" class="resetButton">Reset filters</jqxButton>
</div>
</div>
<div style="clear: both;">
</div>
</div> | luissancheza/sice | js/jqwidgets/demos/angular/app/slider/rangeslider/app.component.html | HTML | mit | 3,029 |
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
'use strict';
const glob = require('glob');
const path = require('path');
/**
* Find the main file for the C# project
*
* @param {String} folder Name of the folder where to seek
* @return {String}
*/
module.exports = function findMainFile(folder) {
let mainFilePath = glob.sync('MainReactNativeHost.cs', {
cwd: folder,
ignore: ['node_modules/**', '**/build/**', 'Examples/**', 'examples/**'],
});
if (mainFilePath.length === 0) {
mainFilePath = glob.sync('MainPage.cs', {
cwd: folder,
ignore: ['node_modules/**', '**/build/**', 'Examples/**', 'examples/**'],
});
}
return mainFilePath && mainFilePath.length > 0 ? path.join(folder, mainFilePath[0]) : null;
};
| bluejeans/react-native-windows | local-cli/core/windows/findMainFile.js | JavaScript | mit | 811 |
-- Copyright 2013 by Till Tantau
--
-- This file may be distributed an/or modified
--
-- 1. under the LaTeX Project Public License and/or
-- 2. under the GNU Public License
--
-- See the file doc/generic/pgf/licenses/LICENSE for more information
-- @release $Header: /cvsroot/pgf/pgf/generic/pgf/graphdrawing/lua/pgf/gd/doc/ogdf/layered/SplitHeuristic.lua,v 1.1 2013/03/07 18:17:14 tantau Exp $
local key = require 'pgf.gd.doc'.key
local documentation = require 'pgf.gd.doc'.documentation
local summary = require 'pgf.gd.doc'.summary
local example = require 'pgf.gd.doc'.example
--------------------------------------------------------------------
key "SplitHeuristic"
summary "The split heuristic for 2-layer crossing minimization."
--------------------------------------------------------------------
| milos-korenciak/heroku-buildpack-tex | buildpack/texmf-dist/tex/generic/pgf/graphdrawing/lua/pgf/gd/doc/ogdf/layered/SplitHeuristic.lua | Lua | mit | 848 |
<!doctype html>
<html>
<title>npm-help</title>
<meta http-equiv="content-type" value="text/html;utf-8">
<link rel="stylesheet" type="text/css" href="../../static/style.css">
<link rel="canonical" href="https://www.npmjs.org/doc/cli/npm-help.html">
<script async=true src="../../static/toc.js"></script>
<body>
<div id="wrapper">
<h1><a href="../cli/npm-help.html">npm-help</a></h1> <p>Get help on npm</p>
<h2 id="synopsis">SYNOPSIS</h2>
<pre><code>npm help <topic>
npm help some search terms
</code></pre><h2 id="description">DESCRIPTION</h2>
<p>If supplied a topic, then show the appropriate documentation page.</p>
<p>If the topic does not exist, or if multiple terms are provided, then run
the <code>help-search</code> command to find a match. Note that, if <code>help-search</code>
finds a single subject, then it will run <code>help</code> on that topic, so unique
matches are equivalent to specifying a topic name.</p>
<h2 id="configuration">CONFIGURATION</h2>
<h3 id="viewer">viewer</h3>
<ul>
<li>Default: "man" on Posix, "browser" on Windows</li>
<li>Type: path</li>
</ul>
<p>The program to use to view help content.</p>
<p>Set to <code>"browser"</code> to view html help content in the default web browser.</p>
<h2 id="see-also">SEE ALSO</h2>
<ul>
<li><a href="../cli/npm.html">npm(1)</a></li>
<li><a href="../../doc/README.html">README</a></li>
<li><a href="../misc/npm-faq.html">npm-faq(7)</a></li>
<li><a href="../files/npm-folders.html">npm-folders(5)</a></li>
<li><a href="../cli/npm-config.html">npm-config(1)</a></li>
<li><a href="../misc/npm-config.html">npm-config(7)</a></li>
<li><a href="../files/npmrc.html">npmrc(5)</a></li>
<li><a href="../files/package.json.html">package.json(5)</a></li>
<li><a href="../cli/npm-help-search.html">npm-help-search(1)</a></li>
<li><a href="../misc/npm-index.html">npm-index(7)</a></li>
</ul>
</div>
<table border=0 cellspacing=0 cellpadding=0 id=npmlogo>
<tr><td style="width:180px;height:10px;background:rgb(237,127,127)" colspan=18> </td></tr>
<tr><td rowspan=4 style="width:10px;height:10px;background:rgb(237,127,127)"> </td><td style="width:40px;height:10px;background:#fff" colspan=4> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=4> </td><td style="width:40px;height:10px;background:#fff" colspan=4> </td><td rowspan=4 style="width:10px;height:10px;background:rgb(237,127,127)"> </td><td colspan=6 style="width:60px;height:10px;background:#fff"> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=4> </td></tr>
<tr><td colspan=2 style="width:20px;height:30px;background:#fff" rowspan=3> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=3> </td><td style="width:10px;height:10px;background:#fff" rowspan=3> </td><td style="width:20px;height:10px;background:#fff" rowspan=4 colspan=2> </td><td style="width:10px;height:20px;background:rgb(237,127,127)" rowspan=2> </td><td style="width:10px;height:10px;background:#fff" rowspan=3> </td><td style="width:20px;height:10px;background:#fff" rowspan=3 colspan=2> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=3> </td><td style="width:10px;height:10px;background:#fff" rowspan=3> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=3> </td></tr>
<tr><td style="width:10px;height:10px;background:#fff" rowspan=2> </td></tr>
<tr><td style="width:10px;height:10px;background:#fff"> </td></tr>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
<p id="footer">npm-help — npm@2.15.9</p>
| usmanantharikta/workshop_bekup | node-v4.6.1-linux-x64/lib/node_modules/npm/html/doc/cli/npm-help.html | HTML | mit | 4,062 |
<a href="https://travis-ci.org/kataras/go-fs"><img src="https://img.shields.io/travis/kataras/go-fs.svg?style=flat-square" alt="Build Status"></a>
<a href="https://github.com/kataras/go-fs/blob/master/LICENSE"><img src="https://img.shields.io/badge/%20license-MIT%20%20License%20-E91E63.svg?style=flat-square" alt="License"></a>
<a href="https://github.com/kataras/go-fs/releases"><img src="https://img.shields.io/badge/%20release%20-%20v0.0.5-blue.svg?style=flat-square" alt="Releases"></a>
<a href="#docs"><img src="https://img.shields.io/badge/%20docs-reference-5272B4.svg?style=flat-square" alt="Read me docs"></a>
<a href="https://kataras.rocket.chat/channel/go-fs"><img src="https://img.shields.io/badge/%20community-chat-00BCD4.svg?style=flat-square" alt="Build Status"></a>
<a href="https://golang.org"><img src="https://img.shields.io/badge/powered_by-Go-3362c2.svg?style=flat-square" alt="Built with GoLang"></a>
<a href="#"><img src="https://img.shields.io/badge/platform-Any--OS-yellow.svg?style=flat-square" alt="Platforms"></a>
The package go-fs provides some common utilities which GoLang developers use when working with files, either system files or web files.
Installation
------------
The only requirement is the [Go Programming Language](https://golang.org/dl).
```bash
$ go get -u github.com/kataras/go-fs
```
Docs
------------
### Local file system helpers
```go
// DirectoryExists returns true if a directory(or file) exists, otherwise false
DirectoryExists(dir string) bool
// GetHomePath returns the user's $HOME directory
GetHomePath() string
// GetParentDir returns the parent directory of the passed targetDirectory
GetParentDir(targetDirectory string) string
// RemoveFile removes a file or a directory
RemoveFile(filePath string) error
// RenameDir renames (moves) oldpath to newpath.
// If newpath already exists, Rename replaces it.
// OS-specific restrictions may apply when oldpath and newpath are in different directories.
// If there is an error, it will be of type *LinkError.
//
// It's a copy of os.Rename
RenameDir(oldPath string, newPath string) error
// CopyFile accepts full path of the source and full path of destination, if file exists it's overrides it
// this function doesn't checks for permissions and all that, it returns an error
CopyFile(source string, destination string) error
// CopyDir recursively copies a directory tree, attempting to preserve permissions.
// Source directory must exist.
CopyDir(source string, dest string) error
// Unzip extracts a zipped file to the target location
// returns the path of the created folder (if any) and an error (if any)
Unzip(archive string, target string) (string, error)
// TypeByExtension returns the MIME type associated with the file extension ext.
// The extension ext should begin with a leading dot, as in ".html".
// When ext has no associated type, TypeByExtension returns "".
//
// Extensions are looked up first case-sensitively, then case-insensitively.
//
// The built-in table is small but on unix it is augmented by the local
// system's mime.types file(s) if available under one or more of these
// names:
//
// /etc/mime.types
// /etc/apache2/mime.types
// /etc/apache/mime.types
//
// On Windows, MIME types are extracted from the registry.
//
// Text types have the charset parameter set to "utf-8" by default.
TypeByExtension(fullfilename string) string
```
### Net/http handlers
```go
// FaviconHandler receives the favicon path and serves the favicon
FaviconHandler(favPath string) http.Handler
// StaticContentHandler returns the net/http.Handler interface to handle raw binary data,
// normally the data parameter was read by custom file reader or by variable
StaticContentHandler(data []byte, contentType string) http.Handler
// StaticFileHandler serves a static file such as css,js, favicons, static images
// it stores the file contents to the memory, doesn't supports seek because we read all-in-one the file, but seek is supported by net/http.ServeContent
StaticFileHandler(filename string) http.Handler
// SendStaticFileHandler sends a file for force-download to the client
// it stores the file contents to the memory, doesn't supports seek because we read all-in-one the file, but seek is supported by net/http.ServeContent
SendStaticFileHandler(filename string) http.Handler
// DirHandler serves a directory as web resource
// accepts a system Directory (string),
// a string which will be stripped off if not empty and
// Note 1: this is a dynamic dir handler, means that if a new file is added to the folder it will be served
// Note 2: it doesn't cache the system files, use it with your own risk, otherwise you can use the http.FileServer method, which is different of what I'm trying to do here.
// example:
// staticHandler := http.FileServer(http.Dir("static"))
// http.Handle("/static/", http.StripPrefix("/static/", staticHandler))
// converted to ->
// http.Handle("/static/", fs.DirHandler("./static", "/static/"))
DirHandler(dir string, strippedPrefix string) http.Handler
```
Read the [http_test.go](https://github.com/kataras/go-fs/blob/master/http_test.go) for more.
### Gzip Writer
Writes gzip compressed content to an underline io.Writer. It uses sync.Pool to reduce memory allocations.
**Better performance** through klauspost/compress package which provides us a gzip.Writer which is faster than Go standard's gzip package's writer.
```go
// NewGzipPool returns a new gzip writer pool, ready to use
NewGzipPool(Level int) *GzipPool
// DefaultGzipPool returns a new writer pool with Compressor's level setted to DefaultCompression
DefaultGzipPool() *GzipPool
// AcquireGzipWriter prepares a gzip writer and returns it
//
// see ReleaseGzipWriter
AcquireGzipWriter(w io.Writer) *gzip.Writer
// ReleaseGzipWriter called when flush/close and put the gzip writer back to the pool
//
// see AcquireGzipWriter
ReleaseGzipWriter(gzipWriter *gzip.Writer)
// WriteGzip writes a compressed form of p to the underlying io.Writer. The
// compressed bytes are not necessarily flushed until the Writer is closed
WriteGzip(w io.Writer, b []byte) (int, error)
```
- `AcquireGzipWriter` get a gzip writer, create new if no free writer available from inside the pool (sync.Pool).
- `ReleaseGzipWriter` releases puts a gzip writer to the pool (sync.Pool).
- `WriteGzip` gets a gzip writer, writes a compressed form of p to the underlying io.Writer. The
compressed bytes are not necessarily flushed until the Writer is closed. Finally it Releases the particular gzip writer.
> if these called from package level then the default gzip writer's pool is used to get/put and write
- `NewGzipPool` receives a compression level and returns a new gzip writer pool
- `DefaultGzipPool` returns a new gzip writer pool with DefaultCompression as the Compressor's Level
> New & Default are optional, use them to create more than one sync.Pool, if you expect thousands of writers working together
Using default pool's writer to compress & write content
```go
import "github.com/kataras/go-fs"
var writer io.Writer
// ... using default package's Pool to get a gzip writer
n, err := fs.WriteGzip(writer, []byte("Compressed data and content here"))
```
Using default Pool to get a gzip writer, compress & write content and finally release manually the gzip writer to the default Pool
```go
import "github.com/kataras/go-fs"
var writer io.Writer
// ... using default writer's pool to get a gzip.Writer
mygzipWriter := fs.AcquireGzipWriter(writer) // get a gzip.Writer from the default gzipwriter Pool
n, err := mygzipWriter.WriteGzip([]byte("Compressed data and content here"))
gzipwriter.ReleaseGzipWriter(mygzipWriter) // release this gzip.Writer to the default gzipwriter package's gzip writer Pool (sync.Pool)
```
Create and use a totally new gzip writer Pool
```go
import "github.com/kataras/go-fs"
var writer io.Writer
var gzipWriterPool = fs.NewGzipPool(fs.DefaultCompression)
// ...
n, err := gzipWriterPool.WriteGzip(writer, []byte("Compressed data and content here"))
```
Get a gzip writer Pool with the default options(compressor's Level)
```go
import "github.com/kataras/go-fs"
var writer io.Writer
var gzipWriterPool = fs.DefaultGzipPool() // returns a new default gzip writer pool
// ...
n, err := gzipWriterPool.WriteGzip(writer, []byte("Compressed data and content here"))
```
Acquire, Write and Release from a new(`.NewGzipPool/.DefaultGzipPool`) gzip writer Pool
```go
import "github.com/kataras/go-fs"
var writer io.Writer
var gzipWriterPool = fs.DefaultGzipPool() // returns a new default gzip writer pool
mygzipWriter := gzipWriterPool.AcquireGzipWriter(writer) // get a gzip.Writer from the new gzipWriterPool
n, err := mygzipWriter.WriteGzip([]byte("Compressed data and content here"))
gzipWriterPool.ReleaseGzipWriter(mygzipWriter) // release this gzip.Writer to the gzipWriterPool (sync.Pool)
```
### Working with remote zip files
```go
// DownloadZip downloads a zip file returns the downloaded filename and an error.
DownloadZip(zipURL string, newDir string, showOutputIndication bool) (string, error)
// Install is just the flow of: downloadZip -> unzip -> removeFile(zippedFile)
// accepts 3 parameters
//
// first parameter is the remote url file zip
// second parameter is the target directory
// third paremeter is a boolean which you can set to true to print out the progress
// returns a string(installedDirectory) and an error
//
// (string) installedDirectory is the directory which the zip file had, this is the real installation path
// the installedDirectory is not empty when the installation is succed, the targetDirectory is not already exists and no error happens
// the installedDirectory is empty when the installation is already done by previous time or an error happens
Install(remoteFileZip string, targetDirectory string, showOutputIndication bool) (string, error)
```
> Install = DownloadZip -> Unzip to the destination folder, remove the downloaded .zip, copy the inside extracted folder to the destination
Install many remote files(URI) to a single destination folder via installer instance
```go
type Installer struct {
// InstallDir is the directory which all zipped downloads will be extracted
// defaults to $HOME path
InstallDir string
// Indicator when it's true it shows an indicator about the installation process
// defaults to false
Indicator bool
// RemoteFiles is the list of the files which should be downloaded when Install() called
RemoteFiles []string
}
// Add adds a remote file(*.zip) to the list for download
Add(...string)
// Install installs all RemoteFiles, when this function called then the RemoteFiles are being resseted
// returns all installed paths and an error (if any)
// it continues on errors and returns them when the operation completed
Install() ([]string, error)
```
**Usage**
```go
package main
import "github.com/kataras/go-fs"
var testInstalledDir = fs.GetHomePath() + fs.PathSeparator + "mydir" + fs.PathSeparator
// remote file zip | expected output(installed) directory
var filesToInstall = map[string]string{
"https://github.com/kataras/q/archive/master.zip": testInstalledDir + "q-master",
"https://github.com/kataras/iris/archive/master.zip": testInstalledDir + "iris-master",
"https://github.com/kataras/go-errors/archive/master.zip": testInstalledDir + "go-errors-master",
"https://github.com/kataras/go-gzipwriter/archive/master.zip": testInstalledDir + "go-gzipwriter-master",
"https://github.com/kataras/go-events/archive/master.zip": testInstalledDir + "go-events-master",
}
func main() {
myInstaller := fs.NewInstaller(testInstalledDir)
for remoteURI := range filesToInstall {
myInstaller.Add(remoteURI)
}
installedDirs, err := myInstaller.Install()
if err != nil {
panic(err)
}
for _, installedDir := range installedDirs {
println("New folder created: " + installedDir)
}
}
```
When you want to install different zip files to different destination directories.
**Usage**
```go
package main
import "github.com/kataras/go-fs"
var testInstalledDir = fs.GetHomePath() + fs.PathSeparator + "mydir" + fs.PathSeparator
// remote file zip | expected output(installed) directory
var filesToInstall = map[string]string{
"https://github.com/kataras/q/archive/master.zip": testInstalledDir + "q-master",
"https://github.com/kataras/iris/archive/master.zip": testInstalledDir + "iris-master",
"https://github.com/kataras/go-errors/archive/master.zip": testInstalledDir + "go-errors-master",
"https://github.com/kataras/go-gzipwriter/archive/master.zip": testInstalledDir + "go-gzipwriter-master",
"https://github.com/kataras/go-events/archive/master.zip": testInstalledDir + "go-events-master",
}
func main(){
for remoteURI, expectedInstalledDir := range filesToInstall {
installedDir, err := fs.Install(remoteURI, testInstalledDir, false)
if err != nil {
panic(err)
}
println("Installed: "+installedDir)
}
}
```
Read the [installer_test.go](https://github.com/kataras/go-fs/blob/master/installer_test.go) for more.
You do not need any other special explanations for this package, just navigate to the [godoc](https://godoc.org/github.com/kataras/go-fs) or the [source](https://github.com/kataras/go-fs/blob/master/http_test.go) [code](https://github.com/kataras/go-fs/blob/master/installer_test.go).
FAQ
------------
Explore [these questions](https://github.com/kataras/go-fs/issues?go-fs=label%3Aquestion) or navigate to the [community chat][Chat].
Versioning
------------
Current: **v0.0.5**
People
------------
The author of go-fs is [@kataras](https://github.com/kataras).
If you're **willing to donate**, feel free to send **any** amount through paypal
[](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=kataras2006%40hotmail%2ecom&lc=GR&item_name=Iris%20web%20framework&item_number=iriswebframeworkdonationid2016¤cy_code=EUR&bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHosted)
Contributing
------------
If you are interested in contributing to the go-fs project, please make a PR.
License
------------
This project is licensed under the MIT License.
License can be found [here](LICENSE).
[Travis Widget]: https://img.shields.io/travis/kataras/go-fs.svg?style=flat-square
[Travis]: http://travis-ci.org/kataras/go-fs
[License Widget]: https://img.shields.io/badge/license-MIT%20%20License%20-E91E63.svg?style=flat-square
[License]: https://github.com/kataras/go-fs/blob/master/LICENSE
[Release Widget]: https://img.shields.io/badge/release-v0.0.5-blue.svg?style=flat-square
[Release]: https://github.com/kataras/go-fs/releases
[Chat Widget]: https://img.shields.io/badge/community-chat-00BCD4.svg?style=flat-square
[Chat]: https://kataras.rocket.chat/channel/go-fs
[ChatMain]: https://kataras.rocket.chat/channel/go-fs
[ChatAlternative]: https://gitter.im/kataras/go-fs
[Report Widget]: https://img.shields.io/badge/report%20card-A%2B-F44336.svg?style=flat-square
[Report]: http://goreportcard.com/report/kataras/go-fs
[Documentation Widget]: https://img.shields.io/badge/documentation-reference-5272B4.svg?style=flat-square
[Documentation]: https://www.gitbook.com/book/kataras/go-fs/details
[Language Widget]: https://img.shields.io/badge/powered_by-Go-3362c2.svg?style=flat-square
[Language]: http://golang.org
[Platform Widget]: https://img.shields.io/badge/platform-Any--OS-gray.svg?style=flat-square
| bjwschaap/copper-caple | vendor/src/github.com/kataras/go-fs/README.md | Markdown | mit | 15,564 |
/**
* Copyright MaDgIK Group 2010 - 2015.
*/
package madgik.exareme.master.streamClient;
import madgik.exareme.master.client.AdpDBClientProperties;
import madgik.exareme.master.engine.AdpDBManager;
import madgik.exareme.master.streamClient.rmi.RmiOptiqueStreamAdpDBClient;
import java.rmi.RemoteException;
/**
* @author Christoforos Svingos
*/
public class AdpStreamDBClientFactory {
public static AdpStreamDBClient createOptiqueStreamDBClient(AdpDBManager manager,
AdpDBClientProperties properties) throws RemoteException {
return new RmiOptiqueStreamAdpDBClient(manager, properties);
}
}
| XristosMallios/cache | exareme-master/src/main/java/madgik/exareme/master/streamClient/AdpStreamDBClientFactory.java | Java | mit | 623 |
module Appsignal
class Aggregator
class PostProcessor
attr_reader :transactions
def initialize(transactions)
@transactions = transactions
end
def post_processed_queue!
transactions.map do |transaction|
transaction.events.each do |event|
Appsignal.post_processing_middleware.invoke(event)
end
transaction.to_hash
end
end
def self.default_middleware
Middleware::Chain.new do |chain|
chain.add Appsignal::Aggregator::Middleware::DeleteBlanks
if defined?(::ActionView)
chain.add Appsignal::Aggregator::Middleware::ActionViewSanitizer
end
if defined?(::ActiveRecord)
chain.add Appsignal::Aggregator::Middleware::ActiveRecordSanitizer
end
end
end
end
end
end
| q-m/appsignal | lib/appsignal/aggregator/post_processor.rb | Ruby | mit | 866 |
module.exports = {
settings: {
},
commands: {
},
};
| vgno/roc-config | test/configuration/fixtures/roc.complex.config.js | JavaScript | mit | 68 |
import os
def get_html_theme_path():
theme_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
return theme_dir
| iktakahiro/sphinx_theme_pd | sphinx_theme_pd/__init__.py | Python | mit | 136 |
---
title: ტაძრის განწმედა
date: 14/08/2019
---
როცა სახარებებში ვკითხულობთ ისტორიებს ქრისტეს შესახებ, ხშირად გვიზიდავს მისი მზრუნველობა სნეულთა და ბავშვთა მიმართ, მისი ისტორიები დაკარგულის ძებნისა და საუბრები ღვთის სასუფევლის შესახებ. შესაძლებელია, ამიტომაც სხვა ისტორიები, რომლებშიც იგი მტკიცედ და მძაფრად მოქმედებს, რელიგიური ლიდერებისა და ზოგიერთი მათი ქმედების წინააღმდეგ გამოსვლისას, შეიძლება სრულიად მოულოდნელი აღმოჩნდეს ჩვენთვის.
`წაიკითხეთ მათ. 21:12-16; მარკ. 11:15-19; ლუკ. 19:45-48 და იოან. 2:13-17. რა მნიშვნელობა აქვს იმ ფაქტს, რომ ეს ისტორია ოთხივე სახარებაშია ჩაწერილი?`
არ არის გასაკვირი, რომ ამ შემთხვევას აღწერს ოთხივე მახარობელი. ეს დრამატული ისტორია აღსავსეა დინამიკითა და ემოციური მხურვალებით. ნათელია, იესო ძალიან განიცდიდა იმას, რომ ტაძარს გამოიყენებდნენ მსგავსი სახით და ჭეშმარიტი თაყვანისცემა ჩაანაცვლეს სამსხვერპლო ცხოველების ვაჭრობით. როგორი წაბილწვაა! ტაძარში სამსხვერპლო ცხოველებით ბინძური ვაჭრობა არანაირად არ წარმოადგენდა წუთისოფლის ცოდვების გამო ქრისტეს ჩამნაცვლებელ მსხვერპლს!
ქრისტეს რეაქცია კარგად ერგება ებრაელი წინასწარმეტყველების ქცევის მოდელს. ყველა ისტორიაში ან იესო ან მახარობელი ციტირებს ესაიას, იერემიას ან ფსალმუნებს, რათა აეხსნათ მომხდარი. როდესაც ვაჭართა განდევნის შემდეგ იესომ დაიწყო განკურნება და სწავლება ტაძარში, ხალხმა იესო წინასწარმეტყველად აღიარა (იხ. მათ. 21:11) და მასთან მივიდა. ეს ადამიანები იკურნებოდნენ მასთან შეხებით და მისი სწავლების მოსმენისას იმედს პოვებდნენ.
რელიგიური ლიდერებიც აღიარებდნენ ქრისტეს წინასწარმეტყველად, მაგრამ თვლიდნენ, რომ საშიშროებას წარმოადგენს მათი ძალაუფლებისა და სოციალური წესრიგის სტაბილურობისთვის. ამიტომ ლიდერები წავიდნენ, რათა შეთქმულება მოეწყოთ იესო ქრისტეს წინააღმდეგ, მსგავსად იმისა როგორც მათი წინამორბედები მოილაპარაკებდნენ ხოლმე წინასწარმეტყველთა მოკვლის შესახებ წარსულში (იხ. ლუკ. 19:47,48).
`როგორც ეკლესიის წევრებმა, რა შეგვიძლია გავაკეთოთ ჩვენი მხრიდან, რათა იერუსალიმის ტაძრისგან განსხვავებით ჩვენი ეკლესია არასდროს იქცეს ადგილად, რომელსაც სჭირდება განწმედა? რა ქმედებებმა შეიძლება წაბილწონ იგი?`
| PrJared/sabbath-school-lessons | src/ka/2019-03/07/05.md | Markdown | mit | 5,266 |
/**
* \file
* \brief Local descriptor table (LDT) management
*/
/*
* Copyright (c) 2011, ETH Zurich.
* All rights reserved.
*
* This file is distributed under the terms in the attached LICENSE file.
* If you do not find this file, copies can be found by writing to:
* ETH Zurich D-INFK, Haldeneggsteig 4, CH-8092 Zurich. Attn: Systems Group.
*/
#include <barrelfish/barrelfish.h>
#include <barrelfish/dispatch.h>
#include <barrelfish/dispatcher_arch.h>
#include <barrelfish/curdispatcher_arch.h>
#include <barrelfish/syscalls.h>
#include <barrelfish/ldt.h>
#include <arch/ldt.h>
#include <target/x86_64/barrelfish_kpi/cpu_target.h> // segment_descriptor
#include <stdio.h>
#define LDT_NENTRIES 512 ///< Number of entries in the statically-sized LDT
/// Local segment descriptor table. Shared by all dispatchers in an address space.
// (XXX: coherence assumption)
static union segment_descriptor ldt[LDT_NENTRIES];
/// Spinlock protecting LDT in spanned domains
// (XXX: coherence assumption)
static spinlock_t ldt_spinlock;
/** \brief Initialise private (per-dispatcher) LDT */
void ldt_init_disabled(dispatcher_handle_t handle)
{
errval_t err;
struct dispatcher_shared_x86_64 *disp =
get_dispatcher_shared_x86_64(handle);
struct dispatcher_x86_64 *disp_priv = get_dispatcher_x86_64(handle);
/* setup private (static) LDT, and get kernel to load it */
disp->ldt_base = (lvaddr_t) ldt;
// XXX: size may not be multiple of page size, but does it really matter?
disp->ldt_npages = DIVIDE_ROUND_UP(sizeof(ldt), BASE_PAGE_SIZE);
sys_x86_reload_ldt();
/* XXX: kludge to maintain backwards compatibility.
* Setup a single segment descriptor that we can use to locate the
* current dispatcher (i.e. curdispatcher() always works). This
* will be replaced once we switch onto a thread with a real FS segment.
*/
disp_priv->dummyseg[0] = 0;
disp_priv->dummyseg[1] = handle;
err = ldt_alloc_segment_disabled(handle, disp_priv->dummyseg,
&disp_priv->disp_seg_selector);
if (err_is_fail(err)) {
// XXX: can't call usual debug/panic code, as curdispatcher() won't work
char buf[128];
snprintf(buf, sizeof(buf),
"%.*s.%u: fatal error in ldt_init_disabled(). Aborted.\n",
DISP_NAME_LEN, disp->d.name, disp_priv->generic.core_id);
sys_print(buf, sizeof(buf));
while (1) {disp_yield_disabled(handle);}
}
/* load this segment to FS */
__asm volatile("mov %%ax, %%fs"
: /* No outputs */
: "a" (disp_priv->disp_seg_selector));
}
/**
* \brief Allocate and fill a segment descriptor in the LDT
*
* \param handle Dispatcher handle
* \param segbase Base of segment
* \param ret_selector On success, used to return selector for new segment
*/
errval_t ldt_alloc_segment_disabled(dispatcher_handle_t handle, void *segbase,
uint16_t *ret_selector)
{
// segment descriptors are limited to a 32-bit base address
if ((lvaddr_t)segbase >= (1ul << 32)) {
return LIB_ERR_SEGBASE_OVER_4G_LIMIT;
}
// construct descriptor
union segment_descriptor desc = {
.d = {
.lo_base = ((lvaddr_t) segbase) & 0xffffff,
.hi_base = (((lvaddr_t) segbase) >> 24) & 0xff,
.type = 3, /* read/write data, accessed */
.system_desc = 1, /* data */
.privilege_level = 3, /* user mode */
.present = 1,
.long_mode = 0,
.operation_size = 1,
}
};
// find free LDT entry
acquire_spinlock(&ldt_spinlock);
for (int i = 0; i < LDT_NENTRIES; i++) {
if (!ldt[i].d.present) {
ldt[i] = desc;
release_spinlock(&ldt_spinlock);
assert_disabled(ret_selector != NULL);
*ret_selector = X86_64_LDT_SELECTOR(i);
return SYS_ERR_OK;
}
}
release_spinlock(&ldt_spinlock);
return LIB_ERR_LDT_FULL;
}
/**
* \brief enabled version of ldt_alloc_segment_disabled()
*
* Exposed for calls by special-case software that needs to play with segments.
*/
errval_t ldt_alloc_segment(void *segbase, uint16_t *ret_selector)
{
dispatcher_handle_t handle = disp_disable();
errval_t ret = ldt_alloc_segment_disabled(handle, segbase, ret_selector);
disp_enable(handle);
return ret;
}
/**
* \brief Free a previously-allocated segment on a specific dispatcher
*
* \param handle Dispatcher handle
* \param selector Segment selector
*/
errval_t ldt_free_segment_ondisp(dispatcher_handle_t handle, uint16_t selector)
{
if ((selector & 0x7) != 7) { // XXX: user-priv LDT selector
return LIB_ERR_LDT_SELECTOR_INVALID;
}
int index = X86_64_SELECTOR_IDX(selector);
// check that this entry is occupied
if (index >= LDT_NENTRIES || !ldt[index].d.present) {
return LIB_ERR_LDT_SELECTOR_INVALID;
}
// mark entry as free
ldt[index].raw = 0;
return SYS_ERR_OK;
}
/**
* \brief Free a previously-allocated segment on the current dispatcher
*
* \param selector Segment selector
*/
errval_t ldt_free_segment(uint16_t selector)
{
// strictly speaking, we probably don't need to disable here
dispatcher_handle_t handle = disp_disable();
errval_t ret = ldt_free_segment_ondisp(handle, selector);
disp_enable(handle);
return ret;
}
/**
* \brief Update the base address of a previously-allocated segment
*
* \param selector Segment selector
* \param segbase New base of segment
*/
errval_t ldt_update_segment(uint16_t selector, void *segbase)
{
if ((selector & 0x7) != 7) { // XXX: user-priv LDT selector
return LIB_ERR_LDT_SELECTOR_INVALID;
}
int index = X86_64_SELECTOR_IDX(selector);
// check that this entry is occupied
if (index >= LDT_NENTRIES || !ldt[index].d.present) {
return LIB_ERR_LDT_SELECTOR_INVALID;
}
// segment descriptors are limited to a 32-bit base address
if ((lvaddr_t)segbase >= (1ul << 32)) {
return LIB_ERR_SEGBASE_OVER_4G_LIMIT;
}
// update base address
ldt[index].d.lo_base = ((lvaddr_t) segbase) & 0xffffff;
ldt[index].d.hi_base = (((lvaddr_t) segbase) >> 24) & 0xff;
return SYS_ERR_OK;
}
| daleooo/barrelfish | lib/barrelfish/arch/x86_64/ldt.c | C | mit | 6,346 |
var fs = require('fs');
var pkg = require('../package.json');
console.log('Creating dist/js-data-debug.js...');
var file = fs.readFileSync('dist/js-data-debug.js', { encoding: 'utf-8' });
var lines = file.split('\n');
var newLines = [];
lines.forEach(function (line) {
if (line.indexOf('logFn(') === -1) {
newLines.push(line);
}
});
file = newLines.join('\n');
file += '\n';
fs.writeFileSync('dist/js-data.js', file, { encoding: 'utf-8' });
console.log('Done!');
| davincho/js-data | scripts/debug.js | JavaScript | mit | 480 |
// "Borrowed" from node-inspector
var CallbackHandler = {
/**
* Create a callback container
* @return {Object} that wraps callbacks and returns a one-time id.
*/
create: function () {
var lastId = 1,
callbacks = {}
return Object.create({}, {
wrap: {
value: function (callback) {
var callbackId = lastId++
callbacks[callbackId] = callback || function () {
}
return callbackId
}
},
processResponse: {
value: function (callbackId, args) {
var callback = callbacks[callbackId]
if (callback) {
callback.apply(null, args)
}
delete callbacks[callbackId]
}
},
removeResponseCallbackEntry: {
value: function (callbackId) {
delete callbacks[callbackId]
}
}
})
}
}
var Net = require('net'),
Protocol = require('_debugger').Protocol,
inherits = require('util').inherits,
EventEmitter = require('events').EventEmitter,
debugProtocol = require('debug')('node-inspector:protocol:v8-debug'),
callbackHandler = CallbackHandler.create()
/**
* @param {Number} port
*/
function Debugger(port) {
this._port = port
this._connected = false
this._connection = null
this._lastError = null
this._setupConnection()
}
inherits(Debugger, EventEmitter)
Object.defineProperties(Debugger.prototype, {
/** @type {boolean} */
isRunning: {writable: true, value: true},
/** @type {boolean} */
connected: {
get: function () {
return this._connected
}
}
})
Debugger.prototype._setupConnection = function () {
var connection = Net.createConnection(this._port),
protocol = new Protocol()
protocol.onResponse = this._processResponse.bind(this)
connection
.on('connect', this._onConnectionOpen.bind(this))
.on('data', protocol.execute.bind(protocol))
.on('error', this._onConnectionError.bind(this))
.on('end', this.close.bind(this))
.on('close', this._onConnectionClose.bind(this))
.setEncoding('utf8')
this._connection = connection
}
Debugger.prototype._onConnectionOpen = function () {
this._connected = true
this.emit('connect')
}
/**
* @param {Error} err
*/
Debugger.prototype._onConnectionError = function (err) {
if (err.code == 'ECONNREFUSED') {
err.helpString = 'Is node running with --debug port ' + this._port + '?'
} else if (err.code == 'ECONNRESET') {
err.helpString = 'Check there is no other debugger client attached to port ' + this._port + '.'
}
this._lastError = err.toString()
if (err.helpString) {
this._lastError += '. ' + err.helpString
}
this.emit('error', err)
}
Debugger.prototype._onConnectionClose = function (hadError) {
this.emit('close', hadError ? this._lastError : 'Debugged process exited.')
this._port = null
this._connected = false
this._connection = null
this._lastError = null
}
Debugger.prototype._processResponse = function (message) {
var obj = message.body
if (typeof obj.running === 'boolean') {
this.isRunning = obj.running
}
if (obj.type === 'response' && obj.request_seq > 0) {
debugProtocol('response: ' + JSON.stringify(message.body))
callbackHandler.processResponse(obj.request_seq, [obj])
} else if (obj.type === 'event') {
debugProtocol('event: ' + JSON.stringify(message.body))
if (['break', 'exception'].indexOf(obj.event) > -1) {
this.isRunning = false
}
this.emit(obj.event, obj)
} else {
debugProtocol('unknown: ' + JSON.stringify(message.body))
}
}
/**
* @param {string} data
*/
Debugger.prototype.send = function (data) {
debugProtocol('request: ' + data)
if (this.connected) {
this._connection.write('Content-Length: ' + Buffer.byteLength(data, 'utf8') + '\r\n\r\n' + data)
}
}
/**
* @param {string} command
* @param {Object} params
* @param {function} callback
*/
Debugger.prototype.request = function (command, params, callback) {
var message = {
seq: 0,
type: 'request',
command: command
}
if (typeof callback === 'function') {
message.seq = callbackHandler.wrap(callback)
}
if (params) {
Object.keys(params).forEach(function (key) {
message[key] = params[key]
})
}
this.send(JSON.stringify(message))
}
/**
*/
Debugger.prototype.close = function () {
this._connection.end()
}
module.exports = function (debugPort, callback) {
// give the process time to start up
setTimeout(function () {
var debuggerClient = new Debugger(debugPort)
debuggerClient.on('error', callback)
debuggerClient.on('connect', function () {
debuggerClient.request('continue', undefined, function (response) {
debuggerClient.close()
if (!response.success) return callback(new Error('Could not continue process'))
callback()
})
})
}, 1000)
}
| codydaig/guvnor | test/integration/fixtures/continueProcess.js | JavaScript | mit | 4,878 |
using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Mvc;
using AllReady.Security;
using AllReady.Models;
using AllReady.Services;
using AllReady.ViewModels;
using System.Linq;
using System.Threading.Tasks;
using MediatR;
using AllReady.Areas.Admin.Models;
using System;
using AllReady.Areas.Admin.Features.Activities;
using AllReady.Areas.Admin.Features.Campaigns;
using AllReady.Extensions;
namespace AllReady.Areas.Admin.Controllers
{
[Area("Admin")]
[Authorize("OrgAdmin")]
public class ActivityController : Controller
{
private readonly IAllReadyDataAccess _dataAccess;
private readonly IImageService _imageService;
private readonly IMediator _bus;
public ActivityController(IAllReadyDataAccess dataAccess, IImageService imageService, IMediator bus)
{
_dataAccess = dataAccess;
_imageService = imageService;
_bus = bus;
}
// GET: Activity/Details/5
[HttpGet]
[Route("Admin/Activity/Details/{id}")]
public IActionResult Details(int id)
{
var activity = _bus.Send(new ActivityDetailQuery { ActivityId = id });
if (activity == null)
{
return HttpNotFound();
}
if (!User.IsOrganizationAdmin(activity.OrganizationId))
{
return HttpUnauthorized();
}
return View(activity);
}
// GET: Activity/Create
[Route("Admin/Activity/Create/{campaignId}")]
public IActionResult Create(int campaignId)
{
CampaignSummaryModel campaign = _bus.Send(new CampaignSummaryQuery { CampaignId = campaignId });
if (campaign == null || !User.IsOrganizationAdmin(campaign.OrganizationId))
{
return HttpUnauthorized();
}
var activity = new ActivityDetailModel
{
CampaignId = campaign.Id,
CampaignName = campaign.Name,
TimeZoneId = campaign.TimeZoneId,
OrganizationId = campaign.OrganizationId,
OrganizationName = campaign.OrganizationName,
StartDateTime = DateTime.Today.Date,
EndDateTime = DateTime.Today.Date.AddMonths(1)
};
return View("Edit", activity);
}
// POST: Activity/Create
[HttpPost]
[ValidateAntiForgeryToken]
[Route("Admin/Activity/Create/{campaignId}")]
public async Task<IActionResult> Create(int campaignId, ActivityDetailModel activity, IFormFile fileUpload)
{
if (activity.EndDateTime < activity.StartDateTime)
{
ModelState.AddModelError(nameof(activity.EndDateTime), "End date cannot be earlier than the start date");
}
CampaignSummaryModel campaign = _bus.Send(new CampaignSummaryQuery { CampaignId = campaignId });
if (campaign == null ||
!User.IsOrganizationAdmin(campaign.OrganizationId))
{
return HttpUnauthorized();
}
if (activity.StartDateTime < campaign.StartDate)
{
ModelState.AddModelError(nameof(activity.StartDateTime), "Start date cannot be earlier than the campaign start date " + campaign.StartDate.ToString("d"));
}
if (activity.EndDateTime > campaign.EndDate)
{
ModelState.AddModelError(nameof(activity.EndDateTime), "End date cannot be later than the campaign end date " + campaign.EndDate.ToString("d"));
}
if (ModelState.IsValid)
{
if (fileUpload != null)
{
if (!fileUpload.IsAcceptableImageContentType())
{
ModelState.AddModelError("ImageUrl", "You must upload a valid image file for the logo (.jpg, .png, .gif)");
return View("Edit", activity);
}
}
activity.OrganizationId = campaign.OrganizationId;
var id = _bus.Send(new EditActivityCommand { Activity = activity });
if (fileUpload != null)
{
// resave now that activty has the ImageUrl
activity.Id = id;
activity.ImageUrl = await _imageService.UploadActivityImageAsync(campaign.OrganizationId, id, fileUpload);
_bus.Send(new EditActivityCommand { Activity = activity });
}
return RedirectToAction("Details", "Activity", new { area = "Admin", id = id });
}
return View("Edit", activity);
}
// GET: Activity/Edit/5
public IActionResult Edit(int id)
{
ActivityDetailModel activity = _bus.Send(new ActivityDetailQuery { ActivityId = id });
if (activity == null)
{
return HttpNotFound();
}
if (!User.IsOrganizationAdmin(activity.OrganizationId))
{
return HttpUnauthorized();
}
return View(activity);
}
// POST: Activity/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(ActivityDetailModel activity, IFormFile fileUpload)
{
if (activity == null)
{
return HttpBadRequest();
}
//TODO: Use the query pattern here
int organizationId = _dataAccess.GetManagingOrganizationId(activity.Id);
if (!User.IsOrganizationAdmin(organizationId))
{
return HttpUnauthorized();
}
if (activity.EndDateTime < activity.StartDateTime)
{
ModelState.AddModelError(nameof(activity.EndDateTime), "End date cannot be earlier than the start date");
}
CampaignSummaryModel campaign = _bus.Send(new CampaignSummaryQuery { CampaignId = activity.CampaignId });
if (activity.StartDateTime < campaign.StartDate)
{
ModelState.AddModelError(nameof(activity.StartDateTime), "Start date cannot be earlier than the campaign start date " + campaign.StartDate.ToString("d"));
}
if (activity.EndDateTime > campaign.EndDate)
{
ModelState.AddModelError(nameof(activity.EndDateTime), "End date cannot be later than the campaign end date " + campaign.EndDate.ToString("d"));
}
if (ModelState.IsValid)
{
if (fileUpload != null)
{
if (fileUpload.IsAcceptableImageContentType())
{
activity.ImageUrl = await _imageService.UploadActivityImageAsync(campaign.OrganizationId, activity.Id, fileUpload);
}
else
{
ModelState.AddModelError("ImageUrl", "You must upload a valid image file for the logo (.jpg, .png, .gif)");
return View(activity);
}
}
var id = _bus.Send(new EditActivityCommand { Activity = activity });
return RedirectToAction("Details", "Activity", new { area = "Admin", id = id });
}
return View(activity);
}
// GET: Activity/Delete/5
[ActionName("Delete")]
public IActionResult Delete(int id)
{
var activity = _bus.Send(new ActivityDetailQuery { ActivityId = id });
if (activity == null)
{
return HttpNotFound();
}
if (!User.IsOrganizationAdmin(activity.OrganizationId))
{
return HttpUnauthorized();
}
return View(activity);
}
// POST: Activity/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public IActionResult DeleteConfirmed(System.Int32 id)
{
//TODO: Should be using an ActivitySummaryQuery here
ActivityDetailModel activity = _bus.Send(new ActivityDetailQuery { ActivityId = id });
if (activity == null)
{
return HttpNotFound();
}
if (!User.IsOrganizationAdmin(activity.OrganizationId))
{
return HttpUnauthorized();
}
_bus.Send(new DeleteActivityCommand { ActivityId = id });
return RedirectToAction("Details", "Campaign", new { area = "Admin", id = activity.CampaignId });
}
[HttpGet]
public IActionResult Assign(int id)
{
//TODO: Update this to use Query pattern
var activity = _dataAccess.GetActivity(id);
if (activity == null)
{
return HttpNotFound();
}
if (!User.IsOrganizationAdmin(activity.Campaign.ManagingOrganizationId))
{
return HttpUnauthorized();
}
var model = new ActivityViewModel(activity);
model.Tasks = model.Tasks.OrderBy(t => t.StartDateTime).ThenBy(t => t.Name).ToList();
model.Volunteers = activity.UsersSignedUp.Select(u => u.User).ToList();
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult MessageAllVolunteers(MessageActivityVolunteersModel model)
{
//TODO: Query only for the organization Id rather than the whole activity detail
if (!ModelState.IsValid)
{
return HttpBadRequest(ModelState);
}
var activity = _bus.Send(new ActivityDetailQuery { ActivityId = model.ActivityId });
if (activity == null)
{
return HttpNotFound();
}
if (!User.IsOrganizationAdmin(activity.OrganizationId))
{
return HttpUnauthorized();
}
_bus.Send(new MessageActivityVolunteersCommand { Model = model });
return Ok();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> PostActivityFile(int id, IFormFile file)
{
//TODO: Use a command here
Activity a = _dataAccess.GetActivity(id);
a.ImageUrl = await _imageService.UploadActivityImageAsync(a.Id, a.Campaign.ManagingOrganizationId, file);
await _dataAccess.UpdateActivity(a);
return RedirectToRoute(new { controller = "Activity", Area = "Admin", action = "Edit", id = id });
}
private bool UserIsOrganizationAdminOfActivity(Activity activity)
{
return User.IsOrganizationAdmin(activity.Campaign.ManagingOrganizationId);
}
private bool UserIsOrganizationAdminOfActivity(int activityId)
{
return UserIsOrganizationAdminOfActivity(_dataAccess.GetActivity(activityId));
}
}
} | aliiftikhar/allReady | AllReadyApp/Web-App/AllReady/Areas/Admin/Controllers/ActivityAdminController.cs | C# | mit | 11,630 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="refresh" content="0;URL=../../../../libc/constant.ETH_P_TEB.html">
</head>
<body>
<p>Redirecting to <a href="../../../../libc/constant.ETH_P_TEB.html">../../../../libc/constant.ETH_P_TEB.html</a>...</p>
<script>location.replace("../../../../libc/constant.ETH_P_TEB.html" + location.search + location.hash);</script>
</body>
</html> | malept/guardhaus | main/libc/unix/linux_like/linux/constant.ETH_P_TEB.html | HTML | mit | 401 |
import { ConfigManager } from './configuration/configManager';
void ConfigManager.removeSettings();
| vscode-icons/vscode-icons | src/uninstall.ts | TypeScript | mit | 101 |
/* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright(c) 2019-2021 Xilinx, Inc.
* Copyright(c) 2019 Solarflare Communications Inc.
*
* This software was jointly developed between OKTET Labs (under contract
* for Solarflare) and Solarflare Communications, Inc.
*/
#ifndef _SFC_MAE_H
#define _SFC_MAE_H
#include <stdbool.h>
#include <rte_spinlock.h>
#include "efx.h"
#include "sfc_stats.h"
#ifdef __cplusplus
extern "C" {
#endif
/** FW-allocatable resource context */
struct sfc_mae_fw_rsrc {
unsigned int refcnt;
RTE_STD_C11
union {
efx_mae_aset_id_t aset_id;
efx_mae_rule_id_t rule_id;
efx_mae_mac_id_t mac_id;
efx_mae_eh_id_t eh_id;
};
};
/** Outer rule registry entry */
struct sfc_mae_outer_rule {
TAILQ_ENTRY(sfc_mae_outer_rule) entries;
unsigned int refcnt;
efx_mae_match_spec_t *match_spec;
efx_tunnel_protocol_t encap_type;
struct sfc_mae_fw_rsrc fw_rsrc;
};
TAILQ_HEAD(sfc_mae_outer_rules, sfc_mae_outer_rule);
/** MAC address registry entry */
struct sfc_mae_mac_addr {
TAILQ_ENTRY(sfc_mae_mac_addr) entries;
unsigned int refcnt;
uint8_t addr_bytes[EFX_MAC_ADDR_LEN];
struct sfc_mae_fw_rsrc fw_rsrc;
};
TAILQ_HEAD(sfc_mae_mac_addrs, sfc_mae_mac_addr);
/** Encap. header registry entry */
struct sfc_mae_encap_header {
TAILQ_ENTRY(sfc_mae_encap_header) entries;
unsigned int refcnt;
uint8_t *buf;
size_t size;
efx_tunnel_protocol_t type;
struct sfc_mae_fw_rsrc fw_rsrc;
};
TAILQ_HEAD(sfc_mae_encap_headers, sfc_mae_encap_header);
/* Counter ID */
struct sfc_mae_counter_id {
/* ID of a counter in MAE */
efx_counter_t mae_id;
/* ID of a counter in RTE */
uint32_t rte_id;
/* RTE counter ID validity status */
bool rte_id_valid;
/* Flow Tunnel (FT) GROUP hit counter (or NULL) */
uint64_t *ft_group_hit_counter;
/* Flow Tunnel (FT) context (for JUMP rules; otherwise, NULL) */
struct sfc_flow_tunnel *ft;
};
/** Action set registry entry */
struct sfc_mae_action_set {
TAILQ_ENTRY(sfc_mae_action_set) entries;
unsigned int refcnt;
struct sfc_mae_counter_id *counters;
uint32_t n_counters;
efx_mae_actions_t *spec;
struct sfc_mae_encap_header *encap_header;
struct sfc_mae_mac_addr *dst_mac_addr;
struct sfc_mae_mac_addr *src_mac_addr;
struct sfc_mae_fw_rsrc fw_rsrc;
};
TAILQ_HEAD(sfc_mae_action_sets, sfc_mae_action_set);
/** Options for MAE support status */
enum sfc_mae_status {
SFC_MAE_STATUS_UNKNOWN = 0,
SFC_MAE_STATUS_UNSUPPORTED,
SFC_MAE_STATUS_SUPPORTED,
SFC_MAE_STATUS_ADMIN,
};
/*
* Encap. header bounce buffer. It is used to store header data
* when parsing the header definition in the action VXLAN_ENCAP.
*/
struct sfc_mae_bounce_eh {
uint8_t *buf;
size_t buf_size;
size_t size;
efx_tunnel_protocol_t type;
};
/** Counter collection entry */
struct sfc_mae_counter {
bool inuse;
uint32_t generation_count;
union sfc_pkts_bytes value;
union sfc_pkts_bytes reset;
uint64_t *ft_group_hit_counter;
};
struct sfc_mae_counters_xstats {
uint64_t not_inuse_update;
uint64_t realloc_update;
};
struct sfc_mae_counters {
/** An array of all MAE counters */
struct sfc_mae_counter *mae_counters;
/** Extra statistics for counters */
struct sfc_mae_counters_xstats xstats;
/** Count of all MAE counters */
unsigned int n_mae_counters;
};
/** Options for MAE counter polling mode */
enum sfc_mae_counter_polling_mode {
SFC_MAE_COUNTER_POLLING_OFF = 0,
SFC_MAE_COUNTER_POLLING_SERVICE,
SFC_MAE_COUNTER_POLLING_THREAD,
};
struct sfc_mae_counter_registry {
/* Common counter information */
/** Counters collection */
struct sfc_mae_counters counters;
/* Information used by counter update service */
/** Callback to get packets from RxQ */
eth_rx_burst_t rx_pkt_burst;
/** Data for the callback to get packets */
struct sfc_dp_rxq *rx_dp;
/** Number of buffers pushed to the RxQ */
unsigned int pushed_n_buffers;
/** Are credits used by counter stream */
bool use_credits;
/* Information used by configuration routines */
enum sfc_mae_counter_polling_mode polling_mode;
union {
struct {
/** Counter service core ID */
uint32_t core_id;
/** Counter service ID */
uint32_t id;
} service;
struct {
/** Counter thread ID */
pthread_t id;
/** The thread should keep running */
bool run;
} thread;
} polling;
};
/**
* MAE rules used to capture traffic generated by VFs and direct it to
* representors (one for each VF).
*/
#define SFC_MAE_NB_REPR_RULES_MAX (64)
/** Rules to forward traffic from PHY port to PF and from PF to PHY port */
#define SFC_MAE_NB_SWITCHDEV_RULES (2)
/** Maximum required internal MAE rules */
#define SFC_MAE_NB_RULES_MAX (SFC_MAE_NB_SWITCHDEV_RULES + \
SFC_MAE_NB_REPR_RULES_MAX)
struct sfc_mae_rule {
efx_mae_match_spec_t *spec;
efx_mae_actions_t *actions;
efx_mae_aset_id_t action_set;
efx_mae_rule_id_t rule_id;
};
struct sfc_mae_internal_rules {
/*
* Rules required to sustain switchdev mode or to provide
* port representor functionality.
*/
struct sfc_mae_rule rules[SFC_MAE_NB_RULES_MAX];
};
struct sfc_mae {
/** Assigned switch domain identifier */
uint16_t switch_domain_id;
/** Assigned switch port identifier */
uint16_t switch_port_id;
/** NIC support for MAE status */
enum sfc_mae_status status;
/** Priority level limit for MAE outer rules */
unsigned int nb_outer_rule_prios_max;
/** Priority level limit for MAE action rules */
unsigned int nb_action_rule_prios_max;
/** Encapsulation support status */
uint32_t encap_types_supported;
/** Outer rule registry */
struct sfc_mae_outer_rules outer_rules;
/** Encap. header registry */
struct sfc_mae_encap_headers encap_headers;
/** MAC address registry */
struct sfc_mae_mac_addrs mac_addrs;
/** Action set registry */
struct sfc_mae_action_sets action_sets;
/** Encap. header bounce buffer */
struct sfc_mae_bounce_eh bounce_eh;
/** Flag indicating whether counter-only RxQ is running */
bool counter_rxq_running;
/** Counter registry */
struct sfc_mae_counter_registry counter_registry;
/** Driver-internal flow rules */
struct sfc_mae_internal_rules internal_rules;
/**
* Switchdev default rules. They forward traffic from PHY port
* to PF and vice versa.
*/
struct sfc_mae_rule *switchdev_rule_pf_to_ext;
struct sfc_mae_rule *switchdev_rule_ext_to_pf;
};
struct sfc_adapter;
struct sfc_flow_spec;
/** This implementation supports double-tagging */
#define SFC_MAE_MATCH_VLAN_MAX_NTAGS (2)
/** It is possible to keep track of one item ETH and two items VLAN */
#define SFC_MAE_L2_MAX_NITEMS (SFC_MAE_MATCH_VLAN_MAX_NTAGS + 1)
/** Auxiliary entry format to keep track of L2 "type" ("inner_type") */
struct sfc_mae_ethertype {
rte_be16_t value;
rte_be16_t mask;
};
struct sfc_mae_pattern_data {
/**
* Keeps track of "type" ("inner_type") mask and value for each
* parsed L2 item in a pattern. These values/masks get filled
* in MAE match specification at the end of parsing. Also, this
* information is used to conduct consistency checks:
*
* - If an item ETH is followed by a single item VLAN,
* the former must have "type" set to one of supported
* TPID values (0x8100, 0x88a8, 0x9100, 0x9200, 0x9300),
* or 0x0000/0x0000.
*
* - If an item ETH is followed by two items VLAN, the
* item ETH must have "type" set to one of supported TPID
* values (0x88a8, 0x9100, 0x9200, 0x9300), or 0x0000/0x0000,
* and the outermost VLAN item must have "inner_type" set
* to TPID value 0x8100, or 0x0000/0x0000
*
* - If a L2 item is followed by a L3 one, the former must
* indicate "type" ("inner_type") which corresponds to
* the protocol used in the L3 item, or 0x0000/0x0000.
*
* In turn, mapping between RTE convention (above requirements) and
* MAE fields is non-trivial. The following scheme indicates
* which item EtherTypes go to which MAE fields in the case
* of single tag:
*
* ETH (0x8100) --> VLAN0_PROTO_BE
* VLAN (L3 EtherType) --> ETHER_TYPE_BE
*
* Similarly, in the case of double tagging:
*
* ETH (0x88a8) --> VLAN0_PROTO_BE
* VLAN (0x8100) --> VLAN1_PROTO_BE
* VLAN (L3 EtherType) --> ETHER_TYPE_BE
*/
struct sfc_mae_ethertype ethertypes[SFC_MAE_L2_MAX_NITEMS];
rte_be16_t tci_masks[SFC_MAE_MATCH_VLAN_MAX_NTAGS];
unsigned int nb_vlan_tags;
/**
* L3 requirement for the innermost L2 item's "type" ("inner_type").
* This contains one of:
* - 0x0800/0xffff: IPV4
* - 0x86dd/0xffff: IPV6
* - 0x0000/0x0000: no L3 item
*/
struct sfc_mae_ethertype innermost_ethertype_restriction;
/**
* The following two fields keep track of L3 "proto" mask and value.
* The corresponding fields get filled in MAE match specification
* at the end of parsing. Also, the information is used by a
* post-check to enforce consistency requirements:
*
* - If a L3 item is followed by an item TCP, the former has
* its "proto" set to either 0x06/0xff or 0x00/0x00.
*
* - If a L3 item is followed by an item UDP, the former has
* its "proto" set to either 0x11/0xff or 0x00/0x00.
*/
uint8_t l3_next_proto_value;
uint8_t l3_next_proto_mask;
/*
* L4 requirement for L3 item's "proto".
* This contains one of:
* - 0x06/0xff: TCP
* - 0x11/0xff: UDP
* - 0x00/0x00: no L4 item
*/
uint8_t l3_next_proto_restriction_value;
uint8_t l3_next_proto_restriction_mask;
/* Projected state of EFX_MAE_FIELD_HAS_OVLAN match bit */
bool has_ovlan_value;
bool has_ovlan_mask;
/* Projected state of EFX_MAE_FIELD_HAS_IVLAN match bit */
bool has_ivlan_value;
bool has_ivlan_mask;
};
struct sfc_mae_parse_ctx {
struct sfc_adapter *sa;
efx_mae_match_spec_t *match_spec_action;
efx_mae_match_spec_t *match_spec_outer;
/*
* This points to either of the above two specifications depending
* on which part of the pattern is being parsed (outer / inner).
*/
efx_mae_match_spec_t *match_spec;
/*
* This points to either "field_ids_remap_to_encap"
* or "field_ids_no_remap" (see sfc_mae.c) depending on
* which part of the pattern is being parsed.
*/
const efx_mae_field_id_t *field_ids_remap;
/* These two fields correspond to the tunnel-specific default mask. */
size_t tunnel_def_mask_size;
const void *tunnel_def_mask;
bool match_mport_set;
enum sfc_flow_tunnel_rule_type ft_rule_type;
struct sfc_mae_pattern_data pattern_data;
efx_tunnel_protocol_t encap_type;
const struct rte_flow_item *pattern;
unsigned int priority;
struct sfc_flow_tunnel *ft;
};
int sfc_mae_attach(struct sfc_adapter *sa);
void sfc_mae_detach(struct sfc_adapter *sa);
sfc_flow_cleanup_cb_t sfc_mae_flow_cleanup;
int sfc_mae_rule_parse_pattern(struct sfc_adapter *sa,
const struct rte_flow_item pattern[],
struct sfc_flow_spec_mae *spec,
struct rte_flow_error *error);
int sfc_mae_rule_parse_actions(struct sfc_adapter *sa,
const struct rte_flow_action actions[],
struct sfc_flow_spec_mae *spec_mae,
struct rte_flow_error *error);
sfc_flow_verify_cb_t sfc_mae_flow_verify;
sfc_flow_insert_cb_t sfc_mae_flow_insert;
sfc_flow_remove_cb_t sfc_mae_flow_remove;
sfc_flow_query_cb_t sfc_mae_flow_query;
/**
* The value used to represent the lowest priority.
* Used in MAE rule API.
*/
#define SFC_MAE_RULE_PRIO_LOWEST (-1)
/**
* Insert a driver-internal flow rule that matches traffic originating from
* some m-port selector and redirects it to another one
* (eg. PF --> PHY, PHY --> PF).
*
* If requested priority is negative, use the lowest priority.
*/
int sfc_mae_rule_add_mport_match_deliver(struct sfc_adapter *sa,
const efx_mport_sel_t *mport_match,
const efx_mport_sel_t *mport_deliver,
int prio, struct sfc_mae_rule **rulep);
void sfc_mae_rule_del(struct sfc_adapter *sa, struct sfc_mae_rule *rule);
int sfc_mae_switchdev_init(struct sfc_adapter *sa);
void sfc_mae_switchdev_fini(struct sfc_adapter *sa);
#ifdef __cplusplus
}
#endif
#endif /* _SFC_MAE_H */
| john-mcnamara-intel/dpdk | drivers/net/sfc/sfc_mae.h | C | mit | 12,044 |
version https://git-lfs.github.com/spec/v1
oid sha256:a5b63c6dfd15dccd31cce53e9713057b4a280de478598a0046a6b1221e6564d0
size 42396
| yogeshsaroya/new-cdnjs | ajax/libs/insightjs/0.1.4/insight.min.js | JavaScript | mit | 130 |
<!doctype html>
<html>
<title>npm-whoami</title>
<meta http-equiv="content-type" value="text/html;utf-8">
<link rel="stylesheet" type="text/css" href="../../static/style.css">
<link rel="canonical" href="https://www.npmjs.org/doc/api/npm-whoami.html">
<script async=true src="../../static/toc.js"></script>
<body>
<div id="wrapper">
<h1><a href="../api/npm-whoami.html">npm-whoami</a></h1> <p>Display npm username</p>
<h2 id="synopsis">SYNOPSIS</h2>
<pre><code>npm.commands.whoami(args, callback)
</code></pre><h2 id="description">DESCRIPTION</h2>
<p>Print the <code>username</code> config to standard output.</p>
<p>'args' is never used and callback is never called with data.
'args' must be present or things will break.</p>
<p>This function is not useful programmatically</p>
</div>
<table border=0 cellspacing=0 cellpadding=0 id=npmlogo>
<tr><td style="width:180px;height:10px;background:rgb(237,127,127)" colspan=18> </td></tr>
<tr><td rowspan=4 style="width:10px;height:10px;background:rgb(237,127,127)"> </td><td style="width:40px;height:10px;background:#fff" colspan=4> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=4> </td><td style="width:40px;height:10px;background:#fff" colspan=4> </td><td rowspan=4 style="width:10px;height:10px;background:rgb(237,127,127)"> </td><td colspan=6 style="width:60px;height:10px;background:#fff"> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=4> </td></tr>
<tr><td colspan=2 style="width:20px;height:30px;background:#fff" rowspan=3> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=3> </td><td style="width:10px;height:10px;background:#fff" rowspan=3> </td><td style="width:20px;height:10px;background:#fff" rowspan=4 colspan=2> </td><td style="width:10px;height:20px;background:rgb(237,127,127)" rowspan=2> </td><td style="width:10px;height:10px;background:#fff" rowspan=3> </td><td style="width:20px;height:10px;background:#fff" rowspan=3 colspan=2> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=3> </td><td style="width:10px;height:10px;background:#fff" rowspan=3> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=3> </td></tr>
<tr><td style="width:10px;height:10px;background:#fff" rowspan=2> </td></tr>
<tr><td style="width:10px;height:10px;background:#fff"> </td></tr>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
<p id="footer">npm-whoami — npm@2.14.10</p>
| michaljach/ember-cli-xpagination | node_modules/ember-cli/node_modules/npm/html/doc/api/npm-whoami.html | HTML | mit | 2,975 |
// -*- c++ -*-
/*
* Copyright (c) 2010-2012, Jim Bosch
* All rights reserved.
*
* ndarray is distributed under a simple BSD-like license;
* see the LICENSE file that should be present in the root
* of the source distribution, or alternately available at:
* https://github.com/ndarray/ndarray
*/
#ifndef NDARRAY_EIGEN_BP_EigenView_h_INCLUDED
#define NDARRAY_EIGEN_BP_EigenView_h_INCLUDED
#include "boost/numpy.hpp"
#include "ndarray/bp/Array.h"
#include "ndarray/eigen.h"
namespace ndarray {
template <typename T, int N, int C, typename XprKind_, int Rows_, int Cols_>
class ToBoostPython< EigenView<T,N,C,XprKind_,Rows_,Cols_> > {
public:
typedef boost::numpy::ndarray result_type;
static boost::numpy::ndarray apply(EigenView<T,N,C,XprKind_,Rows_,Cols_> const & input) {
boost::numpy::ndarray result = ToBoostPython< Array<T,N,C> >::apply(input.shallow());
if (Rows_ == 1 || Cols_ == 1) return result.squeeze();
return result;
}
};
template <typename T, int N, int C, typename XprKind_, int Rows_, int Cols_>
class FromBoostPython< EigenView<T,N,C,XprKind_,Rows_,Cols_> > {
public:
BOOST_STATIC_ASSERT( N == 1 || N == 2 );
BOOST_STATIC_ASSERT( N != 1 || Rows_ == 1 || Cols_ == 1 );
explicit FromBoostPython(boost::python::object const & input) : _impl(input) {}
bool convertible() {
try {
boost::numpy::ndarray array = boost::python::extract<boost::numpy::ndarray>(_impl.input);
if (N == 2) {
if (Rows_ == 1) {
array = array.reshape(boost::python::make_tuple(1, -1));
} else if (Cols_ == 1) {
array = array.reshape(boost::python::make_tuple(-1, 1));
}
if (Rows_ != Eigen::Dynamic && array.shape(0) != Rows_) return false;
if (Cols_ != Eigen::Dynamic && array.shape(1) != Cols_) return false;
} else if (N == 1) {
array = array.squeeze();
int requiredSize = Rows_ * Cols_;
if (requiredSize != Eigen::Dynamic && array.shape(0) != requiredSize) return false;
}
_impl.input = array;
if (!_impl.convertible()) return false;
} catch (boost::python::error_already_set) {
boost::python::handle_exception();
PyErr_Clear();
return false;
}
return true;
}
EigenView<T,N,C,XprKind_,Rows_,Cols_> operator()() {
return EigenView<T,N,C,XprKind_,Rows_,Cols_>(_impl());
}
private:
FromBoostPython< Array<T,N,C> > _impl;
};
} // namespace ndarray
#endif // !NDARRAY_EIGEN_BP_EigenView_h_INCLUDED
| rnavier/rnavier | ndarray/ndarray/eigen/bp/EigenView.h | C | mit | 2,686 |
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.appservice.v2016_03_01;
import java.util.Collection;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.microsoft.rest.ExpandableStringEnum;
/**
* Defines values for InAvailabilityReasonType.
*/
public final class InAvailabilityReasonType extends ExpandableStringEnum<InAvailabilityReasonType> {
/** Static value Invalid for InAvailabilityReasonType. */
public static final InAvailabilityReasonType INVALID = fromString("Invalid");
/** Static value AlreadyExists for InAvailabilityReasonType. */
public static final InAvailabilityReasonType ALREADY_EXISTS = fromString("AlreadyExists");
/**
* Creates or finds a InAvailabilityReasonType from its string representation.
* @param name a name to look for
* @return the corresponding InAvailabilityReasonType
*/
@JsonCreator
public static InAvailabilityReasonType fromString(String name) {
return fromString(name, InAvailabilityReasonType.class);
}
/**
* @return known InAvailabilityReasonType values
*/
public static Collection<InAvailabilityReasonType> values() {
return values(InAvailabilityReasonType.class);
}
}
| navalev/azure-sdk-for-java | sdk/appservice/mgmt-v2016_03_01/src/main/java/com/microsoft/azure/management/appservice/v2016_03_01/InAvailabilityReasonType.java | Java | mit | 1,444 |
<?php # -*- coding: utf-8 -*-
/**
* Class Mlp_Language_Manager_Page_View
*
* @version 2014.07.16
* @author Inpsyde GmbH, toscho
* @license GPL
*/
class Mlp_Language_Manager_Page_View {
/**
* @var Mlp_Options_Page_Data
*/
private $page_data;
/**
* @var Mlp_Browsable
*/
private $pagination_data;
/**
* @var Mlp_Updatable
*/
private $watcher;
/**
* @param Mlp_Options_Page_Data $page_data
* @param Mlp_Updatable $watcher
* @param Mlp_Browsable $pagination_data
*/
public function __construct(
Mlp_Options_Page_Data $page_data,
Mlp_Updatable $watcher,
Mlp_Browsable $pagination_data
) {
$this->watcher = $watcher;
$this->page_data = $page_data;
$this->pagination_data = $pagination_data;
}
/**
* Callback for page output.
*
*/
public function render() {
$title = $this->page_data->get_title();
$action = $this->page_data->get_form_action();
$action_name = $this->page_data->get_action_name();
$paged = $this->pagination_data->get_current_page();
?>
<div class="wrap">
<h1><?php echo esc_html( $title ); ?></h1>
<?php $this->watcher->update( 'before_form' ); ?>
<form action="<?php echo esc_attr( $action ); ?>" method="post">
<input type="hidden" name="action" value="<?php echo esc_attr( $action_name ); ?>">
<input type="hidden" name="paged" value="<?php echo esc_attr( $paged ); ?>">
<?php
wp_nonce_field( $this->page_data->get_nonce_action(), $this->page_data->get_nonce_name() );
$this->watcher->update( 'before_table' );
$this->watcher->update( 'show_table' );
$this->watcher->update( 'after_table' );
submit_button(
esc_attr__( 'Save changes', 'multilingual-press' ),
'primary',
'save',
false,
array(
'style' => 'float:left',
)
);
$this->watcher->update( 'after_form_submit_button' );
?>
</form>
<?php $this->watcher->update( 'after_form' ); ?>
</div>
<?php
}
}
| inpsyde/multilingual-press | src/inc/language-manager/Mlp_Language_Manager_Page_View.php | PHP | mit | 1,993 |
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import { Registry } from 'vs/platform/platform';
import nls = require('vs/nls');
import product from 'vs/platform/node/product';
import * as os from 'os';
import { SyncActionDescriptor } from 'vs/platform/actions/common/actions';
import { IConfigurationRegistry, Extensions as ConfigurationExtensions } from 'vs/platform/configuration/common/configurationRegistry';
import { IWorkbenchActionRegistry, Extensions } from 'vs/workbench/common/actionRegistry';
import { KeyMod, KeyChord, KeyCode } from 'vs/base/common/keyCodes';
import { isWindows, isLinux, isMacintosh } from 'vs/base/common/platform';
import { CloseEditorAction, KeybindingsReferenceAction, OpenDocumentationUrlAction, OpenIntroductoryVideosUrlAction, ReportIssueAction, ReportPerformanceIssueAction, ZoomResetAction, ZoomOutAction, ZoomInAction, ToggleFullScreenAction, ToggleMenuBarAction, CloseFolderAction, CloseWindowAction, SwitchWindow, NewWindowAction, CloseMessagesAction, NavigateUpAction, NavigateDownAction, NavigateLeftAction, NavigateRightAction, IncreaseViewSizeAction, DecreaseViewSizeAction, ShowStartupPerformance, ToggleSharedProcessAction } from 'vs/workbench/electron-browser/actions';
import { MessagesVisibleContext } from 'vs/workbench/electron-browser/workbench';
import { IJSONSchema } from 'vs/base/common/jsonSchema';
import { registerCommands } from 'vs/workbench/electron-browser/commands';
// Contribute Commands
registerCommands();
// Contribute Global Actions
const viewCategory = nls.localize('view', "View");
const helpCategory = nls.localize('help', "Help");
const fileCategory = nls.localize('file', "File");
const workbenchActionsRegistry = Registry.as<IWorkbenchActionRegistry>(Extensions.WorkbenchActions);
workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(NewWindowAction, NewWindowAction.ID, NewWindowAction.LABEL, { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_N }), 'New Window');
workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(CloseWindowAction, CloseWindowAction.ID, CloseWindowAction.LABEL, { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_W }), 'Close Window');
workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(SwitchWindow, SwitchWindow.ID, SwitchWindow.LABEL), 'Switch Window');
workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(CloseFolderAction, CloseFolderAction.ID, CloseFolderAction.LABEL, { primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyCode.KEY_F) }), 'File: Close Folder', fileCategory);
if (!!product.reportIssueUrl) {
workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(ReportIssueAction, ReportIssueAction.ID, ReportIssueAction.LABEL), 'Help: Report Issues', helpCategory);
workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(ReportPerformanceIssueAction, ReportPerformanceIssueAction.ID, ReportPerformanceIssueAction.LABEL), 'Help: Report Performance Issues', helpCategory);
}
if (KeybindingsReferenceAction.AVAILABLE) {
workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(KeybindingsReferenceAction, KeybindingsReferenceAction.ID, KeybindingsReferenceAction.LABEL, { primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyMod.CtrlCmd | KeyCode.KEY_R) }), 'Help: Keyboard Shortcuts Reference', helpCategory);
}
if (OpenDocumentationUrlAction.AVAILABLE) {
workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(OpenDocumentationUrlAction, OpenDocumentationUrlAction.ID, OpenDocumentationUrlAction.LABEL), 'Help: Documentation', helpCategory);
}
if (OpenIntroductoryVideosUrlAction.AVAILABLE) {
workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(OpenIntroductoryVideosUrlAction, OpenIntroductoryVideosUrlAction.ID, OpenIntroductoryVideosUrlAction.LABEL), 'Help: Introductory Videos', helpCategory);
}
workbenchActionsRegistry.registerWorkbenchAction(
new SyncActionDescriptor(ZoomInAction, ZoomInAction.ID, ZoomInAction.LABEL, {
primary: KeyMod.CtrlCmd | KeyCode.US_EQUAL,
secondary: [KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.US_EQUAL, KeyMod.CtrlCmd | KeyCode.NUMPAD_ADD]
}), 'View: Zoom In', viewCategory);
workbenchActionsRegistry.registerWorkbenchAction(
new SyncActionDescriptor(ZoomOutAction, ZoomOutAction.ID, ZoomOutAction.LABEL, {
primary: KeyMod.CtrlCmd | KeyCode.US_MINUS,
secondary: [KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.US_MINUS, KeyMod.CtrlCmd | KeyCode.NUMPAD_SUBTRACT],
linux: { primary: KeyMod.CtrlCmd | KeyCode.US_MINUS, secondary: [KeyMod.CtrlCmd | KeyCode.NUMPAD_SUBTRACT] }
}), 'View: Zoom Out', viewCategory
);
workbenchActionsRegistry.registerWorkbenchAction(
new SyncActionDescriptor(ZoomResetAction, ZoomResetAction.ID, ZoomResetAction.LABEL, {
primary: KeyMod.CtrlCmd | KeyCode.NUMPAD_0
}), 'View: Reset Zoom', viewCategory
);
workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(CloseMessagesAction, CloseMessagesAction.ID, CloseMessagesAction.LABEL, { primary: KeyCode.Escape, secondary: [KeyMod.Shift | KeyCode.Escape] }, MessagesVisibleContext), 'Close Notification Messages');
workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(CloseEditorAction, CloseEditorAction.ID, CloseEditorAction.LABEL, { primary: KeyMod.CtrlCmd | KeyCode.KEY_W, win: { primary: KeyMod.CtrlCmd | KeyCode.F4, secondary: [KeyMod.CtrlCmd | KeyCode.KEY_W] } }), 'View: Close Editor', viewCategory);
workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(ToggleFullScreenAction, ToggleFullScreenAction.ID, ToggleFullScreenAction.LABEL, { primary: KeyCode.F11, mac: { primary: KeyMod.CtrlCmd | KeyMod.WinCtrl | KeyCode.KEY_F } }), 'View: Toggle Full Screen', viewCategory);
if (isWindows || isLinux) {
workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(ToggleMenuBarAction, ToggleMenuBarAction.ID, ToggleMenuBarAction.LABEL), 'View: Toggle Menu Bar', viewCategory);
}
workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(NavigateUpAction, NavigateUpAction.ID, NavigateUpAction.LABEL, null), 'View: Move to the View Above', viewCategory);
workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(NavigateDownAction, NavigateDownAction.ID, NavigateDownAction.LABEL, null), 'View: Move to the View Below', viewCategory);
workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(NavigateLeftAction, NavigateLeftAction.ID, NavigateLeftAction.LABEL, null), 'View: Move to the View on the Left', viewCategory);
workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(NavigateRightAction, NavigateRightAction.ID, NavigateRightAction.LABEL, null), 'View: Move to the View on the Right', viewCategory);
workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(IncreaseViewSizeAction, IncreaseViewSizeAction.ID, IncreaseViewSizeAction.LABEL, null), 'View: Increase View Size', viewCategory);
workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(DecreaseViewSizeAction, DecreaseViewSizeAction.ID, DecreaseViewSizeAction.LABEL, null), 'View: Decrease View Size', viewCategory);
// Developer related actions
const developerCategory = nls.localize('developer', "Developer");
workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(ShowStartupPerformance, ShowStartupPerformance.ID, ShowStartupPerformance.LABEL), 'Developer: Startup Performance', developerCategory);
workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(ToggleSharedProcessAction, ToggleSharedProcessAction.ID, ToggleSharedProcessAction.LABEL), 'Developer: Toggle Shared Process', developerCategory);
// Configuration: Workbench
const configurationRegistry = Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration);
let workbenchProperties: { [path: string]: IJSONSchema; } = {
'workbench.editor.showTabs': {
'type': 'boolean',
'description': nls.localize('showEditorTabs', "Controls if opened editors should show in tabs or not."),
'default': true
},
'workbench.editor.tabCloseButton': {
'type': 'string',
'enum': ['left', 'right', 'off'],
'default': 'right',
'description': nls.localize({ comment: ['This is the description for a setting. Values surrounded by single quotes are not to be translated.'], key: 'editorTabCloseButton' }, "Controls the position of the editor's tabs close buttons or disables them when set to 'off'.")
},
'workbench.editor.showIcons': {
'type': 'boolean',
'description': nls.localize('showIcons', "Controls if opened editors should show with an icon or not. This requires an icon theme to be enabled as well."),
'default': true
},
'workbench.editor.enablePreview': {
'type': 'boolean',
'description': nls.localize('enablePreview', "Controls if opened editors show as preview. Preview editors are reused until they are kept (e.g. via double click or editing)."),
'default': true
},
'workbench.editor.enablePreviewFromQuickOpen': {
'type': 'boolean',
'description': nls.localize('enablePreviewFromQuickOpen', "Controls if opened editors from Quick Open show as preview. Preview editors are reused until they are kept (e.g. via double click or editing)."),
'default': true
},
'workbench.editor.openPositioning': {
'type': 'string',
'enum': ['left', 'right', 'first', 'last'],
'default': 'right',
'description': nls.localize({ comment: ['This is the description for a setting. Values surrounded by single quotes are not to be translated.'], key: 'editorOpenPositioning' }, "Controls where editors open. Select 'left' or 'right' to open editors to the left or right of the current active one. Select 'first' or 'last' to open editors independently from the currently active one.")
},
'workbench.editor.revealIfOpen': {
'type': 'boolean',
'description': nls.localize('revealIfOpen', "Controls if an editor is revealed in any of the visible groups if opened. If disabled, an editor will prefer to open in the currently active editor group. If enabled, an already opened editor will be revealed instead of opened again in the currently active editor group. Note that there are some cases where this setting is ignored, e.g. when forcing an editor to open in a specific group or to the side of the currently active group."),
'default': false
},
'workbench.quickOpen.closeOnFocusLost': {
'type': 'boolean',
'description': nls.localize('closeOnFocusLost', "Controls if Quick Open should close automatically once it loses focus."),
'default': true
},
'workbench.settings.openDefaultSettings': {
'type': 'boolean',
'description': nls.localize('openDefaultSettings', "Controls if opening settings also opens an editor showing all default settings."),
'default': true
},
'workbench.sideBar.location': {
'type': 'string',
'enum': ['left', 'right'],
'default': 'left',
'description': nls.localize('sideBarLocation', "Controls the location of the sidebar. It can either show on the left or right of the workbench.")
},
'workbench.statusBar.visible': {
'type': 'boolean',
'default': true,
'description': nls.localize('statusBarVisibility', "Controls the visibility of the status bar at the bottom of the workbench.")
},
'workbench.activityBar.visible': {
'type': 'boolean',
'default': true,
'description': nls.localize('activityBarVisibility', "Controls the visibility of the activity bar in the workbench.")
},
'workbench.editor.closeOnFileDelete': {
'type': 'boolean',
'description': nls.localize('closeOnFileDelete', "Controls if editors showing a file should close automatically when the file is deleted or renamed by some other process. Disabling this will keep the editor open as dirty on such an event. Note that deleting from within the application will always close the editor and that dirty files will never close to preserve your data."),
'default': true
}
};
if (isMacintosh) {
workbenchProperties['workbench.editor.swipeToNavigate'] = {
'type': 'boolean',
'description': nls.localize('swipeToNavigate', "Navigate between open files using three-finger swipe horizontally."),
'default': false
};
}
configurationRegistry.registerConfiguration({
'id': 'workbench',
'order': 7,
'title': nls.localize('workbenchConfigurationTitle', "Workbench"),
'type': 'object',
'properties': workbenchProperties
});
// Configuration: Window
let properties: { [path: string]: IJSONSchema; } = {
'window.openFilesInNewWindow': {
'type': 'string',
'enum': ['on', 'off', 'default'],
'enumDescriptions': [
nls.localize({ comment: ['This is the description for a setting. Values surrounded by single quotes are not to be translated.'], key: 'window.openFilesInNewWindow.on' }, "Files will open in a new window"),
nls.localize({ comment: ['This is the description for a setting. Values surrounded by single quotes are not to be translated.'], key: 'window.openFilesInNewWindow.off' }, "Files will open in the window with the files' folder open or the last active window"),
nls.localize({ comment: ['This is the description for a setting. Values surrounded by single quotes are not to be translated.'], key: 'window.openFilesInNewWindow.default' }, "Files will open in the window with the files' folder open or the last active window unless opened via the dock or from finder (macOS only)")
],
'default': 'default',
'description':
nls.localize('openFilesInNewWindow',
`Controls if files should open in a new window.
- default: files will open in the window with the files' folder open or the last active window unless opened via the dock or from finder (macOS only)
- on: files will open in a new window
- off: files will open in the window with the files' folder open or the last active window
Note that there can still be cases where this setting is ignored (e.g. when using the -new-window or -reuse-window command line option).`
)
},
'window.openFoldersInNewWindow': {
'type': 'string',
'enum': ['on', 'off', 'default'],
'enumDescriptions': [
nls.localize({ comment: ['This is the description for a setting. Values surrounded by single quotes are not to be translated.'], key: 'window.openFoldersInNewWindow.on' }, "Folders will open in a new window"),
nls.localize({ comment: ['This is the description for a setting. Values surrounded by single quotes are not to be translated.'], key: 'window.openFoldersInNewWindow.off' }, "Folders will replace the last active window"),
nls.localize({ comment: ['This is the description for a setting. Values surrounded by single quotes are not to be translated.'], key: 'window.openFoldersInNewWindow.default' }, "Folders will open in a new window unless a folder is picked from within the application (e.g. via the File menu)")
],
'default': 'default',
'description': nls.localize('openFoldersInNewWindow',
`Controls if folders should open in a new window or replace the last active window.
- default: folders will open in a new window unless a folder is picked from within the application (e.g. via the File menu)
- on: folders will open in a new window
- off: folders will replace the last active window
Note that there can still be cases where this setting is ignored (e.g. when using the -new-window or -reuse-window command line option).`
)
},
'window.reopenFolders': {
'type': 'string',
'enum': ['none', 'one', 'all'],
'enumDescriptions': [
nls.localize({ comment: ['This is the description for a setting. Values surrounded by single quotes are not to be translated.'], key: 'window.reopenFolders.none' }, "Never reopen a folder."),
nls.localize({ comment: ['This is the description for a setting. Values surrounded by single quotes are not to be translated.'], key: 'window.reopenFolders.one' }, "Reopen the last active folder."),
nls.localize({ comment: ['This is the description for a setting. Values surrounded by single quotes are not to be translated.'], key: 'window.reopenFolders.all' }, "Reopen all folders of the last session."),
],
'default': 'one',
'description': nls.localize('reopenFolders', "Controls how folders are being reopened after a restart. Select 'none' to never reopen a folder, 'one' to reopen the last folder you worked on or 'all' to reopen all folders of your last session.")
},
'window.restoreFullscreen': {
'type': 'boolean',
'default': false,
'description': nls.localize('restoreFullscreen', "Controls if a window should restore to full screen mode if it was exited in full screen mode.")
},
'window.zoomLevel': {
'type': 'number',
'default': 0,
'description': nls.localize('zoomLevel', "Adjust the zoom level of the window. The original size is 0 and each increment above (e.g. 1) or below (e.g. -1) represents zooming 20% larger or smaller. You can also enter decimals to adjust the zoom level with a finer granularity.")
},
'window.title': {
'type': 'string',
'default': isMacintosh ? '${activeEditorShort}${separator}${rootName}' : '${dirty}${activeEditorShort}${separator}${rootName}${separator}${appName}',
'description': nls.localize({ comment: ['This is the description for a setting. Values surrounded by parenthesis are not to be translated.'], key: 'title' },
`Controls the window title based on the active editor. Variables are substituted based on the context:
\${activeEditorShort}: e.g. myFile.txt
\${activeEditorMedium}: e.g. myFolder/myFile.txt
\${activeEditorLong}: e.g. /Users/Development/myProject/myFolder/myFile.txt
\${rootName}: e.g. myProject
\${rootPath}: e.g. /Users/Development/myProject
\${appName}: e.g. VS Code
\${dirty}: a dirty indicator if the active editor is dirty
\${separator}: a conditional separator (" - ") that only shows when surrounded by variables with values`)
},
'window.newWindowDimensions': {
'type': 'string',
'enum': ['default', 'inherit', 'maximized', 'fullscreen'],
'enumDescriptions': [
nls.localize({ comment: ['This is the description for a setting. Values surrounded by single quotes are not to be translated.'], key: 'window.newWindowDimensions.default' }, "Open new windows in the center of the screen."),
nls.localize({ comment: ['This is the description for a setting. Values surrounded by single quotes are not to be translated.'], key: 'window.newWindowDimensions.inherit' }, "Open new windows with same dimension as last active one."),
nls.localize({ comment: ['This is the description for a setting. Values surrounded by single quotes are not to be translated.'], key: 'window.newWindowDimensions.maximized' }, "Open new windows maximized."),
nls.localize({ comment: ['This is the description for a setting. Values surrounded by single quotes are not to be translated.'], key: 'window.newWindowDimensions.fullscreen' }, "Open new windows in full screen mode.")
],
'default': 'default',
'description': nls.localize('newWindowDimensions', "Controls the dimensions of opening a new window when at least one window is already opened. By default, a new window will open in the center of the screen with small dimensions. When set to 'inherit', the window will get the same dimensions as the last window that was active. When set to 'maximized', the window will open maximized and fullscreen if configured to 'fullscreen'. Note that this setting does not have an impact on the first window that is opened. The first window will always restore the size and location as you left it before closing.")
},
};
if (isWindows || isLinux) {
properties['window.menuBarVisibility'] = {
'type': 'string',
'enum': ['default', 'visible', 'toggle', 'hidden'],
'enumDescriptions': [
nls.localize({ comment: ['This is the description for a setting. Values surrounded by single quotes are not to be translated.'], key: 'window.menuBarVisibility.default' }, "Menu is only hidden in full screen mode."),
nls.localize({ comment: ['This is the description for a setting. Values surrounded by single quotes are not to be translated.'], key: 'window.menuBarVisibility.visible' }, "Menu is always visible even in full screen mode."),
nls.localize({ comment: ['This is the description for a setting. Values surrounded by single quotes are not to be translated.'], key: 'window.menuBarVisibility.toggle' }, "Menu is hidden but can be displayed via Alt key."),
nls.localize({ comment: ['This is the description for a setting. Values surrounded by single quotes are not to be translated.'], key: 'window.menuBarVisibility.hidden' }, "Menu is always hidden.")
],
'default': 'default',
'description': nls.localize('menuBarVisibility', "Control the visibility of the menu bar. A setting of 'toggle' means that the menu bar is hidden and a single press of the Alt key will show it. By default, the menu bar will be visible, unless the window is full screen.")
};
properties['window.enableMenuBarMnemonics'] = {
'type': 'boolean',
'default': true,
'description': nls.localize('enableMenuBarMnemonics', "If enabled, the main menus can be opened via Alt-key shortcuts. Disabling mnemonics allows to bind these Alt-key shortcuts to editor commands instead.")
};
}
if (isWindows) {
properties['window.autoDetectHighContrast'] = {
'type': 'boolean',
'default': true,
'description': nls.localize('autoDetectHighContrast', "If enabled, will automatically change to high contrast theme if Windows is using a high contrast theme, and to dark theme when switching away from a Windows high contrast theme."),
};
}
if (isMacintosh) {
properties['window.titleBarStyle'] = {
'type': 'string',
'enum': ['native', 'custom'],
'default': 'custom',
'description': nls.localize('titleBarStyle', "Adjust the appearance of the window title bar. Changes require a full restart to apply.")
};
// macOS Sierra (10.12.x = darwin 16.x) and electron > 1.4.6 only
if (os.release().indexOf('16.') === 0 && process.versions.electron !== '1.4.6') {
properties['window.nativeTabs'] = {
'type': 'boolean',
'default': false,
'description': nls.localize('window.nativeTabs', "Enables macOS Sierra window tabs. Note that changes require a full restart to apply and that native tabs will disable a custom title bar style if configured.")
};
}
}
configurationRegistry.registerConfiguration({
'id': 'window',
'order': 8,
'title': nls.localize('windowConfigurationTitle', "Window"),
'type': 'object',
'properties': properties
});
// Configuration: Zen Mode
configurationRegistry.registerConfiguration({
'id': 'zenMode',
'order': 9,
'title': nls.localize('zenModeConfigurationTitle', "Zen Mode"),
'type': 'object',
'properties': {
'zenMode.fullScreen': {
'type': 'boolean',
'default': true,
'description': nls.localize('zenMode.fullScreen', "Controls if turning on Zen Mode also puts the workbench into full screen mode.")
},
'zenMode.hideTabs': {
'type': 'boolean',
'default': true,
'description': nls.localize('zenMode.hideTabs', "Controls if turning on Zen Mode also hides workbench tabs.")
},
'zenMode.hideStatusBar': {
'type': 'boolean',
'default': true,
'description': nls.localize('zenMode.hideStatusBar', "Controls if turning on Zen Mode also hides the status bar at the bottom of the workbench.")
},
'zenMode.hideActivityBar': {
'type': 'boolean',
'default': true,
'description': nls.localize('zenMode.hideActivityBar', "Controls if turning on Zen Mode also hides the activity bar at the left of the workbench.")
},
'zenMode.restore': {
'type': 'boolean',
'default': false,
'description': nls.localize('zenMode.restore', "Controls if a window should restore to zen mode if it was exited in zen mode.")
}
}
});
| radshit/vscode | src/vs/workbench/electron-browser/main.contribution.ts | TypeScript | mit | 23,948 |
using System;
using System.Drawing;
namespace Gwen.Control.Layout
{
/// <summary>
/// Single table row.
/// </summary>
public class TableRow : Base
{
// [omeg] todo: get rid of this
public const int MaxColumns = 5;
private int m_ColumnCount;
private bool m_EvenRow;
private readonly Label[] m_Columns;
internal Label GetColumn(int index)
{
return m_Columns[index];
}
/// <summary>
/// Invoked when the row has been selected.
/// </summary>
public event GwenEventHandler<ItemSelectedEventArgs> Selected;
/// <summary>
/// Column count.
/// </summary>
public int ColumnCount { get { return m_ColumnCount; } set { SetColumnCount(value); } }
/// <summary>
/// Indicates whether the row is even or odd (used for alternate coloring).
/// </summary>
public bool EvenRow { get { return m_EvenRow; } set { m_EvenRow = value; } }
/// <summary>
/// Text of the first column.
/// </summary>
public string Text { get { return GetText(0); } set { SetCellText(0, value); } }
/// <summary>
/// Initializes a new instance of the <see cref="TableRow"/> class.
/// </summary>
/// <param name="parent">Parent control.</param>
public TableRow(Base parent)
: base(parent)
{
m_Columns = new Label[MaxColumns];
m_ColumnCount = 0;
KeyboardInputEnabled = true;
}
/// <summary>
/// Sets the number of columns.
/// </summary>
/// <param name="columnCount">Number of columns.</param>
protected void SetColumnCount(int columnCount)
{
if (columnCount == m_ColumnCount) return;
if (columnCount >= MaxColumns)
throw new ArgumentException("Invalid column count", "columnCount");
for (int i = 0; i < MaxColumns; i++)
{
if (i < columnCount)
{
if (null == m_Columns[i])
{
m_Columns[i] = new Label(this);
m_Columns[i].Padding = Padding.Three;
m_Columns[i].Margin = new Margin(0, 0, 2, 0); // to separate them slightly
if (i == columnCount - 1)
{
// last column fills remaining space
m_Columns[i].Dock = Pos.Fill;
}
else
{
m_Columns[i].Dock = Pos.Left;
}
}
}
else if (null != m_Columns[i])
{
RemoveChild(m_Columns[i], true);
m_Columns[i] = null;
}
m_ColumnCount = columnCount;
}
}
/// <summary>
/// Sets the column width (in pixels).
/// </summary>
/// <param name="column">Column index.</param>
/// <param name="width">Column width.</param>
public void SetColumnWidth(int column, int width)
{
if (null == m_Columns[column])
return;
if (m_Columns[column].Width == width)
return;
m_Columns[column].Width = width;
}
/// <summary>
/// Sets the text of a specified cell.
/// </summary>
/// <param name="column">Column number.</param>
/// <param name="text">Text to set.</param>
public void SetCellText(int column, string text)
{
if (null == m_Columns[column])
return;
m_Columns[column].Text = text;
}
/// <summary>
/// Sets the contents of a specified cell.
/// </summary>
/// <param name="column">Column number.</param>
/// <param name="control">Cell contents.</param>
/// <param name="enableMouseInput">Determines whether mouse input should be enabled for the cell.</param>
public void SetCellContents(int column, Base control, bool enableMouseInput = false)
{
if (null == m_Columns[column])
return;
control.Parent = m_Columns[column];
m_Columns[column].MouseInputEnabled = enableMouseInput;
}
/// <summary>
/// Gets the contents of a specified cell.
/// </summary>
/// <param name="column">Column number.</param>
/// <returns>Control embedded in the cell.</returns>
public Base GetCellContents(int column)
{
return m_Columns[column];
}
protected virtual void OnRowSelected()
{
if (Selected != null)
Selected.Invoke(this, new ItemSelectedEventArgs(this));
}
/// <summary>
/// Sizes all cells to fit contents.
/// </summary>
public void SizeToContents()
{
int width = 0;
int height = 0;
for (int i = 0; i < m_ColumnCount; i++)
{
if (null == m_Columns[i])
continue;
// Note, more than 1 child here, because the
// label has a child built in ( The Text )
if (m_Columns[i].Children.Count > 1)
{
m_Columns[i].SizeToChildren();
}
else
{
m_Columns[i].SizeToContents();
}
//if (i == m_ColumnCount - 1) // last column
// m_Columns[i].Width = Parent.Width - width; // fill if not autosized
width += m_Columns[i].Width + m_Columns[i].Margin.Left + m_Columns[i].Margin.Right;
height = Math.Max(height, m_Columns[i].Height + m_Columns[i].Margin.Top + m_Columns[i].Margin.Bottom);
}
SetSize(width, height);
}
/// <summary>
/// Sets the text color for all cells.
/// </summary>
/// <param name="color">Text color.</param>
public void SetTextColor(Color color)
{
for (int i = 0; i < m_ColumnCount; i++)
{
if (null == m_Columns[i]) continue;
m_Columns[i].TextColor = color;
}
}
/// <summary>
/// Returns text of a specified row cell (default first).
/// </summary>
/// <param name="column">Column index.</param>
/// <returns>Column cell text.</returns>
public string GetText(int column = 0)
{
return m_Columns[column].Text;
}
/// <summary>
/// Handler for Copy event.
/// </summary>
/// <param name="from">Source control.</param>
protected override void OnCopy(Base from, EventArgs args)
{
Platform.Neutral.SetClipboardText(Text);
}
}
}
| BreyerW/Sharp.Engine | Gwen/Control/Layout/TableRow.cs | C# | mit | 7,144 |
package mcjty.rftools.items.dimlets;
import java.util.HashMap;
import java.util.Map;
public class DimletCosts {
static final Map<DimletKey,Integer> dimletBuiltinRfCreate = new HashMap<DimletKey, Integer>();
static final Map<DimletKey,Integer> dimletBuiltinRfMaintain = new HashMap<DimletKey, Integer>();
static final Map<DimletKey,Integer> dimletBuiltinTickCost = new HashMap<DimletKey, Integer>();
public static int baseDimensionCreationCost = 1000;
public static int baseDimensionMaintenanceCost = 10;
public static int baseDimensionTickCost = 100;
}
| Elecs-Mods/RFTools | src/main/java/mcjty/rftools/items/dimlets/DimletCosts.java | Java | mit | 580 |
package com.example.conami.dokimemo;
public final class UserModel {
private static int id = 1;
private static String name = "user1";
private static int coupleId = 1;
private static int partnarId = 3;
private UserModel() {}
private void setId(int id) {
this.id = id;
}
private void setName(String name) {
this.name = name;
}
private void setCoupleId(int coupleId) {
this.coupleId = coupleId;
}
private void setPartnarId(int partnarId) {
this.partnarId = partnarId;
}
public static int getId() {
return id;
}
public static String getName() {
return name;
}
public static int getCoupleId() {
return coupleId;
}
public static int getPartnarId() {
return partnarId;
}
}
| shimomo/dokidoki-memorial | client/app/src/main/java/com/example/conami/dokimemo/UserModel.java | Java | mit | 823 |
import baseCallback from '../internal/baseCallback';
import basePullAt from '../internal/basePullAt';
/**
* Removes all elements from `array` that `predicate` returns truthy for
* and returns an array of the removed elements. The predicate is bound to
* `thisArg` and invoked with three arguments: (value, index, array).
*
* If a property name is provided for `predicate` the created `_.property`
* style callback returns the property value of the given element.
*
* If a value is also provided for `thisArg` the created `_.matchesProperty`
* style callback returns `true` for elements that have a matching property
* value, else `false`.
*
* If an object is provided for `predicate` the created `_.matches` style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* **Note:** Unlike `_.filter`, this method mutates `array`.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to modify.
* @param {Function|Object|string} [predicate=_.identity] The function invoked
* per iteration.
* @param {*} [thisArg] The `this` binding of `predicate`.
* @returns {Array} Returns the new array of removed elements.
* @example
*
* var array = [1, 2, 3, 4];
* var evens = _.remove(array, function(n) {
* return n % 2 == 0;
* });
*
* console.log(array);
* // => [1, 3]
*
* console.log(evens);
* // => [2, 4]
*/
function remove(array, predicate, thisArg) {
var result = [];
if (!(array && array.length)) {
return result;
}
var index = -1,
indexes = [],
length = array.length;
predicate = baseCallback(predicate, thisArg, 3);
while (++index < length) {
var value = array[index];
if (predicate(value, index, array)) {
result.push(value);
indexes.push(index);
}
}
basePullAt(array, indexes);
return result;
}
export default remove;
| heavyk/affinaty | src/lib/lodash/array/remove.js | JavaScript | mit | 1,892 |
<?php
session_start();
header('Access-Control-Allow-Origin: *');
if (isset($_SESSION['token'])) {
$token=$_SESSION['token'];
$servername = "localhost";
$username = "root";
$password = "sAhArAnTech1Kriti16";
$conn = new mysqli($servername, $username, $password);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
mysqli_set_charset($conn, 'utf8');
$sql = "USE events";
if ($conn->query($sql) === TRUE) {
} else {
}
$id=0;
$sql="SELECT * FROM `users17` WHERE confirm_token='$token'";
$result=$conn->query($sql);
while ($row = mysqli_fetch_array($result)) {
$id = $row["id"];
}
$sql="SELECT * FROM `group_info` WHERE tech_ids='$id'";
$result=$conn->query($sql);
$response["products"] = array();
while ($row = mysqli_fetch_array($result)) {
$group_id = $row["group_id"];
$sql="SELECT * FROM `groups_17` WHERE id=$group_id";
$result1=$conn->query($sql);
while ($row1 = mysqli_fetch_array($result1)) {
$product = array();
$product["competition"] = $row1["competition"];
$product["members"] = $row1["members"];
$members=$product["members"];
$myArray = explode(',', $members);
$final_name="";
$t=0;
for($k=0;$k<sizeof($myArray);$k=$k+1)
{
$mem_id=$myArray[$k];
$mem_id=(int)$mem_id;
$sql="SELECT * FROM `users17` WHERE id=$mem_id";
$result3=$conn->query($sql);
while ($row3 = mysqli_fetch_array($result3)) {
$mem_name=$row3['name'];
}
if($k==0)
{
$final_name=$mem_name;
}
else
{
$final_name=$final_name.",".$mem_name;
}
}
$product["names"] = $final_name;
array_push($response["products"], $product);
}
}
}
else
{
$response='false';
}
echo json_encode($response['products']);
?>
| subhdeep/Techkriti-17-Beta | zonals_old/profile.php | PHP | mit | 1,673 |
# coding: utf-8
require 'spec_helper'
describe ActiveInteraction::TimeFilter, :filter do
include_context 'filters'
it_behaves_like 'a filter'
shared_context 'with format' do
let(:format) { '%d/%m/%Y %H:%M:%S %z' }
before do
options.merge!(format: format)
end
end
describe '#initialize' do
context 'with a format' do
before { options[:format] = '%T' }
context 'with a time zone' do
before do
time_zone = double
allow(Time).to receive(:zone).and_return(time_zone)
time_with_zone = double
allow(time_zone).to receive(:at).and_return(time_with_zone)
end
it 'raises an error' do
expect do
filter
end.to raise_error(ActiveInteraction::InvalidFilterError)
end
end
end
end
describe '#cast' do
let(:result) { filter.cast(value) }
context 'with a Time' do
let(:value) { Time.new }
it 'returns the Time' do
expect(result).to eql value
end
end
context 'with a String' do
let(:value) { '2011-12-13 14:15:16 +1718' }
it 'returns a Time' do
expect(result).to eql Time.parse(value)
end
context 'with format' do
include_context 'with format'
let(:value) { '13/12/2011 14:15:16 +1718' }
it 'returns a Time' do
expect(result).to eql Time.strptime(value, format)
end
end
end
context 'with an invalid String' do
let(:value) { 'invalid' }
it 'raises an error' do
expect do
result
end.to raise_error ActiveInteraction::InvalidValueError
end
context 'with format' do
include_context 'with format'
it do
expect do
result
end.to raise_error ActiveInteraction::InvalidValueError
end
end
end
context 'with a GroupedInput' do
let(:year) { 2012 }
let(:month) { 1 }
let(:day) { 2 }
let(:hour) { 3 }
let(:min) { 4 }
let(:sec) { 5 }
let(:value) do
ActiveInteraction::GroupedInput.new(
'1' => year.to_s,
'2' => month.to_s,
'3' => day.to_s,
'4' => hour.to_s,
'5' => min.to_s,
'6' => sec.to_s
)
end
it 'returns a Time' do
expect(
result
).to eql Time.new(year, month, day, hour, min, sec)
end
end
context 'with an invalid GroupedInput' do
context 'empty' do
let(:value) { ActiveInteraction::GroupedInput.new }
it 'raises an error' do
expect do
result
end.to raise_error ActiveInteraction::InvalidValueError
end
end
context 'partial inputs' do
let(:value) do
ActiveInteraction::GroupedInput.new(
'2' => '1'
)
end
it 'raises an error' do
expect do
result
end.to raise_error ActiveInteraction::InvalidValueError
end
end
end
end
describe '#database_column_type' do
it 'returns :datetime' do
expect(filter.database_column_type).to eql :datetime
end
end
describe '#default' do
context 'with a GroupedInput' do
before do
options.merge!(
default: ActiveInteraction::GroupedInput.new(
'1' => '2012',
'2' => '1',
'3' => '2',
'4' => '3',
'5' => '4',
'6' => '5'
)
)
end
it 'raises an error' do
expect do
filter.default
end.to raise_error ActiveInteraction::InvalidDefaultError
end
end
end
end
| JasOXIII/active_interaction | spec/active_interaction/filters/time_filter_spec.rb | Ruby | mit | 3,726 |
var roundTrip = module.exports = require('azure-mobile-apps').table();
roundTrip.update(function (context) {
return context.execute()
.catch(function (error) {
if(context.req.query.conflictPolicy === 'clientWins') {
context.item.version = error.item.version;
return context.execute();
} else if (context.req.query.conflictPolicy === 'serverWins') {
return error.item;
} else {
throw error;
}
});
});
roundTrip.columns = { name: 'string', date1: 'date', bool: 'boolean', integer: 'number', number: 'number' };
roundTrip.dynamicSchema = false;
| shrishrirang/azure-mobile-apps-node | e2etest/tables/roundTripTable.js | JavaScript | mit | 675 |
module Timeline {
declare var vis;
export interface ITimelineScope extends ng.IScope {
vm: TimelineCtrl;
numberOfItems: number;
timeline: any;
datePickerOptions: any;
datePickerDate: Date;
}
/** Interface for the timeline configuration, may be part of the {csComp.Services.IFeatureType} or {csComp.Services.IProjectLayer}. */
export interface ITimelineConfig {
/** Group (row/lane) to use */
group?: string;
/** Property to use as the group (row/lane) */
groupProperty?: string;
/** CSS class to use for the group */
groupClass?: string;
/** Property to use as the CSS class for the group */
groupClassProperty?: string;
/** CSS class to use for the timeline item */
class?: string;
/** Property to use as the CSS class for the timeline item */
classProperty?: string;
/** Property that contains the start time (as stringified Date) */
startTimeProperty?: string;
/** Property that contains the end time (as stringified Date) */
endTimeProperty?: string;
/** Property that contains the content (text that appears inside the timeline item) */
contentProperty?: string;
}
/** Interface for every group and timeline item. */
export interface ITimelineItem {
/** Feature ID */
id?: any;
/** Layer ID */
layerId?: string;
/** Content to show in the timeline item (html or string) */
content?: string;
/** Start time */
start?: Date;
/** End time */
end?: Date;
group?: string;
/** CSS group class name */
groupClass?: string;
/** CSS timeline item class name */
className?: string;
}
/** Interface to talk to the timeline items in the timeline, of type vis.DataSet. */
export interface IDataSet {
/** Add one or more timeline items. */
add(items: ITimelineItem | ITimelineItem[]);
/** Removes an item from the timeline. */
remove(items: ITimelineItem | ITimelineItem[]);
/** Returns the ids of all timeline items. */
getIds(): string[];
/** Get all timeline items. */
get(): ITimelineItem[];
/** Clears the timeline items. */
clear();
forEach(calback: (item: ITimelineItem) => void);
}
export class TimelineCtrl {
private scope: ITimelineScope;
private locale = 'en-us';
private timelineGroups: IDataSet = new vis.DataSet();
/** Holds the timeline items, is databound to the timeline. */
private timelineItems: IDataSet = new vis.DataSet();
// $inject annotation.
// It provides $injector with information about dependencies to be injected into constructor
// it is better to have it close to the constructor, because the parameters must match in count and type.
// See http://docs.angularjs.org/guide/di
public static $inject = [
'$scope',
'layerService',
'mapService',
'messageBusService',
'TimelineService'
];
public focusDate: Date;
public line1: string;
public line2: string;
public startDate: Date;
public endDate: Date;
public timer: any;
public isPlaying: boolean;
public showControl: boolean;
public isPinned: boolean = true;
public activeDateRange: csComp.Services.DateRange;
public options: any;
public expandButtonBottom = 52;
public datePickerBottom = 120;
public items = new vis.DataSet();
private debounceUpdate: Function;
private debounceSetItems: Function;
private ids: string[] = [];
// dependencies are injected via AngularJS $injector
// controller's name is registered in Application.ts and specified from ng-controller attribute in index.html
constructor(
private $scope: ITimelineScope,
private $layerService: csComp.Services.LayerService,
private $mapService: csComp.Services.MapService,
private $messageBusService: csComp.Services.MessageBusService,
private TimelineService: Timeline.ITimelineService
) {
this.loadLocales();
this.options = {
'width': '100%',
'editable': false,
'margin': 0,
'height': 54,
'moveable': false,
'zoomMax': 172800000000,
'zoomMin': 3600000
//'layout': 'box'
};
this.debounceUpdate = _.debounce(this.updateFeatures, 500);
this.debounceSetItems = _.debounce((items) => { this.addItems(items); }, 500);
$scope.$watch("datePickerDate", (d: string) => {
if (typeof d !== 'undefined') {
var date = new Date(d);
this.updateTimeline(date, new Date(date.getTime() + 1000 * 60 * 60 * 24));
}
})
$scope.vm = this;
$scope.datePickerOptions = {
customClass: this.getDayClass,
minDate: new Date(2015, 1, 1),
maxDate: new Date()
};
this.$messageBusService.subscribe('dashboard-main', (s: string, data: any) => {
if (s === 'activated') {
this.updatePanelHeights();
this.updateTimelineHeight();
}
});
this.$messageBusService.subscribe('project', (s: string, data: any) => {
setTimeout(() => {
this.$scope.timeline.setItems(this.timelineItems);
this.$scope.timeline.setGroups(this.timelineGroups);
// set min/max zoom levels if available
if (this.activeDateRange !== null) {
if (!_.isUndefined(this.activeDateRange.zoomMax)) this.$scope.timeline.options['zoomMax'] = this.activeDateRange.zoomMax;
if (!_.isUndefined(this.activeDateRange.zoomMin)) this.$scope.timeline.options['zoomMin'] = this.activeDateRange.zoomMin;
}
this.updateFocusTime();
this.updateDragging();
this.myTimer();
if (this.activeDateRange && this.activeDateRange.isLive) this.goLive();
}, 0);
});
this.initTimeline();
this.$messageBusService.subscribe('timeline', (s: string, data: any) => { this.update(s, data); });
this.$messageBusService.subscribe('feature', (s: string, feature: csComp.Services.IFeature) => {
if (s === 'onFeatureSelect' && feature) {
if (this.ids.indexOf(feature.id) !== -1) {
this.$scope.timeline.setSelection(feature.id);
}
}
});
//$scope.focusDate = $layerService.project.timeLine.focusDate();
// Options for the timeline
this.$messageBusService.subscribe('language', (s: string, newLanguage: string) => {
switch (s) {
case 'newLanguage':
this.initTimeline();
break;
}
});
this.$messageBusService.subscribe('layer', (title: string, layer: csComp.Services.IProjectLayer) => {
switch (title) {
case 'timelineUpdated':
this.addTimelineItemsInLayer(layer);
break;
case 'activated':
this.addTimelineItemsInLayer(layer);
break;
case 'deactivate':
this.removeTimelineItemsInLayer(layer);
break;
}
});
}
public updateTimeline(start: Date, end: Date) {
var d = this.$layerService.project.activeDashboard;
if (d.showTimeline && (d.timeline || this.$layerService.project.timeLine)) {
//console.log('checkTimeline: dashboard has timeline');
var t = (d.timeline) ? d.timeline : this.$layerService.project.timeLine;
t.start = start.getTime();
t.end = end.getTime();
this.$messageBusService.publish('timeline', 'updateTimerange', t);
}
}
private getDayClass(data) {
var date = data.date,
mode = data.mode;
if (mode === 'day') {
var dayToCheck = new Date(date).setHours(0, 0, 0, 0);
}
return '';
}
/** Check whether the layer contains timeline items, and if so, add them to the timeline. */
private addTimelineItemsInLayer(layer: csComp.Services.IProjectLayer) {
if (!layer.timeAware || !layer.data || !layer.data.features) return;
var layerConfig = layer.timelineConfig;
var items: ITimelineItem[] = [];
layer.data.features.forEach((f: csComp.Services.IFeature) => {
let props = f.properties;
let featureConfig = f.fType.timelineConfig;
if (!featureConfig && !layerConfig) return;
let classProp = (featureConfig && featureConfig.classProperty) || (layerConfig && layerConfig.classProperty);
let groupClassProp = (featureConfig && featureConfig.groupClassProperty) || (layerConfig && layerConfig.groupClassProperty);
let contentProp = (featureConfig && featureConfig.contentProperty) || (layerConfig && layerConfig.contentProperty);
let startProp = (featureConfig && featureConfig.startTimeProperty) || (layerConfig && layerConfig.startTimeProperty);
let endProp = (featureConfig && featureConfig.endTimeProperty) || (layerConfig && layerConfig.endTimeProperty);
let groupProp = (featureConfig && featureConfig.groupProperty) || (layerConfig && layerConfig.groupProperty);
let timelineItem = <ITimelineItem>{
id: f.id,
layerId: layer.id,
className: props.hasOwnProperty(classProp) ? props[classProp] : (featureConfig && featureConfig.class) || (layerConfig && layerConfig.class),
groupClass: props.hasOwnProperty(groupClassProp) ? props[groupClassProp] : (featureConfig && featureConfig.groupClass) || (layerConfig && layerConfig.groupClass),
group: props.hasOwnProperty(groupProp) ? props[groupProp] : (featureConfig && featureConfig.group) || (layerConfig && layerConfig.group) || '',
start: props.hasOwnProperty(startProp) ? props[startProp] : null,
end: props.hasOwnProperty(endProp) ? props[endProp] : null,
type: props.hasOwnProperty('type') ? props['type'] : null,
content: props.hasOwnProperty(contentProp) ? props[contentProp] : ''
};
if (timelineItem.start) items.push(timelineItem);
});
this.addItems(items);
}
/** Remove all timeline items that could be found in this layer. */
private removeTimelineItemsInLayer(layer) {
if (!layer.timeAware || !layer.data || !layer.data.features) return;
var deleteItems: ITimelineItem[] = [];
this.timelineItems.forEach(item => {
if (item.layerId !== layer.id) return;
deleteItems.push(item);
});
this.deleteItems(deleteItems);
}
/** Update the groups, most likely after certain items have been added or deleted */
private updateGroups() {
this.timelineGroups.clear();
var groups: string[] = [];
this.timelineItems.forEach(item => {
if (groups.indexOf(item.group) >= 0) return;
groups.push(item.group);
this.timelineGroups.add(<ITimelineItem>{
className: item.groupClass,
content: item.group,
id: item.group,
title: item.group
});
});
}
private update(s, data) {
switch (s) {
case 'updateTimerange':
this.$scope.timeline.setWindow(data.start, data.end);
this.updateFocusTime();
break;
case 'loadProjectTimeRange':
if (typeof this.$layerService.project === 'undefined'
|| this.$layerService.project === null
|| typeof this.$layerService.project.timeLine === 'undefined'
|| this.$layerService.project.timeLine === null) return;
this.$scope.timeline.setWindow(this.$layerService.project.timeLine.start, this.$layerService.project.timeLine.end);
this.updateFocusTime();
break;
case 'setFocus':
this.setFocusContainerDebounce(data);
break;
case 'updateFeatures':
this.debounceUpdate();
break;
case 'setItems':
this.debounceSetItems(data);
break;
case 'setGroups':
this.setGroups(data);
break;
}
}
private setFocusContainerDebounce = _.debounce((data) => {
this.updateFocusTimeContainer(data);
//console.log(`Moved timeline and focuscontainer to ${data}`);
}, 300, true);
private addItems(items: ITimelineItem[]) {
if (!items) return;
let its = [];
items.forEach(i => {
if (this.timelineItems.getIds().indexOf(i.id) === -1) its.push(i);
});
this.timelineItems.add(its);
this.updateGroups();
}
private deleteItems(items: ITimelineItem[]) {
if (!items) return;
this.timelineItems.remove(items);
this.updateGroups();
}
private setGroups(groups: ITimelineItem[]) {
if (!groups || groups.length === 1) return;
this.timelineGroups.add(groups);
//var gs = new vis.DataSet(groups);
//this.$scope.timeline.setGroups(gs);
}
private updateFeatures() {
//console.log('timeline: updating features');
//this.items = [];
//this.$scope.timeline.redraw();
var temp: string[] = [];
var hasChanged = false;
// check for new items
this.$layerService.project.features.forEach((f: csComp.Services.IFeature) => {
hasChanged = true;
if (f.layer.showOnTimeline && f.properties.hasOwnProperty('date')) {
temp.push(f.id);
if (this.ids.indexOf(f.id) === -1) {
var t = { id: f.id, group: 'all', content: f.properties['Name'], start: new Date(f.properties['date']) };
this.items.update(t);
this.ids.push(f.id);
}
}
});
// check for old items
this.ids.forEach((s) => {
hasChanged = true;
if (temp.indexOf(s) === -1) {
// remove item
var i = this.items.remove(s);
this.ids = this.ids.filter((t) => s !== t);
}
});
//this.$scope.timeline.setItems(i);
if (hasChanged) this.$scope.timeline.redraw();
}
private initTimeline() {
var container = document.getElementById('timeline');
// Remove old timeline before initializing a new one
while (container.firstChild) {
container.removeChild(container.firstChild);
}
this.$layerService.timeline = this.$scope.timeline = new vis.Timeline(container, this.items, this.options);
this.$scope.timeline.addCustomTime(this.focusDate, '1');
this.$scope.timeline.on('timechange', (res) => {
console.log(res.time);
});
this.$layerService.timeline.redraw();
if (this.$layerService.project && this.activeDateRange !== null) {
this.$scope.timeline.setWindow(this.activeDateRange.start, this.activeDateRange.end);
if (this.activeDateRange && this.activeDateRange.isLive) this.goLive();
}
this.updateDragging();
this.updateFocusTime();
this.$scope.timeline.on('select', (properties) => {
if (properties.items && properties.items.length > 0) {
var id = properties.items[0];
var f = this.$layerService.findFeatureById(id);
if (f) {
this.$layerService.selectFeature(f);
} else if (this.$layerService.project.eventTab) {
this.$messageBusService.publish('eventtab', 'zoomto', { id: id });
}
}
});
this.$scope.timeline.addEventListener('rangechange', _.throttle((prop) => this.onRangeChanged(prop), 200));
//this.addEventListener('featureschanged', _.throttle((prop) => this.updateFeatures(), 200));
}
public selectDate() {
}
public updateDragging() {
if (this.activeDateRange && this.activeDateRange.isLive) {
(<any>$('#focustimeContainer')).draggable('disable');
} else {
(<any>$('#focustimeContainer')).draggable({
axis: 'x',
containment: 'parent',
drag: _.throttle(() => this.updateFocusTime(), 200)
});
(<any>$('#focustimeContainer')).draggable('enable');
}
}
public expandToggle() {
this.activeDateRange.isExpanded = !this.activeDateRange.isExpanded;
this.updateTimelineHeight();
// this.options.margin = {};
// this.options.margin['item'] = (this.expanded) ? 65 : 0;
this.updatePanelHeights();
}
private updateTimelineHeight() {
this.options.moveable = this.activeDateRange.ismoveable;
this.options.height = (this.activeDateRange.isExpanded) ? this.activeDateRange.expandHeight : 54;
this.expandButtonBottom = (this.activeDateRange.isExpanded) ? this.activeDateRange.expandHeight - 1 : 52;
this.datePickerBottom = this.expandButtonBottom + 170;
this.$layerService.timeline.setOptions(this.options);
this.$layerService.timeline.redraw();
}
private updatePanelHeights() {
this.activeDateRange = (this.$layerService.project.activeDashboard.timeline) ? this.$layerService.project.activeDashboard.timeline : this.$layerService.project.timeLine;
var height = (this.activeDateRange.isExpanded && this.$layerService.project.activeDashboard.showTimeline) ? this.activeDateRange.expandHeight : 54;
$('.leftpanel-container').css('bottom', height + 20);
$('.rightpanel').css('bottom', height);
}
private throttleTimeSpanUpdate = _.debounce(this.triggerTimeSpanUpdated, 1000);
/**
* trigger a debounced timespan updated message on the message bus
*/
private triggerTimeSpanUpdated() {
this.$messageBusService.publish('timeline', 'timeSpanUpdated', '');
}
/**
* time span was updated by timeline control
*/
public onRangeChanged(prop) {
this.updateFocusTime();
this.throttleTimeSpanUpdate();
}
public start() {
this.stop();
this.isPlaying = true;
if (this.timer) this.timer = null;
this.timer = setInterval(() => { this.myTimer(); }, 500);
}
public goLive() {
this.stop();
this.activeDateRange.isLive = true;
this.isPlaying = false;
if (this.activeDateRange.isLive) {
this.myTimer();
this.start();
}
this.updateDragging();
}
public stopLive() {
if (!this.activeDateRange) return;
this.stop();
this.activeDateRange.isLive = false;
this.isPlaying = false;
this.updateDragging();
}
public myTimer() {
var tl = this.$scope.timeline;
if (this.activeDateRange.isLive) {
var pos = tl._toScreen(new Date());
$('#focustimeContainer').css('left', pos - 65);
if (this.isPinned)
tl.moveTo(new Date(), { animation: { duration: 500, easingFunction: 'linear' } });
this.updateFocusTime();
} else if (this.isPlaying) {
var w = tl.getWindow();
var dif = (w.end.getTime() - w.start.getTime()) / 200;
tl.setWindow(w.start.getTime() + dif, w.end.getTime() + dif, { animation: { duration: 500, easingFunction: 'linear' } });
//tl.move(0.005);
this.updateFocusTime();
}
}
public mouseEnter() {
this.updateFocusTime();
if (!isNaN(this.focusDate.getTime())) {
this.showControl = true;
}
}
public mouseLeave() {
if (!this.isPlaying) this.showControl = false;
}
public pin() {
this.isPinned = true;
}
public unPin() {
this.isPinned = false;
}
public pinToNow() {
this.isPinned = true;
this.start();
}
public stop() {
this.isPlaying = false;
if (this.timer) clearInterval(this.timer);
}
public timelineSelect() {
}
public updateFocusTimeContainer(time: Date) {
this.$scope.timeline.moveTo(time);
this.$scope.timeline.redraw();
if (this.$scope.$$phase !== '$apply' && this.$scope.$$phase !== '$digest') { this.$scope.$apply(); }
let screenPos = this.$scope.timeline._toScreen(time);
$('#focustimeContainer').css('left', screenPos - $('#focustimeContainer').width() / 2);
}
public updateFocusTime() {
if (!this.$layerService.project) return;
//if (!this.$mapService.timelineVisible) return;
setTimeout(() => {
var tl = this.$scope.timeline;
tl.showCustomTime = true;
// typeof this.$layerService.project === 'undefined'
// ? tl.setCustomTime(new Date())
// : tl.setCustomTime(this.$layerService.project.timeLine.focusDate());
//var end = $("#timeline").width;
var range = this.$scope.timeline.getWindow();
//tl.calcConversionFactor();
var pos = $('#focustimeContainer').position().left + $('#focustimeContainer').width() / 2;
if (this.activeDateRange.isLive) {
this.focusDate = new Date();
} else {
this.focusDate = new Date(this.$scope.timeline._toTime(pos));
}
this.startDate = range.start; //new Date(range.start); //this.$scope.timeline.screenToTime(0));
this.endDate = range.end; //new Date(this.$scope.timeline.screenToTime(end));
if (this.activeDateRange != null) {
this.activeDateRange.setFocus(this.focusDate, this.startDate, this.endDate);
this.$layerService.project.timeLine.setFocus(this.focusDate, this.startDate, this.endDate);
var month = (<any>this.focusDate).toLocaleString(this.locale, { month: 'long' });
switch (this.activeDateRange.zoomLevelName) {
case 'decades':
this.line1 = this.focusDate.getFullYear().toString();
this.line2 = '';
break;
case 'years':
this.line1 = this.focusDate.getFullYear().toString();
this.line2 = month;
break;
case 'weeks':
this.line1 = this.focusDate.getFullYear().toString();
this.line2 = moment(this.focusDate).format('DD') + ' ' + month;
break;
case 'milliseconds':
this.line1 = moment(this.focusDate).format('MM - DD - YYYY');
this.line2 = moment(this.focusDate).format('HH:mm:ss.SSS');
break;
default:
this.line1 = moment(this.focusDate).format('MM - DD - YYYY');
this.line2 = moment(this.focusDate).format('HH:mm:ss');
}
}
if (this.$scope.$$phase !== '$apply' && this.$scope.$$phase !== '$digest') { this.$scope.$apply(); }
this.$messageBusService.publish('timeline', 'focusChange', this.focusDate);
tl.setCustomTime(this.focusDate, "1");
}, 0);
//this.$layerService.focusTime = new Date(this.timelineCtrl.screenToTime(centerX));
}
/**
* Load the locales: instead of loading them from the original timeline-locales.js distribution,
* add them here so you don't need to add another js dependency.
* @seealso: http://almende.github.io/chap-links-library/downloads.html
*/
loadLocales() {
if (typeof vis === 'undefined') {
vis = {};
vis.locales = {};
} else if (typeof vis.locales === 'undefined') {
vis.locales = {};
}
// English ===================================================
vis.locales['en'] = {
'MONTHS': ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
'MONTHS_SHORT': ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
'DAYS': ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
'DAYS_SHORT': ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
'ZOOM_IN': 'Zoom in',
'ZOOM_OUT': 'Zoom out',
'MOVE_LEFT': 'Move left',
'MOVE_RIGHT': 'Move right',
'NEW': 'New',
'CREATE_NEW_EVENT': 'Create new event'
};
vis.locales['en_US'] = vis.locales['en'];
vis.locales['en_UK'] = vis.locales['en'];
// French ===================================================
vis.locales['fr'] = {
'MONTHS': ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre'],
'MONTHS_SHORT': ['Jan', 'Fev', 'Mar', 'Avr', 'Mai', 'Jun', 'Jul', 'Aou', 'Sep', 'Oct', 'Nov', 'Dec'],
'DAYS': ['Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'],
'DAYS_SHORT': ['Dim', 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam'],
'ZOOM_IN': 'Zoomer',
'ZOOM_OUT': 'Dézoomer',
'MOVE_LEFT': 'Déplacer à gauche',
'MOVE_RIGHT': 'Déplacer à droite',
'NEW': 'Nouveau',
'CREATE_NEW_EVENT': 'Créer un nouvel évènement'
};
vis.locales['fr_FR'] = vis.locales['fr'];
vis.locales['fr_BE'] = vis.locales['fr'];
vis.locales['fr_CA'] = vis.locales['fr'];
// German ===================================================
vis.locales['de'] = {
'MONTHS': ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'],
'MONTHS_SHORT': ['Jan', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez'],
'DAYS': ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'],
'DAYS_SHORT': ['Son', 'Mon', 'Die', 'Mit', 'Don', 'Fre', 'Sam'],
'ZOOM_IN': 'Vergrößern',
'ZOOM_OUT': 'Verkleinern',
'MOVE_LEFT': 'Nach links verschieben',
'MOVE_RIGHT': 'Nach rechts verschieben',
'NEW': 'Neu',
'CREATE_NEW_EVENT': 'Neues Ereignis erzeugen'
};
vis.locales['de_DE'] = vis.locales['de'];
vis.locales['de_CH'] = vis.locales['de'];
// Dutch =====================================================
vis.locales['nl'] = {
'MONTHS': ['januari', 'februari', 'maart', 'april', 'mei', 'juni', 'juli', 'augustus', 'september', 'oktober', 'november', 'december'],
'MONTHS_SHORT': ['jan', 'feb', 'mrt', 'apr', 'mei', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'dec'],
'DAYS': ['zondag', 'maandag', 'dinsdag', 'woensdag', 'donderdag', 'vrijdag', 'zaterdag'],
'DAYS_SHORT': ['zo', 'ma', 'di', 'wo', 'do', 'vr', 'za'],
'ZOOM_IN': 'Inzoomen',
'ZOOM_OUT': 'Uitzoomen',
'MOVE_LEFT': 'Naar links',
'MOVE_RIGHT': 'Naar rechts',
'NEW': 'Nieuw',
'CREATE_NEW_EVENT': 'Nieuwe gebeurtenis maken'
};
vis.locales['nl_NL'] = vis.locales['nl'];
vis.locales['nl_BE'] = vis.locales['nl'];
}
}
}
| indodutch/csWeb | csComp/directives/Timeline/TimelineCtrl.ts | TypeScript | mit | 30,558 |
import unittest
import chainer
from chainer import testing
from chainer.testing import attr
from chainercv.links.model.deeplab import SeparableASPP
class TestSeparableASPP(unittest.TestCase):
def setUp(self):
self.in_channels = 128
self.out_channels = 32
self.link = SeparableASPP(
self.in_channels, self.out_channels)
def check_call(self):
xp = self.link.xp
x = chainer.Variable(xp.random.uniform(
low=-1, high=1, size=(2, self.in_channels, 64, 64)
).astype(xp.float32))
y = self.link(x)
self.assertIsInstance(y, chainer.Variable)
self.assertIsInstance(y.data, xp.ndarray)
self.assertEqual(y.shape, (2, self.out_channels, 64, 64))
@attr.slow
def test_call_cpu(self):
self.check_call()
@attr.gpu
@attr.slow
def test_call_gpu(self):
self.link.to_gpu()
self.check_call()
testing.run_module(__name__, __file__)
| chainer/chainercv | tests/links_tests/model_tests/deeplab_tests/test_aspp.py | Python | mit | 975 |
<?php
/*
*
* (c) Sergi Tur Badenas <sergiturbadenas@gmail.com>
*
*
* For the full copyright and license information, please view the LICENSE.txt
* file that was distributed with this source code.
*
*/
namespace Acacha\AdminLTETemplateLaravel\app\Providers;
use Illuminate\Support\ServiceProvider;
/**
* Class AdminLTETemplateServiceProvider
* @package Acacha\AdminLTETemplateLaravel\Providers
*/
class AdminLTETemplateServiceProvider extends ServiceProvider
{
/**
* Register the application services.
*
* @return void
*/
public function register()
{
}
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
$this->publishPublicAssets();
$this->publishViews();
$this->publishResourceAssets();
}
/**
* Publish package views to Laravel project
*
* @return void
*/
private function publishViews()
{
$this->loadViewsFrom( dirname(__FILE__) . '/../resources/views/', 'adminltetemplate');
$this->publishes([
dirname(__FILE__) . '/../../resources/views/auth' => base_path('resources/views/auth'),
dirname(__FILE__) . '/../../resources/views/errors' => base_path('resources/views/errors'),
dirname(__FILE__) . '/../../resources/views/partials' => base_path('resources/views/partials'),
dirname(__FILE__) . '/../../resources/views/app.blade.php' => base_path('resources/views/app.blade.php'),
dirname(__FILE__) . '/../../resources/views/home.blade.php' => base_path('resources/views/home.blade.php'),
dirname(__FILE__) . '/../../resources/views/welcome.blade.php' => base_path('resources/views/welcome.blade.php'),
]);
}
/**
* Publish package resource assets to Laravel project
*
* @return void
*/
private function publishResourceAssets()
{
$this->publishes([
dirname(__FILE__) . '/../../resources/assets/less' => base_path('resources/assets/less'),
dirname(__FILE__) . '/../../gulpfile.js' => base_path('gulpfile.js'),
]);
}
/**
* Publish public resource assets to Laravel project
*
* @return void
*/
private function publishPublicAssets()
{
$this->publishes([
dirname(__FILE__) . '/../../public/img' => public_path('img'),
dirname(__FILE__) . '/../../public/css' => public_path('css'),
dirname(__FILE__) . '/../../public/js' => public_path('js'),
dirname(__FILE__) . '/../../public/plugins' => public_path('plugins'),
], 'assets');
}
}
| SatoshiDark/adminlte-laravel | src/app/Providers/AdminLTETemplateServiceProvider.php | PHP | mit | 2,684 |
<?php
namespace Rad\Core;
use Composer\Autoload\ClassLoader;
use InvalidArgumentException;
use Rad\Core\Exception\MissingBundleException;
use Rad\Utility\Inflection;
/**
* Bundles Loader
*
* @package Rad\Core
*/
class Bundles
{
/**
* @var ClassLoader
*/
protected static $classLoader;
/**
* @var array
*/
protected static $bundlesLoaded = [];
/**
* Load bundle
*
* @param BundleInterface $bundle
*
* @throws MissingBundleException
*/
public static function load(BundleInterface $bundle)
{
if (is_dir($bundle->getPath())) {
self::$bundlesLoaded[$bundle->getName()] = [
'namespace' => $bundle->getNamespace(),
'path' => $bundle->getPath()
];
if (!self::$classLoader) {
self::$classLoader = new ClassLoader();
}
self::$classLoader->addPsr4($bundle->getNamespace(), $bundle->getPath());
self::$classLoader->register();
} else {
throw new MissingBundleException(sprintf('Bundle "%s" could not be found.', $bundle->getName()));
}
}
/**
* Load all bundles
*
* @param array $bundles
*
* @throws MissingBundleException
*/
public static function loadAll(array $bundles)
{
foreach ($bundles as $bundle) {
if (!$bundle instanceof BundleInterface) {
throw new InvalidArgumentException('Bundle must be instance of "Rad\Core\BundleInterface".');
}
self::load($bundle);
}
}
/**
* Check bundle is loaded
*
* @param string $bundleName Bundle name
*
* @return bool
*/
public static function isLoaded($bundleName)
{
$bundleName = Inflection::camelize($bundleName);
return isset(self::$bundlesLoaded[$bundleName]);
}
/**
* Get all loaded bundles
*
* @return array
*/
public static function getLoaded()
{
return array_keys(self::$bundlesLoaded);
}
/**
* Get bundle namespace
*
* @param string $bundleName Bundle name
*
* @return string
* @throws MissingBundleException
*/
public static function getNamespace($bundleName)
{
if (isset(self::$bundlesLoaded[$bundleName])) {
return self::$bundlesLoaded[$bundleName]['namespace'];
}
throw new MissingBundleException(sprintf('Bundle "%s" could not be found.', $bundleName));
}
/**
* Get bundle path
*
* @param string $bundleName Bundle name
*
* @return string
* @throws MissingBundleException
*/
public static function getPath($bundleName)
{
if (isset(self::$bundlesLoaded[$bundleName])) {
return self::$bundlesLoaded[$bundleName]['path'];
}
throw new MissingBundleException(sprintf('Bundle "%s" could not be found.', $bundleName));
}
}
| radphp/radphp | src/Core/Bundles.php | PHP | mit | 3,011 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_112-release) on Mon Apr 03 15:13:53 MDT 2017 -->
<title>ElasticSearchUserController.UpdateUserTask</title>
<meta name="date" content="2017-04-03">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="ElasticSearchUserController.UpdateUserTask";
}
}
catch(err) {
}
//-->
var methods = {"i0":10};
var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../com/projectattitude/projectattitude/Controllers/ElasticSearchUserController.UpdateUserRequestTask.html" title="class in com.projectattitude.projectattitude.Controllers"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../com/projectattitude/projectattitude/Controllers/MainController.html" title="class in com.projectattitude.projectattitude.Controllers"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?com/projectattitude/projectattitude/Controllers/ElasticSearchUserController.UpdateUserTask.html" target="_top">Frames</a></li>
<li><a href="ElasticSearchUserController.UpdateUserTask.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li><a href="#nested.classes.inherited.from.class.android.os.AsyncTask">Nested</a> | </li>
<li><a href="#fields.inherited.from.class.android.os.AsyncTask">Field</a> | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">com.projectattitude.projectattitude.Controllers</div>
<h2 title="Class ElasticSearchUserController.UpdateUserTask" class="title">Class ElasticSearchUserController.UpdateUserTask</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>android.os.AsyncTask<<a href="../../../../com/projectattitude/projectattitude/Objects/User.html" title="class in com.projectattitude.projectattitude.Objects">User</a>,java.lang.Void,java.lang.Void></li>
<li>
<ul class="inheritance">
<li>com.projectattitude.projectattitude.Controllers.ElasticSearchUserController.UpdateUserTask</li>
</ul>
</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>Enclosing class:</dt>
<dd><a href="../../../../com/projectattitude/projectattitude/Controllers/ElasticSearchUserController.html" title="class in com.projectattitude.projectattitude.Controllers">ElasticSearchUserController</a></dd>
</dl>
<hr>
<br>
<pre>public static class <span class="typeNameLabel">ElasticSearchUserController.UpdateUserTask</span>
extends android.os.AsyncTask<<a href="../../../../com/projectattitude/projectattitude/Objects/User.html" title="class in com.projectattitude.projectattitude.Objects">User</a>,java.lang.Void,java.lang.Void></pre>
<div class="block">Updates a user in the database.</div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== NESTED CLASS SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="nested.class.summary">
<!-- -->
</a>
<h3>Nested Class Summary</h3>
<ul class="blockList">
<li class="blockList"><a name="nested.classes.inherited.from.class.android.os.AsyncTask">
<!-- -->
</a>
<h3>Nested classes/interfaces inherited from class android.os.AsyncTask</h3>
<code>android.os.AsyncTask.Status</code></li>
</ul>
</li>
</ul>
<!-- =========== FIELD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="field.summary">
<!-- -->
</a>
<h3>Field Summary</h3>
<ul class="blockList">
<li class="blockList"><a name="fields.inherited.from.class.android.os.AsyncTask">
<!-- -->
</a>
<h3>Fields inherited from class android.os.AsyncTask</h3>
<code>SERIAL_EXECUTOR, THREAD_POOL_EXECUTOR</code></li>
</ul>
</li>
</ul>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../com/projectattitude/projectattitude/Controllers/ElasticSearchUserController.UpdateUserTask.html#UpdateUserTask--">UpdateUserTask</a></span>()</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>protected java.lang.Void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/projectattitude/projectattitude/Controllers/ElasticSearchUserController.UpdateUserTask.html#doInBackground-com.projectattitude.projectattitude.Objects.User...-">doInBackground</a></span>(<a href="../../../../com/projectattitude/projectattitude/Objects/User.html" title="class in com.projectattitude.projectattitude.Objects">User</a>... search_parameters)</code> </td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.android.os.AsyncTask">
<!-- -->
</a>
<h3>Methods inherited from class android.os.AsyncTask</h3>
<code>cancel, execute, execute, executeOnExecutor, get, get, getStatus, isCancelled, onCancelled, onCancelled, onPostExecute, onPreExecute, onProgressUpdate, publishProgress</code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="UpdateUserTask--">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>UpdateUserTask</h4>
<pre>public UpdateUserTask()</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="doInBackground-com.projectattitude.projectattitude.Objects.User...-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>doInBackground</h4>
<pre>protected java.lang.Void doInBackground(<a href="../../../../com/projectattitude/projectattitude/Objects/User.html" title="class in com.projectattitude.projectattitude.Objects">User</a>... search_parameters)</pre>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code>doInBackground</code> in class <code>android.os.AsyncTask<<a href="../../../../com/projectattitude/projectattitude/Objects/User.html" title="class in com.projectattitude.projectattitude.Objects">User</a>,java.lang.Void,java.lang.Void></code></dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../com/projectattitude/projectattitude/Controllers/ElasticSearchUserController.UpdateUserRequestTask.html" title="class in com.projectattitude.projectattitude.Controllers"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../com/projectattitude/projectattitude/Controllers/MainController.html" title="class in com.projectattitude.projectattitude.Controllers"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?com/projectattitude/projectattitude/Controllers/ElasticSearchUserController.UpdateUserTask.html" target="_top">Frames</a></li>
<li><a href="ElasticSearchUserController.UpdateUserTask.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li><a href="#nested.classes.inherited.from.class.android.os.AsyncTask">Nested</a> | </li>
<li><a href="#fields.inherited.from.class.android.os.AsyncTask">Field</a> | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| bfleyshe/ProjectAttitude | doc/com/projectattitude/projectattitude/Controllers/ElasticSearchUserController.UpdateUserTask.html | HTML | mit | 12,892 |
/**
* @fileoverview This option sets a specific tab width for your code
* @author Dmitriy Shekhovtsov
* @author Gyandeep Singh
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const rule = require("../../../lib/rules/indent"),
{ RuleTester } = require("../../../lib/rule-tester");
const fs = require("fs");
const path = require("path");
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
const fixture = fs.readFileSync(path.join(__dirname, "../../fixtures/rules/indent/indent-invalid-fixture-1.js"), "utf8");
const fixedFixture = fs.readFileSync(path.join(__dirname, "../../fixtures/rules/indent/indent-valid-fixture-1.js"), "utf8");
const parser = require("../../fixtures/fixture-parser");
const { unIndent } = require("../../_utils");
/**
* Create error message object for failure cases with a single 'found' indentation type
* @param {string} providedIndentType indent type of string or tab
* @param {Array} providedErrors error info
* @returns {Object} returns the error messages collection
* @private
*/
function expectedErrors(providedIndentType, providedErrors) {
let indentType;
let errors;
if (Array.isArray(providedIndentType)) {
errors = Array.isArray(providedIndentType[0]) ? providedIndentType : [providedIndentType];
indentType = "space";
} else {
errors = Array.isArray(providedErrors[0]) ? providedErrors : [providedErrors];
indentType = providedIndentType;
}
return errors.map(err => ({
messageId: "wrongIndentation",
data: {
expected: typeof err[1] === "string" && typeof err[2] === "string"
? err[1]
: `${err[1]} ${indentType}${err[1] === 1 ? "" : "s"}`,
actual: err[2]
},
type: err[3],
line: err[0]
}));
}
//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------
const ruleTester = new RuleTester({ parserOptions: { ecmaVersion: 8, ecmaFeatures: { jsx: true } } });
ruleTester.run("indent", rule, {
valid: [
{
code: unIndent`
bridge.callHandler(
'getAppVersion', 'test23', function(responseData) {
window.ah.mobileAppVersion = responseData;
}
);
`,
options: [2]
},
{
code: unIndent`
bridge.callHandler(
'getAppVersion', 'test23', function(responseData) {
window.ah.mobileAppVersion = responseData;
});
`,
options: [2]
},
{
code: unIndent`
bridge.callHandler(
'getAppVersion',
null,
function responseCallback(responseData) {
window.ah.mobileAppVersion = responseData;
}
);
`,
options: [2]
},
{
code: unIndent`
bridge.callHandler(
'getAppVersion',
null,
function responseCallback(responseData) {
window.ah.mobileAppVersion = responseData;
});
`,
options: [2]
},
{
code: unIndent`
function doStuff(keys) {
_.forEach(
keys,
key => {
doSomething(key);
}
);
}
`,
options: [4]
},
{
code: unIndent`
example(
function () {
console.log('example');
}
);
`,
options: [4]
},
{
code: unIndent`
let foo = somethingList
.filter(x => {
return x;
})
.map(x => {
return 100 * x;
});
`,
options: [4]
},
{
code: unIndent`
var x = 0 &&
{
a: 1,
b: 2
};
`,
options: [4]
},
{
code: unIndent`
var x = 0 &&
\t{
\t\ta: 1,
\t\tb: 2
\t};
`,
options: ["tab"]
},
{
code: unIndent`
var x = 0 &&
{
a: 1,
b: 2
}||
{
c: 3,
d: 4
};
`,
options: [4]
},
{
code: unIndent`
var x = [
'a',
'b',
'c'
];
`,
options: [4]
},
{
code: unIndent`
var x = ['a',
'b',
'c',
];
`,
options: [4]
},
{
code: "var x = 0 && 1;",
options: [4]
},
{
code: "var x = 0 && { a: 1, b: 2 };",
options: [4]
},
{
code: unIndent`
var x = 0 &&
(
1
);
`,
options: [4]
},
{
code: unIndent`
require('http').request({hostname: 'localhost',
port: 80}, function(res) {
res.end();
});
`,
options: [2]
},
{
code: unIndent`
function test() {
return client.signUp(email, PASSWORD, { preVerified: true })
.then(function (result) {
// hi
})
.then(function () {
return FunctionalHelpers.clearBrowserState(self, {
contentServer: true,
contentServer1: true
});
});
}
`,
options: [2]
},
{
code: unIndent`
it('should... some lengthy test description that is forced to be' +
'wrapped into two lines since the line length limit is set', () => {
expect(true).toBe(true);
});
`,
options: [2]
},
{
code: unIndent`
function test() {
return client.signUp(email, PASSWORD, { preVerified: true })
.then(function (result) {
var x = 1;
var y = 1;
}, function(err){
var o = 1 - 2;
var y = 1 - 2;
return true;
})
}
`,
options: [4]
},
{
// https://github.com/eslint/eslint/issues/11802
code: unIndent`
import foo from "foo"
;(() => {})()
`,
options: [4],
parserOptions: { ecmaVersion: 6, sourceType: "module" }
},
{
code: unIndent`
function test() {
return client.signUp(email, PASSWORD, { preVerified: true })
.then(function (result) {
var x = 1;
var y = 1;
}, function(err){
var o = 1 - 2;
var y = 1 - 2;
return true;
});
}
`,
options: [4, { MemberExpression: 0 }]
},
{
code: "// hi",
options: [2, { VariableDeclarator: 1, SwitchCase: 1 }]
},
{
code: unIndent`
var Command = function() {
var fileList = [],
files = []
files.concat(fileList)
};
`,
options: [2, { VariableDeclarator: { var: 2, let: 2, const: 3 } }]
},
{
code: " ",
options: [2, { VariableDeclarator: 1, SwitchCase: 1 }]
},
{
code: unIndent`
if(data) {
console.log('hi');
b = true;};
`,
options: [2, { VariableDeclarator: 1, SwitchCase: 1 }]
},
{
code: unIndent`
foo = () => {
console.log('hi');
return true;};
`,
options: [2, { VariableDeclarator: 1, SwitchCase: 1 }]
},
{
code: unIndent`
function test(data) {
console.log('hi');
return true;};
`,
options: [2, { VariableDeclarator: 1, SwitchCase: 1 }]
},
{
code: unIndent`
var test = function(data) {
console.log('hi');
};
`,
options: [2, { VariableDeclarator: 1, SwitchCase: 1 }]
},
{
code: unIndent`
arr.forEach(function(data) {
otherdata.forEach(function(zero) {
console.log('hi');
}) });
`,
options: [2, { VariableDeclarator: 1, SwitchCase: 1 }]
},
{
code: unIndent`
a = [
,3
]
`,
options: [4, { VariableDeclarator: 1, SwitchCase: 1 }]
},
{
code: unIndent`
[
['gzip', 'gunzip'],
['gzip', 'unzip'],
['deflate', 'inflate'],
['deflateRaw', 'inflateRaw'],
].forEach(function(method) {
console.log(method);
});
`,
options: [2, { SwitchCase: 1, VariableDeclarator: 2 }]
},
{
code: unIndent`
test(123, {
bye: {
hi: [1,
{
b: 2
}
]
}
});
`,
options: [4, { VariableDeclarator: 1, SwitchCase: 1 }]
},
{
code: unIndent`
var xyz = 2,
lmn = [
{
a: 1
}
];
`,
options: [4, { VariableDeclarator: 1, SwitchCase: 1 }]
},
{
code: unIndent`
lmnn = [{
a: 1
},
{
b: 2
}, {
x: 2
}];
`,
options: [4, { VariableDeclarator: 1, SwitchCase: 1 }]
},
unIndent`
[{
foo: 1
}, {
foo: 2
}, {
foo: 3
}]
`,
unIndent`
foo([
bar
], [
baz
], [
qux
]);
`,
{
code: unIndent`
abc({
test: [
[
c,
xyz,
2
].join(',')
]
});
`,
options: [4, { VariableDeclarator: 1, SwitchCase: 1 }]
},
{
code: unIndent`
abc = {
test: [
[
c,
xyz,
2
]
]
};
`,
options: [2, { VariableDeclarator: 1, SwitchCase: 1 }]
},
{
code: unIndent`
abc(
{
a: 1,
b: 2
}
);
`,
options: [2, { VariableDeclarator: 1, SwitchCase: 1 }]
},
{
code: unIndent`
abc({
a: 1,
b: 2
});
`,
options: [4, { VariableDeclarator: 1, SwitchCase: 1 }]
},
{
code: unIndent`
var abc =
[
c,
xyz,
{
a: 1,
b: 2
}
];
`,
options: [2, { VariableDeclarator: 1, SwitchCase: 1 }]
},
{
code: unIndent`
var abc = [
c,
xyz,
{
a: 1,
b: 2
}
];
`,
options: [2, { VariableDeclarator: 1, SwitchCase: 1 }]
},
{
code: unIndent`
var abc = 5,
c = 2,
xyz =
{
a: 1,
b: 2
};
`,
options: [2, { VariableDeclarator: 2, SwitchCase: 1 }]
},
unIndent`
var
x = {
a: 1,
},
y = {
b: 2
}
`,
unIndent`
const
x = {
a: 1,
},
y = {
b: 2
}
`,
unIndent`
let
x = {
a: 1,
},
y = {
b: 2
}
`,
unIndent`
var foo = { a: 1 }, bar = {
b: 2
};
`,
unIndent`
var foo = { a: 1 }, bar = {
b: 2
},
baz = {
c: 3
}
`,
unIndent`
const {
foo
} = 1,
bar = 2
`,
{
code: unIndent`
var foo = 1,
bar =
2
`,
options: [2, { VariableDeclarator: 1 }]
},
{
code: unIndent`
var foo = 1,
bar
= 2
`,
options: [2, { VariableDeclarator: 1 }]
},
{
code: unIndent`
var foo
= 1,
bar
= 2
`,
options: [2, { VariableDeclarator: 1 }]
},
{
code: unIndent`
var foo
=
1,
bar
=
2
`,
options: [2, { VariableDeclarator: 1 }]
},
{
code: unIndent`
var foo
= (1),
bar
= (2)
`,
options: [2, { VariableDeclarator: 1 }]
},
{
code: unIndent`
let foo = 'foo',
bar = bar;
const a = 'a',
b = 'b';
`,
options: [2, { VariableDeclarator: "first" }]
},
{
code: unIndent`
let foo = 'foo',
bar = bar // <-- no semicolon here
const a = 'a',
b = 'b' // <-- no semicolon here
`,
options: [2, { VariableDeclarator: "first" }]
},
{
code: unIndent`
var foo = 1,
bar = 2,
baz = 3
;
`,
options: [2, { VariableDeclarator: { var: 2 } }]
},
{
code: unIndent`
var foo = 1,
bar = 2,
baz = 3
;
`,
options: [2, { VariableDeclarator: { var: 2 } }]
},
{
code: unIndent`
var foo = 'foo',
bar = bar;
`,
options: [2, { VariableDeclarator: { var: "first" } }]
},
{
code: unIndent`
var foo = 'foo',
bar = 'bar' // <-- no semicolon here
`,
options: [2, { VariableDeclarator: { var: "first" } }]
},
{
code: unIndent`
let foo = 1,
bar = 2,
baz
`,
options: [2, { VariableDeclarator: "first" }]
},
{
code: unIndent`
let
foo
`,
options: [4, { VariableDeclarator: "first" }]
},
{
code: unIndent`
let foo = 1,
bar =
2
`,
options: [2, { VariableDeclarator: "first" }]
},
{
code: unIndent`
var abc =
{
a: 1,
b: 2
};
`,
options: [2, { VariableDeclarator: 2, SwitchCase: 1 }]
},
{
code: unIndent`
var a = new abc({
a: 1,
b: 2
}),
b = 2;
`,
options: [4, { VariableDeclarator: 1, SwitchCase: 1 }]
},
{
code: unIndent`
var a = 2,
c = {
a: 1,
b: 2
},
b = 2;
`,
options: [2, { VariableDeclarator: 1, SwitchCase: 1 }]
},
{
code: unIndent`
var x = 2,
y = {
a: 1,
b: 2
},
b = 2;
`,
options: [2, { VariableDeclarator: 2, SwitchCase: 1 }]
},
{
code: unIndent`
var e = {
a: 1,
b: 2
},
b = 2;
`,
options: [2, { VariableDeclarator: 2, SwitchCase: 1 }]
},
{
code: unIndent`
var a = {
a: 1,
b: 2
};
`,
options: [2, { VariableDeclarator: 2, SwitchCase: 1 }]
},
{
code: unIndent`
function test() {
if (true ||
false){
console.log(val);
}
}
`,
options: [2, { VariableDeclarator: 2, SwitchCase: 1 }]
},
unIndent`
var foo = bar ||
!(
baz
);
`,
unIndent`
for (var foo = 1;
foo < 10;
foo++) {}
`,
unIndent`
for (
var foo = 1;
foo < 10;
foo++
) {}
`,
{
code: unIndent`
for (var val in obj)
if (true)
console.log(val);
`,
options: [2, { VariableDeclarator: 2, SwitchCase: 1 }]
},
{
code: unIndent`
if(true)
if (true)
if (true)
console.log(val);
`,
options: [2, { VariableDeclarator: 2, SwitchCase: 1 }]
},
{
code: unIndent`
function hi(){ var a = 1;
y++; x++;
}
`,
options: [2, { VariableDeclarator: 2, SwitchCase: 1 }]
},
{
code: unIndent`
for(;length > index; index++)if(NO_HOLES || index in self){
x++;
}
`,
options: [2, { VariableDeclarator: 2, SwitchCase: 1 }]
},
{
code: unIndent`
function test(){
switch(length){
case 1: return function(a){
return fn.call(that, a);
};
}
}
`,
options: [2, { VariableDeclarator: 2, SwitchCase: 1 }]
},
{
code: unIndent`
var geometry = 2,
rotate = 2;
`,
options: [2, { VariableDeclarator: 0 }]
},
{
code: unIndent`
var geometry,
rotate;
`,
options: [4, { VariableDeclarator: 1 }]
},
{
code: unIndent`
var geometry,
\trotate;
`,
options: ["tab", { VariableDeclarator: 1 }]
},
{
code: unIndent`
var geometry,
rotate;
`,
options: [2, { VariableDeclarator: 1 }]
},
{
code: unIndent`
var geometry,
rotate;
`,
options: [2, { VariableDeclarator: 2 }]
},
{
code: unIndent`
let geometry,
rotate;
`,
options: [2, { VariableDeclarator: 2 }]
},
{
code: unIndent`
const geometry = 2,
rotate = 3;
`,
options: [2, { VariableDeclarator: 2 }]
},
{
code: unIndent`
var geometry, box, face1, face2, colorT, colorB, sprite, padding, maxWidth,
height, rotate;
`,
options: [2, { SwitchCase: 1 }]
},
{
code: "var geometry, box, face1, face2, colorT, colorB, sprite, padding, maxWidth;",
options: [2, { SwitchCase: 1 }]
},
{
code: unIndent`
if (1 < 2){
//hi sd
}
`,
options: [2]
},
{
code: unIndent`
while (1 < 2){
//hi sd
}
`,
options: [2]
},
{
code: "while (1 < 2) console.log('hi');",
options: [2]
},
{
code: unIndent`
[a, boop,
c].forEach((index) => {
index;
});
`,
options: [4]
},
{
code: unIndent`
[a, b,
c].forEach(function(index){
return index;
});
`,
options: [4]
},
{
code: unIndent`
[a, b, c].forEach((index) => {
index;
});
`,
options: [4]
},
{
code: unIndent`
[a, b, c].forEach(function(index){
return index;
});
`,
options: [4]
},
{
code: unIndent`
(foo)
.bar([
baz
]);
`,
options: [4, { MemberExpression: 1 }]
},
{
code: unIndent`
switch (x) {
case "foo":
a();
break;
case "bar":
switch (y) {
case "1":
break;
case "2":
a = 6;
break;
}
case "test":
break;
}
`,
options: [4, { SwitchCase: 1 }]
},
{
code: unIndent`
switch (x) {
case "foo":
a();
break;
case "bar":
switch (y) {
case "1":
break;
case "2":
a = 6;
break;
}
case "test":
break;
}
`,
options: [4, { SwitchCase: 2 }]
},
unIndent`
switch (a) {
case "foo":
a();
break;
case "bar":
switch(x){
case '1':
break;
case '2':
a = 6;
break;
}
}
`,
unIndent`
switch (a) {
case "foo":
a();
break;
case "bar":
if(x){
a = 2;
}
else{
a = 6;
}
}
`,
unIndent`
switch (a) {
case "foo":
a();
break;
case "bar":
if(x){
a = 2;
}
else
a = 6;
}
`,
unIndent`
switch (a) {
case "foo":
a();
break;
case "bar":
a(); break;
case "baz":
a(); break;
}
`,
unIndent`
switch (0) {
}
`,
unIndent`
function foo() {
var a = "a";
switch(a) {
case "a":
return "A";
case "b":
return "B";
}
}
foo();
`,
{
code: unIndent`
switch(value){
case "1":
case "2":
a();
break;
default:
a();
break;
}
switch(value){
case "1":
a();
break;
case "2":
break;
default:
break;
}
`,
options: [4, { SwitchCase: 1 }]
},
unIndent`
var obj = {foo: 1, bar: 2};
with (obj) {
console.log(foo + bar);
}
`,
unIndent`
if (a) {
(1 + 2 + 3); // no error on this line
}
`,
"switch(value){ default: a(); break; }",
{
code: unIndent`
import {addons} from 'react/addons'
import React from 'react'
`,
options: [2],
parserOptions: { ecmaVersion: 6, sourceType: "module" }
},
{
code: unIndent`
import {
foo,
bar,
baz
} from 'qux';
`,
parserOptions: { ecmaVersion: 6, sourceType: "module" }
},
{
code: unIndent`
var foo = 0, bar = 0; baz = 0;
export {
foo,
bar,
baz
} from 'qux';
`,
parserOptions: { ecmaVersion: 6, sourceType: "module" }
},
{
code: unIndent`
var a = 1,
b = 2,
c = 3;
`,
options: [4]
},
{
code: unIndent`
var a = 1
,b = 2
,c = 3;
`,
options: [4]
},
{
code: "while (1 < 2) console.log('hi')",
options: [2]
},
{
code: unIndent`
function salutation () {
switch (1) {
case 0: return console.log('hi')
case 1: return console.log('hey')
}
}
`,
options: [2, { SwitchCase: 1 }]
},
{
code: unIndent`
var items = [
{
foo: 'bar'
}
];
`,
options: [2, { VariableDeclarator: 2 }]
},
{
code: unIndent`
const a = 1,
b = 2;
const items1 = [
{
foo: 'bar'
}
];
const items2 = Items(
{
foo: 'bar'
}
);
`,
options: [2, { VariableDeclarator: 3 }]
},
{
code: unIndent`
const geometry = 2,
rotate = 3;
var a = 1,
b = 2;
let light = true,
shadow = false;
`,
options: [2, { VariableDeclarator: { const: 3, let: 2 } }]
},
{
code: unIndent`
const abc = 5,
c = 2,
xyz =
{
a: 1,
b: 2
};
let abc2 = 5,
c2 = 2,
xyz2 =
{
a: 1,
b: 2
};
var abc3 = 5,
c3 = 2,
xyz3 =
{
a: 1,
b: 2
};
`,
options: [2, { VariableDeclarator: { var: 2, const: 3 }, SwitchCase: 1 }]
},
{
code: unIndent`
module.exports = {
'Unit tests':
{
rootPath: './',
environment: 'node',
tests:
[
'test/test-*.js'
],
sources:
[
'*.js',
'test/**.js'
]
}
};
`,
options: [2]
},
{
code: unIndent`
foo =
bar;
`,
options: [2]
},
{
code: unIndent`
foo = (
bar
);
`,
options: [2]
},
{
code: unIndent`
var path = require('path')
, crypto = require('crypto')
;
`,
options: [2]
},
unIndent`
var a = 1
,b = 2
;
`,
{
code: unIndent`
export function create (some,
argument) {
return Object.create({
a: some,
b: argument
});
};
`,
options: [2, { FunctionDeclaration: { parameters: "first" } }],
parserOptions: { ecmaVersion: 6, sourceType: "module" }
},
{
code: unIndent`
export function create (id, xfilter, rawType,
width=defaultWidth, height=defaultHeight,
footerHeight=defaultFooterHeight,
padding=defaultPadding) {
// ... function body, indented two spaces
}
`,
options: [2, { FunctionDeclaration: { parameters: "first" } }],
parserOptions: { ecmaVersion: 6, sourceType: "module" }
},
{
code: unIndent`
var obj = {
foo: function () {
return new p()
.then(function (ok) {
return ok;
}, function () {
// ignore things
});
}
};
`,
options: [2]
},
{
code: unIndent`
a.b()
.c(function(){
var a;
}).d.e;
`,
options: [2]
},
{
code: unIndent`
const YO = 'bah',
TE = 'mah'
var res,
a = 5,
b = 4
`,
options: [2, { VariableDeclarator: { var: 2, let: 2, const: 3 } }]
},
{
code: unIndent`
const YO = 'bah',
TE = 'mah'
var res,
a = 5,
b = 4
if (YO) console.log(TE)
`,
options: [2, { VariableDeclarator: { var: 2, let: 2, const: 3 } }]
},
{
code: unIndent`
var foo = 'foo',
bar = 'bar',
baz = function() {
}
function hello () {
}
`,
options: [2]
},
{
code: unIndent`
var obj = {
send: function () {
return P.resolve({
type: 'POST'
})
.then(function () {
return true;
}, function () {
return false;
});
}
};
`,
options: [2]
},
{
code: unIndent`
var obj = {
send: function () {
return P.resolve({
type: 'POST'
})
.then(function () {
return true;
}, function () {
return false;
});
}
};
`,
options: [2, { MemberExpression: 0 }]
},
unIndent`
const someOtherFunction = argument => {
console.log(argument);
},
someOtherValue = 'someOtherValue';
`,
{
code: unIndent`
[
'a',
'b'
].sort().should.deepEqual([
'x',
'y'
]);
`,
options: [2]
},
{
code: unIndent`
var a = 1,
B = class {
constructor(){}
a(){}
get b(){}
};
`,
options: [2, { VariableDeclarator: 2, SwitchCase: 1 }]
},
{
code: unIndent`
var a = 1,
B =
class {
constructor(){}
a(){}
get b(){}
},
c = 3;
`,
options: [2, { VariableDeclarator: 2, SwitchCase: 1 }]
},
{
code: unIndent`
class A{
constructor(){}
a(){}
get b(){}
}
`,
options: [4, { VariableDeclarator: 1, SwitchCase: 1 }]
},
{
code: unIndent`
var A = class {
constructor(){}
a(){}
get b(){}
}
`,
options: [4, { VariableDeclarator: 1, SwitchCase: 1 }]
},
{
code: unIndent`
var a = {
some: 1
, name: 2
};
`,
options: [2]
},
{
code: unIndent`
a.c = {
aa: function() {
'test1';
return 'aa';
}
, bb: function() {
return this.bb();
}
};
`,
options: [4]
},
{
code: unIndent`
var a =
{
actions:
[
{
name: 'compile'
}
]
};
`,
options: [4, { VariableDeclarator: 0, SwitchCase: 1 }]
},
{
code: unIndent`
var a =
[
{
name: 'compile'
}
];
`,
options: [4, { VariableDeclarator: 0, SwitchCase: 1 }]
},
unIndent`
[[
], function(
foo
) {}
]
`,
unIndent`
define([
'foo'
], function(
bar
) {
baz;
}
)
`,
{
code: unIndent`
const func = function (opts) {
return Promise.resolve()
.then(() => {
[
'ONE', 'TWO'
].forEach(command => { doSomething(); });
});
};
`,
options: [4, { MemberExpression: 0 }]
},
{
code: unIndent`
const func = function (opts) {
return Promise.resolve()
.then(() => {
[
'ONE', 'TWO'
].forEach(command => { doSomething(); });
});
};
`,
options: [4]
},
{
code: unIndent`
var haveFun = function () {
SillyFunction(
{
value: true,
},
{
_id: true,
}
);
};
`,
options: [4]
},
{
code: unIndent`
var haveFun = function () {
new SillyFunction(
{
value: true,
},
{
_id: true,
}
);
};
`,
options: [4]
},
{
code: unIndent`
let object1 = {
doThing() {
return _.chain([])
.map(v => (
{
value: true,
}
))
.value();
}
};
`,
options: [2]
},
{
code: unIndent`
var foo = {
bar: 1,
baz: {
qux: 2
}
},
bar = 1;
`,
options: [2]
},
{
code: unIndent`
class Foo
extends Bar {
baz() {}
}
`,
options: [2]
},
{
code: unIndent`
class Foo extends
Bar {
baz() {}
}
`,
options: [2]
},
{
code: unIndent`
class Foo extends
(
Bar
) {
baz() {}
}
`,
options: [2]
},
{
code: unIndent`
fs.readdirSync(path.join(__dirname, '../rules')).forEach(name => {
files[name] = foo;
});
`,
options: [2, { outerIIFEBody: 0 }]
},
{
code: unIndent`
(function(){
function foo(x) {
return x + 1;
}
})();
`,
options: [2, { outerIIFEBody: 0 }]
},
{
code: unIndent`
(function(){
function foo(x) {
return x + 1;
}
})();
`,
options: [4, { outerIIFEBody: 2 }]
},
{
code: unIndent`
(function(x, y){
function foo(x) {
return x + 1;
}
})(1, 2);
`,
options: [2, { outerIIFEBody: 0 }]
},
{
code: unIndent`
(function(){
function foo(x) {
return x + 1;
}
}());
`,
options: [2, { outerIIFEBody: 0 }]
},
{
code: unIndent`
!function(){
function foo(x) {
return x + 1;
}
}();
`,
options: [2, { outerIIFEBody: 0 }]
},
{
code: unIndent`
!function(){
\t\t\tfunction foo(x) {
\t\t\t\treturn x + 1;
\t\t\t}
}();
`,
options: ["tab", { outerIIFEBody: 3 }]
},
{
code: unIndent`
var out = function(){
function fooVar(x) {
return x + 1;
}
};
`,
options: [2, { outerIIFEBody: 0 }]
},
{
code: unIndent`
var ns = function(){
function fooVar(x) {
return x + 1;
}
}();
`,
options: [2, { outerIIFEBody: 0 }]
},
{
code: unIndent`
ns = function(){
function fooVar(x) {
return x + 1;
}
}();
`,
options: [2, { outerIIFEBody: 0 }]
},
{
code: unIndent`
var ns = (function(){
function fooVar(x) {
return x + 1;
}
}(x));
`,
options: [2, { outerIIFEBody: 0 }]
},
{
code: unIndent`
var ns = (function(){
function fooVar(x) {
return x + 1;
}
}(x));
`,
options: [4, { outerIIFEBody: 2 }]
},
{
code: unIndent`
var obj = {
foo: function() {
return true;
}
};
`,
options: [2, { outerIIFEBody: 0 }]
},
{
code: unIndent`
while (
function() {
return true;
}()) {
x = x + 1;
};
`,
options: [2, { outerIIFEBody: 20 }]
},
{
code: unIndent`
(() => {
function foo(x) {
return x + 1;
}
})();
`,
options: [2, { outerIIFEBody: 0 }]
},
{
code: unIndent`
function foo() {
}
`,
options: ["tab", { outerIIFEBody: 0 }]
},
{
code: unIndent`
;(() => {
function foo(x) {
return x + 1;
}
})();
`,
options: [2, { outerIIFEBody: 0 }]
},
{
code: unIndent`
if(data) {
console.log('hi');
}
`,
options: [2, { outerIIFEBody: 0 }]
},
{
code: unIndent`
(function(x) {
return x + 1;
})();
`,
options: [4, { outerIIFEBody: "off" }]
},
{
code: unIndent`
(function(x) {
return x + 1;
})();
`,
options: [4, { outerIIFEBody: "off" }]
},
{
code: unIndent`
;(() => {
function x(y) {
return y + 1;
}
})();
`,
options: [4, { outerIIFEBody: "off" }]
},
{
code: unIndent`
;(() => {
function x(y) {
return y + 1;
}
})();
`,
options: [4, { outerIIFEBody: "off" }]
},
{
code: unIndent`
function foo() {
}
`,
options: [4, { outerIIFEBody: "off" }]
},
{
code: "Buffer.length",
options: [4, { MemberExpression: 1 }]
},
{
code: unIndent`
Buffer
.indexOf('a')
.toString()
`,
options: [4, { MemberExpression: 1 }]
},
{
code: unIndent`
Buffer.
length
`,
options: [4, { MemberExpression: 1 }]
},
{
code: unIndent`
Buffer
.foo
.bar
`,
options: [4, { MemberExpression: 1 }]
},
{
code: unIndent`
Buffer
\t.foo
\t.bar
`,
options: ["tab", { MemberExpression: 1 }]
},
{
code: unIndent`
Buffer
.foo
.bar
`,
options: [2, { MemberExpression: 2 }]
},
unIndent`
(
foo
.bar
)
`,
unIndent`
(
(
foo
.bar
)
)
`,
unIndent`
(
foo
)
.bar
`,
unIndent`
(
(
foo
)
.bar
)
`,
unIndent`
(
(
foo
)
[
(
bar
)
]
)
`,
unIndent`
(
foo[bar]
)
.baz
`,
unIndent`
(
(foo.bar)
)
.baz
`,
{
code: unIndent`
MemberExpression
.can
.be
.turned
.off();
`,
options: [4, { MemberExpression: "off" }]
},
{
code: unIndent`
foo = bar.baz()
.bip();
`,
options: [4, { MemberExpression: 1 }]
},
unIndent`
function foo() {
new
.target
}
`,
unIndent`
function foo() {
new.
target
}
`,
{
code: unIndent`
if (foo) {
bar();
} else if (baz) {
foobar();
} else if (qux) {
qux();
}
`,
options: [2]
},
{
code: unIndent`
function foo(aaa,
bbb, ccc, ddd) {
bar();
}
`,
options: [2, { FunctionDeclaration: { parameters: 1, body: 2 } }]
},
{
code: unIndent`
function foo(aaa, bbb,
ccc, ddd) {
bar();
}
`,
options: [2, { FunctionDeclaration: { parameters: 3, body: 1 } }]
},
{
code: unIndent`
function foo(aaa,
bbb,
ccc) {
bar();
}
`,
options: [4, { FunctionDeclaration: { parameters: 1, body: 3 } }]
},
{
code: unIndent`
function foo(aaa,
bbb, ccc,
ddd, eee, fff) {
bar();
}
`,
options: [2, { FunctionDeclaration: { parameters: "first", body: 1 } }]
},
{
code: unIndent`
function foo(aaa, bbb)
{
bar();
}
`,
options: [2, { FunctionDeclaration: { body: 3 } }]
},
{
code: unIndent`
function foo(
aaa,
bbb) {
bar();
}
`,
options: [2, { FunctionDeclaration: { parameters: "first", body: 2 } }]
},
{
code: unIndent`
var foo = function(aaa,
bbb,
ccc,
ddd) {
bar();
}
`,
options: [2, { FunctionExpression: { parameters: 2, body: 0 } }]
},
{
code: unIndent`
var foo = function(aaa,
bbb,
ccc) {
bar();
}
`,
options: [2, { FunctionExpression: { parameters: 1, body: 10 } }]
},
{
code: unIndent`
var foo = function(aaa,
bbb, ccc, ddd,
eee, fff) {
bar();
}
`,
options: [4, { FunctionExpression: { parameters: "first", body: 1 } }]
},
{
code: unIndent`
var foo = function(
aaa, bbb, ccc,
ddd, eee) {
bar();
}
`,
options: [2, { FunctionExpression: { parameters: "first", body: 3 } }]
},
{
code: unIndent`
foo.bar(
baz, qux, function() {
qux;
}
);
`,
options: [2, { FunctionExpression: { body: 3 }, CallExpression: { arguments: 3 } }]
},
{
code: unIndent`
function foo() {
bar();
\tbaz();
\t \t\t\t \t\t\t \t \tqux();
}
`,
options: [2]
},
{
code: unIndent`
function foo() {
function bar() {
baz();
}
}
`,
options: [2, { FunctionDeclaration: { body: 1 } }]
},
{
code: unIndent`
function foo() {
bar();
\t\t}
`,
options: [2]
},
{
code: unIndent`
function foo() {
function bar(baz,
qux) {
foobar();
}
}
`,
options: [2, { FunctionDeclaration: { body: 1, parameters: 2 } }]
},
{
code: unIndent`
((
foo
))
`,
options: [4]
},
// ternary expressions (https://github.com/eslint/eslint/issues/7420)
{
code: unIndent`
foo
? bar
: baz
`,
options: [2]
},
{
code: unIndent`
foo = (bar ?
baz :
qux
);
`,
options: [2]
},
{
code: unIndent`
condition
? () => {
return true
}
: condition2
? () => {
return true
}
: () => {
return false
}
`,
options: [2]
},
{
code: unIndent`
condition
? () => {
return true
}
: condition2
? () => {
return true
}
: () => {
return false
}
`,
options: [2, { offsetTernaryExpressions: false }]
},
{
code: unIndent`
condition
? () => {
return true
}
: condition2
? () => {
return true
}
: () => {
return false
}
`,
options: [2, { offsetTernaryExpressions: true }]
},
{
code: unIndent`
condition
? () => {
return true
}
: condition2
? () => {
return true
}
: () => {
return false
}
`,
options: [4, { offsetTernaryExpressions: true }]
},
{
code: unIndent`
condition1
? condition2
? Promise.resolve(1)
: Promise.resolve(2)
: Promise.resolve(3)
`,
options: [2, { offsetTernaryExpressions: true }]
},
{
code: unIndent`
condition1
? Promise.resolve(1)
: condition2
? Promise.resolve(2)
: Promise.resolve(3)
`,
options: [2, { offsetTernaryExpressions: true }]
},
{
code: unIndent`
condition
\t? () => {
\t\t\treturn true
\t\t}
\t: condition2
\t\t? () => {
\t\t\t\treturn true
\t\t\t}
\t\t: () => {
\t\t\t\treturn false
\t\t\t}
`,
options: ["tab", { offsetTernaryExpressions: true }]
},
unIndent`
[
foo ?
bar :
baz,
qux
];
`,
{
/*
* Checking comments:
* https://github.com/eslint/eslint/issues/3845, https://github.com/eslint/eslint/issues/6571
*/
code: unIndent`
foo();
// Line
/* multiline
Line */
bar();
// trailing comment
`,
options: [2]
},
{
code: unIndent`
switch (foo) {
case bar:
baz();
// call the baz function
}
`,
options: [2, { SwitchCase: 1 }]
},
{
code: unIndent`
switch (foo) {
case bar:
baz();
// no default
}
`,
options: [2, { SwitchCase: 1 }]
},
unIndent`
[
// no elements
]
`,
{
/*
* Destructuring assignments:
* https://github.com/eslint/eslint/issues/6813
*/
code: unIndent`
var {
foo,
bar,
baz: qux,
foobar: baz = foobar
} = qux;
`,
options: [2]
},
{
code: unIndent`
var [
foo,
bar,
baz,
foobar = baz
] = qux;
`,
options: [2]
},
{
code: unIndent`
const {
a
}
=
{
a: 1
}
`,
options: [2]
},
{
code: unIndent`
const {
a
} = {
a: 1
}
`,
options: [2]
},
{
code: unIndent`
const
{
a
} = {
a: 1
};
`,
options: [2]
},
{
code: unIndent`
const
foo = {
bar: 1
}
`,
options: [2]
},
{
code: unIndent`
const [
a
] = [
1
]
`,
options: [2]
},
{
// https://github.com/eslint/eslint/issues/7233
code: unIndent`
var folder = filePath
.foo()
.bar;
`,
options: [2, { MemberExpression: 2 }]
},
{
code: unIndent`
for (const foo of bar)
baz();
`,
options: [2]
},
{
code: unIndent`
var x = () =>
5;
`,
options: [2]
},
unIndent`
(
foo
)(
bar
)
`,
unIndent`
(() =>
foo
)(
bar
)
`,
unIndent`
(() => {
foo();
})(
bar
)
`,
{
// Don't lint the indentation of the first token after a :
code: unIndent`
({code:
"foo.bar();"})
`,
options: [2]
},
{
// Don't lint the indentation of the first token after a :
code: unIndent`
({code:
"foo.bar();"})
`,
options: [2]
},
unIndent`
({
foo:
bar
})
`,
unIndent`
({
[foo]:
bar
})
`,
{
// Comments in switch cases
code: unIndent`
switch (foo) {
// comment
case study:
// comment
bar();
case closed:
/* multiline comment
*/
}
`,
options: [2, { SwitchCase: 1 }]
},
{
// Comments in switch cases
code: unIndent`
switch (foo) {
// comment
case study:
// the comment can also be here
case closed:
}
`,
options: [2, { SwitchCase: 1 }]
},
{
// BinaryExpressions with parens
code: unIndent`
foo && (
bar
)
`,
options: [4]
},
{
// BinaryExpressions with parens
code: unIndent`
foo && ((
bar
))
`,
options: [4]
},
{
code: unIndent`
foo &&
(
bar
)
`,
options: [4]
},
unIndent`
foo &&
!bar(
)
`,
unIndent`
foo &&
![].map(() => {
bar();
})
`,
{
code: unIndent`
foo =
bar;
`,
options: [4]
},
{
code: unIndent`
function foo() {
var bar = function(baz,
qux) {
foobar();
};
}
`,
options: [2, { FunctionExpression: { parameters: 3 } }]
},
unIndent`
function foo() {
return (bar === 1 || bar === 2 &&
(/Function/.test(grandparent.type))) &&
directives(parent).indexOf(node) >= 0;
}
`,
{
code: unIndent`
function foo() {
return (foo === bar || (
baz === qux && (
foo === foo ||
bar === bar ||
baz === baz
)
))
}
`,
options: [4]
},
unIndent`
if (
foo === 1 ||
bar === 1 ||
// comment
(baz === 1 && qux === 1)
) {}
`,
{
code: unIndent`
foo =
(bar + baz);
`,
options: [2]
},
{
code: unIndent`
function foo() {
return (bar === 1 || bar === 2) &&
(z === 3 || z === 4);
}
`,
options: [2]
},
{
code: unIndent`
/* comment */ if (foo) {
bar();
}
`,
options: [2]
},
{
// Comments at the end of if blocks that have `else` blocks can either refer to the lines above or below them
code: unIndent`
if (foo) {
bar();
// Otherwise, if foo is false, do baz.
// baz is very important.
} else {
baz();
}
`,
options: [2]
},
{
code: unIndent`
function foo() {
return ((bar === 1 || bar === 2) &&
(z === 3 || z === 4));
}
`,
options: [2]
},
{
code: unIndent`
foo(
bar,
baz,
qux
);
`,
options: [2, { CallExpression: { arguments: 1 } }]
},
{
code: unIndent`
foo(
\tbar,
\tbaz,
\tqux
);
`,
options: ["tab", { CallExpression: { arguments: 1 } }]
},
{
code: unIndent`
foo(bar,
baz,
qux);
`,
options: [4, { CallExpression: { arguments: 2 } }]
},
{
code: unIndent`
foo(
bar,
baz,
qux
);
`,
options: [2, { CallExpression: { arguments: 0 } }]
},
{
code: unIndent`
foo(bar,
baz,
qux
);
`,
options: [2, { CallExpression: { arguments: "first" } }]
},
{
code: unIndent`
foo(bar, baz,
qux, barbaz,
barqux, bazqux);
`,
options: [2, { CallExpression: { arguments: "first" } }]
},
{
code: unIndent`
foo(bar,
1 + 2,
!baz,
new Car('!')
);
`,
options: [2, { CallExpression: { arguments: 4 } }]
},
unIndent`
foo(
(bar)
);
`,
{
code: unIndent`
foo(
(bar)
);
`,
options: [4, { CallExpression: { arguments: 1 } }]
},
// https://github.com/eslint/eslint/issues/7484
{
code: unIndent`
var foo = function() {
return bar(
[{
}].concat(baz)
);
};
`,
options: [2]
},
// https://github.com/eslint/eslint/issues/7573
{
code: unIndent`
return (
foo
);
`,
parserOptions: { ecmaFeatures: { globalReturn: true } }
},
{
code: unIndent`
return (
foo
)
`,
parserOptions: { ecmaFeatures: { globalReturn: true } }
},
unIndent`
var foo = [
bar,
baz
]
`,
unIndent`
var foo = [bar,
baz,
qux
]
`,
{
code: unIndent`
var foo = [bar,
baz,
qux
]
`,
options: [2, { ArrayExpression: 0 }]
},
{
code: unIndent`
var foo = [bar,
baz,
qux
]
`,
options: [2, { ArrayExpression: 8 }]
},
{
code: unIndent`
var foo = [bar,
baz,
qux
]
`,
options: [2, { ArrayExpression: "first" }]
},
{
code: unIndent`
var foo = [bar,
baz, qux
]
`,
options: [2, { ArrayExpression: "first" }]
},
{
code: unIndent`
var foo = [
{ bar: 1,
baz: 2 },
{ bar: 3,
baz: 4 }
]
`,
options: [4, { ArrayExpression: 2, ObjectExpression: "first" }]
},
{
code: unIndent`
var foo = {
bar: 1,
baz: 2
};
`,
options: [2, { ObjectExpression: 0 }]
},
{
code: unIndent`
var foo = { foo: 1, bar: 2,
baz: 3 }
`,
options: [2, { ObjectExpression: "first" }]
},
{
code: unIndent`
var foo = [
{
foo: 1
}
]
`,
options: [4, { ArrayExpression: 2 }]
},
{
code: unIndent`
function foo() {
[
foo
]
}
`,
options: [2, { ArrayExpression: 4 }]
},
{
code: "[\n]",
options: [2, { ArrayExpression: "first" }]
},
{
code: "[\n]",
options: [2, { ArrayExpression: 1 }]
},
{
code: "{\n}",
options: [2, { ObjectExpression: "first" }]
},
{
code: "{\n}",
options: [2, { ObjectExpression: 1 }]
},
{
code: unIndent`
var foo = [
[
1
]
]
`,
options: [2, { ArrayExpression: "first" }]
},
{
code: unIndent`
var foo = [ 1,
[
2
]
];
`,
options: [2, { ArrayExpression: "first" }]
},
{
code: unIndent`
var foo = bar(1,
[ 2,
3
]
);
`,
options: [4, { ArrayExpression: "first", CallExpression: { arguments: "first" } }]
},
{
code: unIndent`
var foo =
[
]()
`,
options: [4, { CallExpression: { arguments: "first" }, ArrayExpression: "first" }]
},
// https://github.com/eslint/eslint/issues/7732
{
code: unIndent`
const lambda = foo => {
Object.assign({},
filterName,
{
display
}
);
}
`,
options: [2, { ObjectExpression: 1 }]
},
{
code: unIndent`
const lambda = foo => {
Object.assign({},
filterName,
{
display
}
);
}
`,
options: [2, { ObjectExpression: "first" }]
},
// https://github.com/eslint/eslint/issues/7733
{
code: unIndent`
var foo = function() {
\twindow.foo('foo',
\t\t{
\t\t\tfoo: 'bar',
\t\t\tbar: {
\t\t\t\tfoo: 'bar'
\t\t\t}
\t\t}
\t);
}
`,
options: ["tab"]
},
{
code: unIndent`
echo = spawn('cmd.exe',
['foo', 'bar',
'baz']);
`,
options: [2, { ArrayExpression: "first", CallExpression: { arguments: "first" } }]
},
{
code: unIndent`
if (foo)
bar();
// Otherwise, if foo is false, do baz.
// baz is very important.
else {
baz();
}
`,
options: [2]
},
{
code: unIndent`
if (
foo && bar ||
baz && qux // This line is ignored because BinaryExpressions are not checked.
) {
qux();
}
`,
options: [4]
},
unIndent`
[
] || [
]
`,
unIndent`
(
[
] || [
]
)
`,
unIndent`
1
+ (
1
)
`,
unIndent`
(
foo && (
bar ||
baz
)
)
`,
unIndent`
foo
|| (
bar
)
`,
unIndent`
foo
|| (
bar
)
`,
{
code: unIndent`
var foo =
1;
`,
options: [4, { VariableDeclarator: 2 }]
},
{
code: unIndent`
var foo = 1,
bar =
2;
`,
options: [4]
},
{
code: unIndent`
switch (foo) {
case bar:
{
baz();
}
}
`,
options: [2, { SwitchCase: 1 }]
},
// Template curlies
{
code: unIndent`
\`foo\${
bar}\`
`,
options: [2]
},
{
code: unIndent`
\`foo\${
\`bar\${
baz}\`}\`
`,
options: [2]
},
{
code: unIndent`
\`foo\${
\`bar\${
baz
}\`
}\`
`,
options: [2]
},
{
code: unIndent`
\`foo\${
(
bar
)
}\`
`,
options: [2]
},
unIndent`
foo(\`
bar
\`, {
baz: 1
});
`,
unIndent`
function foo() {
\`foo\${bar}baz\${
qux}foo\${
bar}baz\`
}
`,
unIndent`
JSON
.stringify(
{
ok: true
}
);
`,
// Don't check AssignmentExpression assignments
unIndent`
foo =
bar =
baz;
`,
unIndent`
foo =
bar =
baz;
`,
unIndent`
function foo() {
const template = \`this indentation is not checked
because it's part of a template literal.\`;
}
`,
unIndent`
function foo() {
const template = \`the indentation of a \${
node.type
} node is checked.\`;
}
`,
{
// https://github.com/eslint/eslint/issues/7320
code: unIndent`
JSON
.stringify(
{
test: 'test'
}
);
`,
options: [4, { CallExpression: { arguments: 1 } }]
},
unIndent`
[
foo,
// comment
// another comment
bar
]
`,
unIndent`
if (foo) {
/* comment */ bar();
}
`,
unIndent`
function foo() {
return (
1
);
}
`,
unIndent`
function foo() {
return (
1
)
}
`,
unIndent`
if (
foo &&
!(
bar
)
) {}
`,
{
// https://github.com/eslint/eslint/issues/6007
code: unIndent`
var abc = [
(
''
),
def,
]
`,
options: [2]
},
{
code: unIndent`
var abc = [
(
''
),
(
'bar'
)
]
`,
options: [2]
},
unIndent`
function f() {
return asyncCall()
.then(
'some string',
[
1,
2,
3
]
);
}
`,
{
// https://github.com/eslint/eslint/issues/6670
code: unIndent`
function f() {
return asyncCall()
.then(
'some string',
[
1,
2,
3
]
);
}
`,
options: [4, { MemberExpression: 1 }]
},
// https://github.com/eslint/eslint/issues/7242
unIndent`
var x = [
[1],
[2]
]
`,
unIndent`
var y = [
{a: 1},
{b: 2}
]
`,
unIndent`
foo(
)
`,
{
// https://github.com/eslint/eslint/issues/7616
code: unIndent`
foo(
bar,
{
baz: 1
}
)
`,
options: [4, { CallExpression: { arguments: "first" } }]
},
"new Foo",
"new (Foo)",
unIndent`
if (Foo) {
new Foo
}
`,
{
code: unIndent`
var foo = 0, bar = 0, baz = 0;
export {
foo,
bar,
baz
}
`,
parserOptions: { ecmaVersion: 6, sourceType: "module" }
},
{
code: unIndent`
foo
? bar
: baz
`,
options: [4, { flatTernaryExpressions: true }]
},
{
code: unIndent`
foo ?
bar :
baz
`,
options: [4, { flatTernaryExpressions: true }]
},
{
code: unIndent`
foo ?
bar
: baz
`,
options: [4, { flatTernaryExpressions: true }]
},
{
code: unIndent`
foo
? bar :
baz
`,
options: [4, { flatTernaryExpressions: true }]
},
{
code: unIndent`
foo
? bar
: baz
? qux
: foobar
? boop
: beep
`,
options: [4, { flatTernaryExpressions: true }]
},
{
code: unIndent`
foo ?
bar :
baz ?
qux :
foobar ?
boop :
beep
`,
options: [4, { flatTernaryExpressions: true }]
},
{
code: unIndent`
var a =
foo ? bar :
baz ? qux :
foobar ? boop :
/*else*/ beep
`,
options: [4, { flatTernaryExpressions: true }]
},
{
code: unIndent`
var a = foo
? bar
: baz
`,
options: [4, { flatTernaryExpressions: true }]
},
{
code: unIndent`
var a =
foo
? bar
: baz
`,
options: [4, { flatTernaryExpressions: true }]
},
{
code: unIndent`
a =
foo ? bar :
baz ? qux :
foobar ? boop :
/*else*/ beep
`,
options: [4, { flatTernaryExpressions: true }]
},
{
code: unIndent`
a = foo
? bar
: baz
`,
options: [4, { flatTernaryExpressions: true }]
},
{
code: unIndent`
a =
foo
? bar
: baz
`,
options: [4, { flatTernaryExpressions: true }]
},
{
code: unIndent`
foo(
foo ? bar :
baz ? qux :
foobar ? boop :
/*else*/ beep
)
`,
options: [4, { flatTernaryExpressions: true }]
},
{
code: unIndent`
function wrap() {
return (
foo ? bar :
baz ? qux :
foobar ? boop :
/*else*/ beep
)
}
`,
options: [4, { flatTernaryExpressions: true }]
},
{
code: unIndent`
function wrap() {
return foo
? bar
: baz
}
`,
options: [4, { flatTernaryExpressions: true }]
},
{
code: unIndent`
function wrap() {
return (
foo
? bar
: baz
)
}
`,
options: [4, { flatTernaryExpressions: true }]
},
{
code: unIndent`
foo(
foo
? bar
: baz
)
`,
options: [4, { flatTernaryExpressions: true }]
},
{
code: unIndent`
foo(foo
? bar
: baz
)
`,
options: [4, { flatTernaryExpressions: true }]
},
{
code: unIndent`
foo
? bar
: baz
? qux
: foobar
? boop
: beep
`,
options: [4, { flatTernaryExpressions: false }]
},
{
code: unIndent`
foo ?
bar :
baz ?
qux :
foobar ?
boop :
beep
`,
options: [4, { flatTernaryExpressions: false }]
},
{
code: "[,]",
options: [2, { ArrayExpression: "first" }]
},
{
code: "[,]",
options: [2, { ArrayExpression: "off" }]
},
{
code: unIndent`
[
,
foo
]
`,
options: [4, { ArrayExpression: "first" }]
},
{
code: "[sparse, , array];",
options: [2, { ArrayExpression: "first" }]
},
{
code: unIndent`
foo.bar('baz', function(err) {
qux;
});
`,
options: [2, { CallExpression: { arguments: "first" } }]
},
{
code: unIndent`
foo.bar(function() {
cookies;
}).baz(function() {
cookies;
});
`,
options: [2, { MemberExpression: 1 }]
},
{
code: unIndent`
foo.bar().baz(function() {
cookies;
}).qux(function() {
cookies;
});
`,
options: [2, { MemberExpression: 1 }]
},
{
code: unIndent`
(
{
foo: 1,
baz: 2
}
);
`,
options: [2, { ObjectExpression: "first" }]
},
{
code: unIndent`
foo(() => {
bar;
}, () => {
baz;
})
`,
options: [4, { CallExpression: { arguments: "first" } }]
},
{
code: unIndent`
[ foo,
bar ].forEach(function() {
baz;
})
`,
options: [2, { ArrayExpression: "first", MemberExpression: 1 }]
},
unIndent`
foo = bar[
baz
];
`,
{
code: unIndent`
foo[
bar
];
`,
options: [4, { MemberExpression: 1 }]
},
{
code: unIndent`
foo[
(
bar
)
];
`,
options: [4, { MemberExpression: 1 }]
},
unIndent`
if (foo)
bar;
else if (baz)
qux;
`,
unIndent`
if (foo) bar()
; [1, 2, 3].map(baz)
`,
unIndent`
if (foo)
;
`,
"x => {}",
{
code: unIndent`
import {foo}
from 'bar';
`,
parserOptions: { ecmaVersion: 6, sourceType: "module" }
},
{
code: "import 'foo'",
parserOptions: { ecmaVersion: 6, sourceType: "module" }
},
{
code: unIndent`
import { foo,
bar,
baz,
} from 'qux';
`,
options: [4, { ImportDeclaration: 1 }],
parserOptions: { ecmaVersion: 6, sourceType: "module" }
},
{
code: unIndent`
import {
foo,
bar,
baz,
} from 'qux';
`,
options: [4, { ImportDeclaration: 1 }],
parserOptions: { ecmaVersion: 6, sourceType: "module" }
},
{
code: unIndent`
import { apple as a,
banana as b } from 'fruits';
import { cat } from 'animals';
`,
options: [4, { ImportDeclaration: "first" }],
parserOptions: { ecmaVersion: 6, sourceType: "module" }
},
{
code: unIndent`
import { declaration,
can,
be,
turned } from 'off';
`,
options: [4, { ImportDeclaration: "off" }],
parserOptions: { ecmaVersion: 6, sourceType: "module" }
},
// https://github.com/eslint/eslint/issues/8455
unIndent`
(
a
) => b => {
c
}
`,
unIndent`
(
a
) => b => c => d => {
e
}
`,
unIndent`
(
a
) =>
(
b
) => {
c
}
`,
unIndent`
if (
foo
) bar(
baz
);
`,
unIndent`
if (foo)
{
bar();
}
`,
unIndent`
function foo(bar)
{
baz();
}
`,
unIndent`
() =>
({})
`,
unIndent`
() =>
(({}))
`,
unIndent`
(
() =>
({})
)
`,
unIndent`
var x = function foop(bar)
{
baz();
}
`,
unIndent`
var x = (bar) =>
{
baz();
}
`,
unIndent`
class Foo
{
constructor()
{
foo();
}
bar()
{
baz();
}
}
`,
unIndent`
class Foo
extends Bar
{
constructor()
{
foo();
}
bar()
{
baz();
}
}
`,
unIndent`
(
class Foo
{
constructor()
{
foo();
}
bar()
{
baz();
}
}
)
`,
{
code: unIndent`
switch (foo)
{
case 1:
bar();
}
`,
options: [4, { SwitchCase: 1 }]
},
unIndent`
foo
.bar(function() {
baz
})
`,
{
code: unIndent`
foo
.bar(function() {
baz
})
`,
options: [4, { MemberExpression: 2 }]
},
unIndent`
foo
[bar](function() {
baz
})
`,
unIndent`
foo.
bar.
baz
`,
{
code: unIndent`
foo
.bar(function() {
baz
})
`,
options: [4, { MemberExpression: "off" }]
},
{
code: unIndent`
foo
.bar(function() {
baz
})
`,
options: [4, { MemberExpression: "off" }]
},
{
code: unIndent`
foo
[bar](function() {
baz
})
`,
options: [4, { MemberExpression: "off" }]
},
{
code: unIndent`
foo.
bar.
baz
`,
options: [4, { MemberExpression: "off" }]
},
{
code: unIndent`
foo = bar(
).baz(
)
`,
options: [4, { MemberExpression: "off" }]
},
{
code: unIndent`
foo[
bar ? baz :
qux
]
`,
options: [4, { flatTernaryExpressions: true }]
},
{
code: unIndent`
function foo() {
return foo ? bar :
baz
}
`,
options: [4, { flatTernaryExpressions: true }]
},
{
code: unIndent`
throw foo ? bar :
baz
`,
options: [4, { flatTernaryExpressions: true }]
},
{
code: unIndent`
foo(
bar
) ? baz :
qux
`,
options: [4, { flatTernaryExpressions: true }]
},
unIndent`
foo
[
bar
]
.baz(function() {
quz();
})
`,
unIndent`
[
foo
][
"map"](function() {
qux();
})
`,
unIndent`
(
a.b(function() {
c;
})
)
`,
unIndent`
(
foo
).bar(function() {
baz();
})
`,
unIndent`
new Foo(
bar
.baz
.qux
)
`,
unIndent`
const foo = a.b(),
longName =
(baz(
'bar',
'bar'
));
`,
unIndent`
const foo = a.b(),
longName =
(baz(
'bar',
'bar'
));
`,
unIndent`
const foo = a.b(),
longName =
baz(
'bar',
'bar'
);
`,
unIndent`
const foo = a.b(),
longName =
baz(
'bar',
'bar'
);
`,
unIndent`
const foo = a.b(),
longName
= baz(
'bar',
'bar'
);
`,
unIndent`
const foo = a.b(),
longName
= baz(
'bar',
'bar'
);
`,
unIndent`
const foo = a.b(),
longName =
('fff');
`,
unIndent`
const foo = a.b(),
longName =
('fff');
`,
unIndent`
const foo = a.b(),
longName
= ('fff');
`,
unIndent`
const foo = a.b(),
longName
= ('fff');
`,
unIndent`
const foo = a.b(),
longName =
(
'fff'
);
`,
unIndent`
const foo = a.b(),
longName =
(
'fff'
);
`,
unIndent`
const foo = a.b(),
longName
=(
'fff'
);
`,
unIndent`
const foo = a.b(),
longName
=(
'fff'
);
`,
//----------------------------------------------------------------------
// Ignore Unknown Nodes
//----------------------------------------------------------------------
{
code: unIndent`
interface Foo {
bar: string;
baz: number;
}
`,
parser: parser("unknown-nodes/interface")
},
{
code: unIndent`
namespace Foo {
const bar = 3,
baz = 2;
if (true) {
const bax = 3;
}
}
`,
parser: parser("unknown-nodes/namespace-valid")
},
{
code: unIndent`
abstract class Foo {
public bar() {
let aaa = 4,
boo;
if (true) {
boo = 3;
}
boo = 3 + 2;
}
}
`,
parser: parser("unknown-nodes/abstract-class-valid")
},
{
code: unIndent`
function foo() {
function bar() {
abstract class X {
public baz() {
if (true) {
qux();
}
}
}
}
}
`,
parser: parser("unknown-nodes/functions-with-abstract-class-valid")
},
{
code: unIndent`
namespace Unknown {
function foo() {
function bar() {
abstract class X {
public baz() {
if (true) {
qux();
}
}
}
}
}
}
`,
parser: parser("unknown-nodes/namespace-with-functions-with-abstract-class-valid")
},
{
code: unIndent`
type httpMethod = 'GET'
| 'POST'
| 'PUT';
`,
options: [2, { VariableDeclarator: 0 }],
parser: parser("unknown-nodes/variable-declarator-type-indent-two-spaces")
},
{
code: unIndent`
type httpMethod = 'GET'
| 'POST'
| 'PUT';
`,
options: [2, { VariableDeclarator: 1 }],
parser: parser("unknown-nodes/variable-declarator-type-no-indent")
},
unIndent`
foo(\`foo
\`, {
ok: true
},
{
ok: false
})
`,
unIndent`
foo(tag\`foo
\`, {
ok: true
},
{
ok: false
}
)
`,
// https://github.com/eslint/eslint/issues/8815
unIndent`
async function test() {
const {
foo,
bar,
} = await doSomethingAsync(
1,
2,
3,
);
}
`,
unIndent`
function* test() {
const {
foo,
bar,
} = yield doSomethingAsync(
1,
2,
3,
);
}
`,
unIndent`
({
a: b
} = +foo(
bar
));
`,
unIndent`
const {
foo,
bar,
} = typeof foo(
1,
2,
3,
);
`,
unIndent`
const {
foo,
bar,
} = +(
foo
);
`,
//----------------------------------------------------------------------
// JSX tests
// https://github.com/eslint/eslint/issues/8425
// Some of the following tests are adapted from the tests in eslint-plugin-react.
// License: https://github.com/yannickcr/eslint-plugin-react/blob/7ca9841f22d599f447a27ef5b2a97def9229d6c8/LICENSE
//----------------------------------------------------------------------
"<Foo a=\"b\" c=\"d\"/>;",
unIndent`
<Foo
a="b"
c="d"
/>;
`,
"var foo = <Bar a=\"b\" c=\"d\"/>;",
unIndent`
var foo = <Bar
a="b"
c="d"
/>;
`,
unIndent`
var foo = (<Bar
a="b"
c="d"
/>);
`,
unIndent`
var foo = (
<Bar
a="b"
c="d"
/>
);
`,
unIndent`
<
Foo
a="b"
c="d"
/>;
`,
unIndent`
<Foo
a="b"
c="d"/>;
`,
unIndent`
<
Foo
a="b"
c="d"/>;
`,
"<a href=\"foo\">bar</a>;",
unIndent`
<a href="foo">
bar
</a>;
`,
unIndent`
<a
href="foo"
>
bar
</a>;
`,
unIndent`
<a
href="foo">
bar
</a>;
`,
unIndent`
<
a
href="foo">
bar
</a>;
`,
unIndent`
<a
href="foo">
bar
</
a>;
`,
unIndent`
<a
href="foo">
bar
</a
>;
`,
unIndent`
var foo = <a href="bar">
baz
</a>;
`,
unIndent`
var foo = <a
href="bar"
>
baz
</a>;
`,
unIndent`
var foo = <a
href="bar">
baz
</a>;
`,
unIndent`
var foo = <
a
href="bar">
baz
</a>;
`,
unIndent`
var foo = <a
href="bar">
baz
</
a>;
`,
unIndent`
var foo = <a
href="bar">
baz
</a
>
`,
unIndent`
var foo = (<a
href="bar">
baz
</a>);
`,
unIndent`
var foo = (
<a href="bar">baz</a>
);
`,
unIndent`
var foo = (
<a href="bar">
baz
</a>
);
`,
unIndent`
var foo = (
<a
href="bar">
baz
</a>
);
`,
"var foo = <a href=\"bar\">baz</a>;",
unIndent`
<a>
{
}
</a>
`,
unIndent`
<a>
{
foo
}
</a>
`,
unIndent`
function foo() {
return (
<a>
{
b.forEach(() => {
// comment
a = c
.d()
.e();
})
}
</a>
);
}
`,
"<App></App>",
unIndent`
<App>
</App>
`,
{
code: unIndent`
<App>
<Foo />
</App>
`,
options: [2]
},
{
code: unIndent`
<App>
<Foo />
</App>
`,
options: [0]
},
{
code: unIndent`
<App>
\t<Foo />
</App>
`,
options: ["tab"]
},
{
code: unIndent`
function App() {
return <App>
<Foo />
</App>;
}
`,
options: [2]
},
{
code: unIndent`
function App() {
return (<App>
<Foo />
</App>);
}
`,
options: [2]
},
{
code: unIndent`
function App() {
return (
<App>
<Foo />
</App>
);
}
`,
options: [2]
},
{
code: unIndent`
it(
(
<div>
<span />
</div>
)
)
`,
options: [2]
},
{
code: unIndent`
it(
(<div>
<span />
<span />
<span />
</div>)
)
`,
options: [2]
},
{
code: unIndent`
(
<div>
<span />
</div>
)
`,
options: [2]
},
{
code: unIndent`
{
head.title &&
<h1>
{head.title}
</h1>
}
`,
options: [2]
},
{
code: unIndent`
{
head.title &&
<h1>
{head.title}
</h1>
}
`,
options: [2]
},
{
code: unIndent`
{
head.title && (
<h1>
{head.title}
</h1>)
}
`,
options: [2]
},
{
code: unIndent`
{
head.title && (
<h1>
{head.title}
</h1>
)
}
`,
options: [2]
},
{
code: unIndent`
[
<div />,
<div />
]
`,
options: [2]
},
unIndent`
<div>
{
[
<Foo />,
<Bar />
]
}
</div>
`,
unIndent`
<div>
{foo &&
[
<Foo />,
<Bar />
]
}
</div>
`,
unIndent`
<div>
bar <div>
bar
bar {foo}
bar </div>
</div>
`,
unIndent`
foo ?
<Foo /> :
<Bar />
`,
unIndent`
foo ?
<Foo />
: <Bar />
`,
unIndent`
foo ?
<Foo />
:
<Bar />
`,
unIndent`
<div>
{!foo ?
<Foo
onClick={this.onClick}
/>
:
<Bar
onClick={this.onClick}
/>
}
</div>
`,
{
code: unIndent`
<span>
{condition ?
<Thing
foo={\`bar\`}
/> :
<Thing/>
}
</span>
`,
options: [2]
},
{
code: unIndent`
<span>
{condition ?
<Thing
foo={"bar"}
/> :
<Thing/>
}
</span>
`,
options: [2]
},
{
code: unIndent`
function foo() {
<span>
{condition ?
<Thing
foo={bar}
/> :
<Thing/>
}
</span>
}
`,
options: [2]
},
unIndent`
<App foo
/>
`,
{
code: unIndent`
<App
foo
/>
`,
options: [2]
},
{
code: unIndent`
<App
foo
/>
`,
options: [0]
},
{
code: unIndent`
<App
\tfoo
/>
`,
options: ["tab"]
},
unIndent`
<App
foo
/>
`,
unIndent`
<App
foo
></App>
`,
{
code: unIndent`
<App
foo={function() {
console.log('bar');
}}
/>
`,
options: [2]
},
{
code: unIndent`
<App foo={function() {
console.log('bar');
}}
/>
`,
options: [2]
},
{
code: unIndent`
var x = function() {
return <App
foo={function() {
console.log('bar');
}}
/>
}
`,
options: [2]
},
{
code: unIndent`
var x = <App
foo={function() {
console.log('bar');
}}
/>
`,
options: [2]
},
{
code: unIndent`
<Provider
store
>
<App
foo={function() {
console.log('bar');
}}
/>
</Provider>
`,
options: [2]
},
{
code: unIndent`
<Provider
store
>
{baz && <App
foo={function() {
console.log('bar');
}}
/>}
</Provider>
`,
options: [2]
},
{
code: unIndent`
<App
\tfoo
/>
`,
options: ["tab"]
},
{
code: unIndent`
<App
\tfoo
></App>
`,
options: ["tab"]
},
{
code: unIndent`
<App foo={function() {
\tconsole.log('bar');
}}
/>
`,
options: ["tab"]
},
{
code: unIndent`
var x = <App
\tfoo={function() {
\t\tconsole.log('bar');
\t}}
/>
`,
options: ["tab"]
},
unIndent`
<App
foo />
`,
unIndent`
<div>
unrelated{
foo
}
</div>
`,
unIndent`
<div>unrelated{
foo
}
</div>
`,
unIndent`
<
foo
.bar
.baz
>
foo
</
foo.
bar.
baz
>
`,
unIndent`
<
input
type=
"number"
/>
`,
unIndent`
<
input
type=
{'number'}
/>
`,
unIndent`
<
input
type
="number"
/>
`,
unIndent`
foo ? (
bar
) : (
baz
)
`,
unIndent`
foo ? (
<div>
</div>
) : (
<span>
</span>
)
`,
unIndent`
<div>
{
/* foo */
}
</div>
`,
/*
* JSX Fragments
* https://github.com/eslint/eslint/issues/12208
*/
unIndent`
<>
<A />
</>
`,
unIndent`
<
>
<A />
</>
`,
unIndent`
<>
<A />
<
/>
`,
unIndent`
<>
<A />
</
>
`,
unIndent`
<
>
<A />
</
>
`,
unIndent`
<
>
<A />
<
/>
`,
unIndent`
< // Comment
>
<A />
</>
`,
unIndent`
<
// Comment
>
<A />
</>
`,
unIndent`
<
// Comment
>
<A />
</>
`,
unIndent`
<>
<A />
< // Comment
/>
`,
unIndent`
<>
<A />
<
// Comment
/>
`,
unIndent`
<>
<A />
<
// Comment
/>
`,
unIndent`
<>
<A />
</ // Comment
>
`,
unIndent`
<>
<A />
</
// Comment
>
`,
unIndent`
<>
<A />
</
// Comment
>
`,
unIndent`
< /* Comment */
>
<A />
</>
`,
unIndent`
<
/* Comment */
>
<A />
</>
`,
unIndent`
<
/* Comment */
>
<A />
</>
`,
unIndent`
<
/*
* Comment
*/
>
<A />
</>
`,
unIndent`
<
/*
* Comment
*/
>
<A />
</>
`,
unIndent`
<>
<A />
< /* Comment */
/>
`,
unIndent`
<>
<A />
<
/* Comment */ />
`,
unIndent`
<>
<A />
<
/* Comment */ />
`,
unIndent`
<>
<A />
<
/* Comment */
/>
`,
unIndent`
<>
<A />
<
/* Comment */
/>
`,
unIndent`
<>
<A />
</ /* Comment */
>
`,
unIndent`
<>
<A />
</
/* Comment */ >
`,
unIndent`
<>
<A />
</
/* Comment */ >
`,
unIndent`
<>
<A />
</
/* Comment */
>
`,
unIndent`
<>
<A />
</
/* Comment */
>
`,
// https://github.com/eslint/eslint/issues/8832
unIndent`
<div>
{
(
1
)
}
</div>
`,
unIndent`
function A() {
return (
<div>
{
b && (
<div>
</div>
)
}
</div>
);
}
`,
unIndent`
<div>foo
<div>bar</div>
</div>
`,
unIndent`
<small>Foo bar
<a>baz qux</a>.
</small>
`,
unIndent`
<div
{...props}
/>
`,
unIndent`
<div
{
...props
}
/>
`,
{
code: unIndent`
a(b
, c
)
`,
options: [2, { CallExpression: { arguments: "off" } }]
},
{
code: unIndent`
a(
new B({
c,
})
);
`,
options: [2, { CallExpression: { arguments: "off" } }]
},
{
code: unIndent`
foo
? bar
: baz
`,
options: [4, { ignoredNodes: ["ConditionalExpression"] }]
},
{
code: unIndent`
class Foo {
foo() {
bar();
}
}
`,
options: [4, { ignoredNodes: ["ClassBody"] }]
},
{
code: unIndent`
class Foo {
foo() {
bar();
}
}
`,
options: [4, { ignoredNodes: ["ClassBody", "BlockStatement"] }]
},
{
code: unIndent`
foo({
bar: 1
},
{
baz: 2
},
{
qux: 3
})
`,
options: [4, { ignoredNodes: ["CallExpression > ObjectExpression"] }]
},
{
code: unIndent`
foo
.bar
`,
options: [4, { ignoredNodes: ["MemberExpression"] }]
},
{
code: unIndent`
$(function() {
foo();
bar();
});
`,
options: [4, {
ignoredNodes: ["Program > ExpressionStatement > CallExpression[callee.name='$'] > FunctionExpression > BlockStatement"]
}]
},
{
code: unIndent`
<Foo
bar="1" />
`,
options: [4, { ignoredNodes: ["JSXOpeningElement"] }]
},
{
code: unIndent`
foo &&
<Bar
>
</Bar>
`,
options: [4, { ignoredNodes: ["JSXElement", "JSXOpeningElement"] }]
},
{
code: unIndent`
(function($) {
$(function() {
foo;
});
}())
`,
options: [4, { ignoredNodes: ["ExpressionStatement > CallExpression > FunctionExpression.callee > BlockStatement"] }]
},
{
code: unIndent`
const value = (
condition ?
valueIfTrue :
valueIfFalse
);
`,
options: [4, { ignoredNodes: ["ConditionalExpression"] }]
},
{
code: unIndent`
var a = 0, b = 0, c = 0;
export default foo(
a,
b, {
c
}
)
`,
options: [4, { ignoredNodes: ["ExportDefaultDeclaration > CallExpression > ObjectExpression"] }],
parserOptions: { ecmaVersion: 6, sourceType: "module" }
},
{
code: unIndent`
foobar = baz
? qux
: boop
`,
options: [4, { ignoredNodes: ["ConditionalExpression"] }]
},
{
code: unIndent`
\`
SELECT
\${
foo
} FROM THE_DATABASE
\`
`,
options: [4, { ignoredNodes: ["TemplateLiteral"] }]
},
{
code: unIndent`
<foo
prop='bar'
>
Text
</foo>
`,
options: [4, { ignoredNodes: ["JSXOpeningElement"] }]
},
{
code: unIndent`
{
\tvar x = 1,
\t y = 2;
}
`,
options: ["tab"]
},
{
code: unIndent`
var x = 1,
y = 2;
var z;
`,
options: ["tab", { ignoredNodes: ["VariableDeclarator"] }]
},
{
code: unIndent`
[
foo(),
bar
]
`,
options: ["tab", { ArrayExpression: "first", ignoredNodes: ["CallExpression"] }]
},
{
code: unIndent`
if (foo) {
doSomething();
// Intentionally unindented comment
doSomethingElse();
}
`,
options: [4, { ignoreComments: true }]
},
{
code: unIndent`
if (foo) {
doSomething();
/* Intentionally unindented comment */
doSomethingElse();
}
`,
options: [4, { ignoreComments: true }]
},
unIndent`
const obj = {
foo () {
return condition ? // comment
1 :
2
}
}
`,
//----------------------------------------------------------------------
// Comment alignment tests
//----------------------------------------------------------------------
unIndent`
if (foo) {
// Comment can align with code immediately above even if "incorrect" alignment
doSomething();
}
`,
unIndent`
if (foo) {
doSomething();
// Comment can align with code immediately below even if "incorrect" alignment
}
`,
unIndent`
if (foo) {
// Comment can be in correct alignment even if not aligned with code above/below
}
`,
unIndent`
if (foo) {
// Comment can be in correct alignment even if gaps between (and not aligned with) code above/below
}
`,
unIndent`
[{
foo
},
// Comment between nodes
{
bar
}];
`,
unIndent`
[{
foo
},
// Comment between nodes
{ // comment
bar
}];
`,
unIndent`
let foo
// comment
;(async () => {})()
`,
unIndent`
let foo
// comment
;(async () => {})()
`,
unIndent`
let foo
// comment
;(async () => {})()
`,
unIndent`
let foo
// comment
;(async () => {})()
`,
unIndent`
let foo
/* comment */;
(async () => {})()
`,
unIndent`
let foo
/* comment */;
(async () => {})()
`,
unIndent`
let foo
/* comment */;
(async () => {})()
`,
unIndent`
let foo
/* comment */;
(async () => {})()
`,
unIndent`
let foo
/* comment */;
(async () => {})()
`,
unIndent`
let foo
/* comment */;
(async () => {})()
`,
unIndent`
// comment
;(async () => {})()
`,
unIndent`
// comment
;(async () => {})()
`,
unIndent`
{
let foo
// comment
;(async () => {})()
}
`,
unIndent`
{
let foo
// comment
;(async () => {})()
}
`,
unIndent`
{
// comment
;(async () => {})()
}
`,
unIndent`
{
// comment
;(async () => {})()
}
`,
unIndent`
const foo = 1
const bar = foo
/* comment */
;[1, 2, 3].forEach(() => {})
`,
unIndent`
const foo = 1
const bar = foo
/* comment */
;[1, 2, 3].forEach(() => {})
`,
unIndent`
const foo = 1
const bar = foo
/* comment */
;[1, 2, 3].forEach(() => {})
`,
unIndent`
const foo = 1
const bar = foo
/* comment */
;[1, 2, 3].forEach(() => {})
`,
unIndent`
const foo = 1
const bar = foo
/* comment */;
[1, 2, 3].forEach(() => {})
`,
unIndent`
const foo = 1
const bar = foo
/* comment */;
[1, 2, 3].forEach(() => {})
`,
unIndent`
const foo = 1
const bar = foo
/* comment */;
[1, 2, 3].forEach(() => {})
`,
unIndent`
const foo = 1
const bar = foo
/* comment */;
[1, 2, 3].forEach(() => {})
`,
unIndent`
const foo = 1
const bar = foo
/* comment */;
[1, 2, 3].forEach(() => {})
`,
unIndent`
const foo = 1
const bar = foo
/* comment */;
[1, 2, 3].forEach(() => {})
`,
unIndent`
/* comment */
;[1, 2, 3].forEach(() => {})
`,
unIndent`
/* comment */
;[1, 2, 3].forEach(() => {})
`,
unIndent`
{
const foo = 1
const bar = foo
/* comment */
;[1, 2, 3].forEach(() => {})
}
`,
unIndent`
{
const foo = 1
const bar = foo
/* comment */
;[1, 2, 3].forEach(() => {})
}
`,
unIndent`
{
/* comment */
;[1, 2, 3].forEach(() => {})
}
`,
unIndent`
{
/* comment */
;[1, 2, 3].forEach(() => {})
}
`,
// import expressions
{
code: unIndent`
import(
// before
source
// after
)
`,
parserOptions: { ecmaVersion: 2020 }
},
// https://github.com/eslint/eslint/issues/12122
{
code: unIndent`
foo(() => {
tag\`
multiline
template
literal
\`(() => {
bar();
});
});
`,
parserOptions: { ecmaVersion: 2015 }
},
{
code: unIndent`
{
tag\`
multiline
template
\${a} \${b}
literal
\`(() => {
bar();
});
}
`,
parserOptions: { ecmaVersion: 2015 }
},
{
code: unIndent`
foo(() => {
tagOne\`
multiline
template
literal
\${a} \${b}
\`(() => {
tagTwo\`
multiline
template
literal
\`(() => {
bar();
});
baz();
});
});
`,
parserOptions: { ecmaVersion: 2015 }
},
{
code: unIndent`
{
tagOne\`
\${a} \${b}
multiline
template
literal
\`(() => {
tagTwo\`
multiline
template
literal
\`(() => {
bar();
});
baz();
});
};
`,
parserOptions: { ecmaVersion: 2015 }
},
{
code: unIndent`
tagOne\`multiline
\${a} \${b}
template
literal
\`(() => {
foo();
tagTwo\`multiline
template
literal
\`({
bar: 1,
baz: 2
});
});
`,
parserOptions: { ecmaVersion: 2015 }
},
{
code: unIndent`
tagOne\`multiline
template
literal
\${a} \${b}\`({
foo: 1,
bar: tagTwo\`multiline
template
literal\`(() => {
baz();
})
});
`,
parserOptions: { ecmaVersion: 2015 }
},
{
code: unIndent`
foo.bar\` template literal \`(() => {
baz();
})
`,
parserOptions: { ecmaVersion: 2015 }
},
{
code: unIndent`
foo.bar.baz\` template literal \`(() => {
baz();
})
`,
parserOptions: { ecmaVersion: 2015 }
},
{
code: unIndent`
foo
.bar\` template
literal \`(() => {
baz();
})
`,
parserOptions: { ecmaVersion: 2015 }
},
{
code: unIndent`
foo
.bar
.baz\` template
literal \`(() => {
baz();
})
`,
parserOptions: { ecmaVersion: 2015 }
},
{
code: unIndent`
foo.bar\`
\${a} \${b}
\`(() => {
baz();
})
`,
parserOptions: { ecmaVersion: 2015 }
},
{
code: unIndent`
foo.bar1.bar2\`
\${a} \${b}
\`(() => {
baz();
})
`,
parserOptions: { ecmaVersion: 2015 }
},
{
code: unIndent`
foo
.bar1
.bar2\`
\${a} \${b}
\`(() => {
baz();
})
`,
parserOptions: { ecmaVersion: 2015 }
},
{
code: unIndent`
foo
.bar\`
\${a} \${b}
\`(() => {
baz();
})
`,
parserOptions: { ecmaVersion: 2015 }
},
{
code: unIndent`
foo
.test\`
\${a} \${b}
\`(() => {
baz();
})
`,
options: [4, { MemberExpression: 0 }],
parserOptions: { ecmaVersion: 2015 }
},
{
code: unIndent`
foo
.test\`
\${a} \${b}
\`(() => {
baz();
})
`,
options: [4, { MemberExpression: 2 }],
parserOptions: { ecmaVersion: 2015 }
},
{
code: unIndent`
const foo = async (arg1,
arg2) =>
{
return arg1 + arg2;
}
`,
options: [2, { FunctionDeclaration: { parameters: "first" }, FunctionExpression: { parameters: "first" } }]
},
{
code: unIndent`
const foo = async /* some comments */(arg1,
arg2) =>
{
return arg1 + arg2;
}
`,
options: [2, { FunctionDeclaration: { parameters: "first" }, FunctionExpression: { parameters: "first" } }]
},
{
code: unIndent`
const a = async
b => {}
`,
options: [2]
},
{
code: unIndent`
const foo = (arg1,
arg2) => async (arr1,
arr2) =>
{
return arg1 + arg2;
}
`,
options: [2, { FunctionDeclaration: { parameters: "first" }, FunctionExpression: { parameters: "first" } }]
},
{
code: unIndent`
const foo = async (arg1,
arg2) =>
{
return arg1 + arg2;
}
`,
options: [2]
},
{
code: unIndent`
const foo = async /*comments*/(arg1,
arg2) =>
{
return arg1 + arg2;
}
`,
options: [2]
},
{
code: unIndent`
const foo = async (arg1,
arg2) =>
{
return arg1 + arg2;
}
`,
options: [2, { FunctionDeclaration: { parameters: 4 }, FunctionExpression: { parameters: 4 } }]
},
{
code: unIndent`
const foo = (arg1,
arg2) =>
{
return arg1 + arg2;
}
`,
options: [2, { FunctionDeclaration: { parameters: 4 }, FunctionExpression: { parameters: 4 } }]
},
{
code: unIndent`
async function fn(ar1,
ar2){}
`,
options: [2, { FunctionDeclaration: { parameters: "first" }, FunctionExpression: { parameters: "first" } }]
},
{
code: unIndent`
async function /* some comments */ fn(ar1,
ar2){}
`,
options: [2, { FunctionDeclaration: { parameters: "first" }, FunctionExpression: { parameters: "first" } }]
},
{
code: unIndent`
async /* some comments */ function fn(ar1,
ar2){}
`,
options: [2, { FunctionDeclaration: { parameters: "first" }, FunctionExpression: { parameters: "first" } }]
},
{
code: unIndent`
class C {
static {
foo();
bar();
}
}
`,
options: [2],
parserOptions: { ecmaVersion: 2022 }
},
{
code: unIndent`
class C {
static {
foo();
bar();
}
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 }
},
{
code: unIndent`
class C {
static {
foo();
bar();
}
}
`,
options: [4, { StaticBlock: { body: 2 } }],
parserOptions: { ecmaVersion: 2022 }
},
{
code: unIndent`
class C {
static {
foo();
bar();
}
}
`,
options: [4, { StaticBlock: { body: 0 } }],
parserOptions: { ecmaVersion: 2022 }
},
{
code: unIndent`
class C {
\tstatic {
\t\tfoo();
\t\tbar();
\t}
}
`,
options: ["tab"],
parserOptions: { ecmaVersion: 2022 }
},
{
code: unIndent`
class C {
\tstatic {
\t\t\tfoo();
\t\t\tbar();
\t}
}
`,
options: ["tab", { StaticBlock: { body: 2 } }],
parserOptions: { ecmaVersion: 2022 }
},
{
code: unIndent`
class C {
static
{
foo();
bar();
}
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 }
},
{
code: unIndent`
class C {
static {
var x,
y;
}
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 }
},
{
code: unIndent`
class C {
static
{
var x,
y;
}
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 }
},
{
code: unIndent`
class C {
static {
if (foo) {
bar;
}
}
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 }
},
{
code: unIndent`
class C {
static {
{
bar;
}
}
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 }
},
{
code: unIndent`
class C {
static {}
static {
}
static
{
}
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 }
},
{
code: unIndent`
class C {
static {
foo;
}
static {
bar;
}
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 }
},
{
code: unIndent`
class C {
x = 1;
static {
foo;
}
y = 2;
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 }
},
{
code: unIndent`
class C {
method1(param) {
foo;
}
static {
bar;
}
method2(param) {
foo;
}
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 }
},
{
code: unIndent`
function f() {
class C {
static {
foo();
bar();
}
}
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 }
},
{
code: unIndent`
class C {
method() {
foo;
}
static {
bar;
}
}
`,
options: [4, { FunctionExpression: { body: 2 }, StaticBlock: { body: 2 } }],
parserOptions: { ecmaVersion: 2022 }
}
],
invalid: [
{
code: unIndent`
var a = b;
if (a) {
b();
}
`,
output: unIndent`
var a = b;
if (a) {
b();
}
`,
options: [2],
errors: expectedErrors([[3, 2, 0, "Identifier"]])
},
{
code: unIndent`
require('http').request({hostname: 'localhost',
port: 80}, function(res) {
res.end();
});
`,
output: unIndent`
require('http').request({hostname: 'localhost',
port: 80}, function(res) {
res.end();
});
`,
options: [2],
errors: expectedErrors([[2, 2, 18, "Identifier"], [3, 2, 4, "Identifier"], [4, 0, 2, "Punctuator"]])
},
{
code: unIndent`
if (array.some(function(){
return true;
})) {
a++; // ->
b++;
c++; // <-
}
`,
output: unIndent`
if (array.some(function(){
return true;
})) {
a++; // ->
b++;
c++; // <-
}
`,
options: [2],
errors: expectedErrors([[4, 2, 0, "Identifier"], [6, 2, 4, "Identifier"]])
},
{
code: unIndent`
if (a){
\tb=c;
\t\tc=d;
e=f;
}
`,
output: unIndent`
if (a){
\tb=c;
\tc=d;
\te=f;
}
`,
options: ["tab"],
errors: expectedErrors("tab", [[3, 1, 2, "Identifier"], [4, 1, 0, "Identifier"]])
},
{
code: unIndent`
if (a){
b=c;
c=d;
e=f;
}
`,
output: unIndent`
if (a){
b=c;
c=d;
e=f;
}
`,
options: [4],
errors: expectedErrors([[3, 4, 6, "Identifier"], [4, 4, 1, "Identifier"]])
},
{
code: fixture,
output: fixedFixture,
options: [2, { SwitchCase: 1, MemberExpression: 1, CallExpression: { arguments: "off" } }],
errors: expectedErrors([
[5, 2, 4, "Keyword"],
[6, 2, 0, "Line"],
[10, 4, 6, "Punctuator"],
[11, 2, 4, "Punctuator"],
[15, 4, 2, "Identifier"],
[16, 2, 4, "Punctuator"],
[23, 2, 4, "Punctuator"],
[29, 2, 4, "Keyword"],
[30, 4, 6, "Identifier"],
[36, 4, 6, "Identifier"],
[38, 2, 4, "Punctuator"],
[39, 4, 2, "Identifier"],
[40, 2, 0, "Punctuator"],
[54, 2, 4, "Punctuator"],
[114, 4, 2, "Keyword"],
[120, 4, 6, "Keyword"],
[124, 4, 2, "Keyword"],
[134, 4, 6, "Keyword"],
[138, 2, 3, "Punctuator"],
[139, 2, 3, "Punctuator"],
[143, 4, 0, "Identifier"],
[144, 6, 2, "Punctuator"],
[145, 6, 2, "Punctuator"],
[151, 4, 6, "Identifier"],
[152, 6, 8, "Punctuator"],
[153, 6, 8, "Punctuator"],
[159, 4, 2, "Identifier"],
[161, 4, 6, "Identifier"],
[175, 2, 0, "Identifier"],
[177, 2, 4, "Identifier"],
[189, 2, 0, "Keyword"],
[192, 6, 18, "Identifier"],
[193, 6, 4, "Identifier"],
[195, 6, 8, "Identifier"],
[228, 5, 4, "Identifier"],
[231, 3, 2, "Punctuator"],
[245, 0, 2, "Punctuator"],
[248, 0, 2, "Punctuator"],
[304, 4, 6, "Identifier"],
[306, 4, 8, "Identifier"],
[307, 2, 4, "Punctuator"],
[308, 2, 4, "Identifier"],
[311, 4, 6, "Identifier"],
[312, 4, 6, "Identifier"],
[313, 4, 6, "Identifier"],
[314, 2, 4, "Punctuator"],
[315, 2, 4, "Identifier"],
[318, 4, 6, "Identifier"],
[319, 4, 6, "Identifier"],
[320, 4, 6, "Identifier"],
[321, 2, 4, "Punctuator"],
[322, 2, 4, "Identifier"],
[326, 2, 1, "Numeric"],
[327, 2, 1, "Numeric"],
[328, 2, 1, "Numeric"],
[329, 2, 1, "Numeric"],
[330, 2, 1, "Numeric"],
[331, 2, 1, "Numeric"],
[332, 2, 1, "Numeric"],
[333, 2, 1, "Numeric"],
[334, 2, 1, "Numeric"],
[335, 2, 1, "Numeric"],
[340, 2, 4, "Identifier"],
[341, 2, 0, "Identifier"],
[344, 2, 4, "Identifier"],
[345, 2, 0, "Identifier"],
[348, 2, 4, "Identifier"],
[349, 2, 0, "Identifier"],
[355, 2, 0, "Identifier"],
[357, 2, 4, "Identifier"],
[361, 4, 6, "Identifier"],
[362, 2, 4, "Punctuator"],
[363, 2, 4, "Identifier"],
[368, 2, 0, "Keyword"],
[370, 2, 4, "Keyword"],
[374, 4, 6, "Keyword"],
[376, 4, 2, "Keyword"],
[383, 2, 0, "Identifier"],
[385, 2, 4, "Identifier"],
[390, 2, 0, "Identifier"],
[392, 2, 4, "Identifier"],
[409, 2, 0, "Identifier"],
[410, 2, 4, "Identifier"],
[416, 2, 0, "Identifier"],
[417, 2, 4, "Identifier"],
[418, 0, 4, "Punctuator"],
[422, 2, 4, "Identifier"],
[423, 2, 0, "Identifier"],
[427, 2, 6, "Identifier"],
[428, 2, 8, "Identifier"],
[429, 2, 4, "Identifier"],
[430, 0, 4, "Punctuator"],
[433, 2, 4, "Identifier"],
[434, 0, 4, "Punctuator"],
[437, 2, 0, "Identifier"],
[438, 0, 4, "Punctuator"],
[442, 2, 4, "Identifier"],
[443, 2, 4, "Identifier"],
[444, 0, 2, "Punctuator"],
[451, 2, 0, "Identifier"],
[453, 2, 4, "Identifier"],
[499, 6, 8, "Punctuator"],
[500, 8, 6, "Identifier"],
[504, 4, 6, "Punctuator"],
[505, 6, 8, "Identifier"],
[506, 4, 8, "Punctuator"]
])
},
{
code: unIndent`
switch(value){
case "1":
a();
break;
case "2":
a();
break;
default:
a();
break;
}
`,
output: unIndent`
switch(value){
case "1":
a();
break;
case "2":
a();
break;
default:
a();
break;
}
`,
options: [4, { SwitchCase: 1 }],
errors: expectedErrors([[4, 8, 4, "Keyword"], [7, 8, 4, "Keyword"]])
},
{
code: unIndent`
var x = 0 &&
{
a: 1,
b: 2
};
`,
output: unIndent`
var x = 0 &&
{
a: 1,
b: 2
};
`,
options: [4],
errors: expectedErrors([[3, 8, 7, "Identifier"], [4, 8, 10, "Identifier"]])
},
{
code: unIndent`
switch(value){
case "1":
a();
break;
case "2":
a();
break;
default:
break;
}
`,
output: unIndent`
switch(value){
case "1":
a();
break;
case "2":
a();
break;
default:
break;
}
`,
options: [4, { SwitchCase: 1 }],
errors: expectedErrors([9, 8, 4, "Keyword"])
},
{
code: unIndent`
switch(value){
case "1":
case "2":
a();
break;
default:
break;
}
switch(value){
case "1":
break;
case "2":
a();
break;
default:
a();
break;
}
`,
output: unIndent`
switch(value){
case "1":
case "2":
a();
break;
default:
break;
}
switch(value){
case "1":
break;
case "2":
a();
break;
default:
a();
break;
}
`,
options: [4, { SwitchCase: 1 }],
errors: expectedErrors([[11, 8, 4, "Keyword"], [14, 8, 4, "Keyword"], [17, 8, 4, "Keyword"]])
},
{
code: unIndent`
switch(value){
case "1":
a();
break;
case "2":
break;
default:
break;
}
`,
output: unIndent`
switch(value){
case "1":
a();
break;
case "2":
break;
default:
break;
}
`,
options: [4],
errors: expectedErrors([
[3, 4, 8, "Identifier"],
[4, 4, 8, "Keyword"],
[5, 0, 4, "Keyword"],
[6, 4, 8, "Keyword"],
[7, 0, 4, "Keyword"],
[8, 4, 8, "Keyword"]
])
},
{
code: unIndent`
var obj = {foo: 1, bar: 2};
with (obj) {
console.log(foo + bar);
}
`,
output: unIndent`
var obj = {foo: 1, bar: 2};
with (obj) {
console.log(foo + bar);
}
`,
errors: expectedErrors([3, 4, 0, "Identifier"])
},
{
code: unIndent`
switch (a) {
case '1':
b();
break;
default:
c();
break;
}
`,
output: unIndent`
switch (a) {
case '1':
b();
break;
default:
c();
break;
}
`,
options: [4, { SwitchCase: 1 }],
errors: expectedErrors([
[2, 4, 0, "Keyword"],
[3, 8, 0, "Identifier"],
[4, 8, 0, "Keyword"],
[5, 4, 0, "Keyword"],
[6, 8, 0, "Identifier"],
[7, 8, 0, "Keyword"]
])
},
{
code: unIndent`
var foo = function(){
foo
.bar
}
`,
output: unIndent`
var foo = function(){
foo
.bar
}
`,
options: [4, { MemberExpression: 1 }],
errors: expectedErrors(
[3, 8, 10, "Punctuator"]
)
},
{
code: unIndent`
(
foo
.bar
)
`,
output: unIndent`
(
foo
.bar
)
`,
errors: expectedErrors([3, 8, 4, "Punctuator"])
},
{
code: unIndent`
var foo = function(){
foo
.bar
}
`,
output: unIndent`
var foo = function(){
foo
.bar
}
`,
options: [4, { MemberExpression: 2 }],
errors: expectedErrors(
[3, 12, 13, "Punctuator"]
)
},
{
code: unIndent`
var foo = () => {
foo
.bar
}
`,
output: unIndent`
var foo = () => {
foo
.bar
}
`,
options: [4, { MemberExpression: 2 }],
errors: expectedErrors(
[3, 12, 13, "Punctuator"]
)
},
{
code: unIndent`
TestClass.prototype.method = function () {
return Promise.resolve(3)
.then(function (x) {
return x;
});
};
`,
output: unIndent`
TestClass.prototype.method = function () {
return Promise.resolve(3)
.then(function (x) {
return x;
});
};
`,
options: [2, { MemberExpression: 1 }],
errors: expectedErrors([3, 4, 6, "Punctuator"])
},
{
code: unIndent`
while (a)
b();
`,
output: unIndent`
while (a)
b();
`,
options: [4],
errors: expectedErrors([
[2, 4, 0, "Identifier"]
])
},
{
code: unIndent`
lmn = [{
a: 1
},
{
b: 2
},
{
x: 2
}];
`,
output: unIndent`
lmn = [{
a: 1
},
{
b: 2
},
{
x: 2
}];
`,
errors: expectedErrors([
[2, 4, 8, "Identifier"],
[3, 0, 4, "Punctuator"],
[4, 0, 4, "Punctuator"],
[5, 4, 8, "Identifier"],
[6, 0, 4, "Punctuator"],
[7, 0, 4, "Punctuator"],
[8, 4, 8, "Identifier"]
])
},
{
code: unIndent`
for (var foo = 1;
foo < 10;
foo++) {}
`,
output: unIndent`
for (var foo = 1;
foo < 10;
foo++) {}
`,
errors: expectedErrors([[2, 4, 0, "Identifier"], [3, 4, 0, "Identifier"]])
},
{
code: unIndent`
for (
var foo = 1;
foo < 10;
foo++
) {}
`,
output: unIndent`
for (
var foo = 1;
foo < 10;
foo++
) {}
`,
errors: expectedErrors([[2, 4, 0, "Keyword"], [3, 4, 0, "Identifier"], [4, 4, 0, "Identifier"], [5, 0, 4, "Punctuator"]])
},
{
code: unIndent`
for (;;)
b();
`,
output: unIndent`
for (;;)
b();
`,
options: [4],
errors: expectedErrors([
[2, 4, 0, "Identifier"]
])
},
{
code: unIndent`
for (a in x)
b();
`,
output: unIndent`
for (a in x)
b();
`,
options: [4],
errors: expectedErrors([
[2, 4, 0, "Identifier"]
])
},
{
code: unIndent`
do
b();
while(true)
`,
output: unIndent`
do
b();
while(true)
`,
options: [4],
errors: expectedErrors([
[2, 4, 0, "Identifier"]
])
},
{
code: unIndent`
if(true)
b();
`,
output: unIndent`
if(true)
b();
`,
options: [4],
errors: expectedErrors([
[2, 4, 0, "Identifier"]
])
},
{
code: unIndent`
var test = {
a: 1,
b: 2
};
`,
output: unIndent`
var test = {
a: 1,
b: 2
};
`,
options: [2],
errors: expectedErrors([
[2, 2, 6, "Identifier"],
[3, 2, 4, "Identifier"],
[4, 0, 4, "Punctuator"]
])
},
{
code: unIndent`
var a = function() {
a++;
b++;
c++;
},
b;
`,
output: unIndent`
var a = function() {
a++;
b++;
c++;
},
b;
`,
options: [4],
errors: expectedErrors([
[2, 8, 6, "Identifier"],
[3, 8, 4, "Identifier"],
[4, 8, 10, "Identifier"]
])
},
{
code: unIndent`
var a = 1,
b = 2,
c = 3;
`,
output: unIndent`
var a = 1,
b = 2,
c = 3;
`,
options: [4],
errors: expectedErrors([
[2, 4, 0, "Identifier"],
[3, 4, 0, "Identifier"]
])
},
{
code: unIndent`
[a, b,
c].forEach((index) => {
index;
});
`,
output: unIndent`
[a, b,
c].forEach((index) => {
index;
});
`,
options: [4],
errors: expectedErrors([
[3, 4, 8, "Identifier"],
[4, 0, 4, "Punctuator"]
])
},
{
code: unIndent`
[a, b,
c].forEach(function(index){
return index;
});
`,
output: unIndent`
[a, b,
c].forEach(function(index){
return index;
});
`,
options: [4],
errors: expectedErrors([
[2, 4, 0, "Identifier"],
[3, 4, 2, "Keyword"]
])
},
{
code: unIndent`
[a, b, c].forEach(function(index){
return index;
});
`,
output: unIndent`
[a, b, c].forEach(function(index){
return index;
});
`,
options: [4],
errors: expectedErrors([
[2, 4, 2, "Keyword"]
])
},
{
code: unIndent`
(foo)
.bar([
baz
]);
`,
output: unIndent`
(foo)
.bar([
baz
]);
`,
options: [4, { MemberExpression: 1 }],
errors: expectedErrors([[3, 8, 4, "Identifier"], [4, 4, 0, "Punctuator"]])
},
{
code: unIndent`
var x = ['a',
'b',
'c'
];
`,
output: unIndent`
var x = ['a',
'b',
'c'
];
`,
options: [4],
errors: expectedErrors([
[2, 4, 9, "String"],
[3, 4, 9, "String"]
])
},
{
code: unIndent`
var x = [
'a',
'b',
'c'
];
`,
output: unIndent`
var x = [
'a',
'b',
'c'
];
`,
options: [4],
errors: expectedErrors([
[2, 4, 9, "String"],
[3, 4, 9, "String"],
[4, 4, 9, "String"]
])
},
{
code: unIndent`
var x = [
'a',
'b',
'c',
'd'];
`,
output: unIndent`
var x = [
'a',
'b',
'c',
'd'];
`,
options: [4],
errors: expectedErrors([
[2, 4, 9, "String"],
[3, 4, 9, "String"],
[4, 4, 9, "String"],
[5, 4, 0, "String"]
])
},
{
code: unIndent`
var x = [
'a',
'b',
'c'
];
`,
output: unIndent`
var x = [
'a',
'b',
'c'
];
`,
options: [4],
errors: expectedErrors([
[2, 4, 9, "String"],
[3, 4, 9, "String"],
[4, 4, 9, "String"],
[5, 0, 2, "Punctuator"]
])
},
{
code: unIndent`
[[
], function(
foo
) {}
]
`,
output: unIndent`
[[
], function(
foo
) {}
]
`,
errors: expectedErrors([[3, 4, 8, "Identifier"], [4, 0, 4, "Punctuator"]])
},
{
code: unIndent`
define([
'foo'
], function(
bar
) {
baz;
}
)
`,
output: unIndent`
define([
'foo'
], function(
bar
) {
baz;
}
)
`,
errors: expectedErrors([[4, 4, 8, "Identifier"], [5, 0, 4, "Punctuator"]])
},
{
code: unIndent`
while (1 < 2)
console.log('foo')
console.log('bar')
`,
output: unIndent`
while (1 < 2)
console.log('foo')
console.log('bar')
`,
options: [2],
errors: expectedErrors([
[2, 2, 0, "Identifier"],
[3, 0, 2, "Identifier"]
])
},
{
code: unIndent`
function salutation () {
switch (1) {
case 0: return console.log('hi')
case 1: return console.log('hey')
}
}
`,
output: unIndent`
function salutation () {
switch (1) {
case 0: return console.log('hi')
case 1: return console.log('hey')
}
}
`,
options: [2, { SwitchCase: 1 }],
errors: expectedErrors([
[3, 4, 2, "Keyword"]
])
},
{
code: unIndent`
var geometry, box, face1, face2, colorT, colorB, sprite, padding, maxWidth,
height, rotate;
`,
output: unIndent`
var geometry, box, face1, face2, colorT, colorB, sprite, padding, maxWidth,
height, rotate;
`,
options: [2, { SwitchCase: 1 }],
errors: expectedErrors([
[2, 2, 0, "Identifier"]
])
},
{
code: unIndent`
switch (a) {
case '1':
b();
break;
default:
c();
break;
}
`,
output: unIndent`
switch (a) {
case '1':
b();
break;
default:
c();
break;
}
`,
options: [4, { SwitchCase: 2 }],
errors: expectedErrors([
[2, 8, 0, "Keyword"],
[3, 12, 0, "Identifier"],
[4, 12, 0, "Keyword"],
[5, 8, 0, "Keyword"],
[6, 12, 0, "Identifier"],
[7, 12, 0, "Keyword"]
])
},
{
code: unIndent`
var geometry,
rotate;
`,
output: unIndent`
var geometry,
rotate;
`,
options: [2, { VariableDeclarator: 1 }],
errors: expectedErrors([
[2, 2, 0, "Identifier"]
])
},
{
code: unIndent`
var geometry,
rotate;
`,
output: unIndent`
var geometry,
rotate;
`,
options: [2, { VariableDeclarator: 2 }],
errors: expectedErrors([
[2, 4, 2, "Identifier"]
])
},
{
code: unIndent`
var geometry,
\trotate;
`,
output: unIndent`
var geometry,
\t\trotate;
`,
options: ["tab", { VariableDeclarator: 2 }],
errors: expectedErrors("tab", [
[2, 2, 1, "Identifier"]
])
},
{
code: unIndent`
let geometry,
rotate;
`,
output: unIndent`
let geometry,
rotate;
`,
options: [2, { VariableDeclarator: 2 }],
errors: expectedErrors([
[2, 4, 2, "Identifier"]
])
},
{
code: unIndent`
let foo = 'foo',
bar = bar;
const a = 'a',
b = 'b';
`,
output: unIndent`
let foo = 'foo',
bar = bar;
const a = 'a',
b = 'b';
`,
options: [2, { VariableDeclarator: "first" }],
errors: expectedErrors([
[2, 4, 2, "Identifier"],
[4, 6, 2, "Identifier"]
])
},
{
code: unIndent`
var foo = 'foo',
bar = bar;
`,
output: unIndent`
var foo = 'foo',
bar = bar;
`,
options: [2, { VariableDeclarator: { var: "first" } }],
errors: expectedErrors([
[2, 4, 2, "Identifier"]
])
},
{
code: unIndent`
if(true)
if (true)
if (true)
console.log(val);
`,
output: unIndent`
if(true)
if (true)
if (true)
console.log(val);
`,
options: [2, { VariableDeclarator: 2, SwitchCase: 1 }],
errors: expectedErrors([
[4, 6, 4, "Identifier"]
])
},
{
code: unIndent`
var a = {
a: 1,
b: 2
}
`,
output: unIndent`
var a = {
a: 1,
b: 2
}
`,
options: [2, { VariableDeclarator: 2, SwitchCase: 1 }],
errors: expectedErrors([
[2, 2, 4, "Identifier"],
[3, 2, 4, "Identifier"]
])
},
{
code: unIndent`
var a = [
a,
b
]
`,
output: unIndent`
var a = [
a,
b
]
`,
options: [2, { VariableDeclarator: 2, SwitchCase: 1 }],
errors: expectedErrors([
[2, 2, 4, "Identifier"],
[3, 2, 4, "Identifier"]
])
},
{
code: unIndent`
let a = [
a,
b
]
`,
output: unIndent`
let a = [
a,
b
]
`,
options: [2, { VariableDeclarator: { let: 2 }, SwitchCase: 1 }],
errors: expectedErrors([
[2, 2, 4, "Identifier"],
[3, 2, 4, "Identifier"]
])
},
{
code: unIndent`
var a = new Test({
a: 1
}),
b = 4;
`,
output: unIndent`
var a = new Test({
a: 1
}),
b = 4;
`,
options: [4],
errors: expectedErrors([
[2, 8, 6, "Identifier"],
[3, 4, 2, "Punctuator"]
])
},
{
code: unIndent`
var a = new Test({
a: 1
}),
b = 4;
const c = new Test({
a: 1
}),
d = 4;
`,
output: unIndent`
var a = new Test({
a: 1
}),
b = 4;
const c = new Test({
a: 1
}),
d = 4;
`,
options: [2, { VariableDeclarator: { var: 2 } }],
errors: expectedErrors([
[6, 4, 6, "Identifier"],
[7, 2, 4, "Punctuator"],
[8, 2, 4, "Identifier"]
])
},
{
code: unIndent`
var abc = 5,
c = 2,
xyz =
{
a: 1,
b: 2
};
`,
output: unIndent`
var abc = 5,
c = 2,
xyz =
{
a: 1,
b: 2
};
`,
options: [2, { VariableDeclarator: 2, SwitchCase: 1 }],
errors: expectedErrors([6, 6, 7, "Identifier"])
},
{
code: unIndent`
var abc =
{
a: 1,
b: 2
};
`,
output: unIndent`
var abc =
{
a: 1,
b: 2
};
`,
options: [2, { VariableDeclarator: 2, SwitchCase: 1 }],
errors: expectedErrors([4, 7, 8, "Identifier"])
},
{
code: unIndent`
var foo = {
bar: 1,
baz: {
qux: 2
}
},
bar = 1;
`,
output: unIndent`
var foo = {
bar: 1,
baz: {
qux: 2
}
},
bar = 1;
`,
options: [2],
errors: expectedErrors([[4, 6, 8, "Identifier"], [5, 4, 6, "Punctuator"]])
},
{
code: unIndent`
var path = require('path')
, crypto = require('crypto')
;
`,
output: unIndent`
var path = require('path')
, crypto = require('crypto')
;
`,
options: [2],
errors: expectedErrors([
[2, 2, 1, "Punctuator"]
])
},
{
code: unIndent`
var a = 1
,b = 2
;
`,
output: unIndent`
var a = 1
,b = 2
;
`,
errors: expectedErrors([
[2, 4, 3, "Punctuator"]
])
},
{
code: unIndent`
class A{
constructor(){}
a(){}
get b(){}
}
`,
output: unIndent`
class A{
constructor(){}
a(){}
get b(){}
}
`,
options: [4, { VariableDeclarator: 1, SwitchCase: 1 }],
errors: expectedErrors([[2, 4, 2, "Identifier"]])
},
{
code: unIndent`
var A = class {
constructor(){}
a(){}
get b(){}
};
`,
output: unIndent`
var A = class {
constructor(){}
a(){}
get b(){}
};
`,
options: [4, { VariableDeclarator: 1, SwitchCase: 1 }],
errors: expectedErrors([[2, 4, 2, "Identifier"], [4, 4, 2, "Identifier"]])
},
{
code: unIndent`
var a = 1,
B = class {
constructor(){}
a(){}
get b(){}
};
`,
output: unIndent`
var a = 1,
B = class {
constructor(){}
a(){}
get b(){}
};
`,
options: [2, { VariableDeclarator: 2, SwitchCase: 1 }],
errors: expectedErrors([[3, 6, 4, "Identifier"]])
},
{
code: unIndent`
{
if(a){
foo();
}
else{
bar();
}
}
`,
output: unIndent`
{
if(a){
foo();
}
else{
bar();
}
}
`,
options: [4],
errors: expectedErrors([[5, 4, 2, "Keyword"]])
},
{
code: unIndent`
{
if(a){
foo();
}
else
bar();
}
`,
output: unIndent`
{
if(a){
foo();
}
else
bar();
}
`,
options: [4],
errors: expectedErrors([[5, 4, 2, "Keyword"]])
},
{
code: unIndent`
{
if(a)
foo();
else
bar();
}
`,
output: unIndent`
{
if(a)
foo();
else
bar();
}
`,
options: [4],
errors: expectedErrors([[4, 4, 2, "Keyword"]])
},
{
code: unIndent`
(function(){
function foo(x) {
return x + 1;
}
})();
`,
output: unIndent`
(function(){
function foo(x) {
return x + 1;
}
})();
`,
options: [2, { outerIIFEBody: 0 }],
errors: expectedErrors([[2, 0, 2, "Keyword"], [3, 2, 4, "Keyword"], [4, 0, 2, "Punctuator"]])
},
{
code: unIndent`
(function(){
function foo(x) {
return x + 1;
}
})();
`,
output: unIndent`
(function(){
function foo(x) {
return x + 1;
}
})();
`,
options: [4, { outerIIFEBody: 2 }],
errors: expectedErrors([[2, 8, 4, "Keyword"], [3, 12, 8, "Keyword"], [4, 8, 4, "Punctuator"]])
},
{
code: unIndent`
if(data) {
console.log('hi');
}
`,
output: unIndent`
if(data) {
console.log('hi');
}
`,
options: [2, { outerIIFEBody: 0 }],
errors: expectedErrors([[2, 2, 0, "Identifier"]])
},
{
code: unIndent`
var ns = function(){
function fooVar(x) {
return x + 1;
}
}(x);
`,
output: unIndent`
var ns = function(){
function fooVar(x) {
return x + 1;
}
}(x);
`,
options: [4, { outerIIFEBody: 2 }],
errors: expectedErrors([[2, 8, 4, "Keyword"], [3, 12, 8, "Keyword"], [4, 8, 4, "Punctuator"]])
},
{
code: unIndent`
var obj = {
foo: function() {
return true;
}()
};
`,
output: unIndent`
var obj = {
foo: function() {
return true;
}()
};
`,
options: [2, { outerIIFEBody: 0 }],
errors: expectedErrors([[3, 4, 2, "Keyword"]])
},
{
code: unIndent`
typeof function() {
function fooVar(x) {
return x + 1;
}
}();
`,
output: unIndent`
typeof function() {
function fooVar(x) {
return x + 1;
}
}();
`,
options: [2, { outerIIFEBody: 2 }],
errors: expectedErrors([[2, 2, 4, "Keyword"], [3, 4, 6, "Keyword"], [4, 2, 4, "Punctuator"]])
},
{
code: unIndent`
{
\t!function(x) {
\t\t\t\treturn x + 1;
\t}()
};
`,
output: unIndent`
{
\t!function(x) {
\t\treturn x + 1;
\t}()
};
`,
options: ["tab", { outerIIFEBody: 3 }],
errors: expectedErrors("tab", [[3, 2, 4, "Keyword"]])
},
{
code: unIndent`
(function(){
function foo(x) {
return x + 1;
}
})();
`,
output: unIndent`
(function(){
function foo(x) {
return x + 1;
}
})();
`,
options: [4, { outerIIFEBody: "off" }],
errors: expectedErrors([[3, 8, 4, "Keyword"]])
},
{
code: unIndent`
(function(){
function foo(x) {
return x + 1;
}
})();
`,
output: unIndent`
(function(){
function foo(x) {
return x + 1;
}
})();
`,
options: [4, { outerIIFEBody: "off" }],
errors: expectedErrors([[3, 4, 0, "Keyword"]])
},
{
code: unIndent`
(() => {
function foo(x) {
return x + 1;
}
})();
`,
output: unIndent`
(() => {
function foo(x) {
return x + 1;
}
})();
`,
options: [4, { outerIIFEBody: "off" }],
errors: expectedErrors([[3, 8, 4, "Keyword"]])
},
{
code: unIndent`
(() => {
function foo(x) {
return x + 1;
}
})();
`,
output: unIndent`
(() => {
function foo(x) {
return x + 1;
}
})();
`,
options: [4, { outerIIFEBody: "off" }],
errors: expectedErrors([[3, 4, 0, "Keyword"]])
},
{
code: unIndent`
Buffer
.toString()
`,
output: unIndent`
Buffer
.toString()
`,
options: [4, { MemberExpression: 1 }],
errors: expectedErrors([[2, 4, 0, "Punctuator"]])
},
{
code: unIndent`
Buffer
.indexOf('a')
.toString()
`,
output: unIndent`
Buffer
.indexOf('a')
.toString()
`,
options: [4, { MemberExpression: 1 }],
errors: expectedErrors([[3, 4, 0, "Punctuator"]])
},
{
code: unIndent`
Buffer.
length
`,
output: unIndent`
Buffer.
length
`,
options: [4, { MemberExpression: 1 }],
errors: expectedErrors([[2, 4, 0, "Identifier"]])
},
{
code: unIndent`
Buffer.
\t\tlength
`,
output: unIndent`
Buffer.
\tlength
`,
options: ["tab", { MemberExpression: 1 }],
errors: expectedErrors("tab", [[2, 1, 2, "Identifier"]])
},
{
code: unIndent`
Buffer
.foo
.bar
`,
output: unIndent`
Buffer
.foo
.bar
`,
options: [2, { MemberExpression: 2 }],
errors: expectedErrors([[2, 4, 2, "Punctuator"], [3, 4, 2, "Punctuator"]])
},
{
code: unIndent`
function foo() {
new
.target
}
`,
output: unIndent`
function foo() {
new
.target
}
`,
errors: expectedErrors([3, 8, 4, "Punctuator"])
},
{
code: unIndent`
function foo() {
new.
target
}
`,
output: unIndent`
function foo() {
new.
target
}
`,
errors: expectedErrors([3, 8, 4, "Identifier"])
},
{
// Indentation with multiple else statements: https://github.com/eslint/eslint/issues/6956
code: unIndent`
if (foo) bar();
else if (baz) foobar();
else if (qux) qux();
`,
output: unIndent`
if (foo) bar();
else if (baz) foobar();
else if (qux) qux();
`,
options: [2],
errors: expectedErrors([3, 0, 2, "Keyword"])
},
{
code: unIndent`
if (foo) bar();
else if (baz) foobar();
else qux();
`,
output: unIndent`
if (foo) bar();
else if (baz) foobar();
else qux();
`,
options: [2],
errors: expectedErrors([3, 0, 2, "Keyword"])
},
{
code: unIndent`
foo();
if (baz) foobar();
else qux();
`,
output: unIndent`
foo();
if (baz) foobar();
else qux();
`,
options: [2],
errors: expectedErrors([[2, 0, 2, "Keyword"], [3, 0, 2, "Keyword"]])
},
{
code: unIndent`
if (foo) bar();
else if (baz) foobar();
else if (bip) {
qux();
}
`,
output: unIndent`
if (foo) bar();
else if (baz) foobar();
else if (bip) {
qux();
}
`,
options: [2],
errors: expectedErrors([[3, 0, 5, "Keyword"], [4, 2, 7, "Identifier"], [5, 0, 5, "Punctuator"]])
},
{
code: unIndent`
if (foo) bar();
else if (baz) {
foobar();
} else if (boop) {
qux();
}
`,
output: unIndent`
if (foo) bar();
else if (baz) {
foobar();
} else if (boop) {
qux();
}
`,
options: [2],
errors: expectedErrors([[3, 2, 4, "Identifier"], [4, 0, 5, "Punctuator"], [5, 2, 7, "Identifier"], [6, 0, 5, "Punctuator"]])
},
{
code: unIndent`
function foo(aaa,
bbb, ccc, ddd) {
bar();
}
`,
output: unIndent`
function foo(aaa,
bbb, ccc, ddd) {
bar();
}
`,
options: [2, { FunctionDeclaration: { parameters: 1, body: 2 } }],
errors: expectedErrors([[2, 2, 4, "Identifier"], [3, 4, 6, "Identifier"]])
},
{
code: unIndent`
function foo(aaa, bbb,
ccc, ddd) {
bar();
}
`,
output: unIndent`
function foo(aaa, bbb,
ccc, ddd) {
bar();
}
`,
options: [2, { FunctionDeclaration: { parameters: 3, body: 1 } }],
errors: expectedErrors([[2, 6, 2, "Identifier"], [3, 2, 0, "Identifier"]])
},
{
code: unIndent`
function foo(aaa,
bbb,
ccc) {
bar();
}
`,
output: unIndent`
function foo(aaa,
bbb,
ccc) {
bar();
}
`,
options: [4, { FunctionDeclaration: { parameters: 1, body: 3 } }],
errors: expectedErrors([[2, 4, 8, "Identifier"], [3, 4, 2, "Identifier"], [4, 12, 6, "Identifier"]])
},
{
code: unIndent`
function foo(aaa,
bbb, ccc,
ddd, eee, fff) {
bar();
}
`,
output: unIndent`
function foo(aaa,
bbb, ccc,
ddd, eee, fff) {
bar();
}
`,
options: [2, { FunctionDeclaration: { parameters: "first", body: 1 } }],
errors: expectedErrors([[2, 13, 2, "Identifier"], [3, 13, 19, "Identifier"], [4, 2, 3, "Identifier"]])
},
{
code: unIndent`
function foo(aaa, bbb)
{
bar();
}
`,
output: unIndent`
function foo(aaa, bbb)
{
bar();
}
`,
options: [2, { FunctionDeclaration: { body: 3 } }],
errors: expectedErrors([3, 6, 0, "Identifier"])
},
{
code: unIndent`
function foo(
aaa,
bbb) {
bar();
}
`,
output: unIndent`
function foo(
aaa,
bbb) {
bar();
}
`,
options: [2, { FunctionDeclaration: { parameters: "first", body: 2 } }],
errors: expectedErrors([[2, 2, 0, "Identifier"], [3, 2, 4, "Identifier"], [4, 4, 0, "Identifier"]])
},
{
code: unIndent`
var foo = function(aaa,
bbb,
ccc,
ddd) {
bar();
}
`,
output: unIndent`
var foo = function(aaa,
bbb,
ccc,
ddd) {
bar();
}
`,
options: [2, { FunctionExpression: { parameters: 2, body: 0 } }],
errors: expectedErrors([[2, 4, 2, "Identifier"], [4, 4, 6, "Identifier"], [5, 0, 2, "Identifier"]])
},
{
code: unIndent`
var foo = function(aaa,
bbb,
ccc) {
bar();
}
`,
output: unIndent`
var foo = function(aaa,
bbb,
ccc) {
bar();
}
`,
options: [2, { FunctionExpression: { parameters: 1, body: 10 } }],
errors: expectedErrors([[2, 2, 3, "Identifier"], [3, 2, 1, "Identifier"], [4, 20, 2, "Identifier"]])
},
{
code: unIndent`
var foo = function(aaa,
bbb, ccc, ddd,
eee, fff) {
bar();
}
`,
output: unIndent`
var foo = function(aaa,
bbb, ccc, ddd,
eee, fff) {
bar();
}
`,
options: [4, { FunctionExpression: { parameters: "first", body: 1 } }],
errors: expectedErrors([[2, 19, 2, "Identifier"], [3, 19, 24, "Identifier"], [4, 4, 8, "Identifier"]])
},
{
code: unIndent`
var foo = function(
aaa, bbb, ccc,
ddd, eee) {
bar();
}
`,
output: unIndent`
var foo = function(
aaa, bbb, ccc,
ddd, eee) {
bar();
}
`,
options: [2, { FunctionExpression: { parameters: "first", body: 3 } }],
errors: expectedErrors([[2, 2, 0, "Identifier"], [3, 2, 4, "Identifier"], [4, 6, 2, "Identifier"]])
},
{
code: unIndent`
var foo = bar;
\t\t\tvar baz = qux;
`,
output: unIndent`
var foo = bar;
var baz = qux;
`,
options: [2],
errors: expectedErrors([2, "0 spaces", "3 tabs", "Keyword"])
},
{
code: unIndent`
function foo() {
\tbar();
baz();
qux();
}
`,
output: unIndent`
function foo() {
\tbar();
\tbaz();
\tqux();
}
`,
options: ["tab"],
errors: expectedErrors("tab", [[3, "1 tab", "2 spaces", "Identifier"], [4, "1 tab", "14 spaces", "Identifier"]])
},
{
code: unIndent`
function foo() {
bar();
\t\t}
`,
output: unIndent`
function foo() {
bar();
}
`,
options: [2],
errors: expectedErrors([[3, "0 spaces", "2 tabs", "Punctuator"]])
},
{
code: unIndent`
function foo() {
function bar() {
baz();
}
}
`,
output: unIndent`
function foo() {
function bar() {
baz();
}
}
`,
options: [2, { FunctionDeclaration: { body: 1 } }],
errors: expectedErrors([3, 4, 8, "Identifier"])
},
{
code: unIndent`
function foo() {
function bar(baz,
qux) {
foobar();
}
}
`,
output: unIndent`
function foo() {
function bar(baz,
qux) {
foobar();
}
}
`,
options: [2, { FunctionDeclaration: { body: 1, parameters: 2 } }],
errors: expectedErrors([3, 6, 4, "Identifier"])
},
{
code: unIndent`
function foo() {
var bar = function(baz,
qux) {
foobar();
};
}
`,
output: unIndent`
function foo() {
var bar = function(baz,
qux) {
foobar();
};
}
`,
options: [2, { FunctionExpression: { parameters: 3 } }],
errors: expectedErrors([3, 8, 10, "Identifier"])
},
{
code: unIndent`
foo.bar(
baz, qux, function() {
qux;
}
);
`,
output: unIndent`
foo.bar(
baz, qux, function() {
qux;
}
);
`,
options: [2, { FunctionExpression: { body: 3 }, CallExpression: { arguments: 3 } }],
errors: expectedErrors([3, 12, 8, "Identifier"])
},
{
code: unIndent`
{
try {
}
catch (err) {
}
finally {
}
}
`,
output: unIndent`
{
try {
}
catch (err) {
}
finally {
}
}
`,
errors: expectedErrors([
[4, 4, 0, "Keyword"],
[6, 4, 0, "Keyword"]
])
},
{
code: unIndent`
{
do {
}
while (true)
}
`,
output: unIndent`
{
do {
}
while (true)
}
`,
errors: expectedErrors([4, 4, 0, "Keyword"])
},
{
code: unIndent`
function foo() {
return (
1
)
}
`,
output: unIndent`
function foo() {
return (
1
)
}
`,
options: [2],
errors: expectedErrors([[4, 2, 4, "Punctuator"]])
},
{
code: unIndent`
function foo() {
return (
1
);
}
`,
output: unIndent`
function foo() {
return (
1
);
}
`,
options: [2],
errors: expectedErrors([[4, 2, 4, "Punctuator"]])
},
{
code: unIndent`
function test(){
switch(length){
case 1: return function(a){
return fn.call(that, a);
};
}
}
`,
output: unIndent`
function test(){
switch(length){
case 1: return function(a){
return fn.call(that, a);
};
}
}
`,
options: [2, { VariableDeclarator: 2, SwitchCase: 1 }],
errors: expectedErrors([[4, 6, 4, "Keyword"]])
},
{
code: unIndent`
function foo() {
return 1
}
`,
output: unIndent`
function foo() {
return 1
}
`,
options: [2],
errors: expectedErrors([[2, 2, 3, "Keyword"]])
},
{
code: unIndent`
foo(
bar,
baz,
qux);
`,
output: unIndent`
foo(
bar,
baz,
qux);
`,
options: [2, { CallExpression: { arguments: 1 } }],
errors: expectedErrors([[2, 2, 0, "Identifier"], [4, 2, 4, "Identifier"]])
},
{
code: unIndent`
foo(
\tbar,
\tbaz);
`,
output: unIndent`
foo(
bar,
baz);
`,
options: [2, { CallExpression: { arguments: 2 } }],
errors: expectedErrors([[2, "4 spaces", "1 tab", "Identifier"], [3, "4 spaces", "1 tab", "Identifier"]])
},
{
code: unIndent`
foo(bar,
\t\tbaz,
\t\tqux);
`,
output: unIndent`
foo(bar,
\tbaz,
\tqux);
`,
options: ["tab", { CallExpression: { arguments: 1 } }],
errors: expectedErrors("tab", [[2, 1, 2, "Identifier"], [3, 1, 2, "Identifier"]])
},
{
code: unIndent`
foo(bar, baz,
qux);
`,
output: unIndent`
foo(bar, baz,
qux);
`,
options: [2, { CallExpression: { arguments: "first" } }],
errors: expectedErrors([2, 4, 9, "Identifier"])
},
{
code: unIndent`
foo(
bar,
baz);
`,
output: unIndent`
foo(
bar,
baz);
`,
options: [2, { CallExpression: { arguments: "first" } }],
errors: expectedErrors([[2, 2, 10, "Identifier"], [3, 2, 4, "Identifier"]])
},
{
code: unIndent`
foo(bar,
1 + 2,
!baz,
new Car('!')
);
`,
output: unIndent`
foo(bar,
1 + 2,
!baz,
new Car('!')
);
`,
options: [2, { CallExpression: { arguments: 3 } }],
errors: expectedErrors([[2, 6, 2, "Numeric"], [3, 6, 14, "Punctuator"], [4, 6, 8, "Keyword"]])
},
// https://github.com/eslint/eslint/issues/7573
{
code: unIndent`
return (
foo
);
`,
output: unIndent`
return (
foo
);
`,
parserOptions: { ecmaFeatures: { globalReturn: true } },
errors: expectedErrors([3, 0, 4, "Punctuator"])
},
{
code: unIndent`
return (
foo
)
`,
output: unIndent`
return (
foo
)
`,
parserOptions: { ecmaFeatures: { globalReturn: true } },
errors: expectedErrors([3, 0, 4, "Punctuator"])
},
// https://github.com/eslint/eslint/issues/7604
{
code: unIndent`
if (foo) {
/* comment */bar();
}
`,
output: unIndent`
if (foo) {
/* comment */bar();
}
`,
errors: expectedErrors([2, 4, 8, "Block"])
},
{
code: unIndent`
foo('bar',
/** comment */{
ok: true
});
`,
output: unIndent`
foo('bar',
/** comment */{
ok: true
});
`,
errors: expectedErrors([2, 4, 8, "Block"])
},
{
code: unIndent`
foo(
(bar)
);
`,
output: unIndent`
foo(
(bar)
);
`,
options: [4, { CallExpression: { arguments: 1 } }],
errors: expectedErrors([2, 4, 0, "Punctuator"])
},
{
code: unIndent`
((
foo
))
`,
output: unIndent`
((
foo
))
`,
options: [4],
errors: expectedErrors([2, 4, 0, "Identifier"])
},
// ternary expressions (https://github.com/eslint/eslint/issues/7420)
{
code: unIndent`
foo
? bar
: baz
`,
output: unIndent`
foo
? bar
: baz
`,
options: [2],
errors: expectedErrors([[2, 2, 0, "Punctuator"], [3, 2, 4, "Punctuator"]])
},
{
code: unIndent`
[
foo ?
bar :
baz,
qux
]
`,
output: unIndent`
[
foo ?
bar :
baz,
qux
]
`,
errors: expectedErrors([5, 4, 8, "Identifier"])
},
{
code: unIndent`
condition
? () => {
return true
}
: condition2
? () => {
return true
}
: () => {
return false
}
`,
output: unIndent`
condition
? () => {
return true
}
: condition2
? () => {
return true
}
: () => {
return false
}
`,
options: [2, { offsetTernaryExpressions: true }],
errors: expectedErrors([
[2, 2, 0, "Punctuator"],
[3, 6, 0, "Keyword"],
[4, 4, 0, "Punctuator"],
[5, 2, 0, "Punctuator"],
[6, 4, 0, "Punctuator"],
[7, 8, 0, "Keyword"],
[8, 6, 0, "Punctuator"],
[9, 4, 0, "Punctuator"],
[10, 8, 0, "Keyword"],
[11, 6, 0, "Punctuator"]
])
},
{
code: unIndent`
condition
? () => {
return true
}
: condition2
? () => {
return true
}
: () => {
return false
}
`,
output: unIndent`
condition
? () => {
return true
}
: condition2
? () => {
return true
}
: () => {
return false
}
`,
options: [2, { offsetTernaryExpressions: false }],
errors: expectedErrors([
[2, 2, 0, "Punctuator"],
[3, 4, 0, "Keyword"],
[4, 2, 0, "Punctuator"],
[5, 2, 0, "Punctuator"],
[6, 4, 0, "Punctuator"],
[7, 6, 0, "Keyword"],
[8, 4, 0, "Punctuator"],
[9, 4, 0, "Punctuator"],
[10, 6, 0, "Keyword"],
[11, 4, 0, "Punctuator"]
])
},
{
/*
* Checking comments:
* https://github.com/eslint/eslint/issues/6571
*/
code: unIndent`
foo();
// comment
/* multiline
comment */
bar();
// trailing comment
`,
output: unIndent`
foo();
// comment
/* multiline
comment */
bar();
// trailing comment
`,
options: [2],
errors: expectedErrors([[2, 0, 2, "Line"], [3, 0, 4, "Block"], [6, 0, 1, "Line"]])
},
{
code: " // comment",
output: "// comment",
errors: expectedErrors([1, 0, 2, "Line"])
},
{
code: unIndent`
foo
// comment
`,
output: unIndent`
foo
// comment
`,
errors: expectedErrors([2, 0, 2, "Line"])
},
{
code: unIndent`
// comment
foo
`,
output: unIndent`
// comment
foo
`,
errors: expectedErrors([1, 0, 2, "Line"])
},
{
code: unIndent`
[
// no elements
]
`,
output: unIndent`
[
// no elements
]
`,
errors: expectedErrors([2, 4, 8, "Line"])
},
{
/*
* Destructuring assignments:
* https://github.com/eslint/eslint/issues/6813
*/
code: unIndent`
var {
foo,
bar,
baz: qux,
foobar: baz = foobar
} = qux;
`,
output: unIndent`
var {
foo,
bar,
baz: qux,
foobar: baz = foobar
} = qux;
`,
options: [2],
errors: expectedErrors([[2, 2, 0, "Identifier"], [4, 2, 4, "Identifier"], [5, 2, 6, "Identifier"], [6, 0, 2, "Punctuator"]])
},
{
code: unIndent`
const {
a
} = {
a: 1
}
`,
output: unIndent`
const {
a
} = {
a: 1
}
`,
options: [2],
errors: expectedErrors([[4, 2, 4, "Identifier"], [5, 0, 2, "Punctuator"]])
},
{
code: unIndent`
var foo = [
bar,
baz
]
`,
output: unIndent`
var foo = [
bar,
baz
]
`,
errors: expectedErrors([[2, 4, 11, "Identifier"], [3, 4, 2, "Identifier"], [4, 0, 10, "Punctuator"]])
},
{
code: unIndent`
var foo = [bar,
baz,
qux
]
`,
output: unIndent`
var foo = [bar,
baz,
qux
]
`,
errors: expectedErrors([2, 4, 0, "Identifier"])
},
{
code: unIndent`
var foo = [bar,
baz,
qux
]
`,
output: unIndent`
var foo = [bar,
baz,
qux
]
`,
options: [2, { ArrayExpression: 0 }],
errors: expectedErrors([[2, 0, 2, "Identifier"], [3, 0, 2, "Identifier"]])
},
{
code: unIndent`
var foo = [bar,
baz,
qux
]
`,
output: unIndent`
var foo = [bar,
baz,
qux
]
`,
options: [2, { ArrayExpression: 8 }],
errors: expectedErrors([[2, 16, 2, "Identifier"], [3, 16, 2, "Identifier"]])
},
{
code: unIndent`
var foo = [bar,
baz,
qux
]
`,
output: unIndent`
var foo = [bar,
baz,
qux
]
`,
options: [2, { ArrayExpression: "first" }],
errors: expectedErrors([[2, 11, 4, "Identifier"], [3, 11, 4, "Identifier"]])
},
{
code: unIndent`
var foo = [bar,
baz, qux
]
`,
output: unIndent`
var foo = [bar,
baz, qux
]
`,
options: [2, { ArrayExpression: "first" }],
errors: expectedErrors([2, 11, 4, "Identifier"])
},
{
code: unIndent`
var foo = [
{ bar: 1,
baz: 2 },
{ bar: 3,
qux: 4 }
]
`,
output: unIndent`
var foo = [
{ bar: 1,
baz: 2 },
{ bar: 3,
qux: 4 }
]
`,
options: [4, { ArrayExpression: 2, ObjectExpression: "first" }],
errors: expectedErrors([[3, 10, 12, "Identifier"], [5, 10, 12, "Identifier"]])
},
{
code: unIndent`
var foo = {
bar: 1,
baz: 2
};
`,
output: unIndent`
var foo = {
bar: 1,
baz: 2
};
`,
options: [2, { ObjectExpression: 0 }],
errors: expectedErrors([[2, 0, 2, "Identifier"], [3, 0, 2, "Identifier"]])
},
{
code: unIndent`
var quux = { foo: 1, bar: 2,
baz: 3 }
`,
output: unIndent`
var quux = { foo: 1, bar: 2,
baz: 3 }
`,
options: [2, { ObjectExpression: "first" }],
errors: expectedErrors([2, 13, 0, "Identifier"])
},
{
code: unIndent`
function foo() {
[
foo
]
}
`,
output: unIndent`
function foo() {
[
foo
]
}
`,
options: [2, { ArrayExpression: 4 }],
errors: expectedErrors([[2, 2, 4, "Punctuator"], [3, 10, 12, "Identifier"], [4, 2, 4, "Punctuator"]])
},
{
code: unIndent`
var [
foo,
bar,
baz,
foobar = baz
] = qux;
`,
output: unIndent`
var [
foo,
bar,
baz,
foobar = baz
] = qux;
`,
options: [2],
errors: expectedErrors([[2, 2, 0, "Identifier"], [4, 2, 4, "Identifier"], [5, 2, 6, "Identifier"], [6, 0, 2, "Punctuator"]])
},
{
code: unIndent`
import {
foo,
bar,
baz
} from 'qux';
`,
output: unIndent`
import {
foo,
bar,
baz
} from 'qux';
`,
parserOptions: { ecmaVersion: 6, sourceType: "module" },
errors: expectedErrors([[2, 4, 0, "Identifier"], [3, 4, 2, "Identifier"]])
},
{
code: unIndent`
import { foo,
bar,
baz,
} from 'qux';
`,
output: unIndent`
import { foo,
bar,
baz,
} from 'qux';
`,
options: [4, { ImportDeclaration: "first" }],
parserOptions: { ecmaVersion: 6, sourceType: "module" },
errors: expectedErrors([[3, 9, 10, "Identifier"]])
},
{
code: unIndent`
import { foo,
bar,
baz,
} from 'qux';
`,
output: unIndent`
import { foo,
bar,
baz,
} from 'qux';
`,
options: [2, { ImportDeclaration: 2 }],
parserOptions: { ecmaVersion: 6, sourceType: "module" },
errors: expectedErrors([[3, 4, 5, "Identifier"]])
},
{
code: unIndent`
var foo = 0, bar = 0, baz = 0;
export {
foo,
bar,
baz
};
`,
output: unIndent`
var foo = 0, bar = 0, baz = 0;
export {
foo,
bar,
baz
};
`,
parserOptions: { ecmaVersion: 6, sourceType: "module" },
errors: expectedErrors([[3, 4, 0, "Identifier"], [4, 4, 2, "Identifier"]])
},
{
code: unIndent`
var foo = 0, bar = 0, baz = 0;
export {
foo,
bar,
baz
} from 'qux';
`,
output: unIndent`
var foo = 0, bar = 0, baz = 0;
export {
foo,
bar,
baz
} from 'qux';
`,
parserOptions: { ecmaVersion: 6, sourceType: "module" },
errors: expectedErrors([[3, 4, 0, "Identifier"], [4, 4, 2, "Identifier"]])
},
{
// https://github.com/eslint/eslint/issues/7233
code: unIndent`
var folder = filePath
.foo()
.bar;
`,
output: unIndent`
var folder = filePath
.foo()
.bar;
`,
options: [2, { MemberExpression: 2 }],
errors: expectedErrors([[2, 4, 2, "Punctuator"], [3, 4, 6, "Punctuator"]])
},
{
code: unIndent`
for (const foo of bar)
baz();
`,
output: unIndent`
for (const foo of bar)
baz();
`,
options: [2],
errors: expectedErrors([2, 2, 4, "Identifier"])
},
{
code: unIndent`
var x = () =>
5;
`,
output: unIndent`
var x = () =>
5;
`,
options: [2],
errors: expectedErrors([2, 2, 4, "Numeric"])
},
{
// BinaryExpressions with parens
code: unIndent`
foo && (
bar
)
`,
output: unIndent`
foo && (
bar
)
`,
options: [4],
errors: expectedErrors([2, 4, 8, "Identifier"])
},
{
code: unIndent`
foo &&
!bar(
)
`,
output: unIndent`
foo &&
!bar(
)
`,
errors: expectedErrors([3, 4, 0, "Punctuator"])
},
{
code: unIndent`
foo &&
![].map(() => {
bar();
})
`,
output: unIndent`
foo &&
![].map(() => {
bar();
})
`,
errors: expectedErrors([[3, 8, 4, "Identifier"], [4, 4, 0, "Punctuator"]])
},
{
code: unIndent`
[
] || [
]
`,
output: unIndent`
[
] || [
]
`,
errors: expectedErrors([3, 0, 4, "Punctuator"])
},
{
code: unIndent`
foo
|| (
bar
)
`,
output: unIndent`
foo
|| (
bar
)
`,
errors: expectedErrors([[3, 12, 16, "Identifier"], [4, 8, 12, "Punctuator"]])
},
{
code: unIndent`
1
+ (
1
)
`,
output: unIndent`
1
+ (
1
)
`,
errors: expectedErrors([[3, 4, 8, "Numeric"], [4, 0, 4, "Punctuator"]])
},
// Template curlies
{
code: unIndent`
\`foo\${
bar}\`
`,
output: unIndent`
\`foo\${
bar}\`
`,
options: [2],
errors: expectedErrors([2, 2, 0, "Identifier"])
},
{
code: unIndent`
\`foo\${
\`bar\${
baz}\`}\`
`,
output: unIndent`
\`foo\${
\`bar\${
baz}\`}\`
`,
options: [2],
errors: expectedErrors([[2, 2, 4, "Template"], [3, 4, 0, "Identifier"]])
},
{
code: unIndent`
\`foo\${
\`bar\${
baz
}\`
}\`
`,
output: unIndent`
\`foo\${
\`bar\${
baz
}\`
}\`
`,
options: [2],
errors: expectedErrors([[2, 2, 4, "Template"], [3, 4, 2, "Identifier"], [4, 2, 4, "Template"], [5, 0, 2, "Template"]])
},
{
code: unIndent`
\`foo\${
(
bar
)
}\`
`,
output: unIndent`
\`foo\${
(
bar
)
}\`
`,
options: [2],
errors: expectedErrors([[2, 2, 0, "Punctuator"], [3, 4, 2, "Identifier"], [4, 2, 0, "Punctuator"]])
},
{
code: unIndent`
function foo() {
\`foo\${bar}baz\${
qux}foo\${
bar}baz\`
}
`,
output: unIndent`
function foo() {
\`foo\${bar}baz\${
qux}foo\${
bar}baz\`
}
`,
errors: expectedErrors([[3, 8, 0, "Identifier"], [4, 8, 2, "Identifier"]])
},
{
code: unIndent`
function foo() {
const template = \`the indentation of
a curly element in a \${
node.type
} node is checked.\`;
}
`,
output: unIndent`
function foo() {
const template = \`the indentation of
a curly element in a \${
node.type
} node is checked.\`;
}
`,
errors: expectedErrors([[4, 4, 8, "Identifier"], [5, 0, 4, "Template"]])
},
{
code: unIndent`
function foo() {
const template = \`this time the
closing curly is at the end of the line \${
foo}
so the spaces before this line aren't removed.\`;
}
`,
output: unIndent`
function foo() {
const template = \`this time the
closing curly is at the end of the line \${
foo}
so the spaces before this line aren't removed.\`;
}
`,
errors: expectedErrors([4, 4, 12, "Identifier"])
},
{
/*
* https://github.com/eslint/eslint/issues/1801
* Note: This issue also mentioned checking the indentation for the 2 below. However,
* this is intentionally ignored because everyone seems to have a different idea of how
* BinaryExpressions should be indented.
*/
code: unIndent`
if (true) {
a = (
1 +
2);
}
`,
output: unIndent`
if (true) {
a = (
1 +
2);
}
`,
errors: expectedErrors([3, 8, 0, "Numeric"])
},
{
// https://github.com/eslint/eslint/issues/3737
code: unIndent`
if (true) {
for (;;) {
b();
}
}
`,
output: unIndent`
if (true) {
for (;;) {
b();
}
}
`,
options: [2],
errors: expectedErrors([[2, 2, 4, "Keyword"], [3, 4, 6, "Identifier"]])
},
{
// https://github.com/eslint/eslint/issues/6670
code: unIndent`
function f() {
return asyncCall()
.then(
'some string',
[
1,
2,
3
]
);
}
`,
output: unIndent`
function f() {
return asyncCall()
.then(
'some string',
[
1,
2,
3
]
);
}
`,
options: [4, { MemberExpression: 1, CallExpression: { arguments: 1 } }],
errors: expectedErrors([
[3, 8, 4, "Punctuator"],
[4, 12, 15, "String"],
[5, 12, 14, "Punctuator"],
[6, 16, 14, "Numeric"],
[7, 16, 9, "Numeric"],
[8, 16, 35, "Numeric"],
[9, 12, 22, "Punctuator"],
[10, 8, 0, "Punctuator"],
[11, 0, 1, "Punctuator"]
])
},
// https://github.com/eslint/eslint/issues/7242
{
code: unIndent`
var x = [
[1],
[2]
]
`,
output: unIndent`
var x = [
[1],
[2]
]
`,
errors: expectedErrors([[2, 4, 6, "Punctuator"], [3, 4, 2, "Punctuator"]])
},
{
code: unIndent`
var y = [
{a: 1},
{b: 2}
]
`,
output: unIndent`
var y = [
{a: 1},
{b: 2}
]
`,
errors: expectedErrors([[2, 4, 6, "Punctuator"], [3, 4, 2, "Punctuator"]])
},
{
code: unIndent`
echo = spawn('cmd.exe',
['foo', 'bar',
'baz']);
`,
output: unIndent`
echo = spawn('cmd.exe',
['foo', 'bar',
'baz']);
`,
options: [2, { ArrayExpression: "first", CallExpression: { arguments: "first" } }],
errors: expectedErrors([[2, 13, 12, "Punctuator"], [3, 14, 13, "String"]])
},
{
// https://github.com/eslint/eslint/issues/7522
code: unIndent`
foo(
)
`,
output: unIndent`
foo(
)
`,
errors: expectedErrors([2, 0, 2, "Punctuator"])
},
{
// https://github.com/eslint/eslint/issues/7616
code: unIndent`
foo(
bar,
{
baz: 1
}
)
`,
output: unIndent`
foo(
bar,
{
baz: 1
}
)
`,
options: [4, { CallExpression: { arguments: "first" } }],
errors: expectedErrors([[2, 4, 8, "Identifier"]])
},
{
code: " new Foo",
output: "new Foo",
errors: expectedErrors([1, 0, 2, "Keyword"])
},
{
code: unIndent`
var foo = 0, bar = 0, baz = 0;
export {
foo,
bar,
baz
}
`,
output: unIndent`
var foo = 0, bar = 0, baz = 0;
export {
foo,
bar,
baz
}
`,
parserOptions: { ecmaVersion: 6, sourceType: "module" },
errors: expectedErrors([[3, 4, 0, "Identifier"], [4, 4, 8, "Identifier"], [5, 4, 2, "Identifier"]])
},
{
code: unIndent`
foo
? bar
: baz
`,
output: unIndent`
foo
? bar
: baz
`,
options: [4, { flatTernaryExpressions: true }],
errors: expectedErrors([3, 4, 0, "Punctuator"])
},
{
code: unIndent`
foo ?
bar :
baz
`,
output: unIndent`
foo ?
bar :
baz
`,
options: [4, { flatTernaryExpressions: true }],
errors: expectedErrors([3, 4, 0, "Identifier"])
},
{
code: unIndent`
foo ?
bar
: baz
`,
output: unIndent`
foo ?
bar
: baz
`,
options: [4, { flatTernaryExpressions: true }],
errors: expectedErrors([3, 4, 2, "Punctuator"])
},
{
code: unIndent`
foo
? bar :
baz
`,
output: unIndent`
foo
? bar :
baz
`,
options: [4, { flatTernaryExpressions: true }],
errors: expectedErrors([3, 4, 0, "Identifier"])
},
{
code: unIndent`
foo ? bar
: baz ? qux
: foobar ? boop
: beep
`,
output: unIndent`
foo ? bar
: baz ? qux
: foobar ? boop
: beep
`,
options: [4, { flatTernaryExpressions: true }],
errors: expectedErrors([
[3, 4, 8, "Punctuator"],
[4, 4, 12, "Punctuator"]
])
},
{
code: unIndent`
foo ? bar :
baz ? qux :
foobar ? boop :
beep
`,
output: unIndent`
foo ? bar :
baz ? qux :
foobar ? boop :
beep
`,
options: [4, { flatTernaryExpressions: true }],
errors: expectedErrors([
[3, 4, 8, "Identifier"],
[4, 4, 12, "Identifier"]
])
},
{
code: unIndent`
var a =
foo ? bar :
baz ? qux :
foobar ? boop :
/*else*/ beep
`,
output: unIndent`
var a =
foo ? bar :
baz ? qux :
foobar ? boop :
/*else*/ beep
`,
options: [4, { flatTernaryExpressions: true }],
errors: expectedErrors([
[3, 4, 6, "Identifier"],
[4, 4, 2, "Identifier"]
])
},
{
code: unIndent`
var a =
foo
? bar
: baz
`,
output: unIndent`
var a =
foo
? bar
: baz
`,
options: [4, { flatTernaryExpressions: true }],
errors: expectedErrors([
[3, 8, 4, "Punctuator"],
[4, 8, 4, "Punctuator"]
])
},
{
code: unIndent`
foo ? bar
: baz ? qux
: foobar ? boop
: beep
`,
output: unIndent`
foo ? bar
: baz ? qux
: foobar ? boop
: beep
`,
options: [4, { flatTernaryExpressions: false }],
errors: expectedErrors([
[3, 8, 4, "Punctuator"],
[4, 12, 4, "Punctuator"]
])
},
{
code: unIndent`
foo ? bar :
baz ? qux :
foobar ? boop :
beep
`,
output: unIndent`
foo ? bar :
baz ? qux :
foobar ? boop :
beep
`,
options: [4, { flatTernaryExpressions: false }],
errors: expectedErrors([
[3, 8, 4, "Identifier"],
[4, 12, 4, "Identifier"]
])
},
{
code: unIndent`
foo
? bar
: baz
? qux
: foobar
? boop
: beep
`,
output: unIndent`
foo
? bar
: baz
? qux
: foobar
? boop
: beep
`,
options: [4, { flatTernaryExpressions: false }],
errors: expectedErrors([
[4, 8, 4, "Punctuator"],
[5, 8, 4, "Punctuator"],
[6, 12, 4, "Punctuator"],
[7, 12, 4, "Punctuator"]
])
},
{
code: unIndent`
foo ?
bar :
baz ?
qux :
foobar ?
boop :
beep
`,
output: unIndent`
foo ?
bar :
baz ?
qux :
foobar ?
boop :
beep
`,
options: [4, { flatTernaryExpressions: false }],
errors: expectedErrors([
[4, 8, 4, "Identifier"],
[5, 8, 4, "Identifier"],
[6, 12, 4, "Identifier"],
[7, 12, 4, "Identifier"]
])
},
{
code: unIndent`
foo.bar('baz', function(err) {
qux;
});
`,
output: unIndent`
foo.bar('baz', function(err) {
qux;
});
`,
options: [2, { CallExpression: { arguments: "first" } }],
errors: expectedErrors([2, 2, 10, "Identifier"])
},
{
code: unIndent`
foo.bar(function() {
cookies;
}).baz(function() {
cookies;
});
`,
output: unIndent`
foo.bar(function() {
cookies;
}).baz(function() {
cookies;
});
`,
options: [2, { MemberExpression: 1 }],
errors: expectedErrors([[4, 2, 4, "Identifier"], [5, 0, 2, "Punctuator"]])
},
{
code: unIndent`
foo.bar().baz(function() {
cookies;
}).qux(function() {
cookies;
});
`,
output: unIndent`
foo.bar().baz(function() {
cookies;
}).qux(function() {
cookies;
});
`,
options: [2, { MemberExpression: 1 }],
errors: expectedErrors([[4, 2, 4, "Identifier"], [5, 0, 2, "Punctuator"]])
},
{
code: unIndent`
[ foo,
bar ].forEach(function() {
baz;
})
`,
output: unIndent`
[ foo,
bar ].forEach(function() {
baz;
})
`,
options: [2, { ArrayExpression: "first", MemberExpression: 1 }],
errors: expectedErrors([[3, 2, 4, "Identifier"], [4, 0, 2, "Punctuator"]])
},
{
code: unIndent`
foo[
bar
];
`,
output: unIndent`
foo[
bar
];
`,
options: [4, { MemberExpression: 1 }],
errors: expectedErrors([3, 0, 4, "Punctuator"])
},
{
code: unIndent`
foo({
bar: 1,
baz: 2
})
`,
output: unIndent`
foo({
bar: 1,
baz: 2
})
`,
options: [4, { ObjectExpression: "first" }],
errors: expectedErrors([[2, 4, 0, "Identifier"], [3, 4, 0, "Identifier"]])
},
{
code: unIndent`
foo(
bar, baz,
qux);
`,
output: unIndent`
foo(
bar, baz,
qux);
`,
options: [2, { CallExpression: { arguments: "first" } }],
errors: expectedErrors([[2, 2, 24, "Identifier"], [3, 2, 24, "Identifier"]])
},
{
code: unIndent`
if (foo) bar()
; [1, 2, 3].map(baz)
`,
output: unIndent`
if (foo) bar()
; [1, 2, 3].map(baz)
`,
errors: expectedErrors([3, 0, 4, "Punctuator"])
},
{
code: unIndent`
if (foo)
;
`,
output: unIndent`
if (foo)
;
`,
errors: expectedErrors([2, 4, 0, "Punctuator"])
},
{
code: unIndent`
import {foo}
from 'bar';
`,
output: unIndent`
import {foo}
from 'bar';
`,
parserOptions: { ecmaVersion: 6, sourceType: "module" },
errors: expectedErrors([2, 4, 0, "Identifier"])
},
{
code: unIndent`
export {foo}
from 'bar';
`,
output: unIndent`
export {foo}
from 'bar';
`,
parserOptions: { ecmaVersion: 6, sourceType: "module" },
errors: expectedErrors([2, 4, 0, "Identifier"])
},
{
code: unIndent`
(
a
) => b => {
c
}
`,
output: unIndent`
(
a
) => b => {
c
}
`,
errors: expectedErrors([[4, 4, 8, "Identifier"], [5, 0, 4, "Punctuator"]])
},
{
code: unIndent`
(
a
) => b => c => d => {
e
}
`,
output: unIndent`
(
a
) => b => c => d => {
e
}
`,
errors: expectedErrors([[4, 4, 8, "Identifier"], [5, 0, 4, "Punctuator"]])
},
{
code: unIndent`
if (
foo
) bar(
baz
);
`,
output: unIndent`
if (
foo
) bar(
baz
);
`,
errors: expectedErrors([[4, 4, 8, "Identifier"], [5, 0, 4, "Punctuator"]])
},
{
code: unIndent`
(
foo
)(
bar
)
`,
output: unIndent`
(
foo
)(
bar
)
`,
errors: expectedErrors([[4, 4, 8, "Identifier"], [5, 0, 4, "Punctuator"]])
},
{
code: unIndent`
(() =>
foo
)(
bar
)
`,
output: unIndent`
(() =>
foo
)(
bar
)
`,
errors: expectedErrors([[4, 4, 8, "Identifier"], [5, 0, 4, "Punctuator"]])
},
{
code: unIndent`
(() => {
foo();
})(
bar
)
`,
output: unIndent`
(() => {
foo();
})(
bar
)
`,
errors: expectedErrors([[4, 4, 8, "Identifier"], [5, 0, 4, "Punctuator"]])
},
{
code: unIndent`
foo.
bar.
baz
`,
output: unIndent`
foo.
bar.
baz
`,
errors: expectedErrors([[2, 4, 2, "Identifier"], [3, 4, 6, "Identifier"]])
},
{
code: unIndent`
const foo = a.b(),
longName
= (baz(
'bar',
'bar'
));
`,
output: unIndent`
const foo = a.b(),
longName
= (baz(
'bar',
'bar'
));
`,
errors: expectedErrors([[4, 8, 12, "String"], [5, 8, 12, "String"], [6, 4, 8, "Punctuator"]])
},
{
code: unIndent`
const foo = a.b(),
longName =
(baz(
'bar',
'bar'
));
`,
output: unIndent`
const foo = a.b(),
longName =
(baz(
'bar',
'bar'
));
`,
errors: expectedErrors([[4, 8, 12, "String"], [5, 8, 12, "String"], [6, 4, 8, "Punctuator"]])
},
{
code: unIndent`
const foo = a.b(),
longName
=baz(
'bar',
'bar'
);
`,
output: unIndent`
const foo = a.b(),
longName
=baz(
'bar',
'bar'
);
`,
errors: expectedErrors([[6, 8, 4, "Punctuator"]])
},
{
code: unIndent`
const foo = a.b(),
longName
=(
'fff'
);
`,
output: unIndent`
const foo = a.b(),
longName
=(
'fff'
);
`,
errors: expectedErrors([[4, 12, 8, "String"]])
},
//----------------------------------------------------------------------
// Ignore Unknown Nodes
//----------------------------------------------------------------------
{
code: unIndent`
namespace Foo {
const bar = 3,
baz = 2;
if (true) {
const bax = 3;
}
}
`,
output: unIndent`
namespace Foo {
const bar = 3,
baz = 2;
if (true) {
const bax = 3;
}
}
`,
parser: parser("unknown-nodes/namespace-invalid"),
errors: expectedErrors([[3, 8, 4, "Identifier"], [6, 8, 4, "Keyword"]])
},
{
code: unIndent`
abstract class Foo {
public bar() {
let aaa = 4,
boo;
if (true) {
boo = 3;
}
boo = 3 + 2;
}
}
`,
output: unIndent`
abstract class Foo {
public bar() {
let aaa = 4,
boo;
if (true) {
boo = 3;
}
boo = 3 + 2;
}
}
`,
parser: parser("unknown-nodes/abstract-class-invalid"),
errors: expectedErrors([[4, 12, 8, "Identifier"], [7, 12, 8, "Identifier"], [10, 8, 4, "Identifier"]])
},
{
code: unIndent`
function foo() {
function bar() {
abstract class X {
public baz() {
if (true) {
qux();
}
}
}
}
}
`,
output: unIndent`
function foo() {
function bar() {
abstract class X {
public baz() {
if (true) {
qux();
}
}
}
}
}
`,
parser: parser("unknown-nodes/functions-with-abstract-class-invalid"),
errors: expectedErrors([
[4, 12, 8, "Keyword"],
[5, 16, 8, "Keyword"],
[6, 20, 8, "Identifier"],
[7, 16, 8, "Punctuator"],
[8, 12, 8, "Punctuator"]
])
},
{
code: unIndent`
namespace Unknown {
function foo() {
function bar() {
abstract class X {
public baz() {
if (true) {
qux();
}
}
}
}
}
}
`,
output: unIndent`
namespace Unknown {
function foo() {
function bar() {
abstract class X {
public baz() {
if (true) {
qux();
}
}
}
}
}
}
`,
parser: parser("unknown-nodes/namespace-with-functions-with-abstract-class-invalid"),
errors: expectedErrors([
[3, 8, 4, "Keyword"],
[7, 24, 20, "Identifier"]
])
},
//----------------------------------------------------------------------
// JSX tests
// Some of the following tests are adapted from the tests in eslint-plugin-react.
// License: https://github.com/yannickcr/eslint-plugin-react/blob/7ca9841f22d599f447a27ef5b2a97def9229d6c8/LICENSE
//----------------------------------------------------------------------
{
code: unIndent`
<App>
<Foo />
</App>
`,
output: unIndent`
<App>
<Foo />
</App>
`,
errors: expectedErrors([2, 4, 2, "Punctuator"])
},
{
code: unIndent`
<App>
<Foo />
</App>
`,
output: unIndent`
<App>
<Foo />
</App>
`,
options: [2],
errors: expectedErrors([2, 2, 4, "Punctuator"])
},
{
code: unIndent`
<App>
<Foo />
</App>
`,
output: unIndent`
<App>
\t<Foo />
</App>
`,
options: ["tab"],
errors: expectedErrors([2, "1 tab", "4 spaces", "Punctuator"])
},
{
code: unIndent`
function App() {
return <App>
<Foo />
</App>;
}
`,
output: unIndent`
function App() {
return <App>
<Foo />
</App>;
}
`,
options: [2],
errors: expectedErrors([4, 2, 9, "Punctuator"])
},
{
code: unIndent`
function App() {
return (<App>
<Foo />
</App>);
}
`,
output: unIndent`
function App() {
return (<App>
<Foo />
</App>);
}
`,
options: [2],
errors: expectedErrors([4, 2, 4, "Punctuator"])
},
{
code: unIndent`
function App() {
return (
<App>
<Foo />
</App>
);
}
`,
output: unIndent`
function App() {
return (
<App>
<Foo />
</App>
);
}
`,
options: [2],
errors: expectedErrors([[3, 4, 0, "Punctuator"], [4, 6, 2, "Punctuator"], [5, 4, 0, "Punctuator"]])
},
{
code: unIndent`
<App>
{test}
</App>
`,
output: unIndent`
<App>
{test}
</App>
`,
errors: expectedErrors([2, 4, 1, "Punctuator"])
},
{
code: unIndent`
<App>
{options.map((option, index) => (
<option key={index} value={option.key}>
{option.name}
</option>
))}
</App>
`,
output: unIndent`
<App>
{options.map((option, index) => (
<option key={index} value={option.key}>
{option.name}
</option>
))}
</App>
`,
errors: expectedErrors([4, 12, 11, "Punctuator"])
},
{
code: unIndent`
[
<div />,
<div />
]
`,
output: unIndent`
[
<div />,
<div />
]
`,
options: [2],
errors: expectedErrors([3, 2, 4, "Punctuator"])
},
{
code: unIndent`
<App>
<Foo />
</App>
`,
output: unIndent`
<App>
\t<Foo />
</App>
`,
options: ["tab"],
errors: expectedErrors([3, "1 tab", "1 space", "Punctuator"])
},
{
/*
* Multiline ternary
* (colon at the end of the first expression)
*/
code: unIndent`
foo ?
<Foo /> :
<Bar />
`,
output: unIndent`
foo ?
<Foo /> :
<Bar />
`,
errors: expectedErrors([3, 4, 0, "Punctuator"])
},
{
/*
* Multiline ternary
* (colon on its own line)
*/
code: unIndent`
foo ?
<Foo />
:
<Bar />
`,
output: unIndent`
foo ?
<Foo />
:
<Bar />
`,
errors: expectedErrors([[3, 4, 0, "Punctuator"], [4, 4, 0, "Punctuator"]])
},
{
/*
* Multiline ternary
* (colon at the end of the first expression, parenthesized first expression)
*/
code: unIndent`
foo ? (
<Foo />
) :
<Bar />
`,
output: unIndent`
foo ? (
<Foo />
) :
<Bar />
`,
errors: expectedErrors([4, 4, 0, "Punctuator"])
},
{
code: unIndent`
<App
foo
/>
`,
output: unIndent`
<App
foo
/>
`,
errors: expectedErrors([2, 4, 2, "JSXIdentifier"])
},
{
code: unIndent`
<App
foo
/>
`,
output: unIndent`
<App
foo
/>
`,
options: [2],
errors: expectedErrors([3, 0, 2, "Punctuator"])
},
{
code: unIndent`
<App
foo
></App>
`,
output: unIndent`
<App
foo
></App>
`,
options: [2],
errors: expectedErrors([3, 0, 2, "Punctuator"])
},
{
code: unIndent`
const Button = function(props) {
return (
<Button
size={size}
onClick={onClick}
>
Button Text
</Button>
);
};
`,
output: unIndent`
const Button = function(props) {
return (
<Button
size={size}
onClick={onClick}
>
Button Text
</Button>
);
};
`,
options: [2],
errors: expectedErrors([6, 4, 36, "Punctuator"])
},
{
code: unIndent`
var x = function() {
return <App
foo
/>
}
`,
output: unIndent`
var x = function() {
return <App
foo
/>
}
`,
options: [2],
errors: expectedErrors([4, 2, 9, "Punctuator"])
},
{
code: unIndent`
var x = <App
foo
/>
`,
output: unIndent`
var x = <App
foo
/>
`,
options: [2],
errors: expectedErrors([3, 0, 8, "Punctuator"])
},
{
code: unIndent`
var x = (
<Something
/>
)
`,
output: unIndent`
var x = (
<Something
/>
)
`,
options: [2],
errors: expectedErrors([3, 2, 4, "Punctuator"])
},
{
code: unIndent`
<App
\tfoo
\t/>
`,
output: unIndent`
<App
\tfoo
/>
`,
options: ["tab"],
errors: expectedErrors("tab", [3, 0, 1, "Punctuator"])
},
{
code: unIndent`
<App
\tfoo
\t></App>
`,
output: unIndent`
<App
\tfoo
></App>
`,
options: ["tab"],
errors: expectedErrors("tab", [3, 0, 1, "Punctuator"])
},
{
code: unIndent`
<
foo
.bar
.baz
>
foo
</
foo.
bar.
baz
>
`,
output: unIndent`
<
foo
.bar
.baz
>
foo
</
foo.
bar.
baz
>
`,
errors: expectedErrors([
[3, 8, 4, "Punctuator"],
[4, 8, 4, "Punctuator"],
[9, 8, 4, "JSXIdentifier"],
[10, 8, 4, "JSXIdentifier"]
])
},
{
code: unIndent`
<
input
type=
"number"
/>
`,
output: unIndent`
<
input
type=
"number"
/>
`,
errors: expectedErrors([4, 8, 4, "JSXText"])
},
{
code: unIndent`
<
input
type=
{'number'}
/>
`,
output: unIndent`
<
input
type=
{'number'}
/>
`,
errors: expectedErrors([4, 8, 4, "Punctuator"])
},
{
code: unIndent`
<
input
type
="number"
/>
`,
output: unIndent`
<
input
type
="number"
/>
`,
errors: expectedErrors([4, 8, 4, "Punctuator"])
},
{
code: unIndent`
foo ? (
bar
) : (
baz
)
`,
output: unIndent`
foo ? (
bar
) : (
baz
)
`,
errors: expectedErrors([[4, 4, 8, "Identifier"], [5, 0, 4, "Punctuator"]])
},
{
code: unIndent`
foo ? (
<div>
</div>
) : (
<span>
</span>
)
`,
output: unIndent`
foo ? (
<div>
</div>
) : (
<span>
</span>
)
`,
errors: expectedErrors([[5, 4, 8, "Punctuator"], [6, 4, 8, "Punctuator"], [7, 0, 4, "Punctuator"]])
},
{
code: unIndent`
<div>
{
(
1
)
}
</div>
`,
output: unIndent`
<div>
{
(
1
)
}
</div>
`,
errors: expectedErrors([[3, 8, 4, "Punctuator"], [4, 12, 8, "Numeric"], [5, 8, 4, "Punctuator"]])
},
{
code: unIndent`
<div>
{
/* foo */
}
</div>
`,
output: unIndent`
<div>
{
/* foo */
}
</div>
`,
errors: expectedErrors([3, 8, 6, "Block"])
},
{
code: unIndent`
<div
{...props}
/>
`,
output: unIndent`
<div
{...props}
/>
`,
errors: expectedErrors([2, 4, 0, "Punctuator"])
},
{
code: unIndent`
<div
{
...props
}
/>
`,
output: unIndent`
<div
{
...props
}
/>
`,
errors: expectedErrors([3, 8, 6, "Punctuator"])
},
{
code: unIndent`
<div>foo
<div>bar</div>
</div>
`,
output: unIndent`
<div>foo
<div>bar</div>
</div>
`,
errors: expectedErrors([2, 4, 0, "Punctuator"])
},
{
code: unIndent`
<small>Foo bar
<a>baz qux</a>.
</small>
`,
output: unIndent`
<small>Foo bar
<a>baz qux</a>.
</small>
`,
errors: expectedErrors([2, 4, 0, "Punctuator"])
},
/*
* JSX Fragments
* https://github.com/eslint/eslint/issues/12208
*/
{
code: unIndent`
<>
<A />
</>
`,
output: unIndent`
<>
<A />
</>
`,
errors: expectedErrors([2, 4, 0, "Punctuator"])
},
{
code: unIndent`
<
>
<A />
</>
`,
output: unIndent`
<
>
<A />
</>
`,
errors: expectedErrors([2, 0, 4, "Punctuator"])
},
{
code: unIndent`
<>
<A />
<
/>
`,
output: unIndent`
<>
<A />
<
/>
`,
errors: expectedErrors([4, 0, 4, "Punctuator"])
},
{
code: unIndent`
<>
<A />
</
>
`,
output: unIndent`
<>
<A />
</
>
`,
errors: expectedErrors([4, 0, 4, "Punctuator"])
},
{
code: unIndent`
<
>
<A />
</
>
`,
output: unIndent`
<
>
<A />
</
>
`,
errors: expectedErrors([
[2, 0, 4, "Punctuator"],
[5, 0, 4, "Punctuator"]
])
},
{
code: unIndent`
<
>
<A />
<
/>
`,
output: unIndent`
<
>
<A />
<
/>
`,
errors: expectedErrors([
[2, 0, 4, "Punctuator"],
[5, 0, 4, "Punctuator"]
])
},
{
code: unIndent`
< // Comment
>
<A />
</>
`,
output: unIndent`
< // Comment
>
<A />
</>
`,
errors: expectedErrors([2, 0, 4, "Punctuator"])
},
{
code: unIndent`
<>
<A />
< // Comment
/>
`,
output: unIndent`
<>
<A />
< // Comment
/>
`,
errors: expectedErrors([4, 0, 4, "Punctuator"])
},
{
code: unIndent`
<>
<A />
</ // Comment
>
`,
output: unIndent`
<>
<A />
</ // Comment
>
`,
errors: expectedErrors([4, 0, 4, "Punctuator"])
},
{
code: unIndent`
< /* Comment */
>
<A />
</>
`,
output: unIndent`
< /* Comment */
>
<A />
</>
`,
errors: expectedErrors([2, 0, 4, "Punctuator"])
},
{
code: unIndent`
<>
<A />
< /* Comment */
/>
`,
output: unIndent`
<>
<A />
< /* Comment */
/>
`,
errors: expectedErrors([4, 0, 4, "Punctuator"])
},
{
code: unIndent`
<>
<A />
</ /* Comment */
>
`,
output: unIndent`
<>
<A />
</ /* Comment */
>
`,
errors: expectedErrors([4, 0, 4, "Punctuator"])
},
{
code: unIndent`
({
foo
}: bar) => baz
`,
output: unIndent`
({
foo
}: bar) => baz
`,
parser: require.resolve("../../fixtures/parsers/babel-eslint7/object-pattern-with-annotation"),
errors: expectedErrors([3, 0, 4, "Punctuator"])
},
{
code: unIndent`
([
foo
]: bar) => baz
`,
output: unIndent`
([
foo
]: bar) => baz
`,
parser: require.resolve("../../fixtures/parsers/babel-eslint7/array-pattern-with-annotation"),
errors: expectedErrors([3, 0, 4, "Punctuator"])
},
{
code: unIndent`
({
foo
}: {}) => baz
`,
output: unIndent`
({
foo
}: {}) => baz
`,
parser: require.resolve("../../fixtures/parsers/babel-eslint7/object-pattern-with-object-annotation"),
errors: expectedErrors([3, 0, 4, "Punctuator"])
},
{
code: unIndent`
class Foo {
foo() {
bar();
}
}
`,
output: unIndent`
class Foo {
foo() {
bar();
}
}
`,
options: [4, { ignoredNodes: ["ClassBody"] }],
errors: expectedErrors([3, 4, 0, "Identifier"])
},
{
code: unIndent`
$(function() {
foo();
bar();
foo(function() {
baz();
});
});
`,
output: unIndent`
$(function() {
foo();
bar();
foo(function() {
baz();
});
});
`,
options: [4, {
ignoredNodes: ["ExpressionStatement > CallExpression[callee.name='$'] > FunctionExpression > BlockStatement"]
}],
errors: expectedErrors([7, 4, 0, "Identifier"])
},
{
code: unIndent`
(function($) {
$(function() {
foo;
});
})()
`,
output: unIndent`
(function($) {
$(function() {
foo;
});
})()
`,
options: [4, {
ignoredNodes: ["ExpressionStatement > CallExpression > FunctionExpression.callee > BlockStatement"]
}],
errors: expectedErrors([3, 4, 0, "Identifier"])
},
{
code: unIndent`
if (foo) {
doSomething();
// Intentionally unindented comment
doSomethingElse();
}
`,
output: unIndent`
if (foo) {
doSomething();
// Intentionally unindented comment
doSomethingElse();
}
`,
options: [4, { ignoreComments: false }],
errors: expectedErrors([4, 4, 0, "Line"])
},
{
code: unIndent`
if (foo) {
doSomething();
/* Intentionally unindented comment */
doSomethingElse();
}
`,
output: unIndent`
if (foo) {
doSomething();
/* Intentionally unindented comment */
doSomethingElse();
}
`,
options: [4, { ignoreComments: false }],
errors: expectedErrors([4, 4, 0, "Block"])
},
{
code: unIndent`
const obj = {
foo () {
return condition ? // comment
1 :
2
}
}
`,
output: unIndent`
const obj = {
foo () {
return condition ? // comment
1 :
2
}
}
`,
errors: expectedErrors([4, 12, 8, "Numeric"])
},
//----------------------------------------------------------------------
// Comment alignment tests
//----------------------------------------------------------------------
{
code: unIndent`
if (foo) {
// Comment cannot align with code immediately above if there is a whitespace gap
doSomething();
}
`,
output: unIndent`
if (foo) {
// Comment cannot align with code immediately above if there is a whitespace gap
doSomething();
}
`,
errors: expectedErrors([3, 4, 0, "Line"])
},
{
code: unIndent`
if (foo) {
foo(
bar);
// Comment cannot align with code immediately below if there is a whitespace gap
}
`,
output: unIndent`
if (foo) {
foo(
bar);
// Comment cannot align with code immediately below if there is a whitespace gap
}
`,
errors: expectedErrors([4, 4, 0, "Line"])
},
{
code: unIndent`
[{
foo
},
// Comment between nodes
{
bar
}];
`,
output: unIndent`
[{
foo
},
// Comment between nodes
{
bar
}];
`,
errors: expectedErrors([5, 0, 4, "Line"])
},
{
code: unIndent`
let foo
// comment
;(async () => {})()
`,
output: unIndent`
let foo
// comment
;(async () => {})()
`,
errors: expectedErrors([3, 0, 4, "Line"])
},
{
code: unIndent`
let foo
// comment
;(async () => {})()
`,
output: unIndent`
let foo
// comment
;(async () => {})()
`,
errors: expectedErrors([2, 0, 4, "Line"])
},
{
code: unIndent`
let foo
/* comment */;
(async () => {})()
`,
output: unIndent`
let foo
/* comment */;
(async () => {})()
`,
errors: expectedErrors([3, 4, 0, "Block"])
},
{
code: unIndent`
// comment
;(async () => {})()
`,
output: unIndent`
// comment
;(async () => {})()
`,
errors: expectedErrors([1, 0, 4, "Line"])
},
{
code: unIndent`
// comment
;(async () => {})()
`,
output: unIndent`
// comment
;(async () => {})()
`,
errors: expectedErrors([1, 0, 4, "Line"])
},
{
code: unIndent`
{
let foo
// comment
;(async () => {})()
}
`,
output: unIndent`
{
let foo
// comment
;(async () => {})()
}
`,
errors: expectedErrors([4, 4, 8, "Line"])
},
{
code: unIndent`
{
let foo
// comment
;(async () => {})()
}
`,
output: unIndent`
{
let foo
// comment
;(async () => {})()
}
`,
errors: expectedErrors([3, 4, 8, "Line"])
},
{
code: unIndent`
{
let foo
/* comment */;
(async () => {})()
}
`,
output: unIndent`
{
let foo
/* comment */;
(async () => {})()
}
`,
errors: expectedErrors([4, 8, 4, "Block"])
},
{
code: unIndent`
const foo = 1
const bar = foo
/* comment */
;[1, 2, 3].forEach(() => {})
`,
output: unIndent`
const foo = 1
const bar = foo
/* comment */
;[1, 2, 3].forEach(() => {})
`,
errors: expectedErrors([4, 0, 4, "Block"])
},
{
code: unIndent`
const foo = 1
const bar = foo
/* comment */
;[1, 2, 3].forEach(() => {})
`,
output: unIndent`
const foo = 1
const bar = foo
/* comment */
;[1, 2, 3].forEach(() => {})
`,
errors: expectedErrors([3, 0, 4, "Block"])
},
{
code: unIndent`
const foo = 1
const bar = foo
/* comment */;
[1, 2, 3].forEach(() => {})
`,
output: unIndent`
const foo = 1
const bar = foo
/* comment */;
[1, 2, 3].forEach(() => {})
`,
errors: expectedErrors([4, 4, 0, "Block"])
},
{
code: unIndent`
/* comment */
;[1, 2, 3].forEach(() => {})
`,
output: unIndent`
/* comment */
;[1, 2, 3].forEach(() => {})
`,
errors: expectedErrors([1, 0, 4, "Block"])
},
{
code: unIndent`
/* comment */
;[1, 2, 3].forEach(() => {})
`,
output: unIndent`
/* comment */
;[1, 2, 3].forEach(() => {})
`,
errors: expectedErrors([1, 0, 4, "Block"])
},
{
code: unIndent`
{
const foo = 1
const bar = foo
/* comment */
;[1, 2, 3].forEach(() => {})
}
`,
output: unIndent`
{
const foo = 1
const bar = foo
/* comment */
;[1, 2, 3].forEach(() => {})
}
`,
errors: expectedErrors([5, 4, 8, "Block"])
},
{
code: unIndent`
{
const foo = 1
const bar = foo
/* comment */
;[1, 2, 3].forEach(() => {})
}
`,
output: unIndent`
{
const foo = 1
const bar = foo
/* comment */
;[1, 2, 3].forEach(() => {})
}
`,
errors: expectedErrors([4, 4, 8, "Block"])
},
{
code: unIndent`
{
const foo = 1
const bar = foo
/* comment */;
[1, 2, 3].forEach(() => {})
}
`,
output: unIndent`
{
const foo = 1
const bar = foo
/* comment */;
[1, 2, 3].forEach(() => {})
}
`,
errors: expectedErrors([5, 8, 4, "Block"])
},
// import expressions
{
code: unIndent`
import(
source
)
`,
output: unIndent`
import(
source
)
`,
parserOptions: { ecmaVersion: 2020 },
errors: expectedErrors([
[2, 4, 0, "Identifier"],
[3, 0, 4, "Punctuator"]
])
},
// https://github.com/eslint/eslint/issues/12122
{
code: unIndent`
foo(() => {
tag\`
multiline
template\${a} \${b}
literal
\`(() => {
bar();
});
});
`,
output: unIndent`
foo(() => {
tag\`
multiline
template\${a} \${b}
literal
\`(() => {
bar();
});
});
`,
parserOptions: { ecmaVersion: 2015 },
errors: expectedErrors([
[7, 8, 4, "Identifier"]
])
},
{
code: unIndent`
{
tag\`
multiline
template
literal
\${a} \${b}\`(() => {
bar();
});
}
`,
output: unIndent`
{
tag\`
multiline
template
literal
\${a} \${b}\`(() => {
bar();
});
}
`,
parserOptions: { ecmaVersion: 2015 },
errors: expectedErrors([
[2, 4, 8, "Identifier"],
[7, 8, 12, "Identifier"],
[8, 4, 8, "Punctuator"]
])
},
{
code: unIndent`
foo(() => {
tagOne\`\${a} \${b}
multiline
template
literal
\`(() => {
tagTwo\`
multiline
template
literal
\`(() => {
bar();
});
baz();
});
});
`,
output: unIndent`
foo(() => {
tagOne\`\${a} \${b}
multiline
template
literal
\`(() => {
tagTwo\`
multiline
template
literal
\`(() => {
bar();
});
baz();
});
});
`,
parserOptions: { ecmaVersion: 2015 },
errors: expectedErrors([
[7, 8, 12, "Identifier"],
[15, 8, 12, "Identifier"],
[16, 4, 0, "Punctuator"]
])
},
{
code: unIndent`
{
tagOne\`
multiline
template
literal
\${a} \${b}\`(() => {
tagTwo\`
multiline
template
literal
\`(() => {
bar();
});
baz();
});
}
`,
output: unIndent`
{
tagOne\`
multiline
template
literal
\${a} \${b}\`(() => {
tagTwo\`
multiline
template
literal
\`(() => {
bar();
});
baz();
});
}
`,
parserOptions: { ecmaVersion: 2015 },
errors: expectedErrors([
[7, 8, 12, "Identifier"],
[15, 8, 12, "Identifier"],
[16, 4, 0, "Punctuator"]
])
},
{
code: unIndent`
tagOne\`multiline \${a} \${b}
template
literal
\`(() => {
foo();
tagTwo\`multiline
template
literal
\`({
bar: 1,
baz: 2
});
});
`,
output: unIndent`
tagOne\`multiline \${a} \${b}
template
literal
\`(() => {
foo();
tagTwo\`multiline
template
literal
\`({
bar: 1,
baz: 2
});
});
`,
parserOptions: { ecmaVersion: 2015 },
errors: expectedErrors([
[5, 4, 0, "Identifier"],
[11, 8, 4, "Identifier"]
])
},
{
code: unIndent`
tagOne\`multiline
template \${a} \${b}
literal\`({
foo: 1,
bar: tagTwo\`multiline
template
literal\`(() => {
baz();
})
});
`,
output: unIndent`
tagOne\`multiline
template \${a} \${b}
literal\`({
foo: 1,
bar: tagTwo\`multiline
template
literal\`(() => {
baz();
})
});
`,
parserOptions: { ecmaVersion: 2015 },
errors: expectedErrors([
[4, 4, 8, "Identifier"],
[5, 4, 0, "Identifier"],
[9, 8, 0, "Identifier"]
])
},
{
code: unIndent`
foo.bar\` template literal \`(() => {
baz();
})
`,
output: unIndent`
foo.bar\` template literal \`(() => {
baz();
})
`,
parserOptions: { ecmaVersion: 2015 },
errors: expectedErrors([
[2, 4, 8, "Identifier"]
])
},
{
code: unIndent`
foo.bar.baz\` template literal \`(() => {
baz();
})
`,
output: unIndent`
foo.bar.baz\` template literal \`(() => {
baz();
})
`,
parserOptions: { ecmaVersion: 2015 },
errors: expectedErrors([
[2, 4, 0, "Identifier"],
[3, 0, 4, "Punctuator"]
])
},
{
code: unIndent`
foo
.bar\` template
literal \`(() => {
baz();
})
`,
output: unIndent`
foo
.bar\` template
literal \`(() => {
baz();
})
`,
parserOptions: { ecmaVersion: 2015 },
errors: expectedErrors([
[5, 4, 0, "Punctuator"]
])
},
{
code: unIndent`
foo
.test\`
\${a} \${b}
\`(() => {
bar();
})
`,
output: unIndent`
foo
.test\`
\${a} \${b}
\`(() => {
bar();
})
`,
parserOptions: { ecmaVersion: 2015 },
errors: expectedErrors([
[5, 8, 0, "Identifier"]
])
},
{
code: unIndent`
foo
.test\`
\${a} \${b}
\`(() => {
bar();
})
`,
output: unIndent`
foo
.test\`
\${a} \${b}
\`(() => {
bar();
})
`,
options: [4, { MemberExpression: 0 }],
parserOptions: { ecmaVersion: 2015 },
errors: expectedErrors([
[2, 0, 4, "Punctuator"],
[5, 4, 0, "Identifier"],
[6, 0, 4, "Punctuator"]
])
},
// Optional chaining
{
code: unIndent`
obj
?.prop
?.[key]
?.
[key]
`,
output: unIndent`
obj
?.prop
?.[key]
?.
[key]
`,
options: [4],
parserOptions: { ecmaVersion: 2020 },
errors: expectedErrors([
[2, 4, 0, "Punctuator"],
[3, 4, 0, "Punctuator"],
[4, 4, 0, "Punctuator"],
[5, 8, 0, "Punctuator"]
])
},
{
code: unIndent`
(
longSomething
?.prop
?.[key]
)
?.prop
?.[key]
`,
output: unIndent`
(
longSomething
?.prop
?.[key]
)
?.prop
?.[key]
`,
options: [4],
parserOptions: { ecmaVersion: 2020 },
errors: expectedErrors([
[6, 4, 0, "Punctuator"],
[7, 4, 0, "Punctuator"]
])
},
{
code: unIndent`
obj
?.(arg)
?.
(arg)
`,
output: unIndent`
obj
?.(arg)
?.
(arg)
`,
options: [4],
parserOptions: { ecmaVersion: 2020 },
errors: expectedErrors([
[2, 4, 0, "Punctuator"],
[3, 4, 0, "Punctuator"],
[4, 4, 0, "Punctuator"]
])
},
{
code: unIndent`
(
longSomething
?.(arg)
?.(arg)
)
?.(arg)
?.(arg)
`,
output: unIndent`
(
longSomething
?.(arg)
?.(arg)
)
?.(arg)
?.(arg)
`,
options: [4],
parserOptions: { ecmaVersion: 2020 },
errors: expectedErrors([
[6, 4, 0, "Punctuator"],
[7, 4, 0, "Punctuator"]
])
},
{
code: unIndent`
const foo = async (arg1,
arg2) =>
{
return arg1 + arg2;
}
`,
output: unIndent`
const foo = async (arg1,
arg2) =>
{
return arg1 + arg2;
}
`,
options: [2, { FunctionDeclaration: { parameters: "first" }, FunctionExpression: { parameters: "first" } }],
parserOptions: { ecmaVersion: 2020 },
errors: expectedErrors([
[2, 19, 20, "Identifier"]
])
},
{
code: unIndent`
const a = async
b => {}
`,
output: unIndent`
const a = async
b => {}
`,
options: [2],
errors: expectedErrors([
[2, 0, 1, "Identifier"]
])
},
{
code: unIndent`
class C {
field1;
static field2;
}
`,
output: unIndent`
class C {
field1;
static field2;
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 },
errors: expectedErrors([
[2, 4, 0, "Identifier"],
[3, 4, 0, "Keyword"]
])
},
{
code: unIndent`
class C {
field1
=
0
;
static
field2
=
0
;
}
`,
output: unIndent`
class C {
field1
=
0
;
static
field2
=
0
;
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 },
errors: expectedErrors([
[2, 4, 0, "Identifier"],
[3, 8, 0, "Punctuator"],
[4, 12, 0, "Numeric"],
[5, 12, 0, "Punctuator"],
[6, 4, 0, "Keyword"],
[7, 8, 0, "Identifier"],
[8, 12, 0, "Punctuator"],
[9, 16, 0, "Numeric"],
[10, 16, 0, "Punctuator"]
])
},
{
code: unIndent`
class C {
[
field1
]
=
0
;
static
[
field2
]
=
0
;
[
field3
] =
0;
[field4] =
0;
}
`,
output: unIndent`
class C {
[
field1
]
=
0
;
static
[
field2
]
=
0
;
[
field3
] =
0;
[field4] =
0;
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 },
errors: expectedErrors([
[2, 4, 0, "Punctuator"],
[3, 8, 0, "Identifier"],
[4, 4, 0, "Punctuator"],
[5, 8, 0, "Punctuator"],
[6, 12, 0, "Numeric"],
[7, 12, 0, "Punctuator"],
[8, 4, 0, "Keyword"],
[9, 4, 0, "Punctuator"],
[10, 8, 0, "Identifier"],
[11, 4, 0, "Punctuator"],
[12, 8, 0, "Punctuator"],
[13, 12, 0, "Numeric"],
[14, 12, 0, "Punctuator"],
[15, 4, 0, "Punctuator"],
[16, 8, 0, "Identifier"],
[17, 4, 0, "Punctuator"],
[18, 8, 0, "Numeric"],
[19, 4, 0, "Punctuator"],
[20, 8, 0, "Numeric"]
])
},
{
code: unIndent`
class C {
field1 = (
foo
+ bar
);
}
`,
output: unIndent`
class C {
field1 = (
foo
+ bar
);
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 },
errors: expectedErrors([
[2, 4, 0, "Identifier"],
[3, 8, 0, "Identifier"],
[5, 4, 0, "Punctuator"]
])
},
{
code: unIndent`
class C {
#aaa
foo() {
return this.#aaa
}
}
`,
output: unIndent`
class C {
#aaa
foo() {
return this.#aaa
}
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 },
errors: expectedErrors([
[2, 4, 0, "PrivateIdentifier"],
[3, 4, 0, "Identifier"],
[4, 8, 0, "Keyword"],
[5, 4, 0, "Punctuator"]
])
},
{
code: unIndent`
class C {
static {
foo();
bar();
}
}
`,
output: unIndent`
class C {
static {
foo();
bar();
}
}
`,
options: [2],
parserOptions: { ecmaVersion: 2022 },
errors: expectedErrors([
[2, 2, 0, "Keyword"],
[3, 4, 0, "Identifier"],
[4, 4, 0, "Identifier"],
[5, 2, 0, "Punctuator"]
])
},
{
code: unIndent`
class C {
static {
foo();
bar();
}
}
`,
output: unIndent`
class C {
static {
foo();
bar();
}
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 },
errors: expectedErrors([
[2, 4, 0, "Keyword"],
[3, 8, 0, "Identifier"],
[4, 8, 0, "Identifier"],
[5, 4, 0, "Punctuator"]
])
},
{
code: unIndent`
class C {
static {
foo();
bar();
}
}
`,
output: unIndent`
class C {
static {
foo();
bar();
}
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 },
errors: expectedErrors([
[2, 4, 8, "Keyword"],
[3, 8, 4, "Identifier"],
[4, 8, 0, "Identifier"],
[5, 4, 8, "Punctuator"]
])
},
{
code: unIndent`
class C {
static {
foo();
bar();
}
}
`,
output: unIndent`
class C {
static {
foo();
bar();
}
}
`,
options: [4, { StaticBlock: { body: 2 } }],
parserOptions: { ecmaVersion: 2022 },
errors: expectedErrors([
[2, 4, 0, "Keyword"],
[3, 12, 0, "Identifier"],
[4, 12, 0, "Identifier"],
[5, 4, 0, "Punctuator"]
])
},
{
code: unIndent`
class C {
static {
foo();
bar();
}
}
`,
output: unIndent`
class C {
static {
foo();
bar();
}
}
`,
options: [4, { StaticBlock: { body: 0 } }],
parserOptions: { ecmaVersion: 2022 },
errors: expectedErrors([
[2, 4, 0, "Keyword"],
[3, 4, 0, "Identifier"],
[4, 4, 0, "Identifier"],
[5, 4, 0, "Punctuator"]
])
},
{
code: unIndent`
class C {
static {
foo();
bar();
}
}
`,
output: unIndent`
class C {
\tstatic {
\t\tfoo();
\t\tbar();
\t}
}
`,
options: ["tab"],
parserOptions: { ecmaVersion: 2022 },
errors: expectedErrors("tab", [
[2, 1, 0, "Keyword"],
[3, 2, 0, "Identifier"],
[4, 2, 0, "Identifier"],
[5, 1, 0, "Punctuator"]
])
},
{
code: unIndent`
class C {
static {
foo();
bar();
}
}
`,
output: unIndent`
class C {
\tstatic {
\t\t\tfoo();
\t\t\tbar();
\t}
}
`,
options: ["tab", { StaticBlock: { body: 2 } }],
parserOptions: { ecmaVersion: 2022 },
errors: expectedErrors("tab", [
[2, 1, 0, "Keyword"],
[3, 3, 0, "Identifier"],
[4, 3, 0, "Identifier"],
[5, 1, 0, "Punctuator"]
])
},
{
code: unIndent`
class C {
static
{
foo();
bar();
}
}
`,
output: unIndent`
class C {
static
{
foo();
bar();
}
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 },
errors: expectedErrors([
[2, 4, 0, "Keyword"],
[3, 4, 0, "Punctuator"],
[4, 8, 0, "Identifier"],
[5, 8, 0, "Identifier"],
[6, 4, 0, "Punctuator"]
])
},
{
code: unIndent`
class C {
static
{
foo();
bar();
}
}
`,
output: unIndent`
class C {
static
{
foo();
bar();
}
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 },
errors: expectedErrors([
[3, 4, 8, "Punctuator"],
[6, 4, 8, "Punctuator"]
])
},
{
code: unIndent`
class C {
static {
var x,
y;
}
}
`,
output: unIndent`
class C {
static {
var x,
y;
}
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 },
errors: expectedErrors([
[2, 4, 0, "Keyword"],
[3, 8, 0, "Keyword"],
[4, 12, 0, "Identifier"],
[5, 4, 0, "Punctuator"]
])
},
{
code: unIndent`
class C {
static
{
var x,
y;
}
}
`,
output: unIndent`
class C {
static
{
var x,
y;
}
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 },
errors: expectedErrors([
[2, 4, 0, "Keyword"],
[3, 4, 0, "Punctuator"],
[4, 8, 0, "Keyword"],
[5, 12, 0, "Identifier"],
[6, 4, 0, "Punctuator"]
])
},
{
code: unIndent`
class C {
static {
if (foo) {
bar;
}
}
}
`,
output: unIndent`
class C {
static {
if (foo) {
bar;
}
}
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 },
errors: expectedErrors([
[2, 4, 0, "Keyword"],
[3, 8, 0, "Keyword"],
[4, 12, 0, "Identifier"],
[5, 8, 0, "Punctuator"],
[6, 4, 0, "Punctuator"]
])
},
{
code: unIndent`
class C {
static {
{
bar;
}
}
}
`,
output: unIndent`
class C {
static {
{
bar;
}
}
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 },
errors: expectedErrors([
[2, 4, 0, "Keyword"],
[3, 8, 0, "Punctuator"],
[4, 12, 0, "Identifier"],
[5, 8, 0, "Punctuator"],
[6, 4, 0, "Punctuator"]
])
},
{
code: unIndent`
class C {
static {}
static {
}
static
{
}
}
`,
output: unIndent`
class C {
static {}
static {
}
static
{
}
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 },
errors: expectedErrors([
[2, 4, 0, "Keyword"],
[4, 4, 0, "Keyword"],
[5, 4, 0, "Punctuator"],
[7, 4, 0, "Keyword"],
[8, 4, 0, "Punctuator"],
[9, 4, 0, "Punctuator"]
])
},
{
code: unIndent`
class C {
static {
foo;
}
static {
bar;
}
}
`,
output: unIndent`
class C {
static {
foo;
}
static {
bar;
}
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 },
errors: expectedErrors([
[3, 4, 0, "Keyword"],
[4, 8, 4, "Identifier"],
[5, 4, 0, "Punctuator"],
[7, 4, 0, "Keyword"],
[8, 8, 4, "Identifier"],
[9, 4, 0, "Punctuator"]
])
},
{
code: unIndent`
class C {
x = 1;
static {
foo;
}
y = 2;
}
`,
output: unIndent`
class C {
x = 1;
static {
foo;
}
y = 2;
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 },
errors: expectedErrors([
[3, 4, 0, "Identifier"],
[5, 4, 0, "Keyword"],
[6, 8, 4, "Identifier"],
[7, 4, 0, "Punctuator"],
[9, 4, 0, "Identifier"]
])
},
{
code: unIndent`
class C {
method1(param) {
foo;
}
static {
bar;
}
method2(param) {
foo;
}
}
`,
output: unIndent`
class C {
method1(param) {
foo;
}
static {
bar;
}
method2(param) {
foo;
}
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 },
errors: expectedErrors([
[3, 4, 0, "Identifier"],
[4, 8, 4, "Identifier"],
[5, 4, 0, "Punctuator"],
[7, 4, 0, "Keyword"],
[8, 8, 4, "Identifier"],
[9, 4, 0, "Punctuator"],
[11, 4, 0, "Identifier"],
[12, 8, 4, "Identifier"],
[13, 4, 0, "Punctuator"]
])
},
{
code: unIndent`
function f() {
class C {
static {
foo();
bar();
}
}
}
`,
output: unIndent`
function f() {
class C {
static {
foo();
bar();
}
}
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 },
errors: expectedErrors([
[2, 4, 0, "Keyword"],
[3, 8, 0, "Keyword"],
[4, 12, 0, "Identifier"],
[5, 12, 0, "Identifier"],
[6, 8, 0, "Punctuator"],
[7, 4, 0, "Punctuator"]
])
},
{
code: unIndent`
class C {
method() {
foo;
}
static {
bar;
}
}
`,
output: unIndent`
class C {
method() {
foo;
}
static {
bar;
}
}
`,
options: [4, { FunctionExpression: { body: 2 }, StaticBlock: { body: 2 } }],
parserOptions: { ecmaVersion: 2022 },
errors: expectedErrors([
[2, 4, 0, "Identifier"],
[3, 12, 0, "Identifier"],
[4, 4, 0, "Punctuator"],
[5, 4, 0, "Keyword"],
[6, 12, 0, "Identifier"],
[7, 4, 0, "Punctuator"]
])
}
]
});
| DavidAnson/eslint | tests/lib/rules/indent.js | JavaScript | mit | 328,533 |
<?php
/**
* Dns
*
* êëàññ DNS
*/
class Dns extends Model {
private $ref_domain;
private $ref_ns;
} | AlmazKo/Brill | Brill/Modules/Settings/Models/Dns.php | PHP | mit | 113 |
<div role="columnheader"
ng-class="{ 'sortable': sortable }"
ui-grid-one-bind-aria-labelledby-grid="col.uid + '-header-text ' + col.uid + '-sortdir-text'"
aria-sort="{{col.sort.direction == asc ? 'ascending' : ( col.sort.direction == desc ? 'descending' : (!col.sort.direction ? 'none' : 'other'))}}">
<div role="button"
tabindex="0"
class="ui-grid-cell-contents ui-grid-header-cell-primary-focus"
col-index="renderIndex"
title="TOOLTIP">
<span class="ui-grid-header-cell-label"
ui-grid-one-bind-id-grid="col.uid + '-header-text'"
uib-tooltip="{{col.headerTooltip(col)}}"
tooltip-placement="top"
tooltip-append-to-body="true">
{{ col.displayName }}
</span>
<span ui-grid-one-bind-id-grid="col.uid + '-sortdir-text'"
ui-grid-visible="col.sort.direction"
aria-label="{{getSortDirectionAriaLabel()}}">
<i ng-class="{ 'ui-grid-icon-up-dir': col.sort.direction == asc, 'ui-grid-icon-down-dir': col.sort.direction == desc, 'ui-grid-icon-blank': !col.sort.direction }"
title="{{col.sort.priority ? i18n.headerCell.priority + ' ' + col.sort.priority : null}}"
aria-hidden="true">
</i>
<sub
class="ui-grid-sort-priority-number">
{{col.sort.priority}}
</sub>
</span>
</div>
<div role="button"
tabindex="0"
ui-grid-one-bind-id-grid="col.uid + '-menu-button'" class="ui-grid-column-menu-button"
ng-if="grid.options.enableColumnMenus && !col.isRowHeader && col.colDef.enableColumnMenu !== false"
ng-click="toggleMenu($event)"
ng-class="{'ui-grid-column-menu-button-last-col': isLastCol}"
ui-grid-one-bind-aria-label="i18n.headerCell.aria.columnMenuButtonLabel"
aria-haspopup="true">
<i class="ui-grid-icon-angle-down"
aria-hidden="true"> </i>
</div>
<div ui-grid-filter></div>
</div>
| genome/civic-client | src/app/views/events/variantGroups/summary/variantGridTooltipHeader.tpl.html | HTML | mit | 1,931 |
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace spec\Sylius\Bundle\MoneyBundle\Templating\Helper;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
use Sylius\Bundle\MoneyBundle\Templating\Helper\ConvertMoneyHelper;
use Sylius\Bundle\MoneyBundle\Templating\Helper\ConvertMoneyHelperInterface;
use Sylius\Component\Currency\Converter\CurrencyConverterInterface;
use Symfony\Component\Templating\Helper\Helper;
/**
* @author Paweł Jędrzejewski <pawel@sylius.org>
* @author Łukasz Chruściel <lukasz.chrusciel@lakion.com>
*/
final class ConvertMoneyHelperSpec extends ObjectBehavior
{
function let(CurrencyConverterInterface $currencyConverter)
{
$this->beConstructedWith($currencyConverter);
}
function it_is_initializable()
{
$this->shouldHaveType(ConvertMoneyHelper::class);
}
function it_is_a_templating_helper()
{
$this->shouldHaveType(Helper::class);
}
function it_is_a_convert_money_price_helper()
{
$this->shouldImplement(ConvertMoneyHelperInterface::class);
}
function it_converts_and_formats_money_using_default_locale_if_not_given(
CurrencyConverterInterface $currencyConverter
) {
$currencyConverter->convert(500, 'USD', 'CAD')->willReturn(250);
$this->convertAmount(500, 'USD', 'CAD')->shouldReturn(250);
}
}
| psren/Sylius | src/Sylius/Bundle/MoneyBundle/spec/Templating/Helper/ConvertMoneyHelperSpec.php | PHP | mit | 1,557 |
app.service('programmingLandingService', function ($http) {
//get user profile information
this.getGymObj = function (gymId) {
return $http({
method: 'GET',
url: 'api/gyms/pathway/' + gymId,
})
.then(function (response) {
return response.data;
});
};
this.getStages = function (pathwayObj) {
return $http({
method: 'POST',
url: 'api/gyms/stage',
data: pathwayObj
})
.then(function (response) {
return response.data;
});
};
this.getEvals = function (stageObj) {
return $http({
method: 'POST',
url: 'api/gyms/evaluations',
data: stageObj
})
.then(function (response) {
return response.data;
});
};
this.getEvalDetails = function (evalObj) {
return $http({
method: 'POST',
url: '/api/gyms/evaluation/specifics',
data: evalObj
})
.then(function (response) {
return response.data;
});
};
this.addEvalObj = function (evalObj) {
return $http({
method: 'POST',
url: '/api/gyms/add/evaluation',
data: evalObj
})
.then(function (response) {
return response;
});
};
this.editEvaluation = function (evalObj) {
return $http({
method: 'PUT',
url: '/api/gyms/edit/evaluation',
data: evalObj
})
.then(function (response) {
return response.data;
});
};
this.deleteEval = function (evalObj) {
return $http({
method: 'PUT',
url: '/api/gyms/removeById',
data: evalObj
})
.then(function (response) {
return response;
});
};
});
| blundercode/logosShit | client/app/admin/gym/programming/programmingLanding/programmingLandingService.js | JavaScript | mit | 1,973 |
"""tests/test_output_format.py.
Tests the output format handlers included with Hug
Copyright (C) 2015 Timothy Edmund Crosley
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.
"""
import pytest
import hug
from collections import namedtuple
from datetime import datetime
def test_text():
'''Ensure that it's possible to output a Hug API method as text'''
hug.output_format.text("Hello World!") == "Hello World!"
hug.output_format.text(str(1)) == "1"
def test_json():
'''Ensure that it's possible to output a Hug API method as JSON'''
now = datetime.now()
test_data = {'text': 'text', 'datetime': now, 'bytes': b'bytes'}
output = hug.output_format.json(test_data).decode('utf8')
assert 'text' in output
assert 'bytes' in output
assert now.isoformat() in output
class NewObject(object):
pass
test_data['non_serializable'] = NewObject()
with pytest.raises(TypeError):
hug.output_format.json(test_data).decode('utf8')
class NamedTupleObject(namedtuple('BaseTuple', ('name', 'value'))):
pass
data = NamedTupleObject('name', 'value')
converted = hug.input_format.json(hug.output_format.json(data).decode('utf8'))
assert converted == {'name': 'name', 'value': 'value'}
def test_pretty_json():
'''Ensure that it's possible to output a Hug API method as prettified and indented JSON'''
test_data = {'text': 'text'}
assert hug.output_format.pretty_json(test_data).decode('utf8') == ('{\n'
' "text": "text"\n'
'}')
def test_json_camelcase():
'''Ensure that it's possible to output a Hug API method as camelCased JSON'''
test_data = {'under_score': {'values_can': 'Be Converted'}}
output = hug.output_format.json_camelcase(test_data).decode('utf8')
assert 'underScore' in output
assert 'valuesCan' in output
assert 'Be Converted' in output
| janusnic/hug | tests/test_output_format.py | Python | mit | 2,987 |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.AzureStack.Management.Backup.Admin
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Serialization;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
/// <summary>
/// Backup Admin Client
/// </summary>
public partial class BackupAdminClient : ServiceClient<BackupAdminClient>, IBackupAdminClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Subscription credentials that uniquely identify Microsoft Azure
/// subscription. The subscription ID forms part of the URI for every service
/// call.
/// </summary>
public string SubscriptionId { get; set; }
/// <summary>
/// Client API version.
/// </summary>
public string ApiVersion { get; private set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IOperations.
/// </summary>
public virtual IOperations Operations { get; private set; }
/// <summary>
/// Gets the IBackupLocationsOperations.
/// </summary>
public virtual IBackupLocationsOperations BackupLocations { get; private set; }
/// <summary>
/// Gets the IBackupsOperations.
/// </summary>
public virtual IBackupsOperations Backups { get; private set; }
/// <summary>
/// Initializes a new instance of the BackupAdminClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected BackupAdminClient(params DelegatingHandler[] handlers) : base(handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the BackupAdminClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected BackupAdminClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the BackupAdminClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected BackupAdminClient(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the BackupAdminClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected BackupAdminClient(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the BackupAdminClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public BackupAdminClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the BackupAdminClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public BackupAdminClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the BackupAdminClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public BackupAdminClient(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the BackupAdminClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public BackupAdminClient(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
Operations = new Operations(this);
BackupLocations = new BackupLocationsOperations(this);
Backups = new BackupsOperations(this);
BaseUri = new System.Uri("https://adminmanagement.local.azurestack.external");
ApiVersion = "2016-05-01";
AcceptLanguage = "en-US";
LongRunningOperationRetryTimeout = 30;
GenerateClientRequestId = true;
SerializationSettings = new JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
SerializationSettings.Converters.Add(new TransformationJsonConverter());
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
CustomInitialize();
DeserializationSettings.Converters.Add(new TransformationJsonConverter());
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
}
}
| yaakoviyun/azure-sdk-for-net | src/AzureStack/Admin/BackupAdmin/Backup.Admin/Generated/BackupAdminClient.cs | C# | mit | 13,055 |
// This file implements the IProvideTaskPage Interface for Python.
// Generated by makegw.py
#include "PyIProvideTaskPage.h"
#include "PyWinObjects.h"
// @doc - This file contains autoduck documentation
// ---------------------------------------------------
//
// Interface Implementation
PyIProvideTaskPage::PyIProvideTaskPage(IUnknown *pdisp):
PyIUnknown(pdisp)
{
ob_type = &type;
}
PyIProvideTaskPage::~PyIProvideTaskPage()
{
}
/* static */ IProvideTaskPage *PyIProvideTaskPage::GetI(PyObject *self)
{
return (IProvideTaskPage *)PyIUnknown::GetI(self);
}
// @pymethod |PyIProvideTaskPage|GetPage|Return a property sheet page handle for the spedified type (TASKPAGE_TASK,TASKPAGE_SCHEDULE,TASKPAGE_SETTINGS)
// @comm There's not yet anything useful that can be done with this handle - return type subject to change
PyObject *PyIProvideTaskPage::GetPage(PyObject *self, PyObject *args)
{
IProvideTaskPage *pIPTP = GetI(self);
if ( pIPTP == NULL )
return NULL;
TASKPAGE tpType;
// @pyparm int|tpType||Type of page to retreive (TASKPAGE_TASK,TASKPAGE_SCHEDULE,TASKPAGE_SETTINGS)
// @pyparm bool|PersistChanges||Indicates if changes should be saved automatically
HPROPSHEETPAGE phPage;
BOOL bPersistChanges;
if ( !PyArg_ParseTuple(args, "ii:GetPage", &tpType, &bPersistChanges))
return NULL;
HRESULT hr;
PY_INTERFACE_PRECALL;
hr = pIPTP->GetPage(tpType, bPersistChanges, &phPage);
PY_INTERFACE_POSTCALL;
if ( FAILED(hr) )
return PyCom_BuildPyException(hr, pIPTP, IID_IProvideTaskPage );
return PyWinLong_FromHANDLE(phPage);
}
// @object PyIProvideTaskPage|Description of the interface
static struct PyMethodDef PyIProvideTaskPage_methods[] =
{
{ "GetPage", PyIProvideTaskPage::GetPage, 1 }, // @pymeth GetPage|Return a property sheet page handle for the spedified type (TASKPAGE_TASK,TASKPAGE_SCHEDULE,TASKPAGE_SETTINGS)
{ NULL }
};
PyComTypeObject PyIProvideTaskPage::type("PyIProvideTaskPage",
&PyIUnknown::type,
sizeof(PyIProvideTaskPage),
PyIProvideTaskPage_methods,
GET_PYCOM_CTOR(PyIProvideTaskPage));
| DavidGuben/rcbplayspokemon | app/pywin32-220/com/win32comext/taskscheduler/src/PyIProvideTaskPage.cpp | C++ | mit | 2,049 |
module Doorkeeper
class Application < ActiveRecord::Base
self.table_name = "#{table_name_prefix}oauth_applications#{table_name_suffix}".to_sym
include ApplicationMixin
has_many :authorized_tokens, -> { where(revoked_at: nil) }, class_name: 'AccessToken'
has_many :authorized_applications, through: :authorized_tokens, source: :application
# Returns Applications associated with active (not revoked) Access Tokens
# that are owned by the specific Resource Owner.
#
# @param resource_owner [ActiveRecord::Base]
# Resource Owner model instance
#
# @return [ActiveRecord::Relation]
# Applications authorized for the Resource Owner
#
def self.authorized_for(resource_owner)
resource_access_tokens = AccessToken.active_for(resource_owner)
where(id: resource_access_tokens.select(:application_id).distinct)
end
end
end
| EasterAndJay/doorkeeper | lib/doorkeeper/orm/active_record/application.rb | Ruby | mit | 895 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NBitcoin.BuilderExtensions;
using NBitcoin.Crypto;
using NBitcoin.OpenAsset;
using NBitcoin.Policy;
using NBitcoin.Stealth;
using Builder = System.Func<NBitcoin.TransactionBuilder.TransactionBuildingContext, NBitcoin.IMoney>;
namespace NBitcoin
{
[Flags]
public enum ChangeType : int
{
All = 3,
Colored = 1,
Uncolored = 2
}
public interface ICoinSelector
{
IEnumerable<ICoin> Select(IEnumerable<ICoin> coins, IMoney target);
}
/// <summary>
/// A coin selector that selects all the coins passed by default.
/// Useful when a user wants a specific set of coins to be spent.
/// </summary>
public class AllCoinsSelector : ICoinSelector
{
public IEnumerable<ICoin> Select(IEnumerable<ICoin> coins, IMoney target)
{
return coins;
}
}
/// <summary>
/// Algorithm implemented by bitcoin core https://github.com/bitcoin/bitcoin/blob/master/src/wallet.cpp#L1276
/// Minimize the change
/// </summary>
public class DefaultCoinSelector : ICoinSelector
{
public DefaultCoinSelector()
{
}
private Random _Rand = new Random();
public DefaultCoinSelector(int seed)
{
this._Rand = new Random(seed);
}
/// <summary>
/// Select all coins belonging to same scriptPubKey together to protect privacy. (Default: true)
/// </summary>
public bool GroupByScriptPubKey
{
get; set;
} = true;
#region ICoinSelector Members
public IEnumerable<ICoin> Select(IEnumerable<ICoin> coins, IMoney target)
{
IMoney zero = target.Sub(target);
var result = new List<ICoin>();
IMoney total = zero;
if (target.CompareTo(zero) == 0)
return result;
var orderedCoinGroups = coins.GroupBy(c => this.GroupByScriptPubKey ? c.TxOut.ScriptPubKey : new Key().ScriptPubKey)
.Select(scriptPubKeyCoins => new
{
Amount = scriptPubKeyCoins.Select(c => c.Amount).Sum(zero),
Coins = scriptPubKeyCoins.ToList()
}).OrderBy(c => c.Amount);
var targetCoin = orderedCoinGroups
.FirstOrDefault(c => c.Amount.CompareTo(target) == 0);
//If any of your UTXO² matches the Target¹ it will be used.
if (targetCoin != null)
return targetCoin.Coins;
foreach (var coinGroup in orderedCoinGroups)
{
if (coinGroup.Amount.CompareTo(target) == -1 && total.CompareTo(target) == -1)
{
total = total.Add(coinGroup.Amount);
result.AddRange(coinGroup.Coins);
//If the "sum of all your UTXO smaller than the Target" happens to match the Target, they will be used. (This is the case if you sweep a complete wallet.)
if (total.CompareTo(target) == 0)
return result;
}
else
{
if (total.CompareTo(target) == -1 && coinGroup.Amount.CompareTo(target) == 1)
{
//If the "sum of all your UTXO smaller than the Target" doesn't surpass the target, the smallest UTXO greater than your Target will be used.
return coinGroup.Coins;
}
else
{
// Else Bitcoin Core does 1000 rounds of randomly combining unspent transaction outputs until their sum is greater than or equal to the Target. If it happens to find an exact match, it stops early and uses that.
// Otherwise it finally settles for the minimum of
// the smallest UTXO greater than the Target
// the smallest combination of UTXO it discovered in Step 4.
var allCoins = orderedCoinGroups.ToArray();
IMoney minTotal = null;
for (int _ = 0; _ < 1000; _++)
{
var selection = new List<ICoin>();
Utils.Shuffle(allCoins, this._Rand);
total = zero;
for (int i = 0; i < allCoins.Length; i++)
{
selection.AddRange(allCoins[i].Coins);
total = total.Add(allCoins[i].Amount);
if (total.CompareTo(target) == 0)
return selection;
if (total.CompareTo(target) == 1)
break;
}
if (total.CompareTo(target) == -1)
{
return null;
}
if (minTotal == null || total.CompareTo(minTotal) == -1)
{
minTotal = total;
result = selection;
}
}
if (minTotal != null)
{
total = minTotal;
}
break;
}
}
}
if (total.CompareTo(target) == -1)
return null;
// optimize the set of used coins, removing unnecessary small inputs
List<ICoin> sortedUsedCoins = result.OrderBy(c => c.Amount).ToList();
IMoney excess = total.Sub(target);
for (int i = 0; i < sortedUsedCoins.Count; i++)
{
// if the smallest coin in the set is smaller or equal to the difference between the excess of
// the total and its amount, we can safely remove it
ICoin coin = sortedUsedCoins[i];
if (coin.Amount.CompareTo(excess) <= 0)
{
result.Remove(coin);
excess = excess.Sub(coin.Amount);
}
if (excess.CompareTo(zero) <= 0)
break;
}
return result;
}
#endregion
}
/// <summary>
/// Exception thrown when not enough funds are present for verifying or building a transaction
/// </summary>
public class NotEnoughFundsException : Exception
{
public NotEnoughFundsException(string message, string group, IMoney missing)
: base(BuildMessage(message, group, missing))
{
this.Missing = missing;
this.Group = group;
}
private static string BuildMessage(string message, string group, IMoney missing)
{
var builder = new StringBuilder();
builder.Append(message);
if (group != null)
builder.Append(" in group " + group);
if (missing != null)
builder.Append(" with missing amount " + missing);
return builder.ToString();
}
public NotEnoughFundsException(string message, Exception inner)
: base(message, inner)
{
}
/// <summary>
/// The group name who is missing the funds
/// </summary>
public string Group
{
get;
set;
}
/// <summary>
/// Amount of Money missing
/// </summary>
public IMoney Missing
{
get;
set;
}
}
/// <summary>
/// A class for building and signing all sort of transactions easily (http://www.codeproject.com/Articles/835098/NBitcoin-Build-Them-All)
/// </summary>
public class TransactionBuilder
{
internal class TransactionBuilderSigner : ISigner
{
private ICoin coin;
private SigHash sigHash;
private IndexedTxIn txIn;
private TransactionBuilder builder;
public TransactionBuilderSigner(TransactionBuilder builder, ICoin coin, SigHash sigHash, IndexedTxIn txIn)
{
this.builder = builder;
this.coin = coin;
this.sigHash = sigHash;
this.txIn = txIn;
}
#region ISigner Members
public TransactionSignature Sign(Key key)
{
return this.txIn.Sign(this.builder.Network, key, this.coin, this.sigHash);
}
#endregion
}
internal class TransactionBuilderKeyRepository : IKeyRepository
{
private TransactionSigningContext _Ctx;
private TransactionBuilder _TxBuilder;
public TransactionBuilderKeyRepository(TransactionBuilder txBuilder, TransactionSigningContext ctx)
{
this._Ctx = ctx;
this._TxBuilder = txBuilder;
}
#region IKeyRepository Members
public Key FindKey(Script scriptPubkey)
{
return this._TxBuilder.FindKey(this._Ctx, scriptPubkey);
}
#endregion
}
private class KnownSignatureSigner : ISigner, IKeyRepository
{
private ICoin coin;
private SigHash sigHash;
private IndexedTxIn txIn;
private List<Tuple<PubKey, ECDSASignature>> _KnownSignatures;
private Dictionary<KeyId, ECDSASignature> _VerifiedSignatures = new Dictionary<KeyId, ECDSASignature>();
private Dictionary<uint256, PubKey> _DummyToRealKey = new Dictionary<uint256, PubKey>();
private TransactionBuilder builder;
public KnownSignatureSigner(TransactionBuilder builder, List<Tuple<PubKey, ECDSASignature>> _KnownSignatures, ICoin coin, SigHash sigHash, IndexedTxIn txIn)
{
this.builder = builder;
this._KnownSignatures = _KnownSignatures;
this.coin = coin;
this.sigHash = sigHash;
this.txIn = txIn;
}
public Key FindKey(Script scriptPubKey)
{
foreach (Tuple<PubKey, ECDSASignature> tv in this._KnownSignatures.Where(tv => IsCompatibleKey(tv.Item1, scriptPubKey)))
{
uint256 hash = this.txIn.GetSignatureHash(this.builder.Network, this.coin, this.sigHash);
if (tv.Item1.Verify(hash, tv.Item2))
{
var key = new Key();
this._DummyToRealKey.Add(Hashes.Hash256(key.PubKey.ToBytes()), tv.Item1);
this._VerifiedSignatures.AddOrReplace(key.PubKey.Hash, tv.Item2);
return key;
}
}
return null;
}
public Script ReplaceDummyKeys(Script script)
{
List<Op> ops = script.ToOps().ToList();
var result = new List<Op>();
foreach (Op op in ops)
{
uint256 h = Hashes.Hash256(op.PushData);
PubKey real;
if (this._DummyToRealKey.TryGetValue(h, out real))
result.Add(Op.GetPushOp(real.ToBytes()));
else
result.Add(op);
}
return new Script(result.ToArray());
}
public TransactionSignature Sign(Key key)
{
return new TransactionSignature(this._VerifiedSignatures[key.PubKey.Hash], this.sigHash);
}
}
internal class TransactionSigningContext
{
public TransactionSigningContext(TransactionBuilder builder, Transaction transaction)
{
this.Builder = builder;
this.Transaction = transaction;
}
public Transaction Transaction
{
get;
set;
}
public TransactionBuilder Builder
{
get;
set;
}
private readonly List<Key> _AdditionalKeys = new List<Key>();
public List<Key> AdditionalKeys
{
get
{
return this._AdditionalKeys;
}
}
public SigHash SigHash
{
get;
set;
}
}
internal class TransactionBuildingContext
{
public TransactionBuildingContext(TransactionBuilder builder)
{
this.Builder = builder;
this.Transaction = builder.Network.CreateTransaction();
this.AdditionalFees = Money.Zero;
}
public BuilderGroup Group
{
get;
set;
}
private readonly List<ICoin> _ConsumedCoins = new List<ICoin>();
public List<ICoin> ConsumedCoins
{
get
{
return this._ConsumedCoins;
}
}
public TransactionBuilder Builder
{
get;
set;
}
public Transaction Transaction
{
get;
set;
}
public Money AdditionalFees
{
get;
set;
}
private readonly List<Builder> _AdditionalBuilders = new List<Builder>();
public List<Builder> AdditionalBuilders
{
get
{
return this._AdditionalBuilders;
}
}
private ColorMarker _Marker;
public ColorMarker GetColorMarker(bool issuance)
{
if (this._Marker == null) this._Marker = new ColorMarker();
if (!issuance)
EnsureMarkerInserted();
return this._Marker;
}
private TxOut EnsureMarkerInserted()
{
uint position;
TxIn dummy = this.Transaction.AddInput(new TxIn(new OutPoint(new uint256(1), 0))); //Since a transaction without input will be considered without marker, insert a dummy
try
{
if (ColorMarker.Get(this.Transaction, out position) != null)
return this.Transaction.Outputs[position];
}
finally
{
this.Transaction.Inputs.Remove(dummy);
}
TxOut txout = this.Transaction.AddOutput(new TxOut()
{
ScriptPubKey = new ColorMarker().GetScript()
});
txout.Value = Money.Zero;
return txout;
}
public void Finish()
{
if (this._Marker != null)
{
TxOut txout = EnsureMarkerInserted();
txout.ScriptPubKey = this._Marker.GetScript();
}
}
public IssuanceCoin IssuanceCoin
{
get;
set;
}
public IMoney ChangeAmount
{
get;
set;
}
public TransactionBuildingContext CreateMemento()
{
var memento = new TransactionBuildingContext(this.Builder);
memento.RestoreMemento(this);
return memento;
}
public void RestoreMemento(TransactionBuildingContext memento)
{
this._Marker = memento._Marker == null ? null : new ColorMarker(memento._Marker.GetScript());
this.Transaction = memento.Builder.Network.CreateTransaction(memento.Transaction.ToBytes());
this.AdditionalFees = memento.AdditionalFees;
}
public bool NonFinalSequenceSet
{
get;
set;
}
public IMoney CoverOnly
{
get;
set;
}
public IMoney Dust
{
get;
set;
}
public ChangeType ChangeType
{
get;
set;
}
}
internal class BuilderGroup
{
private TransactionBuilder _Parent;
public BuilderGroup(TransactionBuilder parent)
{
this._Parent = parent;
this.FeeWeight = 1.0m;
this.Builders.Add(SetChange);
}
private IMoney SetChange(TransactionBuildingContext ctx)
{
var changeAmount = (Money)ctx.ChangeAmount;
if (changeAmount.Satoshi == 0)
return Money.Zero;
ctx.Transaction.AddOutput(new TxOut(changeAmount, ctx.Group.ChangeScript[(int)ChangeType.Uncolored]));
return changeAmount;
}
internal List<Builder> Builders = new List<Builder>();
internal Dictionary<OutPoint, ICoin> Coins = new Dictionary<OutPoint, ICoin>();
internal List<Builder> IssuanceBuilders = new List<Builder>();
internal Dictionary<AssetId, List<Builder>> BuildersByAsset = new Dictionary<AssetId, List<Builder>>();
internal Script[] ChangeScript = new Script[3];
internal void Shuffle()
{
Shuffle(this.Builders);
foreach (KeyValuePair<AssetId, List<Builder>> builders in this.BuildersByAsset)
Shuffle(builders.Value);
Shuffle(this.IssuanceBuilders);
}
private void Shuffle(List<Builder> builders)
{
Utils.Shuffle(builders, this._Parent._Rand);
}
public Money CoverOnly
{
get;
set;
}
public string Name
{
get;
set;
}
public decimal FeeWeight
{
get;
set;
}
}
private List<BuilderGroup> _BuilderGroups = new List<BuilderGroup>();
private BuilderGroup _CurrentGroup = null;
internal BuilderGroup CurrentGroup
{
get
{
if (this._CurrentGroup == null)
{
this._CurrentGroup = new BuilderGroup(this);
this._BuilderGroups.Add(this._CurrentGroup);
}
return this._CurrentGroup;
}
}
public TransactionBuilder(Network network)
{
this.Network = network;
this._Rand = new Random();
this.CoinSelector = new DefaultCoinSelector();
this.StandardTransactionPolicy = new StandardTransactionPolicy(this.Network);
this.DustPrevention = true;
InitExtensions();
}
private void InitExtensions()
{
this.Extensions.Add(new P2PKHBuilderExtension());
this.Extensions.Add(new P2MultiSigBuilderExtension());
this.Extensions.Add(new P2PKBuilderExtension());
this.Extensions.Add(new OPTrueExtension());
}
internal Random _Rand;
public TransactionBuilder(int seed, Network network)
{
this.Network = network;
this._Rand = new Random(seed);
this.CoinSelector = new DefaultCoinSelector(seed);
this.StandardTransactionPolicy = new StandardTransactionPolicy(this.Network);
this.DustPrevention = true;
InitExtensions();
}
public ICoinSelector CoinSelector
{
get;
set;
}
/// <summary>
/// This field should be mandatory in the constructor.
/// </summary>
public Network Network
{
get;
private set;
}
/// <summary>
/// Will transform transfers below Dust, so the transaction get correctly relayed by the network.
/// If true, it will remove any TxOut below Dust, so the transaction get correctly relayed by the network. (Default: true)
/// </summary>
public bool DustPrevention
{
get;
set;
}
/// <summary>
/// If true, the TransactionBuilder will not select coins whose fee to spend is higher than its value. (Default: true)
/// The cost of spending a coin is based on the <see cref="FilterUneconomicalCoinsRate"/>.
/// </summary>
public bool FilterUneconomicalCoins { get; set; } = true;
/// <summary>
/// If <see cref="FilterUneconomicalCoins"/> is true, this rate is used to know if an output is economical.
/// This property is set automatically when calling <see cref="SendEstimatedFees(FeeRate)"/> or <see cref="SendEstimatedFeesSplit(FeeRate)"/>.
/// </summary>
public FeeRate FilterUneconomicalCoinsRate
{
get; set;
}
/// <summary>
/// A callback used by the TransactionBuilder when it does not find the coin for an input
/// </summary>
public Func<OutPoint, ICoin> CoinFinder
{
get;
set;
}
/// <summary>
/// A callback used by the TransactionBuilder when it does not find the key for a scriptPubKey
/// </summary>
public Func<Script, Key> KeyFinder
{
get;
set;
}
private LockTime? _LockTime;
public TransactionBuilder SetLockTime(LockTime lockTime)
{
this._LockTime = lockTime;
return this;
}
private uint? _TimeStamp;
public TransactionBuilder SetTimeStamp(uint timeStamp)
{
this._TimeStamp = timeStamp;
return this;
}
private List<Key> _Keys = new List<Key>();
public TransactionBuilder AddKeys(params ISecret[] keys)
{
AddKeys(keys.Select(k => k.PrivateKey).ToArray());
return this;
}
public TransactionBuilder AddKeys(params Key[] keys)
{
this._Keys.AddRange(keys);
foreach (Key k in keys)
{
AddKnownRedeems(k.PubKey.ScriptPubKey);
AddKnownRedeems(k.PubKey.WitHash.ScriptPubKey);
AddKnownRedeems(k.PubKey.Hash.ScriptPubKey);
}
return this;
}
public TransactionBuilder AddKnownSignature(PubKey pubKey, TransactionSignature signature)
{
if (pubKey == null)
throw new ArgumentNullException("pubKey");
if (signature == null)
throw new ArgumentNullException("signature");
this._KnownSignatures.Add(Tuple.Create(pubKey, signature.Signature));
return this;
}
public TransactionBuilder AddKnownSignature(PubKey pubKey, ECDSASignature signature)
{
if (pubKey == null)
throw new ArgumentNullException("pubKey");
if (signature == null)
throw new ArgumentNullException("signature");
this._KnownSignatures.Add(Tuple.Create(pubKey, signature));
return this;
}
public TransactionBuilder AddCoins(params ICoin[] coins)
{
return AddCoins((IEnumerable<ICoin>)coins);
}
public TransactionBuilder AddCoins(IEnumerable<ICoin> coins)
{
foreach (ICoin coin in coins)
{
this.CurrentGroup.Coins.AddOrReplace(coin.Outpoint, coin);
}
return this;
}
/// <summary>
/// Set the name of this group (group are separated by call to Then())
/// </summary>
/// <param name="groupName">Name of the group</param>
/// <returns></returns>
public TransactionBuilder SetGroupName(string groupName)
{
this.CurrentGroup.Name = groupName;
return this;
}
/// <summary>
/// Send bitcoins to a destination
/// </summary>
/// <param name="destination">The destination</param>
/// <param name="amount">The amount</param>
/// <returns></returns>
public TransactionBuilder Send(IDestination destination, Money amount)
{
return Send(destination.ScriptPubKey, amount);
}
private readonly static TxNullDataTemplate _OpReturnTemplate = new TxNullDataTemplate(1024 * 1024);
/// <summary>
/// Send bitcoins to a destination
/// </summary>
/// <param name="scriptPubKey">The destination</param>
/// <param name="amount">The amount</param>
/// <returns></returns>
public TransactionBuilder Send(Script scriptPubKey, Money amount)
{
if (amount < Money.Zero)
throw new ArgumentOutOfRangeException("amount", "amount can't be negative");
this._LastSendBuilder = null; //If the amount is dust, we don't want the fee to be paid by the previous Send
if (this.DustPrevention && amount < GetDust(scriptPubKey) && !_OpReturnTemplate.CheckScriptPubKey(scriptPubKey))
{
SendFees(amount);
return this;
}
var builder = new SendBuilder(new TxOut(amount, scriptPubKey));
this.CurrentGroup.Builders.Add(builder.Build);
this._LastSendBuilder = builder;
return this;
}
private SendBuilder _LastSendBuilder;
private SendBuilder _SubstractFeeBuilder;
private class SendBuilder
{
internal TxOut _TxOut;
public SendBuilder(TxOut txout)
{
this._TxOut = txout;
}
public Money Build(TransactionBuildingContext ctx)
{
ctx.Transaction.Outputs.Add(this._TxOut);
return this._TxOut.Value;
}
}
/// <summary>
/// Will subtract fees from the previous TxOut added by the last TransactionBuidler.Send() call
/// </summary>
/// <returns></returns>
public TransactionBuilder SubtractFees()
{
if (this._LastSendBuilder == null)
throw new InvalidOperationException("No call to TransactionBuilder.Send has been done which can support the fees");
this._SubstractFeeBuilder = this._LastSendBuilder;
return this;
}
/// <summary>
/// Send a money amount to the destination
/// </summary>
/// <param name="destination">The destination</param>
/// <param name="amount">The amount (supported : Money, AssetMoney, MoneyBag)</param>
/// <returns></returns>
/// <exception cref="System.NotSupportedException">The coin type is not supported</exception>
public TransactionBuilder Send(IDestination destination, IMoney amount)
{
return Send(destination.ScriptPubKey, amount);
}
/// <summary>
/// Send a money amount to the destination
/// </summary>
/// <param name="destination">The destination</param>
/// <param name="amount">The amount (supported : Money, AssetMoney, MoneyBag)</param>
/// <returns></returns>
/// <exception cref="NotSupportedException">The coin type is not supported</exception>
public TransactionBuilder Send(Script scriptPubKey, IMoney amount)
{
var bag = amount as MoneyBag;
if (bag != null)
{
foreach (IMoney money in bag)
Send(scriptPubKey, amount);
return this;
}
var coinAmount = amount as Money;
if (coinAmount != null)
return Send(scriptPubKey, coinAmount);
var assetAmount = amount as AssetMoney;
if (assetAmount != null)
return SendAsset(scriptPubKey, assetAmount);
throw new NotSupportedException("Type of Money not supported");
}
/// <summary>
/// Send assets (Open Asset) to a destination
/// </summary>
/// <param name="destination">The destination</param>
/// <param name="asset">The asset and amount</param>
/// <returns></returns>
public TransactionBuilder SendAsset(IDestination destination, AssetMoney asset)
{
return SendAsset(destination.ScriptPubKey, asset);
}
/// <summary>
/// Send assets (Open Asset) to a destination
/// </summary>
/// <param name="destination">The destination</param>
/// <param name="asset">The asset and amount</param>
/// <returns></returns>
public TransactionBuilder SendAsset(IDestination destination, AssetId assetId, ulong quantity)
{
return SendAsset(destination, new AssetMoney(assetId, quantity));
}
public TransactionBuilder Shuffle()
{
Utils.Shuffle(this._BuilderGroups, this._Rand);
foreach (BuilderGroup group in this._BuilderGroups)
group.Shuffle();
return this;
}
private IMoney SetColoredChange(TransactionBuildingContext ctx)
{
var changeAmount = (AssetMoney)ctx.ChangeAmount;
if (changeAmount.Quantity == 0)
return changeAmount;
ColorMarker marker = ctx.GetColorMarker(false);
Script script = ctx.Group.ChangeScript[(int)ChangeType.Colored];
TxOut txout = ctx.Transaction.AddOutput(new TxOut(GetDust(script), script));
marker.SetQuantity(ctx.Transaction.Outputs.Count - 2, changeAmount.Quantity);
ctx.AdditionalFees += txout.Value;
return changeAmount;
}
public TransactionBuilder SendAsset(Script scriptPubKey, AssetId assetId, ulong assetQuantity)
{
return SendAsset(scriptPubKey, new AssetMoney(assetId, assetQuantity));
}
public TransactionBuilder SendAsset(Script scriptPubKey, AssetMoney asset)
{
if (asset.Quantity < 0)
throw new ArgumentOutOfRangeException("asset", "Asset amount can't be negative");
if (asset.Quantity == 0)
return this;
AssertOpReturn("Colored Coin");
List<Builder> builders = this.CurrentGroup.BuildersByAsset.TryGet(asset.Id);
if (builders == null)
{
builders = new List<Builder>();
this.CurrentGroup.BuildersByAsset.Add(asset.Id, builders);
builders.Add(SetColoredChange);
}
builders.Add(ctx =>
{
ColorMarker marker = ctx.GetColorMarker(false);
TxOut txout = ctx.Transaction.AddOutput(new TxOut(GetDust(scriptPubKey), scriptPubKey));
marker.SetQuantity(ctx.Transaction.Outputs.Count - 2, asset.Quantity);
ctx.AdditionalFees += txout.Value;
return asset;
});
return this;
}
private Money GetDust()
{
return GetDust(new Script(new byte[25]));
}
private Money GetDust(Script script)
{
if (this.StandardTransactionPolicy == null || this.StandardTransactionPolicy.MinRelayTxFee == null)
return Money.Zero;
return new TxOut(Money.Zero, script).GetDustThreshold(this.StandardTransactionPolicy.MinRelayTxFee);
}
/// <summary>
/// Set transaction policy fluently
/// </summary>
/// <param name="policy">The policy</param>
/// <returns>this</returns>
public TransactionBuilder SetTransactionPolicy(StandardTransactionPolicy policy)
{
this.StandardTransactionPolicy = policy;
return this;
}
public StandardTransactionPolicy StandardTransactionPolicy
{
get;
set;
}
private string _OpReturnUser;
private void AssertOpReturn(string name)
{
if (this._OpReturnUser == null)
{
this._OpReturnUser = name;
}
else
{
if (this._OpReturnUser != name)
throw new InvalidOperationException("Op return already used for " + this._OpReturnUser);
}
}
public TransactionBuilder Send(BitcoinStealthAddress address, Money amount, Key ephemKey = null)
{
if (amount < Money.Zero)
throw new ArgumentOutOfRangeException("amount", "amount can't be negative");
if (this._OpReturnUser == null)
this._OpReturnUser = "Stealth Payment";
else
throw new InvalidOperationException("Op return already used for " + this._OpReturnUser);
this.CurrentGroup.Builders.Add(ctx =>
{
StealthPayment payment = address.CreatePayment(ephemKey);
payment.AddToTransaction(ctx.Transaction, amount);
return amount;
});
return this;
}
public TransactionBuilder IssueAsset(IDestination destination, AssetMoney asset)
{
return IssueAsset(destination.ScriptPubKey, asset);
}
private AssetId _IssuedAsset;
public TransactionBuilder IssueAsset(Script scriptPubKey, AssetMoney asset)
{
AssertOpReturn("Colored Coin");
if (this._IssuedAsset == null)
this._IssuedAsset = asset.Id;
else if (this._IssuedAsset != asset.Id)
throw new InvalidOperationException("You can issue only one asset type in a transaction");
this.CurrentGroup.IssuanceBuilders.Add(ctx =>
{
ColorMarker marker = ctx.GetColorMarker(true);
if (ctx.IssuanceCoin == null)
{
IssuanceCoin issuance = ctx.Group.Coins.Values.OfType<IssuanceCoin>().Where(i => i.AssetId == asset.Id).FirstOrDefault();
if (issuance == null)
throw new InvalidOperationException("No issuance coin for emitting asset found");
ctx.IssuanceCoin = issuance;
ctx.Transaction.Inputs.Insert(0, new TxIn(issuance.Outpoint));
ctx.AdditionalFees -= issuance.Bearer.Amount;
if (issuance.DefinitionUrl != null)
{
marker.SetMetadataUrl(issuance.DefinitionUrl);
}
}
ctx.Transaction.Outputs.Insert(0, new TxOut(GetDust(scriptPubKey), scriptPubKey));
marker.Quantities = new[] { checked((ulong)asset.Quantity) }.Concat(marker.Quantities).ToArray();
ctx.AdditionalFees += ctx.Transaction.Outputs[0].Value;
return asset;
});
return this;
}
public TransactionBuilder SendFees(Money fees)
{
if (fees == null)
throw new ArgumentNullException("fees");
this.CurrentGroup.Builders.Add(ctx => fees);
this._TotalFee += fees;
return this;
}
private Money _TotalFee = Money.Zero;
/// <summary>
/// Split the estimated fees across the several groups (separated by Then())
/// </summary>
/// <param name="feeRate"></param>
/// <returns></returns>
public TransactionBuilder SendEstimatedFees(FeeRate feeRate)
{
this.FilterUneconomicalCoinsRate = feeRate;
Money fee = EstimateFees(feeRate);
SendFees(fee);
return this;
}
/// <summary>
/// Estimate the fee needed for the transaction, and split among groups according to their fee weight
/// </summary>
/// <param name="feeRate"></param>
/// <returns></returns>
public TransactionBuilder SendEstimatedFeesSplit(FeeRate feeRate)
{
this.FilterUneconomicalCoinsRate = feeRate;
Money fee = EstimateFees(feeRate);
SendFeesSplit(fee);
return this;
}
/// <summary>
/// Send the fee splitted among groups according to their fee weight
/// </summary>
/// <param name="fees"></param>
/// <returns></returns>
public TransactionBuilder SendFeesSplit(Money fees)
{
if (fees == null)
throw new ArgumentNullException("fees");
BuilderGroup lastGroup = this.CurrentGroup; //Make sure at least one group exists
decimal totalWeight = this._BuilderGroups.Select(b => b.FeeWeight).Sum();
Money totalSent = Money.Zero;
foreach (BuilderGroup group in this._BuilderGroups)
{
Money groupFee = Money.Satoshis((group.FeeWeight / totalWeight) * fees.Satoshi);
totalSent += groupFee;
if (this._BuilderGroups.Last() == group)
{
Money leftOver = fees - totalSent;
groupFee += leftOver;
}
group.Builders.Add(ctx => groupFee);
}
return this;
}
/// <summary>
/// If using SendFeesSplit or SendEstimatedFeesSplit, determine the weight this group participate in paying the fees
/// </summary>
/// <param name="feeWeight">The weight of fee participation</param>
/// <returns></returns>
public TransactionBuilder SetFeeWeight(decimal feeWeight)
{
this.CurrentGroup.FeeWeight = feeWeight;
return this;
}
public TransactionBuilder SetChange(IDestination destination, ChangeType changeType = ChangeType.All)
{
return SetChange(destination.ScriptPubKey, changeType);
}
public TransactionBuilder SetChange(Script scriptPubKey, ChangeType changeType = ChangeType.All)
{
if ((changeType & ChangeType.Colored) != 0)
{
this.CurrentGroup.ChangeScript[(int)ChangeType.Colored] = scriptPubKey;
}
if ((changeType & ChangeType.Uncolored) != 0)
{
this.CurrentGroup.ChangeScript[(int)ChangeType.Uncolored] = scriptPubKey;
}
return this;
}
public TransactionBuilder SetCoinSelector(ICoinSelector selector)
{
if (selector == null)
throw new ArgumentNullException("selector");
this.CoinSelector = selector;
return this;
}
/// <summary>
/// Build the transaction
/// </summary>
/// <param name="sign">True if signs all inputs with the available keys</param>
/// <returns>The transaction</returns>
/// <exception cref="NBitcoin.NotEnoughFundsException">Not enough funds are available</exception>
public Transaction BuildTransaction(bool sign)
{
return BuildTransaction(sign, SigHash.All);
}
/// <summary>
/// Build the transaction
/// </summary>
/// <param name="sign">True if signs all inputs with the available keys</param>
/// <param name="sigHash">The type of signature</param>
/// <returns>The transaction</returns>
/// <exception cref="NBitcoin.NotEnoughFundsException">Not enough funds are available</exception>
public Transaction BuildTransaction(bool sign, SigHash sigHash)
{
var ctx = new TransactionBuildingContext(this);
if (this._CompletedTransaction != null)
ctx.Transaction = this.Network.CreateTransaction(this._CompletedTransaction.ToBytes());
if (this._LockTime != null)
ctx.Transaction.LockTime = this._LockTime.Value;
if (this._TimeStamp != null)
ctx.Transaction.Time = this._TimeStamp.Value;
foreach (BuilderGroup group in this._BuilderGroups)
{
ctx.Group = group;
ctx.AdditionalBuilders.Clear();
ctx.AdditionalFees = Money.Zero;
ctx.ChangeType = ChangeType.Colored;
foreach (Builder builder in group.IssuanceBuilders)
builder(ctx);
List<KeyValuePair<AssetId, List<Builder>>> buildersByAsset = group.BuildersByAsset.ToList();
foreach (KeyValuePair<AssetId, List<Builder>> builders in buildersByAsset)
{
IEnumerable<ColoredCoin> coins = group.Coins.Values.OfType<ColoredCoin>().Where(c => c.Amount.Id == builders.Key);
ctx.Dust = new AssetMoney(builders.Key);
ctx.CoverOnly = null;
ctx.ChangeAmount = new AssetMoney(builders.Key);
Money btcSpent = BuildTransaction(ctx, group, builders.Value, coins, new AssetMoney(builders.Key))
.OfType<IColoredCoin>().Select(c => c.Bearer.Amount).Sum();
ctx.AdditionalFees -= btcSpent;
}
ctx.AdditionalBuilders.Add(_ => _.AdditionalFees);
ctx.Dust = GetDust();
ctx.ChangeAmount = Money.Zero;
ctx.CoverOnly = group.CoverOnly;
ctx.ChangeType = ChangeType.Uncolored;
BuildTransaction(ctx, group, group.Builders, group.Coins.Values.OfType<Coin>().Where(IsEconomical), Money.Zero);
}
ctx.Finish();
if (sign)
{
SignTransactionInPlace(ctx.Transaction, sigHash);
}
return ctx.Transaction;
}
private bool IsEconomical(Coin c)
{
if (!this.FilterUneconomicalCoins || this.FilterUneconomicalCoinsRate == null)
return true;
int witSize = 0;
int baseSize = 0;
EstimateScriptSigSize(c, ref witSize, ref baseSize);
var vSize = witSize / this.Network.Consensus.Options.WitnessScaleFactor + baseSize;
return c.Amount >= this.FilterUneconomicalCoinsRate.GetFee(vSize);
}
private IEnumerable<ICoin> BuildTransaction(
TransactionBuildingContext ctx,
BuilderGroup group,
IEnumerable<Builder> builders,
IEnumerable<ICoin> coins,
IMoney zero)
{
TransactionBuildingContext originalCtx = ctx.CreateMemento();
Money fees = this._TotalFee + ctx.AdditionalFees;
// Replace the _SubstractFeeBuilder by another one with the fees substracts
List<Builder> builderList = builders.ToList();
for (int i = 0; i < builderList.Count; i++)
{
if (builderList[i].Target == this._SubstractFeeBuilder)
{
builderList.Remove(builderList[i]);
TxOut newTxOut = this._SubstractFeeBuilder._TxOut.Clone();
newTxOut.Value -= fees;
builderList.Insert(i, new SendBuilder(newTxOut).Build);
}
}
////////////////////////////////////////////////////////
IMoney target = builderList.Concat(ctx.AdditionalBuilders).Select(b => b(ctx)).Sum(zero);
if (ctx.CoverOnly != null)
{
target = ctx.CoverOnly.Add(ctx.ChangeAmount);
}
IEnumerable<ICoin> unconsumed = coins.Where(c => ctx.ConsumedCoins.All(cc => cc.Outpoint != c.Outpoint));
IEnumerable<ICoin> selection = this.CoinSelector.Select(unconsumed, target);
if (selection == null)
{
throw new NotEnoughFundsException("Not enough funds to cover the target",
group.Name,
target.Sub(unconsumed.Select(u => u.Amount).Sum(zero))
);
}
IMoney total = selection.Select(s => s.Amount).Sum(zero);
IMoney change = total.Sub(target);
if (change.CompareTo(zero) == -1)
{
throw new NotEnoughFundsException("Not enough funds to cover the target",
group.Name,
change.Negate()
);
}
if (change.CompareTo(ctx.Dust) == 1)
{
Script changeScript = group.ChangeScript[(int)ctx.ChangeType];
if (changeScript == null)
throw new InvalidOperationException("A change address should be specified (" + ctx.ChangeType + ")");
if (!(ctx.Dust is Money) || change.CompareTo(GetDust(changeScript)) == 1)
{
ctx.RestoreMemento(originalCtx);
ctx.ChangeAmount = change;
try
{
return BuildTransaction(ctx, group, builders, coins, zero);
}
finally
{
ctx.ChangeAmount = zero;
}
}
}
foreach (ICoin coin in selection)
{
ctx.ConsumedCoins.Add(coin);
TxIn input = ctx.Transaction.Inputs.FirstOrDefault(i => i.PrevOut == coin.Outpoint);
if (input == null)
input = ctx.Transaction.AddInput(new TxIn(coin.Outpoint));
if (this._LockTime != null && !ctx.NonFinalSequenceSet)
{
input.Sequence = 0;
ctx.NonFinalSequenceSet = true;
}
}
return selection;
}
public Transaction SignTransaction(Transaction transaction, SigHash sigHash)
{
Transaction tx = this.Network.CreateTransaction(transaction.ToBytes());
SignTransactionInPlace(tx, sigHash);
return tx;
}
public Transaction SignTransaction(Transaction transaction)
{
return SignTransaction(transaction, SigHash.All);
}
public Transaction SignTransactionInPlace(Transaction transaction)
{
return SignTransactionInPlace(transaction, SigHash.All);
}
public Transaction SignTransactionInPlace(Transaction transaction, SigHash sigHash)
{
var ctx = new TransactionSigningContext(this, transaction)
{
SigHash = sigHash
};
foreach (IndexedTxIn input in transaction.Inputs.AsIndexedInputs())
{
ICoin coin = FindSignableCoin(input);
if (coin != null)
{
Sign(ctx, coin, input);
}
}
return transaction;
}
public ICoin FindSignableCoin(IndexedTxIn txIn)
{
ICoin coin = FindCoin(txIn.PrevOut);
if (coin is IColoredCoin)
coin = ((IColoredCoin)coin).Bearer;
if (coin == null || coin is ScriptCoin || coin is StealthCoin)
return coin;
TxDestination hash = ScriptCoin.GetRedeemHash(this.Network, coin.TxOut.ScriptPubKey);
if (hash != null)
{
Script redeem = this._ScriptPubKeyToRedeem.TryGet(coin.TxOut.ScriptPubKey);
if (redeem != null && PayToWitScriptHashTemplate.Instance.CheckScriptPubKey(redeem))
redeem = this._ScriptPubKeyToRedeem.TryGet(redeem);
if (redeem == null)
{
if (hash is WitScriptId)
redeem = PayToWitScriptHashTemplate.Instance.ExtractWitScriptParameters(txIn.WitScript, (WitScriptId)hash);
if (hash is ScriptId)
{
PayToScriptHashSigParameters parameters = PayToScriptHashTemplate.Instance.ExtractScriptSigParameters(this.Network, txIn.ScriptSig, (ScriptId)hash);
if (parameters != null)
redeem = parameters.RedeemScript;
}
}
if (redeem != null)
return new ScriptCoin(coin, redeem);
}
return coin;
}
/// <summary>
/// Verify that a transaction is fully signed and have enough fees
/// </summary>
/// <param name="tx">The transaction to check</param>
/// <returns>True if no error</returns>
public bool Verify(Transaction tx)
{
TransactionPolicyError[] errors;
return Verify(tx, null as Money, out errors);
}
/// <summary>
/// Verify that a transaction is fully signed and have enough fees
/// </summary>
/// <param name="tx">The transaction to check</param>
/// <param name="expectedFees">The expected fees (more or less 10%)</param>
/// <returns>True if no error</returns>
public bool Verify(Transaction tx, Money expectedFees)
{
TransactionPolicyError[] errors;
return Verify(tx, expectedFees, out errors);
}
/// <summary>
/// Verify that a transaction is fully signed and have enough fees
/// </summary>
/// <param name="tx">The transaction to check</param>
/// <param name="expectedFeeRate">The expected fee rate</param>
/// <returns>True if no error</returns>
public bool Verify(Transaction tx, FeeRate expectedFeeRate)
{
TransactionPolicyError[] errors;
return Verify(tx, expectedFeeRate, out errors);
}
/// <summary>
/// Verify that a transaction is fully signed and have enough fees
/// </summary>
/// <param name="tx">The transaction to check</param>
/// <param name="errors">Detected errors</param>
/// <returns>True if no error</returns>
public bool Verify(Transaction tx, out TransactionPolicyError[] errors)
{
return Verify(tx, null as Money, out errors);
}
/// <summary>
/// Verify that a transaction is fully signed, have enough fees, and follow the Standard and Miner Transaction Policy rules
/// </summary>
/// <param name="tx">The transaction to check</param>
/// <param name="expectedFees">The expected fees (more or less 10%)</param>
/// <param name="errors">Detected errors</param>
/// <returns>True if no error</returns>
public bool Verify(Transaction tx, Money expectedFees, out TransactionPolicyError[] errors)
{
if (tx == null)
throw new ArgumentNullException("tx");
ICoin[] coins = tx.Inputs.Select(i => FindCoin(i.PrevOut)).Where(c => c != null).ToArray();
var exceptions = new List<TransactionPolicyError>();
TransactionPolicyError[] policyErrors = MinerTransactionPolicy.Instance.Check(tx, coins);
exceptions.AddRange(policyErrors);
policyErrors = this.StandardTransactionPolicy.Check(tx, coins);
exceptions.AddRange(policyErrors);
if (expectedFees != null)
{
Money fees = tx.GetFee(coins);
if (fees != null)
{
Money margin = Money.Zero;
if (this.DustPrevention)
margin = GetDust() * 2;
if (!fees.Almost(expectedFees, margin))
exceptions.Add(new NotEnoughFundsPolicyError("Fees different than expected", expectedFees - fees));
}
}
errors = exceptions.ToArray();
return errors.Length == 0;
}
/// <summary>
/// Verify that a transaction is fully signed and have enough fees
/// </summary>
/// <param name="tx">The transaction to check</param>
/// <param name="expectedFeeRate">The expected fee rate</param>
/// <param name="errors">Detected errors</param>
/// <returns>True if no error</returns>
public bool Verify(Transaction tx, FeeRate expectedFeeRate, out TransactionPolicyError[] errors)
{
if (tx == null)
throw new ArgumentNullException("tx");
return Verify(tx, expectedFeeRate == null ? null : expectedFeeRate.GetFee(tx, this.Network.Consensus.Options.WitnessScaleFactor), out errors);
}
/// <summary>
/// Verify that a transaction is fully signed and have enough fees
/// </summary>
/// <param name="tx">he transaction to check</param>
/// <param name="expectedFeeRate">The expected fee rate</param>
/// <returns>Detected errors</returns>
public TransactionPolicyError[] Check(Transaction tx, FeeRate expectedFeeRate)
{
return Check(tx, expectedFeeRate == null ? null : expectedFeeRate.GetFee(tx, this.Network.Consensus.Options.WitnessScaleFactor));
}
/// <summary>
/// Verify that a transaction is fully signed and have enough fees
/// </summary>
/// <param name="tx">he transaction to check</param>
/// <param name="expectedFee">The expected fee</param>
/// <returns>Detected errors</returns>
public TransactionPolicyError[] Check(Transaction tx, Money expectedFee)
{
TransactionPolicyError[] errors;
Verify(tx, expectedFee, out errors);
return errors;
}
/// <summary>
/// Verify that a transaction is fully signed and have enough fees
/// </summary>
/// <param name="tx">he transaction to check</param>
/// <returns>Detected errors</returns>
public TransactionPolicyError[] Check(Transaction tx)
{
return Check(tx, null as Money);
}
private CoinNotFoundException CoinNotFound(IndexedTxIn txIn)
{
return new CoinNotFoundException(txIn);
}
public ICoin FindCoin(OutPoint outPoint)
{
ICoin result = this._BuilderGroups.Select(c => c.Coins.TryGet(outPoint)).FirstOrDefault(r => r != null);
if (result == null && this.CoinFinder != null)
result = this.CoinFinder(outPoint);
return result;
}
/// <summary>
/// Find spent coins of a transaction
/// </summary>
/// <param name="tx">The transaction</param>
/// <returns>Array of size tx.Input.Count, if a coin is not fund, a null coin is returned.</returns>
public ICoin[] FindSpentCoins(Transaction tx)
{
return
tx
.Inputs
.Select(i => FindCoin(i.PrevOut))
.ToArray();
}
/// <summary>
/// Estimate the physical size of the transaction
/// </summary>
/// <param name="tx">The transaction to be estimated</param>
/// <returns></returns>
public int EstimateSize(Transaction tx)
{
return EstimateSize(tx, false);
}
/// <summary>
/// Estimate the size of the transaction
/// </summary>
/// <param name="tx">The transaction to be estimated</param>
/// <param name="virtualSize">If true, returns the size on which fee calculation are based, else returns the physical byte size</param>
/// <returns></returns>
public int EstimateSize(Transaction tx, bool virtualSize)
{
if (tx == null)
throw new ArgumentNullException("tx");
Transaction clone = this.Network.CreateTransaction(tx.ToHex());
clone.Inputs.Clear();
int baseSize = clone.GetSerializedSize();
int witSize = 0;
if (tx.HasWitness)
witSize += 2;
foreach (var txin in tx.Inputs.AsIndexedInputs())
{
ICoin coin = FindSignableCoin(txin) ?? FindCoin(txin.PrevOut);
if (coin == null)
throw CoinNotFound(txin);
EstimateScriptSigSize(coin, ref witSize, ref baseSize);
baseSize += 41;
}
return (virtualSize ? witSize / this.Network.Consensus.Options.WitnessScaleFactor + baseSize : witSize + baseSize);
}
private void EstimateScriptSigSize(ICoin coin, ref int witSize, ref int baseSize)
{
if (coin is IColoredCoin)
coin = ((IColoredCoin)coin).Bearer;
if (coin is ScriptCoin scriptCoin)
{
Script p2sh = scriptCoin.GetP2SHRedeem();
if (p2sh != null)
{
coin = new Coin(scriptCoin.Outpoint, new TxOut(scriptCoin.Amount, p2sh));
baseSize += new Script(Op.GetPushOp(p2sh.ToBytes(true))).Length;
if (scriptCoin.RedeemType == RedeemType.WitnessV0)
{
coin = new ScriptCoin(coin, scriptCoin.Redeem);
}
}
if (scriptCoin.RedeemType == RedeemType.WitnessV0)
{
witSize += new Script(Op.GetPushOp(scriptCoin.Redeem.ToBytes(true))).Length;
}
}
Script scriptPubkey = coin.GetScriptCode(this.Network);
int scriptSigSize = -1;
foreach (BuilderExtension extension in this.Extensions)
{
if (extension.CanEstimateScriptSigSize(this.Network, scriptPubkey))
{
scriptSigSize = extension.EstimateScriptSigSize(this.Network, scriptPubkey);
break;
}
}
if (scriptSigSize == -1)
scriptSigSize += coin.TxOut.ScriptPubKey.Length; //Using heurestic to approximate size of unknown scriptPubKey
if (coin.GetHashVersion(this.Network) == HashVersion.Witness)
witSize += scriptSigSize + 1; //Account for the push
if (coin.GetHashVersion(this.Network) == HashVersion.Original)
baseSize += scriptSigSize;
}
/// <summary>
/// Estimate fees of the built transaction
/// </summary>
/// <param name="feeRate">Fee rate</param>
/// <returns></returns>
public Money EstimateFees(FeeRate feeRate)
{
if (feeRate == null)
throw new ArgumentNullException("feeRate");
int builderCount = this.CurrentGroup.Builders.Count;
Money feeSent = Money.Zero;
try
{
while (true)
{
Transaction tx = BuildTransaction(false);
Money shouldSend = EstimateFees(tx, feeRate);
Money delta = shouldSend - feeSent;
if (delta <= Money.Zero)
break;
SendFees(delta);
feeSent += delta;
}
}
finally
{
while (this.CurrentGroup.Builders.Count != builderCount)
{
this.CurrentGroup.Builders.RemoveAt(this.CurrentGroup.Builders.Count - 1);
}
this._TotalFee -= feeSent;
}
return feeSent;
}
/// <summary>
/// Estimate fees of an unsigned transaction
/// </summary>
/// <param name="tx"></param>
/// <param name="feeRate">Fee rate</param>
/// <returns></returns>
public Money EstimateFees(Transaction tx, FeeRate feeRate)
{
if (tx == null)
throw new ArgumentNullException("tx");
if (feeRate == null)
throw new ArgumentNullException("feeRate");
int estimation = EstimateSize(tx, true);
return feeRate.GetFee(estimation);
}
private void Sign(TransactionSigningContext ctx, ICoin coin, IndexedTxIn txIn)
{
TxIn input = txIn.TxIn;
if (coin is StealthCoin)
{
var stealthCoin = (StealthCoin)coin;
Key scanKey = FindKey(ctx, stealthCoin.Address.ScanPubKey.ScriptPubKey);
if (scanKey == null)
throw new KeyNotFoundException("Scan key for decrypting StealthCoin not found");
Key[] spendKeys = stealthCoin.Address.SpendPubKeys.Select(p => FindKey(ctx, p.ScriptPubKey)).Where(p => p != null).ToArray();
ctx.AdditionalKeys.AddRange(stealthCoin.Uncover(spendKeys, scanKey));
var normalCoin = new Coin(coin.Outpoint, coin.TxOut);
if (stealthCoin.Redeem != null)
normalCoin = normalCoin.ToScriptCoin(stealthCoin.Redeem);
coin = normalCoin;
}
Script scriptSig = CreateScriptSig(ctx, coin, txIn);
if (scriptSig == null)
return;
var scriptCoin = coin as ScriptCoin;
Script signatures = null;
if (coin.GetHashVersion(this.Network) == HashVersion.Witness)
{
signatures = txIn.WitScript;
if (scriptCoin != null)
{
if (scriptCoin.IsP2SH)
txIn.ScriptSig = Script.Empty;
if (scriptCoin.RedeemType == RedeemType.WitnessV0)
signatures = RemoveRedeem(signatures);
}
}
else
{
signatures = txIn.ScriptSig;
if (scriptCoin != null && scriptCoin.RedeemType == RedeemType.P2SH)
signatures = RemoveRedeem(signatures);
}
signatures = CombineScriptSigs(coin, scriptSig, signatures);
if (coin.GetHashVersion(this.Network) == HashVersion.Witness)
{
txIn.WitScript = signatures;
if (scriptCoin != null)
{
if (scriptCoin.IsP2SH)
txIn.ScriptSig = new Script(Op.GetPushOp(scriptCoin.GetP2SHRedeem().ToBytes(true)));
if (scriptCoin.RedeemType == RedeemType.WitnessV0)
txIn.WitScript = txIn.WitScript + new WitScript(Op.GetPushOp(scriptCoin.Redeem.ToBytes(true)));
}
}
else
{
txIn.ScriptSig = signatures;
if (scriptCoin != null && scriptCoin.RedeemType == RedeemType.P2SH)
{
txIn.ScriptSig = input.ScriptSig + Op.GetPushOp(scriptCoin.GetP2SHRedeem().ToBytes(true));
}
}
}
private static Script RemoveRedeem(Script script)
{
if (script == Script.Empty)
return script;
Op[] ops = script.ToOps().ToArray();
return new Script(ops.Take(ops.Length - 1));
}
private Script CombineScriptSigs(ICoin coin, Script a, Script b)
{
Script scriptPubkey = coin.GetScriptCode(this.Network);
if (Script.IsNullOrEmpty(a))
return b ?? Script.Empty;
if (Script.IsNullOrEmpty(b))
return a ?? Script.Empty;
foreach (BuilderExtension extension in this.Extensions)
{
if (extension.CanCombineScriptSig(this.Network, scriptPubkey, a, b))
{
return extension.CombineScriptSig(this.Network, scriptPubkey, a, b);
}
}
return a.Length > b.Length ? a : b; //Heurestic
}
private Script CreateScriptSig(TransactionSigningContext ctx, ICoin coin, IndexedTxIn txIn)
{
Script scriptPubKey = coin.GetScriptCode(this.Network);
var keyRepo = new TransactionBuilderKeyRepository(this, ctx);
var signer = new TransactionBuilderSigner(this, coin, ctx.SigHash, txIn);
var signer2 = new KnownSignatureSigner(this, this._KnownSignatures, coin, ctx.SigHash, txIn);
foreach (BuilderExtension extension in this.Extensions)
{
if (extension.CanGenerateScriptSig(this.Network, scriptPubKey))
{
Script scriptSig1 = extension.GenerateScriptSig(this.Network, scriptPubKey, keyRepo, signer);
Script scriptSig2 = extension.GenerateScriptSig(this.Network, scriptPubKey, signer2, signer2);
if (scriptSig2 != null)
{
scriptSig2 = signer2.ReplaceDummyKeys(scriptSig2);
}
if (scriptSig1 != null && scriptSig2 != null && extension.CanCombineScriptSig(this.Network, scriptPubKey, scriptSig1, scriptSig2))
{
Script combined = extension.CombineScriptSig(this.Network, scriptPubKey, scriptSig1, scriptSig2);
return combined;
}
return scriptSig1 ?? scriptSig2;
}
}
throw new NotSupportedException("Unsupported scriptPubKey");
}
private List<Tuple<PubKey, ECDSASignature>> _KnownSignatures = new List<Tuple<PubKey, ECDSASignature>>();
private Key FindKey(TransactionSigningContext ctx, Script scriptPubKey)
{
Key key = this._Keys
.Concat(ctx.AdditionalKeys)
.FirstOrDefault(k => IsCompatibleKey(k.PubKey, scriptPubKey));
if (key == null && this.KeyFinder != null)
{
key = this.KeyFinder(scriptPubKey);
}
return key;
}
private static bool IsCompatibleKey(PubKey k, Script scriptPubKey)
{
return k.ScriptPubKey == scriptPubKey || //P2PK
k.Hash.ScriptPubKey == scriptPubKey || //P2PKH
k.ScriptPubKey.Hash.ScriptPubKey == scriptPubKey || //P2PK P2SH
k.Hash.ScriptPubKey.Hash.ScriptPubKey == scriptPubKey; //P2PKH P2SH
}
/// <summary>
/// Create a new participant in the transaction with its own set of coins and keys
/// </summary>
/// <returns></returns>
public TransactionBuilder Then()
{
this._CurrentGroup = null;
return this;
}
/// <summary>
/// Switch to another participant in the transaction, or create a new one if it is not found.
/// </summary>
/// <returns></returns>
public TransactionBuilder Then(string groupName)
{
BuilderGroup group = this._BuilderGroups.FirstOrDefault(g => g.Name == groupName);
if (group == null)
{
group = new BuilderGroup(this);
this._BuilderGroups.Add(group);
group.Name = groupName;
}
this._CurrentGroup = group;
return this;
}
/// <summary>
/// Specify the amount of money to cover txouts, if not specified all txout will be covered
/// </summary>
/// <param name="amount"></param>
/// <returns></returns>
public TransactionBuilder CoverOnly(Money amount)
{
this.CurrentGroup.CoverOnly = amount;
return this;
}
private Transaction _CompletedTransaction;
/// <summary>
/// Allows to keep building on the top of a partially built transaction
/// </summary>
/// <param name="transaction">Transaction to complete</param>
/// <returns></returns>
public TransactionBuilder ContinueToBuild(Transaction transaction)
{
if (this._CompletedTransaction != null)
throw new InvalidOperationException("Transaction to complete already set");
this._CompletedTransaction = this.Network.CreateTransaction(transaction.ToHex());
return this;
}
/// <summary>
/// Will cover the remaining amount of TxOut of a partially built transaction (to call after ContinueToBuild)
/// </summary>
/// <returns></returns>
public TransactionBuilder CoverTheRest()
{
if (this._CompletedTransaction == null)
throw new InvalidOperationException("A partially built transaction should be specified by calling ContinueToBuild");
Money spent = this._CompletedTransaction.Inputs.AsIndexedInputs().Select(txin =>
{
ICoin c = FindCoin(txin.PrevOut);
if (c == null)
throw CoinNotFound(txin);
if (!(c is Coin))
return null;
return (Coin)c;
})
.Where(c => c != null)
.Select(c => c.Amount)
.Sum();
Money toComplete = this._CompletedTransaction.TotalOut - spent;
this.CurrentGroup.Builders.Add(ctx =>
{
if (toComplete < Money.Zero)
return Money.Zero;
return toComplete;
});
return this;
}
public TransactionBuilder AddCoins(Transaction transaction)
{
uint256 txId = transaction.GetHash();
AddCoins(transaction.Outputs.Select((o, i) => new Coin(txId, (uint)i, o.Value, o.ScriptPubKey)).ToArray());
return this;
}
private Dictionary<Script, Script> _ScriptPubKeyToRedeem = new Dictionary<Script, Script>();
public TransactionBuilder AddKnownRedeems(params Script[] knownRedeems)
{
foreach (Script redeem in knownRedeems)
{
this._ScriptPubKeyToRedeem.AddOrReplace(redeem.WitHash.ScriptPubKey.Hash.ScriptPubKey, redeem); //Might be P2SH(PWSH)
this._ScriptPubKeyToRedeem.AddOrReplace(redeem.Hash.ScriptPubKey, redeem); //Might be P2SH
this._ScriptPubKeyToRedeem.AddOrReplace(redeem.WitHash.ScriptPubKey, redeem); //Might be PWSH
}
return this;
}
public Transaction CombineSignatures(params Transaction[] transactions)
{
// Necessary because we can't use params and default parameters together
return this.CombineSignatures(false, transactions);
}
/// <summary>
/// Combine transactions by merging their signatures.
/// </summary>
/// <param name="requireFirstSigned">
/// An optional optimisation to exit early. If set and the merging of the first input doesn't change the transaction, the method will exit.
/// </param>
/// <param name="transactions">The transactions to merge signatures for.</param>
/// <returns>The merged transaction.</returns>
public Transaction CombineSignatures(bool requireFirstSigned, params Transaction[] transactions)
{
if (transactions.Length == 1)
return transactions[0];
if (transactions.Length == 0)
return null;
Transaction tx = this.Network.CreateTransaction(transactions[0].ToHex());
for (int i = 1; i < transactions.Length; i++)
{
Transaction signed = transactions[i];
tx = this.CombineSignaturesCore(tx, signed, requireFirstSigned);
}
return tx;
}
private readonly List<BuilderExtension> _Extensions = new List<BuilderExtension>();
public List<BuilderExtension> Extensions
{
get
{
return this._Extensions;
}
}
/// <summary>
/// Combine multiple transactions into one, merging signatures for all of their inputs.
/// </summary>
/// <param name="signed1">First transaction to sign.</param>
/// <param name="signed2">Second transaction to sign.</param>
/// <param name="requireFirstSigned">
/// An optional optimisation to exit early. If set and the merging of the first input doesn't change the transaction, the method will exit.
/// </param>
/// <returns>The combined transaction.</returns>
private Transaction CombineSignaturesCore(Transaction signed1, Transaction signed2, bool requireFirstSigned)
{
if (signed1 == null)
return signed2;
if (signed2 == null)
return signed1;
Transaction tx = this.Network.CreateTransaction(signed1.ToHex());
IndexedTxIn[] signed1Inputs = signed1.Inputs.AsIndexedInputs().ToArray();
IndexedTxIn[] signed2Inputs = signed2.Inputs.AsIndexedInputs().ToArray();
for (int i = 0; i < tx.Inputs.Count; i++)
{
if (i >= signed2.Inputs.Count)
break;
TxIn txIn = tx.Inputs[i];
ICoin coin = FindCoin(txIn.PrevOut);
Script scriptPubKey = coin == null
? (DeduceScriptPubKey(txIn.ScriptSig) ?? DeduceScriptPubKey(signed2.Inputs[i].ScriptSig))
: coin.TxOut.ScriptPubKey;
Money amount = null;
if (coin != null)
amount = coin is IColoredCoin ? ((IColoredCoin)coin).Bearer.Amount : ((Coin)coin).Amount;
ScriptSigs result = Script.CombineSignatures(
this.Network,
scriptPubKey,
new TransactionChecker(tx, i, amount),
GetScriptSigs(signed1Inputs[i]),
GetScriptSigs(signed2Inputs[i]));
IndexedTxIn input = tx.Inputs.AsIndexedInputs().Skip(i).First();
input.WitScript = result.WitSig;
input.ScriptSig = result.ScriptSig;
// In certain cases we're expecting every input to be signed.
// If merging the first input doesn't affect the transaction, exit early.
if (i == 0 && requireFirstSigned && tx.GetHash() == signed1.GetHash())
{
return tx;
}
}
return tx;
}
private ScriptSigs GetScriptSigs(IndexedTxIn indexedTxIn)
{
return new ScriptSigs()
{
ScriptSig = indexedTxIn.ScriptSig,
WitSig = indexedTxIn.WitScript
};
}
private Script DeduceScriptPubKey(Script scriptSig)
{
PayToScriptHashSigParameters p2sh = PayToScriptHashTemplate.Instance.ExtractScriptSigParameters(this.Network, scriptSig);
if (p2sh != null && p2sh.RedeemScript != null)
{
return p2sh.RedeemScript.Hash.ScriptPubKey;
}
foreach (BuilderExtension extension in this.Extensions)
{
if (extension.CanDeduceScriptPubKey(this.Network, scriptSig))
{
return extension.DeduceScriptPubKey(this.Network, scriptSig);
}
}
return null;
}
}
public class CoinNotFoundException : KeyNotFoundException
{
public CoinNotFoundException(IndexedTxIn txIn)
: base("No coin matching " + txIn.PrevOut + " was found")
{
this._OutPoint = txIn.PrevOut;
this._InputIndex = txIn.Index;
}
private readonly OutPoint _OutPoint;
public OutPoint OutPoint
{
get
{
return this._OutPoint;
}
}
private readonly uint _InputIndex;
public uint InputIndex
{
get
{
return this._InputIndex;
}
}
}
}
| stratisproject/StratisBitcoinFullNode | src/NBitcoin/TransactionBuilder.cs | C# | mit | 77,539 |
use uuid::Uuid;
use std::str::FromStr;
use std::fmt;
use version;
#[derive(Clone,Debug)]
pub struct SessionConfig {
pub user_agent: String,
pub device_id: String,
}
impl Default for SessionConfig {
fn default() -> SessionConfig {
let device_id = Uuid::new_v4().hyphenated().to_string();
SessionConfig {
user_agent: version::version_string(),
device_id: device_id,
}
}
}
#[derive(Clone, Copy, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)]
pub enum Bitrate {
Bitrate96,
Bitrate160,
Bitrate320,
}
impl FromStr for Bitrate {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"96" => Ok(Bitrate::Bitrate96),
"160" => Ok(Bitrate::Bitrate160),
"320" => Ok(Bitrate::Bitrate320),
_ => Err(()),
}
}
}
impl Default for Bitrate {
fn default() -> Bitrate {
Bitrate::Bitrate160
}
}
#[derive(Clone, Copy, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)]
pub enum DeviceType {
Unknown = 0,
Computer = 1,
Tablet = 2,
Smartphone = 3,
Speaker = 4,
TV = 5,
AVR = 6,
STB = 7,
AudioDongle = 8,
}
impl FromStr for DeviceType {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
use self::DeviceType::*;
match s.to_lowercase().as_ref() {
"computer" => Ok(Computer),
"tablet" => Ok(Tablet),
"smartphone" => Ok(Smartphone),
"speaker" => Ok(Speaker),
"tv" => Ok(TV),
"avr" => Ok(AVR),
"stb" => Ok(STB),
"audiodongle" => Ok(AudioDongle),
_ => Err(()),
}
}
}
impl fmt::Display for DeviceType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use self::DeviceType::*;
match *self {
Unknown => f.write_str("Unknown"),
Computer => f.write_str("Computer"),
Tablet => f.write_str("Tablet"),
Smartphone => f.write_str("Smartphone"),
Speaker => f.write_str("Speaker"),
TV => f.write_str("TV"),
AVR => f.write_str("AVR"),
STB => f.write_str("STB"),
AudioDongle => f.write_str("AudioDongle"),
}
}
}
impl Default for DeviceType {
fn default() -> DeviceType {
DeviceType::Speaker
}
}
#[derive(Clone,Debug)]
pub struct PlayerConfig {
pub bitrate: Bitrate,
pub onstart: Option<String>,
pub onstop: Option<String>,
}
impl Default for PlayerConfig {
fn default() -> PlayerConfig {
PlayerConfig {
bitrate: Bitrate::default(),
onstart: None,
onstop: None,
}
}
}
#[derive(Clone,Debug)]
pub struct ConnectConfig {
pub name: String,
pub device_type: DeviceType,
}
| XDjackieXD/librespot | core/src/config.rs | Rust | mit | 2,856 |
define({
"add": "Κάντε κλικ για προσθήκη νέου",
"title": "Τίτλος",
"placeholderBookmarkName": "Όνομα σελιδοδείκτη",
"ok": "ΟΚ",
"cancel": "Ακύρωση",
"warning": "Ολοκληρώστε την επεξεργασία!",
"edit": "Επεξεργασία σελιδοδείκτη",
"errorNameExist": "Ο σελιδοδείκτης υπάρχει!",
"errorNameNull": "Μη έγκυρο όνομα σελιδοδείκτη!",
"addBookmark": "Δημιουργία νέου",
"thumbnail": "Μικρογραφία",
"thumbnailHint": "Κάντε κλικ στην εικόνα για ενημέρωση",
"displayBookmarksAs": "Παρουσίαση σελιδοδεικτών ως",
"cards": "Κάρτες",
"list": "Λίστα",
"cardsTips": "Προβολή σε κάρτες",
"listTips": "Προβολή σε λίστα",
"makeAsDefault": "Καθορισμός ως προεπιλεγμένης ρύθμισης",
"default": "Προεπιλεγμένη ρύθμιση",
"editable": "Να επιτρέπεται η προσθήκη σελιδοδεικτών στο widget.",
"alwaysSync": "Παρουσίαση σελιδοδεικτών από διαδικτυακό χάρτη",
"configCustom": "Παρουσίαση εξατομικευμένων σελιδοδεικτών",
"import": "Εισαγωγή",
"create": "Δημιουργία",
"importTitle": "Εισαγωγή σελιδοδεικτών",
"importFromWeb": "Εισαγωγή σελιδοδεικτών από τον τρέχοντα διαδικτυακό χάρτη",
"selectAll": "Επιλογή όλων",
"noBookmarkInConfig": "Για να προσθέσετε σελιδοδείκτες, κάντε κλικ στην επιλογή «Εισαγωγή» ή στην επιλογή «Δημιουργία νέου».",
"noBookmarkInWebMap": "Δεν έχει διαμορφωθεί κανένας σελιδοδείκτης στον χάρτη.",
"extent": "Έκταση",
"saveExtent": "Αποθήκευση έκτασης χάρτη στον σελιδοδείκτη",
"savelayers": "Αποθήκευση ορατότητας θεματικού επιπέδου",
"withVisibility": "Με ορατότητα θεματικών επιπέδων",
"bookmark": "Σελιδοδείκτης",
"addBtn": "Προσθήκη",
"deleteBtn": "Διαγραφή",
"editBtn": "Επεξεργασία",
"dragReorderTip": "Πιέστε παρατεταμένα και σύρετε για αναδιάταξη.",
"deleteBtnTip": "Διαγραφή του σελιδοδείκτη",
"editBtnTip": "Επεξεργασία του σελιδοδείκτη"
}); | tmcgee/cmv-wab-widgets | wab/2.15/widgets/Bookmark/setting/nls/el/strings.js | JavaScript | mit | 2,733 |
module Fastlane
module Actions
# will make sure a gem is installed. If it's not an appropriate error message is shown
# this will *not* 'require' the gem
def self.verify_gem!(gem_name)
begin
Gem::Specification.find_by_name(gem_name)
# We don't import this by default, as it's not always the same
# also e.g. cocoapods is just required and not imported
rescue Gem::LoadError
print_gem_error "Could not find gem '#{gem_name}'"
print_gem_error ""
print_gem_error "If you installed fastlane using `sudo gem install fastlane` run"
print_gem_error "`sudo gem install #{gem_name}` to install the missing gem"
print_gem_error ""
print_gem_error "If you use a Gemfile add this to your Gemfile:"
print_gem_error "gem '#{gem_name}'"
print_gem_error "and run `bundle install`"
raise "You have to install the `#{gem_name}`".red unless Helper.is_test?
end
true
end
def self.print_gem_error(str)
Helper.log.error str.red
end
end
end
| pubuim/fastlane | lib/fastlane/helper/gem_helper.rb | Ruby | mit | 1,074 |
# react-router-native
[React Native](https://facebook.github.io/react-native/) bindings for [React Router](https://reacttraining.com/react-router).
## Installation
Using [npm](https://www.npmjs.com/):
$ npm install --save react-router-native
Then `import` or `require` as you would anything else:
```js
// using ES6 modules
import { NativeRouter, Route, Link } from "react-router-native";
// using CommonJS modules
var NativeRouter = require("react-router-native").NativeRouter;
var Route = require("react-router-native").Route;
var Link = require("react-router-native").Link;
```
## Issues
If you find a bug, please file an issue on [our issue tracker on GitHub](https://github.com/ReactTraining/react-router/issues).
## Credits
React Router is built and maintained by [React Training](https://reacttraining.com).
| rackt/react-router | packages/react-router-native/README.md | Markdown | mit | 830 |
const DrawCard = require('../../drawcard.js');
class BrothersRobes extends DrawCard {
setupCardAbilities() {
this.attachmentRestriction({ trait: 'The Seven' });
this.reaction({
when: {
onCardKneeled: event => event.card === this.parent
},
target: {
activePrompTitle: 'Select a location or attachment',
cardCondition: card => card.location === 'play area' && ['location', 'attachment'].includes(card.getType())
},
handler: context => {
this.untilEndOfPhase(ability => ({
match: context.target,
effect: ability.effects.blankExcludingTraits
}));
this.game.addMessage('{0} uses {1} to treat the text box of {2} as blank until the end of the phase',
context.player, this, context.target);
}
});
}
}
BrothersRobes.code = '10043';
module.exports = BrothersRobes;
| DukeTax/throneteki | server/game/cards/10-SoD/BrothersRobes.js | JavaScript | mit | 1,020 |
module.exports = {
tests: {
unit: ['test/unit/helpers/**/*.coffee', 'test/unit/**/*.coffee'],
integration: ['test/integration/**/*.coffee']
},
helpers: ['test/unit/helpers/**/*.coffee'],
lib: ['lib/**/*.js']
};
| tandrewnichols/file-manifest | gulp/config.js | JavaScript | mit | 227 |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.dialog.add( 'paste', function( editor )
{
var lang = editor.lang.clipboard;
var isCustomDomain = CKEDITOR.env.isCustomDomain();
function onPasteFrameLoad( win )
{
var doc = new CKEDITOR.dom.document( win.document ),
docElement = doc.$;
var script = doc.getById( 'cke_actscrpt' );
script && script.remove();
CKEDITOR.env.ie ?
docElement.body.contentEditable = "true" :
docElement.designMode = "on";
// IE before version 8 will leave cursor blinking inside the document after
// editor blurred unless we clean up the selection. (#4716)
if ( CKEDITOR.env.ie && CKEDITOR.env.version < 8 )
{
doc.getWindow().on( 'blur', function()
{
docElement.selection.empty();
} );
}
doc.on( "keydown", function( e )
{
var domEvent = e.data,
key = domEvent.getKeystroke(),
processed;
switch( key )
{
case 27 :
this.hide();
processed = 1;
break;
case 9 :
case CKEDITOR.SHIFT + 9 :
this.changeFocus( true );
processed = 1;
}
processed && domEvent.preventDefault();
}, this );
editor.fire( 'ariaWidget', new CKEDITOR.dom.element( win.frameElement ) );
}
return {
title : lang.title,
minWidth : CKEDITOR.env.ie && CKEDITOR.env.quirks ? 370 : 350,
minHeight : CKEDITOR.env.quirks ? 250 : 245,
onShow : function()
{
// FIREFOX BUG: Force the browser to render the dialog to make the to-be-
// inserted iframe editable. (#3366)
this.parts.dialog.$.offsetHeight;
this.setupContent();
},
onHide : function()
{
if ( CKEDITOR.env.ie )
this.getParentEditor().document.getBody().$.contentEditable = 'true';
},
onLoad : function()
{
if ( ( CKEDITOR.env.ie7Compat || CKEDITOR.env.ie6Compat ) && editor.lang.dir == 'rtl' )
this.parts.contents.setStyle( 'overflow', 'hidden' );
},
onOk : function()
{
this.commitContent();
},
contents : [
{
id : 'general',
label : editor.lang.common.generalTab,
elements : [
{
type : 'html',
id : 'securityMsg',
html : '<div style="white-space:normal;width:340px;">' + lang.securityMsg + '</div>'
},
{
type : 'html',
id : 'pasteMsg',
html : '<div style="white-space:normal;width:340px;">'+lang.pasteMsg +'</div>'
},
{
type : 'html',
id : 'editing_area',
style : 'width: 100%; height: 100%;',
html : '',
focus : function()
{
var win = this.getInputElement().$.contentWindow;
// #3291 : JAWS needs the 500ms delay to detect that the editor iframe
// iframe is no longer editable. So that it will put the focus into the
// Paste from Word dialog's editable area instead.
setTimeout( function()
{
win.focus();
}, 500 );
},
setup : function()
{
var dialog = this.getDialog();
var htmlToLoad =
'<html dir="' + editor.config.contentsLangDirection + '"' +
' lang="' + ( editor.config.contentsLanguage || editor.langCode ) + '">' +
'<head><style>body { margin: 3px; height: 95%; } </style></head><body>' +
'<script id="cke_actscrpt" type="text/javascript">' +
'window.parent.CKEDITOR.tools.callFunction( ' + CKEDITOR.tools.addFunction( onPasteFrameLoad, dialog ) + ', this );' +
'</script></body>' +
'</html>';
var src =
CKEDITOR.env.air ?
'javascript:void(0)' :
isCustomDomain ?
'javascript:void((function(){' +
'document.open();' +
'document.domain=\'' + document.domain + '\';' +
'document.close();' +
'})())"'
:
'';
var iframe = CKEDITOR.dom.element.createFromHtml(
'<iframe' +
' class="cke_pasteframe"' +
' frameborder="0" ' +
' allowTransparency="true"' +
' src="' + src + '"' +
' role="region"' +
' aria-label="' + lang.pasteArea + '"' +
' aria-describedby="' + dialog.getContentElement( 'general', 'pasteMsg' ).domId + '"' +
' aria-multiple="true"' +
'></iframe>' );
iframe.on( 'load', function( e )
{
e.removeListener();
var doc = iframe.getFrameDocument();
doc.write( htmlToLoad );
if ( CKEDITOR.env.air )
onPasteFrameLoad.call( this, doc.getWindow().$ );
}, dialog );
iframe.setCustomData( 'dialog', dialog );
var container = this.getElement();
container.setHtml( '' );
container.append( iframe );
// IE need a redirect on focus to make
// the cursor blinking inside iframe. (#5461)
if ( CKEDITOR.env.ie )
{
var focusGrabber = CKEDITOR.dom.element.createFromHtml( '<span tabindex="-1" style="position:absolute;" role="presentation"></span>' );
focusGrabber.on( 'focus', function()
{
iframe.$.contentWindow.focus();
});
container.append( focusGrabber );
// Override focus handler on field.
this.focus = function()
{
focusGrabber.focus();
this.fire( 'focus' );
};
}
this.getInputElement = function(){ return iframe; };
// Force container to scale in IE.
if ( CKEDITOR.env.ie )
{
container.setStyle( 'display', 'block' );
container.setStyle( 'height', ( iframe.$.offsetHeight + 2 ) + 'px' );
}
},
commit : function( data )
{
var container = this.getElement(),
editor = this.getDialog().getParentEditor(),
body = this.getInputElement().getFrameDocument().getBody(),
bogus = body.getBogus(),
html;
bogus && bogus.remove();
// Saving the contents so changes until paste is complete will not take place (#7500)
html = body.getHtml();
setTimeout( function(){
editor.fire( 'paste', { 'html' : html } );
}, 0 );
}
}
]
}
]
};
});
| evansd-archive/kohana-module--ckeditor | vendor/ckeditor/_source/plugins/clipboard/dialogs/paste.js | JavaScript | mit | 6,348 |
<?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_Dataflow
* @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)
*/
$installer = $this;
/* @var $installer Mage_Core_Model_Resource_Setup */
$installer->startSetup();
$installer->getConnection()->addColumn($installer->getTable('dataflow_batch'), 'params', 'text default NULL AFTER adapter');
$installer->endSetup();
| fabiensebban/magento | app/code/core/Mage/Dataflow/sql/dataflow_setup/mysql4-upgrade-0.7.3-0.7.4.php | PHP | mit | 1,213 |
var Tape = function() {
var pos = 0, tape = [0];
this.inc = function() { tape[pos]++; }
this.dec = function() { tape[pos]--; }
this.advance = function() { pos++; if (tape.length <= pos) tape.push(0); }
this.devance = function() { if (pos > 0) pos--; }
this.get = function() { return tape[pos]; }
}
var Brainfuck = function(text) {
var me = this;
me.code = "";
me.bracket_map = function(text) {
var leftstack = [];
var bm = {};
for (var i = 0, pc = 0; i < text.length; i++) {
var c = text.charAt(i);
if ("+-<>[].,".indexOf(c) === -1) continue;
if (c === '[') leftstack.push(pc);
if (c === ']' && leftstack.length > 0) {
var left = leftstack.pop();
bm[left] = pc;
bm[pc] = left;
}
me.code += c;
pc++;
}
return bm;
}(text);
me.run = function() {
var pc = 0;
var tape = new Tape();
var code = this.code;
var bm = this.bracket_map;
for (var pc = 0; pc < code.length; pc++)
switch(code[pc]) {
case '+': tape.inc(); break;
case '-': tape.dec(); break;
case '>': tape.advance(); break;
case '<': tape.devance(); break;
case '[': if (tape.get() == 0) pc = bm[pc]; break;
case ']': if (tape.get() != 0) pc = bm[pc]; break;
case '.': process.stdout.write(String.fromCharCode(tape.get()));
default:
}
};
}
var text = require('fs').readFileSync(process.argv[2]).toString();
var brainfuck = new Brainfuck(text);
brainfuck.run();
| erickt/benchmarks | brainfuck/brainfuck.js | JavaScript | mit | 1,429 |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>mac close crash</title>
</head>
<body>
<button id="winclose" onclick="winclose()">close</button>
<script>
function out(id, msg) {
var h1 = document.createElement('h1');
h1.setAttribute('id', id);
h1.innerHTML = msg;
document.body.appendChild(h1);
}
function winclose() {
var win = nw.Window.get();
win.close(true);
out('result', 'success');
}
</script>
</body>
</html>
| nwjs/nw.js | test/sanity/issue4056-mac-close-crash/index.html | HTML | mit | 531 |
var Image = require('./image');
var imageFields = ["fieldname", "originalname", "encoding", "mimetype", "destination",
"filename", "path", "size"];
module.exports = {
create: function (req, cb) {
var newImage = new Image();
//go through array fields which are the fields that are
//given from mutler and are part of the schema
for (var i = 0; i < imageFields.length; i++) {
newImage[imageFields[i]] = req.file[imageFields[i]];
};
newImage.save(function(err, image) {
if(err) {
req.flash('error', "Error Creating Image");
cb(err);
}
cb(null, image);
});
}, //close create
get: function (id, cb) {
Image.findById(id, function(err, image) {
if(err) {
cb(err);
}
if (!image) {
var error= new Error("Image not found");
error.type="image";
error.http_code = 404;
error.arguments ={id: id};
error.message="Image not found";
cb(error);
}
cb(null, image);
});
},
all: function (cb) {
Image.find(function(err, images) {
if(err) {
cb(err);
}
cb(null, images);
});
},
put: function (req, cb) {
Image.findById(req.params.id, function(err, image) {
if(err) {
cb(err);
}
//go through array fields which are the fields that are
//given from mutler and are part of the schema
for (var i = 0; i < imageFields.length; i++) {
newImage[imageFields[i]] = req.file[imageFields[i]];
};
image.save(function(err, image) {
if(err) {
cb(err);
}
cb(null,image);
});
});
},
delete: function (id, cb) {
Image.remove({
_id: id
}, function(err) {
if(err) {
cb(err);
}
});
}
} | TAMUSHPE/goalAppServer | models/images/index.js | JavaScript | mit | 2,109 |
/**
* @desc notify()
* - http://notifyjs.com/ for examples / docs
*
* @param {Function} fn - the function to curry
* @param {Number} [len] - specifies the number of arguments needed to call the function
*
* @return {Function} - the curried function
*/
const url = '//rawgit.com/clearhead/clearhead/master/bower_components/notifyjs/dist/notify-combined.min.js';
let script = null;
function notify(...args) {
// only notify in debug mode
if (!/clearhead-debug=true/.test(document.cookie)) {
return;
}
// wait for jQuery
if (!window.jQuery) {
return setTimeout(notify.bind(this, ...args), 1000);
}
script = script || jQuery.getScript(url); // promise
script.done(function () {
jQuery.notify.call(jQuery, args.join(': '));
});
}
export default notify;
| clearhead/clearhead | src/notify.js | JavaScript | mit | 794 |
## Solving The CPU Hog Problem
Sometimes a handler has a lot of CPU intensive work to do, and
getting through it will take a while.
When a handler hogs the CPU, nothing else can happen. Browsers
only give us one thread of execution and that CPU-hogging handler
owns it, and it isn't giving it up. The UI will be frozen and
there will be no processing of any other handlers (eg: `on-success`
of POSTs), etc, etc. Nothing.
And a frozen UI is a problem. GUI repaints are not happening. And
user interactions are not being processed.
How are we to show progress updates like "Hey, X% completed"? Or
how can we handle the user clicking on that "Cancel" button trying
to stop this long running process?
We need a means by which long running handlers can hand control
back for "other" processing every so often, while still continuing
on with their computation.
## The re-frame Solution
__First__, all long running, CPU-hogging processes are put in event handlers.
Not in subscriptions. Not in components. Not hard to do,
but worth establishing as a rule, right up front.
__Second__, you must be able to break up that CPU
work into chunks. You need a way to do part of the work, pause,
then resume from where you left off. (More in min).
In a perfect world, each chunk would take something like
16ms (60 fps). If you go longer, say 50ms or 100ms, it is no train
smash, but UI responsiveness will degrade and animations, like
busy spinners, will get jerky. Shorter is better, but less than
16ms delivers no added smoothness.
__Third__, within our handler, after it completes one unit (chunk)
of work, it should not continue straight on with the next. Instead,
it should do a `dispatch` to itself and, in the event vector,
include something like the following:
1. a flag to say the work is not finished
2. the working state so far; and
3. what chunk to do next.
## A Sketch
Here's an `-fx` handler which counts up to some number in chunks:
```clj
(re-frame.core/reg-event-fx
:count-to
(fn
[{db :db} [_ first-time so-far finish-at]]
(if first-time
;; We are at the beginning, so:
;; - modify db, causing popup of Modal saying "Working ..."
;; - begin iterative dispatch. Give initial version of "so-far"
{:dispatch [:count-to false {:counter 0} finish-at] ;; dispatch to self
:db (assoc db :we-are-working true)}
(if (> (:counter so-far) finish-at)
;; We are finished:
;; - take away the state which causes the modal to be up
;; - store the result of the calculation
{:db (-> db
(assoc :fruits-of-labour (:counter so-far)) ;; remember the result
(assoc :we-are-working false))} ;; no more modal
;; Still more work to do
;; - run the calculation
;; - redispatch, passing in new running state
(let [new-so-far (update so-far :counter inc)]
{:dispatch [:count-to false new-so-far finish-at]}))))
```
### Why Does A Redispatch Work?
A `dispatched` event is handled asynchronously. It is queued
and not actioned straight away.
And here's the key: **After handling current events, re-frame yields control
to the browser**, allowing it to render any pending DOM changes, etc. After
it is finished, the browser will hand control back to the re-frame router
loop, which will then handle any other queued events
which, in our case, would include the event we just dispatched to perform
the next chunk of work.
When the next dispatch is handled, a next chunk of work will be done, and then another
`dispatch` will happen. And so on. `dispatch` after `dispatch`. Chunk
after chunk. In 16ms increments if we are very careful (or some small amount
of time less than, say, 100ms). But with the browser getting a look-in after each iteration.
### Variations
As we go, the handler could be updating some value in `app-db` which indicates
progress, and this state would then be rendered into the UI.
At a certain point, when all the work is done, the handler will likely put the
fruits of its computational labour into `app-db` and clear any flags which might, for example,
cause a modal dialog to be showing progress. And the process would then be done.
### Cancel Button
It is a flexible pattern. For example, it can be tweaked to handle a "Cancel' button ...
If there was a “Cancel” button to be clicked, we might
`(dispatch [:cancel-it])` and then have this event’s handler tweak the `app-db`
by adding `:abandonment-required` flags. When a chunk-processing-handler
next begins, it could check for this `:abandonment-required` flag, and,
if found, stop the CPU intensive process (and clear the abandonment flags).
When the abandonment-flags
are set, the UI could show "Abandoning process ..." and thus appear responsive
to the user's click on “Cancel”.
That's just one approach. You can adapt the pattern as necessary.
### Further Notes
Going to this trouble is completely unnecessary if the long running
task involves I/O (GET, POST, HTML5 database action?) because the
browser will handle I/O in another thread and give UI activities plenty of look in.
You only need to go to this trouble if it is your code which is
hogging the CPU.
## Forcing A One Off Render
Imagine you have a process which takes, say, 5 seconds, and chunking
is just too much effort.
You lazily decide to leave the UI unresponsive for that short period.
Except,
you aren't totally lazy. If there was a button which kicked off
this 5 second process, and the user clicks it, you’d like the UI to
show a response. Perhaps it could show a modal popup thing saying
“Doing X for you”.
At this point, you still have a small problem to solve. You want
the UI to show your modal message before you then hog the CPU for
5 seconds.
Updating the UI means altering `app-db`. Remember, the UI is a
function of the data in `app-db`. Only changes to `app-db` cause UI
changes.
So, to show that Modal, you’ll need to `assoc` some value into `app-db`
and have that new value change what is rendered in your reagent components.
You might be tempted to do this:
```clj
(re-frame.core/reg-event-db
:process-x
(fn
[db event-v]
(assoc db :processing-X true) ;; hog the CPU
(do-long-process-x))) ;; update state, so reagent components render a modal
```
But that is just plain wrong.
That `assoc` into `db` is not returned (and it must be for a `-db` handler).
And, even if that did somehow work,
then you continue hogging the thread with `do-long-process-x`. There's no
chance for any UI updates because the handler never gives up control. This
handler owns the thread right through.
Ahhh, you think. I know what to do! I'll use that pattern I read
about in the Wiki, and `re-dispatch` within an`-fx` handler:
```clj
(re-frame.core/reg-event-fx
:process-x
(fn
[{db :db} event-v]
{:dispatch [:do-work-process-x] ;; do processing later, give CPU back to browser.
:db (assoc db :processing-X true)})) ;; ao the modal gets rendered
(re-frame.core/reg-event-db
:do-work-process-x
(fn [db _]
(do-long-process-x db))) ;; return a new db, presumably containing work done
```
So close. But it still won’t work. There's a little wrinkle.
That event handler for `:process-x` will indeed give back control
to the browser. BUT, because of the way reagent works, that `assoc` on `db`
won't trigger DOM updates until the next animation frame runs, which is 16ms away.
So, you will be yielding control to the browser, but for next 16ms
there won't appear to be anything to do. And, by then, your CPU hogging
code will have got control back, and will keep control for the next 5
seconds. That nice little Dialog telling you the button was clicked and
action is being taken won't show.
In these kinds of cases, where you are only going to give the UI
**one chance to update** (not a repeated chances every few milli seconds),
then you had better be sure the DOM is fully synced.
To do this, you put meta data on the event being dispatched:
```clj
(re-frame.core/reg-event-fx
:process-x
(fn
[{db :db} event-v]
{:dispatch ^:flush-dom [:do-work-process-x] ;; <--- NOW WITH METADATA
:db (assoc db :processing-X true)})) ;; ao the modal gets rendered
```
Notice the `^:flush-dom` metadata on the event being dispatched. Use
that when you want the UI to be fully updated before the event dispatch
is handled.
You only need this technique when you:
1. want the DOM to be fully updated
2. because you are going to hog the CPU for a while and not give it back. One chunk of work.
If you handle via multiple chunks you don't have to do this, because
you are repeatedly handing back control to the browser/UI. Its just
when you are going to tie up the CPU for a one, longish chunk.
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
| chpill/re-frankenstein | docs/Solve-the-CPU-hog-problem.md | Markdown | mit | 9,201 |
#ifndef __GETPASS_H
#define __GETPASS_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2009, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* $Id: getpass.h,v 1.4 2009-05-18 12:25:45 yangtse Exp $
***************************************************************************/
#ifndef HAVE_GETPASS_R
/* If there's a system-provided function named like this, we trust it is
also found in one of the standard headers. */
/*
* Returning NULL will abort the continued operation!
*/
char* getpass_r(const char *prompt, char* buffer, size_t buflen );
#endif
#endif
| jjimenezg93/ai-pathfinding | moai/3rdparty/curl-7.19.7/src/getpass.h | C | mit | 1,412 |
using System.Runtime.InteropServices;
namespace SharpShell.Interop
{
/// <summary>
/// Exposes methods that the Shell uses to retrieve flags and info tip information
/// for an item that resides in an IShellFolder implementation. Info tips are usually
/// displayed inside a tooltip control.
/// </summary>
[ComImport]
[Guid("00021500-0000-0000-C000-000000000046")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IQueryInfo
{
/// <summary>
/// Gets the info tip text for an item.
/// </summary>
/// <param name="dwFlags">Flags that direct the handling of the item from which you're retrieving the info tip text. This value is commonly zero.</param>
/// <param name="ppwszTip">he address of a Unicode string pointer that, when this method returns successfully, receives the tip string pointer. Applications that implement this method must allocate memory for ppwszTip by calling CoTaskMemAlloc.
/// Calling applications must call CoTaskMemFree to free the memory when it is no longer needed.</param>
/// <returns>Returns S_OK if the function succeeds. If no info tip text is available, ppwszTip is set to NULL. Otherwise, returns a COM-defined error value.</returns>
[PreserveSig]
int GetInfoTip(QITIPF dwFlags, [MarshalAs(UnmanagedType.LPWStr)] out string ppwszTip);
/// <summary>
/// Gets the information flags for an item. This method is not currently used.
/// </summary>
/// <param name="pdwFlags">A pointer to a value that receives the flags for the item. If no flags are to be returned, this value should be set to zero.</param>
/// <returns>Returns S_OK if pdwFlags returns any flag values, or a COM-defined error value otherwise.</returns>
[PreserveSig]
int GetInfoFlags(out int pdwFlags);
}
} | umutozel/sharpshell | SharpShell/SharpShell/Interop/IQueryInfo.cs | C# | mit | 1,901 |
<!--$Id: db_set_msgfile.so,v 1.1 2004/07/14 19:30:39 bostic Exp $-->
<!--$Id: env_set_msgfile.so,v 10.7 2006/02/10 22:54:59 bostic Exp $-->
<!--Copyright (c) 1997,2008 Oracle. All rights reserved.-->
<!--See the file LICENSE for redistribution information.-->
<html>
<head>
<title>Berkeley DB: Db::set_msgfile</title>
<meta name="description" content="Berkeley DB: An embedded database programmatic toolkit.">
<meta name="keywords" content="embedded,database,programmatic,toolkit,btree,hash,hashing,transaction,transactions,locking,logging,access method,access methods,Java,C,C++">
</head>
<body bgcolor=white>
<table width="100%"><tr valign=top>
<td>
<b>Db::set_msgfile</b>
</td>
<td align=right>
<a href="../api_cxx/api_core.html"><img src="../images/api.gif" alt="API"></a>
<a href="../ref/toc.html"><img src="../images/ref.gif" alt="Ref"></a></td>
</tr></table>
<hr size=1 noshade>
<tt>
<b><pre>
#include <db_cxx.h>
<p>
void Db::set_msgfile(FILE *msgfile);
<p>
void Db::get_msgfile(FILE **msgfilep);
</pre></b>
<hr size=1 noshade>
<b>Description: Db::set_msgfile</b>
<p>There are interfaces in the Berkeley DB library which either directly output
informational messages or statistical information, or configure the
library to output such messages when performing other operations, for
example, <a href="../api_cxx/env_set_verbose.html">DbEnv::set_verbose</a> and <a href="../api_cxx/env_stat.html">DbEnv::stat_print</a>.</p>
<p>The <a href="../api_cxx/env_set_msgfile.html">DbEnv::set_msgfile</a> and Db::set_msgfile methods are used to
display these messages for the application. In this case, the message
will include a trailing <newline> character.</p>
<p>Setting <b>msgfile</b> to NULL unconfigures the interface.</p>
<p>Alternatively, you can use the <a href="../api_cxx/env_set_msg_stream.html">DbEnv::set_message_stream</a> and
<a href="../api_cxx/db_set_msg_stream.html">Db::set_message_stream</a> methods to display the messages via an output
stream, or the <a href="../api_cxx/env_set_msgcall.html">DbEnv::set_msgcall</a> and <a href="../api_cxx/db_set_msgcall.html">Db::set_msgcall</a> methods
to capture the additional error information in a way that does not use
either output streams or C library FILE *'s. You should not mix these
approaches.</p>
<p>For <a href="../api_cxx/db_class.html">Db</a> handles opened inside of Berkeley DB environments, calling the
Db::set_msgfile method affects the entire environment and is equivalent to calling
the <a href="../api_cxx/env_set_msgfile.html">DbEnv::set_msgfile</a> method.</p>
<p>The Db::set_msgfile method configures operations performed using the specified
<a href="../api_cxx/db_class.html">Db</a> handle, not all operations performed on the underlying
database.</p>
<p>The Db::set_msgfile method may be called at any time during the life of the
application.</p>
<b>Parameters</b> <br>
<b>msgfile</b><ul compact><li>The <b>msgfile</b> parameter is a C library FILE * to be used for
displaying messages.</ul>
<br>
<hr size=1 noshade>
<b>Description: Db::get_msgfile</b>
<p>The Db::get_msgfile method returns the FILE *.</p>
<p>The Db::get_msgfile method may be called at any time during the life of the
application.</p>
<p>The Db::get_msgfile method
either returns a non-zero error value
or throws an exception that encapsulates a non-zero error value on
failure, and returns 0 on success.
</p>
<b>Parameters</b> <br>
<b>msgfilep</b><ul compact><li>The Db::get_msgfile method returns the
FILE * in <b>msgfilep</b>.</ul>
<br>
<hr size=1 noshade>
<br><b>Class</b>
<a href="../api_cxx/db_class.html">Db</a>
<br><b>See Also</b>
<a href="../api_cxx/db_list.html">Databases and Related Methods</a>
</tt>
<table width="100%"><tr><td><br></td><td align=right>
<a href="../api_cxx/api_core.html"><img src="../images/api.gif" alt="API"></a><a href="../ref/toc.html"><img src="../images/ref.gif" alt="Ref"></a>
</td></tr></table>
<p><font size=1>Copyright (c) 1996,2008 Oracle. All rights reserved.</font>
</body>
</html>
| djsedulous/namecoind | libs/db-4.7.25.NC/docs/api_cxx/db_set_msgfile.html | HTML | mit | 3,997 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.