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
/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright (C) 2011 - 2015 * * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #include "caf/io/doorman.hpp" #include "caf/detail/logging.hpp" #include "caf/io/abstract_broker.hpp" namespace caf { namespace io { doorman::doorman(abstract_broker* ptr, accept_handle acc_hdl, uint16_t p) : network::acceptor_manager(ptr), hdl_(acc_hdl), accept_msg_(make_message(new_connection_msg{hdl_, connection_handle{}})), port_(p) { // nop } doorman::~doorman() { // nop } void doorman::detach_from_parent() { CAF_LOG_TRACE("hdl = " << hdl().id()); parent()->doormen_.erase(hdl()); } message doorman::detach_message() { return make_message(acceptor_closed_msg{hdl()}); } void doorman::io_failure(network::operation op) { CAF_LOG_TRACE("id = " << hdl().id() << ", " << CAF_TARG(op, static_cast<int>)); // keep compiler happy when compiling w/o logging static_cast<void>(op); detach(true); } } // namespace io } // namespace caf
tbenthompson/actor-framework
libcaf_io/src/doorman.cpp
C++
bsd-3-clause
2,350
/***************************************************************************** Copyright (c) 2015, Intel Corp. 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 Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***************************************************************************** * Contents: Native middle-level C interface to LAPACK function zgghd3 * Author: Intel Corporation * Generated January, 2015 *****************************************************************************/ #include "lapacke_utils.h" lapack_int LAPACKE_zgghd3( int matrix_layout, char compq, char compz, lapack_int n, lapack_int ilo, lapack_int ihi, lapack_complex_double* a, lapack_int lda, lapack_complex_double* b, lapack_int ldb, lapack_complex_double* q, lapack_int ldq, lapack_complex_double* z, lapack_int ldz ) { lapack_int info = 0; lapack_int lwork = -1; lapack_complex_double* work = NULL; lapack_complex_double work_query; if( matrix_layout != LAPACK_COL_MAJOR && matrix_layout != LAPACK_ROW_MAJOR ) { LAPACKE_xerbla( "LAPACKE_zgghd3", -1 ); return -1; } #ifndef LAPACK_DISABLE_NAN_CHECK /* Optionally check input matrices for NaNs */ if( LAPACKE_zge_nancheck( matrix_layout, n, n, a, lda ) ) { return -7; } if( LAPACKE_zge_nancheck( matrix_layout, n, n, b, ldb ) ) { return -9; } if( LAPACKE_lsame( compq, 'i' ) || LAPACKE_lsame( compq, 'v' ) ) { if( LAPACKE_zge_nancheck( matrix_layout, n, n, q, ldq ) ) { return -11; } } if( LAPACKE_lsame( compz, 'i' ) || LAPACKE_lsame( compz, 'v' ) ) { if( LAPACKE_zge_nancheck( matrix_layout, n, n, z, ldz ) ) { return -13; } } #endif /* Query optimal working array(s) size */ info = LAPACKE_zgghd3_work( matrix_layout, compq, compz, n, ilo, ihi, a, lda, b, ldb, q, ldq, z, ldz, &work_query, lwork ); if( info != 0 ) { goto exit_level_0; } lwork = LAPACK_C2INT( work_query ); /* Allocate memory for work arrays */ work = (lapack_complex_double*) LAPACKE_malloc( sizeof(lapack_complex_double) * lwork ); if( work == NULL ) { info = LAPACK_WORK_MEMORY_ERROR; goto exit_level_0; } /* Call middle-level interface */ info = LAPACKE_zgghd3_work( matrix_layout, compq, compz, n, ilo, ihi, a, lda, b, ldb, q, ldq, z, ldz, work, lwork ); /* Release memory and exit */ LAPACKE_free( work ); exit_level_0: if( info == LAPACK_WORK_MEMORY_ERROR ) { LAPACKE_xerbla( "LAPACKE_zgghd3", info ); } return info; }
ryanrhymes/openblas
lib/OpenBLAS-0.2.19/lapack-netlib/LAPACKE/src/lapacke_zgghd3.c
C
bsd-3-clause
4,268
require 'test_helper' class SpiderKpisControllerTest < ActionController::TestCase # Replace this with your real tests. test "the truth" do assert true end end
cdebortoli/scpm
test/functional/spider_kpis_controller_test.rb
Ruby
bsd-3-clause
170
var searchData= [ ['gamepad_20axes',['Gamepad axes',['../group__gamepad__axes.html',1,'']]], ['gamepad_20buttons',['Gamepad buttons',['../group__gamepad__buttons.html',1,'']]] ];
DweebsUnited/CodeMonkey
resources/glfw3.3/docs/html/search/groups_2.js
JavaScript
bsd-3-clause
183
/* Copyright (c) by respective owners including Yahoo!, Microsoft, and individual contributors. All rights reserved. Released under a BSD (revised) license as described in the file LICENSE. */ #pragma once #include "vw_clr.h" #include "vw_base.h" #include "vw_example.h" #include "vowpalwabbit.h" namespace VW { /// <summary> /// Helper class to ease construction of native vowpal wabbit namespace data structure. /// </summary> public ref class VowpalWabbitNamespaceBuilder { private: /// <summary> /// Features. /// </summary> features* m_features; /// <summary> /// The namespace index. /// </summary> unsigned char m_index; /// <summary> /// The native example. /// </summary> example* m_example; // float(*m_sum_of_squares)(float*, float*); !VowpalWabbitNamespaceBuilder(); internal: /// <summary> /// Initializes a new <see cref="VowpalWabbitNamespaceBuilder"/> instance. /// </summary> /// <param name="features">Pointer into features owned by <see cref="VowpalWabbitExample"/>.</param> /// <param name="index">The namespace index.</param> /// <param name="example">The native example to build up.</param> VowpalWabbitNamespaceBuilder(features* features, unsigned char index, example* example); public: ~VowpalWabbitNamespaceBuilder(); /// <summary> /// Add feature entry. /// </summary> /// <param name="weight_index">The weight index.</param> /// <param name="x">The value.</param> void AddFeature(uint64_t weight_index, float x); /// <summary> /// Adds a dense array to the example. /// </summary> /// <param name="weight_index_base">The base weight index. Each element is then placed relative to this index.</param> /// <param name="begin">The start pointer of the float array.</param> /// <param name="end">The end pointer of the float array.</param> void AddFeaturesUnchecked(uint64_t weight_index_base, float* begin, float* end); /// <summary> /// Pre-allocate features of <paramref name="size"/>. /// </summary> /// <param name="size">The number of features to pre-allocate.</param> void PreAllocate(int size); }; /// <summary> /// Helper class to ease construction of native vowpal wabbit example data structure. /// </summary> public ref class VowpalWabbitExampleBuilder { private: IVowpalWabbitExamplePool^ m_vw; /// <summary> /// The produced CLR example data structure. /// </summary> VowpalWabbitExample^ m_example; protected: /// <summary> /// Cleanup. /// </summary> !VowpalWabbitExampleBuilder(); public: /// <summary> /// Initializes a new <see cref="VowpalWabbitExampleBuilder"/> instance. /// </summary> /// <param name="vw">The parent vowpal wabbit instance.</param> VowpalWabbitExampleBuilder(IVowpalWabbitExamplePool^ vw); /// <summary> /// Cleanup. /// </summary> ~VowpalWabbitExampleBuilder(); /// <summary> /// Creates the managed example representation. /// </summary> /// <returns>Creates the managed example.</returns> VowpalWabbitExample^ CreateExample(); /// <summary> /// Sets the label for the resulting example. /// </summary> /// <param name="value">The label value to be parsed.</param> void ParseLabel(String^ value); /// <summary> /// Creates and adds a new namespace to this example. /// </summary> VowpalWabbitNamespaceBuilder^ AddNamespace(Byte featureGroup); /// <summary> /// Creates and adds a new namespace to this example. /// </summary> /// <param name="featureGroup">The feature group of the new namespace.</param> /// <remarks>Casts to System::Byte.</remarks> VowpalWabbitNamespaceBuilder^ AddNamespace(Char featureGroup); }; }
raosudha89/vowpal_wabbit
cs/cli/vw_builder.h
C
bsd-3-clause
4,202
from bravado_core.spec import Spec import mock from pyramid.config import Configurator from pyramid.registry import Registry import pytest from swagger_spec_validator.common import SwaggerValidationError import pyramid_swagger from pyramid_swagger.model import SwaggerSchema @mock.patch('pyramid_swagger.register_api_doc_endpoints') @mock.patch('pyramid_swagger.get_swagger_schema') @mock.patch('pyramid_swagger.get_swagger_spec') def test_disable_api_doc_views(_1, _2, mock_register): settings = { 'pyramid_swagger.enable_api_doc_views': False, 'pyramid_swagger.enable_swagger_spec_validation': False, } mock_config = mock.Mock( spec=Configurator, registry=mock.Mock(spec=Registry, settings=settings)) pyramid_swagger.includeme(mock_config) assert not mock_register.called def test_bad_schema_validated_on_include(): settings = { 'pyramid_swagger.schema_directory': 'tests/sample_schemas/bad_app/', 'pyramid_swagger.enable_swagger_spec_validation': True, } mock_config = mock.Mock(registry=mock.Mock(settings=settings)) with pytest.raises(SwaggerValidationError): pyramid_swagger.includeme(mock_config) # TODO: Figure out why this assertion fails on travis # assert "'info' is a required property" in str(excinfo.value) @mock.patch('pyramid_swagger.get_swagger_spec') def test_bad_schema_not_validated_if_spec_validation_is_disabled(_): settings = { 'pyramid_swagger.schema_directory': 'tests/sample_schemas/bad_app/', 'pyramid_swagger.enable_swagger_spec_validation': False, } mock_config = mock.Mock( spec=Configurator, registry=mock.Mock(settings=settings)) pyramid_swagger.includeme(mock_config) @mock.patch('pyramid_swagger.register_api_doc_endpoints') def test_swagger_12_only(mock_register): settings = { 'pyramid_swagger.schema_directory': 'tests/sample_schemas/good_app/', 'pyramid_swagger.swagger_versions': ['1.2'] } mock_config = mock.Mock(registry=mock.Mock(settings=settings)) pyramid_swagger.includeme(mock_config) assert isinstance(settings['pyramid_swagger.schema12'], SwaggerSchema) assert mock_register.call_count == 1 @mock.patch('pyramid_swagger.register_api_doc_endpoints') def test_swagger_20_only(mock_register): settings = { 'pyramid_swagger.schema_directory': 'tests/sample_schemas/good_app/', 'pyramid_swagger.swagger_versions': ['2.0'] } mock_config = mock.Mock(registry=mock.Mock(settings=settings)) pyramid_swagger.includeme(mock_config) assert isinstance(settings['pyramid_swagger.schema20'], Spec) assert not settings['pyramid_swagger.schema12'] assert mock_register.call_count == 1 @mock.patch('pyramid_swagger.register_api_doc_endpoints') def test_swagger_12_and_20(mock_register): settings = { 'pyramid_swagger.schema_directory': 'tests/sample_schemas/good_app/', 'pyramid_swagger.swagger_versions': ['1.2', '2.0'] } mock_config = mock.Mock(registry=mock.Mock(settings=settings)) pyramid_swagger.includeme(mock_config) assert isinstance(settings['pyramid_swagger.schema20'], Spec) assert isinstance(settings['pyramid_swagger.schema12'], SwaggerSchema) assert mock_register.call_count == 2
analogue/pyramid_swagger
tests/includeme_test.py
Python
bsd-3-clause
3,308
/* * Copyright (c) 2012, Michael Lehn, Klaus Pototzky * * 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 FLENS development group nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef CXXLAPACK_INTERFACE_LAGTM_H #define CXXLAPACK_INTERFACE_LAGTM_H 1 #include <cxxstd/complex.h> namespace cxxlapack { template <typename IndexType> IndexType lagtm(char trans, IndexType n, IndexType nRhs, float alpha, const float *dl, const float *d, const float *du, const float *X, IndexType ldX, float beta, float *B, IndexType ldB); template <typename IndexType> IndexType lagtm(char trans, IndexType n, IndexType nRhs, double alpha, const double *dl, const double *d, const double *du, const double *X, IndexType ldX, double beta, double *B, IndexType ldB); template <typename IndexType> IndexType lagtm(char trans, IndexType n, IndexType nRhs, float alpha, const std::complex<float > *dl, const std::complex<float > *d, const std::complex<float > *du, const std::complex<float > *X, IndexType ldX, float beta, std::complex<float > *B, IndexType ldB); template <typename IndexType> IndexType lagtm(char trans, IndexType n, IndexType nRhs, double alpha, const std::complex<double> *dl, const std::complex<double> *d, const std::complex<double> *du, const std::complex<double> *X, IndexType ldX, double beta, std::complex<double> *B, IndexType ldB); } // namespace cxxlapack #endif // CXXLAPACK_INTERFACE_LAGTM_H
d-tk/FLENS
cxxlapack/interface/lagtm.h
C
bsd-3-clause
3,962
/*----------------------------------------------------------------------------*/ /* Copyright (c) FIRST 2008-2016. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.test; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Vector; import java.util.logging.LogManager; import java.util.logging.Logger; import java.util.regex.Pattern; import junit.framework.JUnit4TestAdapter; import junit.runner.Version; import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.RunWith; import org.junit.runner.notification.Failure; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; import edu.wpi.first.wpilibj.WpiLibJTestSuite; import edu.wpi.first.wpilibj.can.CANTestSuite; import edu.wpi.first.wpilibj.command.CommandTestSuite; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboardTestSuite; /** * The WPILibJ Integeration Test Suite collects all of the tests to be run by * junit. In order for a test to be run, it must be added the list of suite * classes below. The tests will be run in the order they are listed in the * suite classes annotation. */ @RunWith(Suite.class) // These are listed on separate lines to prevent merge conflicts @SuiteClasses({WpiLibJTestSuite.class, CANTestSuite.class, CommandTestSuite.class, SmartDashboardTestSuite.class}) public class TestSuite extends AbstractTestSuite { static { // Sets up the logging output final InputStream inputStream = TestSuite.class.getResourceAsStream("/logging.properties"); try { if (inputStream == null) throw new NullPointerException("./logging.properties was not loaded"); LogManager.getLogManager().readConfiguration(inputStream); Logger.getAnonymousLogger().info("Loaded"); } catch (final IOException | NullPointerException e) { Logger.getAnonymousLogger().severe("Could not load default logging.properties file"); Logger.getAnonymousLogger().severe(e.getMessage()); } TestBench.out().println("Starting Tests"); } private static final Logger WPILIBJ_ROOT_LOGGER = Logger.getLogger("edu.wpi.first.wpilibj"); private static final Logger WPILIBJ_COMMAND_ROOT_LOGGER = Logger .getLogger("edu.wpi.first.wpilibj.command"); private static final Class<?> QUICK_TEST = QuickTest.class; private static final String QUICK_TEST_FLAG = "--quick"; private static final String HELP_FLAG = "--help"; private static final String METHOD_NAME_FILTER = "--methodFilter="; private static final String METHOD_REPEAT_FILTER = "--repeat="; private static final String CLASS_NAME_FILTER = "--filter="; private static TestSuite instance = null; public static TestSuite getInstance() { if (instance == null) { instance = new TestSuite(); } return instance; } /** * This has to be public so that the JUnit4 */ public TestSuite() {} /** * Displays a help message for the user when they use the --help flag at * runtime. */ protected static void displayHelp() { StringBuilder helpMessage = new StringBuilder("Test Parameters help: \n"); helpMessage.append("\t" + QUICK_TEST_FLAG + " will cause the quick test to be run. Ignores other flags except for " + METHOD_REPEAT_FILTER + "\n"); helpMessage.append("\t" + CLASS_NAME_FILTER + " will use the supplied regex text to search for suite/test class names " + "matching the regex and run them.\n"); helpMessage.append("\t" + METHOD_NAME_FILTER + " will use the supplied regex text to search for test methods (excluding methods " + "with the @Ignore annotation) and run only those methods. Can be paired with " + METHOD_REPEAT_FILTER + " to " + "repeat the selected tests multiple times.\n"); helpMessage.append("\t" + METHOD_REPEAT_FILTER + " will repeat the tests selected with either " + QUICK_TEST_FLAG + " or " + CLASS_NAME_FILTER + " and run them the given number of times.\n"); helpMessage .append("[NOTE] All regex uses the syntax defined by java.util.regex.Pattern. This documentation can be found at " + "http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html\n"); helpMessage.append("\n"); helpMessage.append("\n"); TestBench.out().println(helpMessage); } /** * Lets the user know that they used the TestSuite improperly and gives * details about how to use it correctly in the future. */ protected static void displayInvalidUsage(String message, String... args) { StringBuilder invalidMessage = new StringBuilder("Invalid Usage: " + message + "\n"); invalidMessage.append("Params received: "); for (String a : args) { invalidMessage.append(a + " "); } invalidMessage.append("\n"); invalidMessage .append("For details on proper usage of the runtime flags please run again with the " + HELP_FLAG + " flag.\n\n"); TestBench.out().println(invalidMessage); } /** * Prints the loaded tests before they are run. *$ * @param classes the classes that were loaded. */ protected static void printLoadedTests(final Class<?>... classes) { StringBuilder loadedTestsMessage = new StringBuilder("The following tests were loaded:\n"); Package p = null; for (Class<?> c : classes) { if (c.getPackage().equals(p)) { p = c.getPackage(); loadedTestsMessage.append(p.getName() + "\n"); } loadedTestsMessage.append("\t" + c.getSimpleName() + "\n"); } TestBench.out().println(loadedTestsMessage); } /** * Parses the arguments passed at runtime and runs the appropriate tests based * upon these arguments *$ * @param args the args passed into the program at runtime * @return the restults of the tests that have run. If no tests were run then * null is returned. */ protected static Result parseArgsRunAndGetResult(final String[] args) { if (args.length == 0) { // If there are no args passed at runtime then just // run all of the tests. printLoadedTests(TestSuite.class); return JUnitCore.runClasses(TestSuite.class); } // The method filter was passed boolean methodFilter = false; String methodRegex = ""; // The class filter was passed boolean classFilter = false; String classRegex = ""; boolean repeatFilter = false; int repeatCount = 1; for (String s : args) { if (Pattern.matches(METHOD_NAME_FILTER + ".*", s)) { methodFilter = true; methodRegex = new String(s).replace(METHOD_NAME_FILTER, ""); } if (Pattern.matches(METHOD_REPEAT_FILTER + ".*", s)) { repeatFilter = true; try { repeatCount = Integer.parseInt(new String(s).replace(METHOD_REPEAT_FILTER, "")); } catch (NumberFormatException e) { displayInvalidUsage("The argument passed to the repeat rule was not a valid integer.", args); } } if (Pattern.matches(CLASS_NAME_FILTER + ".*", s)) { classFilter = true; classRegex = new String(s).replace(CLASS_NAME_FILTER, ""); } } ArrayList<String> argsParsed = new ArrayList<String>(Arrays.asList(args)); if (argsParsed.contains(HELP_FLAG)) { // If the user inputs the help flag then return the help message and exit // without running any tests displayHelp(); return null; } if (argsParsed.contains(QUICK_TEST_FLAG)) { printLoadedTests(QUICK_TEST); return JUnitCore.runClasses(QUICK_TEST); } /** * Stores the data from multiple {@link Result}s in one class that can be * returned to display the results. */ class MultipleResult extends Result { private static final long serialVersionUID = 1L; private final List<Failure> failures = new Vector<Failure>(); private int runCount = 0; private int ignoreCount = 0; private long runTime = 0; @Override public int getRunCount() { return runCount; } @Override public int getFailureCount() { return failures.size(); } @Override public long getRunTime() { return runTime; } @Override public List<Failure> getFailures() { return failures; } @Override public int getIgnoreCount() { return ignoreCount; } /** * Adds the given result's data to this result *$ * @param r the result to add to this result */ void addResult(Result r) { failures.addAll(r.getFailures()); runCount += r.getRunCount(); ignoreCount += r.getIgnoreCount(); runTime += r.getRunTime(); } } // If a specific method has been requested if (methodFilter) { List<ClassMethodPair> pairs = (new TestSuite()).getMethodMatching(methodRegex); if (pairs.size() == 0) { displayInvalidUsage("None of the arguments passed to the method name filter matched.", args); return null; } // Print out the list of tests before we run them TestBench.out().println("Running the following tests:"); Class<?> classListing = null; for (ClassMethodPair p : pairs) { if (!p.methodClass.equals(classListing)) { // Only display the class name every time it changes classListing = p.methodClass; TestBench.out().println(classListing); } TestBench.out().println("\t" + p.methodName); } // The test results will be saved here MultipleResult results = new MultipleResult(); // Runs tests multiple times if the repeat rule is used for (int i = 0; i < repeatCount; i++) { // Now run all of the tests for (ClassMethodPair p : pairs) { Result result = (new JUnitCore()).run(p.getMethodRunRequest()); // Store the given results in one cohesive result results.addResult(result); } } return results; } // If a specific class has been requested if (classFilter) { List<Class<?>> testClasses = (new TestSuite()).getSuiteOrTestMatchingRegex(classRegex); if (testClasses.size() == 0) { displayInvalidUsage("None of the arguments passed to the filter matched.", args); return null; } printLoadedTests(testClasses.toArray(new Class[0])); MultipleResult results = new MultipleResult(); // Runs tests multiple times if the repeat rule is used for (int i = 0; i < repeatCount; i++) { Result result = (new JUnitCore()).run(testClasses.toArray(new Class[0])); // Store the given results in one cohesive result results.addResult(result); } return results; } displayInvalidUsage( "None of the parameters that you passed matched any of the accepted flags.", args); return null; } protected static void displayResults(Result result) { // Results are collected and displayed here TestBench.out().println("\n"); if (!result.wasSuccessful()) { // Prints out a list of stack traces for the failed tests TestBench.out().println("Failure List: "); for (Failure f : result.getFailures()) { TestBench.out().println(f.getDescription()); TestBench.out().println(f.getTrace()); } TestBench.out().println(); TestBench.out().println("FAILURES!!!"); // Print the test statistics TestBench.out().println( "Tests run: " + result.getRunCount() + ", Failures: " + result.getFailureCount() + ", Ignored: " + result.getIgnoreCount() + ", In " + result.getRunTime() + "ms"); // Prints out a list of test that failed TestBench.out().println("Failure List (short):"); String failureClass = result.getFailures().get(0).getDescription().getClassName(); TestBench.out().println(failureClass); for (Failure f : result.getFailures()) { if (!failureClass.equals(f.getDescription().getClassName())) { failureClass = f.getDescription().getClassName(); TestBench.out().println(failureClass); } TestBench.err().println("\t" + f.getDescription()); } } else { TestBench.out().println("SUCCESS!"); TestBench.out().println( "Tests run: " + result.getRunCount() + ", Ignored: " + result.getIgnoreCount() + ", In " + result.getRunTime() + "ms"); } TestBench.out().println(); } /** * This is used by ant to get the Junit tests. This is required because the * tests try to load using a JUnit 3 framework. JUnit4 uses annotations to * load tests. This method allows JUnit3 to load JUnit4 tests. */ public static junit.framework.Test suite() { return new JUnit4TestAdapter(TestSuite.class); } /** * The method called at runtime *$ * @param args The test suites to run */ public static void main(String[] args) { TestBench.out().println("JUnit version " + Version.id()); // Tests are run here Result result = parseArgsRunAndGetResult(args); if (result != null) { // Results are collected and displayed here displayResults(result); System.exit(result.wasSuccessful() ? 0 : 1); } System.exit(1); } }
JLLeitschuh/allwpilib
wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/TestSuite.java
Java
bsd-3-clause
13,796
////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2013, Image Engine Design 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 John Haddon nor the names of // any other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #ifndef GAFFERIMAGE_GRADE_H #define GAFFERIMAGE_GRADE_H #include "Gaffer/CompoundNumericPlug.h" #include "GafferImage/ChannelDataProcessor.h" namespace GafferImage { /// The grade node implements the common grade operation to the RGB channels of the input. /// The computation performed is: /// A = multiply * (gain - lift) / (whitePoint - blackPoint) /// B = offset + lift - A * blackPoint /// output = pow( A * input + B, 1/gamma ) // class Grade : public ChannelDataProcessor { public : Grade( const std::string &name=defaultName<Grade>() ); virtual ~Grade(); IE_CORE_DECLARERUNTIMETYPEDEXTENSION( GafferImage::Grade, GradeTypeId, ChannelDataProcessor ); //! @name Plug Accessors /// Returns a pointer to the node's plugs. ////////////////////////////////////////////////////////////// //@{ Gaffer::Color3fPlug *blackPointPlug(); const Gaffer::Color3fPlug *blackPointPlug() const; Gaffer::Color3fPlug *whitePointPlug(); const Gaffer::Color3fPlug *whitePointPlug() const; Gaffer::Color3fPlug *liftPlug(); const Gaffer::Color3fPlug *liftPlug() const; Gaffer::Color3fPlug *gainPlug(); const Gaffer::Color3fPlug *gainPlug() const; Gaffer::Color3fPlug *multiplyPlug(); const Gaffer::Color3fPlug *multiplyPlug() const; Gaffer::Color3fPlug *offsetPlug(); const Gaffer::Color3fPlug *offsetPlug() const; Gaffer::Color3fPlug *gammaPlug(); const Gaffer::Color3fPlug *gammaPlug() const; Gaffer::BoolPlug *blackClampPlug(); const Gaffer::BoolPlug *blackClampPlug() const; Gaffer::BoolPlug *whiteClampPlug(); const Gaffer::BoolPlug *whiteClampPlug() const; //@} virtual void affects( const Gaffer::Plug *input, AffectedPlugsContainer &outputs ) const; protected : virtual bool channelEnabled( const std::string &channel ) const; virtual void hashChannelData( const GafferImage::ImagePlug *output, const Gaffer::Context *context, IECore::MurmurHash &h ) const; virtual void processChannelData( const Gaffer::Context *context, const ImagePlug *parent, const std::string &channelIndex, IECore::FloatVectorDataPtr outData ) const; private : void parameters( size_t channelIndex, float &a, float &b, float &gamma ) const; static size_t g_firstPlugIndex; }; IE_CORE_DECLAREPTR( Grade ); } // namespace GafferImage #endif // GAFFERIMAGE_GRADE_H
chippey/gaffer
include/GafferImage/Grade.h
C
bsd-3-clause
4,179
#ifndef ALIANALYSISTASKCOMBINHF_H #define ALIANALYSISTASKCOMBINHF_H /* Copyright(c) 1998-2018, ALICE Experiment at CERN, All rights reserved. * * See cxx source for full Copyright notice */ /* $Id: $ */ ///************************************************************************* /// \class Class AliAnalysisTaskCombinHF /// \brief AliAnalysisTaskSE to build D meson candidates by combining tracks /// background is computed LS and track rotations is /// \author Authors: F. Prino, A. Rossi ////////////////////////////////////////////////////////////// #include <TH1F.h> #include <TH3F.h> #include <TObjString.h> #include <THnSparse.h> #include "AliAnalysisTaskSE.h" #include "AliAODTrack.h" #include "AliNormalizationCounter.h" #include "AliRDHFCuts.h" class AliAnalysisTaskCombinHF : public AliAnalysisTaskSE { public: AliAnalysisTaskCombinHF(); AliAnalysisTaskCombinHF(Int_t meson, AliRDHFCuts* analysiscuts); virtual ~AliAnalysisTaskCombinHF(); virtual void UserCreateOutputObjects(); virtual void Init(){}; virtual void LocalInit() {Init();} virtual void UserExec(Option_t *option); virtual void Terminate(Option_t *option); virtual void FinishTaskOutput(); void SetReadMC(Bool_t read){fReadMC=read;} void UseOnlySignalInMC(Bool_t opt){fSignalOnlyMC=opt;} void UseMBTrigMaskInMC(){fEnforceMBTrigMaskInMC=kTRUE;} void UseTrigMaskFromCutFileInMC(){fEnforceMBTrigMaskInMC=kFALSE;} void SetPtHardRange(double pmin, double pmax){ fSelectPtHardRange=kTRUE; fMinPtHard=pmin; fMaxPtHard=pmax; } void SetEventMixingWithCuts(Double_t maxDeltaVz, Double_t maxDeltaMult){ fDoEventMixing=2; fMaxzVertDistForMix=maxDeltaVz; fMaxMultDiffForMix=maxDeltaMult; } void SetEventMixingWithPools(){fDoEventMixing=1;} void SetEventMixingOff(){fDoEventMixing=0;} void SetNumberOfEventsForMixing(Int_t minn){fNumberOfEventsForMixing=minn;} void ConfigureZVertPools(Int_t nPools, Double_t* zVertLimits); void ConfigureMultiplicityPools(Int_t nPools, Double_t* multLimits); void SetGoUpToQuark(Bool_t opt){fGoUpToQuark=opt;} void SetKeepNegIDtracks(Bool_t nid){fKeepNegID=nid;}//set it to kTRUE only if you know what you are doing void SetTrackCuts(AliESDtrackCuts* cuts){ if(fTrackCutsAll) delete fTrackCutsAll; fTrackCutsAll=new AliESDtrackCuts(*cuts); } void SetPionTrackCuts(AliESDtrackCuts* cuts){ if(fTrackCutsPion) delete fTrackCutsPion; fTrackCutsPion=new AliESDtrackCuts(*cuts); } void SetKaonTrackCuts(AliESDtrackCuts* cuts){ if(fTrackCutsKaon) delete fTrackCutsKaon; fTrackCutsKaon=new AliESDtrackCuts(*cuts); } void SetMinNumTPCClsForPID(Int_t cut=0.) {fCutTPCSignalN = cut;} void SetCutOnCosThetaStar(Double_t cut){ if(cut>0 && cut<1) fApplyCutCosThetaStar=kTRUE; else fApplyCutCosThetaStar=kFALSE; fCutCosThetaStar=cut; } void EnableHistosVsCosThetaStar(Bool_t opt){ fFillHistosVsCosThetaStar=opt; } void SetCutOnKKInvMass(Double_t cut){ fPhiMassCut=cut; } void SetCutOnCos3PiKPhiRFrame(Double_t cut){ fCutCos3PiKPhiRFrame=cut; } void SetCutCosPiDsLabFrame(Double_t cut){ fCutCosPiDsLabFrame=cut; } void SetRDHFCuts(AliRDHFCuts* cuts){ fAnalysisCuts=cuts; } void SetFilterMask(UInt_t mask=16){fFilterMask=mask;} void SetAnalysisLevel(Int_t level){fFullAnalysis=level;} void ConfigureRotation(Int_t n, Double_t phimin, Double_t phimax){ fNRotations=n; fMinAngleForRot=phimin; fMaxAngleForRot=phimax; } void ConfigureRotation3rdProng(Int_t n, Double_t phimin, Double_t phimax){ fNRotations3=n; fMinAngleForRot3=phimin; fMaxAngleForRot3=phimax; } void SetMassWindow(Double_t minMass, Double_t maxMass){fMinMass=minMass; fMaxMass=maxMass;} void SetMaxPt(Double_t maxPt){fMaxPt=maxPt;} void SetPtBinWidth(Double_t binw){fPtBinWidth=binw;} void SetEtaAccCut(Double_t etacut){fEtaAccCut=etacut;} void SetPtAccCut(Double_t ptcut){fPtAccCut=ptcut;} void SetMultiplicityRange(Double_t mmin=-0.5, Double_t mmax=199.5, Int_t nbins=200){ fMinMultiplicity=mmin; fMaxMultiplicity=mmax; fNumOfMultBins=nbins; } void SetPIDstrategy(Int_t strat){fPIDstrategy=strat;} void SetMaxPforIDPion(Double_t maxpIdPion){fmaxPforIDPion=maxpIdPion;} void SetMaxPforIDKaon(Double_t maxpIdKaon){fmaxPforIDKaon=maxpIdKaon;} void SetPIDselCaseZero(Int_t strat){fPIDselCaseZero=strat;} void SetBayesThres(Double_t thresKaon, Double_t thresPion){ fBayesThresKaon=thresKaon; fBayesThresPion=thresPion; } Bool_t IsTrackSelected(AliAODTrack* track); Bool_t IsKaon(AliAODTrack* track); Bool_t IsPion(AliAODTrack* track); Bool_t SelectAODTrack(AliAODTrack *track, AliESDtrackCuts *cuts); Bool_t FillHistos(Int_t pdgD,Int_t nProngs, AliAODRecoDecay* tmpRD, Double_t* px, Double_t* py, Double_t* pz, UInt_t *pdgdau, TClonesArray *arrayMC, AliAODMCHeader *mcHeader, Int_t* dgLabels); void FillLSHistos(Int_t pdgD,Int_t nProngs, AliAODRecoDecay* tmpRD, Double_t* px, Double_t* py, Double_t* pz, UInt_t *pdgdau, Int_t charge); void FillMEHistos(Int_t pdgD,Int_t nProngs, AliAODRecoDecay* tmpRD, Double_t* px, Double_t* py, Double_t* pz, UInt_t *pdgdau); void FillMEHistosLS(Int_t pdgD,Int_t nProngs, AliAODRecoDecay* tmpRD, Double_t* px, Double_t* py, Double_t* pz, UInt_t *pdgdau, Int_t charge); void FillGenHistos(TClonesArray* arrayMC, AliAODMCHeader *mcHeader, Bool_t isEvSel); Bool_t CheckAcceptance(TClonesArray* arrayMC, Int_t nProng, Int_t *labDau); Int_t GetPoolIndex(Double_t zvert, Double_t mult); void ResetPool(Int_t poolIndex); void DoMixingWithPools(Int_t poolIndex); void DoMixingWithCuts(); Bool_t CanBeMixed(Double_t zv1, Double_t zv2, Double_t mult1, Double_t mult2); enum EMesonSpecies {kDzero, kDplus, kDstar, kDs}; enum EPrompFd {kNone,kPrompt,kFeeddown,kBoth}; enum EPIDstrategy {knSigma, kBayesianMaxProb, kBayesianThres}; private: AliAnalysisTaskCombinHF(const AliAnalysisTaskCombinHF &source); AliAnalysisTaskCombinHF& operator=(const AliAnalysisTaskCombinHF& source); Double_t ComputeInvMassKK(AliAODTrack* tr1, AliAODTrack* tr2) const; Double_t ComputeInvMassKK(TLorentzVector* tr1, TLorentzVector* tr2) const; Double_t CosPiKPhiRFrame(TLorentzVector* dauK1, TLorentzVector* dauK2, TLorentzVector* daupi) const; Double_t CosPiDsLabFrame(TLorentzVector* dauK1, TLorentzVector* dauK2, TLorentzVector* daupi) const; TList *fOutput; //!<! list with output histograms TList *fListCuts; //!<! list with cut values TH1F *fHistNEvents; //!<!hist. for No. of events TH2F *fHistEventMultCent; //!<!hist. for evnt Mult vs. centrality (all) TH2F *fHistEventMultCentEvSel; //!<!hist. for evnt Mult vs. centrality (sel) TH2F *fHistEventMultZv; //!<!hist. of evnt Mult vs. Zv for all events TH2F *fHistEventMultZvEvSel; //!<!hist. of evnt Mult vs. Zv for selected ev TH1F *fHistXsecVsPtHard; //!<!hist. of xsec vs pthard (MC) TH1F *fHistTrackStatus; //!<!hist. of status of tracks TH3F *fHistTrackEtaMultZv; // track distribution vs. eta z vertex and mult TH2F *fHistSelTrackPhiPt; // track distribution vs. phi and pt TH2F *fHistCheckOrigin; //!<!hist. of origin (c/b) of D meson (gen) TH2F *fHistCheckOriginRecoD; //!<!hist. of origin (c/b) of D meson (reco) TH2F *fHistCheckOriginRecoVsGen; //!<!hist. of origin (c/b) of D meson TH1F *fHistCheckDecChan; //!<!hist. of decay channel of D meson TH1F *fHistCheckDecChanAcc; //!<!hist. of decay channel of D meson in acc. TH3F *fPtVsYVsMultGenPrompt; //!<! hist. of Y vs. Pt vs. Mult generated (all D) TH3F *fPtVsYVsMultGenLargeAccPrompt; //!<! hist. of Y vs. Pt vs. Mult generated (|y|<0.9) TH3F *fPtVsYVsMultGenLimAccPrompt; //!<! hist. of Y vs. Pt vs. Mult generated (|y|<0.5) TH3F *fPtVsYVsMultGenAccPrompt; //!<! hist. of Y vs. Pt vs. Mult generated (D in acc) TH3F *fPtVsYVsMultGenAccEvSelPrompt; //!<! hist. of Y vs. Pt vs. Mult generated (D in acc, sel ev.) TH3F *fPtVsYVsMultRecoPrompt; //!<! hist. of Y vs. Pt vs. Mult generated (Reco D) TH3F *fPtVsYVsMultGenFeeddw; //!<! hist. of Y vs. Pt vs. Mult generated (all D) TH3F *fPtVsYVsMultGenLargeAccFeeddw; //!<! hist. of Y vs. Pt vs. Mult generated (|y|<0.9) TH3F *fPtVsYVsMultGenLimAccFeeddw; //!<! hist. of Y vs. Pt vs. Mult generated (|y|<0.5) TH3F *fPtVsYVsMultGenAccFeeddw; //!<! hist. of Y vs. Pt vs. Mult generated (D in acc) TH3F *fPtVsYVsMultGenAccEvSelFeeddw; //!<! hist. of Y vs. Pt vs. Mult generated (D in acc, sel ev.) TH3F *fPtVsYVsMultRecoFeeddw; //!<! hist. of Y vs. Pt vs. Mult generated (Reco D) TH3F *fPtVsYVsPtBGenFeeddw; //!<! hist. of Y vs. Pt vs. PtB generated (all D) TH3F *fPtVsYVsPtBGenLargeAccFeeddw; //!<! hist. of Y vs. Pt vs. PtB generated (|y|<0.9) TH3F *fPtVsYVsPtBGenLimAccFeeddw; //!<! hist. of Y vs. Pt vs. PtB generated (|y|<0.5) TH3F *fPtVsYVsPtBGenAccFeeddw; //!<! hist. of Y vs. Pt vs. PtB generated (D in acc) TH3F *fPtVsYVsPtBGenAccEvSelFeeddw; //!<! hist. of Y vs. Pt vs. PtB generated (D in acc, sel ev.) TH3F *fPtVsYVsPtBRecoFeeddw; //!<! hist. of Y vs. Pt vs. PtB generated (Reco D) TH3F *fMassVsPtVsY; //!<! hist. of Y vs. Pt vs. Mass (all cand) TH3F *fMassVsPtVsYRot; //!<! hist. of Y vs. Pt vs. Mass (rotations) TH3F *fMassVsPtVsYLSpp; //!<! hist. of Y vs. Pt vs. Mass (like sign ++) TH3F *fMassVsPtVsYLSmm; //!<! hist. of Y vs. Pt vs. Mass (like sign --) TH3F *fMassVsPtVsYSig; //!<! hist. of Y vs. Pt vs. Mass (signal) TH3F *fMassVsPtVsYRefl; //!<! hist. of Y vs. Pt vs. Mass (reflections) TH3F *fMassVsPtVsYBkg; //!<! hist. of Y vs. Pt vs. Mass (background) TH1F *fBMohterPtGen; //!<! hist. of beauty mother pt TH1F *fNSelected; //!<! hist. of n. of selected D+ TH1F *fNormRotated; //!<! hist. rotated/selected D+ TH1F *fDeltaMass; //!<! hist. mass difference after rotations THnSparse *fDeltaMassFullAnalysis; //!<! hist. mass difference after rotations with more details TH3F *fMassVsPtVsYME; //!<! hist. of Y vs. Pt vs. Mass (mixedevents) TH3F *fMassVsPtVsYMELSpp; //!<! hist. of Y vs. Pt vs. Mass (mixedevents) TH3F *fMassVsPtVsYMELSmm; //!<! hist. of Y vs. Pt vs. Mass (mixedevents) TH2F* fEventsPerPool; //!<! hist with number of events per pool TH2F* fMixingsPerPool; //!<! hist with number of mixings per pool TH3F *fMassVsPtVsCosthSt; //!<! hist. of Pt vs. Mass vs. cos(th*) (all cand) TH3F *fMassVsPtVsCosthStRot; //!<! hist. of Pt vs. Mass vs. cos(th*) (rotations) TH3F *fMassVsPtVsCosthStLSpp; //!<! hist. of Pt vs. Mass vs. cos(th*) (like sign ++) TH3F *fMassVsPtVsCosthStLSmm; //!<! hist. of Pt vs. Mass vs. cos(th*) (like sign --) TH3F *fMassVsPtVsCosthStSig; //!<! hist. of Pt vs. Mass vs. cos(th*) (signal) TH3F *fMassVsPtVsCosthStRefl; //!<! hist. of Pt vs. Mass vs. cos(th*) (reflections) TH3F *fMassVsPtVsCosthStBkg; //!<! hist. of Pt vs. Mass vs. cos(th*) (background) TH3F *fMassVsPtVsCosthStME; //!<! hist. of Pt vs. Mass vs. cos(th*) (mixedevents) TH3F *fMassVsPtVsCosthStMELSpp; //!<! hist. of Pt vs. Mass vs. cos(th*) (mixedevents) TH3F *fMassVsPtVsCosthStMELSmm; //!<! hist. of Pt vs. Mass vs. cos(th*) (mixedevents) TH2F *fHistonSigmaTPCPion; //!<! hist. of nSigmaTPC pion TH2F *fHistonSigmaTPCPionGoodTOF; //!<! hist. of nSigmaTPC pion TH2F *fHistonSigmaTOFPion; //!<! hist. of nSigmaTOF pion TH2F *fHistonSigmaTPCKaon; //!<! hist. of nSigmaTPC kaon TH2F *fHistonSigmaTPCKaonGoodTOF; //!<! hist. of nSigmaTPC kaon TH2F *fHistonSigmaTOFKaon; //!<! hist. of nSigmaTOF kaon TH3F *fHistoPtKPtPiPtD; //!<! hist. for propagation of tracking unc TH3F *fHistoPtKPtPiPtDSig; //!<! hist. for propagation of tracking unc UInt_t fFilterMask; /// FilterMask AliESDtrackCuts* fTrackCutsAll; //// track selection AliESDtrackCuts* fTrackCutsPion; /// pion track selection AliESDtrackCuts* fTrackCutsKaon; /// kaon track selection Int_t fCutTPCSignalN; /// min. value of number of TPC clusters for PID, cut if !=0 Bool_t fFillHistosVsCosThetaStar; /// flag to control cos(theta*) cut Bool_t fApplyCutCosThetaStar; /// flag to control cos(theta*) cut Double_t fCutCosThetaStar; /// cos(theta*) cut Double_t fPhiMassCut; /// cut on the KK inv mass for phi selection Double_t fCutCos3PiKPhiRFrame; // cut on the Ds decay angles Double_t fCutCosPiDsLabFrame; // cut on the Ds decay angles AliAODPidHF* fPidHF; /// PID configuration AliRDHFCuts *fAnalysisCuts; /// Cuts for candidates Double_t fMinMass; /// minimum value of invariant mass Double_t fMaxMass; /// maximum value of invariant mass Double_t fMaxPt; /// maximum pT value for inv. mass histograms Double_t fPtBinWidth; /// width of pt bin (GeV/c) Double_t fEtaAccCut; /// eta limits for acceptance step Double_t fPtAccCut; /// pt limits for acceptance step Int_t fNRotations; /// number of rotations Double_t fMinAngleForRot; /// minimum angle for track rotation Double_t fMaxAngleForRot; /// maximum angle for track rotation Int_t fNRotations3; /// number of rotations (3rd prong) Double_t fMinAngleForRot3; /// minimum angle for track rotation (3rd prong) Double_t fMaxAngleForRot3; /// maximum angle for track rotation (3rd prong) AliNormalizationCounter *fCounter;//!<!Counter for normalization Int_t fMeson; /// mesonSpecies (see enum) Bool_t fReadMC; /// flag for access to MC Bool_t fEnforceMBTrigMaskInMC; /// if true force the MC to use Bool_t fGoUpToQuark; /// flag for definition of c,b origin Int_t fFullAnalysis; /// flag to set analysis level (0 is the fastest) Bool_t fSignalOnlyMC; /// flag to speed up the MC Bool_t fSelectPtHardRange; /// flag to select specific phard range in MC Double_t fMinPtHard; /// minimum pthard Double_t fMaxPtHard; /// maximum pthard Int_t fPIDstrategy; /// knSigma, kBayesianMaxProb, kBayesianThres Double_t fmaxPforIDPion; /// flag for upper p limit for id band for pion Double_t fmaxPforIDKaon; /// flag for upper p limit for id band for kaon Bool_t fKeepNegID; /// flag to keep also track with negative ID (default kFALSE, change it only if you know what you are doing) Int_t fPIDselCaseZero; /// flag to change PID strategy Double_t fBayesThresKaon; /// threshold for kaon identification via Bayesian PID Double_t fBayesThresPion; /// threshold for pion identification via Bayesian PID Int_t fOrigContainer[200000]; /// container for checks Int_t fDoEventMixing; /// flag for event mixing Int_t fNumberOfEventsForMixing; /// maximum number of events to be used in event mixing Double_t fMaxzVertDistForMix; /// cut on zvertex distance for event mixing with cuts Double_t fMaxMultDiffForMix; /// cut on multiplicity difference for event mixing with cuts Int_t fNzVertPools; /// number of pools in z vertex for event mixing Int_t fNzVertPoolsLimSize; /// number of pools in z vertex for event mixing +1 Double_t* fzVertPoolLims; //[fNzVertPoolsLimSize] limits of the pools in zVertex Int_t fNMultPools; /// number of pools in multiplicity for event mixing Int_t fNMultPoolsLimSize; /// number of pools in multiplicity for event mixing +1 Double_t* fMultPoolLims; //[fNMultPoolsLimSize] limits of the pools in multiplicity Int_t fNOfPools; /// number of pools TTree** fEventBuffer; //!<! structure for event mixing TObjString* fEventInfo; /// unique event Id for event mixing checks Double_t fVtxZ; /// zVertex Double_t fMultiplicity; /// multiplicity Int_t fNumOfMultBins; /// number of bins for multiplcities in MC histos Double_t fMinMultiplicity; /// lower limit for multiplcities in MC histos Double_t fMaxMultiplicity; /// upper limit for multiplcities in MC histos TObjArray* fKaonTracks; /// array of kaon-compatible tracks (TLorentzVectors) TObjArray* fPionTracks; /// array of pion-compatible tracks (TLorentzVectors) /// \cond CLASSIMP ClassDef(AliAnalysisTaskCombinHF,31); /// D0D+ task from AOD tracks /// \endcond }; #endif
kreisl/AliPhysics
PWGHF/vertexingHF/AliAnalysisTaskCombinHF.h
C
bsd-3-clause
16,713
--TEST-- phpunit -c ../_files/configuration_stop_on_incomplete.xml ./tests/_files/StopOnErrorTestSuite.php --FILE-- <?php declare(strict_types=1); $_SERVER['argv'][] = '--do-not-cache-result'; $_SERVER['argv'][] = '-c'; $_SERVER['argv'][] = \realpath(__DIR__ . '/../../_files/configuration_stop_on_incomplete.xml'); $_SERVER['argv'][] = \realpath(__DIR__ . '/../../_files/StopOnErrorTestSuite.php'); require __DIR__ . '/../../bootstrap.php'; PHPUnit\TextUI\Command::main(); --EXPECTF-- PHPUnit %s by Sebastian Bergmann and contributors. I Time: %s, Memory: %s OK, but incomplete, skipped, or risky tests! Tests: 1, Assertions: 0, Incomplete: 1.
Firehed/phpunit
tests/end-to-end/execution-order/stop-on-incomplete-via-config.phpt
PHP
bsd-3-clause
650
require('babel/register'); var pm2 = require('pm2'); pm2.connect(function() { pm2.start({ name: 'server', script: 'server/server.js', 'exec_mode': 'cluster', instances: '2', 'max_memory_restart': '900M' }, function() { pm2.disconnect(); }); });
mattkuo/freecodecamp
pm2Start.js
JavaScript
bsd-3-clause
275
<?php /** * Created by PhpStorm. * User: kristjan * Date: 9.03.15 * Time: 11:59 */ namespace Application\Entity\User; use Application\Entity\AbstractEntity; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity * @ORM\Table(name="user_provider") * */ class Provider extends AbstractEntity{ /** * @var int * @ORM\Id * @ORM\Column(type="integer", name="user_id") */ protected $userId; /** * @var string * @ORM\Id * @ORM\Column(type="string", name="provider_id") */ protected $providerId; /** * @var string * @ORM\Column(type="string", name="provider") */ protected $provider; /** * @return string */ public function getProvider() { return $this->provider; } /** * @param string $provider */ public function setProvider($provider) { $this->provider = $provider; return $this; } /** * @return int */ public function getUserId() { return $this->userId; } /** * @param int $userId */ public function setUserId($userId) { $this->userId = $userId; return $this; } /** * @return int */ public function getProviderId() { return $this->providerId; } /** * @param int $providerId */ public function setProviderId($providerId) { $this->providerId = $providerId; return $this; } }
kristjanAnd/skeletonSocialUser
module/Application/src/Application/Entity/User/Provider.php
PHP
bsd-3-clause
1,495
--- docid: absolute-position title: Absolute positioning layout: docs permalink: /docs/absolute-position/ --- The `Position` property tells Flexbox how you want your item to be positioned within its parent. There are 2 options: * `Relative` (default) * `Absolute` An item marked with `Position = Absolute` is positioned absolutely in regards to its parent. This is done through 6 properties: * `Left` - controls the distance a child's left edge is from the parent's left edge * `Top` - controls the distance a child's top edge is from the parent's top edge * `Right` - controls the distance a child's right edge is from the parent's right edge * `Bottom` - controls the distance a child's bottom edge is from the parent's bottom edge * `Start` - controls the distance a child's start edge is from the parent's start edge * `End` - controls the distance a child's end edge is from the parent's end edge Using these options you can control the size and position of an absolute item within its parent. Because absolutely positioned children don't effect their siblings layout `Position = Absolute` can be used to create overlays and stack children in the Z axis. #### Position = Absolute; Start = 0; Top = 0; Width = 50; Height = 50; <div class="yoga" style="align-items: flex-start;"> <div class="yoga sample" style="background-color: white; width: 300px; height: 300px;"> <div class="yoga" style="background-color: #303846; width: 50px; height: 50px; left: 0px; top: 0px; position: absolute;"></div> </div> </div> #### Position = Absolute; Start = 10; Top = 10; End = 10; Bottom = 10; <div class="yoga" style="align-items: flex-start;"> <div class="yoga sample" style="background-color: white; width: 300px; height: 300px;"> <div class="yoga" style="background-color: #303846; left: 10px; top: 10px; bottom: 10px; right: 10px; position: absolute;"></div> </div> </div>
rmarinho/yoga
docs/_docs/flexbox/absolute-position.md
Markdown
bsd-3-clause
1,893
ZfcUserDoctrineORM ================== Version 0.0.1 Created by Evan Coury and the ZF-Commons team Introduction ------------ ZfcUserDoctrineORM is a Doctrine2 ORM storage adapter for [ZfcUser](https://github.com/ZF-Commons/ZfcUser). Dependencies ------------ - [ZfcUser](https://github.com/ZF-Commons/ZfcUser) - [DoctrineModule](https://github.com/doctrine/DoctrineModule) - [DoctrineORMModule](https://github.com/doctrine/DoctrineORMModule)
Pol-Valentin/sooyoos
vendor/zf-commons/zfc-user-doctrine-orm/README.md
Markdown
bsd-3-clause
444
<!DOCTYPE html> <html> <style> div { position: absolute; width: 50px; height: 50px; -webkit-transform: rotate3d(0, 0, 1, 10deg) scale(5, 5); } #red { top: 200px; left: 200px; background-color: red; } #green { top: 200px; left: 200px; background-color: green; } </style> </head> <body> <p>This test ensures that the sub-pixel offset is properly carried into a composited transform origin.</p> <div id="red"></div> <div id="green"></div>
ondra-novak/blink
LayoutTests/fast/sub-pixel/sub-pixel-composited-layer-with-transform-expected.html
HTML
bsd-3-clause
480
/* * Copyright 2015, Yahoo Inc. * Copyrights licensed under the New BSD License. * See the accompanying LICENSE file for terms. */ package com.yahoo.gondola.container; import com.fasterxml.jackson.databind.ObjectMapper; import com.yahoo.gondola.Config; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.RetryOneTime; import java.io.IOException; /** * The Factory class for creating registry client easily. */ public class RegistryClients { /** * prevening create instance of this factory class. */ private RegistryClients() { } /** * create zookeeper client via config. * @param config The Gondola config * @return The ZookeeperRegistryClient instance */ public static RegistryClient createZookeeperClient(Config config) throws IOException { CuratorFramework client = CuratorFrameworkFactory.builder() .connectString(getZookeeperConnectionString(config)) .retryPolicy(new RetryOneTime(1000)) .build(); client.start(); return new ZookeeperRegistryClient(client, new ObjectMapper(), config); } private static String getZookeeperConnectionString(Config config) { return String.join(",", config.getList("registry_zookeeper.servers")); } }
patc888/gondola
containers/registration/src/main/java/com/yahoo/gondola/container/RegistryClients.java
Java
bsd-3-clause
1,376
package org.hisp.dhis.setting; /* * Copyright (c) 2004-2016, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertNull; import java.io.Serializable; import java.util.List; import java.util.Map; import org.hisp.dhis.DhisSpringTest; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import static org.hisp.dhis.setting.SettingKey.*; /** * @author Stian Strandli * @author Lars Helge Overland */ public class SystemSettingManagerTest extends DhisSpringTest { @Autowired private SystemSettingManager systemSettingManager; @Override public void setUpTest() { systemSettingManager.invalidateCache(); } @Test public void testSaveGetSystemSetting() { systemSettingManager.saveSystemSetting( "settingA", "valueA" ); systemSettingManager.saveSystemSetting( "settingB", "valueB" ); assertEquals( "valueA", systemSettingManager.getSystemSetting( "settingA" ) ); assertEquals( "valueB", systemSettingManager.getSystemSetting( "settingB" ) ); } @Test public void testSaveGetSetting() { systemSettingManager.saveSystemSetting( APPLICATION_INTRO, "valueA" ); systemSettingManager.saveSystemSetting( APPLICATION_NOTIFICATION, "valueB" ); assertEquals( "valueA", systemSettingManager.getSystemSetting( APPLICATION_INTRO ) ); assertEquals( "valueB", systemSettingManager.getSystemSetting( APPLICATION_NOTIFICATION ) ); } @Test public void testSaveGetSettingWithDefault() { assertEquals( APP_STORE_URL.getDefaultValue(), systemSettingManager.getSystemSetting( APP_STORE_URL ) ); assertEquals( EMAIL_PORT.getDefaultValue(), systemSettingManager.getSystemSetting( EMAIL_PORT ) ); } @Test public void testSaveGetDeleteSetting() { assertNull( systemSettingManager.getSystemSetting( APPLICATION_INTRO ) ); assertEquals( HELP_PAGE_LINK.getDefaultValue(), systemSettingManager.getSystemSetting( HELP_PAGE_LINK ) ); systemSettingManager.saveSystemSetting( APPLICATION_INTRO, "valueA" ); systemSettingManager.saveSystemSetting( HELP_PAGE_LINK, "valueB" ); assertEquals( "valueA", systemSettingManager.getSystemSetting( APPLICATION_INTRO ) ); assertEquals( "valueB", systemSettingManager.getSystemSetting( HELP_PAGE_LINK ) ); systemSettingManager.deleteSystemSetting( APPLICATION_INTRO ); assertNull( systemSettingManager.getSystemSetting( APPLICATION_INTRO ) ); assertEquals( "valueB", systemSettingManager.getSystemSetting( HELP_PAGE_LINK ) ); systemSettingManager.deleteSystemSetting( HELP_PAGE_LINK ); assertNull( systemSettingManager.getSystemSetting( APPLICATION_INTRO ) ); assertEquals( HELP_PAGE_LINK.getDefaultValue(), systemSettingManager.getSystemSetting( HELP_PAGE_LINK ) ); } @Test public void testGetAllSystemSettings() { systemSettingManager.saveSystemSetting( "settingA", "valueA" ); systemSettingManager.saveSystemSetting( "settingB", "valueB" ); systemSettingManager.saveSystemSetting( "settingC", "valueC" ); List<SystemSetting> settings = systemSettingManager.getAllSystemSettings(); assertNotNull( settings ); assertEquals( 3, settings.size() ); } @Test public void testGetSystemSettingsAsMap() { systemSettingManager.saveSystemSetting( SettingKey.APP_STORE_URL, "valueA" ); systemSettingManager.saveSystemSetting( SettingKey.APPLICATION_TITLE, "valueB" ); systemSettingManager.saveSystemSetting( SettingKey.APPLICATION_NOTIFICATION, "valueC" ); Map<String, Serializable> settingsMap = systemSettingManager.getSystemSettingsAsMap(); assertTrue( settingsMap.containsKey( SettingKey.APP_STORE_URL.getName() ) ); assertTrue( settingsMap.containsKey( SettingKey.APPLICATION_TITLE.getName() ) ); assertTrue( settingsMap.containsKey( SettingKey.APPLICATION_NOTIFICATION.getName() ) ); assertEquals( "valueA", settingsMap.get( SettingKey.APP_STORE_URL.getName() ) ); assertEquals( "valueB", settingsMap.get( SettingKey.APPLICATION_TITLE.getName() ) ); assertEquals( "valueC", settingsMap.get( SettingKey.APPLICATION_NOTIFICATION.getName() ) ); assertEquals( SettingKey.CACHE_STRATEGY.getDefaultValue(), settingsMap.get( SettingKey.CACHE_STRATEGY.getName() ) ); assertEquals( SettingKey.CREDENTIALS_EXPIRES.getDefaultValue(), settingsMap.get( SettingKey.CREDENTIALS_EXPIRES.getName() ) ); } }
mortenoh/dhis2-core
dhis-2/dhis-services/dhis-service-core/src/test/java/org/hisp/dhis/setting/SystemSettingManagerTest.java
Java
bsd-3-clause
6,442
<div class='fossil-doc' data-title='bench::in - Benchmarking/Performance tools'> <style> HTML { background: #FFFFFF; color: black; } BODY { background: #FFFFFF; color: black; } DIV.doctools { margin-left: 10%; margin-right: 10%; } DIV.doctools H1,DIV.doctools H2 { margin-left: -5%; } H1, H2, H3, H4 { margin-top: 1em; font-family: sans-serif; font-size: large; color: #005A9C; background: transparent; text-align: left; } H1.doctools_title { text-align: center; } UL,OL { margin-right: 0em; margin-top: 3pt; margin-bottom: 3pt; } UL LI { list-style: disc; } OL LI { list-style: decimal; } DT { padding-top: 1ex; } UL.doctools_toc,UL.doctools_toc UL, UL.doctools_toc UL UL { font: normal 12pt/14pt sans-serif; list-style: none; } LI.doctools_section, LI.doctools_subsection { list-style: none; margin-left: 0em; text-indent: 0em; padding: 0em; } PRE { display: block; font-family: monospace; white-space: pre; margin: 0%; padding-top: 0.5ex; padding-bottom: 0.5ex; padding-left: 1ex; padding-right: 1ex; width: 100%; } PRE.doctools_example { color: black; background: #f5dcb3; border: 1px solid black; } UL.doctools_requirements LI, UL.doctools_syntax LI { list-style: none; margin-left: 0em; text-indent: 0em; padding: 0em; } DIV.doctools_synopsis { color: black; background: #80ffff; border: 1px solid black; font-family: serif; margin-top: 1em; margin-bottom: 1em; } UL.doctools_syntax { margin-top: 1em; border-top: 1px solid black; } UL.doctools_requirements { margin-bottom: 1em; border-bottom: 1px solid black; } </style> <hr> [ <a href="../../../../toc.html">Main Table Of Contents</a> | <a href="../../../toc.html">Table Of Contents</a> | <a href="../../../../index.html">Keyword Index</a> | <a href="../../../../toc0.html">Categories</a> | <a href="../../../../toc1.html">Modules</a> | <a href="../../../../toc2.html">Applications</a> ] <hr> <div class="doctools"> <h1 class="doctools_title">bench::in(n) 0.1 tcllib &quot;Benchmarking/Performance tools&quot;</h1> <div id="name" class="doctools_section"><h2><a name="name">Name</a></h2> <p>bench::in - bench::in - Reading benchmark results</p> </div> <div id="toc" class="doctools_section"><h2><a name="toc">Table Of Contents</a></h2> <ul class="doctools_toc"> <li class="doctools_section"><a href="#toc">Table Of Contents</a></li> <li class="doctools_section"><a href="#synopsis">Synopsis</a></li> <li class="doctools_section"><a href="#section1">Description</a></li> <li class="doctools_section"><a href="#section2">PUBLIC API</a></li> <li class="doctools_section"><a href="#section3">Bugs, Ideas, Feedback</a></li> <li class="doctools_section"><a href="#see-also">See Also</a></li> <li class="doctools_section"><a href="#keywords">Keywords</a></li> <li class="doctools_section"><a href="#category">Category</a></li> <li class="doctools_section"><a href="#copyright">Copyright</a></li> </ul> </div> <div id="synopsis" class="doctools_section"><h2><a name="synopsis">Synopsis</a></h2> <div class="doctools_synopsis"> <ul class="doctools_requirements"> <li>package require <b class="pkgname">Tcl 8.2</b></li> <li>package require <b class="pkgname">csv</b></li> <li>package require <b class="pkgname">bench::in <span class="opt">?0.1?</span></b></li> </ul> <ul class="doctools_syntax"> <li><a href="#1"><b class="cmd">::bench::in::read</b> <i class="arg">file</i></a></li> </ul> </div> </div> <div id="section1" class="doctools_section"><h2><a name="section1">Description</a></h2> <p>This package provides a command for reading benchmark results from files, sockets, etc.</p> <p>A reader interested in the creation, processing or writing of such results should go and read <i class="term"><a href="bench.html">bench - Processing benchmark suites</a></i> instead.</p> <p>If the bench language itself is the actual interest please start with the <i class="term"><a href="bench_lang_intro.html">bench language introduction</a></i> and then proceed from there to the formal <i class="term"><a href="bench_lang_spec.html">bench language specification</a></i>.</p> </div> <div id="section2" class="doctools_section"><h2><a name="section2">PUBLIC API</a></h2> <dl class="doctools_definitions"> <dt><a name="1"><b class="cmd">::bench::in::read</b> <i class="arg">file</i></a></dt> <dd><p>This command reads a benchmark result from the specified <i class="arg">file</i> and returns it as its result. The command understands the three formats created by the commands</p> <dl class="doctools_commands"> <dt><b class="cmd">bench::out::raw</b></dt> <dd><p>Provided by package <b class="package"><a href="bench.html">bench</a></b>.</p></dd> <dt><b class="cmd"><a href="bench_wcsv.html">bench::out::csv</a></b></dt> <dd><p>Provided by package <b class="package"><a href="bench_wcsv.html">bench::out::csv</a></b>.</p></dd> <dt><b class="cmd"><a href="bench_wtext.html">bench::out::text</a></b></dt> <dd><p>Provided by package <b class="package"><a href="bench_wtext.html">bench::out::text</a></b>.</p></dd> </dl> <p>and automatically detects which format is used by the input file.</p></dd> </dl> </div> <div id="section3" class="doctools_section"><h2><a name="section3">Bugs, Ideas, Feedback</a></h2> <p>This document, and the package it describes, will undoubtedly contain bugs and other problems. Please report such in the category <em>bench</em> of the <a href="http://core.tcl.tk/tcllib/reportlist">Tcllib Trackers</a>. Please also report any ideas for enhancements you may have for either package and/or documentation.</p> </div> <div id="see-also" class="doctools_section"><h2><a name="see-also">See Also</a></h2> <p><a href="bench.html">bench</a>, <a href="bench_wcsv.html">bench::out::csv</a>, <a href="bench_wtext.html">bench::out::text</a>, <a href="bench_intro.html">bench_intro</a></p> </div> <div id="keywords" class="doctools_section"><h2><a name="keywords">Keywords</a></h2> <p><a href="../../../../index.html#key101">benchmark</a>, <a href="../../../../index.html#key49">csv</a>, <a href="../../../../index.html#key247">formatting</a>, <a href="../../../../index.html#key503">human readable</a>, <a href="../../../../index.html#key26">parsing</a>, <a href="../../../../index.html#key100">performance</a>, <a href="../../../../index.html#key524">reading</a>, <a href="../../../../index.html#key99">testing</a>, <a href="../../../../index.html#key248">text</a></p> </div> <div id="category" class="doctools_section"><h2><a name="category">Category</a></h2> <p>Benchmark tools</p> </div> <div id="copyright" class="doctools_section"><h2><a name="copyright">Copyright</a></h2> <p>Copyright &copy; 2007 Andreas Kupries &lt;andreas_kupries@users.sourceforge.net&gt;</p> </div> </div>
macports/macports-base
vendor/tcllib-1.18/embedded/www/tcllib/files/modules/bench/bench_read.html
HTML
bsd-3-clause
6,872
/* * Copyright (c) 2018 jMonkeyEngine * 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 'jMonkeyEngine' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.jme3.bullet.collision; /** * Named collision flags for a {@link PhysicsCollisionObject}. Values must agree * with those in BulletCollision/CollisionDispatch/btCollisionObject.h * * @author Stephen Gold sgold@sonic.net * @see PhysicsCollisionObject#getCollisionFlags(long) */ public class CollisionFlag { /** * flag for a static object */ final public static int STATIC_OBJECT = 0x1; /** * flag for a kinematic object */ final public static int KINEMATIC_OBJECT = 0x2; /** * flag for an object with no contact response, such as a PhysicsGhostObject */ final public static int NO_CONTACT_RESPONSE = 0x4; /** * flag to enable a custom material callback for per-triangle * friction/restitution (not used by JME) */ final public static int CUSTOM_MATERIAL_CALLBACK = 0x8; /** * flag for a character object, such as a PhysicsCharacter */ final public static int CHARACTER_OBJECT = 0x10; /** * flag to disable debug visualization (not used by JME) */ final public static int DISABLE_VISUALIZE_OBJECT = 0x20; /** * flag to disable parallel/SPU processing (not used by JME) */ final public static int DISABLE_SPU_COLLISION_PROCESSING = 0x40; /** * flag not used by JME */ final public static int HAS_CONTACT_STIFFNESS_DAMPING = 0x80; /** * flag not used by JME */ final public static int HAS_CUSTOM_DEBUG_RENDERING_COLOR = 0x100; /** * flag not used by JME */ final public static int HAS_FRICTION_ANCHOR = 0x200; /** * flag not used by JME */ final public static int HAS_COLLISION_SOUND_TRIGGER = 0x400; }
zzuegg/jmonkeyengine
jme3-bullet/src/main/java/com/jme3/bullet/collision/CollisionFlag.java
Java
bsd-3-clause
3,292
/******************************************************* * Copyright (c) 2014, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #pragma once #include <kernel_headers/matchTemplate.hpp> #include <program.hpp> #include <traits.hpp> #include <string> #include <mutex> #include <map> #include <dispatch.hpp> #include <Param.hpp> #include <debug_opencl.hpp> using cl::Buffer; using cl::Program; using cl::Kernel; using cl::make_kernel; using cl::EnqueueArgs; using cl::NDRange; using std::string; namespace opencl { namespace kernel { static const dim_type THREADS_X = 16; static const dim_type THREADS_Y = 16; template<typename inType, typename outType, af_match_type mType, bool needMean> void matchTemplate(Param out, const Param srch, const Param tmplt) { try { static std::once_flag compileFlags[DeviceManager::MAX_DEVICES]; static std::map<int, Program*> mtProgs; static std::map<int, Kernel*> mtKernels; int device = getActiveDeviceId(); std::call_once( compileFlags[device], [device] () { std::ostringstream options; options << " -D inType=" << dtype_traits<inType>::getName() << " -D outType=" << dtype_traits<outType>::getName() << " -D MATCH_T=" << mType << " -D NEEDMEAN="<< needMean << " -D AF_SAD=" << AF_SAD << " -D AF_ZSAD=" << AF_ZSAD << " -D AF_LSAD=" << AF_LSAD << " -D AF_SSD=" << AF_SSD << " -D AF_ZSSD=" << AF_ZSSD << " -D AF_LSSD=" << AF_LSSD << " -D AF_NCC=" << AF_NCC << " -D AF_ZNCC=" << AF_ZNCC << " -D AF_SHD=" << AF_SHD; if (std::is_same<outType, double>::value) { options << " -D USE_DOUBLE"; } Program prog; buildProgram(prog, matchTemplate_cl, matchTemplate_cl_len, options.str()); mtProgs[device] = new Program(prog); mtKernels[device] = new Kernel(*mtProgs[device], "matchTemplate"); }); NDRange local(THREADS_X, THREADS_Y); dim_type blk_x = divup(srch.info.dims[0], THREADS_X); dim_type blk_y = divup(srch.info.dims[1], THREADS_Y); NDRange global(blk_x * srch.info.dims[2] * THREADS_X, blk_y * THREADS_Y); auto matchImgOp = make_kernel<Buffer, KParam, Buffer, KParam, Buffer, KParam, dim_type> (*mtKernels[device]); matchImgOp(EnqueueArgs(getQueue(), global, local), *out.data, out.info, *srch.data, srch.info, *tmplt.data, tmplt.info, blk_x); CL_DEBUG_FINISH(getQueue()); } catch (cl::Error err) { CL_TO_AF_ERROR(err); throw; } } } }
0x0all/arrayfire
src/backend/opencl/kernel/match_template.hpp
C++
bsd-3-clause
3,203
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('hhlregistrations', '0004_auto_20150411_1935'), ] operations = [ migrations.AddField( model_name='event', name='payment_due', field=models.DateTimeField(null=True, blank=True), ), migrations.AddField( model_name='event', name='require_registration', field=models.BooleanField(default=False), ), ]
hacklab-fi/hhlevents
hhlevents/apps/hhlregistrations/migrations/0005_auto_20150412_1806.py
Python
bsd-3-clause
592
<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @package Zend_Mail */ namespace Zend\Mail\Storage; use Zend\Stdlib\ErrorHandler; /** * @category Zend * @package Zend_Mail */ class Message extends Part implements Message\MessageInterface { /** * flags for this message * @var array */ protected $flags = array(); /** * Public constructor * * In addition to the parameters of Part::__construct() this constructor supports: * - file filename or file handle of a file with raw message content * - flags array with flags for message, keys are ignored, use constants defined in \Zend\Mail\Storage * * @param array $params * @throws Exception\RuntimeException */ public function __construct(array $params) { if (isset($params['file'])) { if (!is_resource($params['file'])) { ErrorHandler::start(); $params['raw'] = file_get_contents($params['file']); $error = ErrorHandler::stop(); if ($params['raw'] === false) { throw new Exception\RuntimeException('could not open file', 0, $error); } } else { $params['raw'] = stream_get_contents($params['file']); } } if (!empty($params['flags'])) { // set key and value to the same value for easy lookup $this->flags = array_combine($params['flags'], $params['flags']); } parent::__construct($params); } /** * return toplines as found after headers * * @return string toplines */ public function getTopLines() { return $this->topLines; } /** * check if flag is set * * @param mixed $flag a flag name, use constants defined in \Zend\Mail\Storage * @return bool true if set, otherwise false */ public function hasFlag($flag) { return isset($this->flags[$flag]); } /** * get all set flags * * @return array array with flags, key and value are the same for easy lookup */ public function getFlags() { return $this->flags; } }
gustavoeidt/ceranium
vendor/zendframework/zendframework/library/Zend/Mail/Storage/Message.php
PHP
bsd-3-clause
2,562
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. #include "go.h" /// uses arithmetic int mpcmpfixflt(Mpint *a, Mpflt *b) { char buf[500]; Mpflt c; snprint(buf, sizeof(buf), "%B", a); mpatoflt(&c, buf); return mpcmpfltflt(&c, b); } int mpcmpfltfix(Mpflt *a, Mpint *b) { char buf[500]; Mpflt c; snprint(buf, sizeof(buf), "%B", b); mpatoflt(&c, buf); return mpcmpfltflt(a, &c); } int mpcmpfixfix(Mpint *a, Mpint *b) { Mpint c; mpmovefixfix(&c, a); mpsubfixfix(&c, b); return mptestfix(&c); } int mpcmpfixc(Mpint *b, vlong c) { Mpint a; mpmovecfix(&a, c); return mpcmpfixfix(&a, b); } int mpcmpfltflt(Mpflt *a, Mpflt *b) { Mpflt c; mpmovefltflt(&c, a); mpsubfltflt(&c, b); return mptestflt(&c); } int mpcmpfltc(Mpflt *b, double c) { Mpflt a; mpmovecflt(&a, c); return mpcmpfltflt(&a, b); } void mpsubfixfix(Mpint *a, Mpint *b) { mpnegfix(a); mpaddfixfix(a, b); mpnegfix(a); } void mpsubfltflt(Mpflt *a, Mpflt *b) { mpnegflt(a); mpaddfltflt(a, b); mpnegflt(a); } void mpaddcfix(Mpint *a, vlong c) { Mpint b; mpmovecfix(&b, c); mpaddfixfix(a, &b); } void mpaddcflt(Mpflt *a, double c) { Mpflt b; mpmovecflt(&b, c); mpaddfltflt(a, &b); } void mpmulcfix(Mpint *a, vlong c) { Mpint b; mpmovecfix(&b, c); mpmulfixfix(a, &b); } void mpmulcflt(Mpflt *a, double c) { Mpflt b; mpmovecflt(&b, c); mpmulfltflt(a, &b); } void mpdivfixfix(Mpint *a, Mpint *b) { Mpint q, r; mpdivmodfixfix(&q, &r, a, b); mpmovefixfix(a, &q); } void mpmodfixfix(Mpint *a, Mpint *b) { Mpint q, r; mpdivmodfixfix(&q, &r, a, b); mpmovefixfix(a, &r); } void mpcomfix(Mpint *a) { Mpint b; mpmovecfix(&b, 1); mpnegfix(a); mpsubfixfix(a, &b); } void mpmovefixflt(Mpflt *a, Mpint *b) { a->val = *b; a->exp = 0; mpnorm(a); } // convert (truncate) b to a. // return -1 (but still convert) if b was non-integer. int mpmovefltfix(Mpint *a, Mpflt *b) { Mpflt f; *a = b->val; mpshiftfix(a, b->exp); if(b->exp < 0) { f.val = *a; f.exp = 0; mpnorm(&f); if(mpcmpfltflt(b, &f) != 0) return -1; } return 0; } void mpmovefixfix(Mpint *a, Mpint *b) { *a = *b; } void mpmovefltflt(Mpflt *a, Mpflt *b) { *a = *b; } static double tab[] = { 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7 }; static void mppow10flt(Mpflt *a, int p) { if(p < nelem(tab)) { mpmovecflt(a, tab[p]); return; } mppow10flt(a, p>>1); mpmulfltflt(a, a); if(p & 1) mpmulcflt(a, 10); } // // floating point input // required syntax is [+-]d*[.]d*[e[+-]d*] // void mpatoflt(Mpflt *a, char *as) { Mpflt b; int dp, c, f, ef, ex, eb, zer; char *s; s = as; dp = 0; /* digits after decimal point */ f = 0; /* sign */ ex = 0; /* exponent */ eb = 0; /* binary point */ zer = 1; /* zero */ mpmovecflt(a, 0.0); for(;;) { switch(c = *s++) { default: goto bad; case '-': f = 1; case ' ': case '\t': case '+': continue; case '.': dp = 1; continue; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': zer = 0; case '0': mpmulcflt(a, 10); mpaddcflt(a, c-'0'); if(dp) dp++; continue; case 'P': case 'p': eb = 1; case 'E': case 'e': ex = 0; ef = 0; for(;;) { c = *s++; if(c == '+' || c == ' ' || c == '\t') continue; if(c == '-') { ef = 1; continue; } if(c >= '0' && c <= '9') { ex = ex*10 + (c-'0'); continue; } break; } if(ef) ex = -ex; case 0: break; } break; } if(eb) { if(dp) goto bad; a->exp += ex; goto out; } if(dp) dp--; if(mpcmpfltc(a, 0.0) != 0) { if(ex >= dp) { mppow10flt(&b, ex-dp); mpmulfltflt(a, &b); } else { mppow10flt(&b, dp-ex); mpdivfltflt(a, &b); } } out: if(f) mpnegflt(a); return; bad: yyerror("set ovf in mpatof"); mpmovecflt(a, 0.0); } // // fixed point input // required syntax is [+-][0[x]]d* // void mpatofix(Mpint *a, char *as) { int c, f; char *s; s = as; f = 0; mpmovecfix(a, 0); c = *s++; switch(c) { case '-': f = 1; case '+': c = *s++; if(c != '0') break; case '0': goto oct; } while(c) { if(c >= '0' && c <= '9') { mpmulcfix(a, 10); mpaddcfix(a, c-'0'); c = *s++; continue; } goto bad; } goto out; oct: c = *s++; if(c == 'x' || c == 'X') goto hex; while(c) { if(c >= '0' && c <= '7') { mpmulcfix(a, 8); mpaddcfix(a, c-'0'); c = *s++; continue; } goto bad; } goto out; hex: c = *s++; while(c) { if(c >= '0' && c <= '9') { mpmulcfix(a, 16); mpaddcfix(a, c-'0'); c = *s++; continue; } if(c >= 'a' && c <= 'f') { mpmulcfix(a, 16); mpaddcfix(a, c+10-'a'); c = *s++; continue; } if(c >= 'A' && c <= 'F') { mpmulcfix(a, 16); mpaddcfix(a, c+10-'A'); c = *s++; continue; } goto bad; } out: if(f) mpnegfix(a); return; bad: yyerror("set ovf in mpatov: %s", as); mpmovecfix(a, 0); } int Bconv(Fmt *fp) { char buf[500], *p; Mpint *xval, q, r, ten; int f; xval = va_arg(fp->args, Mpint*); mpmovefixfix(&q, xval); f = 0; if(mptestfix(&q) < 0) { f = 1; mpnegfix(&q); } mpmovecfix(&ten, 10); p = &buf[sizeof(buf)]; *--p = 0; for(;;) { mpdivmodfixfix(&q, &r, &q, &ten); *--p = mpgetfix(&r) + '0'; if(mptestfix(&q) <= 0) break; } if(f) *--p = '-'; return fmtstrcpy(fp, p); } int Fconv(Fmt *fp) { char buf[500]; Mpflt *fvp, fv; double d; fvp = va_arg(fp->args, Mpflt*); if(fp->flags & FmtSharp) { // alternate form - decimal for error messages. // for well in range, convert to double and use print's %g if(-900 < fvp->exp && fvp->exp < 900) { d = mpgetflt(fvp); return fmtprint(fp, "%g", d); } // TODO(rsc): for well out of range, print // an approximation like 1.234e1000 } if(sigfig(fvp) == 0) { snprint(buf, sizeof(buf), "0p+0"); goto out; } fv = *fvp; while(fv.val.a[0] == 0) { mpshiftfix(&fv.val, -Mpscale); fv.exp += Mpscale; } while((fv.val.a[0]&1) == 0) { mpshiftfix(&fv.val, -1); fv.exp += 1; } if(fv.exp >= 0) { snprint(buf, sizeof(buf), "%Bp+%d", &fv.val, fv.exp); goto out; } snprint(buf, sizeof(buf), "%Bp-%d", &fv.val, -fv.exp); out: return fmtstrcpy(fp, buf); }
8l/go-learn
src/cmd/gc/mparith1.c
C
bsd-3-clause
6,306
var fs = require("fs"); var path = require("path"); var util = require("util"); var cssParse = require("css-parse"); var cssStringify = require("css-stringify"); var parseString = require("plist").parseString; function parseTheme(themeXml, callback) { parseString(themeXml, function(_, theme) { callback(theme[0]) }); } var unsupportedScopes = { }; var supportedScopes = { "keyword": "keyword", "keyword.operator": "keyword.operator", "keyword.other.unit": "keyword.other.unit", "constant": "constant", "constant.language": "constant.language", "constant.library": "constant.library", "constant.numeric": "constant.numeric", "constant.character" : "constant.character", "constant.character.escape" : "constant.character.escape", "constant.character.entity": "constant.character.entity", "constant.other" : "constant.other", "support": "support", "support.function": "support.function", "support.function.dom": "support.function.dom", "support.function.firebug": "support.firebug", "support.function.constant": "support.function.constant", "support.constant": "support.constant", "support.constant.property-value": "support.constant.property-value", "support.class": "support.class", "support.type": "support.type", "support.other": "support.other", "function": "function", "function.buildin": "function.buildin", "storage": "storage", "storage.type": "storage.type", "invalid": "invalid", "invalid.illegal": "invalid.illegal", "invalid.deprecated": "invalid.deprecated", "string": "string", "string.regexp": "string.regexp", "comment": "comment", "comment.documentation": "comment.doc", "comment.documentation.tag": "comment.doc.tag", "variable": "variable", "variable.language": "variable.language", "variable.parameter": "variable.parameter", "meta": "meta", "meta.tag.sgml.doctype": "xml-pe", "meta.tag": "meta.tag", "meta.selector": "meta.selector", "entity.other.attribute-name": "entity.other.attribute-name", "entity.name.function": "entity.name.function", "entity.name": "entity.name", "entity.name.tag": "entity.name.tag", "markup.heading": "markup.heading", "markup.heading.1": "markup.heading.1", "markup.heading.2": "markup.heading.2", "markup.heading.3": "markup.heading.3", "markup.heading.4": "markup.heading.4", "markup.heading.5": "markup.heading.5", "markup.heading.6": "markup.heading.6", "markup.list": "markup.list", "collab.user1": "collab.user1" }; var fallbackScopes = { "keyword": "meta", "support.type": "storage.type", "variable": "entity.name.function" }; function extractStyles(theme) { var globalSettings = theme.settings[0].settings; var colors = { "printMargin": "#e8e8e8", "background": parseColor(globalSettings.background), "foreground": parseColor(globalSettings.foreground), "gutter": "#e8e8e8", "selection": parseColor(globalSettings.selection), "step": "rgb(198, 219, 174)", "bracket": parseColor(globalSettings.invisibles), "active_line": parseColor(globalSettings.lineHighlight), "cursor": parseColor(globalSettings.caret), "invisible": "color: " + parseColor(globalSettings.invisibles) + ";" }; for (var i=1; i<theme.settings.length; i++) { var element = theme.settings[i]; if (!element.scope) continue; var scopes = element.scope.split(/\s*[|,]\s*/g); for (var j = 0; j < scopes.length; j++) { var scope = scopes[j]; var style = parseStyles(element.settings); var aceScope = supportedScopes[scope]; if (aceScope) { colors[aceScope] = style; } else if (style) { unsupportedScopes[scope] = (unsupportedScopes[scope] || 0) + 1; } } } for (var i in fallbackScopes) { if (!colors[i]) colors[i] = colors[fallbackScopes[i]]; } if (!colors.fold) { var foldSource = colors["entity.name.function"] || colors.keyword; if (foldSource) { colors.fold = foldSource.match(/\:([^;]+)/)[1]; } } colors.gutterBg = colors.background colors.gutterFg = mix(colors.foreground, colors.background, 0.5) if (!colors.selected_word_highlight) colors.selected_word_highlight = "border: 1px solid " + colors.selection + ";"; colors.isDark = (luma(colors.background) < 0.5) + ""; return colors; }; function mix(c1, c2, a1, a2) { c1 = rgbColor(c1); c2 = rgbColor(c2); if (a2 === undefined) a2 = 1 - a1 return "rgb(" + [ Math.round(a1*c1[0] + a2*c2[0]), Math.round(a1*c1[1] + a2*c2[1]), Math.round(a1*c1[2] + a2*c2[2]) ].join(",") + ")"; } function rgbColor(color) { if (typeof color == "object") return color; if (color[0]=="#") return color.match(/^#(..)(..)(..)/).slice(1).map(function(c) { return parseInt(c, 16); }); else return color.match(/\(([^,]+),([^,]+),([^,]+)/).slice(1).map(function(c) { return parseInt(c, 10); }); } function luma(color) { var rgb = rgbColor(color); return (0.21 * rgb[0] + 0.72 * rgb[1] + 0.07 * rgb[2]) / 255; } function parseColor(color) { if (color.length == 4) color = color.replace(/[a-fA-F\d]/g, "$&$&"); if (color.length == 7) return color; else { if (!color.match(/^#(..)(..)(..)(..)$/)) console.error("can't parse color", color); var rgba = color.match(/^#(..)(..)(..)(..)$/).slice(1).map(function(c) { return parseInt(c, 16); }); rgba[3] = (rgba[3] / 0xFF).toPrecision(2); return "rgba(" + rgba.join(", ") + ")"; } } function parseStyles(styles) { var css = []; var fontStyle = styles.fontStyle || ""; if (fontStyle.indexOf("underline") !== -1) { css.push("text-decoration:underline;"); } if (fontStyle.indexOf("italic") !== -1) { css.push("font-style:italic;"); } if (styles.foreground) { css.push("color:" + parseColor(styles.foreground) + ";"); } if (styles.background) { css.push("background-color:" + parseColor(styles.background) + ";"); } return css.join("\n"); } function fillTemplate(template, replacements) { return template.replace(/%(.+?)%/g, function(str, m) { return replacements[m] || ""; }); } function hyphenate(str) { return str.replace(/([A-Z])/g, "-$1").replace(/_/g, "-").toLowerCase(); } function quoteString(str) { return '"' + str.replace(/\\/, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\\n") + '"'; } var cssTemplate = fs.readFileSync(__dirname + "/templates/theme.css", "utf8"); var jsTemplate = fs.readFileSync(__dirname + "/templates/theme.js", "utf8"); function normalizeStylesheet(rules) { for (var i = rules.length; i--; ) { var s = JSON.stringify(rules[i].declarations); for (var j = i; j --; ) { if (s == JSON.stringify(rules[j].declarations)) { console.log(rules[j].selectors, rules[i].selectors) console.log(i, j) rules[j].selectors = rules[i].selectors.concat(rules[j].selectors); rules.splice(i, 1); break; } } } for (var i = rules.length; i--; ) { var s = rules[i].selectors.sort(); rules[i].selectors = s.filter(function(x, i) { return x && x != s[i + 1]; }); } return rules; } var themes = { //"chrome": "Chrome DevTools", "clouds": "Clouds", "clouds_midnight": "Clouds Midnight", "cobalt": "Cobalt", //"crimson_editor": "Crimson Editor", "dawn": "Dawn", //"dreamweaver": "Dreamweaver", //"eclipse": "Eclipse", //"github": "GitHub", "idle_fingers": "idleFingers", "kr_theme": "krTheme", "merbivore": "Merbivore", "merbivore_soft": "Merbivore Soft", "mono_industrial": "monoindustrial", "monokai": "Monokai", "pastel_on_dark": "Pastels on Dark", "solarized_dark": "Solarized-dark", "solarized_light": "Solarized-light", "katzenmilch": "Katzenmilch", "kuroir": "Kuroir Theme", //"textmate": "Textmate (Mac Classic)", "tomorrow": "Tomorrow", "tomorrow_night": "Tomorrow-Night", "tomorrow_night_blue": "Tomorrow-Night-Blue", "tomorrow_night_bright": "Tomorrow-Night-Bright", "tomorrow_night_eighties": "Tomorrow-Night-Eighties", "twilight": "Twilight", "vibrant_ink": "Vibrant Ink", "xcode": "Xcode_default" }; function convertTheme(name) { console.log("Converting " + name); var tmTheme = fs.readFileSync(__dirname + "/tmthemes/" + themes[name] + ".tmTheme", "utf8"); parseTheme(tmTheme, function(theme) { var styles = extractStyles(theme); styles.cssClass = "ace-" + hyphenate(name); styles.uuid = theme.uuid; var css = fillTemplate(cssTemplate, styles); css = css.replace(/[^\{\}]+{\s*}/g, ""); for (var i in supportedScopes) { if (!styles[i]) continue; css += "." + styles.cssClass + " " + i.replace(/^|\./g, ".ace_") + "{" + styles[i] + "}"; } // we're going to look for NEW rules in the parsed content only // if such a rule exists, add it to the destination file // this way, we preserve all hand-modified rules in the <theme>.css rules, // (because some exist, for collab1 and ace_indentation_guide try { var outThemeCss = fs.readFileSync(__dirname + "/../lib/ace/theme/" + name + ".css"); var oldRules = cssParse(outThemeCss).stylesheet.rules; var newRules = cssParse(css).stylesheet.rules; for (var i = 0; i < newRules.length; i++) { var newSelectors = newRules[i].selectors; for (var j = 0; j < oldRules.length; j++) { var oldSelectors = oldRules[j].selectors; newSelectors = newSelectors.filter(function(s) { return oldSelectors.indexOf(s) == -1; }) if (!newSelectors.length) break; } if (newSelectors.length) { newRules[i].selectors = newSelectors; console.log("Adding NEW rule: ", newRules[i]) oldRules.splice(i, 0, newRules[i]); } } oldRules = normalizeStylesheet(oldRules); css = cssStringify({stylesheet: {rules: oldRules}}, { compress: false }); } catch(e) { console.log("Creating new file: " + name + ".css") } var js = fillTemplate(jsTemplate, { name: name, css: 'require("../requirejs/text!./' + name + '.css")', // quoteString(css), // cssClass: "ace-" + hyphenate(name), isDark: styles.isDark }); fs.writeFileSync(__dirname + "/../lib/ace/theme/" + name + ".js", js); fs.writeFileSync(__dirname + "/../lib/ace/theme/" + name + ".css", css); }) } for (var name in themes) { convertTheme(name); } var sortedUnsupportedScopes = {}; for (var u in unsupportedScopes) { var value = unsupportedScopes[u]; if (sortedUnsupportedScopes[value] === undefined) { sortedUnsupportedScopes[value] = []; } sortedUnsupportedScopes[value].push(u); } console.log("I found these unsupported scopes:"); console.log(sortedUnsupportedScopes); console.log("It's safe to ignore these, but they may affect your syntax highlighting if your mode depends on any of these rules."); console.log("Refer to the docs on ace.ajax.org for information on how to add a scope to the CSS generator."); /*** TODO: generate images for indent guides in node var indentGuideColor = "#2D2D2D" var canvas = document.createElement("canvas") canvas.width = 1; canvas.height = 2; var ctx = canvas.getContext("2d") imageData = ctx.getImageData(0,0,1,2) function getColor(color) { ctx.fillStyle = color; ctx.fillRect(0,0,1,2); return Array.slice(ctx.getImageData(0,0,1,2).data).slice(0,4) } bgColor = getComputedStyle(ace.renderer.scroller).backgroundColor var a = [].concat(getColor(bgColor), getColor(indentGuideColor)); a.forEach(function(val,i){imageData.data[i] = val}) ctx.putImageData(imageData,0,0) image = canvas.toDataURL("png") var rule = "."+ace.renderer.$theme +" .ace_indent-guide {\n\ background: url(" + image +") right repeat-y;\n\ }" console.log(rule) require("ace/lib/dom").importCssString(rule) */
ezoapp/aceeditor
tool/tmtheme.js
JavaScript
bsd-3-clause
12,884
using System.Data; using Orchard.Data.Migration; using Orchard.ContentManagement.MetaData; using Orchard.Core.Contents.Extensions; using Orchard.Indexing; using oforms.Models; namespace oforms { public class Migrations : DataMigrationImpl { public int Create() { // Creating table OFormPartRecord SchemaBuilder.CreateTable("OFormPartRecord", table => table .ContentPartRecord() .Column("Name", DbType.String, x => x.Unique()) .Column("Method", DbType.String) .Column("InnerHtml", DbType.String) .Column("Action", DbType.String) .Column("RedirectUrl", DbType.String) .Column("CanUploadFiles", DbType.Boolean) .Column("UploadFileSizeLimit", DbType.Int64) .Column("UploadFileType", DbType.String) .Column("UseCaptcha", DbType.Boolean) .Column("SendEmail", DbType.Boolean) .Column("EmailFromName", DbType.String) .Column("EmailFrom", DbType.String) .Column("EmailSubject", DbType.String) .Column("EmailSendTo", DbType.String) .Column("EmailTemplate", DbType.String) ); return 1; } public int UpdateFrom1() { SchemaBuilder.AlterTable("OFormPartRecord", table => { table.AddColumn("SaveResultsToDB", DbType.Boolean); table.AddColumn("ValRequiredFields", DbType.String); table.AddColumn("ValNumbersOnly", DbType.String); table.AddColumn("ValLettersOnly", DbType.String); table.AddColumn("ValLettersAndNumbersOnly", DbType.String); table.AddColumn("ValDate", DbType.String); table.AddColumn("ValEmail", DbType.String); table.AddColumn("ValUrl", DbType.String); } ); return 2; } public int UpdateFrom2() { SchemaBuilder.AlterTable("OFormPartRecord", table => { table.AlterColumn("InnerHtml", x => x.WithType(DbType.String).Unlimited()); table.AlterColumn("EmailTemplate", x => x.WithType(DbType.String).Unlimited()); } ); return 3; } public int UpdateFrom3() { SchemaBuilder.CreateTable("OFormResultRecord", table => table .Column<int>("Id", x => x.PrimaryKey().Identity()) .Column<string>("Xml", x => x.Unlimited()) .Column<int>("OFormPartRecord_Id") ); return 4; } public int UpdateFrom4() { SchemaBuilder.AlterTable("OFormResultRecord", table => { table.AddColumn("CreatedDate", DbType.DateTime); table.AddColumn("Ip", DbType.String); } ); return 5; } public int UpdateFrom5() { SchemaBuilder.AlterTable("OFormPartRecord", table => { table.AlterColumn("ValRequiredFields", x => x.WithType(DbType.String).WithLength(800)); table.AlterColumn("ValNumbersOnly", x => x.WithType(DbType.String).WithLength(800)); table.AlterColumn("ValLettersOnly", x => x.WithType(DbType.String).WithLength(800)); table.AlterColumn("ValLettersAndNumbersOnly", x => x.WithType(DbType.String).WithLength(800)); table.AlterColumn("ValDate", x => x.WithType(DbType.String).WithLength(800)); table.AlterColumn("ValEmail", x => x.WithType(DbType.String).WithLength(800)); table.AlterColumn("ValUrl", x => x.WithType(DbType.String).WithLength(800)); } ); return 6; } public int UpdateFrom6() { SchemaBuilder.CreateTable("OFormFileRecord", table => { table.Column<int>("Id", x => x.PrimaryKey().Identity()); table.Column<int>("OFormResultRecord_Id"); table.Column<string>("FieldName"); table.Column<string>("OriginalName"); table.Column<string>("ContentType"); table.Column<byte[]>("Bytes", x => x.WithType(DbType.Binary).Unlimited()); table.Column<long>("Size"); } ); return 7; } public int UpdateFrom7() { SchemaBuilder.AlterTable("OFormResultRecord", table => { table.AddColumn<string>("CreatedBy"); } ); SchemaBuilder.AlterTable("OFormPartRecord", table => { table.AddColumn<string>("SuccessMessage", x => x.WithType(DbType.String).WithLength(500) .WithDefault("Form submitted successfully")); } ); return 8; } public int UpdateFrom8() { ContentDefinitionManager.AlterPartDefinition(typeof(OFormPart).Name, cfg => cfg.Attachable()); ContentDefinitionManager.AlterTypeDefinition("OForm", cfg => cfg .WithPart(typeof(OFormPart).Name) .WithPart("TitlePart") .WithPart("AutoroutePart", builder => builder .WithSetting("AutorouteSettings.AllowCustomPattern", "true") .WithSetting("AutorouteSettings.AutomaticAdjustmentOnEdit", "false") .WithSetting("AutorouteSettings.PatternDefinitions", "[{Name:'Title', Pattern: '{Content.Slug}', Description: 'my-from'}]") .WithSetting("AutorouteSettings.DefaultPatternIndex", "0")) .WithPart("MenuPart")); return 9; } public int UpdateFrom9() { ContentDefinitionManager.AlterTypeDefinition("OFormWidget", cfg => cfg .WithPart(typeof(OFormPart).Name) .WithPart("WidgetPart") .WithPart("CommonPart") .WithSetting("Stereotype", "Widget")); return 10; } public int UpdateFrom10() { SchemaBuilder.AlterTable("OFormPartRecord", table => { table.AddColumn<string>("Target"); } ); return 11; } public int UpdateFrom11() { SchemaBuilder.CreateTable("OFormSettingsPartRecord", table => table.ContentPartRecord() .Column<string>("SerialKey") ); return 12; } } }
dminik/voda_code
src/packages/Orchard.Module.oforms.1.9.1/Content/Modules/oforms/Migrations.cs
C#
bsd-3-clause
7,099
/* * Copyright (C) 2009 Google Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 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. * * THIS SOFTWARE IS PROVIDED BY GOOGLE INC. ``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 GOOGLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "modules/storage/StorageNamespace.h" #include "modules/storage/StorageArea.h" #include "platform/weborigin/SecurityOrigin.h" #include "public/platform/Platform.h" #include "public/platform/WebStorageArea.h" #include "public/platform/WebStorageNamespace.h" namespace blink { StorageNamespace::StorageNamespace(PassOwnPtr<WebStorageNamespace> webStorageNamespace) : m_webStorageNamespace(std::move(webStorageNamespace)) { } StorageNamespace::~StorageNamespace() { } StorageArea* StorageNamespace::localStorageArea(SecurityOrigin* origin) { ASSERT(isMainThread()); static WebStorageNamespace* localStorageNamespace = nullptr; if (!localStorageNamespace) localStorageNamespace = Platform::current()->createLocalStorageNamespace(); return StorageArea::create(adoptPtr(localStorageNamespace->createStorageArea(origin->toString())), LocalStorage); } StorageArea* StorageNamespace::storageArea(SecurityOrigin* origin) { return StorageArea::create(adoptPtr(m_webStorageNamespace->createStorageArea(origin->toString())), SessionStorage); } bool StorageNamespace::isSameNamespace(const WebStorageNamespace& sessionNamespace) const { return m_webStorageNamespace && m_webStorageNamespace->isSameNamespace(sessionNamespace); } } // namespace blink
axinging/chromium-crosswalk
third_party/WebKit/Source/modules/storage/StorageNamespace.cpp
C++
bsd-3-clause
2,623
// SDLECallInfo.h // #import "SDLRPCMessage.h" @class SDLVehicleDataNotificationStatus; @class SDLECallConfirmationStatus; @interface SDLECallInfo : SDLRPCStruct { } - (instancetype)init; - (instancetype)initWithDictionary:(NSMutableDictionary *)dict; @property (strong) SDLVehicleDataNotificationStatus *eCallNotificationStatus; @property (strong) SDLVehicleDataNotificationStatus *auxECallNotificationStatus; @property (strong) SDLECallConfirmationStatus *eCallConfirmationStatus; @end
davidswi/sdl_ios
SmartDeviceLink/SDLECallInfo.h
C
bsd-3-clause
496
// Copyright (c) 2011 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_WINDOW_SIZER_H_ #define CHROME_BROWSER_UI_WINDOW_SIZER_H_ #pragma once #include "base/basictypes.h" #include "base/memory/scoped_ptr.h" #include "ui/gfx/rect.h" class Browser; // An interface implemented by an object that can retrieve information about // the monitors on the system. class MonitorInfoProvider { public: virtual ~MonitorInfoProvider() {} // Returns the bounds of the work area of the primary monitor. virtual gfx::Rect GetPrimaryMonitorWorkArea() const = 0; // Returns the bounds of the primary monitor. virtual gfx::Rect GetPrimaryMonitorBounds() const = 0; // Returns the bounds of the work area of the monitor that most closely // intersects the provided bounds. virtual gfx::Rect GetMonitorWorkAreaMatching( const gfx::Rect& match_rect) const = 0; }; /////////////////////////////////////////////////////////////////////////////// // WindowSizer // // A class that determines the best new size and position for a window to be // shown at based several factors, including the position and size of the last // window of the same type, the last saved bounds of the window from the // previous session, and default system metrics if neither of the above two // conditions exist. The system has built-in providers for monitor metrics // and persistent storage (using preferences) but can be overrided with mocks // for testing. // class WindowSizer { public: class StateProvider; // WindowSizer owns |state_provider| and will create a default // MonitorInfoProvider using the physical screen. explicit WindowSizer(StateProvider* state_provider); // WindowSizer owns |state_provider| and |monitor_info_provider|. // It will use the supplied monitor info provider. Used only for testing. WindowSizer(StateProvider* state_provider, MonitorInfoProvider* monitor_info_provider); virtual ~WindowSizer(); // An interface implemented by an object that can retrieve state from either a // persistent store or an existing window. class StateProvider { public: virtual ~StateProvider() {} // Retrieve the persisted bounds of the window. Returns true if there was // persisted data to retrieve state information, false otherwise. virtual bool GetPersistentState(gfx::Rect* bounds, gfx::Rect* work_area) const = 0; // Retrieve the bounds of the most recent window of the matching type. // Returns true if there was a last active window to retrieve state // information from, false otherwise. virtual bool GetLastActiveWindowState(gfx::Rect* bounds) const = 0; }; // Determines the position and size for a window as it is created. This // function uses several strategies to figure out optimal size and placement, // first looking for an existing active window, then falling back to persisted // data from a previous session, finally utilizing a default // algorithm. If |specified_bounds| are non-empty, this value is returned // instead. For use only in testing. void DetermineWindowBounds(const gfx::Rect& specified_bounds, gfx::Rect* bounds) const; // Determines the size, position and maximized state for the browser window. // See documentation for DetermineWindowBounds above. Normally, // |window_bounds| is calculated by calling GetLastActiveWindowState(). To // explicitly specify a particular window to base the bounds on, pass in a // non-NULL value for |browser|. static void GetBrowserWindowBounds(const std::string& app_name, const gfx::Rect& specified_bounds, const Browser* browser, gfx::Rect* window_bounds); // Returns the default origin for popups of the given size. static gfx::Point GetDefaultPopupOrigin(const gfx::Size& size); // How much horizontal and vertical offset there is between newly // opened windows. This value may be different on each platform. static const int kWindowTilePixels; private: // The edge of the screen to check for out-of-bounds. enum Edge { TOP, LEFT, BOTTOM, RIGHT }; // Gets the size and placement of the last window. Returns true if this data // is valid, false if there is no last window and the application should // restore saved state from preferences using RestoreWindowPosition. bool GetLastWindowBounds(gfx::Rect* bounds) const; // Gets the size and placement of the last window in the last session, saved // in local state preferences. Returns true if local state exists containing // this information, false if this information does not exist and a default // size should be used. bool GetSavedWindowBounds(gfx::Rect* bounds) const; // Gets the default window position and size if there is no last window and // no saved window placement in prefs. This function determines the default // size based on monitor size, etc. void GetDefaultWindowBounds(gfx::Rect* default_bounds) const; // Adjusts |bounds| to be visible onscreen, biased toward the work area of the // monitor containing |other_bounds|. Despite the name, this doesn't // guarantee the bounds are fully contained within this monitor's work rect; // it just tried to ensure the edges are visible on _some_ work rect. // If |saved_work_area| is non-empty, it is used to determine whether the // monitor cofiguration has changed. If it has, bounds are repositioned and // resized if necessary to make them completely contained in the current work // area. void AdjustBoundsToBeVisibleOnMonitorContaining( const gfx::Rect& other_bounds, const gfx::Rect& saved_work_area, gfx::Rect* bounds) const; // Providers for persistent storage and monitor metrics. scoped_ptr<StateProvider> state_provider_; scoped_ptr<MonitorInfoProvider> monitor_info_provider_; DISALLOW_COPY_AND_ASSIGN(WindowSizer); }; #endif // CHROME_BROWSER_UI_WINDOW_SIZER_H_
aYukiSekiguchi/ACCESS-Chromium
chrome/browser/ui/window_sizer.h
C
bsd-3-clause
6,177
# Copyright 2015 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. from tracing.mre import job as job_module class Failure(object): def __init__(self, job, function_handle_string, trace_canonical_url, failure_type_name, description, stack): assert isinstance(job, job_module.Job) self.job = job self.function_handle_string = function_handle_string self.trace_canonical_url = trace_canonical_url self.failure_type_name = failure_type_name self.description = description self.stack = stack def __str__(self): return ( 'Failure for job %s with function handle %s and trace handle %s:\n' 'of type "%s" with description "%s". Stack:\n\n%s' % ( self.job.guid, self.function_handle_string, self.trace_canonical_url, self.failure_type_name, self.description, self.stack)) def AsDict(self): return { 'job_guid': str(self.job.guid), 'function_handle_string': self.function_handle_string, 'trace_canonical_url': self.trace_canonical_url, 'type': self.failure_type_name, 'description': self.description, 'stack': self.stack } @staticmethod def FromDict(failure_dict, job, failure_names_to_constructors=None): if failure_names_to_constructors is None: failure_names_to_constructors = {} failure_type_name = failure_dict['type'] if failure_type_name in failure_names_to_constructors: cls = failure_names_to_constructors[failure_type_name] else: cls = Failure return cls(job, failure_dict['function_handle_string'], failure_dict['trace_canonical_url'], failure_type_name, failure_dict['description'], failure_dict['stack'])
catapult-project/catapult
tracing/tracing/mre/failure.py
Python
bsd-3-clause
1,876
package org.broadinstitute.hellbender.tools.spark.sv.discovery.alignment; import htsjdk.samtools.Cigar; import htsjdk.samtools.CigarElement; import htsjdk.samtools.CigarOperator; import htsjdk.samtools.TextCigarCodec; import org.broadinstitute.hellbender.GATKBaseTest; import org.broadinstitute.hellbender.exceptions.GATKException; import org.broadinstitute.hellbender.tools.spark.sv.StructuralVariationDiscoveryArgumentCollection; import org.broadinstitute.hellbender.tools.spark.sv.discovery.TestUtilsForAssemblyBasedSVDiscovery; import org.broadinstitute.hellbender.tools.spark.sv.utils.SvCigarUtils; import org.broadinstitute.hellbender.utils.SimpleInterval; import org.broadinstitute.hellbender.utils.Utils; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import scala.Tuple2; import scala.Tuple3; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import static org.broadinstitute.hellbender.tools.spark.sv.discovery.alignment.AlignmentInterval.NO_AS; import static org.broadinstitute.hellbender.tools.spark.sv.discovery.alignment.AlignmentInterval.NO_NM; public class ContigAlignmentsModifierUnitTest extends GATKBaseTest { @Test(groups = "sv") public void testCompactifyNeighboringSoftClippings() { Assert.assertEquals(new Cigar(SvCigarUtils.compactifyNeighboringSoftClippings(TextCigarCodec.decode("1H2S3S4M5D6M7I8M9S10S11H") .getCigarElements())), TextCigarCodec.decode("1H5S4M5D6M7I8M19S11H")); } @Test(groups = "sv") public void testGappedAlignmentBreaker_OneInsertion() { final Cigar cigar = TextCigarCodec.decode("56S27M15I32M21S"); final AlignmentInterval alignmentInterval = new AlignmentInterval(new SimpleInterval("1", 100, 158), 57, 130, cigar, true, 60, 0, 100, ContigAlignmentsModifier.AlnModType.NONE); final List<AlignmentInterval> generatedARList = Utils.stream(ContigAlignmentsModifier.splitGappedAlignment(alignmentInterval, 1, cigar.getReadLength())).collect(Collectors.toList()); Assert.assertEquals(generatedARList.size(), 2); Assert.assertEquals(generatedARList.get(0), new AlignmentInterval(new SimpleInterval("1", 100, 126), 57, 83, TextCigarCodec.decode("56S27M68S"), true, 60, NO_NM, NO_AS, ContigAlignmentsModifier.AlnModType.FROM_SPLIT_GAPPED_ALIGNMENT)); Assert.assertEquals(generatedARList.get(1), new AlignmentInterval(new SimpleInterval("1", 127, 158), 99, 130, TextCigarCodec.decode("98S32M21S"), true, 60, NO_NM, NO_AS, ContigAlignmentsModifier.AlnModType.FROM_SPLIT_GAPPED_ALIGNMENT)); } @Test(groups = "sv") public void testGappedAlignmentBreaker_OneDeletion() { final Cigar cigar = TextCigarCodec.decode("2S205M2D269M77S"); final AlignmentInterval alignmentInterval = new AlignmentInterval(new SimpleInterval("1", 100, 575), 3, 476, cigar, true, 60, 0, 100, ContigAlignmentsModifier.AlnModType.NONE); final List<AlignmentInterval> generatedARList = Utils.stream(ContigAlignmentsModifier.splitGappedAlignment(alignmentInterval, 1, cigar.getReadLength())).collect(Collectors.toList()); Assert.assertEquals(generatedARList.size(), 2); Assert.assertEquals(generatedARList.get(0), new AlignmentInterval(new SimpleInterval("1", 100, 304), 3, 207, TextCigarCodec.decode("2S205M346S"), true, 60, NO_NM, NO_AS, ContigAlignmentsModifier.AlnModType.FROM_SPLIT_GAPPED_ALIGNMENT)); Assert.assertEquals(generatedARList.get(1), new AlignmentInterval(new SimpleInterval("1", 307, 575), 208, 476, TextCigarCodec.decode("207S269M77S"), true, 60, NO_NM, NO_AS, ContigAlignmentsModifier.AlnModType.FROM_SPLIT_GAPPED_ALIGNMENT)); } @Test(groups = "sv") public void testGappedAlignmentBreaker_Complex() { final Cigar cigar = TextCigarCodec.decode("397S118M2D26M6I50M7I26M1I8M13D72M398S"); final AlignmentInterval alignmentInterval = new AlignmentInterval(new SimpleInterval("1", 100, 414), 398, 711, cigar, true, 60, 65, 100, ContigAlignmentsModifier.AlnModType.NONE); final List<AlignmentInterval> generatedARList = Utils.stream(ContigAlignmentsModifier.splitGappedAlignment(alignmentInterval, 1, cigar.getReadLength())).collect(Collectors.toList()); Assert.assertEquals(generatedARList.size(), 6); Assert.assertEquals(generatedARList.get(0), new AlignmentInterval(new SimpleInterval("1", 100, 217), 398, 515, TextCigarCodec.decode("397S118M594S"), true, 60, NO_NM, NO_AS, ContigAlignmentsModifier.AlnModType.FROM_SPLIT_GAPPED_ALIGNMENT)); Assert.assertEquals(generatedARList.get(1), new AlignmentInterval(new SimpleInterval("1", 220, 245), 516, 541, TextCigarCodec.decode("515S26M568S"), true, 60, NO_NM, NO_AS, ContigAlignmentsModifier.AlnModType.FROM_SPLIT_GAPPED_ALIGNMENT)); Assert.assertEquals(generatedARList.get(2), new AlignmentInterval(new SimpleInterval("1", 246, 295), 548, 597, TextCigarCodec.decode("547S50M512S"), true, 60, NO_NM, NO_AS, ContigAlignmentsModifier.AlnModType.FROM_SPLIT_GAPPED_ALIGNMENT)); Assert.assertEquals(generatedARList.get(3), new AlignmentInterval(new SimpleInterval("1", 296, 321), 605, 630, TextCigarCodec.decode("604S26M479S"), true, 60, NO_NM, NO_AS, ContigAlignmentsModifier.AlnModType.FROM_SPLIT_GAPPED_ALIGNMENT)); Assert.assertEquals(generatedARList.get(4), new AlignmentInterval(new SimpleInterval("1", 322, 329), 632, 639, TextCigarCodec.decode("631S8M470S"), true, 60, NO_NM, NO_AS, ContigAlignmentsModifier.AlnModType.FROM_SPLIT_GAPPED_ALIGNMENT)); Assert.assertEquals(generatedARList.get(5), new AlignmentInterval(new SimpleInterval("1", 343, 414), 640, 711, TextCigarCodec.decode("639S72M398S"), true, 60, NO_NM, NO_AS, ContigAlignmentsModifier.AlnModType.FROM_SPLIT_GAPPED_ALIGNMENT)); } @Test(groups = "sv") public void testGappedAlignmentBreaker_GapSizeSensitivity() { final Cigar cigar = TextCigarCodec.decode("10M10D10M60I10M10I10M50D10M"); final AlignmentInterval alignmentInterval = new AlignmentInterval(new SimpleInterval("1", 100, 209), 1, 120, cigar, true, 60, 0, 100, ContigAlignmentsModifier.AlnModType.NONE); final List<AlignmentInterval> generatedARList = Utils.stream(ContigAlignmentsModifier.splitGappedAlignment(alignmentInterval, StructuralVariationDiscoveryArgumentCollection.DiscoverVariantsFromContigAlignmentsSparkArgumentCollection.GAPPED_ALIGNMENT_BREAK_DEFAULT_SENSITIVITY, cigar.getReadLength())).collect(Collectors.toList()); Assert.assertEquals(generatedARList.size(), 3); Assert.assertEquals(generatedARList.get(0), new AlignmentInterval(new SimpleInterval("1", 100, 129), 1, 20, TextCigarCodec.decode("10M10D10M100S"), true, 60, NO_NM, NO_AS, ContigAlignmentsModifier.AlnModType.FROM_SPLIT_GAPPED_ALIGNMENT)); Assert.assertEquals(generatedARList.get(1), new AlignmentInterval(new SimpleInterval("1", 130, 149), 81, 110, TextCigarCodec.decode("80S10M10I10M10S"), true, 60, NO_NM, NO_AS, ContigAlignmentsModifier.AlnModType.FROM_SPLIT_GAPPED_ALIGNMENT)); Assert.assertEquals(generatedARList.get(2), new AlignmentInterval(new SimpleInterval("1", 200, 209), 111, 120, TextCigarCodec.decode("110S10M"), true, 60, NO_NM, NO_AS, ContigAlignmentsModifier.AlnModType.FROM_SPLIT_GAPPED_ALIGNMENT)); } @Test(groups = "sv") public void testGappedAlignmentBreaker_HardAndSoftClip() { final Cigar cigar = TextCigarCodec.decode("1H2S3M5I10M20D6M7S8H"); final AlignmentInterval alignmentInterval = new AlignmentInterval(new SimpleInterval("1", 100, 138), 4, 27, cigar, true, 60, 0, 100, ContigAlignmentsModifier.AlnModType.NONE); final List<AlignmentInterval> generatedARList = Utils.stream(ContigAlignmentsModifier.splitGappedAlignment(alignmentInterval, 1, cigar.getReadLength()+1+8)).collect(Collectors.toList()); Assert.assertEquals(generatedARList.get(0), new AlignmentInterval(new SimpleInterval("1", 100, 102), 4, 6, TextCigarCodec.decode("1H2S3M28S8H"), true, 60, NO_NM, NO_AS, ContigAlignmentsModifier.AlnModType.FROM_SPLIT_GAPPED_ALIGNMENT)); Assert.assertEquals(generatedARList.get(1), new AlignmentInterval(new SimpleInterval("1", 103, 112), 12, 21, TextCigarCodec.decode("1H10S10M13S8H"), true, 60, NO_NM, NO_AS, ContigAlignmentsModifier.AlnModType.FROM_SPLIT_GAPPED_ALIGNMENT)); Assert.assertEquals(generatedARList.get(2), new AlignmentInterval(new SimpleInterval("1", 133, 138), 22, 27, TextCigarCodec.decode("1H20S6M7S8H"), true, 60, NO_NM, NO_AS, ContigAlignmentsModifier.AlnModType.FROM_SPLIT_GAPPED_ALIGNMENT)); } @Test(groups = "sv") public void testGappedAlignmentBreaker_TerminalInsertionOperatorToSoftClip() { // beginning with 'I' Cigar cigar = TextCigarCodec.decode("10I10M5I10M"); AlignmentInterval alignmentInterval = new AlignmentInterval(new SimpleInterval("1", 101, 120), 11, 35, cigar, true, 60, 0, 100, ContigAlignmentsModifier.AlnModType.NONE); List<AlignmentInterval> generatedARList = Utils.stream(ContigAlignmentsModifier.splitGappedAlignment(alignmentInterval, 1, cigar.getReadLength())).collect(Collectors.toList()); Assert.assertEquals(generatedARList.size(), 2); Assert.assertEquals(generatedARList.get(0), new AlignmentInterval( new SimpleInterval("1", 101, 110), 11, 20, TextCigarCodec.decode("10S10M15S"), true, 60, NO_NM, NO_AS, ContigAlignmentsModifier.AlnModType.FROM_SPLIT_GAPPED_ALIGNMENT)); Assert.assertEquals(generatedARList.get(1), new AlignmentInterval( new SimpleInterval("1", 111, 120), 26, 35, TextCigarCodec.decode("25S10M"), true, 60, NO_NM, NO_AS, ContigAlignmentsModifier.AlnModType.FROM_SPLIT_GAPPED_ALIGNMENT)); // ending with 'I' cigar = TextCigarCodec.decode("10M5I10M10I"); alignmentInterval = new AlignmentInterval( new SimpleInterval("1", 101, 120), 1, 25, cigar, true, 60, 0, 100, ContigAlignmentsModifier.AlnModType.NONE); generatedARList = Utils.stream(ContigAlignmentsModifier.splitGappedAlignment(alignmentInterval, 1, cigar.getReadLength())).collect(Collectors.toList()); Assert.assertEquals(generatedARList.size(), 2); Assert.assertEquals(generatedARList.get(0), new AlignmentInterval( new SimpleInterval("1", 101, 110), 1, 10, TextCigarCodec.decode("10M25S"), true, 60, NO_NM, NO_AS, ContigAlignmentsModifier.AlnModType.FROM_SPLIT_GAPPED_ALIGNMENT)); Assert.assertEquals(generatedARList.get(1), new AlignmentInterval( new SimpleInterval("1", 111, 120), 16, 25, TextCigarCodec.decode("15S10M10S"), true, 60, NO_NM, NO_AS, ContigAlignmentsModifier.AlnModType.FROM_SPLIT_GAPPED_ALIGNMENT)); } @Test(groups = "sv") public void testGappedAlignmentBreaker_TerminalInsertionNeighboringClippings(){ Cigar cigar = TextCigarCodec.decode("10H20S30I40M50I60S70H"); AlignmentInterval alignmentInterval = new AlignmentInterval( new SimpleInterval("1", 101, 140), 61, 100, cigar, true, 60, 0, 100, ContigAlignmentsModifier.AlnModType.NONE); List<AlignmentInterval> generatedARList = Utils.stream(ContigAlignmentsModifier.splitGappedAlignment(alignmentInterval, 1, cigar.getReadLength()+10+70)) .collect(Collectors.toList()); // no internal gap, so nothing should change Assert.assertEquals(generatedARList.size(), 1); Assert.assertEquals(generatedARList.get(0), alignmentInterval); cigar = TextCigarCodec.decode("10H20S30I40M5D15M50I60S70H"); alignmentInterval = new AlignmentInterval( new SimpleInterval("1", 101, 160), 61, 115, cigar, true, 60, 0, 100, ContigAlignmentsModifier.AlnModType.NONE); generatedARList = Utils.stream(ContigAlignmentsModifier.splitGappedAlignment(alignmentInterval, 1, cigar.getReadLength()+10+70)).collect(Collectors.toList()); Assert.assertEquals(generatedARList.size(), 2); Assert.assertEquals(generatedARList.get(0), new AlignmentInterval( new SimpleInterval("1", 101, 140), 61, 100, TextCigarCodec.decode("10H50S40M125S70H"), true, 60, NO_NM, NO_AS, ContigAlignmentsModifier.AlnModType.FROM_SPLIT_GAPPED_ALIGNMENT)); Assert.assertEquals(generatedARList.get(1), new AlignmentInterval( new SimpleInterval("1", 146, 160), 101, 115, TextCigarCodec.decode("10H90S15M110S70H"), true, 60, NO_NM, NO_AS, ContigAlignmentsModifier.AlnModType.FROM_SPLIT_GAPPED_ALIGNMENT)); } @Test(groups = "sv") public void testGappedAlignmentBreaker_NegativeStrand() { // read data with AlignedAssembly.AlignmentInterval.toString(): // 19149 contig-8 chrUn_JTFH01000557v1_decoy 21 1459 - 10S1044M122I395M75I 60 11 1646 200 final Cigar cigar = TextCigarCodec.decode("10S1044M122I395M75I"); final AlignmentInterval alignmentInterval = new AlignmentInterval( new SimpleInterval("chrUn_JTFH01000557v1_decoy", 21, 1459), 11, 1571, cigar, false, 60, 200, 100, ContigAlignmentsModifier.AlnModType.NONE); final List<AlignmentInterval> generatedARList = Utils.stream(ContigAlignmentsModifier.splitGappedAlignment(alignmentInterval, 1, cigar.getReadLength())).collect(Collectors.toList()); Assert.assertEquals(generatedARList.get(0), new AlignmentInterval( new SimpleInterval("chrUn_JTFH01000557v1_decoy", 416, 1459), 11, 1054, TextCigarCodec.decode("10S1044M592S"), false, 60, NO_NM, NO_AS, ContigAlignmentsModifier.AlnModType.FROM_SPLIT_GAPPED_ALIGNMENT)); Assert.assertEquals(generatedARList.get(1), new AlignmentInterval( new SimpleInterval("chrUn_JTFH01000557v1_decoy", 21, 415), 1177, 1571, TextCigarCodec.decode("1176S395M75S"), false, 60, NO_NM, NO_AS, ContigAlignmentsModifier.AlnModType.FROM_SPLIT_GAPPED_ALIGNMENT)); } @Test(groups = "sv") public void testGappedAlignmentBreaker_ExpectException() { int exceptionCount = 0; try {willThrowOnInvalidCigar(TextCigarCodec.decode("10H10D10M"), 11);} catch (final Exception ex) {++exceptionCount;} try {willThrowOnInvalidCigar(TextCigarCodec.decode("10S10D10M"), 11);} catch (final Exception ex) {++exceptionCount;} try {willThrowOnInvalidCigar(TextCigarCodec.decode("10M10D10S"), 1);} catch (final Exception ex) {++exceptionCount;} try {willThrowOnInvalidCigar(TextCigarCodec.decode("10M10D10H"), 1);} catch (final Exception ex) {++exceptionCount;} try{willThrowOnInvalidCigar(TextCigarCodec.decode("10H10I10S"), 11);} catch (final Exception ex) {++exceptionCount;} try{willThrowOnInvalidCigar(TextCigarCodec.decode("10H10D10S"), 21);} catch (final Exception ex) {++exceptionCount;} try{willThrowOnInvalidCigar(TextCigarCodec.decode("10H10I10M10D10S"), 11);} catch (final Exception ex) {++exceptionCount;} try{willThrowOnInvalidCigar(TextCigarCodec.decode("10H10D10M10I10S"), 21);} catch (final Exception ex) {++exceptionCount;} Assert.assertEquals(exceptionCount, 8); } private static Iterable<AlignmentInterval> willThrowOnInvalidCigar(final Cigar cigar, final int readStart) throws GATKException { final AlignmentInterval detailsDoesnotMatter = new AlignmentInterval( new SimpleInterval("1", 1, cigar.getReferenceLength()), readStart, readStart+cigar.getReadLength()-SvCigarUtils.getNumSoftClippingBases(true, cigar.getCigarElements())-SvCigarUtils.getNumSoftClippingBases(false, cigar.getCigarElements()), cigar, true, 60, 0, 100, ContigAlignmentsModifier.AlnModType.NONE); return ContigAlignmentsModifier.splitGappedAlignment(detailsDoesnotMatter, 1, cigar.getReadLength() + SvCigarUtils.getTotalHardClipping(cigar)); } @Test(groups = "sv") public void testGappedAlignmentBreaker_NoLongerExpectException() { // not testing correctness, just testing the function now accepts these // these 4 are fine now Cigar cigar = TextCigarCodec.decode("10H10I10M"); AlignmentInterval alignment = new AlignmentInterval(new SimpleInterval("1", 1, 10), 21, 30, cigar, true, 60, 0, 100, ContigAlignmentsModifier.AlnModType.NONE); ContigAlignmentsModifier.splitGappedAlignment(alignment, 1, cigar.getReadLength() + SvCigarUtils.getTotalHardClipping(cigar)); cigar = TextCigarCodec.decode("10S10I10M"); alignment = new AlignmentInterval(new SimpleInterval("1", 1, 10), 21, 30, cigar, true, 60, 0, 100, ContigAlignmentsModifier.AlnModType.NONE); ContigAlignmentsModifier.splitGappedAlignment(alignment, 1, cigar.getReadLength() + SvCigarUtils.getTotalHardClipping(cigar)); cigar = TextCigarCodec.decode("10M10I10S"); alignment = new AlignmentInterval(new SimpleInterval("1", 1, 10), 1, 10, cigar, true, 60, 0, 100, ContigAlignmentsModifier.AlnModType.NONE); ContigAlignmentsModifier.splitGappedAlignment(alignment, 1, cigar.getReadLength() + SvCigarUtils.getTotalHardClipping(cigar)); cigar = TextCigarCodec.decode("10M10I10H"); alignment = new AlignmentInterval(new SimpleInterval("1", 1, 10), 1, 10, cigar, true, 60, 0, 100, ContigAlignmentsModifier.AlnModType.NONE); ContigAlignmentsModifier.splitGappedAlignment(alignment, 1, cigar.getReadLength() + SvCigarUtils.getTotalHardClipping(cigar)); // last two are valid cigar = TextCigarCodec.decode("10H10M10I10M10S"); alignment = new AlignmentInterval(new SimpleInterval("1", 1, 20), 11, 40, cigar, true, 60, 0, 100, ContigAlignmentsModifier.AlnModType.NONE); ContigAlignmentsModifier.splitGappedAlignment(alignment, 1, cigar.getReadLength() + SvCigarUtils.getTotalHardClipping(cigar)); cigar = TextCigarCodec.decode("10H10M10D10M10S"); alignment = new AlignmentInterval(new SimpleInterval("1", 1, 30), 11, 30, cigar, true, 60, 0, 100, ContigAlignmentsModifier.AlnModType.NONE); ContigAlignmentsModifier.splitGappedAlignment(alignment, 1, cigar.getReadLength() + SvCigarUtils.getTotalHardClipping(cigar)); } //================================================================================================================== @DataProvider(name = "forComputeNewRefSpanAndCigar") private Object[][] createTestDataForComputeNewRefSpanAndCigar() { final List<Object[]> data = new ArrayList<>(20); AlignmentInterval alignment = new AlignmentInterval(new SimpleInterval("chr1", 175417007, 175417074), 14, 81, TextCigarCodec.decode("13H68M394H"), true, 60, 0, 68, ContigAlignmentsModifier.AlnModType.NONE); SimpleInterval refSpan = new SimpleInterval("chr1", 175417007, 175417043); data.add(new Object[]{alignment, 31, true, refSpan, TextCigarCodec.decode("13H37M31S394H")}); alignment = new AlignmentInterval(new SimpleInterval("chr2", 122612655, 122612751), 9, 105, TextCigarCodec.decode("8H97M138H"), false, 60, 0, 97, ContigAlignmentsModifier.AlnModType.NONE); refSpan = new SimpleInterval("chr2", 122612659, 122612751); data.add(new Object[]{alignment, 4, true, refSpan, TextCigarCodec.decode("8H93M4S138H")}); alignment = new AlignmentInterval(new SimpleInterval("chr6", 66782514, 66782679), 32, 197, TextCigarCodec.decode("31S166M"), false, 60, 3, 151, ContigAlignmentsModifier.AlnModType.NONE); refSpan = new SimpleInterval("chr6", 66782514, 66782675); data.add(new Object[]{alignment, 4, false, refSpan, TextCigarCodec.decode("35S162M")}); alignment = new AlignmentInterval(new SimpleInterval("chr2", 91421528, 91421734), 271, 477, TextCigarCodec.decode("270H207M"), true, 40, 12, 147, ContigAlignmentsModifier.AlnModType.NONE); refSpan = new SimpleInterval("chr2", 91421560, 91421734); data.add(new Object[]{alignment, 32, false, refSpan, TextCigarCodec.decode("270H32S175M")}); final SimpleInterval originalRefSpan = new SimpleInterval("chr2", 128791173, 128792506); alignment = new AlignmentInterval(originalRefSpan, 1, 1332, TextCigarCodec.decode("1190M4D53M2I26M2I31M2D28M1422S"), true, 60, 13, 1239, ContigAlignmentsModifier.AlnModType.NONE); refSpan = new SimpleInterval("chr2", 128791173, 128792476); data.add(new Object[]{alignment, 28, true, refSpan, TextCigarCodec.decode("1190M4D53M2I26M2I31M1450S")}); alignment = new AlignmentInterval(new SimpleInterval("chr2", 128791173, 128792504), 1, 1334, TextCigarCodec.decode("1190M4D53M2I26M2I31M2I28M1422S"), true, 60, 13, 1239, ContigAlignmentsModifier.AlnModType.NONE); refSpan = new SimpleInterval("chr2", 128791173, 128792476); data.add(new Object[]{alignment, 28, true, refSpan, TextCigarCodec.decode("1190M4D53M2I26M2I31M1452S")}); alignment = new AlignmentInterval(originalRefSpan, 1, 1332, TextCigarCodec.decode("1190M4D53M2I26M2I31M2D28M1422S"), true, 60, 13, 1239, ContigAlignmentsModifier.AlnModType.NONE); refSpan = new SimpleInterval("chr2", 128792367, 128792506); data.add(new Object[]{alignment, 1190, false, refSpan, TextCigarCodec.decode("1190S53M2I26M2I31M2D28M1422S")}); alignment = new AlignmentInterval(new SimpleInterval("chr2", 128791173, 128792500), 1, 1338, TextCigarCodec.decode("1190M4I53M2I26M2I31M2I28M1422S"), true, 60, 13, 1239, ContigAlignmentsModifier.AlnModType.NONE); refSpan = new SimpleInterval("chr2", 128792363, 128792500); data.add(new Object[]{alignment, 1190, false, refSpan, TextCigarCodec.decode("1194S53M2I26M2I31M2I28M1422S")}); alignment = new AlignmentInterval(new SimpleInterval("chr20", 38653045, 38653268), 1783, 2053, TextCigarCodec.decode("1782S89M44I106M3I29M1431S"), false, 60, 59, 85, ContigAlignmentsModifier.AlnModType.NONE); data.add(new Object[]{alignment, 89, false, new SimpleInterval("chr20", 38653045, 38653179), TextCigarCodec.decode("1915S106M3I29M1431S")}); alignment = new AlignmentInterval(new SimpleInterval("chr5", 33757389, 33757589), 419, 658, TextCigarCodec.decode("418H78M39I123M180H"), true, 60, 41, 136, ContigAlignmentsModifier.AlnModType.NONE); data.add(new Object[]{alignment, 79, false, new SimpleInterval("chr5", 33757467, 33757589), TextCigarCodec.decode("418H117S123M180H")}); alignment = new AlignmentInterval(new SimpleInterval("chr5", 33757467, 33757589), 536, 658, TextCigarCodec.decode("418H117S123M180H"), true, 60, NO_NM, NO_AS, ContigAlignmentsModifier.AlnModType.UNDERGONE_OVERLAP_REMOVAL); data.add(new Object[]{alignment, 101, true, new SimpleInterval("chr5", 33757467, 33757488), TextCigarCodec.decode("418H117S22M101S180H")}); return data.toArray(new Object[data.size()][]); } @Test(dataProvider = "forComputeNewRefSpanAndCigar", groups = "sv") public void testComputeNewRefSpanAndCigar(final AlignmentInterval interval, final int clipLength, final boolean clipFrom3PrimeEnd, final SimpleInterval expectedRefSpan, final Cigar expectedCigar) { final Tuple2<SimpleInterval, Cigar> x = ContigAlignmentsModifier.computeNewRefSpanAndCigar(interval, clipLength, clipFrom3PrimeEnd); Assert.assertEquals(x._1, expectedRefSpan); Assert.assertEquals(x._2, expectedCigar); } @DataProvider(name = "forCigarExtraction") private Object[][] createTestDataForCigarExtraction() { final List<Object[]> data = new ArrayList<>(20); SimpleInterval refSpan = new SimpleInterval("chr1", 82666357, 82666765); AlignmentInterval alignment = new AlignmentInterval(refSpan, 69, 472, TextCigarCodec.decode("68S122M5D282M"), true, 60, 11, 353, ContigAlignmentsModifier.AlnModType.NONE); List<CigarElement> left = Arrays.asList(new CigarElement(68, CigarOperator.S)); List<CigarElement> middle = Arrays.asList(new CigarElement(122, CigarOperator.M), new CigarElement(5, CigarOperator.D), new CigarElement(282, CigarOperator.M)); List<CigarElement> right = Collections.emptyList(); data.add(new Object[]{alignment, left, middle, right}); refSpan = new SimpleInterval("chr3", 61792401, 61792448); alignment = new AlignmentInterval(refSpan, 43, 90, TextCigarCodec.decode("42H48M382H"), true, 46, 1, 43, ContigAlignmentsModifier.AlnModType.NONE); left = Arrays.asList(new CigarElement(42, CigarOperator.H)); middle = Arrays.asList(new CigarElement(48, CigarOperator.M)); right = Arrays.asList(new CigarElement(382, CigarOperator.H)); data.add(new Object[]{alignment, left, middle, right}); refSpan = new SimpleInterval("chrY", 26303624, 26303671); alignment = new AlignmentInterval(refSpan, 1, 48, TextCigarCodec.decode("48M424H"), true, 0, 2, 38, ContigAlignmentsModifier.AlnModType.NONE); left = Collections.emptyList(); middle = Arrays.asList(new CigarElement(48, CigarOperator.M)); right = Arrays.asList(new CigarElement(424, CigarOperator.H)); data.add(new Object[]{alignment, left, middle, right}); return data.toArray(new Object[data.size()][]); } @Test(dataProvider = "forCigarExtraction", groups = "sv") public void testExtractCigar(final AlignmentInterval interval, final List<CigarElement> expectedLeft, final List<CigarElement> expectedMiddle, final List<CigarElement> expectedRight) { final Tuple3<List<CigarElement>, List<CigarElement>, List<CigarElement>> x = ContigAlignmentsModifier.splitCigarByLeftAndRightClipping(interval); Assert.assertEquals(x._1(), expectedLeft); Assert.assertEquals(x._2(), expectedMiddle); Assert.assertEquals(x._3(), expectedRight); } //================================================================================================================== @DataProvider(name = "forClipAlignmentInterval") private Object[][] createTestDataForClipAlignmentInterval() { final List<Object[]> data = new ArrayList<>(20); data.add(new Object[]{null, 10, true, null, IllegalArgumentException.class}); AlignmentInterval alignment = TestUtilsForAssemblyBasedSVDiscovery.fromSAMRecordString("asm004677:tig00000\t2064\tchr1\t202317371\t60\t1393H50M1085H\t*\t0\t0\tGTCTTGCTCTGTTGCCCAGGCTGGAGTGCAGTAGAGCAATCATAGCTCAC\t*\tSA:Z:chr3,15736242,-,1282M1246S,60,0;chr3,15737523,-,1425S377M1D726M,60,4;\tMD:Z:41T8\tRG:Z:GATKSVContigAlignments\tNM:i:1\tAS:i:45\tXS:i:0", true); data.add(new Object[]{alignment, -1, true, null, IllegalArgumentException.class}); data.add(new Object[]{alignment, 51, true, null, IllegalArgumentException.class}); AlignmentInterval expected = new AlignmentInterval( new SimpleInterval("chr1", 202317371, 202317402), 1104, 1135, TextCigarCodec.decode("1085H18S32M1393H"), false, 60, AlignmentInterval.NO_NM, AlignmentInterval.NO_AS, ContigAlignmentsModifier.AlnModType.UNDERGONE_OVERLAP_REMOVAL); data.add(new Object[]{alignment, 18, false, expected, null}); alignment = new AlignmentInterval(new SimpleInterval("chr5", 33757389, 33757589), 419, 658, TextCigarCodec.decode("418H78M39I123M180H"), true, 60, 41, 136, ContigAlignmentsModifier.AlnModType.NONE); expected = new AlignmentInterval( new SimpleInterval("chr5", 33757467, 33757589), 536, 658, TextCigarCodec.decode("418H117S123M180H"), true, 60, AlignmentInterval.NO_NM, AlignmentInterval.NO_AS, ContigAlignmentsModifier.AlnModType.UNDERGONE_OVERLAP_REMOVAL); data.add(new Object[]{alignment, 79, false, expected, null}); alignment = new AlignmentInterval(new SimpleInterval("chr5", 33757467, 33757589), 536, 658, TextCigarCodec.decode("418H117S123M180H"), true, 60, NO_NM, NO_AS, ContigAlignmentsModifier.AlnModType.UNDERGONE_OVERLAP_REMOVAL); expected = new AlignmentInterval( new SimpleInterval("chr5", 33757467, 33757488), 536, 557, TextCigarCodec.decode("418H117S22M101S180H"), true, 60, AlignmentInterval.NO_NM, AlignmentInterval.NO_AS, ContigAlignmentsModifier.AlnModType.UNDERGONE_OVERLAP_REMOVAL); data.add(new Object[]{alignment, 101, true, expected, null}); alignment = new AlignmentInterval(new SimpleInterval("chr12", 31118319, 31118856), 179, 714, TextCigarCodec.decode("178S91M1D118M1D327M285S"), false, 60, 51, 257, ContigAlignmentsModifier.AlnModType.NONE); expected = new AlignmentInterval( new SimpleInterval("chr12", 31118372, 31118856), 179, 661, TextCigarCodec.decode("178S91M1D118M1D274M338S"), false, 60, AlignmentInterval.NO_NM, AlignmentInterval.NO_AS, ContigAlignmentsModifier.AlnModType.UNDERGONE_OVERLAP_REMOVAL); data.add(new Object[]{alignment, 53, true, expected, null}); return data.toArray(new Object[data.size()][]); } @Test(groups = "sv", dataProvider = "forClipAlignmentInterval") @SuppressWarnings("rawtypes") public void testClipAlignmentInterval(final AlignmentInterval toBeClipped, final int clipLength, final boolean clipFrom3PrimeEnd, final AlignmentInterval expectedResult, final Class expectedExceptionClass) { try { Assert.assertEquals(ContigAlignmentsModifier.clipAlignmentInterval(toBeClipped, clipLength, clipFrom3PrimeEnd), expectedResult); } catch (final Exception ex) { Assert.assertEquals(ex.getClass(), expectedExceptionClass); } } }
magicDGS/gatk
src/test/java/org/broadinstitute/hellbender/tools/spark/sv/discovery/alignment/ContigAlignmentsModifierUnitTest.java
Java
bsd-3-clause
31,806
// // AboutWISTViewController.h // WIST SDK Version 1.0.0 // // Portions contributed by Retronyms (www.retronyms.com). // Copyright 2011 KORG INC. All rights reserved. // #import <UIKit/UIKit.h> @interface AboutWISTViewController : UIViewController <UIWebViewDelegate> { @private NSString* pageUrl_; UIWebView* webview_; UIActivityIndicatorView* indicatorView_; } @end
Apolotary/KORG-Wist-SDK
WIST/AboutWISTViewController.h
C
bsd-3-clause
394
{% extends "pact/chw/pact_chw_profile_base.html" %} {% load i18n %} {% block actor-tab-container %} <div class="span6"> <table class="table table-striped table-bordered"> <tr> <th>{% trans "Username" %}</th> <td>{{ user_doc.username }}</td> </tr> <tr> <th>{% trans "Phone" %}</th> <td>{{ user_doc.phone_number }}</td> </tr> <tr> <th>{% trans "Email" %}</th> <td>{{ user_doc.email }}</td> </tr> </table> </div> <div class="span8"> <h4>Active Patients ({{ assigned_patients|length }})</h4> <table class="table table-striped table-bordered"> <thead> <tr> <th>Pact ID</th> <th>Name</th> <th>HP Status</th> <th>DOT Status</th> <th>{# Submits #}</th> </tr> </thead> {% for pt in assigned_patients %} <tr> <th>{{ pt.pactid }}</th> <td>{{ pt.name }}</td> <td> {{ pt.hp_status }} </td> <td> {% if pt.dot_url %} <a href="{{ pt.dot_url }}">{{ pt.dot_status }}</a> {% else %} {{ pt.dot_status }} {% endif %} </td> <td><a href="{{ pt.info_url }}">Profile</a></td> </tr> {% endfor %} </table> </div> {% endblock actor-tab-container %}
puttarajubr/commcare-hq
custom/_legacy/pact/templates/pact/chw/pact_chw_profile_info.html
HTML
bsd-3-clause
1,436
<?php /** * UMI.Framework (http://umi-framework.ru/) * * @link http://github.com/Umisoft/framework for the canonical source repository * @copyright Copyright (c) 2007-2013 Umisoft ltd. (http://umisoft.ru/) * @license http://umi-framework.ru/license/bsd-3 BSD-3 License */ namespace umi\hmvc\dispatcher; use SplStack; use umi\hmvc\component\IComponent; use umi\hmvc\exception\RuntimeException; /** * Контекст диспетчеризации MVC-компонентов. */ class DispatchContext implements IDispatchContext { /** * @var IComponent $component */ protected $component; /** * @var IDispatcher $dispatcher диспетчер компонентов */ protected $dispatcher; /** * @var string $baseUrl базовый URL запроса к компоненту */ protected $baseUrl = ''; /** * @var array $routeParams параметры маршрутизации */ protected $routeParams = []; /** * @var SplStack $callStack стек вызова компонента */ private $callStack; /** * Конструктор. * @param IComponent $component * @param IDispatcher $dispatcher диспетчер компонентов */ public function __construct(IComponent $component, IDispatcher $dispatcher) { $this->component = $component; $this->dispatcher = $dispatcher; } /** * {@inheritdoc} */ public function setCallStack(SplStack $callStack) { $this->callStack = $callStack; return $this; } /** * {@inheritdoc} */ public function getComponent() { return $this->component; } /** * {@inheritdoc} */ public function getDispatcher() { return $this->dispatcher; } /** * {@inheritdoc} */ public function getCallStack() { if (!$this->callStack) { throw new RuntimeException( 'Call stack is unknown.' ); } return $this->callStack; } /** * {@inheritdoc} */ public function setRouteParams(array $params) { $this->routeParams = $params; return $this; } /** * {@inheritdoc} */ public function getRouteParams() { return $this->routeParams; } /** * {@inheritdoc} */ public function setBaseUrl($baseUrl) { $this->baseUrl = $baseUrl; return $this; } /** * {@inheritdoc} */ public function getBaseUrl() { return $this->baseUrl; } }
Umisoft/umi.framework-dev
library/hmvc/dispatcher/DispatchContext.php
PHP
bsd-3-clause
2,663
from django import forms from django.contrib import admin from django.contrib.admin import AdminSite from django.contrib.auth.backends import ModelBackend from django.contrib.auth.middleware import AuthenticationMiddleware from django.contrib.contenttypes.admin import GenericStackedInline from django.contrib.messages.middleware import MessageMiddleware from django.contrib.sessions.middleware import SessionMiddleware from django.core import checks from django.test import SimpleTestCase, override_settings from .models import ( Album, Author, Book, City, Influence, Song, State, TwoAlbumFKAndAnE, ) class SongForm(forms.ModelForm): pass class ValidFields(admin.ModelAdmin): form = SongForm fields = ['title'] class ValidFormFieldsets(admin.ModelAdmin): def get_form(self, request, obj=None, **kwargs): class ExtraFieldForm(SongForm): name = forms.CharField(max_length=50) return ExtraFieldForm fieldsets = ( (None, { 'fields': ('name',), }), ) class MyAdmin(admin.ModelAdmin): def check(self, **kwargs): return ['error!'] class AuthenticationMiddlewareSubclass(AuthenticationMiddleware): pass class MessageMiddlewareSubclass(MessageMiddleware): pass class ModelBackendSubclass(ModelBackend): pass class SessionMiddlewareSubclass(SessionMiddleware): pass @override_settings( SILENCED_SYSTEM_CHECKS=['fields.W342'], # ForeignKey(unique=True) INSTALLED_APPS=[ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.messages', 'admin_checks', ], ) class SystemChecksTestCase(SimpleTestCase): def test_checks_are_performed(self): admin.site.register(Song, MyAdmin) try: errors = checks.run_checks() expected = ['error!'] self.assertEqual(errors, expected) finally: admin.site.unregister(Song) @override_settings(INSTALLED_APPS=['django.contrib.admin']) def test_apps_dependencies(self): errors = admin.checks.check_dependencies() expected = [ checks.Error( "'django.contrib.contenttypes' must be in " "INSTALLED_APPS in order to use the admin application.", id="admin.E401", ), checks.Error( "'django.contrib.auth' must be in INSTALLED_APPS in order " "to use the admin application.", id='admin.E405', ), checks.Error( "'django.contrib.messages' must be in INSTALLED_APPS in order " "to use the admin application.", id='admin.E406', ), ] self.assertEqual(errors, expected) @override_settings(TEMPLATES=[]) def test_no_template_engines(self): self.assertEqual(admin.checks.check_dependencies(), [ checks.Error( "A 'django.template.backends.django.DjangoTemplates' " "instance must be configured in TEMPLATES in order to use " "the admin application.", id='admin.E403', ) ]) @override_settings( TEMPLATES=[{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [], }, }], ) def test_context_processor_dependencies(self): expected = [ checks.Error( "'django.contrib.auth.context_processors.auth' must be " "enabled in DjangoTemplates (TEMPLATES) if using the default " "auth backend in order to use the admin application.", id='admin.E402', ), checks.Error( "'django.contrib.messages.context_processors.messages' must " "be enabled in DjangoTemplates (TEMPLATES) in order to use " "the admin application.", id='admin.E404', ), checks.Warning( "'django.template.context_processors.request' must be enabled " "in DjangoTemplates (TEMPLATES) in order to use the admin " "navigation sidebar.", id='admin.W411', ) ] self.assertEqual(admin.checks.check_dependencies(), expected) # The first error doesn't happen if # 'django.contrib.auth.backends.ModelBackend' isn't in # AUTHENTICATION_BACKENDS. with self.settings(AUTHENTICATION_BACKENDS=[]): self.assertEqual(admin.checks.check_dependencies(), expected[1:]) @override_settings( AUTHENTICATION_BACKENDS=['admin_checks.tests.ModelBackendSubclass'], TEMPLATES=[{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.request', 'django.contrib.messages.context_processors.messages', ], }, }], ) def test_context_processor_dependencies_model_backend_subclass(self): self.assertEqual(admin.checks.check_dependencies(), [ checks.Error( "'django.contrib.auth.context_processors.auth' must be " "enabled in DjangoTemplates (TEMPLATES) if using the default " "auth backend in order to use the admin application.", id='admin.E402', ), ]) @override_settings( TEMPLATES=[ { 'BACKEND': 'django.template.backends.dummy.TemplateStrings', 'DIRS': [], 'APP_DIRS': True, }, { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ], ) def test_several_templates_backends(self): self.assertEqual(admin.checks.check_dependencies(), []) @override_settings(MIDDLEWARE=[]) def test_middleware_dependencies(self): errors = admin.checks.check_dependencies() expected = [ checks.Error( "'django.contrib.auth.middleware.AuthenticationMiddleware' " "must be in MIDDLEWARE in order to use the admin application.", id='admin.E408', ), checks.Error( "'django.contrib.messages.middleware.MessageMiddleware' " "must be in MIDDLEWARE in order to use the admin application.", id='admin.E409', ), checks.Error( "'django.contrib.sessions.middleware.SessionMiddleware' " "must be in MIDDLEWARE in order to use the admin application.", hint=( "Insert " "'django.contrib.sessions.middleware.SessionMiddleware' " "before " "'django.contrib.auth.middleware.AuthenticationMiddleware'." ), id='admin.E410', ), ] self.assertEqual(errors, expected) @override_settings(MIDDLEWARE=[ 'admin_checks.tests.AuthenticationMiddlewareSubclass', 'admin_checks.tests.MessageMiddlewareSubclass', 'admin_checks.tests.SessionMiddlewareSubclass', ]) def test_middleware_subclasses(self): self.assertEqual(admin.checks.check_dependencies(), []) @override_settings(MIDDLEWARE=[ 'django.contrib.does.not.Exist', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', ]) def test_admin_check_ignores_import_error_in_middleware(self): self.assertEqual(admin.checks.check_dependencies(), []) def test_custom_adminsite(self): class CustomAdminSite(admin.AdminSite): pass custom_site = CustomAdminSite() custom_site.register(Song, MyAdmin) try: errors = checks.run_checks() expected = ['error!'] self.assertEqual(errors, expected) finally: custom_site.unregister(Song) def test_allows_checks_relying_on_other_modeladmins(self): class MyBookAdmin(admin.ModelAdmin): def check(self, **kwargs): errors = super().check(**kwargs) author_admin = self.admin_site._registry.get(Author) if author_admin is None: errors.append('AuthorAdmin missing!') return errors class MyAuthorAdmin(admin.ModelAdmin): pass admin.site.register(Book, MyBookAdmin) admin.site.register(Author, MyAuthorAdmin) try: self.assertEqual(admin.site.check(None), []) finally: admin.site.unregister(Book) admin.site.unregister(Author) def test_field_name_not_in_list_display(self): class SongAdmin(admin.ModelAdmin): list_editable = ["original_release"] errors = SongAdmin(Song, AdminSite()).check() expected = [ checks.Error( "The value of 'list_editable[0]' refers to 'original_release', " "which is not contained in 'list_display'.", obj=SongAdmin, id='admin.E122', ) ] self.assertEqual(errors, expected) def test_list_editable_not_a_list_or_tuple(self): class SongAdmin(admin.ModelAdmin): list_editable = 'test' self.assertEqual(SongAdmin(Song, AdminSite()).check(), [ checks.Error( "The value of 'list_editable' must be a list or tuple.", obj=SongAdmin, id='admin.E120', ) ]) def test_list_editable_missing_field(self): class SongAdmin(admin.ModelAdmin): list_editable = ('test',) self.assertEqual(SongAdmin(Song, AdminSite()).check(), [ checks.Error( "The value of 'list_editable[0]' refers to 'test', which is " "not an attribute of 'admin_checks.Song'.", obj=SongAdmin, id='admin.E121', ) ]) def test_readonly_and_editable(self): class SongAdmin(admin.ModelAdmin): readonly_fields = ["original_release"] list_display = ["pk", "original_release"] list_editable = ["original_release"] fieldsets = [ (None, { "fields": ["title", "original_release"], }), ] errors = SongAdmin(Song, AdminSite()).check() expected = [ checks.Error( "The value of 'list_editable[0]' refers to 'original_release', " "which is not editable through the admin.", obj=SongAdmin, id='admin.E125', ) ] self.assertEqual(errors, expected) def test_editable(self): class SongAdmin(admin.ModelAdmin): list_display = ["pk", "title"] list_editable = ["title"] fieldsets = [ (None, { "fields": ["title", "original_release"], }), ] errors = SongAdmin(Song, AdminSite()).check() self.assertEqual(errors, []) def test_custom_modelforms_with_fields_fieldsets(self): """ # Regression test for #8027: custom ModelForms with fields/fieldsets """ errors = ValidFields(Song, AdminSite()).check() self.assertEqual(errors, []) def test_custom_get_form_with_fieldsets(self): """ The fieldsets checks are skipped when the ModelAdmin.get_form() method is overridden. """ errors = ValidFormFieldsets(Song, AdminSite()).check() self.assertEqual(errors, []) def test_fieldsets_fields_non_tuple(self): """ The first fieldset's fields must be a list/tuple. """ class NotATupleAdmin(admin.ModelAdmin): list_display = ["pk", "title"] list_editable = ["title"] fieldsets = [ (None, { "fields": "title" # not a tuple }), ] errors = NotATupleAdmin(Song, AdminSite()).check() expected = [ checks.Error( "The value of 'fieldsets[0][1]['fields']' must be a list or tuple.", obj=NotATupleAdmin, id='admin.E008', ) ] self.assertEqual(errors, expected) def test_nonfirst_fieldset(self): """ The second fieldset's fields must be a list/tuple. """ class NotATupleAdmin(admin.ModelAdmin): fieldsets = [ (None, { "fields": ("title",) }), ('foo', { "fields": "author" # not a tuple }), ] errors = NotATupleAdmin(Song, AdminSite()).check() expected = [ checks.Error( "The value of 'fieldsets[1][1]['fields']' must be a list or tuple.", obj=NotATupleAdmin, id='admin.E008', ) ] self.assertEqual(errors, expected) def test_exclude_values(self): """ Tests for basic system checks of 'exclude' option values (#12689) """ class ExcludedFields1(admin.ModelAdmin): exclude = 'foo' errors = ExcludedFields1(Book, AdminSite()).check() expected = [ checks.Error( "The value of 'exclude' must be a list or tuple.", obj=ExcludedFields1, id='admin.E014', ) ] self.assertEqual(errors, expected) def test_exclude_duplicate_values(self): class ExcludedFields2(admin.ModelAdmin): exclude = ('name', 'name') errors = ExcludedFields2(Book, AdminSite()).check() expected = [ checks.Error( "The value of 'exclude' contains duplicate field(s).", obj=ExcludedFields2, id='admin.E015', ) ] self.assertEqual(errors, expected) def test_exclude_in_inline(self): class ExcludedFieldsInline(admin.TabularInline): model = Song exclude = 'foo' class ExcludedFieldsAlbumAdmin(admin.ModelAdmin): model = Album inlines = [ExcludedFieldsInline] errors = ExcludedFieldsAlbumAdmin(Album, AdminSite()).check() expected = [ checks.Error( "The value of 'exclude' must be a list or tuple.", obj=ExcludedFieldsInline, id='admin.E014', ) ] self.assertEqual(errors, expected) def test_exclude_inline_model_admin(self): """ Regression test for #9932 - exclude in InlineModelAdmin should not contain the ForeignKey field used in ModelAdmin.model """ class SongInline(admin.StackedInline): model = Song exclude = ['album'] class AlbumAdmin(admin.ModelAdmin): model = Album inlines = [SongInline] errors = AlbumAdmin(Album, AdminSite()).check() expected = [ checks.Error( "Cannot exclude the field 'album', because it is the foreign key " "to the parent model 'admin_checks.Album'.", obj=SongInline, id='admin.E201', ) ] self.assertEqual(errors, expected) def test_valid_generic_inline_model_admin(self): """ Regression test for #22034 - check that generic inlines don't look for normal ForeignKey relations. """ class InfluenceInline(GenericStackedInline): model = Influence class SongAdmin(admin.ModelAdmin): inlines = [InfluenceInline] errors = SongAdmin(Song, AdminSite()).check() self.assertEqual(errors, []) def test_generic_inline_model_admin_non_generic_model(self): """ A model without a GenericForeignKey raises problems if it's included in a GenericInlineModelAdmin definition. """ class BookInline(GenericStackedInline): model = Book class SongAdmin(admin.ModelAdmin): inlines = [BookInline] errors = SongAdmin(Song, AdminSite()).check() expected = [ checks.Error( "'admin_checks.Book' has no GenericForeignKey.", obj=BookInline, id='admin.E301', ) ] self.assertEqual(errors, expected) def test_generic_inline_model_admin_bad_ct_field(self): """ A GenericInlineModelAdmin errors if the ct_field points to a nonexistent field. """ class InfluenceInline(GenericStackedInline): model = Influence ct_field = 'nonexistent' class SongAdmin(admin.ModelAdmin): inlines = [InfluenceInline] errors = SongAdmin(Song, AdminSite()).check() expected = [ checks.Error( "'ct_field' references 'nonexistent', which is not a field on 'admin_checks.Influence'.", obj=InfluenceInline, id='admin.E302', ) ] self.assertEqual(errors, expected) def test_generic_inline_model_admin_bad_fk_field(self): """ A GenericInlineModelAdmin errors if the ct_fk_field points to a nonexistent field. """ class InfluenceInline(GenericStackedInline): model = Influence ct_fk_field = 'nonexistent' class SongAdmin(admin.ModelAdmin): inlines = [InfluenceInline] errors = SongAdmin(Song, AdminSite()).check() expected = [ checks.Error( "'ct_fk_field' references 'nonexistent', which is not a field on 'admin_checks.Influence'.", obj=InfluenceInline, id='admin.E303', ) ] self.assertEqual(errors, expected) def test_generic_inline_model_admin_non_gfk_ct_field(self): """ A GenericInlineModelAdmin raises problems if the ct_field points to a field that isn't part of a GenericForeignKey. """ class InfluenceInline(GenericStackedInline): model = Influence ct_field = 'name' class SongAdmin(admin.ModelAdmin): inlines = [InfluenceInline] errors = SongAdmin(Song, AdminSite()).check() expected = [ checks.Error( "'admin_checks.Influence' has no GenericForeignKey using " "content type field 'name' and object ID field 'object_id'.", obj=InfluenceInline, id='admin.E304', ) ] self.assertEqual(errors, expected) def test_generic_inline_model_admin_non_gfk_fk_field(self): """ A GenericInlineModelAdmin raises problems if the ct_fk_field points to a field that isn't part of a GenericForeignKey. """ class InfluenceInline(GenericStackedInline): model = Influence ct_fk_field = 'name' class SongAdmin(admin.ModelAdmin): inlines = [InfluenceInline] errors = SongAdmin(Song, AdminSite()).check() expected = [ checks.Error( "'admin_checks.Influence' has no GenericForeignKey using " "content type field 'content_type' and object ID field 'name'.", obj=InfluenceInline, id='admin.E304', ) ] self.assertEqual(errors, expected) def test_app_label_in_admin_checks(self): class RawIdNonexistentAdmin(admin.ModelAdmin): raw_id_fields = ('nonexistent',) errors = RawIdNonexistentAdmin(Album, AdminSite()).check() expected = [ checks.Error( "The value of 'raw_id_fields[0]' refers to 'nonexistent', " "which is not an attribute of 'admin_checks.Album'.", obj=RawIdNonexistentAdmin, id='admin.E002', ) ] self.assertEqual(errors, expected) def test_fk_exclusion(self): """ Regression test for #11709 - when testing for fk excluding (when exclude is given) make sure fk_name is honored or things blow up when there is more than one fk to the parent model. """ class TwoAlbumFKAndAnEInline(admin.TabularInline): model = TwoAlbumFKAndAnE exclude = ("e",) fk_name = "album1" class MyAdmin(admin.ModelAdmin): inlines = [TwoAlbumFKAndAnEInline] errors = MyAdmin(Album, AdminSite()).check() self.assertEqual(errors, []) def test_inline_self_check(self): class TwoAlbumFKAndAnEInline(admin.TabularInline): model = TwoAlbumFKAndAnE class MyAdmin(admin.ModelAdmin): inlines = [TwoAlbumFKAndAnEInline] errors = MyAdmin(Album, AdminSite()).check() expected = [ checks.Error( "'admin_checks.TwoAlbumFKAndAnE' has more than one ForeignKey " "to 'admin_checks.Album'. You must specify a 'fk_name' " "attribute.", obj=TwoAlbumFKAndAnEInline, id='admin.E202', ) ] self.assertEqual(errors, expected) def test_inline_with_specified(self): class TwoAlbumFKAndAnEInline(admin.TabularInline): model = TwoAlbumFKAndAnE fk_name = "album1" class MyAdmin(admin.ModelAdmin): inlines = [TwoAlbumFKAndAnEInline] errors = MyAdmin(Album, AdminSite()).check() self.assertEqual(errors, []) def test_inlines_property(self): class CitiesInline(admin.TabularInline): model = City class StateAdmin(admin.ModelAdmin): @property def inlines(self): return [CitiesInline] errors = StateAdmin(State, AdminSite()).check() self.assertEqual(errors, []) def test_readonly(self): class SongAdmin(admin.ModelAdmin): readonly_fields = ("title",) errors = SongAdmin(Song, AdminSite()).check() self.assertEqual(errors, []) def test_readonly_on_method(self): @admin.display def my_function(obj): pass class SongAdmin(admin.ModelAdmin): readonly_fields = (my_function,) errors = SongAdmin(Song, AdminSite()).check() self.assertEqual(errors, []) def test_readonly_on_modeladmin(self): class SongAdmin(admin.ModelAdmin): readonly_fields = ("readonly_method_on_modeladmin",) @admin.display def readonly_method_on_modeladmin(self, obj): pass errors = SongAdmin(Song, AdminSite()).check() self.assertEqual(errors, []) def test_readonly_dynamic_attribute_on_modeladmin(self): class SongAdmin(admin.ModelAdmin): readonly_fields = ("dynamic_method",) def __getattr__(self, item): if item == "dynamic_method": @admin.display def method(obj): pass return method raise AttributeError errors = SongAdmin(Song, AdminSite()).check() self.assertEqual(errors, []) def test_readonly_method_on_model(self): class SongAdmin(admin.ModelAdmin): readonly_fields = ("readonly_method_on_model",) errors = SongAdmin(Song, AdminSite()).check() self.assertEqual(errors, []) def test_nonexistent_field(self): class SongAdmin(admin.ModelAdmin): readonly_fields = ("title", "nonexistent") errors = SongAdmin(Song, AdminSite()).check() expected = [ checks.Error( "The value of 'readonly_fields[1]' is not a callable, an attribute " "of 'SongAdmin', or an attribute of 'admin_checks.Song'.", obj=SongAdmin, id='admin.E035', ) ] self.assertEqual(errors, expected) def test_nonexistent_field_on_inline(self): class CityInline(admin.TabularInline): model = City readonly_fields = ['i_dont_exist'] # Missing attribute errors = CityInline(State, AdminSite()).check() expected = [ checks.Error( "The value of 'readonly_fields[0]' is not a callable, an attribute " "of 'CityInline', or an attribute of 'admin_checks.City'.", obj=CityInline, id='admin.E035', ) ] self.assertEqual(errors, expected) def test_readonly_fields_not_list_or_tuple(self): class SongAdmin(admin.ModelAdmin): readonly_fields = 'test' self.assertEqual(SongAdmin(Song, AdminSite()).check(), [ checks.Error( "The value of 'readonly_fields' must be a list or tuple.", obj=SongAdmin, id='admin.E034', ) ]) def test_extra(self): class SongAdmin(admin.ModelAdmin): @admin.display def awesome_song(self, instance): if instance.title == "Born to Run": return "Best Ever!" return "Status unknown." errors = SongAdmin(Song, AdminSite()).check() self.assertEqual(errors, []) def test_readonly_lambda(self): class SongAdmin(admin.ModelAdmin): readonly_fields = (lambda obj: "test",) errors = SongAdmin(Song, AdminSite()).check() self.assertEqual(errors, []) def test_graceful_m2m_fail(self): """ Regression test for #12203/#12237 - Fail more gracefully when a M2M field that specifies the 'through' option is included in the 'fields' or the 'fieldsets' ModelAdmin options. """ class BookAdmin(admin.ModelAdmin): fields = ['authors'] errors = BookAdmin(Book, AdminSite()).check() expected = [ checks.Error( "The value of 'fields' cannot include the ManyToManyField 'authors', " "because that field manually specifies a relationship model.", obj=BookAdmin, id='admin.E013', ) ] self.assertEqual(errors, expected) def test_cannot_include_through(self): class FieldsetBookAdmin(admin.ModelAdmin): fieldsets = ( ('Header 1', {'fields': ('name',)}), ('Header 2', {'fields': ('authors',)}), ) errors = FieldsetBookAdmin(Book, AdminSite()).check() expected = [ checks.Error( "The value of 'fieldsets[1][1][\"fields\"]' cannot include the ManyToManyField " "'authors', because that field manually specifies a relationship model.", obj=FieldsetBookAdmin, id='admin.E013', ) ] self.assertEqual(errors, expected) def test_nested_fields(self): class NestedFieldsAdmin(admin.ModelAdmin): fields = ('price', ('name', 'subtitle')) errors = NestedFieldsAdmin(Book, AdminSite()).check() self.assertEqual(errors, []) def test_nested_fieldsets(self): class NestedFieldsetAdmin(admin.ModelAdmin): fieldsets = ( ('Main', {'fields': ('price', ('name', 'subtitle'))}), ) errors = NestedFieldsetAdmin(Book, AdminSite()).check() self.assertEqual(errors, []) def test_explicit_through_override(self): """ Regression test for #12209 -- If the explicitly provided through model is specified as a string, the admin should still be able use Model.m2m_field.through """ class AuthorsInline(admin.TabularInline): model = Book.authors.through class BookAdmin(admin.ModelAdmin): inlines = [AuthorsInline] errors = BookAdmin(Book, AdminSite()).check() self.assertEqual(errors, []) def test_non_model_fields(self): """ Regression for ensuring ModelAdmin.fields can contain non-model fields that broke with r11737 """ class SongForm(forms.ModelForm): extra_data = forms.CharField() class FieldsOnFormOnlyAdmin(admin.ModelAdmin): form = SongForm fields = ['title', 'extra_data'] errors = FieldsOnFormOnlyAdmin(Song, AdminSite()).check() self.assertEqual(errors, []) def test_non_model_first_field(self): """ Regression for ensuring ModelAdmin.field can handle first elem being a non-model field (test fix for UnboundLocalError introduced with r16225). """ class SongForm(forms.ModelForm): extra_data = forms.CharField() class Meta: model = Song fields = '__all__' class FieldsOnFormOnlyAdmin(admin.ModelAdmin): form = SongForm fields = ['extra_data', 'title'] errors = FieldsOnFormOnlyAdmin(Song, AdminSite()).check() self.assertEqual(errors, []) def test_check_sublists_for_duplicates(self): class MyModelAdmin(admin.ModelAdmin): fields = ['state', ['state']] errors = MyModelAdmin(Song, AdminSite()).check() expected = [ checks.Error( "The value of 'fields' contains duplicate field(s).", obj=MyModelAdmin, id='admin.E006' ) ] self.assertEqual(errors, expected) def test_check_fieldset_sublists_for_duplicates(self): class MyModelAdmin(admin.ModelAdmin): fieldsets = [ (None, { 'fields': ['title', 'album', ('title', 'album')] }), ] errors = MyModelAdmin(Song, AdminSite()).check() expected = [ checks.Error( "There are duplicate field(s) in 'fieldsets[0][1]'.", obj=MyModelAdmin, id='admin.E012' ) ] self.assertEqual(errors, expected) def test_list_filter_works_on_through_field_even_when_apps_not_ready(self): """ Ensure list_filter can access reverse fields even when the app registry is not ready; refs #24146. """ class BookAdminWithListFilter(admin.ModelAdmin): list_filter = ['authorsbooks__featured'] # Temporarily pretending apps are not ready yet. This issue can happen # if the value of 'list_filter' refers to a 'through__field'. Book._meta.apps.ready = False try: errors = BookAdminWithListFilter(Book, AdminSite()).check() self.assertEqual(errors, []) finally: Book._meta.apps.ready = True
wkschwartz/django
tests/admin_checks/tests.py
Python
bsd-3-clause
32,171
// Copyright 2015 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. #include "sky/compositor/clip_rrect_layer.h" namespace sky { namespace compositor { ClipRRectLayer::ClipRRectLayer() { } ClipRRectLayer::~ClipRRectLayer() { } void ClipRRectLayer::Paint(PaintContext::ScopedFrame& frame) { SkCanvas& canvas = frame.canvas(); canvas.saveLayer(&clip_rrect_.getBounds(), nullptr); canvas.clipRRect(clip_rrect_); PaintChildren(frame); canvas.restore(); } } // namespace compositor } // namespace sky
mdakin/engine
sky/compositor/clip_rrect_layer.cc
C++
bsd-3-clause
611
/* * Copyright (c) 2009-2018 jMonkeyEngine * 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 'jMonkeyEngine' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.jme3.input.lwjgl; import com.jme3.cursors.plugins.JmeCursor; import com.jme3.input.MouseInput; import com.jme3.input.RawInputListener; import com.jme3.input.event.MouseButtonEvent; import com.jme3.input.event.MouseMotionEvent; import com.jme3.system.lwjgl.LwjglAbstractDisplay; import com.jme3.system.lwjgl.LwjglTimer; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import org.lwjgl.LWJGLException; import org.lwjgl.Sys; import org.lwjgl.input.Cursor; import org.lwjgl.input.Mouse; public class LwjglMouseInput implements MouseInput { private static final Logger logger = Logger.getLogger(LwjglMouseInput.class.getName()); private LwjglAbstractDisplay context; private RawInputListener listener; private boolean supportHardwareCursor = false; private boolean cursorVisible = true; /** * We need to cache the cursors * (https://github.com/jMonkeyEngine/jmonkeyengine/issues/537) */ private Map<JmeCursor, Cursor> cursorMap = new HashMap<JmeCursor, Cursor>(); private int curX, curY, curWheel; public LwjglMouseInput(LwjglAbstractDisplay context){ this.context = context; } public void initialize() { if (!context.isRenderable()) return; try { Mouse.create(); logger.fine("Mouse created."); supportHardwareCursor = (Cursor.getCapabilities() & Cursor.CURSOR_ONE_BIT_TRANSPARENCY) != 0; // Recall state that was set before initialization Mouse.setGrabbed(!cursorVisible); } catch (LWJGLException ex) { logger.log(Level.SEVERE, "Error while creating mouse", ex); } if (listener != null) { sendFirstMouseEvent(); } } public boolean isInitialized(){ return Mouse.isCreated(); } public int getButtonCount(){ return Mouse.getButtonCount(); } public void update() { if (!context.isRenderable()) return; while (Mouse.next()){ int btn = Mouse.getEventButton(); int wheelDelta = Mouse.getEventDWheel(); int xDelta = Mouse.getEventDX(); int yDelta = Mouse.getEventDY(); int x = Mouse.getX(); int y = Mouse.getY(); curWheel += wheelDelta; if (cursorVisible){ xDelta = x - curX; yDelta = y - curY; curX = x; curY = y; }else{ x = curX + xDelta; y = curY + yDelta; curX = x; curY = y; } if (xDelta != 0 || yDelta != 0 || wheelDelta != 0){ MouseMotionEvent evt = new MouseMotionEvent(x, y, xDelta, yDelta, curWheel, wheelDelta); evt.setTime(Mouse.getEventNanoseconds()); listener.onMouseMotionEvent(evt); } if (btn != -1){ MouseButtonEvent evt = new MouseButtonEvent(btn, Mouse.getEventButtonState(), x, y); evt.setTime(Mouse.getEventNanoseconds()); listener.onMouseButtonEvent(evt); } } } public void destroy() { if (!context.isRenderable()) return; Mouse.destroy(); // Destroy the cursor cache for (Cursor cursor : cursorMap.values()) { cursor.destroy(); } cursorMap.clear(); logger.fine("Mouse destroyed."); } public void setCursorVisible(boolean visible){ cursorVisible = visible; if (!context.isRenderable()) return; Mouse.setGrabbed(!visible); } @Override public void setInputListener(RawInputListener listener) { this.listener = listener; if (listener != null && Mouse.isCreated()) { sendFirstMouseEvent(); } } /** * Send the input listener a special mouse-motion event with zero deltas in * order to initialize the listener's cursor position. */ private void sendFirstMouseEvent() { assert listener != null; assert Mouse.isCreated(); int x = Mouse.getX(); int y = Mouse.getY(); int xDelta = 0; int yDelta = 0; int wheelDelta = 0; MouseMotionEvent evt = new MouseMotionEvent(x, y, xDelta, yDelta, curWheel, wheelDelta); evt.setTime(Mouse.getEventNanoseconds()); listener.onMouseMotionEvent(evt); } public long getInputTimeNanos() { return Sys.getTime() * LwjglTimer.LWJGL_TIME_TO_NANOS; } public void setNativeCursor(JmeCursor jmeCursor) { try { Cursor newCursor = null; if (jmeCursor != null) { newCursor = cursorMap.get(jmeCursor); if (newCursor == null) { newCursor = new Cursor( jmeCursor.getWidth(), jmeCursor.getHeight(), jmeCursor.getXHotSpot(), jmeCursor.getYHotSpot(), jmeCursor.getNumImages(), jmeCursor.getImagesData(), jmeCursor.getImagesDelay()); // Add to cache cursorMap.put(jmeCursor, newCursor); } } Mouse.setNativeCursor(newCursor); } catch (LWJGLException ex) { Logger.getLogger(LwjglMouseInput.class.getName()).log(Level.SEVERE, null, ex); } } }
atomixnmc/jmonkeyengine
jme3-lwjgl/src/main/java/com/jme3/input/lwjgl/LwjglMouseInput.java
Java
bsd-3-clause
7,267
# Non functional issues - ~~Fix broken build~~ - ~~Add a license~~ - ~~Build file~~ - ~~Test build on TeamCity~~ - ~~NuSpec~~ # Functional issues ## To complete - Extra tests that prove that an identifier can't be null (repository) - Complete tests for test result - Complete tests for aggregate scenario test specification infrastructure - Factory tests are missing - ThrowsFixture is missing for all - Usage of indented text writer as the text writer for specifications and results ## Features - ~~[DESIGN] Replace Guid by String as identifier (supersedes)~~ - ~~[DESIGN] Support both Guid and String as identifier - using conditional compilation~~ - ~~[DESIGN] Support both Guid and String as identifier - using yet another abstraction~~ - ~~[DESIGN] The asynchronous repository~~ - ~~[DESIGN] Snapshotting~~ - [DESIGN] StreamSource - Writing to sql - [DESIGN] StreamSource - Reading from sql - [DESIGN] StreamSource - Readonly resource oriented API using Nancy - Extend SampleSource with an async sample. - DRY up those repos, there's a SlicedEventStreamReader in them (bonus, we can test this thing separately). - Build a realistic app on top of this API that shows off entities, aggregates, testing, bulk loading. ## Ideas AggregateSource.Repositories AggregateSource.CollectionRepositories.EventStore AggregateSource.CollectionRepositories.NEventStore AggregateSource.PersistenceRepositories.EventStore AggregateSource.PersistenceRepositories.NEventStore
yreynhout/AggregateSource
docs/backlog.md
Markdown
bsd-3-clause
1,480
// Copyright 2014 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. #include "mojo/gles2/command_buffer_client_impl.h" #include <stddef.h> #include <stdint.h> #include <limits> #include <utility> #include "base/logging.h" #include "base/process/process_handle.h" #include "base/threading/thread_restrictions.h" #include "components/mus/gles2/command_buffer_type_conversions.h" #include "components/mus/gles2/mojo_buffer_backing.h" #include "components/mus/gles2/mojo_gpu_memory_buffer.h" #include "gpu/command_buffer/client/gpu_control_client.h" #include "gpu/command_buffer/common/command_buffer_id.h" #include "gpu/command_buffer/common/gpu_memory_buffer_support.h" #include "gpu/command_buffer/common/sync_token.h" #include "mojo/platform_handle/platform_handle_functions.h" namespace gles2 { namespace { bool CreateMapAndDupSharedBuffer(size_t size, void** memory, mojo::ScopedSharedBufferHandle* handle, mojo::ScopedSharedBufferHandle* duped) { MojoResult result = mojo::CreateSharedBuffer(NULL, size, handle); if (result != MOJO_RESULT_OK) return false; DCHECK(handle->is_valid()); result = mojo::DuplicateBuffer(handle->get(), NULL, duped); if (result != MOJO_RESULT_OK) return false; DCHECK(duped->is_valid()); result = mojo::MapBuffer( handle->get(), 0, size, memory, MOJO_MAP_BUFFER_FLAG_NONE); if (result != MOJO_RESULT_OK) return false; DCHECK(*memory); return true; } void MakeProgressCallback( gpu::CommandBuffer::State* output, const gpu::CommandBuffer::State& input) { *output = input; } void InitializeCallback(mus::mojom::CommandBufferInitializeResultPtr* output, mus::mojom::CommandBufferInitializeResultPtr input) { *output = std::move(input); } } // namespace CommandBufferClientImpl::CommandBufferClientImpl( const std::vector<int32_t>& attribs, mojo::ScopedMessagePipeHandle command_buffer_handle) : gpu_control_client_(nullptr), destroyed_(false), attribs_(attribs), client_binding_(this), command_buffer_id_(), shared_state_(NULL), last_put_offset_(-1), next_transfer_buffer_id_(0), next_image_id_(0), next_fence_sync_release_(1), flushed_fence_sync_release_(0) { command_buffer_.Bind(mojo::InterfacePtrInfo<mus::mojom::CommandBuffer>( std::move(command_buffer_handle), 0u)); command_buffer_.set_connection_error_handler( [this]() { Destroyed(gpu::error::kUnknown, gpu::error::kLostContext); }); } CommandBufferClientImpl::~CommandBufferClientImpl() {} bool CommandBufferClientImpl::Initialize() { const size_t kSharedStateSize = sizeof(gpu::CommandBufferSharedState); void* memory = NULL; mojo::ScopedSharedBufferHandle duped; bool result = CreateMapAndDupSharedBuffer( kSharedStateSize, &memory, &shared_state_handle_, &duped); if (!result) return false; shared_state_ = static_cast<gpu::CommandBufferSharedState*>(memory); shared_state()->Initialize(); mus::mojom::CommandBufferClientPtr client_ptr; client_binding_.Bind(GetProxy(&client_ptr)); mus::mojom::CommandBufferInitializeResultPtr initialize_result; command_buffer_->Initialize( std::move(client_ptr), std::move(duped), mojo::Array<int32_t>::From(attribs_), base::Bind(&InitializeCallback, &initialize_result)); base::ThreadRestrictions::ScopedAllowWait wait; if (!command_buffer_.WaitForIncomingResponse()) { VLOG(1) << "Channel encountered error while creating command buffer."; return false; } if (!initialize_result) { VLOG(1) << "Command buffer cannot be initialized successfully."; return false; } DCHECK_EQ(gpu::CommandBufferNamespace::MOJO, initialize_result->command_buffer_namespace); command_buffer_id_ = gpu::CommandBufferId::FromUnsafeValue( initialize_result->command_buffer_id); capabilities_ = initialize_result->capabilities; return true; } gpu::CommandBuffer::State CommandBufferClientImpl::GetLastState() { return last_state_; } int32_t CommandBufferClientImpl::GetLastToken() { TryUpdateState(); return last_state_.token; } void CommandBufferClientImpl::Flush(int32_t put_offset) { if (last_put_offset_ == put_offset) return; last_put_offset_ = put_offset; command_buffer_->Flush(put_offset); flushed_fence_sync_release_ = next_fence_sync_release_ - 1; } void CommandBufferClientImpl::OrderingBarrier(int32_t put_offset) { // TODO(jamesr): Implement this more efficiently. Flush(put_offset); } void CommandBufferClientImpl::WaitForTokenInRange(int32_t start, int32_t end) { TryUpdateState(); while (!InRange(start, end, last_state_.token) && last_state_.error == gpu::error::kNoError) { MakeProgressAndUpdateState(); } } void CommandBufferClientImpl::WaitForGetOffsetInRange(int32_t start, int32_t end) { TryUpdateState(); while (!InRange(start, end, last_state_.get_offset) && last_state_.error == gpu::error::kNoError) { MakeProgressAndUpdateState(); } } void CommandBufferClientImpl::SetGetBuffer(int32_t shm_id) { command_buffer_->SetGetBuffer(shm_id); last_put_offset_ = -1; } scoped_refptr<gpu::Buffer> CommandBufferClientImpl::CreateTransferBuffer( size_t size, int32_t* id) { if (size >= std::numeric_limits<uint32_t>::max()) return NULL; void* memory = NULL; mojo::ScopedSharedBufferHandle handle; mojo::ScopedSharedBufferHandle duped; if (!CreateMapAndDupSharedBuffer(size, &memory, &handle, &duped)) { if (last_state_.error == gpu::error::kNoError) last_state_.error = gpu::error::kLostContext; return NULL; } *id = ++next_transfer_buffer_id_; command_buffer_->RegisterTransferBuffer(*id, std::move(duped), static_cast<uint32_t>(size)); std::unique_ptr<gpu::BufferBacking> backing( new mus::MojoBufferBacking(std::move(handle), memory, size)); scoped_refptr<gpu::Buffer> buffer(new gpu::Buffer(std::move(backing))); return buffer; } void CommandBufferClientImpl::DestroyTransferBuffer(int32_t id) { command_buffer_->DestroyTransferBuffer(id); } void CommandBufferClientImpl::SetGpuControlClient(gpu::GpuControlClient* c) { gpu_control_client_ = c; } gpu::Capabilities CommandBufferClientImpl::GetCapabilities() { return capabilities_; } int32_t CommandBufferClientImpl::CreateImage(ClientBuffer buffer, size_t width, size_t height, unsigned internalformat) { int32_t new_id = ++next_image_id_; mojo::SizePtr size = mojo::Size::New(); size->width = static_cast<int32_t>(width); size->height = static_cast<int32_t>(height); mus::MojoGpuMemoryBufferImpl* gpu_memory_buffer = mus::MojoGpuMemoryBufferImpl::FromClientBuffer(buffer); gfx::GpuMemoryBufferHandle handle = gpu_memory_buffer->GetHandle(); bool requires_sync_point = false; if (handle.type != gfx::SHARED_MEMORY_BUFFER) { requires_sync_point = true; NOTIMPLEMENTED(); return -1; } base::SharedMemoryHandle dupd_handle = base::SharedMemory::DuplicateHandle(handle.handle); #if defined(OS_WIN) HANDLE platform_handle = dupd_handle.GetHandle(); #else int platform_handle = dupd_handle.fd; #endif MojoHandle mojo_handle = MOJO_HANDLE_INVALID; MojoResult create_result = MojoCreatePlatformHandleWrapper( platform_handle, &mojo_handle); if (create_result != MOJO_RESULT_OK) { NOTIMPLEMENTED(); return -1; } mojo::ScopedHandle scoped_handle; scoped_handle.reset(mojo::Handle(mojo_handle)); command_buffer_->CreateImage( new_id, std::move(scoped_handle), handle.type, std::move(size), static_cast<int32_t>(gpu_memory_buffer->GetFormat()), internalformat); if (requires_sync_point) { NOTIMPLEMENTED(); // TODO(jam): need to support this if we support types other than // SHARED_MEMORY_BUFFER. //gpu_memory_buffer_manager->SetDestructionSyncPoint(gpu_memory_buffer, // InsertSyncPoint()); } return new_id; } void CommandBufferClientImpl::DestroyImage(int32_t id) { command_buffer_->DestroyImage(id); } int32_t CommandBufferClientImpl::CreateGpuMemoryBufferImage( size_t width, size_t height, unsigned internalformat, unsigned usage) { std::unique_ptr<gfx::GpuMemoryBuffer> buffer( mus::MojoGpuMemoryBufferImpl::Create( gfx::Size(static_cast<int>(width), static_cast<int>(height)), gpu::DefaultBufferFormatForImageFormat(internalformat), gfx::BufferUsage::SCANOUT)); if (!buffer) return -1; return CreateImage(buffer->AsClientBuffer(), width, height, internalformat); } void CommandBufferClientImpl::SignalQuery(uint32_t query, const base::Closure& callback) { // TODO(piman) NOTIMPLEMENTED(); } void CommandBufferClientImpl::Destroyed(int32_t lost_reason, int32_t error) { if (destroyed_) return; last_state_.context_lost_reason = static_cast<gpu::error::ContextLostReason>(lost_reason); last_state_.error = static_cast<gpu::error::Error>(error); if (gpu_control_client_) gpu_control_client_->OnGpuControlLostContext(); destroyed_ = true; } void CommandBufferClientImpl::SignalAck(uint32_t id) { } void CommandBufferClientImpl::SwapBuffersCompleted(int32_t result) { } void CommandBufferClientImpl::UpdateState( const gpu::CommandBuffer::State& state) { } void CommandBufferClientImpl::UpdateVSyncParameters(int64_t timebase, int64_t interval) { } void CommandBufferClientImpl::TryUpdateState() { if (last_state_.error == gpu::error::kNoError) shared_state()->Read(&last_state_); } void CommandBufferClientImpl::MakeProgressAndUpdateState() { gpu::CommandBuffer::State state; command_buffer_->MakeProgress( last_state_.get_offset, base::Bind(&MakeProgressCallback, &state)); base::ThreadRestrictions::ScopedAllowWait wait; if (!command_buffer_.WaitForIncomingResponse()) { VLOG(1) << "Channel encountered error while waiting for command buffer."; // TODO(piman): is it ok for this to re-enter? Destroyed(gpu::error::kUnknown, gpu::error::kLostContext); return; } if (state.generation - last_state_.generation < 0x80000000U) last_state_ = state; } void CommandBufferClientImpl::SetLock(base::Lock* lock) { } void CommandBufferClientImpl::EnsureWorkVisible() { // This is only relevant for out-of-process command buffers. } gpu::CommandBufferNamespace CommandBufferClientImpl::GetNamespaceID() const { return gpu::CommandBufferNamespace::MOJO; } gpu::CommandBufferId CommandBufferClientImpl::GetCommandBufferID() const { return command_buffer_id_; } int32_t CommandBufferClientImpl::GetExtraCommandBufferData() const { return 0; } uint64_t CommandBufferClientImpl::GenerateFenceSyncRelease() { return next_fence_sync_release_++; } bool CommandBufferClientImpl::IsFenceSyncRelease(uint64_t release) { return release != 0 && release < next_fence_sync_release_; } bool CommandBufferClientImpl::IsFenceSyncFlushed(uint64_t release) { return release != 0 && release <= flushed_fence_sync_release_; } bool CommandBufferClientImpl::IsFenceSyncFlushReceived(uint64_t release) { return IsFenceSyncFlushed(release); } void CommandBufferClientImpl::SignalSyncToken(const gpu::SyncToken& sync_token, const base::Closure& callback) { // TODO(dyen) NOTIMPLEMENTED(); } bool CommandBufferClientImpl::CanWaitUnverifiedSyncToken( const gpu::SyncToken* sync_token) { // Right now, MOJO_LOCAL is only used by trusted code, so it is safe to wait // on a sync token in MOJO_LOCAL command buffer. if (sync_token->namespace_id() == gpu::CommandBufferNamespace::MOJO_LOCAL) return true; // It is also safe to wait on the same context. if (sync_token->namespace_id() == gpu::CommandBufferNamespace::MOJO && sync_token->command_buffer_id() == GetCommandBufferID()) return true; return false; } } // namespace gles2
axinging/chromium-crosswalk
mojo/gles2/command_buffer_client_impl.cc
C++
bsd-3-clause
12,441
########################################################################## # # Copyright (c) 2013-2014, John Haddon. 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 John Haddon nor the names of # any other contributors to this software may be used to endorse or # promote products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ########################################################################## import IECore import Gaffer import GafferUI import GafferOSL import imath import functools _channelNamesOptions = { "RGB" : IECore.Color3fData( imath.Color3f( 1 ) ), "RGBA" : IECore.Color4fData( imath.Color4f( 1 ) ), "R" : IECore.FloatData( 1 ), "G" : IECore.FloatData( 1 ), "B" : IECore.FloatData( 1 ), "A" : IECore.FloatData( 1 ), "customChannel" : IECore.FloatData( 1 ), "customLayer" : IECore.Color3fData( imath.Color3f( 1 ) ), "customLayerRGBA" : IECore.Color4fData( imath.Color4f( 1 ) ), "closure" : None, } ########################################################################## # _ChannelsFooter ########################################################################## class _ChannelsFooter( GafferUI.PlugValueWidget ) : def __init__( self, plug ) : row = GafferUI.ListContainer( GafferUI.ListContainer.Orientation.Horizontal ) GafferUI.PlugValueWidget.__init__( self, row, plug ) with row : GafferUI.Spacer( imath.V2i( GafferUI.PlugWidget.labelWidth(), 1 ) ) menuButton = GafferUI.MenuButton( image = "plus.png", hasFrame = False, menu = GafferUI.Menu( Gaffer.WeakMethod( self.__menuDefinition ), title = "Add Input" ), toolTip = "Add Input" ) menuButton.setEnabled( not Gaffer.MetadataAlgo.readOnly( plug ) ) GafferUI.Spacer( imath.V2i( 1 ), imath.V2i( 999999, 1 ), parenting = { "expand" : True } ) def _updateFromPlug( self ) : self.setEnabled( self._editable() ) def __menuDefinition( self ) : result = IECore.MenuDefinition() usedNames = set() for p in self.getPlug().children(): # TODO - this method for checking if a plug variesWithContext should probably live in PlugAlgo # ( it's based on Switch::variesWithContext ) sourcePlug = p["name"].source() variesWithContext = sourcePlug.direction() == Gaffer.Plug.Direction.Out and isinstance( ComputeNode, sourcePlug.node() ) if not variesWithContext: usedNames.add( p["name"].getValue() ) # Use a fixed order for some standard options that we want to list in a specific order sortedOptions = [] for label in ["RGB", "RGBA", "R", "G", "B", "A" ]: sortedOptions.append( (label, _channelNamesOptions[label] ) ) for label, defaultData in sorted( _channelNamesOptions.items() ): if not label in [ i[0] for i in sortedOptions ]: sortedOptions.append( (label, defaultData) ) categories = { "Standard" : [], "Custom" : [], "Advanced" : [] } for label, defaultData in sortedOptions: if label == "closure": categories["Advanced"].append( ( label, label, defaultData ) ) else: bareLabel = label.replace( "RGBA", "" ).replace( "RGB", "" ) channelName = bareLabel if label.startswith( "custom" ): if channelName in usedNames: suffix = 2 while True: channelName = bareLabel + str( suffix ) if not channelName in usedNames: break suffix += 1 categories["Custom"].append( ( label, channelName, defaultData ) ) else: if channelName in usedNames: continue categories["Standard"].append( ( label, channelName, defaultData ) ) for category in [ "Standard", "Custom", "Advanced" ]: for ( menuLabel, channelName, defaultData ) in categories[category]: result.append( "/" + category + "/" + menuLabel, { "command" : functools.partial( Gaffer.WeakMethod( self.__addPlug ), channelName, defaultData ), } ) return result def __addPlug( self, name, defaultData ) : alphaValue = None if isinstance( defaultData, IECore.Color4fData ): alphaValue = Gaffer.FloatPlug( "value", Gaffer.Plug.Direction.In, defaultData.value.a ) defaultData = IECore.Color3fData( imath.Color3f( defaultData.value.r, defaultData.value.g, defaultData.value.b ) ) if defaultData == None: plugName = "closure" name = "" valuePlug = GafferOSL.ClosurePlug( "value" ) else: plugName = "channel" valuePlug = Gaffer.PlugAlgo.createPlugFromData( "value", Gaffer.Plug.Direction.In, Gaffer.Plug.Flags.Default, defaultData ) with Gaffer.UndoScope( self.getPlug().ancestor( Gaffer.ScriptNode ) ) : self.getPlug().addChild( Gaffer.NameValuePlug( name, valuePlug, True, plugName, Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.Dynamic ) ) if alphaValue: self.getPlug().addChild( Gaffer.NameValuePlug( name + ".A" if name else "A", alphaValue, True, plugName, Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.Dynamic ) ) def __channelLabelFromPlug( plug ): if plug.typeId() == GafferOSL.ClosurePlug.staticTypeId(): return plug.parent().getName() elif plug.typeId() == Gaffer.Color3fPlug.staticTypeId() and plug.parent()["name"].getValue() == "": return "[RGB]" else: return plug.parent()["name"].getValue() ########################################################################## # Metadata ########################################################################## Gaffer.Metadata.registerNode( GafferOSL.OSLImage, "description", """ Executes OSL shaders to perform image processing. Use the shaders from the OSL/ImageProcessing menu to read values from the input image and then write values back to it. """, "plugAdderOptions", IECore.CompoundData( _channelNamesOptions ), "layout:activator:defaultFormatActive", lambda node : not node["in"].getInput(), plugs = { "defaultFormat" : [ "description", """ The resolution and aspect ratio to output when there is no input image provided. """, "layout:activator", "defaultFormatActive", ], "channels" : [ "description", """ Define image channels to output by adding child plugs and connecting corresponding OSL shaders. You can drive RGB layers with a color, or connect individual channels to a float. If you want to add multiple channels at once, you can also add a closure plug, which can accept a connection from an OSLCode with a combined output closure. """, "layout:customWidget:footer:widgetType", "GafferOSLUI.OSLImageUI._ChannelsFooter", "layout:customWidget:footer:index", -1, "nodule:type", "GafferUI::CompoundNodule", "noduleLayout:section", "left", "noduleLayout:spacing", 0.2, "plugValueWidget:type", "GafferUI.LayoutPlugValueWidget", # Add + button for showing and hiding parameters in the GraphEditor "noduleLayout:customGadget:addButton:gadgetType", "GafferOSLUI.OSLImageUI.PlugAdder", ], "channels.*" : [ # Although the parameters plug is positioned # as we want above, we must also register # appropriate values for each individual parameter, # for the case where they get promoted to a box # individually. "noduleLayout:section", "left", "nodule:type", "GafferUI::CompoundNodule", "nameValuePlugPlugValueWidget:ignoreNamePlug", lambda plug : isinstance( plug["value"], GafferOSL.ClosurePlug ), ], "channels.*.name" : [ "nodule:type", "", "stringPlugValueWidget:placeholderText", lambda plug : "[RGB]" if isinstance( plug.parent()["value"], Gaffer.Color3fPlug ) else None, ], "channels.*.enabled" : [ "nodule:type", "", ], "channels.*.value" : [ # Although the parameters plug is positioned # as we want above, we must also register # appropriate values for each individual parameter, # for the case where they get promoted to a box # individually. "noduleLayout:section", "left", "nodule:type", "GafferUI::StandardNodule", "noduleLayout:label", __channelLabelFromPlug, "ui:visibleDimensions", lambda plug : 2 if hasattr( plug, "interpretation" ) and plug.interpretation() == IECore.GeometricData.Interpretation.UV else None, ], } )
lucienfostier/gaffer
python/GafferOSLUI/OSLImageUI.py
Python
bsd-3-clause
9,411
// Copyright 2014 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. Polymer({ is: 'viewer-error-screen', properties: { text: String, reloadFn: { type: Object, value: null, } }, show: function() { this.$.dialog.open(); }, reload: function() { if (this.reloadFn) this.reloadFn(); } });
Chilledheart/chromium
chrome/browser/resources/pdf/elements/viewer-error-screen/viewer-error-screen.js
JavaScript
bsd-3-clause
437
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Rainer Gericke // ============================================================================= // // Marder single-pin track assembly subsystem. // // ============================================================================= #ifndef MARDER_TRACK_ASSEMBLY_SINGLE_PIN_H #define MARDER_TRACK_ASSEMBLY_SINGLE_PIN_H #include <string> #include "chrono_vehicle/tracked_vehicle/track_assembly/ChTrackAssemblySinglePin.h" #include "chrono_models/ChApiModels.h" namespace chrono { namespace vehicle { namespace marder { /// @addtogroup vehicle_models_marder /// @{ /// Marder track assembly using single-pin track shoes. class CH_MODELS_API Marder_TrackAssemblySinglePin : public ChTrackAssemblySinglePin { public: Marder_TrackAssemblySinglePin(VehicleSide side, BrakeType brake_type); virtual const ChVector<> GetSprocketLocation() const override; virtual const ChVector<> GetIdlerLocation() const override; virtual const ChVector<> GetRoadWhelAssemblyLocation(int which) const override; virtual const ChVector<> GetRollerLocation(int which) const override; private: static const ChVector<> m_sprocket_loc; static const ChVector<> m_idler_loc; static const ChVector<> m_susp_locs_L[6]; static const ChVector<> m_susp_locs_R[6]; static const ChVector<> m_supp_locs_L[3]; static const ChVector<> m_supp_locs_R[3]; static const double m_right_x_offset; }; /// @} vehicle_models_marder } // namespace marder } // end namespace vehicle } // end namespace chrono #endif
rserban/chrono
src/chrono_models/vehicle/marder/Marder_TrackAssemblySinglePin.h
C
bsd-3-clause
2,014
//============================================================================== // Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2012 LRI UMR 8623 CNRS/Univ Paris Sud XI // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #ifndef BOOST_SIMD_SDK_SIMD_PACK_GRAMMAR_HPP_INCLUDED #define BOOST_SIMD_SDK_SIMD_PACK_GRAMMAR_HPP_INCLUDED #include <boost/proto/matches.hpp> namespace boost { namespace simd { typedef boost::proto::_ grammar; } } #endif
hainm/pythran
third_party/boost/simd/sdk/simd/pack/grammar.hpp
C++
bsd-3-clause
735
import django.db.models.deletion import oauthlib.common from django.db import migrations, models def move_existing_token(apps, schema_editor): ServiceAccount = apps.get_model("account", "ServiceAccount") for service_account in ServiceAccount.objects.iterator(): service_account.tokens.create( name="Default", auth_token=service_account.auth_token ) class Migration(migrations.Migration): dependencies = [("account", "0033_serviceaccount")] operations = [ migrations.CreateModel( name="ServiceAccountToken", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("name", models.CharField(blank=True, default="", max_length=128)), ( "auth_token", models.CharField( default=oauthlib.common.generate_token, max_length=30, unique=True, ), ), ( "service_account", models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, related_name="tokens", to="account.ServiceAccount", ), ), ], ), migrations.RunPython(move_existing_token), migrations.RemoveField(model_name="serviceaccount", name="auth_token"), ]
maferelo/saleor
saleor/account/migrations/0034_service_account_token.py
Python
bsd-3-clause
1,717
// RUN: %clang_cc1 -fxray-instrument \ // RUN: -fxray-instrumentation-bundle=function-entry -x c++ \ // RUN: -std=c++11 -triple x86_64-unknown-unknown -emit-llvm -o - %s \ // RUN: | FileCheck --check-prefixes CHECK,SKIPEXIT %s // RUN: %clang_cc1 -fxray-instrument \ // RUN: -fxray-instrumentation-bundle=function-exit -x c++ \ // RUN: -std=c++11 -triple x86_64-unknown-unknown -emit-llvm -o - %s \ // RUN: | FileCheck --check-prefixes CHECK,SKIPENTRY %s // RUN: %clang_cc1 -fxray-instrument \ // RUN: -fxray-instrumentation-bundle=function-entry,function-exit -x c++ \ // RUN: -std=c++11 -triple x86_64-unknown-unknown -emit-llvm -o - %s \ // RUN: | FileCheck --check-prefixes CHECK,NOSKIPENTRY,NOSKIPEXIT %s // CHECK: define void @_Z13justAFunctionv() #[[ATTR:[0-9]+]] { void justAFunction() { } // SKIPENTRY: attributes #[[ATTR]] = {{.*}} "xray-skip-entry" {{.*}} // SKIPEXIT: attributes #[[ATTR]] = {{.*}} "xray-skip-exit" {{.*}} // NOSKIPENTRY-NOT: attributes #[[ATTR]] = {{.*}} "xray-skip-entry" {{.*}} // NOSKIPEXIT-NOT: attributes #[[ATTR]] = {{.*}} "xray-skip-exit" {{.*}}
endlessm/chromium-browser
third_party/llvm/clang/test/CodeGen/xray-attributes-skip-entry-exit.cpp
C++
bsd-3-clause
1,120
import six from django import template from oscar.core.loading import get_model from django.utils.translation import ugettext_lazy as _ from django.core.urlresolvers import resolve, Resolver404 from oscar.apps.customer import history from oscar.core.compat import urlparse Site = get_model('sites', 'Site') register = template.Library() @register.inclusion_tag('customer/history/recently_viewed_products.html', takes_context=True) def recently_viewed_products(context): """ Inclusion tag listing the most recently viewed products """ request = context['request'] products = history.get(request) return {'products': products, 'request': request} @register.assignment_tag(takes_context=True) def get_back_button(context): """ Show back button, custom title available for different urls, for example 'Back to search results', no back button if user came from other site """ request = context.get('request', None) if not request: raise Exception('Cannot get request from context') referrer = request.META.get('HTTP_REFERER', None) if not referrer: return None try: url = urlparse.urlparse(referrer) except: return None if request.get_host() != url.netloc: try: Site.objects.get(domain=url.netloc) except Site.DoesNotExist: # Came from somewhere else, don't show back button: return None try: match = resolve(url.path) except Resolver404: return None # This dict can be extended to link back to other browsing pages titles = { 'search:search': _('Back to search results'), } title = titles.get(match.view_name, None) if title is None: return None return {'url': referrer, 'title': six.text_type(title), 'match': match}
MrReN/django-oscar
oscar/templatetags/history_tags.py
Python
bsd-3-clause
1,884
// Copyright 2013 tsuru authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package api import ( "encoding/json" "fmt" "net/http" "strconv" "time" "github.com/tsuru/tsuru/app" "github.com/tsuru/tsuru/auth" tsuruErrors "github.com/tsuru/tsuru/errors" "github.com/tsuru/tsuru/event" tsuruIo "github.com/tsuru/tsuru/io" "github.com/tsuru/tsuru/permission" "github.com/tsuru/tsuru/repository" ) // title: app deploy // path: /apps/{appname}/deploy // method: POST // consume: application/x-www-form-urlencoded // responses: // 200: OK // 400: Invalid data // 403: Forbidden // 404: Not found func deploy(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) { opts, err := prepareToBuild(r) if err != nil { return err } if opts.File != nil { defer opts.File.Close() } commit := r.FormValue("commit") w.Header().Set("Content-Type", "text") appName := r.URL.Query().Get(":appname") origin := r.FormValue("origin") if opts.Image != "" { origin = "image" } if origin != "" { if !app.ValidateOrigin(origin) { return &tsuruErrors.HTTP{ Code: http.StatusBadRequest, Message: "Invalid deployment origin", } } } var userName string if t.IsAppToken() { if t.GetAppName() != appName && t.GetAppName() != app.InternalAppName { return &tsuruErrors.HTTP{Code: http.StatusUnauthorized, Message: "invalid app token"} } userName = r.FormValue("user") } else { commit = "" userName = t.GetUserName() } instance, err := app.GetByName(appName) if err != nil { return &tsuruErrors.HTTP{Code: http.StatusNotFound, Message: err.Error()} } message := r.FormValue("message") if commit != "" && message == "" { var messages []string messages, err = repository.Manager().CommitMessages(instance.Name, commit, 1) if err != nil { return err } if len(messages) > 0 { message = messages[0] } } if origin == "" && commit != "" { origin = "git" } opts.App = instance opts.Commit = commit opts.User = userName opts.Origin = origin opts.Message = message opts.GetKind() if t.GetAppName() != app.InternalAppName { canDeploy := permission.Check(t, permSchemeForDeploy(opts), contextsForApp(instance)...) if !canDeploy { return &tsuruErrors.HTTP{Code: http.StatusForbidden, Message: "User does not have permission to do this action in this app"} } } var imageID string evt, err := event.New(&event.Opts{ Target: appTarget(appName), Kind: permission.PermAppDeploy, RawOwner: event.Owner{Type: event.OwnerTypeUser, Name: userName}, CustomData: opts, Allowed: event.Allowed(permission.PermAppReadEvents, contextsForApp(instance)...), AllowedCancel: event.Allowed(permission.PermAppUpdateEvents, contextsForApp(instance)...), Cancelable: true, }) if err != nil { return err } defer func() { evt.DoneCustomData(err, map[string]string{"image": imageID}) }() opts.Event = evt writer := tsuruIo.NewKeepAliveWriter(w, 30*time.Second, "please wait...") defer writer.Stop() opts.OutputStream = writer imageID, err = app.Deploy(opts) if err == nil { fmt.Fprintln(w, "\nOK") } return err } func permSchemeForDeploy(opts app.DeployOptions) *permission.PermissionScheme { switch opts.GetKind() { case app.DeployGit: return permission.PermAppDeployGit case app.DeployImage: return permission.PermAppDeployImage case app.DeployUpload: return permission.PermAppDeployUpload case app.DeployUploadBuild: return permission.PermAppDeployBuild case app.DeployArchiveURL: return permission.PermAppDeployArchiveUrl case app.DeployRollback: return permission.PermAppDeployRollback default: return permission.PermAppDeploy } } // title: deploy diff // path: /apps/{appname}/diff // method: POST // consume: application/x-www-form-urlencoded // responses: // 200: OK // 400: Invalid data // 403: Forbidden // 404: Not found func diffDeploy(w http.ResponseWriter, r *http.Request, t auth.Token) error { writer := tsuruIo.NewKeepAliveWriter(w, 30*time.Second, "") defer writer.Stop() fmt.Fprint(w, "Saving the difference between the old and new code\n") appName := r.URL.Query().Get(":appname") diff := r.FormValue("customdata") instance, err := app.GetByName(appName) if err != nil { return &tsuruErrors.HTTP{Code: http.StatusNotFound, Message: err.Error()} } if t.GetAppName() != app.InternalAppName { canDiffDeploy := permission.Check(t, permission.PermAppReadDeploy, contextsForApp(instance)...) if !canDiffDeploy { return &tsuruErrors.HTTP{Code: http.StatusForbidden, Message: permission.ErrUnauthorized.Error()} } } evt, err := event.GetRunning(appTarget(appName), permission.PermAppDeploy.FullName()) if err != nil { return err } return evt.SetOtherCustomData(map[string]string{ "diff": diff, }) } // title: rollback // path: /apps/{appname}/deploy/rollback // method: POST // consume: application/x-www-form-urlencoded // produce: application/x-json-stream // responses: // 200: OK // 400: Invalid data // 403: Forbidden // 404: Not found func deployRollback(w http.ResponseWriter, r *http.Request, t auth.Token) error { appName := r.URL.Query().Get(":appname") instance, err := app.GetByName(appName) if err != nil { return &tsuruErrors.HTTP{Code: http.StatusNotFound, Message: fmt.Sprintf("App %s not found.", appName)} } image := r.FormValue("image") if image == "" { return &tsuruErrors.HTTP{ Code: http.StatusBadRequest, Message: "you cannot rollback without an image name", } } origin := r.FormValue("origin") if origin != "" { if !app.ValidateOrigin(origin) { return &tsuruErrors.HTTP{ Code: http.StatusBadRequest, Message: "Invalid deployment origin", } } } w.Header().Set("Content-Type", "application/x-json-stream") keepAliveWriter := tsuruIo.NewKeepAliveWriter(w, 30*time.Second, "") defer keepAliveWriter.Stop() writer := &tsuruIo.SimpleJsonMessageEncoderWriter{Encoder: json.NewEncoder(keepAliveWriter)} opts := app.DeployOptions{ App: instance, OutputStream: writer, Image: image, User: t.GetUserName(), Origin: origin, Rollback: true, } opts.GetKind() canRollback := permission.Check(t, permSchemeForDeploy(opts), contextsForApp(instance)...) if !canRollback { return &tsuruErrors.HTTP{Code: http.StatusForbidden, Message: permission.ErrUnauthorized.Error()} } var imageID string evt, err := event.New(&event.Opts{ Target: appTarget(appName), Kind: permission.PermAppDeploy, Owner: t, CustomData: opts, Allowed: event.Allowed(permission.PermAppReadEvents, contextsForApp(instance)...), AllowedCancel: event.Allowed(permission.PermAppUpdateEvents, contextsForApp(instance)...), Cancelable: true, }) if err != nil { return err } defer func() { evt.DoneCustomData(err, map[string]string{"image": imageID}) }() opts.Event = evt imageID, err = app.Deploy(opts) if err != nil { writer.Encode(tsuruIo.SimpleJsonMessage{Error: err.Error()}) } return nil } // title: deploy list // path: /deploys // method: GET // produce: application/json // responses: // 200: OK // 204: No content func deploysList(w http.ResponseWriter, r *http.Request, t auth.Token) error { contexts := permission.ContextsForPermission(t, permission.PermAppReadDeploy) if len(contexts) == 0 { w.WriteHeader(http.StatusNoContent) return nil } filter := appFilterByContext(contexts, nil) filter.Name = r.URL.Query().Get("app") skip := r.URL.Query().Get("skip") limit := r.URL.Query().Get("limit") skipInt, _ := strconv.Atoi(skip) limitInt, _ := strconv.Atoi(limit) deploys, err := app.ListDeploys(filter, skipInt, limitInt) if err != nil { return err } if len(deploys) == 0 { w.WriteHeader(http.StatusNoContent) return nil } w.Header().Add("Content-Type", "application/json") return json.NewEncoder(w).Encode(deploys) } // title: deploy info // path: /deploys/{deploy} // method: GET // produce: application/json // responses: // 200: OK // 401: Unauthorized // 404: Not found func deployInfo(w http.ResponseWriter, r *http.Request, t auth.Token) error { depID := r.URL.Query().Get(":deploy") deploy, err := app.GetDeploy(depID) if err != nil { if err == event.ErrEventNotFound { return &tsuruErrors.HTTP{Code: http.StatusNotFound, Message: "Deploy not found."} } return err } dbApp, err := app.GetByName(deploy.App) if err != nil { return err } canGet := permission.Check(t, permission.PermAppReadDeploy, contextsForApp(dbApp)...) if !canGet { return &tsuruErrors.HTTP{Code: http.StatusNotFound, Message: "Deploy not found."} } w.Header().Add("Content-Type", "application/json") return json.NewEncoder(w).Encode(deploy) } // title: rebuild // path: /apps/{appname}/deploy/rebuild // method: POST // consume: application/x-www-form-urlencoded // produce: application/x-json-stream // responses: // 200: OK // 400: Invalid data // 403: Forbidden // 404: Not found func deployRebuild(w http.ResponseWriter, r *http.Request, t auth.Token) error { appName := r.URL.Query().Get(":appname") instance, err := app.GetByName(appName) if err != nil { return &tsuruErrors.HTTP{Code: http.StatusNotFound, Message: fmt.Sprintf("App %s not found.", appName)} } origin := r.FormValue("origin") if !app.ValidateOrigin(origin) { return &tsuruErrors.HTTP{ Code: http.StatusBadRequest, Message: "Invalid deployment origin", } } w.Header().Set("Content-Type", "application/x-json-stream") keepAliveWriter := tsuruIo.NewKeepAliveWriter(w, 30*time.Second, "") defer keepAliveWriter.Stop() writer := &tsuruIo.SimpleJsonMessageEncoderWriter{Encoder: json.NewEncoder(keepAliveWriter)} opts := app.DeployOptions{ App: instance, OutputStream: writer, User: t.GetUserName(), Origin: origin, Kind: app.DeployRebuild, } canDeploy := permission.Check(t, permSchemeForDeploy(opts), contextsForApp(instance)...) if !canDeploy { return &tsuruErrors.HTTP{Code: http.StatusForbidden, Message: permission.ErrUnauthorized.Error()} } var imageID string evt, err := event.New(&event.Opts{ Target: appTarget(appName), Kind: permission.PermAppDeploy, Owner: t, CustomData: opts, Allowed: event.Allowed(permission.PermAppReadEvents, contextsForApp(instance)...), AllowedCancel: event.Allowed(permission.PermAppUpdateEvents, contextsForApp(instance)...), Cancelable: true, }) if err != nil { return err } defer func() { evt.DoneCustomData(err, map[string]string{"image": imageID}) }() opts.Event = evt imageID, err = app.Deploy(opts) if err != nil { writer.Encode(tsuruIo.SimpleJsonMessage{Error: err.Error()}) } return nil } // title: rollback update // path: /apps/{appname}/deploy/rollback/update // method: PUT // consume: application/x-www-form-urlencoded // responses: // 200: Rollback updated // 400: Invalid data // 403: Forbidden func deployRollbackUpdate(w http.ResponseWriter, r *http.Request, t auth.Token) error { appName := r.URL.Query().Get(":appname") instance, err := app.GetByName(appName) if err != nil { return &tsuruErrors.HTTP{ Code: http.StatusBadRequest, Message: fmt.Sprintf("App %s was not found", appName), } } canUpdateRollback := permission.Check(t, permission.PermAppUpdateDeployRollback, contextsForApp(instance)...) if !canUpdateRollback { return &tsuruErrors.HTTP{ Code: http.StatusForbidden, Message: "User does not have permission to do this action in this app", } } img := r.FormValue("image") if img == "" { return &tsuruErrors.HTTP{ Code: http.StatusBadRequest, Message: "you must specify an image", } } disable := r.FormValue("disable") disableRollback, err := strconv.ParseBool(disable) if err != nil { return &tsuruErrors.HTTP{ Code: http.StatusBadRequest, Message: fmt.Sprintf("Cannot set 'disable' status to: '%s', instead of 'true' or 'false'", disable), } } reason := r.FormValue("reason") if (reason == "") && (disableRollback) { return &tsuruErrors.HTTP{ Code: http.StatusBadRequest, Message: "Reason cannot be empty while disabling a image rollback", } } evt, err := event.New(&event.Opts{ Target: appTarget(appName), Kind: permission.PermAppUpdateDeployRollback, Owner: t, CustomData: event.FormToCustomData(r.Form), Allowed: event.Allowed(permission.PermAppReadEvents, contextsForApp(instance)...), AllowedCancel: event.Allowed(permission.PermAppUpdateEvents, contextsForApp(instance)...), Cancelable: false, }) if err != nil { return err } defer func() { evt.Done(err) }() err = app.RollbackUpdate(instance.Name, img, reason, disableRollback) if err != nil { return &tsuruErrors.HTTP{ Code: http.StatusBadRequest, Message: err.Error(), } } return err }
ArxdSilva/tsuru
api/deploy.go
GO
bsd-3-clause
12,975
/* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include <gtest/gtest.h> #include "bistro/bistro/utils/BackgroundThreadMixin.h" using namespace std; using namespace facebook::bistro; struct Foo : BackgroundThreadMixin { explicit Foo(std::atomic<int>& d) : data(d) {} ~Foo() override { stopBackgroundThreads(); } void start() { runInBackgroundLoop([this](){ ++data; return std::chrono::seconds(0); }); } std::atomic<int>& data; }; struct FooLongSleep : BackgroundThreadMixin { explicit FooLongSleep(std::atomic<int>& d) : data(d) {} ~FooLongSleep() override { stopBackgroundThreads(); data.store(-1); } void start() { runInBackgroundLoop([this]() { data.store(1); return std::chrono::seconds(300); }); } std::atomic<int>& data; }; TEST(TestBackgroundThread, HandleBackgroundLoop) { std::atomic<int> data(0); { Foo f(data); EXPECT_EQ(0, data.load()); f.start(); // Runs increment thread in background this_thread::sleep_for(chrono::milliseconds(10)); } int val = data.load(); EXPECT_GT(val, 0); // The increment thread should have been destroyed this_thread::sleep_for(chrono::milliseconds(10)); int new_val = data.load(); } TEST(TestBackgroundThread, HandleLongSleepingThread) { std::atomic<int> data(0); { FooLongSleep f(data); EXPECT_EQ(0, data.load()); f.start(); this_thread::sleep_for(chrono::milliseconds(10)); EXPECT_EQ(1, data.load()); } // Foo should have been destroyed, which stopped the thread! EXPECT_EQ(-1, data.load()); }
linearregression/bistro
bistro/utils/test/test_background_thread.cpp
C++
bsd-3-clause
1,838
create index if not exists in_programinstance_trackedentityinstanceid on programinstance (trackedentityinstanceid); create index if not exists in_relationshipitem_trackedentityinstanceid on relationshipitem (trackedentityinstanceid); create index if not exists in_relationshipitem_programinstanceid on relationshipitem (programinstanceid); create index if not exists in_relationshipitem_programstageinstanceid on relationshipitem (programstageinstanceid);
dhis2/dhis2-core
dhis-2/dhis-support/dhis-support-db-migration/src/main/resources/org/hisp/dhis/db/migration/2.36/V2_36_29__Add_indexes_in_relationshipitem_and_programinstance_tables.sql
SQL
bsd-3-clause
456
<?php ############################################################################# # IMDBPHP (c) Giorgos Giagas & Itzchak Rehberg # # written by Giorgos Giagas # # extended & maintained by Itzchak Rehberg <izzysoft AT qumran DOT org> # # http://www.izzysoft.de/ # # ------------------------------------------------------------------------- # # This program is free software; you can redistribute and/or modify it # # under the terms of the GNU General Public License (see doc/LICENSE) # ############################################################################# require __DIR__ . "/../bootstrap.php"; if (isset ($_GET["mid"]) && preg_match('/^[0-9]+$/',$_GET["mid"])) { $config = new \Imdb\Config(); $config->language = 'en-US,en'; $movie = new \Imdb\Title($_GET["mid"],$config); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title><?php echo $movie->title().' ('.$movie->year().')' ?> - IMDbPHP</title> <link rel="stylesheet" href="style.css"> </head> <body> <?php # Title & year ?> <h2 class="text-center"><?php echo $movie->title().' ('.$movie->year().')' ?></h2> <?php # Photo ?> <div class="photo mb-10 text-center"> <?php if (($photo_url = $movie->photo_localurl() ) != FALSE) { echo '<img src="'.$photo_url.'" alt="Cover">'; } else { echo "No photo available"; } ?> </div> <table class="table"> <tr> <th colspan="2" class="move-container"> Movie Details <span class="move-right pr-10">Source: [<a href="<?php echo $movie->main_url() ?>">IMDb</a>]</span> </th> </tr> <tr> <td><b>Original title:</b></td> <td><?= $movie->orig_title() ?></td> </tr> <?php # AKAs $aka = $movie->alsoknow(); $cc = count($aka); if (!empty($aka)) { ?> <tr> <td><b>Also known as:</b></td> <td> <table> <tr> <th>Title</th> <th>Year</th> <th>Country</th> <th>Comment</th> </tr> <?php foreach ( $aka as $ak) { ?> <tr> <td><?php echo $ak["title"] ?></td> <td><?php echo $ak["year"] ?></td> <td><?php echo $ak["country"] ?></td> <td><?php echo $ak["comment"] ?></td> </tr> <?php } ?> </table> </td> </tr> <?php } ?> <?php # Movie Type ?> <tr> <td class="mw-120"><b>Type:</b></td> <td><?php echo $movie->movietype() ?></td> </tr> <?php # Keywords $keywords = $movie->keywords(); if ( !empty($keywords) ) { ?> <tr> <td><b>Keywords:</b></td> <td><?php echo implode(', ',$keywords) ?></td> </tr> <?php } ?> <?php # Seasons if ( $movie->seasons() != 0 ) { ?> <tr> <td><b>Seasons:</b></td> <td><?php echo $movie->seasons() ?></td> </tr> <?php } ?> <?php # Episode Details $ser = $movie->get_episode_details(); if (!empty($ser)) { ?> <tr> <td><b>Episode Details:</b></td> <td><?php echo $ser['seriestitle'].' | Season '.$ser['season'].', Episode '.$ser['episode'].", Airdate ".$ser['airdate'] ?></td> </tr> <?php } ?> <?php # Year ?> <tr> <td><b>Year:</b></td> <td><?php echo $movie->year() ?></td> </tr> <?php # Runtime $runtime = $movie->runtime(); if (!empty($runtime)) { ?> <tr> <td><b>Runtime:</b></td> <td><?php echo $runtime; ?> minutes</td> </tr> <?php } ?> <?php # MPAA $mpaa = $movie->mpaa(); if (!empty($mpaa)) { $mpar = $movie->mpaa_reason(); if (empty($mpar)) { ?> <tr> <td><b>MPAA:</b></td> <td> <?php } else { ?> <tr> <td rowspan="2"><b>MPAA:</b></td> <td> <?php } ?> <table> <tr> <th>Country</th> <th>Rating</th> </tr> <?php foreach ($mpaa as $key=>$mpaa) { ?> <tr> <td><?php echo $key ?></td> <td><?php echo $mpaa ?></td> </tr> <?php } ?> </table> </td> </tr> <?php if (!empty($mpar)) { ?> <tr> <td><?php echo $mpar ?></td> </tr> <?php } } ?> <?php # Ratings $ratv = $movie->rating(); if (!empty($ratv)) { ?> <tr> <td><b>Rating:</b></td> <td><?php echo $ratv; ?></td> </tr> <?php } ?> <?php # Votes $ratv = $movie->votes(); if (!empty($ratv)) { ?> <tr> <td><b>Votes:</b></td> <td><?php echo $ratv; ?></td> </tr> <?php } ?> <?php # Languages $languages = $movie->languages(); if (!empty($languages)) { ?> <tr> <td><b>Languages:</b></td> <td><?php echo implode(', ',$languages) ?></td> </tr> <?php } ?> <?php # Country $country = $movie->country(); if (!empty($country)) { ?> <tr> <td><b>Country:</b></td> <td><?php echo implode(', ',$country) ?></td> </tr> <?php } ?> <?php # Genre $genre = $movie->genre(); if (!empty($genre)) { ?> <tr> <td><b>Genre:</b></td> <td><?php echo $genre ?></td> </tr> <?php } ?> <?php # All Genres $gen = $movie->genres(); if (!empty($gen)) { ?> <tr> <td><b>All Genres:</b></td> <td><?php echo implode(', ',$gen) ?></td> </tr> <?php } ?> <?php # Colors $col = $movie->colors(); if (!empty($col)) { ?> <tr> <td><b>Colors:</b></td> <td><?php echo implode(', ',$col) ?></td> </tr> <?php } ?> <?php # Sound $sound = $movie->sound (); if (!empty($sound)) { ?> <tr> <td><b>Sound:</b></td> <td><?php echo implode(', ',$sound) ?></td> </tr> <?php } ?> <?php # Tagline $tagline = $movie->tagline(); if (!empty($tagline)) { ?> <tr> <td><b>Tagline:</b></td> <td><?php echo $tagline ?></td> </tr> <?php } ?> <?php #==[ Staff ]== # director(s) $director = $movie->director(); if (!empty($director)) { ?> <tr> <td><b>Director:</b></td> <td> <table> <tr> <th class="mw-200">Name</th> <th class="mw-200">Role</th> </tr> <?php foreach ( $director as $d) { ?> <tr> <td><a href="person.php?mid=<?php echo $d["imdb"] ?>"><?php echo $d["name"] ?></a></td> <td><?php echo $d["role"] ?></td> </tr> <?php } ?> </table> </td> </tr> <?php } ?> <?php # Story $write = $movie->writing(); if (!empty($write)) { ?> <tr> <td><b>Writing By:</b></td> <td> <table> <tr> <th class="mw-200">Name</th> <th class="mw-200">Role</th> </tr> <?php foreach ( $write as $w) { ?> <tr> <td><a href="person.php?mid=<?php echo $w["imdb"] ?>"><?php echo $w["name"] ?></a></td> <td><?php echo $w["role"] ?></td> </tr> <?php } ?> </table> </td> </tr> <?php } ?> <?php # Producer $produce = $movie->producer(); if (!empty($produce)) { ?> <tr> <td><b>Produced By:</b></td> <td> <table> <tr> <th class="mw-200">Name</th> <th class="mw-200">Role</th> </tr> <?php foreach ( $produce as $p) { ?> <tr> <td><a href="person.php?mid=<?php echo $p["imdb"] ?>"><?php echo $p["name"] ?></a></td> <td><?php echo $p["role"] ?></td> </tr> <?php } ?> </table> </td> </tr> <?php } ?> <?php # Music $compose = $movie->composer(); if (!empty($compose)) { ?> <tr> <td><b>Music:</b></td> <td> <table> <tr> <th class="mw-200">Name</th> <th class="mw-200">Role</th> </tr> <?php foreach ( $compose as $c) { ?> <tr> <td><a href="person.php?mid=<?php echo $c["imdb"] ?>"><?php echo $c["name"] ?></a></td> <td><?php echo $c["role"] ?></td> </tr> <?php } ?> </table> </td> </tr> <?php } ?> <?php # Cast $cast = $movie->cast(); if (!empty($cast)) { ?> <tr> <td><b>Cast:</b></td> <td> <table> <tr> <th class="mw-200">Name</th> <th class="mw-200">Role</th> </tr> <?php foreach ( $cast as $c) { ?> <tr> <td><a href="person.php?mid=<?php echo $c["imdb"] ?>"><?php echo $c["name"] ?></a></td> <td><?php echo $c["role"] ?></td> </tr> <?php } ?> </table> </td> </tr> <?php } ?> <?php # Plot outline $plotoutline = $movie->plotoutline(); if (!empty($plotoutline)) { ?> <tr> <td><b>Plot Outline:</b></td> <td><?php echo $plotoutline ?></td> </tr> <?php } ?> <?php # Plot $plot = $movie->plot(); if (!empty($plot)) { ?> <tr> <td><b>Plot:</b></td> <td><ul> <?php foreach($plot as $p) { ?> <li><?php echo $p ?></li> <?php } ?> </ul></td> </tr> <?php } ?> <?php # Taglines $taglines = $movie->taglines(); if (!empty($taglines)) { ?> <tr> <td><b>Taglines:</b></td> <td><ul> <?php foreach($taglines as $t) { ?> <li><?php echo $t ?></li> <?php } ?> </ul></td> </tr> <?php } ?> <?php # Episodes if ( $movie->is_serial() || $movie->seasons() ) { $episodes = $movie->episodes(); ?> <tr> <td><b>Episodes:</b></td> <td> <?php foreach ( $episodes as $season => $ep ) { foreach ( $ep as $episodedata ) { echo '<b>Season '.$episodedata['season'].', Episode '.$episodedata['episode'].': <a href="'.$_SERVER["PHP_SELF"].'?mid='.$episodedata['imdbid'].'">'.$episodedata['title'].'</a></b> (<b>Original Air Date: '.$episodedata['airdate'].'</b>)<br>'.$episodedata['plot'].'<br/><br/>'."\n"; } } ?> </td> </tr> <?php } ?> <?php # Locations $locs = $movie->locations(); if (!empty($locs)) { ?> <tr> <td><b>Filming Locations:</b></td> <td><?php echo implode(', ',$locs) ?></td> </tr> <?php } ?> <?php # Selected User Comment $comment = $movie->comment(); if (!empty($comment)) { ?> <tr> <td><b>User Comments:</b></td> <td><?php echo $comment ?></td> </tr> <?php } ?> <?php # Quotes $quotes = $movie->quotes(); if (!empty($quotes)) { ?> <tr> <td><b>Movie Quotes:</b></td> <td><?php echo preg_replace("/https\:\/\/".str_replace(".","\.",$movie->imdbsite)."\/name\/nm(\d{7,8})\/(\?ref_=tt_trv_qu)?/","person.php?mid=\\1",$quotes[0]) ?></td> </tr> <?php } ?> <?php # Trailer $trailers = $movie->trailers(TRUE); if (!empty($trailers)) { ?> <tr> <td><b>Trailers:</b></td> <td> <?php foreach($trailers as $t) { if(!empty($t['url'])) { ?> <a href="<?php echo $t['url'] ?>"><?php echo $t['title'] ?></a><br> <?php } } ?> </td> </tr> <?php } ?> <?php # Crazy Credits $crazy = $movie->crazy_credits(); $cc = count($crazy); if ($cc) { ?> <tr> <td><b>Crazy Credits:</b></td> <td>We know about <?php echo $cc ?> <i>Crazy Credits</i>. One of them reads:<br><?php echo $crazy[0] ?></td> </tr> <?php } ?> <?php # Goofs $goofs = $movie->goofs(); $gc = count($goofs); if ($gc) { ?> <tr> <td><b>Goofs:</b></td> <td> We know about <?php echo $gc ?> <i>Goofs</i>. Here comes one of them:<br> <b><?php echo $goofs[0]["type"] ?></b> <?php echo $goofs[0]["content"] ?> </td> </tr> <?php } ?> <?php # Trivia $trivia = $movie->trivia(); $tc = count($trivia); if ($tc > 0) { ?> <tr> <td><b>Trivia:</b></td> <td> There are <?php echo $tc ?> entries in the trivia list - like these: <ul> <?php for($i=0;$i<5;++$i) { if (empty($trivia[$i])) break; ?> <li> <?php $t = $trivia[$i]; $t = preg_replace('/https\:\/\/'.str_replace(".","\.",$movie->imdbsite).'\/name\/nm(\d{7,8})/','person.php?mid=\\1',$t); $t = preg_replace('/https\:\/\/'.str_replace(".","\.",$movie->imdbsite).'\/title\/tt(\d{7,8})/','movie.php?mid=\\1',$t); echo $t; ?> </li> <?php } ?> </ul> </td> </tr> <?php } ?> <?php # Soundtracks $soundtracks = $movie->soundtrack(); $sc = count($soundtracks); if ($sc > 0) { ?> <tr> <td><b>Soundtracks:</b></td> <td> There are <?php echo $sc ?> soundtracks listed - like these:<br> <table> <tr> <th class="mw-200">Soundtrack</th> <th class="mw-200">Credit 1</th> <th class="mw-200">Credit 2</th> </tr> <?php foreach ( $soundtracks as $soundtrack) { $credit1 = isset($soundtrack["credits"][0]) ? preg_replace("/https\:\/\/".str_replace(".","\.",$movie->imdbsite)."\/name\/nm(\d{7,8})\//","person.php?mid=\\1",$soundtrack["credits"][0]['credit_to'])." (".$soundtrack["credits"][0]['desc'].")" : ''; $credit2 = isset($soundtrack["credits"][1]) ? preg_replace("/https\:\/\/".str_replace(".","\.",$movie->imdbsite)."\/name\/nm(\d{7,8})\//","person.php?mid=\\1",$soundtrack["credits"][1]['credit_to'])." (".$soundtrack["credits"][1]['desc'].")" : ''; ?> <tr> <td><?php echo $soundtrack["soundtrack"] ?></td> <td><?php echo $credit1 ?></td> <td><?php echo $credit2 ?></td> </tr> <?php } ?> </table> </td> </tr> <?php } ?> </table> <p class="text-center"><a href="index.html">Go back</a></p> </body> </html> <?php } ?>
GeoffreyDijkstra/spotweb
vendor/imdbphp/imdbphp/demo/movie.php
PHP
bsd-3-clause
17,085
// Copyright 2017 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 THIRD_PARTY_BLINK_RENDERER_MODULES_SHAPEDETECTION_TEXT_DETECTOR_H_ #define THIRD_PARTY_BLINK_RENDERER_MODULES_SHAPEDETECTION_TEXT_DETECTOR_H_ #include "services/shape_detection/public/mojom/textdetection.mojom-blink.h" #include "third_party/blink/renderer/bindings/core/v8/script_promise.h" #include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h" #include "third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d.h" #include "third_party/blink/renderer/modules/modules_export.h" #include "third_party/blink/renderer/modules/shapedetection/shape_detector.h" #include "third_party/blink/renderer/platform/mojo/heap_mojo_remote.h" #include "third_party/blink/renderer/platform/mojo/heap_mojo_wrapper_mode.h" namespace blink { class ExecutionContext; class MODULES_EXPORT TextDetector final : public ShapeDetector { DEFINE_WRAPPERTYPEINFO(); public: static TextDetector* Create(ExecutionContext*); explicit TextDetector(ExecutionContext*); ~TextDetector() override = default; void Trace(Visitor*) const override; private: ScriptPromise DoDetect(ScriptPromiseResolver*, SkBitmap) override; void OnDetectText( ScriptPromiseResolver*, Vector<shape_detection::mojom::blink::TextDetectionResultPtr>); void OnTextServiceConnectionError(); HeapMojoRemote<shape_detection::mojom::blink::TextDetection> text_service_; HeapHashSet<Member<ScriptPromiseResolver>> text_service_requests_; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_MODULES_SHAPEDETECTION_TEXT_DETECTOR_H_
scheib/chromium
third_party/blink/renderer/modules/shapedetection/text_detector.h
C
bsd-3-clause
1,743
/* * Copyright (C) 2013 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef EventPath_h #define EventPath_h #include "core/CoreExport.h" #include "core/events/NodeEventContext.h" #include "core/events/TreeScopeEventContext.h" #include "core/events/WindowEventContext.h" #include "platform/heap/Handle.h" #include "wtf/HashMap.h" #include "wtf/Vector.h" namespace blink { class Event; class EventTarget; class Node; class TouchEvent; class TouchList; class TreeScope; class CORE_EXPORT EventPath final : public GarbageCollected<EventPath> { WTF_MAKE_NONCOPYABLE(EventPath); public: explicit EventPath(Node&, Event* = nullptr); void initializeWith(Node&, Event*); NodeEventContext& operator[](size_t index) { return m_nodeEventContexts[index]; } const NodeEventContext& operator[](size_t index) const { return m_nodeEventContexts[index]; } NodeEventContext& at(size_t index) { return m_nodeEventContexts[index]; } NodeEventContext& last() { return m_nodeEventContexts[size() - 1]; } WindowEventContext& windowEventContext() { ASSERT(m_windowEventContext); return *m_windowEventContext; } void ensureWindowEventContext(); bool isEmpty() const { return m_nodeEventContexts.isEmpty(); } size_t size() const { return m_nodeEventContexts.size(); } void adjustForRelatedTarget(Node&, EventTarget* relatedTarget); void adjustForTouchEvent(TouchEvent&); static EventTarget* eventTargetRespectingTargetRules(Node&); DECLARE_TRACE(); void clear() { m_nodeEventContexts.clear(); m_treeScopeEventContexts.clear(); } private: EventPath(); void initialize(); void calculatePath(); void calculateAdjustedTargets(); void calculateTreeOrderAndSetNearestAncestorClosedTree(); void shrink(size_t newSize) { ASSERT(!m_windowEventContext); m_nodeEventContexts.shrink(newSize); } void shrinkIfNeeded(const Node& target, const EventTarget& relatedTarget); void adjustTouchList(const TouchList*, HeapVector<Member<TouchList>> adjustedTouchList, const HeapVector<Member<TreeScope>>& treeScopes); using TreeScopeEventContextMap = HeapHashMap<Member<TreeScope>, Member<TreeScopeEventContext>>; TreeScopeEventContext* ensureTreeScopeEventContext(Node* currentTarget, TreeScope*, TreeScopeEventContextMap&); using RelatedTargetMap = HeapHashMap<Member<TreeScope>, Member<EventTarget>>; static void buildRelatedNodeMap(const Node&, RelatedTargetMap&); static EventTarget* findRelatedNode(TreeScope&, RelatedTargetMap&); #if ENABLE(ASSERT) static void checkReachability(TreeScope&, TouchList&); #endif const NodeEventContext& topNodeEventContext(); HeapVector<NodeEventContext> m_nodeEventContexts; Member<Node> m_node; Member<Event> m_event; HeapVector<Member<TreeScopeEventContext>> m_treeScopeEventContexts; Member<WindowEventContext> m_windowEventContext; }; } // namespace blink #endif
axinging/chromium-crosswalk
third_party/WebKit/Source/core/events/EventPath.h
C
bsd-3-clause
4,224
<?php /* * Phake - Mocking Framework * * Copyright (c) 2010-2012, Mike Lively <m@digitalsandwich.com> * 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 Mike Lively nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @category Testing * @package Phake * @author Mike Lively <m@digitalsandwich.com> * @copyright 2010 Mike Lively <m@digitalsandwich.com> * @license http://www.opensource.org/licenses/bsd-license.php BSD License * @link http://www.digitalsandwich.com/ */ /** * Allows verifying that call invocations occurred some number of times. * * @author Brian Feaver <brian.feaver@gmail.com> */ interface Phake_CallRecorder_IVerifierMode { /** * Verifies that the number of <code>$matchedCalls</code> matches the number of invocations expected. * * @param array $matchedCalls * * @return Phake_CallRecorder_VerifierMode_Result */ public function verify(array $matchedCalls); /** * Returns a human readable description of the verifier mode * @return string */ public function __toString(); }
kore/Phake
src/Phake/CallRecorder/IVerifierMode.php
PHP
bsd-3-clause
2,540
//============================================================================== // Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2011 LRI UMR 8623 CNRS/Univ Paris Sud XI // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #ifndef BOOST_SIMD_REDUCTION_FUNCTIONS_SIMD_SSE_SSE2_ALL_HPP_INCLUDED #define BOOST_SIMD_REDUCTION_FUNCTIONS_SIMD_SSE_SSE2_ALL_HPP_INCLUDED #ifdef BOOST_SIMD_HAS_SSE2_SUPPORT #include <boost/simd/reduction/functions/all.hpp> #include <boost/simd/include/functions/simd/genmask.hpp> #include <boost/simd/sdk/meta/as_logical.hpp> namespace boost { namespace simd { namespace ext { BOOST_SIMD_FUNCTOR_IMPLEMENTATION(boost::simd::tag::all_, boost::simd::tag::sse2_, (A0), ((simd_<type16_<A0>,boost::simd::tag::sse_>)) ) { typedef typename meta::scalar_of<A0>::type sA0; typedef typename meta::as_logical<sA0>::type result_type; BOOST_SIMD_FUNCTOR_CALL(1) { return result_type(_mm_movemask_epi8(genmask(a0)) == 0xFFFF); } }; } } } #endif #endif
hainm/pythran
third_party/boost/simd/reduction/functions/simd/sse/sse2/all.hpp
C++
bsd-3-clause
1,367
package org.motechproject.testing.utils.server; import org.mortbay.jetty.Request; import org.mortbay.jetty.Server; import org.mortbay.jetty.servlet.Context; import org.mortbay.jetty.servlet.DefaultServlet; import org.mortbay.jetty.servlet.ServletHolder; import org.motechproject.commons.api.MotechException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class StubServer { public static final String OK = "<status>success</status>"; private final Server server; private Map<String, RequestInfo> requests = new HashMap<>(); public StubServer(int port, String contextPath) { server = new Server(port); Context context = new Context(server, contextPath); context.addServlet(new ServletHolder(createServlet()), "/*"); server.setHandler(context); } public StubServer start() { try { server.start(); } catch (Exception e) { throw new MotechException("Stub Sever Could not be started", e); } return this; } public void stop() { try { server.stop(); } catch (Exception e) { new MotechException("Stub Server could not be stopped", e); } } public boolean waitingForRequests() { return requests.isEmpty(); } public RequestInfo detailForRequest(String contextPath) { return requests.get(contextPath); } private DefaultServlet createServlet() { return new DefaultServlet() { @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { requests.put(request.getContextPath(), collectRequestInfo(request)); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().write(OK); Request baseRequest = (Request) request; baseRequest.setHandled(true); } private RequestInfo collectRequestInfo(HttpServletRequest request) { Map<String, String> map = new HashMap<>(); String queryString = request.getQueryString(); String[] queryParameters = queryString.split("&"); for (String queryParam : queryParameters) { String[] keyValuePair = queryParam.split("="); map.put(keyValuePair[0], keyValuePair[1]); } return new RequestInfo(request.getContextPath(), map); } }; } }
bruceMacLeod/motech-server-pillreminder-0.18
modules/testing-utils/testing-utils/src/main/java/org/motechproject/testing/utils/server/StubServer.java
Java
bsd-3-clause
2,714
// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights // reserved. Use of this source code is governed by a BSD-style license that // can be found in the LICENSE file. // // --------------------------------------------------------------------------- // // This file was generated by the CEF translator tool. If making changes by // hand only do so within the body of existing method and function // implementations. See the translator.README.txt file in the tools directory // for more information. // #include "libcef_dll/ctocpp/pdf_print_callback_ctocpp.h" // VIRTUAL METHODS - Body may be edited by hand. void CefPdfPrintCallbackCToCpp::OnPdfPrintFinished(const CefString& path, bool ok) { cef_pdf_print_callback_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, on_pdf_print_finished)) return; // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Verify param: path; type: string_byref_const DCHECK(!path.empty()); if (path.empty()) return; // Execute _struct->on_pdf_print_finished(_struct, path.GetStruct(), ok); } // CONSTRUCTOR - Do not edit by hand. CefPdfPrintCallbackCToCpp::CefPdfPrintCallbackCToCpp() { } template<> cef_pdf_print_callback_t* CefCToCpp<CefPdfPrintCallbackCToCpp, CefPdfPrintCallback, cef_pdf_print_callback_t>::UnwrapDerived( CefWrapperType type, CefPdfPrintCallback* c) { NOTREACHED() << "Unexpected class type: " << type; return NULL; } #ifndef NDEBUG template<> base::AtomicRefCount CefCToCpp<CefPdfPrintCallbackCToCpp, CefPdfPrintCallback, cef_pdf_print_callback_t>::DebugObjCt = 0; #endif template<> CefWrapperType CefCToCpp<CefPdfPrintCallbackCToCpp, CefPdfPrintCallback, cef_pdf_print_callback_t>::kWrapperType = WT_PDF_PRINT_CALLBACK;
zmike/cef-rebase
libcef_dll/ctocpp/pdf_print_callback_ctocpp.cc
C++
bsd-3-clause
1,792
/* * Copyright (c) 2016, The OpenThread Authors. * 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 nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * @file * This file includes definitions for Thread URIs. */ #ifndef THREAD_URIS_HPP_ #define THREAD_URIS_HPP_ namespace ot { /** * The URI Path for Address Query. * */ #define OT_URI_PATH_ADDRESS_QUERY "a/aq" /** * @def OT_URI_PATH_ADDRESS_NOTIFY * * The URI Path for Address Notify. * */ #define OT_URI_PATH_ADDRESS_NOTIFY "a/an" /** * @def OT_URI_PATH_ADDRESS_ERROR * * The URI Path for Address Error. * */ #define OT_URI_PATH_ADDRESS_ERROR "a/ae" /** * @def OT_URI_PATH_ADDRESS_RELEASE * * The URI Path for Address Release. * */ #define OT_URI_PATH_ADDRESS_RELEASE "a/ar" /** * @def OT_URI_PATH_ADDRESS_SOLICIT * * The URI Path for Address Solicit. * */ #define OT_URI_PATH_ADDRESS_SOLICIT "a/as" /** * @def OT_URI_PATH_ACTIVE_GET * * The URI Path for MGMT_ACTIVE_GET * */ #define OT_URI_PATH_ACTIVE_GET "c/ag" /** * @def OT_URI_PATH_ACTIVE_SET * * The URI Path for MGMT_ACTIVE_SET * */ #define OT_URI_PATH_ACTIVE_SET "c/as" /** * @def OT_URI_PATH_DATASET_CHANGED * * The URI Path for MGMT_DATASET_CHANGED * */ #define OT_URI_PATH_DATASET_CHANGED "c/dc" /** * @def OT_URI_PATH_ENERGY_SCAN * * The URI Path for Energy Scan * */ #define OT_URI_PATH_ENERGY_SCAN "c/es" /** * @def OT_URI_PATH_ENERGY_REPORT * * The URI Path for Energy Report * */ #define OT_URI_PATH_ENERGY_REPORT "c/er" /** * @def OT_URI_PATH_PENDING_GET * * The URI Path for MGMT_PENDING_GET * */ #define OT_URI_PATH_PENDING_GET "c/pg" /** * @def OT_URI_PATH_PENDING_SET * * The URI Path for MGMT_PENDING_SET * */ #define OT_URI_PATH_PENDING_SET "c/ps" /** * @def OT_URI_PATH_SERVER_DATA * * The URI Path for Server Data Registration. * */ #define OT_URI_PATH_SERVER_DATA "a/sd" /** * @def OT_URI_PATH_ANNOUNCE_BEGIN * * The URI Path for Announce Begin. * */ #define OT_URI_PATH_ANNOUNCE_BEGIN "c/ab" /** * @def OT_URI_PATH_RELAY_RX * * The URI Path for Relay RX. * */ #define OT_URI_PATH_RELAY_RX "c/rx" /** * @def OT_URI_PATH_RELAY_TX * * The URI Path for Relay TX. * */ #define OT_URI_PATH_RELAY_TX "c/tx" /** * @def OT_URI_PATH_JOINER_FINALIZE * * The URI Path for Joiner Finalize * */ #define OT_URI_PATH_JOINER_FINALIZE "c/jf" /** * @def OT_URI_PATH_JOINER_ENTRUST * * The URI Path for Joiner Entrust * */ #define OT_URI_PATH_JOINER_ENTRUST "c/je" /** * @def OT_URI_PATH_LEADER_PETITION * * The URI Path for Leader Petition * */ #define OT_URI_PATH_LEADER_PETITION "c/lp" /** * @def OT_URI_PATH_LEADER_KEEP_ALIVE * * The URI Path for Leader Keep Alive * */ #define OT_URI_PATH_LEADER_KEEP_ALIVE "c/la" /** * @def OT_URI_PATH_PANID_CONFLICT * * The URI Path for PAN ID Conflict * */ #define OT_URI_PATH_PANID_CONFLICT "c/pc" /** * @def OT_URI_PATH_PANID_QUERY * * The URI Path for PAN ID Query * */ #define OT_URI_PATH_PANID_QUERY "c/pq" /** * @def OT_URI_PATH_COMMISSIONER_GET * * The URI Path for MGMT_COMMISSIONER_GET * */ #define OT_URI_PATH_COMMISSIONER_GET "c/cg" /** * @def OT_URI_PATH_COMMISSIONER_SET * * The URI Path for MGMT_COMMISSIONER_SET * */ #define OT_URI_PATH_COMMISSIONER_SET "c/cs" /** * @def OT_URI_PATH_DIAGNOSTIC_GET_REQUEST * * The URI Path for Network Diagnostic Get Request. * */ #define OT_URI_PATH_DIAGNOSTIC_GET_REQUEST "d/dg" /** * @def OT_URI_PATH_DIAGNOSTIC_GET_QUERY * * The URI Path for Network Diagnostic Get Query. * */ #define OT_URI_PATH_DIAGNOSTIC_GET_QUERY "d/dq" /** * @def OT_URI_PATH_DIAGNOSTIC_GET_ANSWER * * The URI Path for Network Diagnostic Get Answer. * */ #define OT_URI_PATH_DIAGNOSTIC_GET_ANSWER "d/da" /** * @def OT_URI_PATH_DIAG_RST * * The URI Path for Network Diagnostic Reset. * */ #define OT_URI_PATH_DIAGNOSTIC_RESET "d/dr" } // namespace ot #endif // THREAD_URIS_HPP_
vaas-krish/openthread
src/core/thread/thread_uri_paths.hpp
C++
bsd-3-clause
5,620
// Copyright 2010-2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package org.mozc.android.inputmethod.japanese.session; import org.mozc.android.inputmethod.japanese.protobuf.ProtoCommands.Command; import org.mozc.android.inputmethod.japanese.protobuf.ProtoCommands.Input; import org.mozc.android.inputmethod.japanese.protobuf.ProtoCommands.Input.CommandType; import org.mozc.android.inputmethod.japanese.protobuf.ProtoCommands.Output; import junit.framework.TestCase; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; /** */ public class SocketSessionHandlerTest extends TestCase { public void testSessionHandlerSocket() throws UnknownHostException, IOException { final InetAddress host = InetAddress.getByName("localhost"); final ServerSocket serverSocket = new ServerSocket(0); final int port = serverSocket.getLocalPort(); try { Thread handlerThread = new Thread(new Runnable() { @Override public void run() { try { // Reply for 1st message. { Socket socket = serverSocket.accept(); DataInputStream inputStream = new DataInputStream(socket.getInputStream()); byte[] inBytes = new byte[inputStream.readInt()]; inputStream.readFully(inBytes); Input input = Input.parseFrom(inBytes); assertEquals(CommandType.CREATE_SESSION, input.getType()); Output output = Output.newBuilder().setId(1).build(); DataOutputStream outStream = new DataOutputStream(socket.getOutputStream()); byte[] outBytes = output.toByteArray(); outStream.writeInt(outBytes.length); outStream.write(outBytes); socket.close(); } // Reply for 2nd message. { Socket socket = serverSocket.accept(); DataInputStream inputStream = new DataInputStream(socket.getInputStream()); byte[] inBytes = new byte[inputStream.readInt()]; inputStream.readFully(inBytes); Input input = Input.parseFrom(inBytes); assertEquals(CommandType.RELOAD, input.getType()); Output output = Output.newBuilder().setId(2).build(); DataOutputStream outStream = new DataOutputStream(socket.getOutputStream()); byte[] outBytes = output.toByteArray(); outStream.writeInt(outBytes.length); outStream.write(outBytes); socket.close(); } // Disconnect before arriving 3rd message. serverSocket.close(); } catch (IOException e) { // Do nothing. } } }); handlerThread.setDaemon(true); handlerThread.start(); SocketSessionHandler handler = new SocketSessionHandler(host, port); // Send 1st message. { Command inCommand = Command.newBuilder() .setInput(Input.newBuilder().setType(CommandType.CREATE_SESSION)) .setOutput(Output.getDefaultInstance()) .build(); Command outCommand = handler.evalCommand(inCommand); assertTrue(outCommand.getOutput().getId() == 1); } // Send 2nd message. { Command inCommand = Command.newBuilder() .setInput(Input.newBuilder().setType(CommandType.RELOAD)) .setOutput(Output.getDefaultInstance()) .build(); Command outCommand = handler.evalCommand(inCommand); assertTrue(outCommand.getOutput().getId() == 2); } // Send 3rd message but socket client (mozc server) is disconnected. { try { handler.evalCommand(Command.getDefaultInstance()); fail("An exception has to be thrown because the socket is closed."); } catch (RuntimeException e) { // Expected behavior. } } } finally { serverSocket.close(); } } }
takahashikenichi/mozc
src/android/tests/src/com/google/android/inputmethod/japanese/session/SocketSessionHandlerTest.java
Java
bsd-3-clause
5,612
// 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 CONTENT_RENDERER_PEPPER_PEPPER_WEBPLUGIN_IMPL_H_ #define CONTENT_RENDERER_PEPPER_PEPPER_WEBPLUGIN_IMPL_H_ #include <string> #include <vector> #include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "base/sequenced_task_runner_helpers.h" #include "ppapi/c/pp_var.h" #include "third_party/WebKit/public/web/WebPlugin.h" #include "ui/gfx/geometry/rect.h" struct _NPP; namespace blink { struct WebPluginParams; struct WebPrintParams; } namespace content { class PepperPluginInstanceImpl; class PluginInstanceThrottlerImpl; class PluginModule; class PPB_URLLoader_Impl; class RenderFrameImpl; class PepperWebPluginImpl : public blink::WebPlugin { public: PepperWebPluginImpl(PluginModule* module, const blink::WebPluginParams& params, RenderFrameImpl* render_frame, scoped_ptr<PluginInstanceThrottlerImpl> throttler); PepperPluginInstanceImpl* instance() { return instance_.get(); } // blink::WebPlugin implementation. virtual blink::WebPluginContainer* container() const; virtual bool initialize(blink::WebPluginContainer* container); virtual void destroy(); virtual v8::Local<v8::Object> v8ScriptableObject( v8::Isolate* isolate) override; virtual bool getFormValue(blink::WebString& value); virtual void paint(blink::WebCanvas* canvas, const blink::WebRect& rect); virtual void updateGeometry( const blink::WebRect& window_rect, const blink::WebRect& clip_rect, const blink::WebRect& unobscured_rect, const blink::WebVector<blink::WebRect>& cut_outs_rects, bool is_visible); virtual void updateFocus(bool focused, blink::WebFocusType focus_type); virtual void updateVisibility(bool visible); virtual bool acceptsInputEvents(); virtual bool handleInputEvent(const blink::WebInputEvent& event, blink::WebCursorInfo& cursor_info); virtual void didReceiveResponse(const blink::WebURLResponse& response); virtual void didReceiveData(const char* data, int data_length); virtual void didFinishLoading(); virtual void didFailLoading(const blink::WebURLError&); virtual void didFinishLoadingFrameRequest(const blink::WebURL& url, void* notify_data); virtual void didFailLoadingFrameRequest(const blink::WebURL& url, void* notify_data, const blink::WebURLError& error); virtual bool hasSelection() const; virtual blink::WebString selectionAsText() const; virtual blink::WebString selectionAsMarkup() const; virtual blink::WebURL linkAtPosition(const blink::WebPoint& position) const; virtual bool getPrintPresetOptionsFromDocument( blink::WebPrintPresetOptions* preset_options); virtual void setZoomLevel(double level, bool text_only); virtual bool startFind(const blink::WebString& search_text, bool case_sensitive, int identifier); virtual void selectFindResult(bool forward); virtual void stopFind(); virtual bool supportsPaginatedPrint() override; virtual bool isPrintScalingDisabled() override; virtual int printBegin(const blink::WebPrintParams& print_params) override; virtual bool printPage(int page_number, blink::WebCanvas* canvas) override; virtual void printEnd() override; virtual bool canRotateView() override; virtual void rotateView(RotationType type) override; virtual bool isPlaceholder() override; private: friend class base::DeleteHelper<PepperWebPluginImpl>; virtual ~PepperWebPluginImpl(); struct InitData; scoped_ptr<InitData> init_data_; // Cleared upon successful initialization. // True if the instance represents the entire document in a frame instead of // being an embedded resource. bool full_frame_; scoped_ptr<PluginInstanceThrottlerImpl> throttler_; scoped_refptr<PepperPluginInstanceImpl> instance_; gfx::Rect plugin_rect_; PP_Var instance_object_; blink::WebPluginContainer* container_; DISALLOW_COPY_AND_ASSIGN(PepperWebPluginImpl); }; } // namespace content #endif // CONTENT_RENDERER_PEPPER_PEPPER_WEBPLUGIN_IMPL_H_
mou4e/zirconium
content/renderer/pepper/pepper_webplugin_impl.h
C
bsd-3-clause
4,383
// Copyright (c) 2013 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. #include "webkit/fileapi/async_file_util_adapter.h" #include "base/bind.h" #include "base/sequenced_task_runner.h" #include "base/task_runner_util.h" #include "webkit/fileapi/file_system_context.h" #include "webkit/fileapi/file_system_file_util.h" #include "webkit/fileapi/file_system_operation_context.h" #include "webkit/fileapi/file_system_url.h" #include "webkit/fileapi/file_system_util.h" namespace fileapi { using base::Bind; using base::Callback; using base::Owned; using base::PlatformFileError; using base::Unretained; namespace { class EnsureFileExistsHelper { public: EnsureFileExistsHelper() : error_(base::PLATFORM_FILE_OK), created_(false) {} void RunWork(FileSystemFileUtil* file_util, FileSystemOperationContext* context, const FileSystemURL& url) { error_ = file_util->EnsureFileExists(context, url, &created_); } void Reply(const AsyncFileUtil::EnsureFileExistsCallback& callback) { if (!callback.is_null()) callback.Run(error_, created_); } private: base::PlatformFileError error_; bool created_; DISALLOW_COPY_AND_ASSIGN(EnsureFileExistsHelper); }; class GetFileInfoHelper { public: GetFileInfoHelper() : error_(base::PLATFORM_FILE_OK), snapshot_policy_(kSnapshotFileUnknown) {} void GetFileInfo(FileSystemFileUtil* file_util, FileSystemOperationContext* context, const FileSystemURL& url) { error_ = file_util->GetFileInfo(context, url, &file_info_, &platform_path_); } void CreateSnapshotFile(FileSystemFileUtil* file_util, FileSystemOperationContext* context, const FileSystemURL& url) { error_ = file_util->CreateSnapshotFile( context, url, &file_info_, &platform_path_, &snapshot_policy_); } void ReplyFileInfo(const AsyncFileUtil::GetFileInfoCallback& callback) { if (!callback.is_null()) callback.Run(error_, file_info_, platform_path_); } void ReplySnapshotFile( const AsyncFileUtil::CreateSnapshotFileCallback& callback) { DCHECK(snapshot_policy_ != kSnapshotFileUnknown); if (!callback.is_null()) callback.Run(error_, file_info_, platform_path_, snapshot_policy_); } private: base::PlatformFileError error_; base::PlatformFileInfo file_info_; base::FilePath platform_path_; SnapshotFilePolicy snapshot_policy_; DISALLOW_COPY_AND_ASSIGN(GetFileInfoHelper); }; class ReadDirectoryHelper { public: ReadDirectoryHelper() : error_(base::PLATFORM_FILE_OK) {} void RunWork(FileSystemFileUtil* file_util, FileSystemOperationContext* context, const FileSystemURL& url) { base::PlatformFileInfo file_info; base::FilePath platform_path; PlatformFileError error = file_util->GetFileInfo( context, url, &file_info, &platform_path); if (error != base::PLATFORM_FILE_OK) { error_ = error; return; } if (!file_info.is_directory) { error_ = base::PLATFORM_FILE_ERROR_NOT_A_DIRECTORY; return; } scoped_ptr<FileSystemFileUtil::AbstractFileEnumerator> file_enum( file_util->CreateFileEnumerator(context, url, false /* recursive */)); base::FilePath current; while (!(current = file_enum->Next()).empty()) { AsyncFileUtil::Entry entry; entry.is_directory = file_enum->IsDirectory(); entry.name = VirtualPath::BaseName(current).value(); entry.size = file_enum->Size(); entry.last_modified_time = file_enum->LastModifiedTime(); entries_.push_back(entry); } error_ = base::PLATFORM_FILE_OK; } void Reply(const AsyncFileUtil::ReadDirectoryCallback& callback) { if (!callback.is_null()) callback.Run(error_, entries_, false /* has_more */); } private: base::PlatformFileError error_; std::vector<AsyncFileUtil::Entry> entries_; DISALLOW_COPY_AND_ASSIGN(ReadDirectoryHelper); }; } // namespace AsyncFileUtilAdapter::AsyncFileUtilAdapter( FileSystemFileUtil* sync_file_util) : sync_file_util_(sync_file_util) { DCHECK(sync_file_util_.get()); } AsyncFileUtilAdapter::~AsyncFileUtilAdapter() { } bool AsyncFileUtilAdapter::CreateOrOpen( FileSystemOperationContext* context, const FileSystemURL& url, int file_flags, const CreateOrOpenCallback& callback) { return base::FileUtilProxy::RelayCreateOrOpen( context->task_runner(), Bind(&FileSystemFileUtil::CreateOrOpen, Unretained(sync_file_util_.get()), context, url, file_flags), Bind(&FileSystemFileUtil::Close, Unretained(sync_file_util_.get()), context), callback); } bool AsyncFileUtilAdapter::EnsureFileExists( FileSystemOperationContext* context, const FileSystemURL& url, const EnsureFileExistsCallback& callback) { EnsureFileExistsHelper* helper = new EnsureFileExistsHelper; return context->task_runner()->PostTaskAndReply( FROM_HERE, Bind(&EnsureFileExistsHelper::RunWork, Unretained(helper), sync_file_util_.get(), context, url), Bind(&EnsureFileExistsHelper::Reply, Owned(helper), callback)); } bool AsyncFileUtilAdapter::CreateDirectory( FileSystemOperationContext* context, const FileSystemURL& url, bool exclusive, bool recursive, const StatusCallback& callback) { return base::PostTaskAndReplyWithResult( context->task_runner(), FROM_HERE, Bind(&FileSystemFileUtil::CreateDirectory, Unretained(sync_file_util_.get()), context, url, exclusive, recursive), callback); } bool AsyncFileUtilAdapter::GetFileInfo( FileSystemOperationContext* context, const FileSystemURL& url, const GetFileInfoCallback& callback) { GetFileInfoHelper* helper = new GetFileInfoHelper; return context->task_runner()->PostTaskAndReply( FROM_HERE, Bind(&GetFileInfoHelper::GetFileInfo, Unretained(helper), sync_file_util_.get(), context, url), Bind(&GetFileInfoHelper::ReplyFileInfo, Owned(helper), callback)); } bool AsyncFileUtilAdapter::ReadDirectory( FileSystemOperationContext* context, const FileSystemURL& url, const ReadDirectoryCallback& callback) { ReadDirectoryHelper* helper = new ReadDirectoryHelper; return context->task_runner()->PostTaskAndReply( FROM_HERE, Bind(&ReadDirectoryHelper::RunWork, Unretained(helper), sync_file_util_.get(), context, url), Bind(&ReadDirectoryHelper::Reply, Owned(helper), callback)); } bool AsyncFileUtilAdapter::Touch( FileSystemOperationContext* context, const FileSystemURL& url, const base::Time& last_access_time, const base::Time& last_modified_time, const StatusCallback& callback) { return base::PostTaskAndReplyWithResult( context->task_runner(), FROM_HERE, Bind(&FileSystemFileUtil::Touch, Unretained(sync_file_util_.get()), context, url, last_access_time, last_modified_time), callback); } bool AsyncFileUtilAdapter::Truncate( FileSystemOperationContext* context, const FileSystemURL& url, int64 length, const StatusCallback& callback) { return base::PostTaskAndReplyWithResult( context->task_runner(), FROM_HERE, Bind(&FileSystemFileUtil::Truncate, Unretained(sync_file_util_.get()), context, url, length), callback); } bool AsyncFileUtilAdapter::CopyFileLocal( FileSystemOperationContext* context, const FileSystemURL& src_url, const FileSystemURL& dest_url, const StatusCallback& callback) { return base::PostTaskAndReplyWithResult( context->task_runner(), FROM_HERE, Bind(&FileSystemFileUtil::CopyOrMoveFile, Unretained(sync_file_util_.get()), context, src_url, dest_url, true /* copy */), callback); } bool AsyncFileUtilAdapter::MoveFileLocal( FileSystemOperationContext* context, const FileSystemURL& src_url, const FileSystemURL& dest_url, const StatusCallback& callback) { return base::PostTaskAndReplyWithResult( context->task_runner(), FROM_HERE, Bind(&FileSystemFileUtil::CopyOrMoveFile, Unretained(sync_file_util_.get()), context, src_url, dest_url, false /* copy */), callback); } bool AsyncFileUtilAdapter::CopyInForeignFile( FileSystemOperationContext* context, const base::FilePath& src_file_path, const FileSystemURL& dest_url, const StatusCallback& callback) { return base::PostTaskAndReplyWithResult( context->task_runner(), FROM_HERE, Bind(&FileSystemFileUtil::CopyInForeignFile, Unretained(sync_file_util_.get()), context, src_file_path, dest_url), callback); } bool AsyncFileUtilAdapter::DeleteFile( FileSystemOperationContext* context, const FileSystemURL& url, const StatusCallback& callback) { return base::PostTaskAndReplyWithResult( context->task_runner(), FROM_HERE, Bind(&FileSystemFileUtil::DeleteFile, Unretained(sync_file_util_.get()), context, url), callback); } bool AsyncFileUtilAdapter::DeleteDirectory( FileSystemOperationContext* context, const FileSystemURL& url, const StatusCallback& callback) { return base::PostTaskAndReplyWithResult( context->task_runner(), FROM_HERE, Bind(&FileSystemFileUtil::DeleteDirectory, Unretained(sync_file_util_.get()), context, url), callback); } bool AsyncFileUtilAdapter::CreateSnapshotFile( FileSystemOperationContext* context, const FileSystemURL& url, const CreateSnapshotFileCallback& callback) { GetFileInfoHelper* helper = new GetFileInfoHelper; return context->task_runner()->PostTaskAndReply( FROM_HERE, Bind(&GetFileInfoHelper::CreateSnapshotFile, Unretained(helper), sync_file_util_.get(), context, url), Bind(&GetFileInfoHelper::ReplySnapshotFile, Owned(helper), callback)); } } // namespace fileapi
zcbenz/cefode-chromium
webkit/fileapi/async_file_util_adapter.cc
C++
bsd-3-clause
10,138
vtk_module(vtkInfovisBoostGraphAlgorithms DEPENDS vtkInfovisCore vtkCommonExecutionModel TEST_DEPENDS vtkRenderingOpenGL vtkTestingRendering vtkInteractionStyle vtkIOInfovis vtkViewsInfovis vtkRenderingFreeTypeOpenGL vtkChartsCore vtkViewsContext2D )
biddisco/VTK
Infovis/BoostGraphAlgorithms/module.cmake
CMake
bsd-3-clause
297
// Copyright 2016 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. #include "components/safe_browsing_db/v4_get_hash_protocol_manager.h" #include <memory> #include <vector> #include "base/base64.h" #include "base/memory/ptr_util.h" #include "base/strings/stringprintf.h" #include "base/test/simple_test_clock.h" #include "base/time/time.h" #include "components/safe_browsing_db/safebrowsing.pb.h" #include "components/safe_browsing_db/testing_util.h" #include "components/safe_browsing_db/util.h" #include "net/base/escape.h" #include "net/base/load_flags.h" #include "net/base/net_errors.h" #include "net/url_request/test_url_fetcher_factory.h" #include "testing/gtest/include/gtest/gtest.h" using base::Time; using base::TimeDelta; namespace { const char kClient[] = "unittest"; const char kAppVer[] = "1.0"; const char kKeyParam[] = "test_key_param"; } // namespace namespace safe_browsing { class SafeBrowsingV4GetHashProtocolManagerTest : public testing::Test { protected: std::unique_ptr<V4GetHashProtocolManager> CreateProtocolManager() { V4ProtocolConfig config; config.client_name = kClient; config.version = kAppVer; config.key_param = kKeyParam; return std::unique_ptr<V4GetHashProtocolManager>( V4GetHashProtocolManager::Create(NULL, config)); } std::string GetStockV4HashResponse() { FindFullHashesResponse res; res.mutable_negative_cache_duration()->set_seconds(600); ThreatMatch* m = res.add_matches(); m->set_threat_type(API_ABUSE); m->set_platform_type(CHROME_PLATFORM); m->set_threat_entry_type(URL_EXPRESSION); m->mutable_cache_duration()->set_seconds(300); m->mutable_threat()->set_hash( SBFullHashToString(SBFullHashForString("Everything's shiny, Cap'n."))); ThreatEntryMetadata::MetadataEntry* e = m->mutable_threat_entry_metadata()->add_entries(); e->set_key("permission"); e->set_value("NOTIFICATIONS"); // Serialize. std::string res_data; res.SerializeToString(&res_data); return res_data; } void SetTestClock(base::Time now, V4GetHashProtocolManager* pm) { base::SimpleTestClock* clock = new base::SimpleTestClock(); clock->SetNow(now); pm->SetClockForTests(base::WrapUnique(clock)); } }; void ValidateGetV4HashResults( const std::vector<SBFullHashResult>& expected_full_hashes, const base::Time& expected_cache_expire, const std::vector<SBFullHashResult>& full_hashes, const base::Time& cache_expire) { EXPECT_EQ(expected_cache_expire, cache_expire); ASSERT_EQ(expected_full_hashes.size(), full_hashes.size()); for (unsigned int i = 0; i < expected_full_hashes.size(); ++i) { const SBFullHashResult& expected = expected_full_hashes[i]; const SBFullHashResult& actual = full_hashes[i]; EXPECT_TRUE(SBFullHashEqual(expected.hash, actual.hash)); EXPECT_EQ(expected.metadata, actual.metadata); EXPECT_EQ(expected.cache_expire_after, actual.cache_expire_after); } } TEST_F(SafeBrowsingV4GetHashProtocolManagerTest, TestGetHashErrorHandlingNetwork) { net::TestURLFetcherFactory factory; std::unique_ptr<V4GetHashProtocolManager> pm(CreateProtocolManager()); std::vector<SBPrefix> prefixes; std::vector<SBFullHashResult> expected_full_hashes; base::Time expected_cache_expire; pm->GetFullHashesWithApis( prefixes, base::Bind(&ValidateGetV4HashResults, expected_full_hashes, expected_cache_expire)); net::TestURLFetcher* fetcher = factory.GetFetcherByID(0); DCHECK(fetcher); // Failed request status should result in error. fetcher->set_status(net::URLRequestStatus(net::URLRequestStatus::FAILED, net::ERR_CONNECTION_RESET)); fetcher->set_response_code(200); fetcher->SetResponseString(GetStockV4HashResponse()); fetcher->delegate()->OnURLFetchComplete(fetcher); // Should have recorded one error, but back off multiplier is unchanged. EXPECT_EQ(1ul, pm->gethash_error_count_); EXPECT_EQ(1ul, pm->gethash_back_off_mult_); } TEST_F(SafeBrowsingV4GetHashProtocolManagerTest, TestGetHashErrorHandlingResponseCode) { net::TestURLFetcherFactory factory; std::unique_ptr<V4GetHashProtocolManager> pm(CreateProtocolManager()); std::vector<SBPrefix> prefixes; std::vector<SBFullHashResult> expected_full_hashes; base::Time expected_cache_expire; pm->GetFullHashesWithApis( prefixes, base::Bind(&ValidateGetV4HashResults, expected_full_hashes, expected_cache_expire)); net::TestURLFetcher* fetcher = factory.GetFetcherByID(0); DCHECK(fetcher); fetcher->set_status(net::URLRequestStatus()); // Response code of anything other than 200 should result in error. fetcher->set_response_code(204); fetcher->SetResponseString(GetStockV4HashResponse()); fetcher->delegate()->OnURLFetchComplete(fetcher); // Should have recorded one error, but back off multiplier is unchanged. EXPECT_EQ(1ul, pm->gethash_error_count_); EXPECT_EQ(1ul, pm->gethash_back_off_mult_); } TEST_F(SafeBrowsingV4GetHashProtocolManagerTest, TestGetHashErrorHandlingOK) { net::TestURLFetcherFactory factory; std::unique_ptr<V4GetHashProtocolManager> pm(CreateProtocolManager()); base::Time now = base::Time::UnixEpoch(); SetTestClock(now, pm.get()); std::vector<SBPrefix> prefixes; std::vector<SBFullHashResult> expected_full_hashes; SBFullHashResult hash_result; hash_result.hash = SBFullHashForString("Everything's shiny, Cap'n."); hash_result.metadata.api_permissions.push_back("NOTIFICATIONS"); hash_result.cache_expire_after = now + base::TimeDelta::FromSeconds(300); expected_full_hashes.push_back(hash_result); base::Time expected_cache_expire = now + base::TimeDelta::FromSeconds(600); pm->GetFullHashesWithApis( prefixes, base::Bind(&ValidateGetV4HashResults, expected_full_hashes, expected_cache_expire)); net::TestURLFetcher* fetcher = factory.GetFetcherByID(0); DCHECK(fetcher); fetcher->set_status(net::URLRequestStatus()); fetcher->set_response_code(200); fetcher->SetResponseString(GetStockV4HashResponse()); fetcher->delegate()->OnURLFetchComplete(fetcher); // No error, back off multiplier is unchanged. EXPECT_EQ(0ul, pm->gethash_error_count_); EXPECT_EQ(1ul, pm->gethash_back_off_mult_); } TEST_F(SafeBrowsingV4GetHashProtocolManagerTest, TestGetHashRequest) { std::unique_ptr<V4GetHashProtocolManager> pm(CreateProtocolManager()); FindFullHashesRequest req; ThreatInfo* info = req.mutable_threat_info(); info->add_threat_types(API_ABUSE); info->add_platform_types(CHROME_PLATFORM); info->add_threat_entry_types(URL_EXPRESSION); SBPrefix one = 1u; SBPrefix two = 2u; SBPrefix three = 3u; std::string hash(reinterpret_cast<const char*>(&one), sizeof(SBPrefix)); info->add_threat_entries()->set_hash(hash); hash.clear(); hash.append(reinterpret_cast<const char*>(&two), sizeof(SBPrefix)); info->add_threat_entries()->set_hash(hash); hash.clear(); hash.append(reinterpret_cast<const char*>(&three), sizeof(SBPrefix)); info->add_threat_entries()->set_hash(hash); // Serialize and Base64 encode. std::string req_data, req_base64; req.SerializeToString(&req_data); base::Base64Encode(req_data, &req_base64); std::vector<PlatformType> platform; platform.push_back(CHROME_PLATFORM); std::vector<SBPrefix> prefixes; prefixes.push_back(one); prefixes.push_back(two); prefixes.push_back(three); EXPECT_EQ(req_base64, pm->GetHashRequest(prefixes, platform, API_ABUSE)); } TEST_F(SafeBrowsingV4GetHashProtocolManagerTest, TestParseHashResponse) { std::unique_ptr<V4GetHashProtocolManager> pm(CreateProtocolManager()); base::Time now = base::Time::UnixEpoch(); SetTestClock(now, pm.get()); FindFullHashesResponse res; res.mutable_negative_cache_duration()->set_seconds(600); res.mutable_minimum_wait_duration()->set_seconds(400); ThreatMatch* m = res.add_matches(); m->set_threat_type(API_ABUSE); m->set_platform_type(CHROME_PLATFORM); m->set_threat_entry_type(URL_EXPRESSION); m->mutable_cache_duration()->set_seconds(300); m->mutable_threat()->set_hash( SBFullHashToString(SBFullHashForString("Everything's shiny, Cap'n."))); ThreatEntryMetadata::MetadataEntry* e = m->mutable_threat_entry_metadata()->add_entries(); e->set_key("permission"); e->set_value("NOTIFICATIONS"); // Serialize. std::string res_data; res.SerializeToString(&res_data); std::vector<SBFullHashResult> full_hashes; base::Time cache_expire; EXPECT_TRUE(pm->ParseHashResponse(res_data, &full_hashes, &cache_expire)); EXPECT_EQ(now + base::TimeDelta::FromSeconds(600), cache_expire); EXPECT_EQ(1ul, full_hashes.size()); EXPECT_TRUE(SBFullHashEqual(SBFullHashForString("Everything's shiny, Cap'n."), full_hashes[0].hash)); EXPECT_EQ(1ul, full_hashes[0].metadata.api_permissions.size()); EXPECT_EQ("NOTIFICATIONS", full_hashes[0].metadata.api_permissions[0]); EXPECT_EQ(now + base::TimeDelta::FromSeconds(300), full_hashes[0].cache_expire_after); EXPECT_EQ(now + base::TimeDelta::FromSeconds(400), pm->next_gethash_time_); } // Adds an entry with an ignored ThreatEntryType. TEST_F(SafeBrowsingV4GetHashProtocolManagerTest, TestParseHashResponseWrongThreatEntryType) { std::unique_ptr<V4GetHashProtocolManager> pm(CreateProtocolManager()); base::Time now = base::Time::UnixEpoch(); SetTestClock(now, pm.get()); FindFullHashesResponse res; res.mutable_negative_cache_duration()->set_seconds(600); res.add_matches()->set_threat_entry_type(BINARY_DIGEST); // Serialize. std::string res_data; res.SerializeToString(&res_data); std::vector<SBFullHashResult> full_hashes; base::Time cache_expire; EXPECT_FALSE(pm->ParseHashResponse(res_data, &full_hashes, &cache_expire)); EXPECT_EQ(now + base::TimeDelta::FromSeconds(600), cache_expire); // There should be no hash results. EXPECT_EQ(0ul, full_hashes.size()); } // Adds entries with a ThreatPatternType metadata. TEST_F(SafeBrowsingV4GetHashProtocolManagerTest, TestParseHashThreatPatternType) { std::unique_ptr<V4GetHashProtocolManager> pm(CreateProtocolManager()); base::Time now = base::Time::UnixEpoch(); SetTestClock(now, pm.get()); // Test social engineering pattern type. FindFullHashesResponse se_res; se_res.mutable_negative_cache_duration()->set_seconds(600); ThreatMatch* se = se_res.add_matches(); se->set_threat_type(SOCIAL_ENGINEERING_PUBLIC); se->set_platform_type(CHROME_PLATFORM); se->set_threat_entry_type(URL_EXPRESSION); SBFullHash hash_string = SBFullHashForString("Everything's shiny, Cap'n."); se->mutable_threat()->set_hash(SBFullHashToString(hash_string)); ThreatEntryMetadata::MetadataEntry* se_meta = se->mutable_threat_entry_metadata()->add_entries(); se_meta->set_key("se_pattern_type"); se_meta->set_value("SOCIAL_ENGINEERING_LANDING"); std::string se_data; se_res.SerializeToString(&se_data); std::vector<SBFullHashResult> full_hashes; base::Time cache_expire; EXPECT_TRUE(pm->ParseHashResponse(se_data, &full_hashes, &cache_expire)); EXPECT_EQ(now + base::TimeDelta::FromSeconds(600), cache_expire); EXPECT_EQ(1ul, full_hashes.size()); EXPECT_TRUE(SBFullHashEqual(hash_string, full_hashes[0].hash)); EXPECT_EQ(ThreatPatternType::SOCIAL_ENGINEERING_LANDING, full_hashes[0].metadata.threat_pattern_type); // Test potentially harmful application pattern type. FindFullHashesResponse pha_res; pha_res.mutable_negative_cache_duration()->set_seconds(600); ThreatMatch* pha = pha_res.add_matches(); pha->set_threat_type(POTENTIALLY_HARMFUL_APPLICATION); pha->set_threat_entry_type(URL_EXPRESSION); pha->set_platform_type(CHROME_PLATFORM); hash_string = SBFullHashForString("Not to fret."); pha->mutable_threat()->set_hash(SBFullHashToString(hash_string)); ThreatEntryMetadata::MetadataEntry* pha_meta = pha->mutable_threat_entry_metadata()->add_entries(); pha_meta->set_key("pha_pattern_type"); pha_meta->set_value("LANDING"); std::string pha_data; pha_res.SerializeToString(&pha_data); full_hashes.clear(); EXPECT_TRUE(pm->ParseHashResponse(pha_data, &full_hashes, &cache_expire)); EXPECT_EQ(1ul, full_hashes.size()); EXPECT_TRUE(SBFullHashEqual(hash_string, full_hashes[0].hash)); EXPECT_EQ(ThreatPatternType::MALWARE_LANDING, full_hashes[0].metadata.threat_pattern_type); // Test invalid pattern type. FindFullHashesResponse invalid_res; invalid_res.mutable_negative_cache_duration()->set_seconds(600); ThreatMatch* invalid = invalid_res.add_matches(); invalid->set_threat_type(POTENTIALLY_HARMFUL_APPLICATION); invalid->set_threat_entry_type(URL_EXPRESSION); invalid->set_platform_type(CHROME_PLATFORM); invalid->mutable_threat()->set_hash(SBFullHashToString(hash_string)); ThreatEntryMetadata::MetadataEntry* invalid_meta = invalid->mutable_threat_entry_metadata()->add_entries(); invalid_meta->set_key("pha_pattern_type"); invalid_meta->set_value("INVALIDE_VALUE"); std::string invalid_data; invalid_res.SerializeToString(&invalid_data); full_hashes.clear(); EXPECT_FALSE( pm->ParseHashResponse(invalid_data, &full_hashes, &cache_expire)); EXPECT_EQ(0ul, full_hashes.size()); } // Adds metadata with a key value that is not "permission". TEST_F(SafeBrowsingV4GetHashProtocolManagerTest, TestParseHashResponseNonPermissionMetadata) { std::unique_ptr<V4GetHashProtocolManager> pm(CreateProtocolManager()); base::Time now = base::Time::UnixEpoch(); SetTestClock(now, pm.get()); FindFullHashesResponse res; res.mutable_negative_cache_duration()->set_seconds(600); ThreatMatch* m = res.add_matches(); m->set_threat_type(API_ABUSE); m->set_platform_type(CHROME_PLATFORM); m->set_threat_entry_type(URL_EXPRESSION); m->mutable_threat()->set_hash( SBFullHashToString(SBFullHashForString("Not to fret."))); ThreatEntryMetadata::MetadataEntry* e = m->mutable_threat_entry_metadata()->add_entries(); e->set_key("notpermission"); e->set_value("NOTGEOLOCATION"); // Serialize. std::string res_data; res.SerializeToString(&res_data); std::vector<SBFullHashResult> full_hashes; base::Time cache_expire; EXPECT_FALSE(pm->ParseHashResponse(res_data, &full_hashes, &cache_expire)); EXPECT_EQ(now + base::TimeDelta::FromSeconds(600), cache_expire); EXPECT_EQ(0ul, full_hashes.size()); } TEST_F(SafeBrowsingV4GetHashProtocolManagerTest, TestParseHashResponseInconsistentThreatTypes) { std::unique_ptr<V4GetHashProtocolManager> pm(CreateProtocolManager()); FindFullHashesResponse res; res.mutable_negative_cache_duration()->set_seconds(600); ThreatMatch* m1 = res.add_matches(); m1->set_threat_type(API_ABUSE); m1->set_platform_type(CHROME_PLATFORM); m1->set_threat_entry_type(URL_EXPRESSION); m1->mutable_threat()->set_hash( SBFullHashToString(SBFullHashForString("Everything's shiny, Cap'n."))); m1->mutable_threat_entry_metadata()->add_entries(); ThreatMatch* m2 = res.add_matches(); m2->set_threat_type(MALWARE_THREAT); m2->set_threat_entry_type(URL_EXPRESSION); m2->mutable_threat()->set_hash( SBFullHashToString(SBFullHashForString("Not to fret."))); // Serialize. std::string res_data; res.SerializeToString(&res_data); std::vector<SBFullHashResult> full_hashes; base::Time cache_expire; EXPECT_FALSE(pm->ParseHashResponse(res_data, &full_hashes, &cache_expire)); } } // namespace safe_browsing
axinging/chromium-crosswalk
components/safe_browsing_db/v4_get_hash_protocol_manager_unittest.cc
C++
bsd-3-clause
15,698
<?php /* Prototype : string convert_cyr_string ( string $str , string $from , string $to ) * Description: Convert from one Cyrillic character set to another * Source code: ext/standard/string.c */ echo "*** Testing convert_cyr_string() : basic functionality ***\n"; $str = "Convert from one Cyrillic character set to another."; echo "\n-- First try some simple English text --\n"; var_dump(bin2hex(convert_cyr_string($str, 'w', 'k'))); var_dump(bin2hex(convert_cyr_string($str, 'w', 'i'))); echo "\n-- Now try some of characters in 128-255 range --\n"; for ($i = 128; $i < 256; $i++) { $str = chr($i); echo "$i: " . bin2hex(convert_cyr_string($str, 'w', 'k')) . "\n"; } ?> ===DONE===
JSchwehn/php
testdata/fuzzdir/corpus/ext_standard_tests_strings_convert_cyr_string_basic.php
PHP
bsd-3-clause
701
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef SUPPORT_CHARCONV_TEST_HELPERS_H #define SUPPORT_CHARCONV_TEST_HELPERS_H #include <charconv> #include <cassert> #include <limits> #include <string.h> #include <stdlib.h> #include "test_macros.h" #if TEST_STD_VER <= 11 #error This file requires C++14 #endif using std::false_type; using std::true_type; template <typename To, typename From> constexpr auto is_non_narrowing(From a) -> decltype(To{a}, true_type()) { return {}; } template <typename To> constexpr auto is_non_narrowing(...) -> false_type { return {}; } template <typename X, typename T> constexpr bool _fits_in(T, true_type /* non-narrowing*/, ...) { return true; } template <typename X, typename T, typename xl = std::numeric_limits<X>> constexpr bool _fits_in(T v, false_type, true_type /* T signed*/, true_type /* X signed */) { return xl::lowest() <= v && v <= (xl::max)(); } template <typename X, typename T, typename xl = std::numeric_limits<X>> constexpr bool _fits_in(T v, false_type, true_type /* T signed */, false_type /* X unsigned*/) { return 0 <= v && std::make_unsigned_t<T>(v) <= (xl::max)(); } template <typename X, typename T, typename xl = std::numeric_limits<X>> constexpr bool _fits_in(T v, false_type, false_type /* T unsigned */, ...) { return v <= std::make_unsigned_t<X>((xl::max)()); } template <typename X, typename T> constexpr bool fits_in(T v) { return _fits_in<X>(v, is_non_narrowing<X>(v), std::is_signed<T>(), std::is_signed<X>()); } template <typename X> struct to_chars_test_base { template <typename T, size_t N, typename... Ts> void test(T v, char const (&expect)[N], Ts... args) { using std::to_chars; std::to_chars_result r; constexpr size_t len = N - 1; static_assert(len > 0, "expected output won't be empty"); if (!fits_in<X>(v)) return; r = to_chars(buf, buf + len - 1, X(v), args...); assert(r.ptr == buf + len - 1); assert(r.ec == std::errc::value_too_large); r = to_chars(buf, buf + sizeof(buf), X(v), args...); assert(r.ptr == buf + len); assert(r.ec == std::errc{}); assert(memcmp(buf, expect, len) == 0); } template <typename... Ts> void test_value(X v, Ts... args) { using std::to_chars; std::to_chars_result r; r = to_chars(buf, buf + sizeof(buf), v, args...); assert(r.ec == std::errc{}); *r.ptr = '\0'; auto a = fromchars(buf, r.ptr, args...); assert(v == a); auto ep = r.ptr - 1; r = to_chars(buf, ep, v, args...); assert(r.ptr == ep); assert(r.ec == std::errc::value_too_large); } private: static auto fromchars(char const* p, char const* ep, int base, true_type) { char* last; auto r = strtoll(p, &last, base); assert(last == ep); return r; } static auto fromchars(char const* p, char const* ep, int base, false_type) { char* last; auto r = strtoull(p, &last, base); assert(last == ep); return r; } static auto fromchars(char const* p, char const* ep, int base = 10) { return fromchars(p, ep, base, std::is_signed<X>()); } char buf[100]; }; template <typename X> struct roundtrip_test_base { template <typename T, typename... Ts> void test(T v, Ts... args) { using std::from_chars; using std::to_chars; std::from_chars_result r2; std::to_chars_result r; X x = 0xc; if (fits_in<X>(v)) { r = to_chars(buf, buf + sizeof(buf), v, args...); assert(r.ec == std::errc{}); r2 = from_chars(buf, r.ptr, x, args...); assert(r2.ptr == r.ptr); assert(x == X(v)); } else { r = to_chars(buf, buf + sizeof(buf), v, args...); assert(r.ec == std::errc{}); r2 = from_chars(buf, r.ptr, x, args...); if (std::is_signed<T>::value && v < 0 && std::is_unsigned<X>::value) { assert(x == 0xc); assert(r2.ptr == buf); assert(r2.ec == std::errc::invalid_argument); } else { assert(x == 0xc); assert(r2.ptr == r.ptr); assert(r2.ec == std::errc::result_out_of_range); } } } private: char buf[100]; }; template <typename... T> struct type_list { }; template <typename L1, typename L2> struct type_concat; template <typename... Xs, typename... Ys> struct type_concat<type_list<Xs...>, type_list<Ys...>> { using type = type_list<Xs..., Ys...>; }; template <typename L1, typename L2> using concat_t = typename type_concat<L1, L2>::type; template <typename L1, typename L2> constexpr auto concat(L1, L2) -> concat_t<L1, L2> { return {}; } auto all_signed = type_list<char, signed char, short, int, long, long long>(); auto all_unsigned = type_list<unsigned char, unsigned short, unsigned int, unsigned long, unsigned long long>(); auto integrals = concat(all_signed, all_unsigned); template <template <typename> class Fn, typename... Ts> void run(type_list<Ts...>) { int ls[sizeof...(Ts)] = {(Fn<Ts>{}(), 0)...}; (void)ls; } #endif // SUPPORT_CHARCONV_TEST_HELPERS_H
youtube/cobalt
third_party/llvm-project/libcxx/test/support/charconv_test_helpers.h
C
bsd-3-clause
5,765
public class FemaleBoss extends Woman { public FemaleBoss(){ super(); } public String react(String complement, String adj, String noun, String verb) { if(complementNumber==0) return "This is highly inappropriate."; else if(complementNumber==1){ if((noun.equals("work-ethic")||noun.equals("dream"))&&(verb.equals("work")||verb.equals("program"))) return "I feel a promotion coming your way!!"; else return "get out of my office."; } else if(complementNumber==2) return "are you familiar with the term sexual harassment?"; else if(complementNumber==3) return "I am your boss, you know."; else if(complementNumber==4){ if(noun.equals("work-ethic")&& !(adj.equals("sexy"))) return "I'm impressed, you are hired."; else return "get out of my office, you sick sick man."; } else if(complementNumber==5) return "If I was your girlfriend, that might have been funny. you are fired."; else if(complementNumber==6) return "who the hell do you think you are talking to??"; else if(complementNumber==7){ if ((adj.equals("better")||adj.equals("happy")||adj.equals("talented"))&&(verb.equals("work")||verb.equals("program"))) return "you have a slippery tongue..well done"; else return "get out of my office."; } else if(complementNumber==8){ if (noun.equals("work-ethic")) return "that's a strange proposal, but Ive heard worse.."; else return "you are going to have hard time keeping your job like that."; } else if(complementNumber==9){ if((verb.equals("work")||verb.equals("program"))&& (adj.equals("happy")||adj.equals("talented"))) return "let's indeed! you are a very talented young man.."; else return "are you familiar with the term sexual harassment?"; } else if(complementNumber==10){ if (noun.equals("work-ethic")||noun.equals("problems")||noun.equals("dream")) return "I don't understand exactly what you want, but whatever."; else return "get out of my office, you pervert."; } else return "WTF??"; } }
mike-n-7/PeepholeOptimizer
PeepholeBenchmarks/bench06/FemaleBoss.java
Java
bsd-3-clause
2,077
package org.scalajs.junit import org.junit.Assert._ import org.junit.Test import org.scalajs.junit.utils._ class AssertEqualsTest { @Test def test(): Unit = { assertEquals(false, true) } } class AssertEqualsTestAssertions extends JUnitTest with FailureFrameworkArgs { override val expectedFail: Int = 1 override val expectedTotal: Int = 1 protected def expectedOutput(context: OutputContext): List[Output] = { import context._ List( testRunStartedOutput, testStartedOutput("test"), testAssertionErrorMsgOutput("test", "expected:<false> but was:<true>"), failureEvent, testFinishedOutput("test"), testRunFinishedOutput, done ) } }
xuwei-k/scala-js
junit-test/shared/src/test/scala/org/scalajs/junit/AssertEqualsTest.scala
Scala
bsd-3-clause
720
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="stylesheet" href="css/full_list.css" type="text/css" media="screen" charset="utf-8" /> <script type="text/javascript" charset="utf-8" src="js/jquery.js"></script> <script type="text/javascript" charset="utf-8" src="js/full_list.js"></script> <base id="base_target" target="_parent" /> </head> <body class="frames"> <script type="text/javascript" charset="utf-8"> if (window.top.frames.main) { document.getElementById('base_target').target = 'main'; document.body.className = 'frames'; } </script> <div id="content"> <h1 id="full_list_header"> <a href="https://github.com/cblage/elixir-json" target="_top">json v0.3.0</a> </h1> <h2 id="sub_list_header"> <a href="overview.html">Overview</a> </h2> <div class="nav"> <span class="selected"><a target="_self" href="modules_list.html">Modules</a></span> <span class=""><a target="_self" href="exceptions_list.html">Exceptions</a></span> <span class=""><a target="_self" href="protocols_list.html">Protocols</a></span> </div> <div id="search">Search: <input type="text" /></div> <ul id="full_list" class="class"> <li> <a class="toggle"></a> <span class="object_link"> <a href="JSON.html" title="JSON">JSON</a> </span> <small class="search_info">JSON</small> </li> <ul> <li> <span class="object_link"> <a href="JSON.html#decode/1">decode/1</a> </span> <small class="search_info">JSON</small> </li> <li> <span class="object_link"> <a href="JSON.html#decode!/1">decode!/1</a> </span> <small class="search_info">JSON</small> </li> <li> <span class="object_link"> <a href="JSON.html#encode/1">encode/1</a> </span> <small class="search_info">JSON</small> </li> <li> <span class="object_link"> <a href="JSON.html#encode!/1">encode!/1</a> </span> <small class="search_info">JSON</small> </li> </ul> <li> <a class="toggle"></a> <span class="object_link"> <a href="JSON.Dynamo.Filter.html" title="JSON.Dynamo.Filter">JSON.Dynamo.Filter</a> </span> <small class="search_info">JSON.Dynamo.Filter</small> </li> <ul> <li> <span class="object_link"> <a href="JSON.Dynamo.Filter.html#finalize/1">finalize/1</a> </span> <small class="search_info">JSON.Dynamo.Filter</small> </li> </ul> <li> <a class="toggle"></a> <span class="object_link"> <a href="JSON.Dynamo.Filter.FilterResultObject.html" title="JSON.Dynamo.Filter.FilterResultObject">JSON.Dynamo.Filter.FilterResultObject</a> </span> <small class="search_info">JSON.Dynamo.Filter.FilterResultObject</small> </li> <ul> <li> <span class="object_link"> <a href="JSON.Dynamo.Filter.FilterResultObject.html#run/1">run/1</a> </span> <small class="search_info">JSON.Dynamo.Filter.FilterResultObject</small> </li> </ul> <li> <a class="toggle"></a> <span class="object_link"> <a href="JSON.Dynamo.Filter.ProcessFilteredResponse.html" title="JSON.Dynamo.Filter.ProcessFilteredResponse">JSON.Dynamo.Filter.ProcessFilteredResponse</a> </span> <small class="search_info">JSON.Dynamo.Filter.ProcessFilteredResponse</small> </li> <ul> <li> <span class="object_link"> <a href="JSON.Dynamo.Filter.ProcessFilteredResponse.html#run/2">run/2</a> </span> <small class="search_info">JSON.Dynamo.Filter.ProcessFilteredResponse</small> </li> </ul> <li> <a class="toggle"></a> <span class="object_link"> <a href="JSON.Encoder.Helpers.html" title="JSON.Encoder.Helpers">JSON.Encoder.Helpers</a> </span> <small class="search_info">JSON.Encoder.Helpers</small> </li> <ul> <li> <span class="object_link"> <a href="JSON.Encoder.Helpers.html#dict_encode/1">dict_encode/1</a> </span> <small class="search_info">JSON.Encoder.Helpers</small> </li> <li> <span class="object_link"> <a href="JSON.Encoder.Helpers.html#enum_encode/1">enum_encode/1</a> </span> <small class="search_info">JSON.Encoder.Helpers</small> </li> </ul> <li> <a class="toggle"></a> <span class="object_link"> <a href="JSON.Parser.Bitstring.html" title="JSON.Parser.Bitstring">JSON.Parser.Bitstring</a> </span> <small class="search_info">JSON.Parser.Bitstring</small> </li> <ul> <li> <span class="object_link"> <a href="JSON.Parser.Bitstring.html#parse/1">parse/1</a> </span> <small class="search_info">JSON.Parser.Bitstring</small> </li> <li> <span class="object_link"> <a href="JSON.Parser.Bitstring.html#trim/1">trim/1</a> </span> <small class="search_info">JSON.Parser.Bitstring</small> </li> </ul> <li> <a class="toggle"></a> <span class="object_link"> <a href="JSON.Parser.Bitstring.Array.html" title="JSON.Parser.Bitstring.Array">JSON.Parser.Bitstring.Array</a> </span> <small class="search_info">JSON.Parser.Bitstring.Array</small> </li> <ul> <li> <span class="object_link"> <a href="JSON.Parser.Bitstring.Array.html#parse/1">parse/1</a> </span> <small class="search_info">JSON.Parser.Bitstring.Array</small> </li> </ul> <li> <a class="toggle"></a> <span class="object_link"> <a href="JSON.Parser.Bitstring.Number.html" title="JSON.Parser.Bitstring.Number">JSON.Parser.Bitstring.Number</a> </span> <small class="search_info">JSON.Parser.Bitstring.Number</small> </li> <ul> <li> <span class="object_link"> <a href="JSON.Parser.Bitstring.Number.html#parse/1">parse/1</a> </span> <small class="search_info">JSON.Parser.Bitstring.Number</small> </li> </ul> <li> <a class="toggle"></a> <span class="object_link"> <a href="JSON.Parser.Bitstring.Object.html" title="JSON.Parser.Bitstring.Object">JSON.Parser.Bitstring.Object</a> </span> <small class="search_info">JSON.Parser.Bitstring.Object</small> </li> <ul> <li> <span class="object_link"> <a href="JSON.Parser.Bitstring.Object.html#parse/1">parse/1</a> </span> <small class="search_info">JSON.Parser.Bitstring.Object</small> </li> </ul> <li> <a class="toggle"></a> <span class="object_link"> <a href="JSON.Parser.Bitstring.String.html" title="JSON.Parser.Bitstring.String">JSON.Parser.Bitstring.String</a> </span> <small class="search_info">JSON.Parser.Bitstring.String</small> </li> <ul> <li> <span class="object_link"> <a href="JSON.Parser.Bitstring.String.html#parse/1">parse/1</a> </span> <small class="search_info">JSON.Parser.Bitstring.String</small> </li> </ul> <li> <a class="toggle"></a> <span class="object_link"> <a href="JSON.Parser.Charlist.html" title="JSON.Parser.Charlist">JSON.Parser.Charlist</a> </span> <small class="search_info">JSON.Parser.Charlist</small> </li> <ul> <li> <span class="object_link"> <a href="JSON.Parser.Charlist.html#parse/1">parse/1</a> </span> <small class="search_info">JSON.Parser.Charlist</small> </li> <li> <span class="object_link"> <a href="JSON.Parser.Charlist.html#trim/1">trim/1</a> </span> <small class="search_info">JSON.Parser.Charlist</small> </li> </ul> <li> <a class="toggle"></a> <span class="object_link"> <a href="JSON.Parser.Charlist.Array.html" title="JSON.Parser.Charlist.Array">JSON.Parser.Charlist.Array</a> </span> <small class="search_info">JSON.Parser.Charlist.Array</small> </li> <ul> <li> <span class="object_link"> <a href="JSON.Parser.Charlist.Array.html#parse/1">parse/1</a> </span> <small class="search_info">JSON.Parser.Charlist.Array</small> </li> </ul> <li> <a class="toggle"></a> <span class="object_link"> <a href="JSON.Parser.Charlist.Number.html" title="JSON.Parser.Charlist.Number">JSON.Parser.Charlist.Number</a> </span> <small class="search_info">JSON.Parser.Charlist.Number</small> </li> <ul> <li> <span class="object_link"> <a href="JSON.Parser.Charlist.Number.html#parse/1">parse/1</a> </span> <small class="search_info">JSON.Parser.Charlist.Number</small> </li> </ul> <li> <a class="toggle"></a> <span class="object_link"> <a href="JSON.Parser.Charlist.Object.html" title="JSON.Parser.Charlist.Object">JSON.Parser.Charlist.Object</a> </span> <small class="search_info">JSON.Parser.Charlist.Object</small> </li> <ul> <li> <span class="object_link"> <a href="JSON.Parser.Charlist.Object.html#parse/1">parse/1</a> </span> <small class="search_info">JSON.Parser.Charlist.Object</small> </li> </ul> <li> <a class="toggle"></a> <span class="object_link"> <a href="JSON.Parser.Charlist.String.html" title="JSON.Parser.Charlist.String">JSON.Parser.Charlist.String</a> </span> <small class="search_info">JSON.Parser.Charlist.String</small> </li> <ul> <li> <span class="object_link"> <a href="JSON.Parser.Charlist.String.html#parse/1">parse/1</a> </span> <small class="search_info">JSON.Parser.Charlist.String</small> </li> </ul> </ul> </div> </body> </html>
kidaa/elixir-json
docs/modules_list.html
HTML
bsd-3-clause
9,650
// // DifferentiableOperation.java: Source file for 'DifferentiableOperation' // Project xal // // Created by Tom Pelaia II on 4/29/11 // Copyright 2011 Oak Ridge National Lab. All rights reserved. // package xal.tools.math.differential; import org.junit.*; /** Test DifferentiableOperation */ public class TestDifferentiableOperation { /** maximum error allowed between test and control evaluations */ final static private double ERROR_TOLERANCE = 1.0e-6; @Test public void testOperationEvaluation() { checkOperationEvaluation( -7.2 ); checkOperationEvaluation( -0.43 ); checkOperationEvaluation( 0.0 ); checkOperationEvaluation( 0.27 ); checkOperationEvaluation( 1.0 ); checkOperationEvaluation( 3.5 ); } @Test public void testArithmeticEvaluation() { checkArithmeticEvaluation( 0.0, 1.0 ); checkArithmeticEvaluation( 0.0, 2.5 ); checkArithmeticEvaluation( 3.1, 0.0 ); checkArithmeticEvaluation( 1.0, 4.2 ); checkArithmeticEvaluation( 1.0, -6.3 ); checkArithmeticEvaluation( 8.3, 1.0 ); checkArithmeticEvaluation( 3.5, -7.2 ); checkArithmeticEvaluation( -3.5, 7.2 ); } @Test public void testDerivativeEvaluation() { checkDerivativeEvaluation( 0.0 ); checkDerivativeEvaluation( 1.0 ); checkDerivativeEvaluation( 2.3 ); checkDerivativeEvaluation( -7.8 ); checkDerivativeEvaluation( 8.6 ); } @Test public void testPartialDerivativeEvaluation() { checkPartialDerivativeEvaluation( 0.0, 0.0, 0.0 ); checkPartialDerivativeEvaluation( 1.0, 1.0, 1.0 ); checkPartialDerivativeEvaluation( 2.3, -3.4, 7.9 ); checkPartialDerivativeEvaluation( 7.4, 6.4, 4.0 ); checkPartialDerivativeEvaluation( -4.4, 3.2, -7.0 ); } /** test arithmetic evaluation for the specified variable values */ static private void checkArithmeticEvaluation( final double xValue, final double yValue ) { final DifferentiableVariable xVar = DifferentiableOperation.getVariable( "x", xValue ); final DifferentiableVariable yVar = DifferentiableOperation.getVariable( "y", yValue ); assertResult( xVar.plus( yVar ).evaluate(), xValue + yValue ); assertResult( xVar.minus( yVar ).evaluate(), xValue - yValue ); assertResult( xVar.times( yVar ).evaluate(), xValue * yValue ); assertResult( xVar.over( yVar ).evaluate(), xValue / yValue ); } /** test operation evaluation for the specified variable value */ static private void checkOperationEvaluation( final double xValue ) { final DifferentiableVariable xVar = DifferentiableOperation.getVariable( "x", xValue ); assertResult( xVar.evaluate(), xValue ); assertResult( xVar.abs().evaluate(), Math.abs( xValue ) ); assertResult( xVar.negate().evaluate(), - xValue ); assertResult( xVar.reciprocal().evaluate(), 1.0 / xValue ); assertResult( xVar.pow( 2 ).evaluate(), xValue * xValue ); assertResult( xVar.pow( 5.3 ).evaluate(), Math.pow( xValue, 5.3 ) ); assertResult( xVar.exp().evaluate(), Math.exp( xValue ) ); assertResult( xVar.log().evaluate(), Math.log( xValue ) ); assertResult( xVar.sqrt().evaluate(), Math.sqrt( xValue ) ); assertResult( xVar.sin().evaluate(), Math.sin( xValue ) ); assertResult( xVar.cos().evaluate(), Math.cos( xValue ) ); assertResult( xVar.tan().evaluate(), Math.tan( xValue ) ); assertResult( xVar.asin().evaluate(), Math.asin( xValue ) ); assertResult( xVar.acos().evaluate(), Math.acos( xValue ) ); assertResult( xVar.atan().evaluate(), Math.atan( xValue ) ); assertResult( xVar.sinh().evaluate(), Math.sinh( xValue ) ); assertResult( xVar.cosh().evaluate(), Math.cosh( xValue ) ); assertResult( xVar.tanh().evaluate(), Math.tanh( xValue ) ); } /** test single derivative evaluation for the specified variable value */ static private void checkDerivativeEvaluation( final double xValue ) { final DifferentiableVariable xVar = DifferentiableOperation.getVariable( "x", xValue ); // test polynomials assertResult( xVar.plus( 3.2 ).getDerivative( xVar ).evaluate(), 1.0 ); assertResult( xVar.pow( 2 ).plus( xVar.times( 3 ) ).plus( 7 ).getDerivative( xVar ).evaluate(), 2 * xValue + 3 ); // test transcendentals assertResult( xVar.plus( 1.0 ).exp().getDerivative( xVar ).evaluate(), Math.exp( xValue + 1.0 ) ); assertResult( xVar.sin().getDerivative( xVar ).evaluate(), Math.cos( xValue ) ); assertResult( xVar.cos().getDerivative( xVar ).evaluate(), - Math.sin( xValue ) ); assertResult( xVar.log().getDerivative( xVar ).evaluate(), 1.0 / xValue ); // test chain rule assertResult( xVar.plus( 1 ).pow( 2 ).exp().getDerivative( xVar ).evaluate(), 2 * ( xValue + 1 ) * Math.exp( ( xValue + 1 ) * ( xValue + 1 ) ) ); } /** test partial derivative evaluation for the specified variable values */ static private void checkPartialDerivativeEvaluation( final double xValue, final double yValue, final double zValue ) { final DifferentiableVariable xVar = DifferentiableOperation.getVariable( "x", xValue ); final DifferentiableVariable yVar = DifferentiableOperation.getVariable( "y", yValue ); final DifferentiableVariable zVar = DifferentiableOperation.getVariable( "z", zValue ); // test single order partial differentials assertResult( xVar.plus( yVar, zVar ).getDerivative( xVar ).evaluate(), 1.0 ); assertResult( xVar.times( yVar, zVar ).getDerivative( yVar ).evaluate(), xValue * zValue ); assertResult( xVar.plus( yVar ).exp().getDerivative( yVar ).evaluate(), Math.exp( xValue + yValue ) ); // test mixed differentials assertResult( xVar.times( yVar ).times( zVar ).getDerivative( xVar ).getDerivative( yVar ).evaluate(), zValue ); assertResult( xVar.times( yVar ).times( zVar ).getDerivative( xVar ).getDerivative( yVar ).getDerivative( zVar ).evaluate(), 1.0 ); assertResult( xVar.times( yVar.plus( zVar ) ).sin().getDerivative( xVar ).getDerivative( yVar ).evaluate(), Math.cos( xValue * ( yValue + zValue ) ) - xValue * ( yValue + zValue ) * Math.sin( xValue * ( yValue + zValue ) ) ); } /** * Assert true if the test value result matches the control value * @param testValue value to test * @param controlValue value against which the comparison is made */ static private void assertResult( final double testValue, final double controlValue ) { Assert.assertTrue( testValue == controlValue || Math.abs( testValue - controlValue ) < ERROR_TOLERANCE || ( Double.isNaN( testValue ) && Double.isNaN( controlValue ) ) ); } }
EuropeanSpallationSource/openxal
test/src/test/java/xal/tools/math/differential/TestDifferentiableOperation.java
Java
bsd-3-clause
7,038
////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2010-2015, Image Engine Design 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 Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #ifndef IECOREHOUDINI_TOHOUDINIQUATATTRIBCONVERTER_H #define IECOREHOUDINI_TOHOUDINIQUATATTRIBCONVERTER_H #include "IECore/VectorTypedParameter.h" #include "IECoreHoudini/TypeIds.h" #include "IECoreHoudini/ToHoudiniAttribConverter.h" namespace IECoreHoudini { IE_CORE_FORWARDDECLARE( ToHoudiniQuatVectorAttribConverter ); /// A ToHoudiniQuatVectorAttribConverter can convert from IECore::QuatfVectorData /// to a Houdini GA_Attribute on the provided GU_Detail. class ToHoudiniQuatVectorAttribConverter : public ToHoudiniAttribConverter { public : IE_CORE_DECLARERUNTIMETYPEDEXTENSION( ToHoudiniQuatVectorAttribConverter, ToHoudiniQuatVectorAttribConverterTypeId, ToHoudiniAttribConverter ); ToHoudiniQuatVectorAttribConverter( const IECore::Data *data ); virtual ~ToHoudiniQuatVectorAttribConverter(); protected : virtual GA_RWAttributeRef doConversion( const IECore::Data *data, std::string name, GU_Detail *geo ) const; virtual GA_RWAttributeRef doConversion( const IECore::Data *data, std::string name, GU_Detail *geo, const GA_Range &range ) const; private : static ToHoudiniAttribConverter::Description<ToHoudiniQuatVectorAttribConverter> m_description; }; } // namespace IECoreHoudini #endif // IECOREHOUDINI_TOHOUDINIQUATATTRIBCONVERTER_H
lento/cortex
include/IECoreHoudini/ToHoudiniQuatAttribConverter.h
C
bsd-3-clause
3,101
INC=. LIB=. # Get INC and LIB from Make.user ifeq (exists, $(shell [ -e ./Make.user ] && echo exists )) include ./Make.user endif test-salt2model : test_salt2model.o g++ -DUSELAPACK -DgFortran -g -Wall -O3 -Wl,-rpath,$(LIB) -L$(LIB) -o test-salt2model test_salt2model.o -lsnfit -llapack -lblas -llapack -lgfortran test_salt2model.o : test_salt2model.cc g++ -DHAVE_CONFIG_H -I$(INC) -g -Wall -O3 -DUSELAPACK -DgFortran -g -Wall -O3 -MT test_salt2model.o -MD -MP -std=c++11 -c -o test_salt2model.o test_salt2model.cc .PHONY: clean clean : rm test-salt2model rm test_salt2model.o rm test_salt2model.d
sncosmo/sncosmo
misc/Makefile
Makefile
bsd-3-clause
609
--- layout: data_model title: AttachmentsType this_version: 1.1.1 --- <div class="alert alert-danger bs-alert-old-docs"> <strong>Heads up!</strong> These docs are for STIX 1.1.1, which is not the latest version (1.2). <a href="/data-model/1.2/EmailMessageObj/AttachmentsType">View the latest!</a> </div> <div class="row"> <div class="col-md-10"> <h1>AttachmentsType<span class="subdued">Email Message Object Schema</span></h1> <p class="data-model-description">The AttachmenstType captures a list of attachments for an email message.</p> </div> <div id="nav-area" class="col-md-2"> <p> <form id="nav-version"> <select> <option value="1.2" >STIX 1.2</option> <option value="1.1.1" selected="selected">STIX 1.1.1</option> <option value="1.1" >STIX 1.1</option> <option value="1.0.1" >STIX 1.0.1</option> <option value="1.0" >STIX 1.0</option> </select> </form> </p> </div> </div> <hr /> <h2>Fields</h2> <table class="table table-striped table-hover"> <thead> <tr> <th>Field Name</th> <th>Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>File<span class="occurrence">1..n</span></td> <td> <a href="/data-model/1.1.1/EmailMessageObj/AttachmentReferenceType">AttachmentReferenceType</a> </td> <td> <p>The File field specifies a file that was attached to the email message, via a reference to an Object included elsewhere in the document.</p> </td> </tr> </tbody> </table>
jburns12/stixproject.github.io
data-model/1.1.1/EmailMessageObj/AttachmentsType/index.html
HTML
bsd-3-clause
1,711
<?php /* Copyright (c) 2005, Till Brehm, projektfarm Gmbh 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 ISPConfig nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /****************************************** * Begin Form configuration ******************************************/ $list_def_file = "list/mail_alias.list.php"; $tform_def_file = "form/mail_alias.tform.php"; /****************************************** * End Form configuration ******************************************/ require_once '../../lib/config.inc.php'; require_once '../../lib/app.inc.php'; //* Check permissions for module $app->auth->check_module_permissions('mail'); $app->uses("tform_actions"); $app->tform_actions->onDelete(); ?>
idrassi/ispconfig_ovh_hosting
ispconfig3_install/interface/web/mail/mail_alias_del.php
PHP
bsd-3-clause
2,087
# Copyright 2019 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. import sys import config_util # pylint: disable=import-error # This class doesn't need an __init__ method, so we disable the warning # pylint: disable=no-init class DevToolsFrontend(config_util.Config): """Basic Config class for DevTools frontend.""" @staticmethod def fetch_spec(props): url = 'https://chromium.googlesource.com/devtools/devtools-frontend.git' solution = { 'name' : 'devtools-frontend', 'url' : url, 'deps_file' : 'DEPS', 'managed' : False, 'custom_deps' : {}, } spec = { 'solutions': [solution], 'with_branch_heads': True, } return { 'type': 'gclient_git', 'gclient_git_spec': spec, } @staticmethod def expected_root(_props): return 'devtools-frontend' def main(argv=None): return DevToolsFrontend().handle_args(argv) if __name__ == '__main__': sys.exit(main(sys.argv))
endlessm/chromium-browser
third_party/depot_tools/fetch_configs/devtools-frontend.py
Python
bsd-3-clause
1,092
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Text * @subpackage UnitTests * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ /** * @namespace */ namespace ZendTest\Text; use Zend\Text\Figlet; /** * @category Zend * @package Zend_Text * @subpackage UnitTests * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Text */ class FigletTest extends \PHPUnit_Framework_TestCase { public function testStandardAlignLeft() { $figlet = new Figlet\Figlet(); $this->_equalAgainstFile($figlet->render('Dummy'), 'StandardAlignLeft.figlet'); } public function testStandardAlignCenter() { $figlet = new Figlet\Figlet(array('justification' => Figlet\Figlet::JUSTIFICATION_CENTER)); $this->_equalAgainstFile($figlet->render('Dummy'), 'StandardAlignCenter.figlet'); } public function testStandardAlignRight() { $figlet = new Figlet\Figlet(array('justification' => Figlet\Figlet::JUSTIFICATION_RIGHT)); $this->_equalAgainstFile($figlet->render('Dummy'), 'StandardAlignRight.figlet'); } public function testStandardRightToLeftAlignLeft() { $figlet = new Figlet\Figlet(array('justification' => Figlet\Figlet::JUSTIFICATION_LEFT, 'rightToLeft' => Figlet\Figlet::DIRECTION_RIGHT_TO_LEFT)); $this->_equalAgainstFile($figlet->render('Dummy'), 'StandardRightToLeftAlignLeft.figlet'); } public function testStandardRightToLeftAlignCenter() { $figlet = new Figlet\Figlet(array('justification' => Figlet\Figlet::JUSTIFICATION_CENTER, 'rightToLeft' => Figlet\Figlet::DIRECTION_RIGHT_TO_LEFT)); $this->_equalAgainstFile($figlet->render('Dummy'), 'StandardRightToLeftAlignCenter.figlet'); } public function testStandardRightToLeftAlignRight() { $figlet = new Figlet\Figlet(array('rightToLeft' => Figlet\Figlet::DIRECTION_RIGHT_TO_LEFT)); $this->_equalAgainstFile($figlet->render('Dummy'), 'StandardRightToLeftAlignRight.figlet'); } public function testWrongParameter() { $figlet = new Figlet\Figlet(); $this->setExpectedException('Zend\Text\Figlet\Exception\InvalidArgumentException', 'must be a string'); $figlet->render(1); } public function testCorrectEncodingUTF8() { $figlet = new Figlet\Figlet(); $this->_equalAgainstFile($figlet->render('Ömläüt'), 'CorrectEncoding.figlet'); } public function testCorrectEncodingISO885915() { if (PHP_OS == 'AIX') { $this->markTestSkipped('Test case cannot run on AIX'); } $figlet = new Figlet\Figlet(); $isoText = iconv('UTF-8', 'ISO-8859-15', 'Ömläüt'); $this->_equalAgainstFile($figlet->render($isoText, 'ISO-8859-15'), 'CorrectEncoding.figlet'); } public function testIncorrectEncoding() { $this->markTestSkipped('Test case not reproducible on all setups'); $this->setExpectedException('Zend\Text\Figlet\Exception\RuntimeException'); $figlet = new Figlet\Figlet(); if (PHP_OS == 'AIX') { $isoText = iconv('UTF-8', 'ISO-8859-15', 'Ömläüt'); } else { $isoText = iconv('UTF-8', 'ISO-8859-15', 'Ömläüt'); } $figlet->render($isoText); } public function testNonExistentFont() { $this->setExpectedException('Zend\Text\Figlet\Exception\RuntimeException', 'not found'); $figlet = new Figlet\Figlet(array('font' => __DIR__ . '/Figlet/NonExistentFont.flf')); } public function testInvalidFont() { $this->setExpectedException('Zend\Text\Figlet\Exception\UnexpectedValueException', 'Not a FIGlet'); $figlet = new Figlet\Figlet(array('font' => __DIR__ . '/Figlet/InvalidFont.flf')); } public function testGzippedFont() { $figlet = new Figlet\Figlet(array('font' => __DIR__ . '/Figlet/GzippedFont.gz')); $this->_equalAgainstFile($figlet->render('Dummy'), 'StandardAlignLeft.figlet'); } public function testConfig() { $config = new \Zend\Config\Config(array('justification' => Figlet\Figlet::JUSTIFICATION_RIGHT)); $figlet = new Figlet\Figlet($config); $this->_equalAgainstFile($figlet->render('Dummy'), 'StandardAlignRight.figlet'); } public function testOutputWidth() { $figlet = new Figlet\Figlet(array('outputWidth' => 50, 'justification' => Figlet\Figlet::JUSTIFICATION_RIGHT)); $this->_equalAgainstFile($figlet->render('Dummy'), 'OutputWidth50AlignRight.figlet'); } public function testSmushModeRemoved() { $figlet = new Figlet\Figlet(array('smushMode' => -1)); $this->_equalAgainstFile($figlet->render('Dummy'), 'NoSmush.figlet'); } public function testSmushModeRemovedRightToLeft() { $figlet = new Figlet\Figlet(array('smushMode' => -1, 'rightToLeft' => Figlet\Figlet::DIRECTION_RIGHT_TO_LEFT)); $this->_equalAgainstFile($figlet->render('Dummy'), 'NoSmushRightToLeft.figlet'); } public function testSmushModeInvalid() { $figlet = new Figlet\Figlet(array('smushMode' => -5)); $this->_equalAgainstFile($figlet->render('Dummy'), 'StandardAlignLeft.figlet'); } public function testSmushModeTooSmall() { $figlet = new Figlet\Figlet(array('smushMode' => -2)); $this->_equalAgainstFile($figlet->render('Dummy'), 'StandardAlignLeft.figlet'); } public function testSmushModeDefault() { $figlet = new Figlet\Figlet(array('smushMode' => 0)); $this->_equalAgainstFile($figlet->render('Dummy'), 'SmushDefault.figlet'); } public function testSmushModeForced() { $figlet = new Figlet\Figlet(array('smushMode' => 5)); $this->_equalAgainstFile($figlet->render('Dummy'), 'SmushForced.figlet'); } public function testWordWrapLeftToRight() { $figlet = new Figlet\Figlet(); $this->_equalAgainstFile($figlet->render('Dummy Dummy Dummy'), 'WordWrapLeftToRight.figlet'); } public function testWordWrapRightToLeft() { $figlet = new Figlet\Figlet(array('rightToLeft' => Figlet\Figlet::DIRECTION_RIGHT_TO_LEFT)); $this->_equalAgainstFile($figlet->render('Dummy Dummy Dummy'), 'WordWrapRightToLeft.figlet'); } public function testCharWrapLeftToRight() { $figlet = new Figlet\Figlet(); $this->_equalAgainstFile($figlet->render('DummyDumDummy'), 'CharWrapLeftToRight.figlet'); } public function testCharWrapRightToLeft() { $figlet = new Figlet\Figlet(array('rightToLeft' => Figlet\Figlet::DIRECTION_RIGHT_TO_LEFT)); $this->_equalAgainstFile($figlet->render('DummyDumDummy'), 'CharWrapRightToLeft.figlet'); } public function testParagraphOff() { $figlet = new Figlet\Figlet(); $this->_equalAgainstFile($figlet->render("Dum\nDum\n\nDum\n"), 'ParagraphOff.figlet'); } public function testParagraphOn() { $figlet = new Figlet\Figlet(array('handleParagraphs' => true)); $this->_equalAgainstFile($figlet->render("Dum\nDum\n\nDum\n"), 'ParagraphOn.figlet'); } public function testEmptyString() { $figlet = new Figlet\Figlet(); $this->assertEquals('', $figlet->render('')); } protected function _equalAgainstFile($output, $file) { $compareString = file_get_contents(__DIR__ . '/Figlet/' . $file); $this->assertEquals($compareString, $output); } }
magicobject/zf2
tests/Zend/Text/FigletTest.php
PHP
bsd-3-clause
8,443
<?php function testfunc ($var) { echo "testfunc $var\n"; } class foo { public $arr = array('testfunc'); function bar () { $this->arr[0]('testvalue'); } } $a = new foo (); $a->bar (); ?>
JSchwehn/php
testdata/fuzzdir/corpus/tests_lang_bug25652.php
PHP
bsd-3-clause
210
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript"> (function($){$.fn.easyTabs=function(option){var param=jQuery.extend({fadeSpeed:"fast",defaultContent:1,activeClass:'active'},option);$(this).each(function(){var thisId="#"+this.id;if(param.defaultContent==''){param.defaultContent=1;} if(typeof param.defaultContent=="number") {var defaultTab=$(thisId+" .tabs li:eq("+(param.defaultContent-1)+") a").attr('href').substr(1);}else{var defaultTab=param.defaultContent;} $(thisId+" .tabs li a").each(function(){var tabToHide=$(this).attr('href').substr(1);$("#"+tabToHide).addClass('easytabs-tab-content');});hideAll();changeContent(defaultTab);function hideAll(){$(thisId+" .easytabs-tab-content").hide();} function changeContent(tabId){hideAll();$(thisId+" .tabs li").removeClass(param.activeClass);$(thisId+" .tabs li a[href=#"+tabId+"]").closest('li').addClass(param.activeClass);if(param.fadeSpeed!="none") {$(thisId+" #"+tabId).fadeIn(param.fadeSpeed);}else{$(thisId+" #"+tabId).show();}} $(thisId+" .tabs li").click(function(){var tabId=$(this).find('a').attr('href').substr(1);changeContent(tabId);return false;});});}})(jQuery); </script> <link rel="stylesheet" href="specimen_files/specimen_stylesheet.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="stylesheet.css" type="text/css" charset="utf-8" /> <style type="text/css"> body{ font-family: 'exo_2bold'; } </style> <title>Exo 2 Bold Specimen</title> <script type="text/javascript" charset="utf-8"> $(document).ready(function() { $('#container').easyTabs({defaultContent:1}); }); </script> </head> <body> <div id="container"> <div id="header"> Exo 2 Bold </div> <ul class="tabs"> <li><a href="#specimen">Specimen</a></li> <li><a href="#layout">Sample Layout</a></li> <li><a href="#installing">Installing Webfonts</a></li> </ul> <div id="main_content"> <div id="specimen"> <div class="section"> <div class="grid12 firstcol"> <div class="huge">AaBb</div> </div> </div> <div class="section"> <div class="glyph_range">A&#x200B;B&#x200b;C&#x200b;D&#x200b;E&#x200b;F&#x200b;G&#x200b;H&#x200b;I&#x200b;J&#x200b;K&#x200b;L&#x200b;M&#x200b;N&#x200b;O&#x200b;P&#x200b;Q&#x200b;R&#x200b;S&#x200b;T&#x200b;U&#x200b;V&#x200b;W&#x200b;X&#x200b;Y&#x200b;Z&#x200b;a&#x200b;b&#x200b;c&#x200b;d&#x200b;e&#x200b;f&#x200b;g&#x200b;h&#x200b;i&#x200b;j&#x200b;k&#x200b;l&#x200b;m&#x200b;n&#x200b;o&#x200b;p&#x200b;q&#x200b;r&#x200b;s&#x200b;t&#x200b;u&#x200b;v&#x200b;w&#x200b;x&#x200b;y&#x200b;z&#x200b;1&#x200b;2&#x200b;3&#x200b;4&#x200b;5&#x200b;6&#x200b;7&#x200b;8&#x200b;9&#x200b;0&#x200b;&amp;&#x200b;.&#x200b;,&#x200b;?&#x200b;!&#x200b;&#64;&#x200b;(&#x200b;)&#x200b;#&#x200b;$&#x200b;%&#x200b;*&#x200b;+&#x200b;-&#x200b;=&#x200b;:&#x200b;;</div> </div> <div class="section"> <div class="grid12 firstcol"> <table class="sample_table"> <tr><td>10</td><td class="size10">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</td></tr> <tr><td>11</td><td class="size11">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</td></tr> <tr><td>12</td><td class="size12">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</td></tr> <tr><td>13</td><td class="size13">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</td></tr> <tr><td>14</td><td class="size14">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</td></tr> <tr><td>16</td><td class="size16">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</td></tr> <tr><td>18</td><td class="size18">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</td></tr> <tr><td>20</td><td class="size20">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</td></tr> <tr><td>24</td><td class="size24">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</td></tr> <tr><td>30</td><td class="size30">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</td></tr> <tr><td>36</td><td class="size36">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</td></tr> <tr><td>48</td><td class="size48">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</td></tr> <tr><td>60</td><td class="size60">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</td></tr> <tr><td>72</td><td class="size72">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</td></tr> <tr><td>90</td><td class="size90">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</td></tr> </table> </div> </div> <div class="section" id="bodycomparison"> <div id="xheight"> <div class="fontbody">&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;&#x25FC;body</div><div class="arialbody">body</div><div class="verdanabody">body</div><div class="georgiabody">body</div></div> <div class="fontbody" style="z-index:1"> body<span>Exo 2 Bold</span> </div> <div class="arialbody" style="z-index:1"> body<span>Arial</span> </div> <div class="verdanabody" style="z-index:1"> body<span>Verdana</span> </div> <div class="georgiabody" style="z-index:1"> body<span>Georgia</span> </div> </div> <div class="section psample psample_row1" id=""> <div class="grid2 firstcol"> <p class="size10"><span>10.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p> </div> <div class="grid3"> <p class="size11"><span>11.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p> </div> <div class="grid3"> <p class="size12"><span>12.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p> </div> <div class="grid4"> <p class="size13"><span>13.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p> </div> <div class="white_blend"></div> </div> <div class="section psample psample_row2" id=""> <div class="grid3 firstcol"> <p class="size14"><span>14.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p> </div> <div class="grid4"> <p class="size16"><span>16.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p> </div> <div class="grid5"> <p class="size18"><span>18.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p> </div> <div class="white_blend"></div> </div> <div class="section psample psample_row3" id=""> <div class="grid5 firstcol"> <p class="size20"><span>20.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p> </div> <div class="grid7"> <p class="size24"><span>24.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p> </div> <div class="white_blend"></div> </div> <div class="section psample psample_row4" id=""> <div class="grid12 firstcol"> <p class="size30"><span>30.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p> </div> <div class="white_blend"></div> </div> <div class="section psample psample_row1 fullreverse"> <div class="grid2 firstcol"> <p class="size10"><span>10.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p> </div> <div class="grid3"> <p class="size11"><span>11.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p> </div> <div class="grid3"> <p class="size12"><span>12.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p> </div> <div class="grid4"> <p class="size13"><span>13.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p> </div> <div class="black_blend"></div> </div> <div class="section psample psample_row2 fullreverse"> <div class="grid3 firstcol"> <p class="size14"><span>14.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p> </div> <div class="grid4"> <p class="size16"><span>16.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p> </div> <div class="grid5"> <p class="size18"><span>18.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p> </div> <div class="black_blend"></div> </div> <div class="section psample fullreverse psample_row3" id=""> <div class="grid5 firstcol"> <p class="size20"><span>20.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p> </div> <div class="grid7"> <p class="size24"><span>24.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p> </div> <div class="black_blend"></div> </div> <div class="section psample fullreverse psample_row4" id="" style="border-bottom: 20px #000 solid;"> <div class="grid12 firstcol"> <p class="size30"><span>30.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p> </div> <div class="black_blend"></div> </div> </div> <div id="layout"> <div class="section"> <div class="grid12 firstcol"> <h1>Lorem Ipsum Dolor</h1> <h2>Etiam porta sem malesuada magna mollis euismod</h2> <p class="byline">By <a href="#link">Aenean Lacinia</a></p> </div> </div> <div class="section"> <div class="grid8 firstcol"> <p class="large">Donec sed odio dui. Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. </p> <h3>Pellentesque ornare sem</h3> <p>Maecenas sed diam eget risus varius blandit sit amet non magna. Maecenas faucibus mollis interdum. Donec ullamcorper nulla non metus auctor fringilla. Nullam id dolor id nibh ultricies vehicula ut id elit. Nullam id dolor id nibh ultricies vehicula ut id elit. </p> <p>Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. </p> <p>Nulla vitae elit libero, a pharetra augue. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Aenean lacinia bibendum nulla sed consectetur. </p> <p>Nullam quis risus eget urna mollis ornare vel eu leo. Nullam quis risus eget urna mollis ornare vel eu leo. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec ullamcorper nulla non metus auctor fringilla. </p> <h3>Cras mattis consectetur</h3> <p>Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum. Aenean lacinia bibendum nulla sed consectetur. Integer posuere erat a ante venenatis dapibus posuere velit aliquet. Cras mattis consectetur purus sit amet fermentum. </p> <p>Nullam id dolor id nibh ultricies vehicula ut id elit. Nullam quis risus eget urna mollis ornare vel eu leo. Cras mattis consectetur purus sit amet fermentum.</p> </div> <div class="grid4 sidebar"> <div class="box reverse"> <p class="last">Nullam quis risus eget urna mollis ornare vel eu leo. Donec ullamcorper nulla non metus auctor fringilla. Cras mattis consectetur purus sit amet fermentum. Sed posuere consectetur est at lobortis. Lorem ipsum dolor sit amet, consectetur adipiscing elit. </p> </div> <p class="caption">Maecenas sed diam eget risus varius.</p> <p>Vestibulum id ligula porta felis euismod semper. Integer posuere erat a ante venenatis dapibus posuere velit aliquet. Vestibulum id ligula porta felis euismod semper. Sed posuere consectetur est at lobortis. Maecenas sed diam eget risus varius blandit sit amet non magna. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. </p> <p>Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit. Aenean lacinia bibendum nulla sed consectetur. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Aenean lacinia bibendum nulla sed consectetur. Nullam quis risus eget urna mollis ornare vel eu leo. </p> <p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec ullamcorper nulla non metus auctor fringilla. Maecenas faucibus mollis interdum. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. </p> </div> </div> </div> <div id="specs"> </div> <div id="installing"> <div class="section"> <div class="grid7 firstcol"> <h1>Installing Webfonts</h1> <p>Webfonts are supported by all major browser platforms but not all in the same way. There are currently four different font formats that must be included in order to target all browsers. This includes TTF, WOFF, EOT and SVG.</p> <h2>1. Upload your webfonts</h2> <p>You must upload your webfont kit to your website. They should be in or near the same directory as your CSS files.</p> <h2>2. Include the webfont stylesheet</h2> <p>A special CSS @font-face declaration helps the various browsers select the appropriate font it needs without causing you a bunch of headaches. Learn more about this syntax by reading the <a href="https://www.fontspring.com/blog/further-hardening-of-the-bulletproof-syntax">Fontspring blog post</a> about it. The code for it is as follows:</p> <code> @font-face{ font-family: 'MyWebFont'; src: url('WebFont.eot'); src: url('WebFont.eot?iefix') format('eot'), url('WebFont.woff') format('woff'), url('WebFont.ttf') format('truetype'), url('WebFont.svg#webfont') format('svg'); } </code> <p>We've already gone ahead and generated the code for you. All you have to do is link to the stylesheet in your HTML, like this:</p> <code>&lt;link rel=&quot;stylesheet&quot; href=&quot;stylesheet.css&quot; type=&quot;text/css&quot; charset=&quot;utf-8&quot; /&gt;</code> <h2>3. Modify your own stylesheet</h2> <p>To take advantage of your new fonts, you must tell your stylesheet to use them. Look at the original @font-face declaration above and find the property called "font-family." The name linked there will be what you use to reference the font. Prepend that webfont name to the font stack in the "font-family" property, inside the selector you want to change. For example:</p> <code>p { font-family: 'MyWebFont', Arial, sans-serif; }</code> <h2>4. Test</h2> <p>Getting webfonts to work cross-browser <em>can</em> be tricky. Use the information in the sidebar to help you if you find that fonts aren't loading in a particular browser.</p> </div> <div class="grid5 sidebar"> <div class="box"> <h2>Troubleshooting<br />Font-Face Problems</h2> <p>Having trouble getting your webfonts to load in your new website? Here are some tips to sort out what might be the problem.</p> <h3>Fonts not showing in any browser</h3> <p>This sounds like you need to work on the plumbing. You either did not upload the fonts to the correct directory, or you did not link the fonts properly in the CSS. If you've confirmed that all this is correct and you still have a problem, take a look at your .htaccess file and see if requests are getting intercepted.</p> <h3>Fonts not loading in iPhone or iPad</h3> <p>The most common problem here is that you are serving the fonts from an IIS server. IIS refuses to serve files that have unknown MIME types. If that is the case, you must set the MIME type for SVG to "image/svg+xml" in the server settings. Follow these instructions from Microsoft if you need help.</p> <h3>Fonts not loading in Firefox</h3> <p>The primary reason for this failure? You are still using a version Firefox older than 3.5. So upgrade already! If that isn't it, then you are very likely serving fonts from a different domain. Firefox requires that all font assets be served from the same domain. Lastly it is possible that you need to add WOFF to your list of MIME types (if you are serving via IIS.)</p> <h3>Fonts not loading in IE</h3> <p>Are you looking at Internet Explorer on an actual Windows machine or are you cheating by using a service like Adobe BrowserLab? Many of these screenshot services do not render @font-face for IE. Best to test it on a real machine.</p> <h3>Fonts not loading in IE9</h3> <p>IE9, like Firefox, requires that fonts be served from the same domain as the website. Make sure that is the case.</p> </div> </div> </div> </div> </div> <div id="footer"> <p>&copy;2010-2011 Fontspring. All rights reserved.</p> </div> </div> </body> </html>
alaevka/olam
frontend/web/fonts/exo2_bold_macroman/Exo2-Bold-demo.html
HTML
bsd-3-clause
25,093
// Copyright 2019 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. package org.chromium.chrome.browser.autofill_assistant; import static androidx.test.espresso.Espresso.onView; import static androidx.test.espresso.assertion.ViewAssertions.matches; import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed; import static androidx.test.espresso.matcher.ViewMatchers.withText; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.assertThat; import static org.chromium.chrome.browser.autofill_assistant.AutofillAssistantUiTestUtil.hasTypefaceSpan; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Typeface; import android.support.test.InstrumentationRegistry; import android.widget.TextView; import androidx.test.filters.MediumTest; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.chromium.base.test.util.CommandLineFlags; import org.chromium.chrome.autofill_assistant.R; import org.chromium.chrome.browser.autofill_assistant.infobox.AssistantInfoBox; import org.chromium.chrome.browser.autofill_assistant.infobox.AssistantInfoBoxCoordinator; import org.chromium.chrome.browser.autofill_assistant.infobox.AssistantInfoBoxModel; import org.chromium.chrome.browser.customtabs.CustomTabActivityTestRule; import org.chromium.chrome.browser.customtabs.CustomTabsTestUtils; import org.chromium.chrome.browser.flags.ChromeSwitches; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; import org.chromium.content_public.browser.test.util.TestThreadUtils; /** * Tests for the Autofill Assistant infobox. */ @CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE}) @RunWith(ChromeJUnit4ClassRunner.class) public class AutofillAssistantInfoBoxUiTest { @Rule public CustomTabActivityTestRule mTestRule = new CustomTabActivityTestRule(); private TextView getExplanationView(AssistantInfoBoxCoordinator coordinator) { return coordinator.getView().findViewById(R.id.info_box_explanation); } private AssistantInfoBoxModel createModel() { return TestThreadUtils.runOnUiThreadBlockingNoException(AssistantInfoBoxModel::new); } /** Creates a coordinator for use in UI tests, and adds it to the global view hierarchy. */ private AssistantInfoBoxCoordinator createCoordinator(AssistantInfoBoxModel model) throws Exception { AssistantInfoBoxCoordinator coordinator = TestThreadUtils.runOnUiThreadBlocking(() -> { Bitmap testImage = BitmapFactory.decodeResource( mTestRule.getActivity().getResources(), R.drawable.btn_close); return new AssistantInfoBoxCoordinator(InstrumentationRegistry.getTargetContext(), model, new AutofillAssistantUiTestUtil.MockImageFetcher(testImage, null)); }); TestThreadUtils.runOnUiThreadBlocking( () -> AutofillAssistantUiTestUtil.attachToCoordinator( mTestRule.getActivity(), coordinator.getView())); return coordinator; } @Before public void setUp() { mTestRule.startCustomTabActivityWithIntent(CustomTabsTestUtils.createMinimalCustomTabIntent( InstrumentationRegistry.getTargetContext(), "about:blank")); } /** Tests assumptions about the initial state of the infobox. */ @Test @MediumTest public void testInitialState() throws Exception { AssistantInfoBoxModel model = createModel(); AssistantInfoBoxCoordinator coordinator = createCoordinator(model); assertThat(model.get(AssistantInfoBoxModel.INFO_BOX), nullValue()); onView(is(coordinator.getView())).check(matches(not(isDisplayed()))); } /** Tests for an infobox with a message, but without an image. */ @Test @MediumTest public void testMessageNoImage() throws Exception { AssistantInfoBoxModel model = createModel(); AssistantInfoBoxCoordinator coordinator = createCoordinator(model); AssistantInfoBox infoBox = new AssistantInfoBox("", "Message"); TestThreadUtils.runOnUiThreadBlocking( () -> model.set(AssistantInfoBoxModel.INFO_BOX, infoBox)); onView(is(coordinator.getView())).check(matches(isDisplayed())); // Image should not be set. assertThat(getExplanationView(coordinator).getCompoundDrawables()[1], nullValue()); onView(is(getExplanationView(coordinator))).check(matches(withText("Message"))); // Test that info message supports typeface span. AssistantInfoBox boldInfoBox = new AssistantInfoBox("", "<b>Message</b>"); TestThreadUtils.runOnUiThreadBlocking( () -> model.set(AssistantInfoBoxModel.INFO_BOX, boldInfoBox)); onView(is(getExplanationView(coordinator))).check(matches(withText("Message"))); onView(withText("Message")) .check(matches(hasTypefaceSpan(0, "Message".length() - 1, Typeface.BOLD))); } /** Tests for an infobox with message and image. */ @Test @MediumTest public void testImage() throws Exception { AssistantInfoBoxModel model = createModel(); AssistantInfoBoxCoordinator coordinator = createCoordinator(model); AssistantInfoBox infoBox = new AssistantInfoBox("x", "Message"); TestThreadUtils.runOnUiThreadBlocking( () -> model.set(AssistantInfoBoxModel.INFO_BOX, infoBox)); onView(is(getExplanationView(coordinator))).check(matches(isDisplayed())); // Image should be set. assertThat(getExplanationView(coordinator).getCompoundDrawables()[1], not(nullValue())); onView(is(getExplanationView(coordinator))).check(matches(withText("Message"))); } @Test @MediumTest public void testVisibility() throws Exception { AssistantInfoBoxModel model = createModel(); AssistantInfoBoxCoordinator coordinator = createCoordinator(model); AssistantInfoBox infoBox = new AssistantInfoBox("", ""); TestThreadUtils.runOnUiThreadBlocking( () -> model.set(AssistantInfoBoxModel.INFO_BOX, infoBox)); onView(is(coordinator.getView())).check(matches(isDisplayed())); TestThreadUtils.runOnUiThreadBlocking( () -> model.set(AssistantInfoBoxModel.INFO_BOX, null)); onView(is(coordinator.getView())).check(matches(not(isDisplayed()))); } }
ric2b/Vivaldi-browser
chromium/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantInfoBoxUiTest.java
Java
bsd-3-clause
6,693
/* table reflow widget for TableSorter 2/7/2015 (v2.19.0) * Requires tablesorter v2.8+ and jQuery 1.7+ * Also, this widget requires the following default css (modify as desired) / * REQUIRED CSS: change your reflow breakpoint here (35em below) * / @media ( max-width: 35em ) { .ui-table-reflow td, .ui-table-reflow th { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; float: right; / * if not using the stickyHeaders widget (not the css3 version) * the "!important" flag, and "height: auto" can be removed * / width: 100% !important; height: auto !important; } / * reflow widget * / .ui-table-reflow tbody td[data-title]:before { color: #469; font-size: .9em; content: attr(data-title); float: left; width: 50%; white-space: pre-wrap; text-align: bottom; display: inline-block; } / * reflow2 widget * / table.ui-table-reflow .ui-table-cell-label.ui-table-cell-label-top { display: block; padding: .4em 0; margin: .4em 0; text-transform: uppercase; font-size: .9em; font-weight: 400; } table.ui-table-reflow .ui-table-cell-label { padding: .4em; min-width: 30%; display: inline-block; margin: -.4em 1em -.4em -.4em; } } .ui-table-reflow .ui-table-cell-label { display: none; } */ /*jshint browser:true, jquery:true, unused:false */ /*global jQuery: false */ ;(function($){ "use strict"; var ts = $.tablesorter, tablereflow = { // simple reflow // add data-attribute to each cell which shows when media query is active // this widget DOES NOT WORK on a table with multiple thead rows init : function(table, c, wo) { var $this, title = wo.reflow_dataAttrib, header = wo.reflow_headerAttrib, headers = []; c.$table .addClass(wo.reflow_className) .off('refresh.tsreflow updateComplete.tsreflow2') // emulate jQuery Mobile refresh // https://api.jquerymobile.com/table-reflow/#method-refresh .on('refresh.tsreflow updateComplete.tsreflow2', function(){ tablereflow.init(table, c, wo); }); c.$headers.each(function(){ $this = $(this); headers.push( $.trim( $this.attr(header) || $this.text() ) ); }); c.$tbodies.children().each(function(){ $(this).children().each(function(i){ $(this).attr(title, headers[i]); }); }); }, init2: function(table, c, wo) { var $this, $tbody, i, $hdr, txt, len, cols = c.columns, header = wo.reflow2_headerAttrib, headers = []; c.$table .addClass(wo.reflow2_className) .off('refresh.tsreflow2 updateComplete.tsreflow2') // emulate jQuery Mobile refresh // https://api.jquerymobile.com/table-reflow/#method-refresh .on('refresh.tsreflow2 updateComplete.tsreflow2', function(){ tablereflow.init2(table, c, wo); }); // add <b> to every table cell with thead cell contents for (i = 0; i < cols; i++) { $hdr = c.$headers.filter('[data-column="' + i + '"]'); if ($hdr.length > 1) { txt = []; /*jshint loopfunc:true */ $hdr.each(function(){ $this = $(this); if (!$this.hasClass(wo.reflow2_classIgnore)) { txt.push( $this.attr(header) || $this.text() ); } }); } else { txt = [ $hdr.attr(header) || $hdr.text() ]; } headers.push( txt ); } // include "remove-me" class so these additional elements are removed before updating txt = '<b class="' + c.selectorRemove.slice(1) + ' ' + wo.reflow2_labelClass; c.$tbodies.children().each(function(){ $tbody = ts.processTbody(table, $(this), true); $tbody.children().each(function(j){ $this = $(this); len = headers[j].length; i = len - 1; while (i >= 0) { $this.prepend(txt + (i === 0 && len > 1 ? ' ' + wo.reflow2_labelTop : '') + '">' + headers[j][i] + '</b>'); i--; } }); ts.processTbody(table, $tbody, false); }); }, remove : function(table, c, wo) { c.$table.removeClass(wo.reflow_className); }, remove2 : function(table, c, wo) { c.$table.removeClass(wo.reflow2_className); } }; ts.addWidget({ id: "reflow", options: { // class name added to make it responsive (class name within media query) reflow_className : 'ui-table-reflow', // header attribute containing modified header name reflow_headerAttrib : 'data-name', // data attribute added to each tbody cell reflow_dataAttrib : 'data-title' }, init: function(table, thisWidget, c, wo) { tablereflow.init(table, c, wo); }, remove: function(table, c, wo){ tablereflow.remove(table, c, wo); } }); ts.addWidget({ id: "reflow2", options: { // class name added to make it responsive (class name within media query) reflow2_className : 'ui-table-reflow', // ignore header cell content with this class name reflow2_classIgnore : 'ui-table-reflow-ignore', // header attribute containing modified header name reflow2_headerAttrib : 'data-name', // class name applied to thead labels reflow2_labelClass : 'ui-table-cell-label', // class name applied to first row thead label reflow2_labelTop : 'ui-table-cell-label-top' }, init: function(table, thisWidget, c, wo) { tablereflow.init2(table, c, wo); }, remove: function(table, c, wo){ tablereflow.remove2(table, c, wo); } }); })(jQuery);
herrthiesen/pb-webapp
web/lib/tablesorter-master/js/widgets/widget-reflow.js
JavaScript
mit
5,344
package org.ripple.bouncycastle.pqc.jcajce.provider.rainbow; import java.security.InvalidAlgorithmParameterException; import java.security.KeyPair; import java.security.SecureRandom; import java.security.spec.AlgorithmParameterSpec; import org.ripple.bouncycastle.crypto.AsymmetricCipherKeyPair; import org.ripple.bouncycastle.pqc.crypto.rainbow.RainbowKeyGenerationParameters; import org.ripple.bouncycastle.pqc.crypto.rainbow.RainbowKeyPairGenerator; import org.ripple.bouncycastle.pqc.crypto.rainbow.RainbowParameters; import org.ripple.bouncycastle.pqc.crypto.rainbow.RainbowPrivateKeyParameters; import org.ripple.bouncycastle.pqc.crypto.rainbow.RainbowPublicKeyParameters; import org.ripple.bouncycastle.pqc.jcajce.spec.RainbowParameterSpec; public class RainbowKeyPairGeneratorSpi extends java.security.KeyPairGenerator { RainbowKeyGenerationParameters param; RainbowKeyPairGenerator engine = new RainbowKeyPairGenerator(); int strength = 1024; SecureRandom random = new SecureRandom(); boolean initialised = false; public RainbowKeyPairGeneratorSpi() { super("Rainbow"); } public void initialize( int strength, SecureRandom random) { this.strength = strength; this.random = random; } public void initialize( AlgorithmParameterSpec params, SecureRandom random) throws InvalidAlgorithmParameterException { if (!(params instanceof RainbowParameterSpec)) { throw new InvalidAlgorithmParameterException("parameter object not a RainbowParameterSpec"); } RainbowParameterSpec rainbowParams = (RainbowParameterSpec)params; param = new RainbowKeyGenerationParameters(random, new RainbowParameters(rainbowParams.getVi())); engine.init(param); initialised = true; } public KeyPair generateKeyPair() { if (!initialised) { param = new RainbowKeyGenerationParameters(random, new RainbowParameters(new RainbowParameterSpec().getVi())); engine.init(param); initialised = true; } AsymmetricCipherKeyPair pair = engine.generateKeyPair(); RainbowPublicKeyParameters pub = (RainbowPublicKeyParameters)pair.getPublic(); RainbowPrivateKeyParameters priv = (RainbowPrivateKeyParameters)pair.getPrivate(); return new KeyPair(new BCRainbowPublicKey(pub), new BCRainbowPrivateKey(priv)); } }
xdv/ripple-lib-java
ripple-bouncycastle/src/main/java/org/ripple/bouncycastle/pqc/jcajce/provider/rainbow/RainbowKeyPairGeneratorSpi.java
Java
isc
2,494
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.5.0_13) on Fri Mar 28 02:22:43 EDT 2008 --> <TITLE> PolyShapes </TITLE> <META NAME="keywords" CONTENT="org.jbox2d.testbed.tests.PolyShapes class"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { parent.document.title="PolyShapes"; } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/PolyShapes.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../org/jbox2d/testbed/tests/Overhang.html" title="class in org.jbox2d.testbed.tests"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../org/jbox2d/testbed/tests/Pulleys.html" title="class in org.jbox2d.testbed.tests"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?org/jbox2d/testbed/tests/PolyShapes.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="PolyShapes.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <!-- ======== START OF CLASS DATA ======== --> <H2> <FONT SIZE="-1"> org.jbox2d.testbed.tests</FONT> <BR> Class PolyShapes</H2> <PRE> java.lang.Object <IMG SRC="../../../../resources/inherit.gif" ALT="extended by ">PTest <IMG SRC="../../../../resources/inherit.gif" ALT="extended by "><B>org.jbox2d.testbed.tests.PolyShapes</B> </PRE> <HR> <DL> <DT><PRE>public class <B>PolyShapes</B><DT>extends PTest</DL> </PRE> <P> <HR> <P> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <A NAME="constructor_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Constructor Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../../../../org/jbox2d/testbed/tests/PolyShapes.html#PolyShapes()">PolyShapes</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <!-- ========== METHOD SUMMARY =========== --> <A NAME="method_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Method Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>protected &nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../org/jbox2d/testbed/tests/PolyShapes.html#checkKeys()">checkKeys</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../org/jbox2d/testbed/tests/PolyShapes.html#go(org.jbox2d.dynamics.World)">go</A></B>(<A HREF="../../../../org/jbox2d/dynamics/World.html" title="class in org.jbox2d.dynamics">World</A>&nbsp;world)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../org/jbox2d/testbed/tests/PolyShapes.html#main(java.lang.String[])">main</A></B>(java.lang.String[]&nbsp;args)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD> </TR> </TABLE> &nbsp; <P> <!-- ========= CONSTRUCTOR DETAIL ======== --> <A NAME="constructor_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Constructor Detail</B></FONT></TH> </TR> </TABLE> <A NAME="PolyShapes()"><!-- --></A><H3> PolyShapes</H3> <PRE> public <B>PolyShapes</B>()</PRE> <DL> </DL> <!-- ============ METHOD DETAIL ========== --> <A NAME="method_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Method Detail</B></FONT></TH> </TR> </TABLE> <A NAME="go(org.jbox2d.dynamics.World)"><!-- --></A><H3> go</H3> <PRE> public void <B>go</B>(<A HREF="../../../../org/jbox2d/dynamics/World.html" title="class in org.jbox2d.dynamics">World</A>&nbsp;world)</PRE> <DL> <DD><DL> </DL> </DD> </DL> <HR> <A NAME="checkKeys()"><!-- --></A><H3> checkKeys</H3> <PRE> protected void <B>checkKeys</B>()</PRE> <DL> <DD><DL> </DL> </DD> </DL> <HR> <A NAME="main(java.lang.String[])"><!-- --></A><H3> main</H3> <PRE> public static void <B>main</B>(java.lang.String[]&nbsp;args)</PRE> <DL> <DD><DL> </DL> </DD> </DL> <!-- ========= END OF CLASS DATA ========= --> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/PolyShapes.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../org/jbox2d/testbed/tests/Overhang.html" title="class in org.jbox2d.testbed.tests"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../org/jbox2d/testbed/tests/Pulleys.html" title="class in org.jbox2d.testbed.tests"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?org/jbox2d/testbed/tests/PolyShapes.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="PolyShapes.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
cr0ybot/MIRROR
libraries/JBox2D/doc/org/jbox2d/testbed/tests/PolyShapes.html
HTML
mit
10,992
require 'spec_helper' describe EmployeeDepartmentEvent do end
SumitMunot/fedena-upgradation
spec/models/employee_department_event_spec.rb
Ruby
mit
63
#include <math.h> #include "mex.h" void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { /* Variables */ int n, s,s1,s2,n1,n2,e, yInd, nNodes, nEdges, maxState, sizeEdgeBel[3], sizeLogZ[2], *y, *edgeEnds, *nStates; double pot,Z, *nodePot, *edgePot, *nodeBel, *edgeBel, *logZ; /* Input */ nodePot = mxGetPr(prhs[0]); edgePot = mxGetPr(prhs[1]); edgeEnds = (int*)mxGetPr(prhs[2]); nStates = (int*)mxGetPr(prhs[3]); if (!mxIsClass(prhs[2],"int32")||!mxIsClass(prhs[3],"int32")) mexErrMsgTxt("edgeEnds and nStates must be int32"); /* Compute Sizes */ nNodes = mxGetDimensions(prhs[0])[0]; maxState = mxGetDimensions(prhs[0])[1]; nEdges = mxGetDimensions(prhs[2])[0]; /* Output */ sizeEdgeBel[0] = maxState; sizeEdgeBel[1] = maxState; sizeEdgeBel[2] = nEdges; sizeLogZ[0] = 1; sizeLogZ[1] = 1; plhs[0] = mxCreateNumericArray(2,mxGetDimensions(prhs[0]),mxDOUBLE_CLASS,mxREAL); plhs[1] = mxCreateNumericArray(3,sizeEdgeBel,mxDOUBLE_CLASS,mxREAL); plhs[2] = mxCreateNumericArray(2,sizeLogZ,mxDOUBLE_CLASS,mxREAL); nodeBel = mxGetPr(plhs[0]); edgeBel = mxGetPr(plhs[1]); logZ = mxGetPr(plhs[2]); /* Initialize */ y = mxCalloc(nNodes,sizeof(int)); Z = 0; while(1) { pot = 1; /* Node */ for(n = 0; n < nNodes; n++) { pot *= nodePot[n + nNodes*y[n]]; } /* Edges */ for(e = 0; e < nEdges; e++) { n1 = edgeEnds[e]-1; n2 = edgeEnds[e+nEdges]-1; pot *= edgePot[y[n1] + maxState*(y[n2] + maxState*e)]; } /* Update nodeBel */ for(n = 0; n < nNodes; n++) { nodeBel[n + nNodes*y[n]] += pot; } /* Update edgeBel */ for (e = 0; e < nEdges; e++) { n1 = edgeEnds[e]-1; n2 = edgeEnds[e+nEdges]-1; edgeBel[y[n1] + maxState*(y[n2] + maxState*e)] += pot; } /* Update Z */ Z += pot; /* Go to next y */ for(yInd = 0; yInd < nNodes; yInd++) { y[yInd] += 1; if(y[yInd] < nStates[yInd]) { break; } else { y[yInd] = 0; } } /* Stop when we are done all y combinations */ if(yInd == nNodes) { break; } } /* Normalize by Z */ for(n = 0; n < nNodes; n++) { for(s = 0; s < nStates[n];s++) { nodeBel[n + nNodes*s] /= Z; } } for(e = 0; e < nEdges; e++) { n1 = edgeEnds[e]-1; n2 = edgeEnds[e+nEdges]-1; for(s1 = 0; s1 < nStates[n1]; s1++) { for(s2 = 0; s2 < nStates[n2]; s2++) { edgeBel[s1 + maxState*(s2 + maxState*e)] /= Z; } } } *logZ = log(Z); /* Free memory */ mxFree(y); }
ClaireXie/edgeGuidedSDSP
utils/UGM/mex/UGM_Infer_ExactC.c
C
mit
3,034
require 'test_helper' class ArticlesControllerTest < ActionController::TestCase test "should get index" do get :index assert_response :success assert_not_nil assigns(:articles) end test "should get new" do get :new assert_response :success end test "should create article" do assert_difference('Article.count') do post :create, :article => { } end assert_redirected_to article_path(assigns(:article)) end test "should show article" do get :show, :id => articles(:one).to_param assert_response :success end test "should get edit" do get :edit, :id => articles(:one).to_param assert_response :success end test "should update article" do put :update, :id => articles(:one).to_param, :article => { } assert_redirected_to article_path(assigns(:article)) end test "should destroy article" do assert_difference('Article.count', -1) do delete :destroy, :id => articles(:one).to_param end assert_redirected_to articles_path end end
seouri/medvane3
test/functional/articles_controller_test.rb
Ruby
mit
1,040
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- info: > If thisArg is null or undefined, the called function is passed the global object as the this value es5id: 15.3.4.4_A3_T9 description: Checking by using eval, argument at call function is void 0 ---*/ eval( " Function(\"this.feat=1\").call(void 0) " ); //CHECK#1 if (this["feat"] !== 1) { $ERROR('#1: If thisArg is null or undefined, the called function is passed the global object as the this value'); }
PiotrDabkowski/Js2Py
tests/test_cases/built-ins/Function/prototype/call/S15.3.4.4_A3_T9.js
JavaScript
mit
564
'use strict'; /** * This module contains a variety of generic promise wrapped `node.child_process.spawn` commands * @module childProcess */ const R = require('ramda'); const Q = require('q'); /** this is not a constant for unit testing purposes */ let spawn = require('child_process').spawn; const util = require('../util'); module.exports = { output, quiet, stream, inherit, stdin }; /** * @param {string} command * @param {string} args * @returns {string} */ function commandStr(command, args) { return `${command} ${args.join(' ')}`; } /** * @param {string} command * @param {string} args * @param {string|number} code * @returns {string} */ function successString(command, args, code) { return `${commandStr(command, args)} Process Exited: ${code}`; } /** * @param {string} command * @param {string} args * @param {string|number} code * @param {string=} stderr * @returns {string} */ function failString(command, args, code, stderr) { stderr = stderr || ''; return `${commandStr(command, args)} terminated with exit code: ${code} ` + stderr; } /** * @param {string} command * @param {string[]} args * @param {number} code * @param {string=} stderr * @returns {Error} */ function failError(command, args, code, stderr) { util.verbose('Failed: ', command, args, code, stderr); code = parseInt(code, 10); stderr = stderr || ''; const errString = failString(command, args, code, stderr); const e = new Error(errString); e.code = code; return e; } /** * Resolves stdout, rejects with stderr, also streams * @param {string} command * @param {Array.<string>=} args * @param {Object=} opts * @returns {Promise<string>} */ function output(command, args, opts) { args = args || []; const options = R.merge({}, opts); const d = Q.defer(); const child = spawn(command, args, options); let stdout = ''; let stderr = ''; child.stdout.setEncoding('utf8'); child.stderr.setEncoding('utf8'); child.stdout.on('data', (data) => { d.notify({ stdout: data }); stdout += data; }); child.stderr.on('data', (data) => { d.notify({ stderr: data }); stderr += data; }); child.on('close', (code) => { if (+code) { d.reject(failError(command, args, code, stderr)); } else { util.verbose(successString(command, args, code)); d.resolve(stdout.trim()); } }); child.stdin.end(); return d.promise; } /** * Does not resolve stdout, but streams, and resolves stderr * @param {string} command * @param {Array.<string>=} args * @param {Object=} opts * @returns {Promise} */ function quiet(command, args, opts) { args = args || []; const options = R.merge({}, opts); const d = Q.defer(); const child = spawn(command, args, options); let stderr = ''; child.stderr.setEncoding('utf8'); child.stdout.on('data', (data) => { d.notify({ stdout: data }); }); child.stderr.on('data', (data) => { d.notify({ stderr: data }); stderr += data; }); child.on('close', (code) => { if (+code) { d.reject(failError(command, args, code, stderr)); } else { util.verbose(successString(command, args, code)); d.resolve(); } }); child.stdin.end(); return d.promise; } /** * Only streams stdout/stderr, no output on resolve/reject * @param {string} command * @param {Array.<string>=} args * @param {Object=} opts * @returns {Promise} */ function stream(command, args, opts) { args = args || []; const options = R.merge({}, opts); const d = Q.defer(); const child = spawn(command, args, options); child.stdout.setEncoding('utf8'); child.stderr.setEncoding('utf8'); child.stdout.on('data', (data) => { d.notify({ data: data }); }); child.stderr.on('data', (data) => { d.notify({ error: data }); }); child.on('close', (code) => { if (+code) { d.reject(failError(command, args, code)); } else { util.verbose(successString(command, args, code)); d.resolve(); } }); child.stdin.end(); return d.promise; } /** * Stdio inherits, meaning that the given command takes over stdio * @param {string} command * @param {Array.<string>=} args * @param {Object=} opts * @returns {Promise} */ function inherit(command, args, opts) { args = args || []; const options = R.merge({ stdio: 'inherit' }, opts); const d = Q.defer(); const child = spawn(command, args, options); child.on('close', (code) => { if (+code) { d.reject(failError(command, args, code)); } else { util.verbose(successString(command, args, code)); d.resolve(); } }); return d.promise; } /** * like output, but puts stdin in as stdin * @param {string} stdin * @param {string} command * @param {Array.<string>=} args * @param {Object=} opts * @returns {Promise<string>} */ function stdin(stdin, command, args, opts) { stdin = stdin || ''; args = args || []; const options = R.merge({}, opts); const d = Q.defer(); const child = spawn(command, args, options); let stderr = ''; let stdout = ''; child.stdout.on('data', (data) => { d.notify({ stdout: data }); stdout += data; }); child.stderr.on('data', (data) => { d.notify({ stderr: data }); stderr += data; }); child.on('close', (code) => { if (+code) { d.reject(failError(command, args, code, stderr)); } else { d.resolve(stdout); } }); child.stdin.write(stdin); child.stdin.end(); return d.promise; }
rangle/the-clusternator
src/cli-wrappers/child-process.js
JavaScript
mit
5,520
.contextMenu { font-family: Verdana,Arial,Helvetica,sans-serif; } .contextMenu li.reply a { background-image: url(/content/data/icons/png/comment_16.png); } .contextMenu li.subscribe a { background-image: url(/content/data/icons/png/cloudy_16.png); } .contextMenu li.unsubscribe a { background-image: url(/content/data/icons/png/clear_16.png); } .contextMenu li.answerplease a { background-image: url(/content/data/icons/png/question_16.png); } .contextMenu li.answered a { background-image: url(/content/data/icons/png/happy_16.png); } .contextMenu li.highlight a { background-image: url(/content/data/icons/png/star_16.png); } .contextMenu li.hide a { background-image: url(/content/data/icons/png/close_16.png); } .contextMenu li.approve a { background-image: url(/content/data/icons/png/approve_16.png); } /*.contextMenu li.approve.selected a { background-image: url(/content/data/icons/png/approve_selected_16.png); }*/ .contextMenu li.reject a { background-image: url(/content/data/icons/png/reject_16.png); } /*.contextMenu li.reject.selected a { background-image: url(/content/data/icons/png/reject_selected_16.png); }*/ .contextMenu li.favorite a { background-image: url(/content/data/icons/png/star_16.png); } .contextMenu li.hide a { background-image: url(/content/data/icons/png/remove_16.png); }
dragon96/nbproject
content/data/css/contextmenu.css
CSS
mit
1,357
"use strict"; const ICollectionBase = require("./ICollectionBase"); const IGuild = require("./IGuild"); const Utils = require("../core/Utils"); const rest = require("../networking/rest"); /** * @interface * @extends ICollectionBase */ class IGuildCollection extends ICollectionBase { constructor(discordie, valuesGetter, valueGetter) { super({ valuesGetter: valuesGetter, valueGetter: valueGetter, itemFactory: (id) => new IGuild(this._discordie, id) }); this._discordie = discordie; Utils.privatify(this); } /** * Makes a request to create a guild. * @param {String} name * @param {String} region * @param {Buffer|null} [icon] * @param {Array<IRole|Object>} [roles] * @param {Array<IChannel|Object>} [channels] * @param {Number} [verificationLevel] * See Discordie.VerificationLevel * @param {Number} [defaultMessageNotifications] * See Discordie.UserNotificationSettings * @returns {Promise<IGuild, Error>} */ create(name, region, icon, roles, channels, verificationLevel, defaultMessageNotifications) { if (icon instanceof Buffer) { icon = Utils.imageToDataURL(icon); } const toRaw = (data, param) => { data = data || []; if (!Array.isArray(data)) throw TypeError("Param '" + param + "' must be an array"); return data.map(v => { return typeof v.getRaw === "function" ? v.getRaw() : null; }).filter(v => v); }; roles = toRaw(roles, "roles"); channels = toRaw(channels, "channels"); return new Promise((rs, rj) => { rest(this._discordie).guilds.createGuild( name, region, icon, roles, channels, verificationLevel, defaultMessageNotifications ) .then(guild => rs(this._discordie.Guilds.get(guild.id))) .catch(rj); }); } /** * Makes a request to get a default list of voice regions. * Use IGuild.fetchRegions for getting guild-specific list. * @returns {Promise<Array<Object>, Error>} */ fetchRegions() { return rest(this._discordie).voice.getRegions(); } } module.exports = IGuildCollection;
Gamecloud-Solutions/streambot
node_modules/discordie/lib/interfaces/IGuildCollection.js
JavaScript
mit
2,152
# Copyright (c) 2012 National ICT Australia Limited (NICTA). # This software may be used and distributed solely under the terms of the MIT license (License). # You should find a copy of the License in LICENSE.TXT or at http://opensource.org/licenses/MIT. # By downloading or using this software you accept the terms and the liability disclaimer in the License. require 'test_helper' describe OmfRc::MessageProcessError do it "must be able to initialised" do mpe = OmfRc::MessageProcessError.new('test_cid', 'replyto_address', 'error_messsage') mpe.cid.must_equal 'test_cid' mpe.replyto.must_equal 'replyto_address' mpe.message.must_equal 'error_messsage' mpe.must_be_kind_of StandardError end end
mytestbed/omf
omf_rc/test/omf_rc/message_process_error_spec.rb
Ruby
mit
723
package openblocks.client.renderer.tileentity.tank; import net.minecraftforge.common.util.ForgeDirection; import openmods.utils.Diagonal; public interface ITankConnections { public VerticalConnection getTopConnection(); public VerticalConnection getBottomConnection(); public HorizontalConnection getHorizontalConnection(ForgeDirection dir); public DiagonalConnection getDiagonalConnection(Diagonal dir); }
PrinceOfAmber/OpenBlocks
src/main/java/openblocks/client/renderer/tileentity/tank/ITankConnections.java
Java
mit
416
""" Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param root: The root of binary tree. @return: True if this Binary tree is Balanced, or false. """ def isBalanced(self, root): # write your code here isbalanced, h = self.isBalancedandHeight(root) return isbalanced def isBalancedandHeight(self, root): if root is None: return True, 0 l, r = root.left, root.right l_balanced, l_h = self.isBalancedandHeight(l) if not l_balanced: return False, 0 r_balanced, r_h = self.isBalancedandHeight(r) if not r_balanced: return False, 0 if abs(l_h - r_h) < 2: return True, max(l_h, r_h) + 1 return False, 0
Chasego/codirit
jiuzhang/Nine Chapters/3 Binary Tree & Divide Conquer/py/BalancedBinaryTree_rec.py
Python
mit
873
package org.sql2o; import org.sql2o.converters.Converter; import org.sql2o.converters.ConverterException; import org.sql2o.data.LazyTable; import org.sql2o.data.Row; import org.sql2o.data.Table; import org.sql2o.data.TableResultSetIterator; import org.sql2o.logging.LocalLoggerFactory; import org.sql2o.logging.Logger; import org.sql2o.quirks.Quirks; import org.sql2o.reflection.PojoIntrospector; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.sql.*; import java.util.*; import static org.sql2o.converters.Convert.throwIfNull; /** * Represents a sql2o statement. With sql2o, all statements are instances of the Query class. */ @SuppressWarnings("UnusedDeclaration") public class Query implements AutoCloseable { private final static Logger logger = LocalLoggerFactory.getLogger(Query.class); private Connection connection; private Map<String, String> caseSensitiveColumnMappings; private Map<String, String> columnMappings; private final PreparedStatement statement; private boolean caseSensitive; private boolean autoDeriveColumnNames; private boolean throwOnMappingFailure = true; private String name; private boolean returnGeneratedKeys; private final Map<String, List<Integer>> paramNameToIdxMap; private final Set<String> addedParameters; private final String parsedQuery; private int maxBatchRecords = 0; private int currentBatchRecords = 0; private ResultSetHandlerFactoryBuilder resultSetHandlerFactoryBuilder; @Override public String toString() { return parsedQuery; } public Query(Connection connection, String queryText, boolean returnGeneratedKeys) { this(connection, queryText, returnGeneratedKeys, null); } public Query(Connection connection, String queryText, String[] columnNames) { this(connection, queryText, false, columnNames); } private Query(Connection connection, String queryText, boolean returnGeneratedKeys, String[] columnNames) { this.connection = connection; this.returnGeneratedKeys = returnGeneratedKeys; this.setColumnMappings(connection.getSql2o().getDefaultColumnMappings()); this.caseSensitive = connection.getSql2o().isDefaultCaseSensitive(); paramNameToIdxMap = new HashMap<>(); addedParameters = new HashSet<>(); parsedQuery = connection.getSql2o().getQuirks().getSqlParameterParsingStrategy().parseSql(queryText, paramNameToIdxMap); try { if (columnNames != null && columnNames.length > 0){ statement = connection.getJdbcConnection().prepareStatement(parsedQuery, columnNames); } else if (returnGeneratedKeys) { statement = connection.getJdbcConnection().prepareStatement(parsedQuery, Statement.RETURN_GENERATED_KEYS); } else { statement = connection.getJdbcConnection().prepareStatement(parsedQuery); } } catch(SQLException ex) { throw new Sql2oException(String.format("Error preparing statement - %s", ex.getMessage()), ex); } connection.registerStatement(statement); } // ------------------------------------------------ // ------------- Getter/Setters ------------------- // ------------------------------------------------ public boolean isCaseSensitive() { return caseSensitive; } public Query setCaseSensitive(boolean caseSensitive) { this.caseSensitive = caseSensitive; return this; } public boolean isAutoDeriveColumnNames() { return autoDeriveColumnNames; } public Query setAutoDeriveColumnNames(boolean autoDeriveColumnNames) { this.autoDeriveColumnNames = autoDeriveColumnNames; return this; } public Query throwOnMappingFailure(boolean throwOnMappingFailure) { this.throwOnMappingFailure = throwOnMappingFailure; return this; } public boolean isThrowOnMappingFailure() { return throwOnMappingFailure; } public Connection getConnection(){ return this.connection; } public String getName() { return name; } public Query setName(String name) { this.name = name; return this; } public ResultSetHandlerFactoryBuilder getResultSetHandlerFactoryBuilder() { if (resultSetHandlerFactoryBuilder == null) { resultSetHandlerFactoryBuilder = new DefaultResultSetHandlerFactoryBuilder(); } return resultSetHandlerFactoryBuilder; } public void setResultSetHandlerFactoryBuilder(ResultSetHandlerFactoryBuilder resultSetHandlerFactoryBuilder) { this.resultSetHandlerFactoryBuilder = resultSetHandlerFactoryBuilder; } public Map<String, List<Integer>> getParamNameToIdxMap() { return paramNameToIdxMap; } // ------------------------------------------------ // ------------- Add Parameters ------------------- // ------------------------------------------------ private void addParameterInternal(String name, ParameterSetter parameterSetter) { addedParameters.add(name); if (!this.getParamNameToIdxMap().containsKey(name)) { throw new Sql2oException("Failed to add parameter with name '" + name + "'. No parameter with that name is declared in the sql."); } for (int paramIdx : this.getParamNameToIdxMap().get(name)) { try { parameterSetter.setParameter(paramIdx); } catch (SQLException e) { throw new RuntimeException(String.format("Error adding parameter '%s' - %s", name, e.getMessage()), e); } } } @SuppressWarnings("unchecked") private Object convertParameter(Object value) { if (value == null) { return null; } Converter converter = getQuirks().converterOf(value.getClass()); if (converter == null) { // let's try to add parameter AS IS return value; } return converter.toDatabaseParam(value); } public <T> Query addParameter(String name, Class<T> parameterClass, T value){ //TODO: must cover most of types: BigDecimal,Boolean,SmallInt,Double,Float,byte[] if(InputStream.class.isAssignableFrom(parameterClass)) return addParameter(name, (InputStream)value); if(Integer.class==parameterClass) return addParameter(name, (Integer)value); if(Long.class==parameterClass) return addParameter(name, (Long)value); if(String.class==parameterClass) return addParameter(name, (String)value); if(Timestamp.class==parameterClass) return addParameter(name, (Timestamp)value); if(Time.class==parameterClass) return addParameter(name, (Time)value); final Object convertedValue = convertParameter(value); addParameterInternal(name, new ParameterSetter() { public void setParameter(int paramIdx) throws SQLException { getConnection().getSql2o().getQuirks().setParameter(statement, paramIdx, convertedValue); } }); return this; } public Query withParams(Object... paramValues){ int i=0; for (Object paramValue : paramValues) { addParameter("p" + (++i), paramValue); } return this; } @SuppressWarnings("unchecked") public Query addParameter(String name, Object value) { return value == null ? addParameter(name, Object.class, null) : addParameter(name, (Class<Object>) value.getClass(), value); } public Query addParameter(String name, final InputStream value){ addParameterInternal(name, new ParameterSetter() { public void setParameter(int paramIdx) throws SQLException { getConnection().getSql2o().getQuirks().setParameter(statement, paramIdx, value); } }); return this; } public Query addParameter(String name, final int value){ addParameterInternal(name, new ParameterSetter() { public void setParameter(int paramIdx) throws SQLException { getConnection().getSql2o().getQuirks().setParameter(statement, paramIdx, value); } }); return this; } public Query addParameter(String name, final Integer value) { addParameterInternal(name, new ParameterSetter() { public void setParameter(int paramIdx) throws SQLException { getConnection().getSql2o().getQuirks().setParameter(statement, paramIdx, value); } }); return this; } public Query addParameter(String name, final long value){ addParameterInternal(name, new ParameterSetter() { public void setParameter(int paramIdx) throws SQLException { getConnection().getSql2o().getQuirks().setParameter(statement, paramIdx, value); } }); return this; } public Query addParameter(String name, final Long value){ addParameterInternal(name, new ParameterSetter() { public void setParameter(int paramIdx) throws SQLException { getConnection().getSql2o().getQuirks().setParameter(statement, paramIdx, value); } }); return this; } public Query addParameter(String name, final String value) { addParameterInternal(name, new ParameterSetter() { public void setParameter(int paramIdx) throws SQLException { getConnection().getSql2o().getQuirks().setParameter(statement, paramIdx, value); } }); return this; } public Query addParameter(String name, final Timestamp value){ addParameterInternal(name, new ParameterSetter() { public void setParameter(int paramIdx) throws SQLException { getConnection().getSql2o().getQuirks().setParameter(statement, paramIdx, value); } }); return this; } public Query addParameter(String name, final Time value) { addParameterInternal(name, new ParameterSetter() { public void setParameter(int paramIdx) throws SQLException { getConnection().getSql2o().getQuirks().setParameter(statement, paramIdx, value); } }); return this; } public Query addParameter(String name, final boolean value) { addParameterInternal(name, new ParameterSetter() { @Override public void setParameter(int paramIdx) throws SQLException { getConnection().getSql2o().getQuirks().setParameter(statement, paramIdx, value); } }); return this; } public Query addParameter(String name, final Boolean value) { addParameterInternal(name, new ParameterSetter() { @Override public void setParameter(int paramIdx) throws SQLException { getConnection().getSql2o().getQuirks().setParameter(statement, paramIdx, value); } }); return this; } public Query addParameter(String name, final UUID value) { addParameterInternal(name, new ParameterSetter() { @Override public void setParameter(int paramIdx) throws SQLException { getConnection().getSql2o().getQuirks().setParameter(statement, paramIdx, value); } }); return this; } public Query bind(final Object pojo) { Class clazz = pojo.getClass(); Map<String, PojoIntrospector.ReadableProperty> propertyMap = PojoIntrospector.readableProperties(clazz); for (PojoIntrospector.ReadableProperty property : propertyMap.values()) { try { if( this.getParamNameToIdxMap().containsKey(property.name)) { @SuppressWarnings("unchecked") final Class<Object> type = (Class<Object>) property.type; this.addParameter(property.name, type, property.get(pojo)); } } catch(IllegalArgumentException ex) { logger.debug("Ignoring Illegal Arguments", ex); } catch(IllegalAccessException | InvocationTargetException ex) { throw new RuntimeException(ex); } } return this; } public void close() { connection.removeStatement(statement); try { this.getQuirks().closeStatement(statement); } catch (Throwable ex){ logger.warn("Could not close statement.", ex); } } // ------------------------------------------------ // -------------------- Execute ------------------- // ------------------------------------------------ /** * Iterable {@link java.sql.ResultSet} that wraps {@link PojoResultSetIterator}. */ private abstract class ResultSetIterableBase<T> implements ResultSetIterable<T> { private long start; private long afterExecQuery; protected ResultSet rs; boolean autoCloseConnection = false; public ResultSetIterableBase() { try { start = System.currentTimeMillis(); logExecution(); rs = statement.executeQuery(); afterExecQuery = System.currentTimeMillis(); } catch (SQLException ex) { throw new Sql2oException("Database error: " + ex.getMessage(), ex); } } @Override public void close() { try { if (rs != null) { rs.close(); // log the query long afterClose = System.currentTimeMillis(); logger.debug("total: {} ms, execution: {} ms, reading and parsing: {} ms; executed [{}]", new Object[]{ afterClose - start, afterExecQuery-start, afterClose - afterExecQuery, name }); rs = null; } } catch (SQLException ex) { throw new Sql2oException("Error closing ResultSet.", ex); } finally { if (this.isAutoCloseConnection()){ connection.close(); } else { closeConnectionIfNecessary(); } } } @Override public boolean isAutoCloseConnection() { return this.autoCloseConnection; } @Override public void setAutoCloseConnection(boolean autoCloseConnection) { this.autoCloseConnection = autoCloseConnection; } } /** * Read a collection lazily. Generally speaking, this should only be used if you are reading MANY * results and keeping them all in a Collection would cause memory issues. You MUST call * {@link org.sql2o.ResultSetIterable#close()} when you are done iterating. * * @param returnType type of each row * @return iterable results */ public <T> ResultSetIterable<T> executeAndFetchLazy(final Class<T> returnType) { final ResultSetHandlerFactory<T> resultSetHandlerFactory = newResultSetHandlerFactory(returnType); return executeAndFetchLazy(resultSetHandlerFactory); } private <T> ResultSetHandlerFactory<T> newResultSetHandlerFactory(Class<T> returnType) { final Quirks quirks = getConnection().getSql2o().getQuirks(); ResultSetHandlerFactoryBuilder builder = getResultSetHandlerFactoryBuilder(); if(builder==null) builder=new DefaultResultSetHandlerFactoryBuilder(); builder.setAutoDeriveColumnNames(this.autoDeriveColumnNames); builder.setCaseSensitive(this.caseSensitive); builder.setColumnMappings(this.columnMappings); builder.setQuirks(quirks); builder.throwOnMappingError(this.throwOnMappingFailure); return builder.newFactory(returnType); } /** * Read a collection lazily. Generally speaking, this should only be used if you are reading MANY * results and keeping them all in a Collection would cause memory issues. You MUST call * {@link org.sql2o.ResultSetIterable#close()} when you are done iterating. * * @param resultSetHandlerFactory factory to provide ResultSetHandler * @return iterable results */ public <T> ResultSetIterable<T> executeAndFetchLazy(final ResultSetHandlerFactory<T> resultSetHandlerFactory) { final Quirks quirks = getConnection().getSql2o().getQuirks(); return new ResultSetIterableBase<T>() { public Iterator<T> iterator() { return new PojoResultSetIterator<>(rs, isCaseSensitive(), quirks, resultSetHandlerFactory); } }; } /** * Read a collection lazily. Generally speaking, this should only be used if you are reading MANY * results and keeping them all in a Collection would cause memory issues. You MUST call * {@link org.sql2o.ResultSetIterable#close()} when you are done iterating. * * @param resultSetHandler ResultSetHandler * @return iterable results */ public <T> ResultSetIterable<T> executeAndFetchLazy(final ResultSetHandler<T> resultSetHandler) { final ResultSetHandlerFactory<T> factory = newResultSetHandlerFactory(resultSetHandler); return executeAndFetchLazy(factory); } private static <T> ResultSetHandlerFactory<T> newResultSetHandlerFactory(final ResultSetHandler<T> resultSetHandler) { return new ResultSetHandlerFactory<T>() { public ResultSetHandler<T> newResultSetHandler(ResultSetMetaData resultSetMetaData) throws SQLException { return resultSetHandler; } }; } public <T> List<T> executeAndFetch(Class<T> returnType){ return executeAndFetch(newResultSetHandlerFactory(returnType)); } public <T> List<T> executeAndFetch(ResultSetHandler<T> resultSetHandler){ return executeAndFetch(newResultSetHandlerFactory(resultSetHandler)); } public <T> List<T> executeAndFetch(ResultSetHandlerFactory<T> factory){ List<T> list = new ArrayList<>(); // if sql2o moves to java 7 at some point, this could be much cleaner using try-with-resources ResultSetIterable<T> iterable = null; try { iterable = executeAndFetchLazy(factory); for (T item : iterable) { list.add(item); } } finally { if (iterable != null) { iterable.close(); } } return list; } public <T> T executeAndFetchFirst(Class<T> returnType){ return executeAndFetchFirst(newResultSetHandlerFactory(returnType)); } public <T> T executeAndFetchFirst(ResultSetHandler<T> resultSetHandler){ return executeAndFetchFirst(newResultSetHandlerFactory(resultSetHandler)); } public <T> T executeAndFetchFirst(ResultSetHandlerFactory<T> resultSetHandlerFactory){ // if sql2o moves to java 7 at some point, this could be much cleaner using try-with-resources ResultSetIterable<T> iterable = null; try { iterable = executeAndFetchLazy(resultSetHandlerFactory); Iterator<T> iterator = iterable.iterator(); return iterator.hasNext() ? iterator.next() : null; } finally { if (iterable != null) { iterable.close(); } } } public LazyTable executeAndFetchTableLazy() { final LazyTable lt = new LazyTable(); lt.setRows(new ResultSetIterableBase<Row>() { public Iterator<Row> iterator() { return new TableResultSetIterator(rs, isCaseSensitive(), getConnection().getSql2o().getQuirks(), lt); } }); return lt; } public Table executeAndFetchTable() { LazyTable lt = executeAndFetchTableLazy(); List<Row> rows = new ArrayList<>(); try { for (Row item : lt.rows()) { rows.add(item); } } finally { lt.close(); } // lt==null is always false return new Table(lt.getName(), rows, lt.columns()); } public Connection executeUpdate(){ long start = System.currentTimeMillis(); try{ logExecution(); this.connection.setResult(statement.executeUpdate()); this.connection.setKeys(this.returnGeneratedKeys ? statement.getGeneratedKeys() : null); connection.setCanGetKeys(this.returnGeneratedKeys); } catch(SQLException ex){ this.connection.onException(); throw new Sql2oException("Error in executeUpdate, " + ex.getMessage(), ex); } finally { closeConnectionIfNecessary(); } long end = System.currentTimeMillis(); logger.debug("total: {} ms; executed update [{}]", new Object[]{ end - start, this.getName() == null ? "No name" : this.getName() }); return this.connection; } public Object executeScalar(){ long start = System.currentTimeMillis(); try { logExecution(); ResultSet rs = this.statement.executeQuery(); if (rs.next()){ Object o = getQuirks().getRSVal(rs, 1); long end = System.currentTimeMillis(); logger.debug("total: {} ms; executed scalar [{}]", new Object[]{ end - start, this.getName() == null ? "No name" : this.getName() }); return o; } else{ return null; } } catch (SQLException e) { this.connection.onException(); throw new Sql2oException("Database error occurred while running executeScalar: " + e.getMessage(), e); } finally{ closeConnectionIfNecessary(); } } private Quirks getQuirks() { return this.connection.getSql2o().getQuirks(); } public <V> V executeScalar(Class<V> returnType){ try { Converter<V> converter; //noinspection unchecked converter = throwIfNull(returnType, getQuirks().converterOf(returnType)); //noinspection unchecked logExecution(); return executeScalar(converter); } catch (ConverterException e) { throw new Sql2oException("Error occured while converting value from database to type " + returnType, e); } } public <V> V executeScalar(Converter<V> converter){ try { //noinspection unchecked return converter.convert(executeScalar()); } catch (ConverterException e) { throw new Sql2oException("Error occured while converting value from database", e); } } public <T> List<T> executeScalarList(final Class<T> returnType){ return executeAndFetch(newScalarResultSetHandler(returnType)); } @SuppressWarnings("unchecked") private <T> ResultSetHandler<T> newScalarResultSetHandler(final Class<T> returnType) { final Quirks quirks = getQuirks(); try { final Converter<T> converter = throwIfNull(returnType, quirks.converterOf(returnType)); return new ResultSetHandler<T>() { public T handle(ResultSet resultSet) throws SQLException { Object value = quirks.getRSVal(resultSet, 1); try { return (converter.convert(value)); } catch (ConverterException e) { throw new Sql2oException("Error occurred while converting value from database to type " + returnType, e); } } }; } catch (ConverterException e) { throw new Sql2oException("Can't get converter for type " + returnType, e); } } /************** batch stuff *******************/ /** * Sets the number of batched commands this Query allows to be added * before implicitly calling <code>executeBatch()</code> from <code>addToBatch()</code>. <br/> * * When set to 0, executeBatch is not called implicitly. This is the default behaviour. <br/> * * When using this, please take care about calling <code>exexcuteBatch()</code> after finished * adding all commands to the batch because commands may remain unexecuted after the * last <code>addToBatch()</code> call. * * @throws IllegalArgumentException Thrown if the value is negative. */ public Query setMaxBatchRecords(int maxBatchRecords){ if (maxBatchRecords < 0){ throw new IllegalArgumentException("maxBatchRecords should be a nonnegative value"); } this.maxBatchRecords = maxBatchRecords; return this; } public int getMaxBatchRecords(){ return this.maxBatchRecords; } /** * @return The current number of unexecuted batched statements */ public int getCurrentBatchRecords() { return this.currentBatchRecords; } /** * @return True if maxBatchRecords is set and there are unexecuted batched commands or * maxBatchRecords is not set */ public boolean isExplicitExecuteBatchRequired(){ return (this.maxBatchRecords > 0 && this.currentBatchRecords > 0) || (this.maxBatchRecords == 0); } /** * Adds a set of parameters to this <code>Query</code> * object's batch of commands. <br/> * * If maxBatchRecords is more than 0, executeBatch is called upon adding that manny * commands to the batch. <br/> * * The current number of batched commands is accessible via the <code>getCurrentBatchRecords()</code> * method. * * @return */ public Query addToBatch(){ try { statement.addBatch(); if (this.maxBatchRecords > 0){ if(++this.currentBatchRecords % this.maxBatchRecords == 0) { this.executeBatch(); } } } catch (SQLException e) { throw new Sql2oException("Error while adding statement to batch", e); } return this; } public Connection executeBatch() throws Sql2oException { long start = System.currentTimeMillis(); try { logExecution(); connection.setBatchResult(statement.executeBatch()); this.currentBatchRecords = 0; try { connection.setKeys(this.returnGeneratedKeys ? statement.getGeneratedKeys() : null); connection.setCanGetKeys(this.returnGeneratedKeys); } catch (SQLException sqlex) { throw new Sql2oException("Error while trying to fetch generated keys from database. If you are not expecting any generated keys, fix this error by setting the fetchGeneratedKeys parameter in the createQuery() method to 'false'", sqlex); } } catch (Throwable e) { this.connection.onException(); throw new Sql2oException("Error while executing batch operation: " + e.getMessage(), e); } finally { closeConnectionIfNecessary(); } long end = System.currentTimeMillis(); logger.debug("total: {} ms; executed batch [{}]", new Object[]{ end - start, this.getName() == null ? "No name" : this.getName() }); return this.connection; } /*********** column mapping ****************/ public Map<String, String> getColumnMappings() { if (this.isCaseSensitive()){ return this.caseSensitiveColumnMappings; } else{ return this.columnMappings; } } public Query setColumnMappings(Map<String, String> mappings){ this.caseSensitiveColumnMappings = new HashMap<>(); this.columnMappings = new HashMap<>(); for (Map.Entry<String,String> entry : mappings.entrySet()){ this.caseSensitiveColumnMappings.put(entry.getKey(), entry.getValue()); this.columnMappings.put(entry.getKey().toLowerCase(), entry.getValue().toLowerCase()); } return this; } public Query addColumnMapping(String columnName, String propertyName){ this.caseSensitiveColumnMappings.put(columnName, propertyName); this.columnMappings.put(columnName.toLowerCase(), propertyName.toLowerCase()); return this; } /************** private stuff ***************/ private void closeConnectionIfNecessary(){ try{ if (connection.autoClose){ connection.close(); } } catch (Exception ex){ throw new Sql2oException("Error while attempting to close connection", ex); } } private interface ParameterSetter{ void setParameter(int paramIdx) throws SQLException; } private void logExecution() { logger.debug("Executing query:{}{}", new Object[]{ System.lineSeparator(), this.parsedQuery } ); } }
mugizico/sql2o
core/src/main/java/org/sql2o/Query.java
Java
mit
29,709
// Copyright (c) 2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_VERSION_H #define BITCOIN_VERSION_H #include "clientversion.h" #include <string> // // client versioning // static const int CLIENT_VERSION = 1000000 * CLIENT_VERSION_MAJOR + 10000 * CLIENT_VERSION_MINOR + 100 * CLIENT_VERSION_REVISION + 1 * CLIENT_VERSION_BUILD; extern const std::string CLIENT_NAME; extern const std::string CLIENT_BUILD; extern const std::string CLIENT_DATE; // // network protocol versioning // static const int PROTOCOL_VERSION = 3000000; // intial proto version, to be increased after version/verack negotiation static const int INIT_PROTO_VERSION = 209; // disconnect from peers older than this proto version static const int MIN_PEER_PROTO_VERSION = 60001; // nTime field added to CAddress, starting with this version; // if possible, avoid requesting addresses nodes older than this static const int CADDR_TIME_VERSION = 31402; // only request blocks from nodes outside this range of versions static const int NOBLKS_VERSION_START = 50000; static const int NOBLKS_VERSION_END = 50002; // BIP 0031, pong message, is enabled for all versions AFTER this one static const int BIP0031_VERSION = 60000; // "mempool" command, enhanced "getdata" behavior starts with this version: static const int MEMPOOL_GD_VERSION = 60002; #endif
greencoin-dev/digitalcoin
src/version.h
C
mit
1,583
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { SchematicTestRunner, UnitTestTree } from '@angular-devkit/schematics/testing'; import { Schema as ApplicationOptions } from '../application/schema'; import { Schema as WorkspaceOptions } from '../workspace/schema'; import { Schema as ServiceWorkerOptions } from './schema'; describe('Service Worker Schematic', () => { const schematicRunner = new SchematicTestRunner( '@schematics/angular', require.resolve('../collection.json'), ); const defaultOptions: ServiceWorkerOptions = { project: 'bar', target: 'build', }; let appTree: UnitTestTree; const workspaceOptions: WorkspaceOptions = { name: 'workspace', newProjectRoot: 'projects', version: '6.0.0', }; const appOptions: ApplicationOptions = { name: 'bar', inlineStyle: false, inlineTemplate: false, routing: false, skipTests: false, skipPackageJson: false, }; beforeEach(async () => { appTree = await schematicRunner.runSchematicAsync('workspace', workspaceOptions).toPromise(); appTree = await schematicRunner .runSchematicAsync('application', appOptions, appTree) .toPromise(); }); it('should add `serviceWorker` option to build target', async () => { const tree = await schematicRunner .runSchematicAsync('service-worker', defaultOptions, appTree) .toPromise(); const configText = tree.readContent('/angular.json'); const buildConfig = JSON.parse(configText).projects.bar.architect.build; expect(buildConfig.options.serviceWorker).toBeTrue(); }); it('should add the necessary dependency', async () => { const tree = await schematicRunner .runSchematicAsync('service-worker', defaultOptions, appTree) .toPromise(); const pkgText = tree.readContent('/package.json'); const pkg = JSON.parse(pkgText); const version = pkg.dependencies['@angular/core']; expect(pkg.dependencies['@angular/service-worker']).toEqual(version); }); it('should import ServiceWorkerModule', async () => { const tree = await schematicRunner .runSchematicAsync('service-worker', defaultOptions, appTree) .toPromise(); const pkgText = tree.readContent('/projects/bar/src/app/app.module.ts'); expect(pkgText).toMatch(/import \{ ServiceWorkerModule \} from '@angular\/service-worker'/); }); it('should import environment', async () => { const tree = await schematicRunner .runSchematicAsync('service-worker', defaultOptions, appTree) .toPromise(); const pkgText = tree.readContent('/projects/bar/src/app/app.module.ts'); expect(pkgText).toMatch(/import \{ environment \} from '\.\.\/environments\/environment'/); }); it('should add the SW import to the NgModule imports', async () => { const tree = await schematicRunner .runSchematicAsync('service-worker', defaultOptions, appTree) .toPromise(); const pkgText = tree.readContent('/projects/bar/src/app/app.module.ts'); expect(pkgText).toMatch( new RegExp( "(\\s+)ServiceWorkerModule\\.register\\('ngsw-worker\\.js', \\{\\n" + '\\1 enabled: environment\\.production,\\n' + '\\1 // Register the ServiceWorker as soon as the app is stable\\n' + '\\1 // or after 30 seconds \\(whichever comes first\\)\\.\\n' + "\\1 registrationStrategy: 'registerWhenStable:30000'\\n" + '\\1}\\)', ), ); }); it('should add the SW import to the NgModule imports with aliased environment', async () => { const moduleContent = ` import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { environment as env } from '../environments/environment'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule ], bootstrap: [AppComponent] }) export class AppModule {} `; appTree.overwrite('/projects/bar/src/app/app.module.ts', moduleContent); const tree = await schematicRunner .runSchematicAsync('service-worker', defaultOptions, appTree) .toPromise(); const pkgText = tree.readContent('/projects/bar/src/app/app.module.ts'); expect(pkgText).toMatch( new RegExp( "(\\s+)ServiceWorkerModule\\.register\\('ngsw-worker\\.js', \\{\\n" + '\\1 enabled: env\\.production,\\n' + '\\1 // Register the ServiceWorker as soon as the app is stable\\n' + '\\1 // or after 30 seconds \\(whichever comes first\\)\\.\\n' + "\\1 registrationStrategy: 'registerWhenStable:30000'\\n" + '\\1}\\)', ), ); }); it('should add the SW import to the NgModule imports with existing environment', async () => { const moduleContent = ` import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { environment } from '../environments/environment'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule ], bootstrap: [AppComponent] }) export class AppModule {} `; appTree.overwrite('/projects/bar/src/app/app.module.ts', moduleContent); const tree = await schematicRunner .runSchematicAsync('service-worker', defaultOptions, appTree) .toPromise(); const pkgText = tree.readContent('/projects/bar/src/app/app.module.ts'); expect(pkgText).toMatch( new RegExp( "(\\s+)ServiceWorkerModule\\.register\\('ngsw-worker\\.js', \\{\\n" + '\\1 enabled: environment\\.production,\\n' + '\\1 // Register the ServiceWorker as soon as the app is stable\\n' + '\\1 // or after 30 seconds \\(whichever comes first\\)\\.\\n' + "\\1 registrationStrategy: 'registerWhenStable:30000'\\n" + '\\1}\\)', ), ); }); it('should put the ngsw-config.json file in the project root', async () => { const tree = await schematicRunner .runSchematicAsync('service-worker', defaultOptions, appTree) .toPromise(); const path = '/projects/bar/ngsw-config.json'; expect(tree.exists(path)).toEqual(true); const { projects } = JSON.parse(tree.readContent('/angular.json')); expect(projects.bar.architect.build.options.ngswConfigPath).toBe( 'projects/bar/ngsw-config.json', ); }); it('should add $schema in ngsw-config.json with correct relative path', async () => { const pathToNgswConfigSchema = 'node_modules/@angular/service-worker/config/schema.json'; const name = 'foo'; const rootAppOptions: ApplicationOptions = { ...appOptions, name, projectRoot: '', }; const rootSWOptions: ServiceWorkerOptions = { ...defaultOptions, project: name, }; const rootAppTree = await schematicRunner .runSchematicAsync('application', rootAppOptions, appTree) .toPromise(); const treeInRoot = await schematicRunner .runSchematicAsync('service-worker', rootSWOptions, rootAppTree) .toPromise(); const pkgTextInRoot = treeInRoot.readContent('/ngsw-config.json'); const configInRoot = JSON.parse(pkgTextInRoot); expect(configInRoot.$schema).toBe(`./${pathToNgswConfigSchema}`); const treeNotInRoot = await schematicRunner .runSchematicAsync('service-worker', defaultOptions, appTree) .toPromise(); const pkgTextNotInRoot = treeNotInRoot.readContent('/projects/bar/ngsw-config.json'); const configNotInRoot = JSON.parse(pkgTextNotInRoot); expect(configNotInRoot.$schema).toBe(`../../${pathToNgswConfigSchema}`); }); it('should add root assets RegExp', async () => { const tree = await schematicRunner .runSchematicAsync('service-worker', defaultOptions, appTree) .toPromise(); const pkgText = tree.readContent('/projects/bar/ngsw-config.json'); const config = JSON.parse(pkgText); expect(config.assetGroups[1].resources.files).toContain( '/*.(svg|cur|jpg|jpeg|png|apng|webp|avif|gif|otf|ttf|woff|woff2)', ); }); it('should add resourcesOutputPath to root assets when specified', async () => { const config = JSON.parse(appTree.readContent('/angular.json')); config.projects.bar.architect.build.options.resourcesOutputPath = 'outDir'; appTree.overwrite('/angular.json', JSON.stringify(config)); const tree = await schematicRunner .runSchematicAsync('service-worker', defaultOptions, appTree) .toPromise(); const pkgText = tree.readContent('/projects/bar/ngsw-config.json'); const ngswConfig = JSON.parse(pkgText); expect(ngswConfig.assetGroups[1].resources.files).toContain( '/outDir/*.(svg|cur|jpg|jpeg|png|apng|webp|avif|gif|otf|ttf|woff|woff2)', ); }); it('should generate ngsw-config.json in root when the application is at root level', async () => { const name = 'foo'; const rootAppOptions: ApplicationOptions = { ...appOptions, name, projectRoot: '', }; const rootSWOptions: ServiceWorkerOptions = { ...defaultOptions, project: name, }; let tree = await schematicRunner .runSchematicAsync('application', rootAppOptions, appTree) .toPromise(); tree = await schematicRunner .runSchematicAsync('service-worker', rootSWOptions, tree) .toPromise(); expect(tree.exists('/ngsw-config.json')).toBe(true); const { projects } = JSON.parse(tree.readContent('/angular.json')); expect(projects.foo.architect.build.options.ngswConfigPath).toBe('ngsw-config.json'); }); });
clydin/angular-cli
packages/schematics/angular/service-worker/index_spec.ts
TypeScript
mit
9,921
/* * Copyright (c) 2011-2015 ARM Limited. All rights reserved. * SPDX-License-Identifier: Apache-2.0 * 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. */ #ifndef GRS_H_ #define GRS_H_ #ifdef __cplusplus extern "C" { #endif #define SN_GRS_RESOURCE_ALREADY_EXISTS -2 #define SN_GRS_INVALID_PATH -3 #define SN_GRS_LIST_ADDING_FAILURE -4 #define SN_GRS_RESOURCE_UPDATED -5 #define ACCESS_DENIED -6 #define SN_GRS_DELETE_METHOD 0 #define SN_GRS_SEARCH_METHOD 1 #define SN_GRS_DEFAULT_ACCESS 0x0F #define SN_NDSL_RESOURCE_NOT_REGISTERED 0 #define SN_NDSL_RESOURCE_REGISTERING 1 #define SN_NDSL_RESOURCE_REGISTERED 2 /***** Structs *****/ typedef struct sn_grs_version_ { uint8_t major_version; uint8_t minor_version; uint8_t build; } sn_grs_version_s; typedef NS_LIST_HEAD(sn_nsdl_resource_info_s, link) resource_list_t; struct grs_s { struct coap_s *coap; void *(*sn_grs_alloc)(uint16_t); void (*sn_grs_free)(void *); uint8_t (*sn_grs_tx_callback)(struct nsdl_s *, sn_nsdl_capab_e , uint8_t *, uint16_t, sn_nsdl_addr_s *); int8_t (*sn_grs_rx_callback)(struct nsdl_s *, sn_coap_hdr_s *, sn_nsdl_addr_s *); uint16_t resource_root_count; resource_list_t resource_root_list; }; struct nsdl_s { uint16_t update_register_msg_id; uint16_t register_msg_len; uint16_t update_register_msg_len; uint16_t register_msg_id; uint16_t unregister_msg_id; uint16_t bootstrap_msg_id; uint16_t oma_bs_port; /* Bootstrap port */ uint8_t oma_bs_address_len; /* Bootstrap address length */ unsigned int sn_nsdl_endpoint_registered:1; bool handle_bootstrap_msg:1; struct grs_s *grs; uint8_t *oma_bs_address_ptr; /* Bootstrap address pointer. If null, no bootstrap in use */ sn_nsdl_ep_parameters_s *ep_information_ptr; // Endpoint parameters, Name, Domain etc.. sn_nsdl_oma_server_info_t *nsp_address_ptr; // NSP server address information void (*sn_nsdl_oma_bs_done_cb)(sn_nsdl_oma_server_info_t *server_info_ptr); /* Callback to inform application when bootstrap is done */ void *(*sn_nsdl_alloc)(uint16_t); void (*sn_nsdl_free)(void *); uint8_t (*sn_nsdl_tx_callback)(struct nsdl_s *, sn_nsdl_capab_e , uint8_t *, uint16_t, sn_nsdl_addr_s *); uint8_t (*sn_nsdl_rx_callback)(struct nsdl_s *, sn_coap_hdr_s *, sn_nsdl_addr_s *); void (*sn_nsdl_oma_bs_done_cb_handle)(sn_nsdl_oma_server_info_t *server_info_ptr, struct nsdl_s *handle); /* Callback to inform application when bootstrap is done with nsdl handle */ }; /***** Function prototypes *****/ /** * \fn extern grs_s *sn_grs_init (uint8_t (*sn_grs_tx_callback_ptr)(sn_nsdl_capab_e , uint8_t *, uint16_t, * sn_nsdl_addr_s *), uint8_t (*sn_grs_rx_callback_ptr)(sn_coap_hdr_s *, sn_nsdl_addr_s *), * sn_grs_mem_s *sn_memory) * * \brief GRS library initialize function. * * This function initializes GRS and CoAP. * * \param sn_grs_tx_callback A function pointer to a transmit callback function. Should return 1 when succeed, 0 when failed * \param *sn_grs_rx_callback_ptr A function pointer to a receiving callback function. If received packet is not for GRS, it will be passed to * upper level (NSDL) to be proceed. * \param sn_memory A pointer to a structure containing the platform specific functions for memory allocation and free. * * \return success pointer to handle, failure = NULL * */ extern struct grs_s *sn_grs_init(uint8_t (*sn_grs_tx_callback_ptr)(struct nsdl_s *, sn_nsdl_capab_e , uint8_t *, uint16_t, sn_nsdl_addr_s *), int8_t (*sn_grs_rx_callback_ptr)(struct nsdl_s *, sn_coap_hdr_s *, sn_nsdl_addr_s *), void *(*sn_grs_alloc)(uint16_t), void (*sn_grs_free)(void *)); extern const sn_nsdl_resource_info_s *sn_grs_get_first_resource(struct grs_s *handle); extern const sn_nsdl_resource_info_s *sn_grs_get_next_resource(struct grs_s *handle, const sn_nsdl_resource_info_s *sn_grs_current_resource); extern int8_t sn_grs_process_coap(struct nsdl_s *handle, sn_coap_hdr_s *coap_packet_ptr, sn_nsdl_addr_s *src); extern sn_nsdl_resource_info_s *sn_grs_search_resource(struct grs_s *handle, uint16_t pathlen, uint8_t *path, uint8_t search_method); extern int8_t sn_grs_destroy(struct grs_s *handle); extern sn_grs_resource_list_s *sn_grs_list_resource(struct grs_s *handle, uint16_t pathlen, uint8_t *path); extern void sn_grs_free_resource_list(struct grs_s *handle, sn_grs_resource_list_s *list); extern int8_t sn_grs_update_resource(struct grs_s *handle, sn_nsdl_resource_info_s *res); extern int8_t sn_grs_send_coap_message(struct nsdl_s *handle, sn_nsdl_addr_s *address_ptr, sn_coap_hdr_s *coap_hdr_ptr); extern int8_t sn_grs_create_resource(struct grs_s *handle, sn_nsdl_resource_info_s *res); extern int8_t sn_grs_put_resource(struct grs_s *handle, sn_nsdl_resource_info_s *res); extern int8_t sn_grs_delete_resource(struct grs_s *handle, uint16_t pathlen, uint8_t *path); extern void sn_grs_mark_resources_as_registered(struct nsdl_s *handle); #ifdef __cplusplus } #endif #endif /* GRS_H_ */
donkeybonks/ts16-accumulator
firmware/ts16-bms-master/mbed-os/features/FEATURE_COMMON_PAL/mbed-client-c/source/libNsdl/src/include/sn_grs.h
C
mit
6,225
input { padding: 10px; font-size: 18px; }
gilbox/elegant-react-og
examples/phone-input/app.css
CSS
mit
46
require "rbconfig" require 'test/unit' require 'puma/cli' require 'tempfile' class TestCLI < Test::Unit::TestCase def setup @environment = 'production' @tmp_file = Tempfile.new("puma-test") @tmp_path = @tmp_file.path @tmp_file.close! @tmp_path2 = "#{@tmp_path}2" File.unlink @tmp_path if File.exist? @tmp_path File.unlink @tmp_path2 if File.exist? @tmp_path2 end def teardown File.unlink @tmp_path if File.exist? @tmp_path File.unlink @tmp_path2 if File.exist? @tmp_path2 end def test_pid_file cli = Puma::CLI.new ["--pidfile", @tmp_path] cli.parse_options cli.write_pid assert_equal File.read(@tmp_path).strip.to_i, Process.pid cli.stop assert !File.exist?(@tmp_path), "Pid file shouldn't exist anymore" end def test_control_for_tcp url = "tcp://127.0.0.1:9877/" sin = StringIO.new sout = StringIO.new cli = Puma::CLI.new ["-b", "tcp://127.0.0.1:9876", "--control", url, "--control-token", "", "test/lobster.ru"], sin, sout cli.parse_options thread_exception = nil t = Thread.new do begin cli.run rescue Exception => e thread_exception = e end end sleep 1 s = TCPSocket.new "127.0.0.1", 9877 s << "GET /stats HTTP/1.0\r\n\r\n" body = s.read assert_equal '{ "backlog": 0, "running": 0 }', body.split("\r\n").last cli.stop t.join assert_equal nil, thread_exception end unless defined?(JRUBY_VERSION) || RbConfig::CONFIG["host_os"] =~ /mingw|mswin/ def test_control url = "unix://#{@tmp_path}" sin = StringIO.new sout = StringIO.new cli = Puma::CLI.new ["-b", "unix://#{@tmp_path2}", "--control", url, "--control-token", "", "test/lobster.ru"], sin, sout cli.parse_options t = Thread.new { cli.run } sleep 1 s = UNIXSocket.new @tmp_path s << "GET /stats HTTP/1.0\r\n\r\n" body = s.read assert_equal '{ "backlog": 0, "running": 0 }', body.split("\r\n").last cli.stop t.join end def test_control_stop url = "unix://#{@tmp_path}" sin = StringIO.new sout = StringIO.new cli = Puma::CLI.new ["-b", "unix://#{@tmp_path2}", "--control", url, "--control-token", "", "test/lobster.ru"], sin, sout cli.parse_options t = Thread.new { cli.run } sleep 1 s = UNIXSocket.new @tmp_path s << "GET /stop HTTP/1.0\r\n\r\n" body = s.read assert_equal '{ "status": "ok" }', body.split("\r\n").last t.join end def test_tmp_control url = "tcp://127.0.0.1:8232" cli = Puma::CLI.new ["--state", @tmp_path, "--control", "auto"] cli.parse_options cli.write_state data = YAML.load File.read(@tmp_path) assert_equal Process.pid, data["pid"] url = data["config"].options[:control_url] m = %r!unix://(.*)!.match(url) assert m, "'#{url}' is not a URL" end end # JRUBY or Windows def test_state url = "tcp://127.0.0.1:8232" cli = Puma::CLI.new ["--state", @tmp_path, "--control", url] cli.parse_options cli.write_state data = YAML.load File.read(@tmp_path) assert_equal Process.pid, data["pid"] assert_equal url, data["config"].options[:control_url] end def test_load_path cli = Puma::CLI.new ["--include", 'foo/bar'] cli.parse_options assert_equal 'foo/bar', $LOAD_PATH[0] $LOAD_PATH.shift cli = Puma::CLI.new ["--include", 'foo/bar:baz/qux'] cli.parse_options assert_equal 'foo/bar', $LOAD_PATH[0] $LOAD_PATH.shift assert_equal 'baz/qux', $LOAD_PATH[0] $LOAD_PATH.shift end def test_environment cli = Puma::CLI.new ["--environment", @environment] cli.parse_options cli.set_rack_environment assert_equal ENV['RACK_ENV'], @environment end end
vickeeyz/passty
vendor/bundle/ruby/2.0.0/gems/puma-2.0.1/test/test_cli.rb
Ruby
mit
4,000
# Changelog ## 0.4.5 (2016-03-27) This is a compatibility release that backports some changes from the v0.5 release branch. You should consider upgrading to the v0.5 release. * Fix: PHP 5.6+ uses new SSL/TLS context options backported (#65 by @clue) * Fix: Move SSL/TLS context options to SecureConnector (#43 by @clue) ## 0.4.4 (2015-09-23) * Feature: Add support for Unix domain sockets (UDS) (#41 by @clue) * Bugfix: Explicitly set supported TLS versions for PHP 5.6+ (#31 by @WyriHaximus) * Bugfix: Ignore SSL non-draining buffer workaround for PHP 5.6.8+ (#33 by @alexmace) ## 0.4.3 (2015-03-20) * Bugfix: Set peer name to hostname to correct security concern in PHP 5.6 (@WyriHaximus) * Bugfix: Always wrap secure to pull buffer due to regression in PHP * Bugfix: SecureStream extends Stream to match documentation preventing BC (@clue) ## 0.4.2 (2014-10-16) * Bugfix: Only toggle the stream crypto handshake once (@DaveRandom and @rdlowrey) * Bugfix: Workaround for ext-openssl buffering bug (@DaveRandom) * Bugfix: SNI fix for PHP < 5.6 (@DaveRandom) ## 0.4.(0/1) (2014-02-02) * BC break: Bump minimum PHP version to PHP 5.4, remove 5.3 specific hacks * BC break: Update to React/Promise 2.0 * Dependency: Autoloading and filesystem structure now PSR-4 instead of PSR-0 * Bump React dependencies to v0.4 ## 0.3.1 (2013-04-21) * Feature: [SocketClient] Support connecting to IPv6 addresses (@clue) ## 0.3.0 (2013-04-14) * Feature: [SocketClient] New SocketClient component extracted from HttpClient (@clue)
AndreiMariusSili/EnactusMVC
vendor/react/socket-client/CHANGELOG.md
Markdown
mit
1,529
#include "rpcconsole.h" #include "ui_rpcconsole.h" #include "clientmodel.h" #include "bitcoinrpc.h" #include "guiutil.h" #include <QTime> #include <QTimer> #include <QThread> #include <QTextEdit> #include <QKeyEvent> #include <QUrl> #include <QScrollBar> #include <openssl/crypto.h> // TODO: make it possible to filter out categories (esp debug messages when implemented) // TODO: receive errors and debug messages through ClientModel const int CONSOLE_SCROLLBACK = 50; const int CONSOLE_HISTORY = 50; const QSize ICON_SIZE(24, 24); const struct { const char *url; const char *source; } ICON_MAPPING[] = { {"cmd-request", ":/icons/tx_input"}, {"cmd-reply", ":/icons/tx_output"}, {"cmd-error", ":/icons/tx_output"}, {"misc", ":/icons/tx_inout"}, {NULL, NULL} }; /* Object for executing console RPC commands in a separate thread. */ class RPCExecutor: public QObject { Q_OBJECT public slots: void start(); void request(const QString &command); signals: void reply(int category, const QString &command); }; #include "rpcconsole.moc" void RPCExecutor::start() { // Nothing to do } /** * Split shell command line into a list of arguments. Aims to emulate \c bash and friends. * * - Arguments are delimited with whitespace * - Extra whitespace at the beginning and end and between arguments will be ignored * - Text can be "double" or 'single' quoted * - The backslash \c \ is used as escape character * - Outside quotes, any character can be escaped * - Within double quotes, only escape \c " and backslashes before a \c " or another backslash * - Within single quotes, no escaping is possible and no special interpretation takes place * * @param[out] args Parsed arguments will be appended to this list * @param[in] strCommand Command line to split */ bool parseCommandLine(std::vector<std::string> &args, const std::string &strCommand) { enum CmdParseState { STATE_EATING_SPACES, STATE_ARGUMENT, STATE_SINGLEQUOTED, STATE_DOUBLEQUOTED, STATE_ESCAPE_OUTER, STATE_ESCAPE_DOUBLEQUOTED } state = STATE_EATING_SPACES; std::string curarg; foreach(char ch, strCommand) { switch(state) { case STATE_ARGUMENT: // In or after argument case STATE_EATING_SPACES: // Handle runs of whitespace switch(ch) { case '"': state = STATE_DOUBLEQUOTED; break; case '\'': state = STATE_SINGLEQUOTED; break; case '\\': state = STATE_ESCAPE_OUTER; break; case ' ': case '\n': case '\t': if(state == STATE_ARGUMENT) // Space ends argument { args.push_back(curarg); curarg.clear(); } state = STATE_EATING_SPACES; break; default: curarg += ch; state = STATE_ARGUMENT; } break; case STATE_SINGLEQUOTED: // Single-quoted string switch(ch) { case '\'': state = STATE_ARGUMENT; break; default: curarg += ch; } break; case STATE_DOUBLEQUOTED: // Double-quoted string switch(ch) { case '"': state = STATE_ARGUMENT; break; case '\\': state = STATE_ESCAPE_DOUBLEQUOTED; break; default: curarg += ch; } break; case STATE_ESCAPE_OUTER: // '\' outside quotes curarg += ch; state = STATE_ARGUMENT; break; case STATE_ESCAPE_DOUBLEQUOTED: // '\' in double-quoted text if(ch != '"' && ch != '\\') curarg += '\\'; // keep '\' for everything but the quote and '\' itself curarg += ch; state = STATE_DOUBLEQUOTED; break; } } switch(state) // final state { case STATE_EATING_SPACES: return true; case STATE_ARGUMENT: args.push_back(curarg); return true; default: // ERROR to end in one of the other states return false; } } void RPCExecutor::request(const QString &command) { std::vector<std::string> args; if(!parseCommandLine(args, command.toStdString())) { emit reply(RPCConsole::CMD_ERROR, QString("Parse error: unbalanced ' or \"")); return; } if(args.empty()) return; // Nothing to do try { std::string strPrint; // Convert argument list to JSON objects in method-dependent way, // and pass it along with the method name to the dispatcher. json_spirit::Value result = tableRPC.execute( args[0], RPCConvertValues(args[0], std::vector<std::string>(args.begin() + 1, args.end()))); // Format result reply if (result.type() == json_spirit::null_type) strPrint = ""; else if (result.type() == json_spirit::str_type) strPrint = result.get_str(); else strPrint = write_string(result, true); emit reply(RPCConsole::CMD_REPLY, QString::fromStdString(strPrint)); } catch (json_spirit::Object& objError) { try // Nice formatting for standard-format error { int code = find_value(objError, "code").get_int(); std::string message = find_value(objError, "message").get_str(); emit reply(RPCConsole::CMD_ERROR, QString::fromStdString(message) + " (code " + QString::number(code) + ")"); } catch(std::runtime_error &) // raised when converting to invalid type, i.e. missing code or message { // Show raw JSON object emit reply(RPCConsole::CMD_ERROR, QString::fromStdString(write_string(json_spirit::Value(objError), false))); } } catch (std::exception& e) { emit reply(RPCConsole::CMD_ERROR, QString("Error: ") + QString::fromStdString(e.what())); } } RPCConsole::RPCConsole(QWidget *parent) : QDialog(parent), ui(new Ui::RPCConsole), historyPtr(0) { ui->setupUi(this); #ifndef Q_OS_MAC ui->openDebugLogfileButton->setIcon(QIcon(":/icons/export")); ui->showCLOptionsButton->setIcon(QIcon(":/icons/options")); #endif // Install event filter for up and down arrow ui->lineEdit->installEventFilter(this); ui->messagesWidget->installEventFilter(this); connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear())); // set OpenSSL version label ui->openSSLVersion->setText(SSLeay_version(SSLEAY_VERSION)); startExecutor(); clear(); } RPCConsole::~RPCConsole() { emit stopExecutor(); delete ui; } bool RPCConsole::eventFilter(QObject* obj, QEvent *event) { if(event->type() == QEvent::KeyPress) // Special key handling { QKeyEvent *keyevt = static_cast<QKeyEvent*>(event); int key = keyevt->key(); Qt::KeyboardModifiers mod = keyevt->modifiers(); switch(key) { case Qt::Key_Up: if(obj == ui->lineEdit) { browseHistory(-1); return true; } break; case Qt::Key_Down: if(obj == ui->lineEdit) { browseHistory(1); return true; } break; case Qt::Key_PageUp: /* pass paging keys to messages widget */ case Qt::Key_PageDown: if(obj == ui->lineEdit) { QApplication::postEvent(ui->messagesWidget, new QKeyEvent(*keyevt)); return true; } break; default: // Typing in messages widget brings focus to line edit, and redirects key there // Exclude most combinations and keys that emit no text, except paste shortcuts if(obj == ui->messagesWidget && ( (!mod && !keyevt->text().isEmpty() && key != Qt::Key_Tab) || ((mod & Qt::ControlModifier) && key == Qt::Key_V) || ((mod & Qt::ShiftModifier) && key == Qt::Key_Insert))) { ui->lineEdit->setFocus(); QApplication::postEvent(ui->lineEdit, new QKeyEvent(*keyevt)); return true; } } } return QDialog::eventFilter(obj, event); } void RPCConsole::setClientModel(ClientModel *model) { this->clientModel = model; if(model) { // Subscribe to information, replies, messages, errors connect(model, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int))); connect(model, SIGNAL(numBlocksChanged(int,int)), this, SLOT(setNumBlocks(int,int))); // Provide initial values ui->clientVersion->setText(model->formatFullVersion()); ui->clientName->setText(model->clientName()); ui->buildDate->setText(model->formatBuildDate()); ui->startupTime->setText(model->formatClientStartupTime()); setNumConnections(model->getNumConnections()); ui->isTestNet->setChecked(model->isTestNet()); setNumBlocks(model->getNumBlocks(), model->getNumBlocksOfPeers()); } } static QString categoryClass(int category) { switch(category) { case RPCConsole::CMD_REQUEST: return "cmd-request"; break; case RPCConsole::CMD_REPLY: return "cmd-reply"; break; case RPCConsole::CMD_ERROR: return "cmd-error"; break; default: return "misc"; } } void RPCConsole::clear() { ui->messagesWidget->clear(); ui->lineEdit->clear(); ui->lineEdit->setFocus(); // Add smoothly scaled icon images. // (when using width/height on an img, Qt uses nearest instead of linear interpolation) for(int i=0; ICON_MAPPING[i].url; ++i) { ui->messagesWidget->document()->addResource( QTextDocument::ImageResource, QUrl(ICON_MAPPING[i].url), QImage(ICON_MAPPING[i].source).scaled(ICON_SIZE, Qt::IgnoreAspectRatio, Qt::SmoothTransformation)); } // Set default style sheet ui->messagesWidget->document()->setDefaultStyleSheet( "table { }" "td.time { color: #808080; padding-top: 3px; } " "td.message { font-family: Monospace; font-size: 12px; } " "td.cmd-request { color: #006060; } " "td.cmd-error { color: red; } " "b { color: #006060; } " ); message(CMD_REPLY, (tr("Welcome to the FairCoin RPC console.") + "<br>" + tr("Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.") + "<br>" + tr("Type <b>help</b> for an overview of available commands.")), true); } void RPCConsole::message(int category, const QString &message, bool html) { QTime time = QTime::currentTime(); QString timeString = time.toString(); QString out; out += "<table><tr><td class=\"time\" width=\"65\">" + timeString + "</td>"; out += "<td class=\"icon\" width=\"32\"><img src=\"" + categoryClass(category) + "\"></td>"; out += "<td class=\"message " + categoryClass(category) + "\" valign=\"middle\">"; if(html) out += message; else out += GUIUtil::HtmlEscape(message, true); out += "</td></tr></table>"; ui->messagesWidget->append(out); } void RPCConsole::setNumConnections(int count) { ui->numberOfConnections->setText(QString::number(count)); } void RPCConsole::setNumBlocks(int count, int countOfPeers) { ui->numberOfBlocks->setText(QString::number(count)); ui->totalBlocks->setText(QString::number(countOfPeers)); if(clientModel) { // If there is no current number available display N/A instead of 0, which can't ever be true ui->totalBlocks->setText(clientModel->getNumBlocksOfPeers() == 0 ? tr("N/A") : QString::number(clientModel->getNumBlocksOfPeers())); ui->lastBlockTime->setText(clientModel->getLastBlockDate().toString()); } } void RPCConsole::on_lineEdit_returnPressed() { QString cmd = ui->lineEdit->text(); ui->lineEdit->clear(); if(!cmd.isEmpty()) { message(CMD_REQUEST, cmd); emit cmdRequest(cmd); // Truncate history from current position history.erase(history.begin() + historyPtr, history.end()); // Append command to history history.append(cmd); // Enforce maximum history size while(history.size() > CONSOLE_HISTORY) history.removeFirst(); // Set pointer to end of history historyPtr = history.size(); // Scroll console view to end scrollToEnd(); } } void RPCConsole::browseHistory(int offset) { historyPtr += offset; if(historyPtr < 0) historyPtr = 0; if(historyPtr > history.size()) historyPtr = history.size(); QString cmd; if(historyPtr < history.size()) cmd = history.at(historyPtr); ui->lineEdit->setText(cmd); } void RPCConsole::startExecutor() { QThread* thread = new QThread; RPCExecutor *executor = new RPCExecutor(); executor->moveToThread(thread); // Notify executor when thread started (in executor thread) connect(thread, SIGNAL(started()), executor, SLOT(start())); // Replies from executor object must go to this object connect(executor, SIGNAL(reply(int,QString)), this, SLOT(message(int,QString))); // Requests from this object must go to executor connect(this, SIGNAL(cmdRequest(QString)), executor, SLOT(request(QString))); // On stopExecutor signal // - queue executor for deletion (in execution thread) // - quit the Qt event loop in the execution thread connect(this, SIGNAL(stopExecutor()), executor, SLOT(deleteLater())); connect(this, SIGNAL(stopExecutor()), thread, SLOT(quit())); // Queue the thread for deletion (in this thread) when it is finished connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); // Default implementation of QThread::run() simply spins up an event loop in the thread, // which is what we want. thread->start(); } void RPCConsole::on_tabWidget_currentChanged(int index) { if(ui->tabWidget->widget(index) == ui->tab_console) { ui->lineEdit->setFocus(); } } void RPCConsole::on_openDebugLogfileButton_clicked() { GUIUtil::openDebugLogfile(); } void RPCConsole::scrollToEnd() { QScrollBar *scrollbar = ui->messagesWidget->verticalScrollBar(); scrollbar->setValue(scrollbar->maximum()); } void RPCConsole::on_showCLOptionsButton_clicked() { GUIUtil::HelpMessageBox help; help.exec(); }
FairCoinTeam/fair-coin
src/qt/rpcconsole.cpp
C++
mit
14,507
/** * @file Scharr.cpp * @brief mex interface for Scharr * @author Kota Yamaguchi * @date 2011 */ #include "mexopencv.hpp" using namespace std; using namespace cv; /** * Main entry called from Matlab * @param nlhs number of left-hand-side arguments * @param plhs pointers to mxArrays in the left-hand-side * @param nrhs number of right-hand-side arguments * @param prhs pointers to mxArrays in the right-hand-side */ void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { // Check the number of arguments if (nrhs<1 || (nrhs%2)!=1 || nlhs>1) mexErrMsgIdAndTxt("mexopencv:error","Wrong number of arguments"); // Argument vector vector<MxArray> rhs(prhs,prhs+nrhs); // Option processing int ddepth=-1; int xorder=1; int yorder=0; double scale=1; double delta=0; int borderType=BORDER_DEFAULT; for (int i=1; i<nrhs; i+=2) { string key = rhs[i].toString(); if (key=="DDepth") ddepth = rhs[i+1].toInt(); else if (key=="XOrder") xorder = rhs[i+1].toInt(); else if (key=="YOrder") yorder = rhs[i+1].toInt(); else if (key=="Scale") scale = rhs[i+1].toDouble(); else if (key=="Delta") delta = rhs[i+1].toDouble(); else if (key=="BorderType") borderType = BorderType[rhs[i+1].toString()]; else mexErrMsgIdAndTxt("mexopencv:error","Unrecognized option"); } // Execute function Mat img(rhs[0].toMat()); Scharr(img, img, ddepth, xorder, yorder, scale, delta, borderType); plhs[0] = MxArray(img); }
Rachine/VisualPlaceRecognition
urban_release/lib/cv_kota/src/+cv/Scharr.cpp
C++
mit
1,676
const ButtonBackToTop = FocusComponents.common.button.backToTop.component; const ButtonBTSample = React.createClass({ /** * Render the component. * @return {object} React node */ render() { return ( <div className='button-bt-example'> <img src="http://lorempixel.com/800/600/sports/"/> <img src="http://lorempixel.com/800/600/abstract/"/> <img src="http://lorempixel.com/800/600/city/"/> <img src="http://lorempixel.com/800/600/technics/"/> <img src="http://lorempixel.com/800/600/sports/"/> <img src="http://lorempixel.com/800/600/abstract/"/> <img src="http://lorempixel.com/800/600/city/"/> <img src="http://lorempixel.com/800/600/technics/"/> <ButtonBackToTop /> </div> ); } }); return <ButtonBTSample/>;
Ephrame/focus-components
src/common/button/back-to-top/example/index.js
JavaScript
mit
919