max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
435
{ "copyright_text": "Creative Commons Attribution license (reuse allowed)", "description": "The cPython\u2019s startup speed generally quite fast compared to other\nsimilar dynamic language interpreters. Despite this, the interpreter\u2019s\nstartup time increases linearly with the number and size of imported\npython modules. Although interpreter startup speed isn\u2019t a significant\nconcern in long running servers, it does matter for the command line and\nother frequently launched applications.\n\nOne of the oldest tricks in the book, when it comes to performance\noptimizations is to perform frequent and expensive operations fewer\ntimes and reuse results from previous invocations. We noticed that the\noverhead of reading and un-marshalling .pyc files at startup can be\neliminated if we could directly embed code objects and their associated\nobject graph from .pyc files into the data segment of the cPython\nbinary. This technique is quite similar to the approach taken by image\nbased languages like Smalltalk in the past. Implementing this for\ncPython is made simpler because marshaled code objects in .pyc files\ncontain a subset of the types of objects that marshal format supports.\nWith this approach, loading a module included in the python binary is as\ncheap as dereferencing a pointer, albeit at the cost of increased binary\nsize.\n\nThis talk will discuss the approach taken to implement the\naforementioned idea for Python 3.6 and the challenges faced in\nimplementing it. It will also talk about benchmark results from the\nimprovements and possible future directions for this work. Although this\ntalk delves into cPython internals, no prior experience with cPython\ninternals is required to follow along.\n", "duration": 1675, "language": "eng", "recorded": "2018-07-27", "related_urls": [ { "label": "Conference schedule", "url": "https://ep2018.europython.eu/p3/schedule/ep2018/" } ], "speakers": [ "<NAME>" ], "tags": [], "thumbnail_url": "https://i.ytimg.com/vi/KRqv2Bm1J18/maxresdefault.jpg", "title": "Faster Python startup", "videos": [ { "type": "youtube", "url": "https://www.youtube.com/watch?v=KRqv2Bm1J18" } ] }
628
3,494
#include "cinder/app/App.h" #include "cinder/app/RendererGl.h" #include "cinder/gl/gl.h" #include "cinder/Log.h" #include "cinder/osc/Osc.h" using namespace ci; using namespace ci::app; using namespace std; #define USE_UDP 1 #if USE_UDP using Sender = osc::SenderUdp; #else using Sender = osc::SenderTcp; #endif const std::string destinationHost = "127.0.0.1"; const uint16_t destinationPort = 10001; const uint16_t localPort = 10000; class SimpleSenderApp : public App { public: SimpleSenderApp(); void setup() override; void mouseDown( MouseEvent event ) override; void mouseDrag( MouseEvent event ) override; void mouseUp( MouseEvent event ) override; void mouseMove( MouseEvent event ) override; void draw() override; void onSendError( asio::error_code error ); ivec2 mCurrentMousePositon; Sender mSender; bool mIsConnected; }; SimpleSenderApp::SimpleSenderApp() : mSender( localPort, destinationHost, destinationPort ), mIsConnected( false ) { } void SimpleSenderApp::setup() { try { // Bind the sender to the endpoint. This function may throw. The exception will // contain asio::error_code information. mSender.bind(); } catch ( const osc::Exception &ex ) { CI_LOG_E( "Error binding: " << ex.what() << " val: " << ex.value() ); quit(); } #if ! USE_UDP mSender.connect( // Set up the OnConnectFn. If there's no error, you can consider yourself connected to // the endpoint supplied. [&]( asio::error_code error ){ if( error ) { CI_LOG_E( "Error connecting: " << error.message() << " val: " << error.value() ); quit(); } else { CI_LOG_V( "Connected" ); mIsConnected = true; } }); #else // Udp doesn't "connect" the same way Tcp does. If bind doesn't throw, we can // consider ourselves connected. mIsConnected = true; #endif } // Unified error handler. Easiest to have a bound function in this situation, // since we're sending from many different places. void SimpleSenderApp::onSendError( asio::error_code error ) { if( error ) { CI_LOG_E( "Error sending: " << error.message() << " val: " << error.value() ); // If you determine that this error is fatal, make sure to flip mIsConnected. It's // possible that the error isn't fatal. mIsConnected = false; try { #if ! USE_UDP // If this is Tcp, it's recommended that you shutdown before closing. This // function could throw. The exception will contain asio::error_code // information. mSender.shutdown(); #endif // Close the socket on exit. This function could throw. The exception will // contain asio::error_code information. mSender.close(); } catch( const osc::Exception &ex ) { CI_LOG_EXCEPTION( "Cleaning up socket: val -" << ex.value(), ex ); } quit(); } } void SimpleSenderApp::mouseMove( cinder::app::MouseEvent event ) { mCurrentMousePositon = event.getPos(); // Make sure you're connected before trying to send. if( ! mIsConnected ) return; osc::Message msg( "/mousemove/1" ); msg.append( mCurrentMousePositon.x ); msg.append( mCurrentMousePositon.y ); // Send the msg and also provide an error handler. If the message is important you // could store it in the error callback to dispatch it again if there was a problem. mSender.send( msg, std::bind( &SimpleSenderApp::onSendError, this, std::placeholders::_1 ) ); } void SimpleSenderApp::mouseDown( MouseEvent event ) { // Make sure you're connected before trying to send. if( ! mIsConnected ) return; osc::Message msg( "/mouseclick/1" ); msg.append( (float)event.getPos().x / getWindowWidth() ); msg.append( (float)event.getPos().y / getWindowHeight() ); // Send the msg and also provide an error handler. If the message is important you // could store it in the error callback to dispatch it again if there was a problem. mSender.send( msg, std::bind( &SimpleSenderApp::onSendError, this, std::placeholders::_1 ) ); } void SimpleSenderApp::mouseDrag( MouseEvent event ) { mouseMove( event ); } void SimpleSenderApp::mouseUp( MouseEvent event ) { // Make sure you're connected before trying to send. if( ! mIsConnected ) return; osc::Message msg( "/mouseclick/1" ); msg.append( (float)event.getPos().x / getWindowWidth() ); msg.append( (float)event.getPos().y / getWindowHeight() ); // Send the msg and also provide an error handler. If the message is important you // could store it in the error callback to dispatch it again if there was a problem. mSender.send( msg, std::bind( &SimpleSenderApp::onSendError, this, std::placeholders::_1 ) ); } void SimpleSenderApp::draw() { gl::clear( Color( 0, 0, 0 ) ); gl::setMatricesWindow( getWindowSize() ); gl::drawSolidCircle( mCurrentMousePositon, 100 ); } auto settingsFunc = []( App::Settings *settings ) { #if defined( CINDER_MSW ) settings->setConsoleWindowEnabled(); #endif settings->setMultiTouchEnabled( false ); }; CINDER_APP( SimpleSenderApp, RendererGl, settingsFunc )
1,708
5,169
{ "name": "ROBarcodeScanner", "version": "1.0.2", "summary": "Scans different Barcodes and returns the result as String", "description": "Scans different Barcodes and returns the result as String. Use the ROBarcodeScannerViewController for the View.", "homepage": "https://github.com/prine/ROBarcodeScanner", "screenshots": "https://raw.githubusercontent.com/prine/ROBarcodeScanner/master/Screenshot.png", "license": "MIT", "authors": { "<NAME>": "<EMAIL>" }, "source": { "git": "https://github.com/prine/ROBarcodeScanner.git", "tag": "1.0.2" }, "social_media_url": "https://twitter.com/prinedev", "platforms": { "ios": "8.0" }, "requires_arc": true, "source_files": "Source/**/*", "resource_bundles": { "ROBarcodeScanner": [ "Pod/Assets/*.png" ] }, "resources": [ "Source/*.Storyboard" ] }
340
1,266
// Copyright (c) 2020 The Bitcoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <eventloop.h> #include <scheduler.h> EventLoop::~EventLoop() { stopEventLoop(); } bool EventLoop::startEventLoop(CScheduler &scheduler, std::function<void()> runEventLoop, std::chrono::milliseconds delta) { LOCK(cs_running); if (running) { // Do not start the event loop twice. return false; } running = true; // Start the event loop. scheduler.scheduleEvery( [this, runEventLoop]() -> bool { runEventLoop(); if (!stopRequest) { return true; } LOCK(cs_running); running = false; cond_running.notify_all(); // A stop request was made. return false; }, delta); return true; } bool EventLoop::stopEventLoop() { WAIT_LOCK(cs_running, lock); if (!running) { return false; } // Request event loop to stop. stopRequest = true; // Wait for event loop to stop. cond_running.wait(lock, [this]() EXCLUSIVE_LOCKS_REQUIRED(cs_running) { return !running; }); stopRequest = false; return true; }
625
559
<filename>examples/proxy/src/main/java/com/netflix/msl/ProxyException.java /** * Copyright (c) 2015 Netflix, Inc. All rights reserved. */ package com.netflix.msl; /** * <p>Thrown by the proxy when an exception has occurred. This class is the * general class of exceptions produced by failed proxy operations.</p> * * @author <NAME> <<EMAIL>> */ public class ProxyException extends Exception { private static final long serialVersionUID = -2504349809538822945L; /** * <p>Creates a new {@code ProxyException} with the specified detail * message and cause.</p> * * @param message the detail message. * @param cause the cause. May be {@code null}. */ public ProxyException(final String message, final Throwable cause) { super(message, cause); } }
263
409
<reponame>NearlyTRex/object_threadsafe /* This file is a part of libcds - Concurrent Data Structures library (C) Copyright <NAME> (<EMAIL>) 2006-2016 Source code repo: http://github.com/khizmax/libcds/ Download: http://sourceforge.net/projects/libcds/files/ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef CDSUNIT_QUEUE_TEST_INTRUSIVE_SEGMENTED_QUEUE_H #define CDSUNIT_QUEUE_TEST_INTRUSIVE_SEGMENTED_QUEUE_H #include <cds_test/check_size.h> namespace cds_test { class intrusive_segmented_queue : public ::testing::Test { protected: struct item { int nValue; size_t nDisposeCount; size_t nDispose2Count; item() : nValue( 0 ) , nDisposeCount( 0 ) , nDispose2Count( 0 ) {} item( int nVal ) : nValue( nVal ) , nDisposeCount( 0 ) , nDispose2Count( 0 ) {} }; struct big_item : public item { big_item() {} big_item( int nVal ) : item( nVal ) {} int arr[80]; }; struct Disposer { void operator()( item * p ) { ++p->nDisposeCount; } }; struct Disposer2 { void operator()( item * p ) { ++p->nDispose2Count; } }; template <typename Queue, typename Data> void test( Queue& q, Data& val ) { typedef typename Queue::value_type value_type; val.resize( 100 ); for ( size_t i = 0; i < val.size(); ++i ) val[i].nValue = static_cast<int>( i ); ASSERT_TRUE( q.empty()); ASSERT_CONTAINER_SIZE( q, 0 ); // push/enqueue for ( size_t i = 0; i < val.size(); ++i ) { if ( i & 1 ) { ASSERT_TRUE( q.push( val[i] ) ); } else { ASSERT_TRUE( q.enqueue( val[i] ) ); } ASSERT_CONTAINER_SIZE( q, i + 1 ); } EXPECT_TRUE( !q.empty() ); // pop/dequeue size_t nCount = 0; while ( !q.empty() ) { value_type * pVal; if ( nCount & 1 ) pVal = q.pop(); else pVal = q.dequeue(); ASSERT_TRUE( pVal != nullptr ); int nSegment = int( nCount / q.quasi_factor() ); int nMin = nSegment * int( q.quasi_factor() ); int nMax = nMin + int( q.quasi_factor() ) - 1; EXPECT_TRUE( nMin <= pVal->nValue && pVal->nValue <= nMax ) << nMin << " <= " << pVal->nValue << " <= " << nMax; ++nCount; EXPECT_CONTAINER_SIZE( q, val.size() - nCount ); } EXPECT_EQ( nCount, val.size()); EXPECT_TRUE( q.empty() ); EXPECT_CONTAINER_SIZE( q, 0 ); // pop from empty queue ASSERT_TRUE( q.pop() == nullptr ); EXPECT_TRUE( q.empty() ); EXPECT_CONTAINER_SIZE( q, 0 ); // check that Disposer has not been called Queue::gc::force_dispose(); for ( size_t i = 0; i < val.size(); ++i ) { EXPECT_EQ( val[i].nDisposeCount, 0 ); EXPECT_EQ( val[i].nDispose2Count, 0 ); } // clear for ( size_t i = 0; i < val.size(); ++i ) EXPECT_TRUE( q.push( val[i] ) ); EXPECT_CONTAINER_SIZE( q, val.size()); EXPECT_TRUE( !q.empty() ); q.clear(); EXPECT_CONTAINER_SIZE( q, 0 ); EXPECT_TRUE( q.empty() ); // check if Disposer has been called Queue::gc::force_dispose(); for ( size_t i = 0; i < val.size(); ++i ) { EXPECT_EQ( val[i].nDisposeCount, 1 ); EXPECT_EQ( val[i].nDispose2Count, 0 ); } // clear_with for ( size_t i = 0; i < val.size(); ++i ) EXPECT_TRUE( q.push( val[i] ) ); EXPECT_CONTAINER_SIZE( q, val.size() ); EXPECT_TRUE( !q.empty() ); q.clear_with( Disposer2() ); EXPECT_CONTAINER_SIZE( q, 0 ); EXPECT_TRUE( q.empty() ); // check if Disposer has been called Queue::gc::force_dispose(); for ( size_t i = 0; i < val.size(); ++i ) { EXPECT_EQ( val[i].nDisposeCount, 1 ); EXPECT_EQ( val[i].nDispose2Count, 1 ); } // check clear on destruct for ( size_t i = 0; i < val.size(); ++i ) EXPECT_TRUE( q.push( val[i] )); EXPECT_CONTAINER_SIZE( q, val.size()); EXPECT_TRUE( !q.empty()); } }; } // namespace cds_test #endif // CDSUNIT_QUEUE_TEST_INTRUSIVE_SEGMENTED_QUEUE_H
3,338
2,151
<filename>data-binding/compiler/src/main/java/android/databinding/annotationprocessor/ProcessBindable.java /* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.databinding.annotationprocessor; import android.databinding.Bindable; import android.databinding.BindingBuildInfo; import android.databinding.tool.CompilerChef.BindableHolder; import android.databinding.tool.util.GenerationalClassUtil; import android.databinding.tool.util.L; import android.databinding.tool.util.Preconditions; import android.databinding.tool.writer.BRWriter; import android.databinding.tool.writer.JavaFileWriter; import java.io.Serializable; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.RoundEnvironment; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Name; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeKind; import javax.lang.model.util.Types; // binding app info and library info are necessary to trigger this. public class ProcessBindable extends ProcessDataBinding.ProcessingStep implements BindableHolder { Intermediate mProperties; HashMap<String, HashSet<String>> mLayoutVariables = new HashMap<String, HashSet<String>>(); @Override public boolean onHandleStep(RoundEnvironment roundEnv, ProcessingEnvironment processingEnv, BindingBuildInfo buildInfo) { if (mProperties == null) { mProperties = new IntermediateV1(buildInfo.modulePackage()); mergeLayoutVariables(); mLayoutVariables.clear(); TypeElement observableType = processingEnv.getElementUtils(). getTypeElement("android.databinding.Observable"); Types typeUtils = processingEnv.getTypeUtils(); for (Element element : AnnotationUtil .getElementsAnnotatedWith(roundEnv, Bindable.class)) { Element enclosingElement = element.getEnclosingElement(); ElementKind kind = enclosingElement.getKind(); if (kind != ElementKind.CLASS && kind != ElementKind.INTERFACE) { L.e("Bindable must be on a member field or method. The enclosing type is %s", enclosingElement.getKind()); } TypeElement enclosing = (TypeElement) enclosingElement; if (!typeUtils.isAssignable(enclosing.asType(), observableType.asType())) { L.e("Bindable must be on a member in an Observable class. %s is not Observable", enclosingElement.getSimpleName()); } String name = getPropertyName(element); if (name != null) { Preconditions .checkNotNull(mProperties, "Must receive app / library info before " + "Bindable fields."); mProperties.addProperty(enclosing.getQualifiedName().toString(), name); } } GenerationalClassUtil.writeIntermediateFile(processingEnv, mProperties.getPackage(), createIntermediateFileName(mProperties.getPackage()), mProperties); generateBRClasses(!buildInfo.isLibrary(), mProperties.getPackage()); } return false; } @Override public void addVariable(String variableName, String containingClassName) { HashSet<String> variableNames = mLayoutVariables.get(containingClassName); if (variableNames == null) { variableNames = new HashSet<String>(); mLayoutVariables.put(containingClassName, variableNames); } variableNames.add(variableName); } @Override public void onProcessingOver(RoundEnvironment roundEnvironment, ProcessingEnvironment processingEnvironment, BindingBuildInfo buildInfo) { } private String createIntermediateFileName(String appPkg) { return appPkg + GenerationalClassUtil.ExtensionFilter.BR.getExtension(); } private void generateBRClasses(boolean useFinalFields, String pkg) { L.d("************* Generating BR file %s. use final: %s", pkg, useFinalFields); HashSet<String> properties = new HashSet<String>(); mProperties.captureProperties(properties); List<Intermediate> previousIntermediates = loadPreviousBRFiles(); for (Intermediate intermediate : previousIntermediates) { intermediate.captureProperties(properties); } final JavaFileWriter writer = getWriter(); BRWriter brWriter = new BRWriter(properties, useFinalFields); writer.writeToFile(pkg + ".BR", brWriter.write(pkg)); //writeBRClass(useFinalFields, pkg, properties); if (useFinalFields) { // generate BR for all previous packages for (Intermediate intermediate : previousIntermediates) { writer.writeToFile(intermediate.getPackage() + ".BR", brWriter.write(intermediate.getPackage())); } } mCallback.onBrWriterReady(brWriter); } private String getPropertyName(Element element) { switch (element.getKind()) { case FIELD: return stripPrefixFromField((VariableElement) element); case METHOD: return stripPrefixFromMethod((ExecutableElement) element); default: L.e("@Bindable is not allowed on %s", element.getKind()); return null; } } private static String stripPrefixFromField(VariableElement element) { Name name = element.getSimpleName(); if (name.length() >= 2) { char firstChar = name.charAt(0); char secondChar = name.charAt(1); if (name.length() > 2 && firstChar == 'm' && secondChar == '_') { char thirdChar = name.charAt(2); if (Character.isJavaIdentifierStart(thirdChar)) { return "" + Character.toLowerCase(thirdChar) + name.subSequence(3, name.length()); } } else if ((firstChar == 'm' && Character.isUpperCase(secondChar)) || (firstChar == '_' && Character.isJavaIdentifierStart(secondChar))) { return "" + Character.toLowerCase(secondChar) + name.subSequence(2, name.length()); } } return name.toString(); } private String stripPrefixFromMethod(ExecutableElement element) { Name name = element.getSimpleName(); CharSequence propertyName; if (isGetter(element) || isSetter(element)) { propertyName = name.subSequence(3, name.length()); } else if (isBooleanGetter(element)) { propertyName = name.subSequence(2, name.length()); } else { L.e("@Bindable associated with method must follow JavaBeans convention %s", element); return null; } char firstChar = propertyName.charAt(0); return "" + Character.toLowerCase(firstChar) + propertyName.subSequence(1, propertyName.length()); } private void mergeLayoutVariables() { for (String containingClass : mLayoutVariables.keySet()) { for (String variable : mLayoutVariables.get(containingClass)) { mProperties.addProperty(containingClass, variable); } } } private static boolean prefixes(CharSequence sequence, String prefix) { boolean prefixes = false; if (sequence.length() > prefix.length()) { int count = prefix.length(); prefixes = true; for (int i = 0; i < count; i++) { if (sequence.charAt(i) != prefix.charAt(i)) { prefixes = false; break; } } } return prefixes; } private static boolean isGetter(ExecutableElement element) { Name name = element.getSimpleName(); return prefixes(name, "get") && Character.isJavaIdentifierStart(name.charAt(3)) && element.getParameters().isEmpty() && element.getReturnType().getKind() != TypeKind.VOID; } private static boolean isSetter(ExecutableElement element) { Name name = element.getSimpleName(); return prefixes(name, "set") && Character.isJavaIdentifierStart(name.charAt(3)) && element.getParameters().size() == 1 && element.getReturnType().getKind() == TypeKind.VOID; } private static boolean isBooleanGetter(ExecutableElement element) { Name name = element.getSimpleName(); return prefixes(name, "is") && Character.isJavaIdentifierStart(name.charAt(2)) && element.getParameters().isEmpty() && element.getReturnType().getKind() == TypeKind.BOOLEAN; } private List<Intermediate> loadPreviousBRFiles() { return GenerationalClassUtil .loadObjects(GenerationalClassUtil.ExtensionFilter.BR); } private interface Intermediate extends Serializable { void captureProperties(Set<String> properties); void addProperty(String className, String propertyName); boolean hasValues(); String getPackage(); } private static class IntermediateV1 implements Serializable, Intermediate { private static final long serialVersionUID = 2L; private String mPackage; private final HashMap<String, HashSet<String>> mProperties = new HashMap<String, HashSet<String>>(); public IntermediateV1(String aPackage) { mPackage = aPackage; } @Override public void captureProperties(Set<String> properties) { for (HashSet<String> propertySet : mProperties.values()) { properties.addAll(propertySet); } } @Override public void addProperty(String className, String propertyName) { HashSet<String> properties = mProperties.get(className); if (properties == null) { properties = new HashSet<String>(); mProperties.put(className, properties); } properties.add(propertyName); } @Override public boolean hasValues() { return !mProperties.isEmpty(); } @Override public String getPackage() { return mPackage; } } }
4,692
1,781
/* * HaoRan ImageFilter Classes v0.1 * Copyright (C) 2012 <NAME> * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation; either version 2.1 of the License, or (at your * option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation. */ package com.marshalchen.common.uimodule.ImageFilter; /** * Ť��Ч�� * @author daizhj * */ public class RadialDistortionFilter implements IImageFilter{ public static class Point { public float X; public float Y; public Point(float x, float y){ X = x; Y = y; } } public float Radius = 0.5f; public float Distortion = 1.5f; public Point Center = new Point(0.5f, 0.5f); //@Override public Image process(Image imageIn) { int r, g, b; int width = imageIn.getWidth(); int height = imageIn.getHeight(); int realxpos = (int)(width * Center.X); int realypos = (int)(height * Center.Y); float realradius = Math.min(width, height) * Radius; Image clone = imageIn.clone(); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { float pos = 1f - ((float)Math.sqrt((double)(((x - realxpos) * (x - realxpos)) + (y - realypos) * (y - realypos))) / realradius); if (pos > 0f) { pos = 1f - (Distortion * pos * pos); float pos1 = (x - realxpos) * pos + realxpos; float pos2 = (y - realypos) * pos + realypos; int x1 = (int)pos1; float pos3 = pos1 - x1; int x2 = (pos3 > 0f) ? (x1 + 1) : x1; int y1 = (int)pos2; float pos4 = pos2 - y1; int y2 = (pos4 > 0f) ? (y1 + 1) : y1; if (x1 < 0){ x1 = 0; } else if (x1 >= width){ x1 = width - 1; } if (x2 < 0){ x2 = 0; } else if (x2 >= width){ x2 = width - 1; } if (y1 < 0){ y1 = 0; } else if (y1 >= height){ y1 = height - 1; } if (y2 < 0){ y2 = 0; } else if (y2 >= height){ y2 = height - 1; } r = clone.getRComponent(x1, y1); g = clone.getGComponent(x1, y1); b = clone.getBComponent(x1, y1); int r2 = clone.getRComponent(x2, y1); int g2 = clone.getGComponent(x2, y1); int b2 = clone.getBComponent(x2, y1); int r3 = clone.getRComponent(x2, y2); int g3 = clone.getGComponent(x2, y2); int b3 = clone.getBComponent(x2, y2); int r4 = clone.getRComponent(x1, y2); int g4 = clone.getGComponent(x1, y2); int b4 = clone.getBComponent(x1, y2); r = (int)((r * (1f - pos4) * (1f - pos3) + r2 * (1f - pos4) * pos3 + r3 * pos4 * pos3) + r4 * pos4 * (1f - pos3)); g = (int)((g * (1f - pos4) * (1f - pos3) + g2 * (1f - pos4) * pos3 + g3 * pos4 * pos3) + g4 * pos4 * (1f - pos3)); b = (int)((b * (1f - pos4) * (1f - pos3) + b2 * (1f - pos4) * pos3 + b3 * pos4 * pos3) + b4 * pos4 * (1f - pos3)); } else { r = clone.getRComponent(x, y); g = clone.getGComponent(x, y); b = clone.getBComponent(x, y); } imageIn.setPixelColor(x,y,r,g,b); } } return imageIn; } }
2,572
692
<reponame>iMats/Singularity<filename>SingularityRunnerBase/src/main/java/com/hubspot/singularity/runner/base/jackson/ObfuscateAnnotationIntrospector.java package com.hubspot.singularity.runner.base.jackson; import static com.hubspot.mesos.JavaUtils.obfuscateValue; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.Version; import com.fasterxml.jackson.databind.AnnotationIntrospector; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.introspect.Annotated; import java.io.IOException; import java.util.Optional; public class ObfuscateAnnotationIntrospector extends AnnotationIntrospector { private static final long serialVersionUID = 1L; private static final ObfuscateSerializer OBFUSCATE_SERIALIZER = new ObfuscateSerializer(); @Override public Version version() { return Version.unknownVersion(); } @Override public Object findSerializer(Annotated am) { if (am.hasAnnotation(Obfuscate.class)) { return OBFUSCATE_SERIALIZER; } else { return null; } } public static class ObfuscateSerializer extends JsonSerializer<Object> { @Override public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { if (value instanceof Optional) { if (((Optional<?>) value).isPresent()) { jgen.writeString(obfuscateValue(((Optional<?>) value).get().toString())); } else { jgen.writeNull(); } } else { jgen.writeString(obfuscateValue(value.toString())); } } } }
628
28,321
#!/usr/bin/env python counts=dict() mails=list() fname=input('Enter file name:') fh=open(fname) for line in fh: if not line.startswith('From '): continue # if line.startswith('From:'): # continue id=line.split() mail=id[1] mails.append(mail) freq_mail = max(mails, key=mails.count) #To find frequent mail print(freq_mail, mails.count(freq_mail)) #To find countof frequent mail """ for x in mails: counts[x]=counts.get(x,0)+1 bigmail=None bigvalue=None for key,value in counts.items(): if bigvalue==None or bigvalue<value: bigmail=key bigvalue=value print(bigmail, bigvalue) """
276
2,040
#include "ClassFlowCNNGeneral.h" #include <math.h> #include <iomanip> #include <sys/types.h> #include <sstream> // std::stringstream #include "CTfLiteClass.h" #include "ClassLogFile.h" static const char* TAG = "flow_analog"; bool debugdetailgeneral = false; ClassFlowCNNGeneral::ClassFlowCNNGeneral(ClassFlowAlignment *_flowalign, t_CNNType _cnntype) : ClassFlowImage(NULL, TAG) { string cnnmodelfile = ""; modelxsize = 1; modelysize = 1; ListFlowControll = NULL; previousElement = NULL; SaveAllFiles = false; disabled = false; // extendedResolution = false; isLogImageSelect = false; CNNType = AutoDetect; CNNType = _cnntype; flowpostalignment = _flowalign; } /* int ClassFlowCNNGeneral::AnzahlROIs(int _analog = 0) { int zw = GENERAL[_analog]->ROI.size(); if (extendedResolution && (CNNType != Digital)) zw++; // da letzte Ziffer inkl Nachhkomma, es sei denn, das Nachkomma gibt es nicht (Digital) return zw; } */ string ClassFlowCNNGeneral::getReadout(int _analog = 0, bool _extendedResolution = false) { string result = ""; if (GENERAL[_analog]->ROI.size() == 0) return result; if (CNNType == Analogue) { float zahl = GENERAL[_analog]->ROI[GENERAL[_analog]->ROI.size() - 1]->result_float; int ergebnis_nachkomma = ((int) floor(zahl * 10) + 10) % 10; int prev = -1; prev = ZeigerEval(GENERAL[_analog]->ROI[GENERAL[_analog]->ROI.size() - 1]->result_float, prev); result = std::to_string(prev); if (_extendedResolution && (CNNType != Digital)) result = result + std::to_string(ergebnis_nachkomma); for (int i = GENERAL[_analog]->ROI.size() - 2; i >= 0; --i) { prev = ZeigerEval(GENERAL[_analog]->ROI[i]->result_float, prev); result = std::to_string(prev) + result; } return result; } if (CNNType == Digital) { for (int i = 0; i < GENERAL[_analog]->ROI.size(); ++i) { if (GENERAL[_analog]->ROI[i]->result_klasse >= 10) result = result + "N"; else result = result + std::to_string(GENERAL[_analog]->ROI[i]->result_klasse); } return result; } if (CNNType == DigitalHyprid) { // int ergebnis_nachkomma = -1; int zif_akt = -1; float zahl = GENERAL[_analog]->ROI[GENERAL[_analog]->ROI.size() - 1]->result_float; if (zahl >= 0) // NaN? { if (_extendedResolution) { int ergebnis_nachkomma = ((int) floor(zahl * 10)) % 10; int ergebnis_vorkomma = ((int) floor(zahl)) % 10; result = std::to_string(ergebnis_vorkomma) + std::to_string(ergebnis_nachkomma); zif_akt = ergebnis_vorkomma; } else { zif_akt = ZeigerEvalHybrid(GENERAL[_analog]->ROI[GENERAL[_analog]->ROI.size() - 1]->result_float, -1, -1); result = std::to_string(zif_akt); } } else { result = "N"; if (_extendedResolution && (CNNType != Digital)) result = "NN"; } for (int i = GENERAL[_analog]->ROI.size() - 2; i >= 0; --i) { if (GENERAL[_analog]->ROI[i]->result_float >= 0) { zif_akt = ZeigerEvalHybrid(GENERAL[_analog]->ROI[i]->result_float, GENERAL[_analog]->ROI[i+1]->result_float, zif_akt); result = std::to_string(zif_akt) + result; } else { zif_akt = -1; result = "N" + result; } } return result; } return result; } int ClassFlowCNNGeneral::ZeigerEvalHybrid(float zahl, float zahl_vorgaenger, int eval_vorgaenger) { int ergebnis_nachkomma = ((int) floor(zahl * 10)) % 10; // int ergebnis_vorkomma = ((int) floor(zahl)) % 10; if (zahl_vorgaenger < 0) // keine Vorzahl vorhanden !!! --> Runde die Zahl { if ((ergebnis_nachkomma <= 2) || (ergebnis_nachkomma >= 8)) // Band um die Ziffer --> Runden, da Ziffer im Rahmen Ungenauigkeit erreicht return ((int) round(zahl) + 10) % 10; else return ((int) trunc(zahl) + 10) % 10; } if (zahl_vorgaenger > 9.2) // Ziffernwechsel beginnt { if (eval_vorgaenger == 0) // Wechsel hat schon stattgefunden { return ((int) round(zahl) + 10) % 10; // Annahme, dass die neue Zahl schon in der Nähe des Ziels ist } else { if (zahl_vorgaenger <= 9.5) // Wechsel startet gerade, aber beginnt erst { if ((ergebnis_nachkomma <= 2) || (ergebnis_nachkomma >= 8)) // Band um die Ziffer --> Runden, da Ziffer im Rahmen Ungenauigkeit erreicht return ((int) round(zahl) + 10) % 10; else return ((int) trunc(zahl) + 10) % 10; } else { return ((int) trunc(zahl) + 10) % 10; // Wechsel schon weiter fortgeschritten, d.h. über 2 als Nachkomma } } } if ((ergebnis_nachkomma <= 2) || (ergebnis_nachkomma >= 8)) // Band um die Ziffer --> Runden, da Ziffer im Rahmen Ungenauigkeit erreicht return ((int) round(zahl) + 10) % 10; return ((int) trunc(zahl) + 10) % 10; } int ClassFlowCNNGeneral::ZeigerEval(float zahl, int ziffer_vorgaenger) { int ergebnis_nachkomma = ((int) floor(zahl * 10) + 10) % 10; int ergebnis_vorkomma = ((int) floor(zahl) + 10) % 10; int ergebnis, ergebnis_rating; if (ziffer_vorgaenger == -1) return ergebnis_vorkomma % 10; ergebnis_rating = ergebnis_nachkomma - ziffer_vorgaenger; if (ergebnis_nachkomma >= 5) ergebnis_rating-=5; else ergebnis_rating+=5; ergebnis = (int) round(zahl); if (ergebnis_rating < 0) ergebnis-=1; if (ergebnis == -1) ergebnis+=10; ergebnis = (ergebnis + 10) % 10; return ergebnis; } bool ClassFlowCNNGeneral::ReadParameter(FILE* pfile, string& aktparamgraph) { std::vector<string> zerlegt; aktparamgraph = trim(aktparamgraph); if (aktparamgraph.size() == 0) if (!this->GetNextParagraph(pfile, aktparamgraph)) return false; if ((toUpper(aktparamgraph) != "[ANALOG]") && (toUpper(aktparamgraph) != ";[ANALOG]") && (toUpper(aktparamgraph) != "[DIGIT]") && (toUpper(aktparamgraph) != ";[DIGIT]") && (toUpper(aktparamgraph) != "[DIGITS]") && (toUpper(aktparamgraph) != ";[DIGITS]") ) // Paragraph passt nicht return false; /* if ((aktparamgraph.compare("[Analog]") != 0) && (aktparamgraph.compare(";[Analog]") != 0) && (aktparamgraph.compare("[Digit]") != 0) && (aktparamgraph.compare(";[Digit]"))) // Paragraph passt nicht return false; */ if (aktparamgraph[0] == ';') { disabled = true; while (getNextLine(pfile, &aktparamgraph) && !isNewParagraph(aktparamgraph)); printf("[Analog/Digit] is disabled !!!\n"); return true; } while (this->getNextLine(pfile, &aktparamgraph) && !this->isNewParagraph(aktparamgraph)) { zerlegt = this->ZerlegeZeile(aktparamgraph); if ((zerlegt[0] == "LogImageLocation") && (zerlegt.size() > 1)) { this->LogImageLocation = "/sdcard" + zerlegt[1]; this->isLogImage = true; } if ((zerlegt[0] == "LogImageSelect") && (zerlegt.size() > 1)) { LogImageSelect = zerlegt[1]; isLogImageSelect = true; } if ((toUpper(zerlegt[0]) == "LOGFILERETENTIONINDAYS") && (zerlegt.size() > 1)) { this->logfileRetentionInDays = std::stoi(zerlegt[1]); } if ((toUpper(zerlegt[0]) == "MODELTYPE") && (zerlegt.size() > 1)) { if (toUpper(zerlegt[1]) == "DIGITHYPRID") CNNType = DigitalHyprid; } if ((zerlegt[0] == "Model") && (zerlegt.size() > 1)) { this->cnnmodelfile = zerlegt[1]; } if ((zerlegt[0] == "ModelInputSize") && (zerlegt.size() > 2)) { this->modelxsize = std::stoi(zerlegt[1]); this->modelysize = std::stoi(zerlegt[2]); } if (zerlegt.size() >= 5) { general* _analog = GetGENERAL(zerlegt[0], true); roi* neuroi = _analog->ROI[_analog->ROI.size()-1]; neuroi->posx = std::stoi(zerlegt[1]); neuroi->posy = std::stoi(zerlegt[2]); neuroi->deltax = std::stoi(zerlegt[3]); neuroi->deltay = std::stoi(zerlegt[4]); neuroi->result_float = -1; neuroi->image = NULL; neuroi->image_org = NULL; } if ((toUpper(zerlegt[0]) == "SAVEALLFILES") && (zerlegt.size() > 1)) { if (toUpper(zerlegt[1]) == "TRUE") SaveAllFiles = true; } /* if ((toUpper(zerlegt[0]) == "EXTENDEDRESOLUTION") && (zerlegt.size() > 1)) { if (toUpper(zerlegt[1]) == "TRUE") extendedResolution = true; } */ } for (int _ana = 0; _ana < GENERAL.size(); ++_ana) for (int i = 0; i < GENERAL[_ana]->ROI.size(); ++i) { GENERAL[_ana]->ROI[i]->image = new CImageBasis(modelxsize, modelysize, 3); GENERAL[_ana]->ROI[i]->image_org = new CImageBasis(GENERAL[_ana]->ROI[i]->deltax, GENERAL[_ana]->ROI[i]->deltay, 3); } return true; } general* ClassFlowCNNGeneral::FindGENERAL(string _name_number) { for (int i = 0; i < GENERAL.size(); ++i) if (GENERAL[i]->name == _name_number) return GENERAL[i]; return NULL; } general* ClassFlowCNNGeneral::GetGENERAL(string _name, bool _create = true) { string _analog, _roi; int _pospunkt = _name.find_first_of("."); if (_pospunkt > -1) { _analog = _name.substr(0, _pospunkt); _roi = _name.substr(_pospunkt+1, _name.length() - _pospunkt - 1); } else { _analog = "default"; _roi = _name; } general *_ret = NULL; for (int i = 0; i < GENERAL.size(); ++i) if (GENERAL[i]->name == _analog) _ret = GENERAL[i]; if (!_create) // nicht gefunden und soll auch nicht erzeugt werden return _ret; if (_ret == NULL) { _ret = new general; _ret->name = _analog; GENERAL.push_back(_ret); } roi* neuroi = new roi; neuroi->name = _roi; _ret->ROI.push_back(neuroi); printf("GetGENERAL - GENERAL %s - roi %s\n", _analog.c_str(), _roi.c_str()); return _ret; } string ClassFlowCNNGeneral::getHTMLSingleStep(string host) { string result, zw; std::vector<HTMLInfo*> htmlinfo; result = "<p>Found ROIs: </p> <p><img src=\"" + host + "/img_tmp/alg_roi.jpg\"></p>\n"; result = result + "Analog Pointers: <p> "; htmlinfo = GetHTMLInfo(); for (int i = 0; i < htmlinfo.size(); ++i) { std::stringstream stream; stream << std::fixed << std::setprecision(1) << htmlinfo[i]->val; zw = stream.str(); result = result + "<img src=\"" + host + "/img_tmp/" + htmlinfo[i]->filename + "\"> " + zw; delete htmlinfo[i]; } htmlinfo.clear(); return result; } bool ClassFlowCNNGeneral::doFlow(string time) { if (disabled) return true; if (!doAlignAndCut(time)){ return false; }; if (debugdetailgeneral) LogFile.WriteToFile("ClassFlowCNNGeneral::doFlow nach Alignment"); doNeuralNetwork(time); RemoveOldLogs(); return true; } bool ClassFlowCNNGeneral::doAlignAndCut(string time) { if (disabled) return true; CAlignAndCutImage *caic = flowpostalignment->GetAlignAndCutImage(); for (int _ana = 0; _ana < GENERAL.size(); ++_ana) for (int i = 0; i < GENERAL[_ana]->ROI.size(); ++i) { printf("General %d - Align&Cut\n", i); caic->CutAndSave(GENERAL[_ana]->ROI[i]->posx, GENERAL[_ana]->ROI[i]->posy, GENERAL[_ana]->ROI[i]->deltax, GENERAL[_ana]->ROI[i]->deltay, GENERAL[_ana]->ROI[i]->image_org); if (SaveAllFiles) { if (GENERAL[_ana]->name == "default") GENERAL[_ana]->ROI[i]->image_org->SaveToFile(FormatFileName("/sdcard/img_tmp/" + GENERAL[_ana]->ROI[i]->name + ".jpg")); else GENERAL[_ana]->ROI[i]->image_org->SaveToFile(FormatFileName("/sdcard/img_tmp/" + GENERAL[_ana]->name + "_" + GENERAL[_ana]->ROI[i]->name + ".jpg")); } GENERAL[_ana]->ROI[i]->image_org->Resize(modelxsize, modelysize, GENERAL[_ana]->ROI[i]->image); if (SaveAllFiles) { if (GENERAL[_ana]->name == "default") GENERAL[_ana]->ROI[i]->image->SaveToFile(FormatFileName("/sdcard/img_tmp/" + GENERAL[_ana]->ROI[i]->name + ".bmp")); else GENERAL[_ana]->ROI[i]->image->SaveToFile(FormatFileName("/sdcard/img_tmp/" + GENERAL[_ana]->name + "_" + GENERAL[_ana]->ROI[i]->name + ".bmp")); } } return true; } void ClassFlowCNNGeneral::DrawROI(CImageBasis *_zw) { if (CNNType == Analogue) { int r = 0; int g = 255; int b = 0; for (int _ana = 0; _ana < GENERAL.size(); ++_ana) for (int i = 0; i < GENERAL[_ana]->ROI.size(); ++i) { _zw->drawRect(GENERAL[_ana]->ROI[i]->posx, GENERAL[_ana]->ROI[i]->posy, GENERAL[_ana]->ROI[i]->deltax, GENERAL[_ana]->ROI[i]->deltay, r, g, b, 1); _zw->drawCircle((int) (GENERAL[_ana]->ROI[i]->posx + GENERAL[_ana]->ROI[i]->deltax/2), (int) (GENERAL[_ana]->ROI[i]->posy + GENERAL[_ana]->ROI[i]->deltay/2), (int) (GENERAL[_ana]->ROI[i]->deltax/2), r, g, b, 2); _zw->drawLine((int) (GENERAL[_ana]->ROI[i]->posx + GENERAL[_ana]->ROI[i]->deltax/2), (int) GENERAL[_ana]->ROI[i]->posy, (int) (GENERAL[_ana]->ROI[i]->posx + GENERAL[_ana]->ROI[i]->deltax/2), (int) (GENERAL[_ana]->ROI[i]->posy + GENERAL[_ana]->ROI[i]->deltay), r, g, b, 2); _zw->drawLine((int) GENERAL[_ana]->ROI[i]->posx, (int) (GENERAL[_ana]->ROI[i]->posy + GENERAL[_ana]->ROI[i]->deltay/2), (int) GENERAL[_ana]->ROI[i]->posx + GENERAL[_ana]->ROI[i]->deltax, (int) (GENERAL[_ana]->ROI[i]->posy + GENERAL[_ana]->ROI[i]->deltay/2), r, g, b, 2); } } else { for (int _dig = 0; _dig < GENERAL.size(); ++_dig) for (int i = 0; i < GENERAL[_dig]->ROI.size(); ++i) _zw->drawRect(GENERAL[_dig]->ROI[i]->posx, GENERAL[_dig]->ROI[i]->posy, GENERAL[_dig]->ROI[i]->deltax, GENERAL[_dig]->ROI[i]->deltay, 0, 0, (255 - _dig*100), 2); } } bool ClassFlowCNNGeneral::doNeuralNetwork(string time) { if (disabled) return true; string logPath = CreateLogFolder(time); CTfLiteClass *tflite = new CTfLiteClass; string zwcnn = "/sdcard" + cnnmodelfile; zwcnn = FormatFileName(zwcnn); printf(zwcnn.c_str());printf("\n"); if (!tflite->LoadModel(zwcnn)) { printf("Can't read model file /sdcard%s\n", cnnmodelfile.c_str()); LogFile.WriteToFile("Cannot load model"); delete tflite; return false; } tflite->MakeAllocate(); if (CNNType == AutoDetect) { int _anzoutputdimensions = tflite->GetAnzOutPut(); switch (_anzoutputdimensions) { case 2: CNNType = Analogue; printf("TFlite-Type set to Analogue\n"); break; case 11: CNNType = Digital; printf("TFlite-Type set to Digital\n"); break; case 22: CNNType = DigitalHyprid; printf("TFlite-Type set to DigitalHyprid\n"); break; default: printf("ERROR ERROR ERROR - tflite passt nicht zur Firmware - ERROR ERROR ERROR\n"); } // flowpostprocessing->UpdateNachkommaDecimalShift(); } for (int _ana = 0; _ana < GENERAL.size(); ++_ana) { for (int i = 0; i < GENERAL[_ana]->ROI.size(); ++i) { printf("General %d - TfLite\n", i); switch (CNNType) { case Analogue: { float f1, f2; f1 = 0; f2 = 0; tflite->LoadInputImageBasis(GENERAL[_ana]->ROI[i]->image); tflite->Invoke(); if (debugdetailgeneral) LogFile.WriteToFile("Nach Invoke"); f1 = tflite->GetOutputValue(0); f2 = tflite->GetOutputValue(1); float result = fmod(atan2(f1, f2) / (M_PI * 2) + 2, 1); GENERAL[_ana]->ROI[i]->result_float = result * 10; printf("Result General(Analog)%i: %f\n", i, GENERAL[_ana]->ROI[i]->result_float); if (isLogImage) LogImage(logPath, GENERAL[_ana]->ROI[i]->name, &GENERAL[_ana]->ROI[i]->result_float, NULL, time, GENERAL[_ana]->ROI[i]->image_org); } break; case Digital: { GENERAL[_ana]->ROI[i]->result_klasse = 0; GENERAL[_ana]->ROI[i]->result_klasse = tflite->GetClassFromImageBasis(GENERAL[_ana]->ROI[i]->image); printf("Result General(Digit)%i: %d\n", i, GENERAL[_ana]->ROI[i]->result_klasse); if (isLogImage) { if (isLogImageSelect) { if (LogImageSelect.find(GENERAL[_ana]->ROI[i]->name) != std::string::npos) LogImage(logPath, GENERAL[_ana]->ROI[i]->name, NULL, &GENERAL[_ana]->ROI[i]->result_klasse, time, GENERAL[_ana]->ROI[i]->image_org); } else { LogImage(logPath, GENERAL[_ana]->ROI[i]->name, NULL, &GENERAL[_ana]->ROI[i]->result_klasse, time, GENERAL[_ana]->ROI[i]->image_org); } } } break; case DigitalHyprid: { int _num, _nachkomma; tflite->LoadInputImageBasis(GENERAL[_ana]->ROI[i]->image); tflite->Invoke(); if (debugdetailgeneral) LogFile.WriteToFile("Nach Invoke"); _num = tflite->GetOutClassification(0, 10); _nachkomma = tflite->GetOutClassification(11, 21); string _zwres = "Nach Invoke - Nummer: " + to_string(_num) + " Nachkomma: " + to_string(_nachkomma); if (debugdetailgeneral) LogFile.WriteToFile(_zwres); if ((_num == 10) || (_nachkomma == 10)) // NaN detektiert GENERAL[_ana]->ROI[i]->result_float = -1; else GENERAL[_ana]->ROI[i]->result_float = fmod((double) _num + (((double)_nachkomma)-5)/10 + (double) 10, 10); printf("Result General(DigitalHyprid)%i: %f\n", i, GENERAL[_ana]->ROI[i]->result_float); _zwres = "Result General(DigitalHyprid)" + to_string(i) + ": " + to_string(GENERAL[_ana]->ROI[i]->result_float); if (debugdetailgeneral) LogFile.WriteToFile(_zwres); if (isLogImage) LogImage(logPath, GENERAL[_ana]->ROI[i]->name, &GENERAL[_ana]->ROI[i]->result_float, NULL, time, GENERAL[_ana]->ROI[i]->image_org); } break; default: break; } } } delete tflite; return true; } bool ClassFlowCNNGeneral::isExtendedResolution(int _number) { // if (extendedResolution && !(CNNType == Digital)) if (!(CNNType == Digital)) return true; return false; } std::vector<HTMLInfo*> ClassFlowCNNGeneral::GetHTMLInfo() { std::vector<HTMLInfo*> result; for (int _ana = 0; _ana < GENERAL.size(); ++_ana) for (int i = 0; i < GENERAL[_ana]->ROI.size(); ++i) { if (GENERAL[_ana]->name == "default") GENERAL[_ana]->ROI[i]->image->SaveToFile(FormatFileName("/sdcard/img_tmp/" + GENERAL[_ana]->ROI[i]->name + ".bmp")); else GENERAL[_ana]->ROI[i]->image->SaveToFile(FormatFileName("/sdcard/img_tmp/" + GENERAL[_ana]->name + "_" + GENERAL[_ana]->ROI[i]->name + ".bmp")); HTMLInfo *zw = new HTMLInfo; if (GENERAL[_ana]->name == "default") { zw->filename = GENERAL[_ana]->ROI[i]->name + ".bmp"; zw->filename_org = GENERAL[_ana]->ROI[i]->name + ".jpg"; } else { zw->filename = GENERAL[_ana]->name + "_" + GENERAL[_ana]->ROI[i]->name + ".bmp"; zw->filename_org = GENERAL[_ana]->name + "_" + GENERAL[_ana]->ROI[i]->name + ".jpg"; } if (CNNType == Digital) zw->val = GENERAL[_ana]->ROI[i]->result_klasse; else zw->val = GENERAL[_ana]->ROI[i]->result_float; zw->image = GENERAL[_ana]->ROI[i]->image; zw->image_org = GENERAL[_ana]->ROI[i]->image_org; // printf("Push %s\n", zw->filename.c_str()); result.push_back(zw); } // printf("größe: %d\n", result.size()); return result; } int ClassFlowCNNGeneral::getAnzahlGENERAL() { return GENERAL.size(); } string ClassFlowCNNGeneral::getNameGENERAL(int _analog) { if (_analog < GENERAL.size()) return GENERAL[_analog]->name; return "GENERAL DOES NOT EXIST"; } general* ClassFlowCNNGeneral::GetGENERAL(int _analog) { if (_analog < GENERAL.size()) return GENERAL[_analog]; return NULL; } void ClassFlowCNNGeneral::UpdateNameNumbers(std::vector<std::string> *_name_numbers) { for (int _dig = 0; _dig < GENERAL.size(); _dig++) { std::string _name = GENERAL[_dig]->name; bool found = false; for (int i = 0; i < (*_name_numbers).size(); ++i) { if ((*_name_numbers)[i] == _name) found = true; } if (!found) (*_name_numbers).push_back(_name); } }
12,115
854
__________________________________________________________________________________________________ sample 5 ms submission class Solution { public int carFleet(int target, int[] position, int[] speed) { if(position.length==0)return 0; int fleets=1; int[] idx=new int[position.length]; for(int i=0;i<idx.length;i++)idx[i]=i; sort(idx, position, 0, idx.length-1); // for(int i=0;i<idx.length;i++)System.out.print(position[idx[i]]+" "); //stack stores distinct fleets float ahead=(target-position[idx[0]])/(float)speed[idx[0]]; for(int i=1;i<idx.length;i++){ float t=(target-position[idx[i]])/(float)speed[idx[i]]; //if one can reach earlier or in same time than the ahead then it forms a fleet with the ahead if(ahead>=t)continue; //if one cant reach earlier than the ahead then it forms its own unique fleet ahead=t; fleets++; } return fleets; } public void sort(int[] idx, int[] position, int left, int right){ if(left<right){ int x=partition(idx, position, left, right); sort(idx, position, left, x-1); sort(idx, position, x+1, right); } } public int partition(int[] idx, int[] position, int left, int right){ int pivot=position[idx[right]]; int i=left-1, j=left; while(j<=right){ if(position[idx[j]]>=pivot){ swap(idx, ++i, j); } j++; } return i; } public void swap(int[] A, int i, int j){ int temp=A[i];A[i]=A[j];A[j]=temp; } } __________________________________________________________________________________________________ sample 35704 kb submission class Solution { public int carFleet(int target, int[] position, int[] speed) { if (position == null || position.length == 0) { return 0; } List<int[]> list = new ArrayList<int[]>(); for (int i = 0; i < position.length; i++) { list.add(new int[] {position[i], speed[i]}); } Collections.sort(list, (a,b) -> {return b[0] - a[0];}); int ans = 1; double limit = (double) (target - list.get(0)[0]) / list.get(0)[1]; for (int[] info: list) { double time =(double) (target - info[0]) / info[1]; if (time <= limit) { continue; } else { limit = time; ans ++; } } return ans; } } __________________________________________________________________________________________________
1,291
5,379
<gh_stars>1000+ // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #ifndef BRPC_POLICY_AUTO_CONCURRENCY_LIMITER_H #define BRPC_POLICY_AUTO_CONCURRENCY_LIMITER_H #include "bvar/bvar.h" #include "butil/containers/bounded_queue.h" #include "brpc/concurrency_limiter.h" namespace brpc { namespace policy { class AutoConcurrencyLimiter : public ConcurrencyLimiter { public: AutoConcurrencyLimiter(); bool OnRequested(int current_concurrency) override; void OnResponded(int error_code, int64_t latency_us) override; int MaxConcurrency() override; AutoConcurrencyLimiter* New(const AdaptiveMaxConcurrency&) const override; private: struct SampleWindow { SampleWindow() : start_time_us(0) , succ_count(0) , failed_count(0) , total_failed_us(0) , total_succ_us(0) {} int64_t start_time_us; int32_t succ_count; int32_t failed_count; int64_t total_failed_us; int64_t total_succ_us; }; bool AddSample(int error_code, int64_t latency_us, int64_t sampling_time_us); int64_t NextResetTime(int64_t sampling_time_us); // The following methods are not thread safe and can only be called // in AppSample() void UpdateMaxConcurrency(int64_t sampling_time_us); void ResetSampleWindow(int64_t sampling_time_us); void UpdateMinLatency(int64_t latency_us); void UpdateQps(double qps); void AdjustMaxConcurrency(int next_max_concurrency); // modified per sample-window or more int _max_concurrency; int64_t _remeasure_start_us; int64_t _reset_latency_us; int64_t _min_latency_us; double _ema_max_qps; double _explore_ratio; // modified per sample. butil::atomic<int64_t> BAIDU_CACHELINE_ALIGNMENT _last_sampling_time_us; butil::Mutex _sw_mutex; SampleWindow _sw; // modified per request. butil::atomic<int32_t> BAIDU_CACHELINE_ALIGNMENT _total_succ_req; }; } // namespace policy } // namespace brpc #endif // BRPC_POLICY_AUTO_CONCURRENCY_LIMITER_H
1,059
348
<filename>docs/data/leg-t2/018/01803273.json {"nom":"Venesmes","circ":"3ème circonscription","dpt":"Cher","inscrits":637,"abs":340,"votants":297,"blancs":12,"nuls":14,"exp":271,"res":[{"nuance":"SOC","nom":"<NAME>","voix":137},{"nuance":"REM","nom":"<NAME>","voix":134}]}
110
2,206
<reponame>steljord2/deeplearning4j [ { "name":"org.datavec.api.transform.transform.sequence.SequenceOffsetTransform", "allDeclaredFields":true, "allDeclaredMethods":true, "allDeclaredConstructors":true, "allDeclaredClasses" : true, "allPublicClasses" : true }, { "name":"org.datavec.api.transform.DataAction", "allDeclaredFields":true, "allDeclaredMethods":true, "allDeclaredConstructors":true, "allDeclaredClasses" : true, "allPublicClasses" : true }, { "name":"org.datavec.api.transform.analysis.columns.ColumnAnalysis", "allDeclaredFields":true, "allDeclaredMethods":true, "allDeclaredConstructors":true, "allDeclaredClasses" : true, "allPublicClasses" : true }, { "name":"org.datavec.api.transform.condition.Condition", "allDeclaredFields":true, "allDeclaredMethods":true, "allDeclaredConstructors":true, "allDeclaredClasses" : true, "allPublicClasses" : true }, { "name":"org.datavec.api.transform.condition.sequence.SequenceLengthCondition", "allDeclaredFields":true, "allDeclaredMethods":true, "allDeclaredConstructors":true, "allDeclaredClasses" : true, "allPublicClasses" : true }, { "name":"org.datavec.api.transform.filter.Filter", "allDeclaredFields":true, "allDeclaredMethods":true, "allDeclaredConstructors":true, "allDeclaredClasses" : true, "allPublicClasses" : true }, { "name":"org.datavec.api.transform.metadata.ColumnMetaData", "allDeclaredFields":true, "allDeclaredMethods":true, "allDeclaredConstructors":true, "allDeclaredClasses" : true, "allPublicClasses" : true }, { "name":"org.datavec.api.transform.rank.CalculateSortedRank", "allDeclaredFields":true, "allDeclaredMethods":true, "allDeclaredConstructors":true, "allDeclaredClasses" : true, "allPublicClasses" : true }, { "name":"org.datavec.api.transform.reduce.IAssociativeReducer", "allDeclaredFields":true, "allDeclaredMethods":true, "allDeclaredConstructors":true, "allDeclaredClasses" : true, "allPublicClasses" : true }, { "name":"org.datavec.api.transform.sequence.SequenceComparator", "allDeclaredFields":true, "allDeclaredMethods":true, "allDeclaredConstructors":true, "allDeclaredClasses" : true, "allPublicClasses" : true }, { "name":"org.datavec.api.transform.sequence.expansion.BaseSequenceExpansionTransform", "allDeclaredFields":true, "allDeclaredMethods":true, "allDeclaredConstructors":true, "allDeclaredClasses" : true, "allPublicClasses" : true }, { "name":"org.datavec.api.transform.sequence.window.WindowFunction", "allDeclaredFields":true, "allDeclaredMethods":true, "allDeclaredConstructors":true, "allDeclaredClasses" : true, "allPublicClasses" : true }, { "name":"org.datavec.api.transform.serde.legacy.LegacyJsonFormat", "allDeclaredFields":true, "allDeclaredMethods":true, "allDeclaredConstructors":true, "allDeclaredClasses" : true, "allPublicClasses" : true }, { "name":"org.datavec.api.transform.stringreduce.IStringReducer", "allDeclaredFields":true, "allDeclaredMethods":true, "allDeclaredConstructors":true, "allDeclaredClasses" : true, "allPublicClasses" : true }, { "name":"org.datavec.api.transform.transform.BaseColumnsMathOpTransform", "allDeclaredFields":true, "allDeclaredMethods":true, "allDeclaredConstructors":true, "allDeclaredClasses" : true, "allPublicClasses" : true }, { "name":"org.datavec.api.transform.transform.nlp.TextToTermIndexSequenceTransform", "allDeclaredFields":true, "allDeclaredMethods":true, "allDeclaredConstructors":true, "allDeclaredClasses" : true, "allPublicClasses" : true }, { "name":"org.datavec.api.transform.transform.sequence.SequenceDifferenceTransform", "allDeclaredFields":true, "allDeclaredMethods":true, "allDeclaredConstructors":true, "allDeclaredClasses" : true, "allPublicClasses" : true }, { "name":"org.datavec.api.transform.transform.sequence.SequenceMovingWindowReduceTransform", "allDeclaredFields":true, "allDeclaredMethods":true, "allDeclaredConstructors":true, "allDeclaredClasses" : true, "allPublicClasses" : true }, { "name":"org.datavec.api.transform.transform.sequence.SequenceOffsetTransform", "allDeclaredFields":true, "allDeclaredMethods":true, "allDeclaredConstructors":true, "allDeclaredClasses" : true, "allPublicClasses" : true } ]
1,789
493
<reponame>Dorvaryn/download-manager<filename>library/src/main/java/com/novoda/downloadmanager/FilePersistence.java package com.novoda.downloadmanager; import android.content.Context; /** * For defining the mechanism by which files should be persisted on the device. */ public interface FilePersistence { void initialiseWith(Context context, StorageRequirementRule storageRequirementRule); FilePersistenceResult create(FilePath absoluteFilePath, FileSize fileSize); boolean write(byte[] buffer, int offset, int numberOfBytesToWrite); void delete(FilePath absoluteFilePath); long getCurrentSize(FilePath filePath); void close(); }
184
335
<reponame>Safal08/Hacktoberfest-1 { "word": "Vexation", "definitions": [ "The state of being annoyed, frustrated, or worried.", "A cause of annoyance, frustration, or worry." ], "parts-of-speech": "Noun" }
100
14,668
// Copyright 2018 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_CHROME_CLEANER_OS_PRE_FETCHED_PATHS_H_ #define CHROME_CHROME_CLEANER_OS_PRE_FETCHED_PATHS_H_ #include <unordered_map> #include "base/files/file_path.h" #include "base/memory/singleton.h" namespace chrome_cleaner { // Wrapper for base::PathService with pre-fetched of paths retrieved during // initialization. class PreFetchedPaths { public: static PreFetchedPaths* GetInstance(); virtual ~PreFetchedPaths(); // Pre-fetches all paths and returns true if all fetching operations were // successful. This method must be explicitly called by the cleaner and the // reporter, so an exit code can be emitted if any path cannot be retrieved. bool Initialize(); // Disables prefetching paths. Used in unit tests. Tests sometimes override // some of these paths, so prefetching them will cause problems. void DisableForTesting(); // Auxiliary methods for returning pre-fetched paths. These methods should // only be called after Initialize(). Crash if for some reason the path to be // returned is empty. base::FilePath GetExecutablePath() const; base::FilePath GetProgramFilesFolder() const; base::FilePath GetWindowsFolder() const; base::FilePath GetCommonAppDataFolder() const; base::FilePath GetLocalAppDataFolder() const; base::FilePath GetCsidlProgramFilesFolder() const; base::FilePath GetCsidlProgramFilesX86Folder() const; base::FilePath GetCsidlWindowsFolder() const; base::FilePath GetCsidlStartupFolder() const; base::FilePath GetCsidlSystemFolder() const; base::FilePath GetCsidlCommonAppDataFolder() const; base::FilePath GetCsidlLocalAppDataFolder() const; protected: PreFetchedPaths(); private: friend struct base::DefaultSingletonTraits<PreFetchedPaths>; bool FetchPath(int key); // Implements logic for retrieving a value. base::FilePath Get(int key) const; bool initialized_ = false; bool cache_disabled_ = false; std::unordered_map<int, base::FilePath> paths_; }; } // namespace chrome_cleaner #endif // CHROME_CHROME_CLEANER_OS_PRE_FETCHED_PATHS_H_
674
768
package tellh.com.gitclub.presentation.view.fragment.search; import android.support.v7.widget.RecyclerView; import com.tellh.nolistadapter.adapter.FooterLoadMoreAdapterWrapper; import com.tellh.nolistadapter.adapter.FooterLoadMoreAdapterWrapper.UpdateType; import com.tellh.nolistadapter.adapter.RecyclerViewAdapter; import com.tellh.nolistadapter.viewbinder.utils.EasyEmptyRecyclerViewBinder; import java.util.List; import tellh.com.gitclub.R; import tellh.com.gitclub.model.entity.RepositoryInfo; import tellh.com.gitclub.presentation.view.adapter.viewbinder.ErrorViewBinder; import tellh.com.gitclub.presentation.view.adapter.viewbinder.LoadMoreFooterViewBinder; import tellh.com.gitclub.presentation.view.adapter.viewbinder.RepoListItemViewBinder; import tellh.com.gitclub.presentation.view.fragment.ListFragment; import static com.tellh.nolistadapter.adapter.FooterLoadMoreAdapterWrapper.LOADING; import static com.tellh.nolistadapter.adapter.FooterLoadMoreAdapterWrapper.PULL_TO_LOAD_MORE; import static tellh.com.gitclub.presentation.contract.SearchContract.OnGetReposListener; import static tellh.com.gitclub.presentation.contract.SearchContract.OnListFragmentInteractListener; import static tellh.com.gitclub.presentation.contract.SearchContract.REPO; public class SearchRepoFragment extends ListFragment implements OnGetReposListener, FooterLoadMoreAdapterWrapper.OnReachFooterListener { private OnListFragmentInteractListener mListener; private FooterLoadMoreAdapterWrapper loadMoreWrapper; public static SearchRepoFragment newInstance() { return new SearchRepoFragment(); } @Override protected RecyclerView.Adapter getListAdapter() { assert mListener != null; loadMoreWrapper = (FooterLoadMoreAdapterWrapper) RecyclerViewAdapter.builder() .addItemType(new RepoListItemViewBinder(mListener.getPresenter())) .setLoadMoreFooter(new LoadMoreFooterViewBinder(), recyclerView, this) .setErrorView(new ErrorViewBinder(this)) .setEmptyView(new EasyEmptyRecyclerViewBinder(R.layout.empty_view)) .build(); return loadMoreWrapper; } @Override protected int getLayoutId() { return R.layout.frag_items_list; } @Override public void onDetach() { super.onDetach(); mListener = null; } @Override public void onGetRepos(int total_count, List<RepositoryInfo> items, @UpdateType int updateType) { loadMoreWrapper.OnGetData(items, updateType); } @Override public void onToLoadMore(int curPage) { mListener.onFetchPage(REPO, curPage + 1); } void setListFragmentInteractListener(OnListFragmentInteractListener listener) { mListener = listener; } @Override public void onRefresh() { mListener.onFetchPage(REPO, 1); loadMoreWrapper.hideErrorView(recyclerView); } @Override public void hideLoading() { super.hideLoading(); if (loadMoreWrapper.getFooterStatus() == LOADING) loadMoreWrapper.setFooterStatus(PULL_TO_LOAD_MORE); } }
1,191
1,666
/* * Copyright 2014 Google Inc. All rights reserved. * * 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 FRUIT_TYPE_INFO_DEFN_H #define FRUIT_TYPE_INFO_DEFN_H #include <fruit/impl/util/type_info.h> #include <fruit/fruit_forward_decls.h> #include <fruit/impl/data_structures/arena_allocator.h> #include <fruit/impl/data_structures/memory_pool.h> #include <fruit/impl/fruit-config.h> #include <fruit/impl/fruit_assert.h> namespace fruit { namespace impl { template <typename T, bool is_abstract = std::is_abstract<T>::value> struct GetConcreteTypeInfo { constexpr TypeInfo::ConcreteTypeInfo operator()() const { return TypeInfo::ConcreteTypeInfo{ sizeof(T), alignof(T), std::is_trivially_destructible<T>::value, #if FRUIT_EXTRA_DEBUG false /* is_abstract */, #endif }; } }; // For abstract types we don't need the real information. // Also, some compilers might report compile errors in this case, for example alignof(T) doesn't work in Visual Studio // when T is an abstract type. template <typename T> struct GetConcreteTypeInfo<T, true> { constexpr TypeInfo::ConcreteTypeInfo operator()() const { return TypeInfo::ConcreteTypeInfo{ 0 /* type_size */, 0 /* type_alignment */, false /* is_trivially_destructible */, #if FRUIT_EXTRA_DEBUG true /* is_abstract */, #endif }; } }; // This should only be used if RTTI is disabled. Use the other constructor if possible. inline constexpr TypeInfo::TypeInfo(ConcreteTypeInfo concrete_type_info) : info(nullptr), concrete_type_info(concrete_type_info) {} inline constexpr TypeInfo::TypeInfo(const std::type_info& info, ConcreteTypeInfo concrete_type_info) : info(&info), concrete_type_info(concrete_type_info) {} inline std::string TypeInfo::name() const { if (info != nullptr) // LCOV_EXCL_BR_LINE return demangleTypeName(info->name()); else return "<unknown> (type name not accessible because RTTI is disabled)"; // LCOV_EXCL_LINE } inline size_t TypeInfo::size() const { #if FRUIT_EXTRA_DEBUG FruitAssert(!concrete_type_info.is_abstract); #endif return concrete_type_info.type_size; } inline size_t TypeInfo::alignment() const { #if FRUIT_EXTRA_DEBUG FruitAssert(!concrete_type_info.is_abstract); #endif return concrete_type_info.type_alignment; } inline bool TypeInfo::isTriviallyDestructible() const { #if FRUIT_EXTRA_DEBUG FruitAssert(!concrete_type_info.is_abstract); #endif return concrete_type_info.is_trivially_destructible; } inline TypeId::operator std::string() const { return type_info->name(); } inline bool TypeId::operator==(TypeId x) const { return type_info == x.type_info; } inline bool TypeId::operator!=(TypeId x) const { return type_info != x.type_info; } inline bool TypeId::operator<(TypeId x) const { return type_info < x.type_info; } template <typename T> struct GetTypeInfoForType { constexpr TypeInfo operator()() const { #if FRUIT_HAS_TYPEID return TypeInfo(typeid(T), GetConcreteTypeInfo<T>()()); #else return TypeInfo(GetConcreteTypeInfo<T>()()); #endif }; }; template <typename Annotation, typename T> struct GetTypeInfoForType<fruit::Annotated<Annotation, T>> { constexpr TypeInfo operator()() const { #if FRUIT_HAS_TYPEID return TypeInfo(typeid(fruit::Annotated<Annotation, T>), GetConcreteTypeInfo<T>()()); #else return TypeInfo(GetConcreteTypeInfo<T>()()); #endif }; }; template <typename T> inline TypeId getTypeId() { #if FRUIT_HAS_TYPEID && !FRUIT_HAS_CONSTEXPR_TYPEID // We can't use constexpr here because TypeInfo contains a `const std::type_info&` and that's not constexpr with the // current compiler/STL. static TypeInfo info = GetTypeInfoForType<T>()(); #else // Usual case. The `constexpr' ensures compile-time evaluation. static constexpr TypeInfo info = GetTypeInfoForType<T>()(); #endif return TypeId{&info}; } template <typename L> struct GetTypeIdsForListHelper; template <typename... Ts> struct GetTypeIdsForListHelper<fruit::impl::meta::Vector<Ts...>> { std::vector<TypeId, ArenaAllocator<TypeId>> operator()(MemoryPool& memory_pool) { return std::vector<TypeId, ArenaAllocator<TypeId>>(std::initializer_list<TypeId>{getTypeId<Ts>()...}, ArenaAllocator<TypeId>{memory_pool}); } }; template <typename L> std::vector<TypeId, ArenaAllocator<TypeId>> getTypeIdsForList(MemoryPool& memory_pool) { return GetTypeIdsForListHelper<L>()(memory_pool); } #if FRUIT_EXTRA_DEBUG inline std::ostream& operator<<(std::ostream& os, TypeId type) { return os << std::string(type); } #endif // FRUIT_EXTRA_DEBUG } // namespace impl } // namespace fruit namespace std { inline std::size_t hash<fruit::impl::TypeId>::operator()(fruit::impl::TypeId type) const { return hash<const fruit::impl::TypeInfo*>()(type.type_info); } } // namespace std #endif // FRUIT_TYPE_INFO_DEFN_H
1,849
3,539
/* * Copyright (c) 2015, Freescale Semiconductor, Inc. * Copyright 2016,2019 NXP * All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ #ifndef _USB_DEVICE_CDC_ACM_H_ #define _USB_DEVICE_CDC_ACM_H_ /*! * @addtogroup cdc_acm * @{ */ /******************************************************************************* * Definitions ******************************************************************************/ #define USB_DEVICE_CONFIG_CDC_ACM_MAX_INSTANCE (1U) /*!< The maximum number of CDC device instance. */ #define USB_DEVICE_CONFIG_CDC_COMM_CLASS_CODE (0x02U) /*!< The CDC communication class code. */ #define USB_DEVICE_CONFIG_CDC_DATA_CLASS_CODE (0x0AU) /*!< The CDC data class code. */ #define USB_DEVICE_CDC_REQUEST_SEND_ENCAPSULATED_COMMAND \ (0x00) /*!< The CDC class request code for SEND_ENCAPSULATED_COMMAND. */ #define USB_DEVICE_CDC_REQUEST_GET_ENCAPSULATED_RESPONSE \ (0x01) /*!< The CDC class request code for GET_ENCAPSULATED_RESPONSE. */ #define USB_DEVICE_CDC_REQUEST_SET_COMM_FEATURE (0x02) /*!< The CDC class request code for SET_COMM_FEATURE. */ #define USB_DEVICE_CDC_REQUEST_GET_COMM_FEATURE (0x03) /*!< The CDC class request code for GET_COMM_FEATURE. */ #define USB_DEVICE_CDC_REQUEST_CLEAR_COMM_FEATURE (0x04) /*!< The CDC class request code for CLEAR_COMM_FEATURE. */ #define USB_DEVICE_CDC_REQUEST_SET_AUX_LINE_STATE (0x10) /*!< The CDC class request code for SET_AUX_LINE_STATE. */ #define USB_DEVICE_CDC_REQUEST_SET_HOOK_STATE (0x11) /*!< The CDC class request code for SET_HOOK_STATE. */ #define USB_DEVICE_CDC_REQUEST_PULSE_SETUP (0x12) /*!< The CDC class request code for PULSE_SETUP. */ #define USB_DEVICE_CDC_REQUEST_SEND_PULSE (0x13) /*!< The CDC class request code for SEND_PULSE. */ #define USB_DEVICE_CDC_REQUEST_SET_PULSE_TIME (0x14) /*!< The CDC class request code for SET_PULSE_TIME. */ #define USB_DEVICE_CDC_REQUEST_RING_AUX_JACK (0x15) /*!< The CDC class request code for RING_AUX_JACK. */ #define USB_DEVICE_CDC_REQUEST_SET_LINE_CODING (0x20) /*!< The CDC class request code for SET_LINE_CODING. */ #define USB_DEVICE_CDC_REQUEST_GET_LINE_CODING (0x21) /*!< The CDC class request code for GET_LINE_CODING. */ #define USB_DEVICE_CDC_REQUEST_SET_CONTROL_LINE_STATE \ (0x22) /*!< The CDC class request code for SET_CONTROL_LINE_STATE. */ #define USB_DEVICE_CDC_REQUEST_SEND_BREAK (0x23) /*!< The CDC class request code for SEND_BREAK. */ #define USB_DEVICE_CDC_REQUEST_SET_RINGER_PARAMS (0x30) /*!< The CDC class request code for SET_RINGER_PARAMS. */ #define USB_DEVICE_CDC_REQUEST_GET_RINGER_PARAMS (0x31) /*!< The CDC class request code for GET_RINGER_PARAMS. */ #define USB_DEVICE_CDC_REQUEST_SET_OPERATION_PARAM (0x32) /*!< The CDC class request code for SET_OPERATION_PARAM. */ #define USB_DEVICE_CDC_REQUEST_GET_OPERATION_PARAM (0x33) /*!< The CDC class request code for GET_OPERATION_PARAM. */ #define USB_DEVICE_CDC_REQUEST_SET_LINE_PARAMS (0x34) /*!< The CDC class request code for SET_LINE_PARAMS. */ #define USB_DEVICE_CDC_REQUEST_GET_LINE_PARAMS (0x35) /*!< The CDC class request code for GET_LINE_PARAMS. */ #define USB_DEVICE_CDC_REQUEST_DIAL_DIGITS (0x36) /*!< The CDC class request code for DIAL_DIGITS. */ #define USB_DEVICE_CDC_REQUEST_SET_UNIT_PARAMETER (0x37) /*!< The CDC class request code for SET_UNIT_PARAMETER. */ #define USB_DEVICE_CDC_REQUEST_GET_UNIT_PARAMETER (0x38) /*!< The CDC class request code for GET_UNIT_PARAMETER. */ #define USB_DEVICE_CDC_REQUEST_CLEAR_UNIT_PARAMETER \ (0x39) /*!< The CDC class request code for CLEAR_UNIT_PARAMETER. */ #define USB_DEVICE_CDC_REQUEST_SET_ETHERNET_MULTICAST_FILTERS \ (0x40) /*!< The CDC class request code for SET_ETHERNET_MULTICAST_FILTERS. */ #define USB_DEVICE_CDC_REQUEST_SET_ETHERNET_POW_PATTER_FILTER \ (0x41) /*!< The CDC class request code for SET_ETHERNET_POW_PATTER_FILTER. */ #define USB_DEVICE_CDC_REQUEST_GET_ETHERNET_POW_PATTER_FILTER \ (0x42) /*!< The CDC class request code for GET_ETHERNET_POW_PATTER_FILTER. */ #define USB_DEVICE_CDC_REQUEST_SET_ETHERNET_PACKET_FILTER \ (0x43) /*!< The CDC class request code for SET_ETHERNET_PACKET_FILTER. */ #define USB_DEVICE_CDC_REQUEST_GET_ETHERNET_STATISTIC \ (0x44) /*!< The CDC class request code for GET_ETHERNET_STATISTIC. */ #define USB_DEVICE_CDC_REQUEST_SET_ATM_DATA_FORMAT (0x50) /*!< The CDC class request code for SET_ATM_DATA_FORMAT. */ #define USB_DEVICE_CDC_REQUEST_GET_ATM_DEVICE_STATISTICS \ (0x51) /*!< The CDC class request code for GET_ATM_DEVICE_STATISTICS. */ #define USB_DEVICE_CDC_REQUEST_SET_ATM_DEFAULT_VC (0x52) /*!< The CDC class request code for SET_ATM_DEFAULT_VC. */ #define USB_DEVICE_CDC_REQUEST_GET_ATM_VC_STATISTICS \ (0x53) /*!< The CDC class request code for GET_ATM_VC_STATISTICS. */ #define USB_DEVICE_CDC_REQUEST_MDLM_SPECIFIC_REQUESTS_MASK \ (0x7F) /*!< The CDC class request code for MDLM_SPECIFIC_REQUESTS_MASK. */ #define USB_DEVICE_CDC_NOTIF_NETWORK_CONNECTION (0x00) /*!< The CDC class notify code for NETWORK_CONNECTION. */ #define USB_DEVICE_CDC_NOTIF_RESPONSE_AVAIL (0x01) /*!< The CDC class notify code for RESPONSE_AVAIL. */ #define USB_DEVICE_CDC_NOTIF_AUX_JACK_HOOK_STATE (0x08) /*!< The CDC class notify code for AUX_JACK_HOOK_STATE. */ #define USB_DEVICE_CDC_NOTIF_RING_DETECT (0x09) /*!< The CDC class notify code for RING_DETECT. */ #define USB_DEVICE_CDC_NOTIF_SERIAL_STATE (0x20) /*!< The CDC class notify code for SERIAL_STATE. */ #define USB_DEVICE_CDC_NOTIF_CALL_STATE_CHANGE (0x28) /*!< The CDC class notify code for CALL_STATE_CHANGE. */ #define USB_DEVICE_CDC_NOTIF_LINE_STATE_CHANGE (0x29) /*!< The CDC class notify code for LINE_STATE_CHANGE. */ #define USB_DEVICE_CDC_NOTIF_CONNECTION_SPEED_CHANGE \ (0x2A) /*!< The CDC class notify code for CONNECTION_SPEED_CHANGE. */ #define USB_DEVICE_CDC_FEATURE_ABSTRACT_STATE (0x01) /*!< The CDC class feature select code for ABSTRACT_STATE. */ #define USB_DEVICE_CDC_FEATURE_COUNTRY_SETTING (0x02) /*!< The CDC class feature select code for COUNTRY_SETTING. */ #define USB_DEVICE_CDC_CONTROL_SIG_BITMAP_CARRIER_ACTIVATION \ (0x02) /*!< The CDC class control signal bitmap value for CARRIER_ACTIVATION. */ #define USB_DEVICE_CDC_CONTROL_SIG_BITMAP_DTE_PRESENCE \ (0x01) /*!< The CDC class control signal bitmap value for DTE_PRESENCE. */ #define USB_DEVICE_CDC_UART_STATE_RX_CARRIER (0x01) /*!< The UART state bitmap value of RX_CARRIER. */ #define USB_DEVICE_CDC_UART_STATE_TX_CARRIER (0x02) /*!< The UART state bitmap value of TX_CARRIER. */ #define USB_DEVICE_CDC_UART_STATE_BREAK (0x04) /*!< The UART state bitmap value of BREAK. */ #define USB_DEVICE_CDC_UART_STATE_RING_SIGNAL (0x08) /*!< The UART state bitmap value of RING_SIGNAL. */ #define USB_DEVICE_CDC_UART_STATE_FRAMING (0x10) /*!< The UART state bitmap value of FRAMING. */ #define USB_DEVICE_CDC_UART_STATE_PARITY (0x20) /*!< The UART state bitmap value of PARITY. */ #define USB_DEVICE_CDC_UART_STATE_OVERRUN (0x40) /*!< The UART state bitmap value of OVERRUN. */ /*! @brief Definition of CDC class event. */ typedef enum _usb_device_cdc_acm_event { kUSB_DeviceCdcEventSendResponse = 0x01, /*!< This event indicates the bulk send transfer is complete or cancelled etc. */ kUSB_DeviceCdcEventRecvResponse, /*!< This event indicates the bulk receive transfer is complete or cancelled etc.. */ kUSB_DeviceCdcEventSerialStateNotif, /*!< This event indicates the serial state has been sent to the host. */ kUSB_DeviceCdcEventSendEncapsulatedCommand, /*!< This event indicates the device received the SEND_ENCAPSULATED_COMMAND request. */ kUSB_DeviceCdcEventGetEncapsulatedResponse, /*!< This event indicates the device received the GET_ENCAPSULATED_RESPONSE request. */ kUSB_DeviceCdcEventSetCommFeature, /*!< This event indicates the device received the SET_COMM_FEATURE request. */ kUSB_DeviceCdcEventGetCommFeature, /*!< This event indicates the device received the GET_COMM_FEATURE request. */ kUSB_DeviceCdcEventClearCommFeature, /*!< This event indicates the device received the CLEAR_COMM_FEATURE request. */ kUSB_DeviceCdcEventGetLineCoding, /*!< This event indicates the device received the GET_LINE_CODING request. */ kUSB_DeviceCdcEventSetLineCoding, /*!< This event indicates the device received the SET_LINE_CODING request. */ kUSB_DeviceCdcEventSetControlLineState, /*!< This event indicates the device received the SET_CONTRL_LINE_STATE request. */ kUSB_DeviceCdcEventSendBreak /*!< This event indicates the device received the SEND_BREAK request. */ } usb_device_cdc_acm_event_t; /*! @brief Definition of parameters for CDC ACM request. */ typedef struct _usb_device_cdc_acm_request_param_struct { uint8_t **buffer; /*!< The pointer to the address of the buffer for CDC class request. */ uint32_t *length; /*!< The pointer to the length of the buffer for CDC class request. */ uint16_t interfaceIndex; /*!< The interface index of the setup packet. */ uint16_t setupValue; /*!< The wValue field of the setup packet. */ uint8_t isSetup; /*!< The flag indicates if it is a setup packet, 1: yes, 0: no. */ } usb_device_cdc_acm_request_param_struct_t; /*! @brief Definition of pipe structure. */ typedef struct _usb_device_cdc_acm_pipe { osa_mutex_handle_t mutex; /*!< The mutex of the pipe. */ uint32_t mutexBuffer[(OSA_MUTEX_HANDLE_SIZE + 3)/4]; uint8_t *pipeDataBuffer; /*!< pipe data buffer backup when stall */ uint32_t pipeDataLen; /*!< pipe data length backup when stall */ uint8_t pipeStall; /*!< pipe is stall */ uint8_t ep; /*!< The endpoint number of the pipe. */ uint8_t isBusy; /*!< 1: The pipe is transferring packet, 0: The pipe is idle. */ } usb_device_cdc_acm_pipe_t; /*! @brief Definition of structure for CDC ACM device. */ typedef struct _usb_device_cdc_acm_struct { usb_device_handle handle; /*!< The handle of the USB device. */ usb_device_class_config_struct_t *configStruct; /*!< The class configure structure. */ usb_device_interface_struct_t *commInterfaceHandle; /*!< The CDC communication interface handle. */ usb_device_interface_struct_t *dataInterfaceHandle; /*!< The CDC data interface handle. */ usb_device_cdc_acm_pipe_t bulkIn; /*!< The bulk in pipe for sending packet to host. */ usb_device_cdc_acm_pipe_t bulkOut; /*!< The bulk out pipe for receiving packet from host. */ usb_device_cdc_acm_pipe_t interruptIn; /*!< The interrupt in pipe for notifying the device state to host. */ uint8_t configuration; /*!< The current configuration value. */ uint8_t interfaceNumber; /*!< The current interface number. */ uint8_t alternate; /*!< The alternate setting value of the interface. */ uint8_t hasSentState; /*!< 1: The device has primed the state in interrupt pipe, 0: Not primed the state. */ } usb_device_cdc_acm_struct_t; /******************************************************************************* * API ******************************************************************************/ #if defined(__cplusplus) extern "C" { #endif /*! * @name USB CDC ACM Class Driver * @{ */ /*! * @brief Initializes the USB CDC ACM class. * * This function obtains a USB device handle according to the controller ID, initializes the CDC ACM class * with the class configure parameters and creates the mutex for each pipe. * * @param controllerId The ID of the controller. The value can be chosen from the kUSB_ControllerKhci0, * kUSB_ControllerKhci1, kUSB_ControllerEhci0, or kUSB_ControllerEhci1. * @param config The user configuration structure of type usb_device_class_config_struct_t. The user * populates the members of this structure and passes the pointer of this structure * into this function. * @param handle It is out parameter. The class handle of the CDC ACM class. * @return A USB error code or kStatus_USB_Success. * @retval kStatus_USB_Success The CDC ACM class is initialized successfully. * @retval kStatus_USB_Busy No CDC ACM device handle available for allocation. * @retval kStatus_USB_InvalidHandle The CDC ACM device handle allocation failure. * @retval kStatus_USB_InvalidParameter The USB device handle allocation failure. */ extern usb_status_t USB_DeviceCdcAcmInit(uint8_t controllerId, usb_device_class_config_struct_t *config, class_handle_t *handle); /*! * @brief Deinitializes the USB CDC ACM class. * * This function destroys the mutex for each pipe, deinitializes each endpoint of the CDC ACM class and frees * the CDC ACM class handle. * * @param handle The class handle of the CDC ACM class. * @return A USB error code or kStatus_USB_Success. * @retval kStatus_USB_Success The CDC ACM class is de-initialized successfully. * @retval kStatus_USB_Error The endpoint deinitialization failure. * @retval kStatus_USB_InvalidHandle The CDC ACM device handle or the CDC ACM class handle is invalid. * @retval kStatus_USB_InvalidParameter The endpoint number of the CDC ACM class handle is invalid. */ extern usb_status_t USB_DeviceCdcAcmDeinit(class_handle_t handle); /*! * @brief Handles the CDC ACM class event. * * This function responds to various events including the common device events and the class-specific events. * For class-specific events, it calls the class callback defined in the application to deal with the class-specific * event. * * @param handle The class handle of the CDC ACM class. * @param event The event type. * @param param The class handle of the CDC ACM class. * @return A USB error code or kStatus_USB_Success. * @retval kStatus_USB_Success The CDC ACM class is de-initialized successfully. * @retval kStatus_USB_Error The configure structure of the CDC ACM class handle is invalid. * @retval kStatus_USB_InvalidHandle The CDC ACM device handle or the CDC ACM class handle is invalid. * @retval kStatus_USB_InvalidParameter The endpoint number of the CDC ACM class handle is invalid. * @retval Others The error code returned by class callback in application. */ extern usb_status_t USB_DeviceCdcAcmEvent(void *handle, uint32_t event, void *param); /*! * @brief Primes the endpoint to send packet to host. * * This function checks whether the endpoint is sending packet, then it primes the endpoint * with the buffer address and the buffer length if the pipe is not busy. Otherwise, it ignores this transfer by * returning an error code. * * @param handle The class handle of the CDC ACM class. * @param ep The endpoint number of the transfer. * @param buffer The pointer to the buffer to be transferred. * @param length The length of the buffer to be transferred. * @return A USB error code or kStatus_USB_Success. * @retval kStatus_USB_Success Prime to send packet successfully. * @retval kStatus_USB_Busy The endpoint is busy in transferring. * @retval kStatus_USB_InvalidHandle The CDC ACM device handle or the CDC ACM class handle is invalid. * @retval kStatus_USB_ControllerNotFound The controller interface is invalid. * * @note The function can only be called in the same context. */ extern usb_status_t USB_DeviceCdcAcmSend(class_handle_t handle, uint8_t ep, uint8_t *buffer, uint32_t length); /*! * @brief Primes the endpoint to receive packet from host. * * This function checks whether the endpoint is receiving packet, then it primes the endpoint * with the buffer address and the buffer length if the pipe is not busy. Otherwise, it ignores this transfer by * returning an error code. * * @param handle The class handle of the CDC ACM class. * @param ep The endpoint number of the transfer. * @param buffer The pointer to the buffer to be transferred. * @param length The length of the buffer to be transferred. * @return A USB error code or kStatus_USB_Success. * @retval kStatus_USB_Success Prime to receive packet successfully. * @retval kStatus_USB_Busy The endpoint is busy in transferring. * @retval kStatus_USB_InvalidHandle The CDC ACM device handle or the CDC ACM class handle is invalid. * @retval kStatus_USB_ControllerNotFound The controller interface is invalid. * * @note The function can only be called in the same context. */ extern usb_status_t USB_DeviceCdcAcmRecv(class_handle_t handle, uint8_t ep, uint8_t *buffer, uint32_t length); /*! @}*/ #if defined(__cplusplus) } #endif /*! @}*/ #endif /* _USB_DEVICE_CDC_ACM_H_ */
6,301
837
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2019, University of Stuttgart * 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 University of Stuttgart 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. *********************************************************************/ /* Author: <NAME> */ #include <ompl/geometric/planners/quotientspace/datastructures/QuotientSpace.h> #include <ompl/base/objectives/PathLengthOptimizationObjective.h> #include <ompl/base/goals/GoalSampleableRegion.h> #include <ompl/base/spaces/SO2StateSpace.h> #include <ompl/base/spaces/SO3StateSpace.h> #include <ompl/base/spaces/SE2StateSpace.h> #include <ompl/base/spaces/SE3StateSpace.h> #include <ompl/util/Exception.h> unsigned int ompl::geometric::QuotientSpace::counter_ = 0; ompl::geometric::QuotientSpace::QuotientSpace(const base::SpaceInformationPtr &si, QuotientSpace *parent_) : base::Planner(si, "QuotientSpace"), Q1(si), parent_(parent_) { id_ = counter_++; OMPL_DEVMSG1("QuotientSpace %s", id_); if (parent_ != nullptr) parent_->setChild(this); // need to be able to traverse down the tree const base::StateSpacePtr Q1_space = Q1->getStateSpace(); if (parent_ == nullptr) { OMPL_DEVMSG1("ATOMIC dimension: %d measure: %f", Q1_space->getDimension(), Q1_space->getMeasure()); type_ = ATOMIC; } else { Q0 = parent_->getSpaceInformation(); const base::StateSpacePtr Q0_space = Q0->getStateSpace(); // X1 = Q1 / Q0 const base::StateSpacePtr X1_space = computeQuotientSpace(Q1_space, Q0_space); if (X1_space != nullptr) { X1 = std::make_shared<base::SpaceInformation>(X1_space); X1_sampler_ = X1->allocStateSampler(); if (Q0_space->getDimension() + X1_space->getDimension() != Q1_space->getDimension()) { throw ompl::Exception("QuotientSpace Dimensions are wrong."); } OMPL_DEVMSG1("Q0 dimension: %d measure: %f", Q0_space->getDimension(), Q0_space->getMeasure()); OMPL_DEVMSG1("X1 dimension: %d measure: %f", X1_space->getDimension(), X1_space->getMeasure()); OMPL_DEVMSG1("Q1 dimension: %d measure: %f", Q1_space->getDimension(), Q1_space->getMeasure()); if ((Q0_space->getMeasure() <= 0) || (X1_space->getMeasure() <= 0) || (Q1_space->getMeasure() <= 0)) { throw ompl::Exception("Zero-measure QuotientSpace detected."); } if (!X1_sampler_) { X1_sampler_ = X1->allocStateSampler(); } checkSpaceHasFiniteMeasure(X1_space); } else { OMPL_DEVMSG1("Q0 dimension: %d measure: %f", Q0_space->getDimension(), Q0_space->getMeasure()); OMPL_DEVMSG1("Q1 dimension: %d measure: %f", Q1_space->getDimension(), Q1_space->getMeasure()); } checkSpaceHasFiniteMeasure(Q0_space); } checkSpaceHasFiniteMeasure(Q1_space); if (!Q1_valid_sampler_) { Q1_valid_sampler_ = Q1->allocValidStateSampler(); } if (!Q1_sampler_) { Q1_sampler_ = Q1->allocStateSampler(); } if (parent_ != nullptr) { s_Q0_tmp_ = Q0->allocState(); if (X1_dimension_ > 0) s_X1_tmp_ = X1->allocState(); } } ompl::geometric::QuotientSpace::~QuotientSpace() { if (parent_ != nullptr) { if (s_Q0_tmp_) Q0->freeState(s_Q0_tmp_); if (X1 && s_X1_tmp_) X1->freeState(s_X1_tmp_); } } void ompl::geometric::QuotientSpace::setup() { BaseT::setup(); hasSolution_ = false; firstRun_ = true; } void ompl::geometric::QuotientSpace::clear() { BaseT::clear(); totalNumberOfSamples_ = 0; totalNumberOfFeasibleSamples_ = 0; hasSolution_ = false; firstRun_ = true; if (parent_ == nullptr && X1_dimension_ > 0) X1_sampler_.reset(); pdef_->clearSolutionPaths(); } void ompl::geometric::QuotientSpace::checkSpaceHasFiniteMeasure(const base::StateSpacePtr space) const { if (space->getMeasure() >= std::numeric_limits<double>::infinity()) { const base::StateSpacePtr Q0_space = Q0->getStateSpace(); const base::StateSpacePtr Q1_space = Q1->getStateSpace(); OMPL_ERROR("Q0 dimension: %d measure: %f", Q0_space->getDimension(), Q0_space->getMeasure()); OMPL_ERROR("Q1 dimension: %d measure: %f", Q1_space->getDimension(), Q1_space->getMeasure()); if (X1 != nullptr) { const base::StateSpacePtr X1_space = X1->getStateSpace(); OMPL_ERROR("X1 dimension: %d measure: %f", X1_space->getDimension(), X1_space->getMeasure()); } throw ompl::Exception("QuotientSpace has no bounds"); } } ompl::base::PlannerStatus ompl::geometric::QuotientSpace::solve(const base::PlannerTerminationCondition &ptc) { (void)ptc; throw ompl::Exception("A Quotient-Space cannot be solved alone. Use class MultiQuotient to solve Quotient-Spaces."); } void ompl::geometric::QuotientSpace::setProblemDefinition(const base::ProblemDefinitionPtr &pdef) { BaseT::setProblemDefinition(pdef); if (pdef_->hasOptimizationObjective()) { opt_ = pdef_->getOptimizationObjective(); } else { opt_ = std::make_shared<base::PathLengthOptimizationObjective>(si_); } } void ompl::geometric::QuotientSpace::resetCounter() { QuotientSpace::counter_ = 0; } const ompl::base::StateSpacePtr ompl::geometric::QuotientSpace::computeQuotientSpace(const base::StateSpacePtr Q1, const base::StateSpacePtr Q0) { type_ = identifyQuotientSpaceType(Q1, Q0); base::StateSpacePtr X1{nullptr}; Q1_dimension_ = Q1->getDimension(); Q0_dimension_ = Q0->getDimension(); if (Q0_dimension_ == 0 || Q1_dimension_ == 0) { OMPL_ERROR("Q0 has dimension %d.", Q0_dimension_); OMPL_ERROR("Q1 has dimension %d.", Q1_dimension_); throw ompl::Exception("Detected Zero-dimensional QuotientSpace."); } switch (type_) { case IDENTITY_SPACE_RN: case IDENTITY_SPACE_SE2: case IDENTITY_SPACE_SE2RN: case IDENTITY_SPACE_SO2RN: case IDENTITY_SPACE_SE3: case IDENTITY_SPACE_SE3RN: { X1_dimension_ = 0; break; } case RN_RM: { unsigned int N = Q1_dimension_ - Q0_dimension_; X1 = std::make_shared<base::RealVectorStateSpace>(N); X1_dimension_ = N; base::RealVectorBounds Q1_bounds = std::static_pointer_cast<base::RealVectorStateSpace>(Q1)->getBounds(); std::vector<double> low; low.resize(N); std::vector<double> high; high.resize(N); base::RealVectorBounds X1_bounds(N); for (unsigned int k = 0; k < N; k++) { X1_bounds.setLow(k, Q1_bounds.low.at(k + Q0_dimension_)); X1_bounds.setHigh(k, Q1_bounds.high.at(k + Q0_dimension_)); } std::static_pointer_cast<base::RealVectorStateSpace>(X1)->setBounds(X1_bounds); break; } case SE2_R2: { X1_dimension_ = 1; X1 = std::make_shared<base::SO2StateSpace>(); break; } case SE3_R3: { X1_dimension_ = 3; X1 = std::make_shared<base::SO3StateSpace>(); break; } case SE2RN_SE2: case SE3RN_SE3: case SO2RN_SO2: { base::CompoundStateSpace *Q1_compound = Q1->as<base::CompoundStateSpace>(); const std::vector<base::StateSpacePtr> Q1_decomposed = Q1_compound->getSubspaces(); X1_dimension_ = Q1_decomposed.at(1)->getDimension(); X1 = std::make_shared<base::RealVectorStateSpace>(X1_dimension_); std::static_pointer_cast<base::RealVectorStateSpace>(X1)->setBounds( std::static_pointer_cast<base::RealVectorStateSpace>(Q1_decomposed.at(1))->getBounds()); break; } case SE2RN_R2: { base::CompoundStateSpace *Q1_compound = Q1->as<base::CompoundStateSpace>(); const std::vector<base::StateSpacePtr> Q1_decomposed = Q1_compound->getSubspaces(); const std::vector<base::StateSpacePtr> Q1_SE2_decomposed = Q1_decomposed.at(0)->as<base::CompoundStateSpace>()->getSubspaces(); const base::RealVectorStateSpace *Q1_RN = Q1_decomposed.at(1)->as<base::RealVectorStateSpace>(); unsigned int N = Q1_RN->getDimension(); base::StateSpacePtr SO2(new base::SO2StateSpace()); base::StateSpacePtr RN(new base::RealVectorStateSpace(N)); RN->as<base::RealVectorStateSpace>()->setBounds(Q1_RN->getBounds()); X1 = SO2 + RN; X1_dimension_ = 1 + N; break; } case SE3RN_R3: { base::CompoundStateSpace *Q1_compound = Q1->as<base::CompoundStateSpace>(); const std::vector<base::StateSpacePtr> Q1_decomposed = Q1_compound->getSubspaces(); const std::vector<base::StateSpacePtr> Q1_SE3_decomposed = Q1_decomposed.at(0)->as<base::CompoundStateSpace>()->getSubspaces(); // const base::SE3StateSpace *Q1_SE3 = Q1_SE3_decomposed.at(0)->as<base::SE3StateSpace>(); // const base::SO3StateSpace *Q1_SO3 = Q1_SE3_decomposed.at(1)->as<base::SO3StateSpace>(); const base::RealVectorStateSpace *Q1_RN = Q1_decomposed.at(1)->as<base::RealVectorStateSpace>(); unsigned int N = Q1_RN->getDimension(); base::StateSpacePtr SO3(new base::SO3StateSpace()); base::StateSpacePtr RN(new base::RealVectorStateSpace(N)); RN->as<base::RealVectorStateSpace>()->setBounds(Q1_RN->getBounds()); X1 = SO3 + RN; X1_dimension_ = 3 + N; break; } case SE2RN_SE2RM: case SO2RN_SO2RM: case SE3RN_SE3RM: { base::CompoundStateSpace *Q1_compound = Q1->as<base::CompoundStateSpace>(); const std::vector<base::StateSpacePtr> Q1_decomposed = Q1_compound->getSubspaces(); base::CompoundStateSpace *Q0_compound = Q0->as<base::CompoundStateSpace>(); const std::vector<base::StateSpacePtr> Q0_decomposed = Q0_compound->getSubspaces(); unsigned int N = Q1_decomposed.at(1)->getDimension(); unsigned int M = Q0_decomposed.at(1)->getDimension(); X1_dimension_ = N - M; X1 = std::make_shared<base::RealVectorStateSpace>(X1_dimension_); base::RealVectorBounds Q1_bounds = std::static_pointer_cast<base::RealVectorStateSpace>(Q1_decomposed.at(1))->getBounds(); std::vector<double> low; low.resize(X1_dimension_); std::vector<double> high; high.resize(X1_dimension_); base::RealVectorBounds X1_bounds(X1_dimension_); for (unsigned int k = 0; k < X1_dimension_; k++) { X1_bounds.setLow(k, Q1_bounds.low.at(k + M)); X1_bounds.setHigh(k, Q1_bounds.high.at(k + M)); } std::static_pointer_cast<base::RealVectorStateSpace>(X1)->setBounds(X1_bounds); break; } default: { OMPL_ERROR("Unknown QuotientSpace type: %d", type_); throw ompl::Exception("Unknown type"); } } return X1; } ompl::geometric::QuotientSpace::QuotientSpaceType ompl::geometric::QuotientSpace::identifyQuotientSpaceType(const base::StateSpacePtr Q1, const base::StateSpacePtr Q0) { // // We can currently handle 11 types of quotient-space mappings. // Emptyset is used for constraint relaxations. // // (1) Q1 Rn , Q0 Rm [0<m<=n] => X1 = R(n-m) \union {\emptyset} // (2a) Q1 SE2 , Q0 R2 => X1 = SO2 // (2b) Q1 SE2 , Q0 SE2 => X1 = \emptyset // (3a) Q1 SE3 , Q0 R3 => X1 = SO3 // (3b) Q1 SE3 , Q0 SE3 => X1 = \emptyset // // (4) Q1 SE3xRn , Q0 SE3 => X1 = Rn // (5) Q1 SE3xRn , Q0 R3 => X1 = SO3xRn // (6) Q1 SE3xRn , Q0 SE3xRm [0<m<=n ] => X1 = R(n-m) \union {\emptyset} // // (7) Q1 SE2xRn , Q0 SE2 => X1 = Rn // (8) Q1 SE2xRn , Q0 R2 => X1 = SO2xRN // (9) Q1 SE2xRn , Q0 SE2xRm [0<m<=n ] => X1 = R(n-m) \union {\emptyset} // // (10) Q1 SO2xRn , Q0 SO2 => X1 = Rn // (11) Q1 SO2xRn , Q0 SO2xRm [0<m<=n ] => X1 = R(n-m) \union {\emptyset} if (!Q1->isCompound()) { // ##############################################################################/ //------------------ non-compound cases: // ##############################################################################/ // //------------------ (1) Q1 = Rn, Q0 = Rm, 0<m<n, X1 = R(n-m) if (Q1->getType() == base::STATE_SPACE_REAL_VECTOR) { unsigned int n = Q1->getDimension(); if (Q0->getType() == base::STATE_SPACE_REAL_VECTOR) { unsigned int m = Q0->getDimension(); if (n > m && m > 0) { type_ = RN_RM; } else { if (n == m && m > 0) { type_ = IDENTITY_SPACE_RN; } else { OMPL_ERROR("Not allowed: dimensionality needs to be monotonically increasing."); OMPL_ERROR("We require n >= m > 0 but have n=%d >= m=%d > 0", n, m); throw ompl::Exception("Invalid dimensionality"); } } } else { OMPL_ERROR("Q1 is R^%d but Q0 type %d is not handled.", n, Q0->getType()); throw ompl::Exception("INVALID_STATE_TYPE"); } } else { OMPL_ERROR("Q1 is non-compound state, but its type %d is not handled.", Q1->getType()); throw ompl::Exception("INVALID_STATE_TYPE"); } } else { // ##############################################################################/ //------------------ compound cases: // ##############################################################################/ // //------------------ (2) Q1 = SE2, Q0 = R2, X1 = SO2 // ##############################################################################/ if (Q1->getType() == base::STATE_SPACE_SE2) { if (Q0->getType() == base::STATE_SPACE_REAL_VECTOR) { if (Q0->getDimension() == 2) { type_ = SE2_R2; } else { OMPL_ERROR("Q1 is SE2 but Q0 type %d is of dimension %d", Q0->getType(), Q0->getDimension()); throw ompl::Exception("Invalid dimensions."); } } else { if (Q0->getType() == base::STATE_SPACE_SE2) { type_ = IDENTITY_SPACE_SE2; } else { OMPL_ERROR("Q1 is SE2 but Q0 type %d is not handled.", Q0->getType()); throw ompl::Exception("INVALID_STATE_TYPE"); } } } //------------------ (3) Q1 = SE3, Q0 = R3, X1 = SO3 // ##############################################################################/ else if (Q1->getType() == base::STATE_SPACE_SE3) { if (Q0->getType() == base::STATE_SPACE_REAL_VECTOR) { if (Q0->getDimension() == 3) { type_ = SE3_R3; } else { OMPL_ERROR("Q1 is SE3 but Q0 type %d is of dimension %d.", Q0->getType(), Q0->getDimension()); throw ompl::Exception("Invalid dimensions."); } } else { if (Q0->getType() == base::STATE_SPACE_SE3) { type_ = IDENTITY_SPACE_SE3; } else { OMPL_ERROR("Q1 is SE2 but Q0 type %d is not handled.", Q0->getType()); throw ompl::Exception("Invalid QuotientSpace type"); } OMPL_ERROR("Q1 is SE3 but Q0 type %d is not handled.", Q0->getType()); throw ompl::Exception("Invalid QuotientSpace type"); } } // ##############################################################################/ else { base::CompoundStateSpace *Q1_compound = Q1->as<base::CompoundStateSpace>(); const std::vector<base::StateSpacePtr> Q1_decomposed = Q1_compound->getSubspaces(); unsigned int Q1_subspaces = Q1_decomposed.size(); if (Q1_subspaces == 2) { if (Q1_decomposed.at(0)->getType() == base::STATE_SPACE_SE3 && Q1_decomposed.at(1)->getType() == base::STATE_SPACE_REAL_VECTOR) { unsigned int n = Q1_decomposed.at(1)->getDimension(); if (Q0->getType() == base::STATE_SPACE_SE3) { //------------------ (4) Q1 = SE3xRn, Q0 = SE3, X1 = Rn // ##############################################################################/ type_ = SE3RN_SE3; } else if (Q0->getType() == base::STATE_SPACE_REAL_VECTOR) { //------------------ (5) Q1 = SE3xRn, Q0 = R3, X1 = SO3xRN // ##############################################################################/ unsigned int m = Q0->getDimension(); if (m == 3) { type_ = SE3RN_R3; } else { OMPL_ERROR("Not allowed. Q0 needs to be 3-dimensional but is %d dimensional", m); throw ompl::Exception("Invalid dimensions."); } } else { //------------------ (6) Q1 = SE3xRn, Q0 = SE3xRm, X1 = R(n-m) // ##############################################################################/ base::CompoundStateSpace *Q0_compound = Q0->as<base::CompoundStateSpace>(); const std::vector<base::StateSpacePtr> Q0_decomposed = Q0_compound->getSubspaces(); unsigned int Q0_subspaces = Q0_decomposed.size(); if (Q0_subspaces == 2) { if (Q1_decomposed.at(0)->getType() == base::STATE_SPACE_SE3 && Q1_decomposed.at(1)->getType() == base::STATE_SPACE_REAL_VECTOR) { unsigned int m = Q0_decomposed.at(1)->getDimension(); if (m < n && m > 0) { type_ = SE3RN_SE3RM; } else { if (m == n) { type_ = IDENTITY_SPACE_SE3RN; } else { OMPL_ERROR("We require n >= m > 0, but have n=%d >= m=%d > 0.", n, m); throw ompl::Exception("Invalid dimensions."); } } } } else { OMPL_ERROR("State compound with %d subspaces not handled.", Q0_subspaces); throw ompl::Exception("Invalid QuotientSpace type"); } } } else { if (Q1_decomposed.at(0)->getType() == base::STATE_SPACE_SE2 && Q1_decomposed.at(1)->getType() == base::STATE_SPACE_REAL_VECTOR) { unsigned int n = Q1_decomposed.at(1)->getDimension(); if (Q0->getType() == base::STATE_SPACE_SE2) { //------------------ (7) Q1 = SE2xRn, Q0 = SE2, X1 = Rn // ##############################################################################/ type_ = SE2RN_SE2; } else if (Q0->getType() == base::STATE_SPACE_REAL_VECTOR) { //------------------ (8) Q1 = SE2xRn, Q0 = R2, X1 = SO2xRN // ##############################################################################/ unsigned int m = Q0->getDimension(); if (m == 2) { type_ = SE2RN_R2; } else { OMPL_ERROR("Not allowed. Q0 needs to be 2-dimensional but is %d dimensional", m); throw ompl::Exception("Invalid dimensions."); } } else { //------------------ (9) Q1 = SE2xRn, Q0 = SE2xRm, X1 = R(n-m) // ##############################################################################/ base::CompoundStateSpace *Q0_compound = Q0->as<base::CompoundStateSpace>(); const std::vector<base::StateSpacePtr> Q0_decomposed = Q0_compound->getSubspaces(); unsigned int Q0_subspaces = Q0_decomposed.size(); if (Q0_subspaces == 2) { if (Q1_decomposed.at(0)->getType() == base::STATE_SPACE_SE2 && Q1_decomposed.at(1)->getType() == base::STATE_SPACE_REAL_VECTOR) { unsigned int m = Q0_decomposed.at(1)->getDimension(); if (m < n && m > 0) { type_ = SE2RN_SE2RM; } else { if (m == n) { type_ = IDENTITY_SPACE_SE2RN; } else { OMPL_ERROR("We require n >= m > 0, but have n=%d >= m=%d > 0.", n, m); throw ompl::Exception("Invalid dimensions."); } } } else { } } else { OMPL_ERROR("QO is compound with %d subspaces, but we only handle 2.", Q0_subspaces); throw ompl::Exception("Invalid QuotientSpace type"); } } } else if (Q1_decomposed.at(0)->getType() == base::STATE_SPACE_SO2 && Q1_decomposed.at(1)->getType() == base::STATE_SPACE_REAL_VECTOR) { if (Q0->getType() == base::STATE_SPACE_SO2) { //------------------ (10) Q1 = SO2xRn, Q0 = SO2, X1 = Rn // ##############################################################################/ type_ = SO2RN_SO2; } else { //------------------ (11) Q1 = SO2xRn, Q0 = SO2xRm, X1 = R(n-m) // ##############################################################################/ if (Q0->isCompound()) { base::CompoundStateSpace *Q0_compound = Q0->as<base::CompoundStateSpace>(); const std::vector<base::StateSpacePtr> Q0_decomposed = Q0_compound->getSubspaces(); unsigned int Q0_subspaces = Q0_decomposed.size(); if (Q0_subspaces == 2) { if (Q1_decomposed.at(0)->getType() == base::STATE_SPACE_SO2 && Q1_decomposed.at(1)->getType() == base::STATE_SPACE_REAL_VECTOR) { unsigned int n = Q1_decomposed.at(1)->getDimension(); unsigned int m = Q0_decomposed.at(1)->getDimension(); if (m < n && m > 0) { type_ = SO2RN_SO2RM; } else { if (m == n) { type_ = IDENTITY_SPACE_SO2RN; } else { OMPL_ERROR("We require n >= m > 0 but have n=%d >= m=%d > 0.", n, m); throw ompl::Exception("Invalid dimensions."); } } } else { OMPL_ERROR("Cannot project onto type %d.", Q1->getType()); throw ompl::Exception("Invalid QuotientSpace type."); } } else { OMPL_ERROR("Q0 has %d subspaces. We can handle only 2.", Q0_subspaces); throw ompl::Exception("Invalid QuotientSpace type."); } } else { OMPL_ERROR("Cannot project onto type %d.", Q0->getType()); throw ompl::Exception("Invalid QuotientSpace type."); } } } else { OMPL_ERROR("State compound %d and %d not recognized.", Q1_decomposed.at(0)->getType(), Q1_decomposed.at(1)->getType()); throw ompl::Exception("Invalid QuotientSpace type."); } } } else { OMPL_ERROR("Q1 has %d subspaces, but we only support 2.", Q1_subspaces); throw ompl::Exception("Invalid QuotientSpace type."); } } } return type_; } void ompl::geometric::QuotientSpace::mergeStates(const base::State *qQ0, const base::State *qX1, base::State *qQ1) const { // input : qQ0 \in Q0, qX1 \in X1 // output: qQ1 = qQ0 \circ qX1 \in Q1 const base::StateSpacePtr Q1_space = Q1->getStateSpace(); const base::StateSpacePtr X1_space = X1->getStateSpace(); const base::StateSpacePtr Q0_space = parent_->getSpaceInformation()->getStateSpace(); switch (type_) { case IDENTITY_SPACE_RN: case IDENTITY_SPACE_SE2: case IDENTITY_SPACE_SE2RN: case IDENTITY_SPACE_SO2RN: case IDENTITY_SPACE_SE3: case IDENTITY_SPACE_SE3RN: { throw ompl::Exception("Cannot merge states for Identity space"); } case RN_RM: { base::RealVectorStateSpace::StateType *sQ1 = qQ1->as<base::RealVectorStateSpace::StateType>(); const base::RealVectorStateSpace::StateType *sQ0 = qQ0->as<base::RealVectorStateSpace::StateType>(); const base::RealVectorStateSpace::StateType *sX1 = qX1->as<base::RealVectorStateSpace::StateType>(); for (unsigned int k = 0; k < Q0_dimension_; k++) { sQ1->values[k] = sQ0->values[k]; } for (unsigned int k = Q0_dimension_; k < Q1_dimension_; k++) { sQ1->values[k] = sX1->values[k - Q0_dimension_]; } break; } case SE2_R2: { base::SE2StateSpace::StateType *sQ1 = qQ1->as<base::SE2StateSpace::StateType>(); const base::RealVectorStateSpace::StateType *sQ0 = qQ0->as<base::RealVectorStateSpace::StateType>(); const base::SO2StateSpace::StateType *sX1 = qX1->as<base::SO2StateSpace::StateType>(); sQ1->setXY(sQ0->values[0], sQ0->values[1]); sQ1->setYaw(sX1->value); break; } case SE3_R3: { base::SE3StateSpace::StateType *sQ1 = qQ1->as<base::SE3StateSpace::StateType>(); base::SO3StateSpace::StateType *sQ1_rotation = &sQ1->rotation(); const base::RealVectorStateSpace::StateType *sQ0 = qQ0->as<base::RealVectorStateSpace::StateType>(); const base::SO3StateSpace::StateType *sX1 = qX1->as<base::SO3StateSpace::StateType>(); sQ1->setXYZ(sQ0->values[0], sQ0->values[1], sQ0->values[2]); sQ1_rotation->x = sX1->x; sQ1_rotation->y = sX1->y; sQ1_rotation->z = sX1->z; sQ1_rotation->w = sX1->w; break; } case SE3RN_R3: { base::SE3StateSpace::StateType *sQ1_SE3 = qQ1->as<base::CompoundState>()->as<base::SE3StateSpace::StateType>(0); base::SO3StateSpace::StateType *sQ1_SO3 = &sQ1_SE3->rotation(); base::RealVectorStateSpace::StateType *sQ1_RN = qQ1->as<base::CompoundState>()->as<base::RealVectorStateSpace::StateType>(1); const base::RealVectorStateSpace::StateType *sQ0 = qQ0->as<base::RealVectorStateSpace::StateType>(); const base::SO3StateSpace::StateType *sX1_SO3 = qX1->as<base::CompoundState>()->as<base::SO3StateSpace::StateType>(0); const base::RealVectorStateSpace::StateType *sX1_RN = qX1->as<base::CompoundState>()->as<base::RealVectorStateSpace::StateType>(1); sQ1_SE3->setXYZ(sQ0->values[0], sQ0->values[1], sQ0->values[2]); sQ1_SO3->x = sX1_SO3->x; sQ1_SO3->y = sX1_SO3->y; sQ1_SO3->z = sX1_SO3->z; sQ1_SO3->w = sX1_SO3->w; for (unsigned int k = 0; k < X1_dimension_ - 3; k++) { sQ1_RN->values[k] = sX1_RN->values[k]; } break; } case SE2RN_SE2: { base::SE2StateSpace::StateType *sQ1_SE2 = qQ1->as<base::CompoundState>()->as<base::SE2StateSpace::StateType>(0); base::RealVectorStateSpace::StateType *sQ1_RN = qQ1->as<base::CompoundState>()->as<base::RealVectorStateSpace::StateType>(1); const base::SE2StateSpace::StateType *sQ0 = qQ0->as<base::SE2StateSpace::StateType>(); const base::RealVectorStateSpace::StateType *sX1 = qX1->as<base::RealVectorStateSpace::StateType>(); sQ1_SE2->setX(sQ0->getX()); sQ1_SE2->setY(sQ0->getY()); sQ1_SE2->setYaw(sQ0->getYaw()); for (unsigned int k = 0; k < X1_dimension_; k++) { sQ1_RN->values[k] = sX1->values[k]; } break; } case SO2RN_SO2: { base::SO2StateSpace::StateType *sQ1_SO2 = qQ1->as<base::CompoundState>()->as<base::SO2StateSpace::StateType>(0); base::RealVectorStateSpace::StateType *sQ1_RN = qQ1->as<base::CompoundState>()->as<base::RealVectorStateSpace::StateType>(1); const base::SO2StateSpace::StateType *sQ0 = qQ0->as<base::SO2StateSpace::StateType>(); const base::RealVectorStateSpace::StateType *sX1 = qX1->as<base::RealVectorStateSpace::StateType>(); sQ1_SO2->value = sQ0->value; for (unsigned int k = 0; k < X1_dimension_; k++) { sQ1_RN->values[k] = sX1->values[k]; } break; } case SO2RN_SO2RM: { base::SO2StateSpace::StateType *sQ1_SO2 = qQ1->as<base::CompoundState>()->as<base::SO2StateSpace::StateType>(0); base::RealVectorStateSpace::StateType *sQ1_RN = qQ1->as<base::CompoundState>()->as<base::RealVectorStateSpace::StateType>(1); const base::SO2StateSpace::StateType *sQ0_SO2 = qQ0->as<base::CompoundState>()->as<base::SO2StateSpace::StateType>(0); const base::RealVectorStateSpace::StateType *sQ0_RM = qQ0->as<base::CompoundState>()->as<base::RealVectorStateSpace::StateType>(1); const base::RealVectorStateSpace::StateType *sX1 = qX1->as<base::RealVectorStateSpace::StateType>(); sQ1_SO2->value = sQ0_SO2->value; unsigned int M = Q1_dimension_ - X1_dimension_ - 1; unsigned int N = X1_dimension_; for (unsigned int k = 0; k < M; k++) { sQ1_RN->values[k] = sQ0_RM->values[k]; } for (unsigned int k = M; k < M + N; k++) { sQ1_RN->values[k] = sX1->values[k - M]; } break; } case SE2RN_R2: { base::SE2StateSpace::StateType *sQ1_SE2 = qQ1->as<base::CompoundState>()->as<base::SE2StateSpace::StateType>(0); base::RealVectorStateSpace::StateType *sQ1_RN = qQ1->as<base::CompoundState>()->as<base::RealVectorStateSpace::StateType>(1); const base::RealVectorStateSpace::StateType *sQ0 = qQ0->as<base::RealVectorStateSpace::StateType>(); const base::SO2StateSpace::StateType *sX1_SO2 = qX1->as<base::CompoundState>()->as<base::SO2StateSpace::StateType>(0); const base::RealVectorStateSpace::StateType *sX1_RN = qX1->as<base::CompoundState>()->as<base::RealVectorStateSpace::StateType>(1); sQ1_SE2->setX(sQ0->values[0]); sQ1_SE2->setY(sQ0->values[1]); sQ1_SE2->setYaw(sX1_SO2->value); for (unsigned int k = 0; k < X1_dimension_ - 1; k++) { sQ1_RN->values[k] = sX1_RN->values[k]; } break; } case SE2RN_SE2RM: { base::SE2StateSpace::StateType *sQ1_SE2 = qQ1->as<base::CompoundState>()->as<base::SE2StateSpace::StateType>(0); base::RealVectorStateSpace::StateType *sQ1_RN = qQ1->as<base::CompoundState>()->as<base::RealVectorStateSpace::StateType>(1); const base::SE2StateSpace::StateType *sQ0_SE2 = qQ0->as<base::CompoundState>()->as<base::SE2StateSpace::StateType>(0); const base::RealVectorStateSpace::StateType *sQ0_RM = qQ0->as<base::CompoundState>()->as<base::RealVectorStateSpace::StateType>(1); const base::RealVectorStateSpace::StateType *sX1 = qX1->as<base::RealVectorStateSpace::StateType>(); sQ1_SE2->setX(sQ0_SE2->getX()); sQ1_SE2->setY(sQ0_SE2->getY()); sQ1_SE2->setYaw(sQ0_SE2->getYaw()); //[X Y YAW] [1...M-1][M...N-1] // SE2 RN unsigned int M = Q1_dimension_ - X1_dimension_ - 3; unsigned int N = X1_dimension_; for (unsigned int k = 0; k < M; k++) { sQ1_RN->values[k] = sQ0_RM->values[k]; } for (unsigned int k = M; k < M + N; k++) { sQ1_RN->values[k] = sX1->values[k - M]; } break; } case SE3RN_SE3: { base::SE3StateSpace::StateType *sQ1_SE3 = qQ1->as<base::CompoundState>()->as<base::SE3StateSpace::StateType>(0); base::SO3StateSpace::StateType *sQ1_SE3_rotation = &sQ1_SE3->rotation(); base::RealVectorStateSpace::StateType *sQ1_RN = qQ1->as<base::CompoundState>()->as<base::RealVectorStateSpace::StateType>(1); const base::SE3StateSpace::StateType *sQ0 = qQ0->as<base::SE3StateSpace::StateType>(); const base::SO3StateSpace::StateType *sQ0_rotation = &sQ0->rotation(); const base::RealVectorStateSpace::StateType *sX1 = qX1->as<base::RealVectorStateSpace::StateType>(); sQ1_SE3->setXYZ(sQ0->getX(), sQ0->getY(), sQ0->getZ()); sQ1_SE3_rotation->x = sQ0_rotation->x; sQ1_SE3_rotation->y = sQ0_rotation->y; sQ1_SE3_rotation->z = sQ0_rotation->z; sQ1_SE3_rotation->w = sQ0_rotation->w; for (unsigned int k = 0; k < X1_dimension_; k++) { sQ1_RN->values[k] = sX1->values[k]; } break; } case SE3RN_SE3RM: { base::SE3StateSpace::StateType *sQ1_SE3 = qQ1->as<base::CompoundState>()->as<base::SE3StateSpace::StateType>(0); base::SO3StateSpace::StateType *sQ1_SE3_rotation = &sQ1_SE3->rotation(); base::RealVectorStateSpace::StateType *sQ1_RN = qQ1->as<base::CompoundState>()->as<base::RealVectorStateSpace::StateType>(1); const base::SE3StateSpace::StateType *sQ0_SE3 = qQ0->as<base::CompoundState>()->as<base::SE3StateSpace::StateType>(0); const base::SO3StateSpace::StateType *sQ0_SE3_rotation = &sQ0_SE3->rotation(); const base::RealVectorStateSpace::StateType *sQ0_RM = qQ0->as<base::CompoundState>()->as<base::RealVectorStateSpace::StateType>(1); const base::RealVectorStateSpace::StateType *sX1 = qX1->as<base::RealVectorStateSpace::StateType>(); sQ1_SE3->setXYZ(sQ0_SE3->getX(), sQ0_SE3->getY(), sQ0_SE3->getZ()); sQ1_SE3_rotation->x = sQ0_SE3_rotation->x; sQ1_SE3_rotation->y = sQ0_SE3_rotation->y; sQ1_SE3_rotation->z = sQ0_SE3_rotation->z; sQ1_SE3_rotation->w = sQ0_SE3_rotation->w; //[X Y Z YAW PITCH ROLL] [1...M-1][M...N-1] // SE3 RN unsigned int M = Q1_dimension_ - X1_dimension_ - 6; unsigned int N = X1_dimension_; for (unsigned int k = 0; k < M; k++) { sQ1_RN->values[k] = sQ0_RM->values[k]; } for (unsigned int k = M; k < M + N; k++) { sQ1_RN->values[k] = sX1->values[k - M]; } break; } default: { OMPL_ERROR("Type %d not implemented.", type_); throw ompl::Exception("Cannot merge states."); } } } void ompl::geometric::QuotientSpace::projectX1(const base::State *q, base::State *qX1) const { switch (type_) { case RN_RM: { const base::RealVectorStateSpace::StateType *sQ1 = q->as<base::RealVectorStateSpace::StateType>(); base::RealVectorStateSpace::StateType *sX1 = qX1->as<base::RealVectorStateSpace::StateType>(); for (unsigned int k = Q0_dimension_; k < Q1_dimension_; k++) { sX1->values[k - Q0_dimension_] = sQ1->values[k]; } break; } case SE2_R2: { const base::SE2StateSpace::StateType *sQ1 = q->as<base::SE2StateSpace::StateType>(); base::SO2StateSpace::StateType *sX1 = qX1->as<base::SO2StateSpace::StateType>(); sX1->value = sQ1->getYaw(); break; } case SE3_R3: { const base::SE3StateSpace::StateType *sQ1 = q->as<base::SE3StateSpace::StateType>(); const base::SO3StateSpace::StateType *sQ1_SO3 = &sQ1->rotation(); base::SO3StateSpace::StateType *sX1_SO3 = qX1->as<base::SO3StateSpace::StateType>(); sX1_SO3->x = sQ1_SO3->x; sX1_SO3->y = sQ1_SO3->y; sX1_SO3->z = sQ1_SO3->z; sX1_SO3->w = sQ1_SO3->w; break; } case SE3RN_R3: { const base::SE3StateSpace::StateType *sQ1_SE3 = q->as<base::CompoundState>()->as<base::SE3StateSpace::StateType>(0); const base::SO3StateSpace::StateType *sQ1_SO3 = &sQ1_SE3->rotation(); const base::RealVectorStateSpace::StateType *sQ1_RN = q->as<base::CompoundState>()->as<base::RealVectorStateSpace::StateType>(1); base::SO3StateSpace::StateType *sX1_SO3 = qX1->as<base::CompoundState>()->as<base::SO3StateSpace::StateType>(0); base::RealVectorStateSpace::StateType *sX1_RN = qX1->as<base::CompoundState>()->as<base::RealVectorStateSpace::StateType>(1); sX1_SO3->x = sQ1_SO3->x; sX1_SO3->y = sQ1_SO3->y; sX1_SO3->z = sQ1_SO3->z; sX1_SO3->w = sQ1_SO3->w; for (unsigned int k = 0; k < X1_dimension_ - 3; k++) { sX1_RN->values[k] = sQ1_RN->values[k]; } break; } case SE2RN_R2: { const base::SE2StateSpace::StateType *sQ1_SE2 = q->as<base::CompoundState>()->as<base::SE2StateSpace::StateType>(0); const base::RealVectorStateSpace::StateType *sQ1_RN = q->as<base::CompoundState>()->as<base::RealVectorStateSpace::StateType>(1); base::SO2StateSpace::StateType *sX1_SO2 = qX1->as<base::CompoundState>()->as<base::SO2StateSpace::StateType>(0); base::RealVectorStateSpace::StateType *sX1_RN = qX1->as<base::CompoundState>()->as<base::RealVectorStateSpace::StateType>(1); sX1_SO2->value = sQ1_SE2->getYaw(); for (unsigned int k = 0; k < X1_dimension_ - 1; k++) { sX1_RN->values[k] = sQ1_RN->values[k]; } break; } case SE2RN_SE2RM: case SO2RN_SO2RM: { const base::RealVectorStateSpace::StateType *sQ1_RN = q->as<base::CompoundState>()->as<base::RealVectorStateSpace::StateType>(1); const base::RealVectorStateSpace::StateType *sX1 = qX1->as<base::RealVectorStateSpace::StateType>(); unsigned int N = Q1_dimension_ - X1_dimension_ - 3; for (unsigned int k = N; k < Q1_dimension_ - 3; k++) { sX1->values[k - N] = sQ1_RN->values[k]; } break; } case SE2RN_SE2: case SE3RN_SE3: case SO2RN_SO2: { const base::RealVectorStateSpace::StateType *sQ1_RN = q->as<base::CompoundState>()->as<base::RealVectorStateSpace::StateType>(1); base::RealVectorStateSpace::StateType *sX1 = qX1->as<base::RealVectorStateSpace::StateType>(); for (unsigned int k = 0; k < X1_dimension_; k++) { sX1->values[k] = sQ1_RN->values[k]; } break; } case SE3RN_SE3RM: { const base::RealVectorStateSpace::StateType *sQ1_RN = q->as<base::CompoundState>()->as<base::RealVectorStateSpace::StateType>(1); const base::RealVectorStateSpace::StateType *sX1 = qX1->as<base::RealVectorStateSpace::StateType>(); unsigned int N = Q1_dimension_ - X1_dimension_ - 6; for (unsigned int k = N; k < Q1_dimension_ - 6; k++) { sX1->values[k - N] = sQ1_RN->values[k]; } break; } default: { OMPL_ERROR("Type %d not implemented.", type_); throw ompl::Exception("Cannot project onto X1."); } } } void ompl::geometric::QuotientSpace::projectQ0(const base::State *q, base::State *qQ0) const { switch (type_) { case IDENTITY_SPACE_RN: case IDENTITY_SPACE_SE2: case IDENTITY_SPACE_SE2RN: case IDENTITY_SPACE_SO2RN: case IDENTITY_SPACE_SE3: case IDENTITY_SPACE_SE3RN: { // Identity function Q1->getStateSpace()->copyState(qQ0, q); break; } case RN_RM: { const base::RealVectorStateSpace::StateType *sQ1 = q->as<base::RealVectorStateSpace::StateType>(); base::RealVectorStateSpace::StateType *sQ0 = qQ0->as<base::RealVectorStateSpace::StateType>(); for (unsigned int k = 0; k < Q0_dimension_; k++) { sQ0->values[k] = sQ1->values[k]; } break; } case SE2_R2: { const base::SE2StateSpace::StateType *sQ1 = q->as<base::SE2StateSpace::StateType>(); base::RealVectorStateSpace::StateType *sQ0 = qQ0->as<base::RealVectorStateSpace::StateType>(); sQ0->values[0] = sQ1->getX(); sQ0->values[1] = sQ1->getY(); break; } case SE2RN_R2: { const base::SE2StateSpace::StateType *sQ1 = q->as<base::CompoundState>()->as<base::SE2StateSpace::StateType>(0); base::RealVectorStateSpace::StateType *sQ0 = qQ0->as<base::RealVectorStateSpace::StateType>(); sQ0->values[0] = sQ1->getX(); sQ0->values[1] = sQ1->getY(); break; } case SE2RN_SE2: { const base::SE2StateSpace::StateType *sQ1_SE2 = q->as<base::CompoundState>()->as<base::SE2StateSpace::StateType>(0); base::SE2StateSpace::StateType *sQ0_SE2 = qQ0->as<base::SE2StateSpace::StateType>(); sQ0_SE2->setX(sQ1_SE2->getX()); sQ0_SE2->setY(sQ1_SE2->getY()); sQ0_SE2->setYaw(sQ1_SE2->getYaw()); break; } case SO2RN_SO2: { const base::SO2StateSpace::StateType *sQ1_SO2 = q->as<base::CompoundState>()->as<base::SO2StateSpace::StateType>(0); base::SO2StateSpace::StateType *sQ0_SO2 = qQ0->as<base::SO2StateSpace::StateType>(); sQ0_SO2->value = sQ1_SO2->value; break; } case SO2RN_SO2RM: { const base::SO2StateSpace::StateType *sQ1_SO2 = q->as<base::CompoundState>()->as<base::SO2StateSpace::StateType>(0); const base::RealVectorStateSpace::StateType *sQ1_RN = q->as<base::CompoundState>()->as<base::RealVectorStateSpace::StateType>(1); base::SO2StateSpace::StateType *sQ0_SO2 = qQ0->as<base::CompoundState>()->as<base::SO2StateSpace::StateType>(0); base::RealVectorStateSpace::StateType *sQ0_RM = qQ0->as<base::CompoundState>()->as<base::RealVectorStateSpace::StateType>(1); sQ0_SO2->value = sQ1_SO2->value; for (unsigned int k = 0; k < Q0_dimension_ - 1; k++) { sQ0_RM->values[k] = sQ1_RN->values[k]; } break; } case SE2RN_SE2RM: { const base::SE2StateSpace::StateType *sQ1_SE2 = q->as<base::CompoundState>()->as<base::SE2StateSpace::StateType>(0); const base::RealVectorStateSpace::StateType *sQ1_RN = q->as<base::CompoundState>()->as<base::RealVectorStateSpace::StateType>(1); base::SE2StateSpace::StateType *sQ0_SE2 = qQ0->as<base::CompoundState>()->as<base::SE2StateSpace::StateType>(0); base::RealVectorStateSpace::StateType *sQ0_RN = qQ0->as<base::CompoundState>()->as<base::RealVectorStateSpace::StateType>(1); sQ0_SE2->setX(sQ1_SE2->getX()); sQ0_SE2->setY(sQ1_SE2->getY()); sQ0_SE2->setYaw(sQ1_SE2->getYaw()); for (unsigned int k = 0; k < Q0_dimension_ - 3; k++) { sQ0_RN->values[k] = sQ1_RN->values[k]; } break; } case SE3_R3: { const base::SE3StateSpace::StateType *sQ1 = q->as<base::SE3StateSpace::StateType>(); base::RealVectorStateSpace::StateType *sQ0 = qQ0->as<base::RealVectorStateSpace::StateType>(); sQ0->values[0] = sQ1->getX(); sQ0->values[1] = sQ1->getY(); sQ0->values[2] = sQ1->getZ(); break; } case SE3RN_R3: { const base::SE3StateSpace::StateType *sQ1_SE3 = q->as<base::CompoundState>()->as<base::SE3StateSpace::StateType>(0); base::RealVectorStateSpace::StateType *sQ0 = qQ0->as<base::RealVectorStateSpace::StateType>(); sQ0->values[0] = sQ1_SE3->getX(); sQ0->values[1] = sQ1_SE3->getY(); sQ0->values[2] = sQ1_SE3->getZ(); break; } case SE3RN_SE3: { const base::SE3StateSpace::StateType *sQ1_SE3 = q->as<base::CompoundState>()->as<base::SE3StateSpace::StateType>(0); const base::SO3StateSpace::StateType *sQ1_SE3_rotation = &sQ1_SE3->rotation(); base::SE3StateSpace::StateType *sQ0 = qQ0->as<base::SE3StateSpace::StateType>(); base::SO3StateSpace::StateType *sQ0_rotation = &sQ0->rotation(); sQ0->setXYZ(sQ1_SE3->getX(), sQ1_SE3->getY(), sQ1_SE3->getZ()); sQ0_rotation->x = sQ1_SE3_rotation->x; sQ0_rotation->y = sQ1_SE3_rotation->y; sQ0_rotation->z = sQ1_SE3_rotation->z; sQ0_rotation->w = sQ1_SE3_rotation->w; break; } case SE3RN_SE3RM: { const base::SE3StateSpace::StateType *sQ1_SE3 = q->as<base::CompoundState>()->as<base::SE3StateSpace::StateType>(0); const base::SO3StateSpace::StateType *sQ1_SE3_rotation = &sQ1_SE3->rotation(); const base::RealVectorStateSpace::StateType *sQ1_RN = q->as<base::CompoundState>()->as<base::RealVectorStateSpace::StateType>(1); base::SE3StateSpace::StateType *sQ0_SE3 = qQ0->as<base::CompoundState>()->as<base::SE3StateSpace::StateType>(0); base::SO3StateSpace::StateType *sQ0_rotation = &sQ0_SE3->rotation(); base::RealVectorStateSpace::StateType *sQ0_RN = qQ0->as<base::CompoundState>()->as<base::RealVectorStateSpace::StateType>(1); sQ0_SE3->setXYZ(sQ1_SE3->getX(), sQ1_SE3->getY(), sQ1_SE3->getZ()); sQ0_rotation->x = sQ1_SE3_rotation->x; sQ0_rotation->y = sQ1_SE3_rotation->y; sQ0_rotation->z = sQ1_SE3_rotation->z; sQ0_rotation->w = sQ1_SE3_rotation->w; for (unsigned int k = 0; k < Q0_dimension_ - 6; k++) { sQ0_RN->values[k] = sQ1_RN->values[k]; } break; } default: { OMPL_ERROR("Cannot project onto Q0. Type %d not implemented.", type_); throw ompl::Exception("Cannot project onto Q0."); } } } const ompl::base::SpaceInformationPtr &ompl::geometric::QuotientSpace::getX1() const { return X1; } const ompl::base::SpaceInformationPtr &ompl::geometric::QuotientSpace::getQ1() const { return Q1; } const ompl::base::SpaceInformationPtr &ompl::geometric::QuotientSpace::getQ0() const { return Q0; } unsigned int ompl::geometric::QuotientSpace::getX1Dimension() const { return X1_dimension_; } unsigned int ompl::geometric::QuotientSpace::getQ1Dimension() const { return Q1->getStateDimension(); } unsigned int ompl::geometric::QuotientSpace::getDimension() const { return getQ1Dimension(); } unsigned int ompl::geometric::QuotientSpace::getQ0Dimension() const { return Q0_dimension_; } const ompl::base::StateSamplerPtr &ompl::geometric::QuotientSpace::getX1SamplerPtr() const { return X1_sampler_; } const ompl::base::StateSamplerPtr &ompl::geometric::QuotientSpace::getQ1SamplerPtr() const { return Q1_sampler_; } bool ompl::geometric::QuotientSpace::hasSolution() { if (!hasSolution_) { base::PathPtr path; hasSolution_ = getSolution(path); } return hasSolution_; } unsigned int ompl::geometric::QuotientSpace::getTotalNumberOfSamples() const { return totalNumberOfSamples_; } unsigned int ompl::geometric::QuotientSpace::getTotalNumberOfFeasibleSamples() const { return totalNumberOfFeasibleSamples_; } ompl::geometric::QuotientSpace *ompl::geometric::QuotientSpace::getParent() const { return parent_; } ompl::geometric::QuotientSpace *ompl::geometric::QuotientSpace::getChild() const { return child_; } void ompl::geometric::QuotientSpace::setChild(ompl::geometric::QuotientSpace *child) { child_ = child; } void ompl::geometric::QuotientSpace::setParent(ompl::geometric::QuotientSpace *parent) { parent_ = parent; } unsigned int ompl::geometric::QuotientSpace::getLevel() const { return level_; } void ompl::geometric::QuotientSpace::setLevel(unsigned int level) { level_ = level; } ompl::geometric::QuotientSpace::QuotientSpaceType ompl::geometric::QuotientSpace::getType() const { return type_; } ompl::base::OptimizationObjectivePtr ompl::geometric::QuotientSpace::getOptimizationObjectivePtr() const { return opt_; } bool ompl::geometric::QuotientSpace::sampleQuotient(base::State *q_random) { Q1_sampler_->sampleUniform(q_random); return true; } bool ompl::geometric::QuotientSpace::sample(base::State *q_random) { bool valid = false; if (parent_ == nullptr) { // return Q1_valid_sampler->sample(q_random); Q1_sampler_->sampleUniform(q_random); valid = Q1->isValid(q_random); } else { if (X1_dimension_ > 0) { // Adjusted sampling function: Sampling in G0 x X1 X1_sampler_->sampleUniform(s_X1_tmp_); parent_->sampleQuotient(s_Q0_tmp_); mergeStates(s_Q0_tmp_, s_X1_tmp_, q_random); } else { parent_->sampleQuotient(q_random); } valid = Q1->isValid(q_random); } totalNumberOfSamples_++; if (valid) { totalNumberOfFeasibleSamples_++; } return valid; } double ompl::geometric::QuotientSpace::getImportance() const { double N = (double)totalNumberOfSamples_; return 1.0 / (N + 1); } void ompl::geometric::QuotientSpace::print(std::ostream &out) const { out << "[QuotientSpace: id" << id_ << " |lvl" << level_ << "] "; unsigned int sublevel = std::max(1U, level_); if (parent_ == nullptr) { out << "X" << sublevel << "=Q" << sublevel << ": "; if (Q1->getStateSpace()->getType() == base::STATE_SPACE_SE2) { out << "SE(2)"; } else if (Q1->getStateSpace()->getType() == base::STATE_SPACE_SE3) { out << "SE(3)"; } else if (Q1->getStateSpace()->getType() == base::STATE_SPACE_REAL_VECTOR) { out << "R^" << Q1->getStateDimension(); } else { out << "unknown"; } } else { out << "X" << sublevel << "=Q" << sublevel << ": "; switch (type_) { case QuotientSpace::IDENTITY_SPACE_RN: { out << "R^" << Q0_dimension_ << " | Q" << level_ + 1 << ": R^" << Q1_dimension_; break; } case QuotientSpace::IDENTITY_SPACE_SE2: { out << "SE(2)" << " | Q" << level_ + 1 << ": SE(2)"; break; } case QuotientSpace::IDENTITY_SPACE_SE2RN: { out << "SE(2)xR^" << Q0_dimension_ << " | Q" << level_ + 1 << ": SE(2)xR^" << Q1_dimension_; break; } case QuotientSpace::IDENTITY_SPACE_SO2RN: { out << "SO(2)xR^" << Q0_dimension_ << " | Q" << level_ + 1 << ": SO(2)xR^" << Q1_dimension_; break; } case QuotientSpace::IDENTITY_SPACE_SE3: { out << "SE(3)" << " | Q" << level_ + 1 << ": SE(3)"; break; } case QuotientSpace::IDENTITY_SPACE_SE3RN: { out << "SE(3)xR^" << Q0_dimension_ << " | Q" << level_ + 1 << ": SE(3)xR^" << Q1_dimension_; break; } case QuotientSpace::RN_RM: { out << "R^" << Q0_dimension_ << " | Q" << level_ + 1 << ": R^" << Q1_dimension_ << " | X" << level_ + 1 << ": R^" << Q1_dimension_ - Q0_dimension_; break; } case QuotientSpace::SE2_R2: { out << "R^2 | Q" << level_ + 1 << ": SE(2) | X" << level_ + 1 << ": SO(2)"; break; } case QuotientSpace::SE3_R3: { out << "R^3 | Q" << level_ + 1 << ": SE(3) | X" << level_ + 1 << ": SO(3)"; break; } case QuotientSpace::SE2RN_SE2: { out << "SE(2) | Q" << level_ + 1 << ": SE(2)xR^" << X1_dimension_ << " | X" << level_ + 1 << ": R^" << X1_dimension_; break; } case QuotientSpace::SO2RN_SO2: { out << "SO(2) | Q" << level_ + 1 << ": SO(2)xR^" << X1_dimension_ << " | X" << level_ + 1 << ": R^" << X1_dimension_; break; } case QuotientSpace::SE3RN_SE3: { out << "SE(3) | Q" << level_ + 1 << ": SE(3)xR^" << X1_dimension_ << " | X" << level_ + 1 << ": R^" << X1_dimension_; break; } case QuotientSpace::SE2RN_SE2RM: { out << "SE(2)xR^" << Q0_dimension_ - 3 << " | Q" << level_ + 1 << ": SE(2)xR^" << Q1_dimension_ - 3 << " | X" << level_ + 1 << ": R^" << X1_dimension_; break; } case QuotientSpace::SO2RN_SO2RM: { out << "SO(2)xR^" << Q0_dimension_ - 1 << " | Q" << level_ + 1 << ": SO(2)xR^" << Q1_dimension_ - 1 << " | X" << level_ + 1 << ": R^" << X1_dimension_; break; } case QuotientSpace::SE3RN_SE3RM: { out << "SE(3)xR^" << Q0_dimension_ - 6 << " | Q" << level_ + 1 << ": SE(3)xR^" << Q1_dimension_ - 6 << " | X" << level_ + 1 << ": R^" << X1_dimension_; break; } default: { out << "unknown type_: " << type_; } } } out << " [Importance:" << getImportance() << "]"; } namespace ompl { namespace geometric { std::ostream &operator<<(std::ostream &out, const QuotientSpace &quotient_) { quotient_.print(out); return out; } } // namespace geometric } // namespace ompl
34,842
323
/*this creates a yaml or xml list of files from the command line args */ #include "opencv2/core/core.hpp" #include <string> #include <iostream> using std::string; using std::cout; using std::endl; using namespace cv; static void help(char** av) { cout << "\nThis creates a yaml or xml list of files from the command line args\n" "usage:\n./" << av[0] << " imagelist.yaml *.png\n" << "Try using different extensions.(e.g. yaml yml xml xml.gz etc...)\n" << "This will serialize this list of images or whatever with opencv's FileStorage framework" << endl; } int main(int ac, char** av) { if (ac < 3) { help(av); return 1; } string outputname = av[1]; FileStorage fs(outputname, FileStorage::WRITE); fs << "images" << "["; for(int i = 2; i < ac; i++){ fs << string(av[i]); } fs << "]"; return 0; }
327
2,151
// Copyright 2018 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 "base/time/time.h" #ifndef CHROME_BROWSER_CHROMEOS_POWER_ML_BOOT_CLOCK_H_ #define CHROME_BROWSER_CHROMEOS_POWER_ML_BOOT_CLOCK_H_ namespace chromeos { namespace power { namespace ml { // A class that returns time since boot. The time since boot always increases // even when system is suspended (unlike TimeTicks). class BootClock { public: virtual ~BootClock() {} virtual base::TimeDelta GetTimeSinceBoot() = 0; }; } // namespace ml } // namespace power } // namespace chromeos #endif // CHROME_BROWSER_CHROMEOS_POWER_ML_BOOT_CLOCK_H_
242
357
<reponame>debojyoti-majumder/lightwave /* * Copyright © 2018 VMware, Inc. All Rights Reserved. * * 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. */ typedef struct _LWCA_TEST_STATE { PLWCA_DB_FUNCTION_TABLE pFunctionTable; PLWCA_PLUGIN_HANDLE pPluginHandle; PLWCA_DB_HANDLE pDbHandle; } LWCA_TEST_STATE, *PLWCA_TEST_STATE; typedef DWORD (*PLUGIN_ADD_CA)( PLWCA_DB_HANDLE, PCSTR, PLWCA_DB_CA_DATA, PCSTR ); typedef DWORD (*SERIALIZE_CA_JSON)( PCSTR, PLWCA_DB_CA_DATA, PCSTR, PCSTR, PSTR * ); typedef DWORD (*SERIALIZE_CONFIG_CA_JSON)( PCSTR, PCSTR, PSTR * ); typedef DWORD (*DESERIALIZE_JSON_CA)( PCSTR, PLWCA_DB_CA_DATA * ); typedef DWORD (*PLUGIN_CHECK_CA)( PLWCA_DB_HANDLE, PCSTR, PBOOLEAN ); typedef DWORD (*PLUGIN_GET_CA)( PLWCA_DB_HANDLE, PCSTR, PLWCA_DB_CA_DATA * ); typedef DWORD (*PLUGIN_UPDATE_CA)( PLWCA_DB_HANDLE, PCSTR, PLWCA_DB_CA_DATA ); typedef DWORD (*PLUGIN_UPDATE_CA_REQ_BODY)( PLWCA_DB_CA_DATA, PSTR * ); typedef DWORD (*PLUGIN_GET_PARENT_CA)( PLWCA_DB_HANDLE, PCSTR, PSTR * ); typedef DWORD (*JSON_GET_STRING_ATTR)( PCSTR, PCSTR, PSTR * ); typedef DWORD (*SERIALIZE_CERT_DATA_JSON)( PCSTR, PLWCA_DB_CERT_DATA, PCSTR, PSTR * ); typedef DWORD (*PLUGIN_ADD_CERT)( PLWCA_DB_HANDLE, PCSTR, PLWCA_DB_CERT_DATA ); typedef DWORD (*PLUGIN_GET_CERT)( PLWCA_DB_HANDLE, PCSTR, PLWCA_DB_CERT_DATA_ARRAY * ); typedef DWORD (*DESERIALIZE_JSON_CERT_DATA)( PCSTR, PLWCA_DB_CERT_DATA_ARRAY * ); typedef DWORD (*PLUGIN_UPDATE_CERT_REQ_BODY)( PLWCA_DB_CERT_DATA, PSTR * ); typedef DWORD (*PLUGIN_SERIALIZE_LOCK)( PCSTR, ULONG, PSTR * );
1,120
348
<reponame>chamberone/Leaflet.PixiOverlay {"nom":"Assevent","circ":"3ème circonscription","dpt":"Nord","inscrits":1301,"abs":719,"votants":582,"blancs":35,"nuls":11,"exp":536,"res":[{"nuance":"REM","nom":"<NAME>","voix":283},{"nuance":"FN","nom":"Mme <NAME>","voix":253}]}
111
634
<reponame>halotroop2288/consulo<filename>modules/base/vcs-api/src/main/java/com/intellij/openapi/vcs/history/VcsAnnotationCachedProxy.java /* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.vcs.history; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.util.ThrowableComputable; import com.intellij.openapi.vcs.AbstractVcs; import com.intellij.openapi.vcs.FilePath; import com.intellij.openapi.vcs.ProjectLevelVcsManager; import com.intellij.openapi.vcs.VcsException; import com.intellij.openapi.vcs.annotate.AnnotationProvider; import com.intellij.openapi.vcs.annotate.FileAnnotation; import com.intellij.openapi.vcs.annotate.VcsAnnotation; import com.intellij.openapi.vcs.annotate.VcsCacheableAnnotationProvider; import com.intellij.openapi.vcs.changes.ContentRevision; import com.intellij.openapi.vcs.diff.DiffProvider; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.ObjectUtils; import com.intellij.vcsUtil.VcsUtil; import consulo.logging.Logger; import javax.annotation.Nonnull; /** * @author irengrig * Date: 3/17/11 * Time: 7:51 PM */ public class VcsAnnotationCachedProxy implements AnnotationProvider { private final VcsHistoryCache myCache; private final AbstractVcs myVcs; private final static Logger LOG = Logger.getInstance(VcsAnnotationCachedProxy.class); private final AnnotationProvider myAnnotationProvider; public VcsAnnotationCachedProxy(@Nonnull AbstractVcs vcs, @Nonnull AnnotationProvider provider) { assert provider instanceof VcsCacheableAnnotationProvider; myVcs = vcs; myCache = ProjectLevelVcsManager.getInstance(vcs.getProject()).getVcsHistoryCache(); myAnnotationProvider = provider; } @Override public FileAnnotation annotate(final VirtualFile file) throws VcsException { final DiffProvider diffProvider = myVcs.getDiffProvider(); final VcsRevisionNumber currentRevision = diffProvider.getCurrentRevision(file); return annotate(file, currentRevision, true, new ThrowableComputable<FileAnnotation, VcsException>() { @Override public FileAnnotation compute() throws VcsException { return myAnnotationProvider.annotate(file); } }); } @Override public FileAnnotation annotate(final VirtualFile file, final VcsFileRevision revision) throws VcsException { return annotate(file, revision.getRevisionNumber(), false, new ThrowableComputable<FileAnnotation, VcsException>() { @Override public FileAnnotation compute() throws VcsException { return myAnnotationProvider.annotate(file, revision); } }); } @Override public boolean isCaching() { return true; } /** * @param currentRevision - just a hint for optimization */ private FileAnnotation annotate(VirtualFile file, final VcsRevisionNumber revisionNumber, final boolean currentRevision, final ThrowableComputable<FileAnnotation, VcsException> delegate) throws VcsException { final AnnotationProvider annotationProvider = myAnnotationProvider; final FilePath filePath = VcsUtil.getFilePath(file); final VcsCacheableAnnotationProvider cacheableAnnotationProvider = (VcsCacheableAnnotationProvider)annotationProvider; VcsAnnotation vcsAnnotation = null; if (revisionNumber != null) { Object cachedData = myCache.get(filePath, myVcs.getKeyInstanceMethod(), revisionNumber); vcsAnnotation = ObjectUtils.tryCast(cachedData, VcsAnnotation.class); } if (vcsAnnotation != null) { final VcsHistoryProvider historyProvider = myVcs.getVcsHistoryProvider(); final VcsAbstractHistorySession history = getHistory(revisionNumber, filePath, historyProvider, vcsAnnotation.getFirstRevision()); if (history == null) return null; // question is whether we need "not moved" path here? final ContentRevision fileContent = myVcs.getDiffProvider().createFileContent(revisionNumber, file); final FileAnnotation restored = cacheableAnnotationProvider. restore(vcsAnnotation, history, fileContent.getContent(), currentRevision, revisionNumber); if (restored != null) { return restored; } } final FileAnnotation fileAnnotation = delegate.compute(); vcsAnnotation = cacheableAnnotationProvider.createCacheable(fileAnnotation); if (vcsAnnotation == null) return fileAnnotation; if (revisionNumber != null) { myCache.put(filePath, myVcs.getKeyInstanceMethod(), revisionNumber, vcsAnnotation); } if (myVcs.getVcsHistoryProvider() instanceof VcsCacheableHistorySessionFactory) { loadHistoryInBackgroundToCache(revisionNumber, filePath, vcsAnnotation); } return fileAnnotation; } // todo will be removed - when annotation will be presented together with history private void loadHistoryInBackgroundToCache(final VcsRevisionNumber revisionNumber, final FilePath filePath, final VcsAnnotation vcsAnnotation) { ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { @Override public void run() { try { getHistory(revisionNumber, filePath, myVcs.getVcsHistoryProvider(), vcsAnnotation.getFirstRevision()); } catch (VcsException e) { LOG.info(e); } } }); } private VcsAbstractHistorySession getHistory(VcsRevisionNumber revision, FilePath filePath, VcsHistoryProvider historyProvider, @javax.annotation.Nullable final VcsRevisionNumber firstRevision) throws VcsException { final boolean historyCacheSupported = historyProvider instanceof VcsCacheableHistorySessionFactory; if (historyCacheSupported) { final VcsCacheableHistorySessionFactory cacheableHistorySessionFactory = (VcsCacheableHistorySessionFactory)historyProvider; final VcsAbstractHistorySession cachedSession = myCache.getMaybePartial(filePath, myVcs.getKeyInstanceMethod(), cacheableHistorySessionFactory); if (cachedSession != null && ! cachedSession.getRevisionList().isEmpty()) { final VcsFileRevision recentRevision = cachedSession.getRevisionList().get(0); if (recentRevision.getRevisionNumber().compareTo(revision) >= 0 && (firstRevision == null || cachedSession.getHistoryAsMap().containsKey(firstRevision))) { return cachedSession; } } } // history may be also cut final VcsAbstractHistorySession sessionFor; if (firstRevision != null) { sessionFor = limitedHistory(filePath, firstRevision); } else { sessionFor = (VcsAbstractHistorySession) historyProvider.createSessionFor(filePath); } if (sessionFor != null && historyCacheSupported) { final VcsCacheableHistorySessionFactory cacheableHistorySessionFactory = (VcsCacheableHistorySessionFactory)historyProvider; final FilePath correctedPath = cacheableHistorySessionFactory.getUsedFilePath(sessionFor); myCache.put(filePath, correctedPath, myVcs.getKeyInstanceMethod(), sessionFor, cacheableHistorySessionFactory, firstRevision == null); } return sessionFor; } @Override public boolean isAnnotationValid(@Nonnull VcsFileRevision rev) { return myAnnotationProvider.isAnnotationValid(rev); } private VcsAbstractHistorySession limitedHistory(final FilePath filePath, @Nonnull final VcsRevisionNumber firstNumber) throws VcsException { final VcsAbstractHistorySession[] result = new VcsAbstractHistorySession[1]; final VcsException[] exc = new VcsException[1]; try { myVcs.getVcsHistoryProvider().reportAppendableHistory(filePath, new VcsAppendableHistorySessionPartner() { @Override public void reportCreatedEmptySession(VcsAbstractHistorySession session) { result[0] = session; } @Override public void acceptRevision(VcsFileRevision revision) { result[0].appendRevision(revision); if (firstNumber.equals(revision.getRevisionNumber())) throw new ProcessCanceledException(); } @Override public void reportException(VcsException exception) { exc[0] = exception; } @Override public void finished() { } @Override public void beforeRefresh() { } @Override public void forceRefresh() { } }); } catch (ProcessCanceledException e) { // ok } if (exc[0] != null) { throw exc[0]; } return result[0]; } }
3,219
348
<reponame>chamberone/Leaflet.PixiOverlay {"nom":"<NAME>","circ":"3ème circonscription","dpt":"Aisne","inscrits":191,"abs":82,"votants":109,"blancs":7,"nuls":1,"exp":101,"res":[{"nuance":"SOC","nom":"<NAME>","voix":52},{"nuance":"FN","nom":"<NAME>","voix":49}]}
109
602
<filename>decompiler/IR2/ExpressionHelpers.h #pragma once #include <vector> namespace decompiler { class FormElement; class Form; class Env; class FormPool; class FormStack; FormElement* handle_get_property_value_float(const std::vector<Form*>& forms, FormPool& pool, const Env& env); FormElement* handle_get_property_data(const std::vector<Form*>& forms, FormPool& pool, const Env& env); FormElement* handle_get_property_struct(const std::vector<Form*>& forms, FormPool& pool, const Env& env); FormElement* handle_get_property_value(const std::vector<Form*>& forms, FormPool& pool, const Env& env); FormElement* last_two_in_and_to_handle_get_proc(Form* first, Form* second, const Env& env, FormPool& pool, FormStack& stack, bool part_of_longer_sc); } // namespace decompiler
827
306
<reponame>Ross1503/Brunel<gh_stars>100-1000 /* * Copyright (c) 2015 IBM Corporation and others. * * Licensed under the Apache License, Version 2.0 (the "License"); * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.brunel.maps.projection; import org.brunel.geom.Point; import org.brunel.geom.Rect; /** * Suitable for whole-world projection, cannot be inverted */ class WinkelTripel extends Projection { public String d3Definition(Rect bounds) { Rect ext = transform(bounds); // Finding the center is tricky because we cannot invert the transform so we have to search for it // We just do a grid search; Slow, but simple. First by y (using the center as the x, then by x double y = 0, dy = 9e99; for (int i = -90; i < 90; i++) { Point p = transform(new Point(bounds.cx(), i)); double dp = Math.abs(p.y - ext.cy()); if (dp < dy) { dy = dp; y = i; } } double x = 0, dx = 9e99; for (int i = -180; i < 180; i++) { Point p = transform(new Point(i, y)); double dp = Math.abs(p.x - ext.cx()); if (dp < dx) { dx = dp; x = i; } } String center = ".center([" + F.format(x) + ", " + F.format(y) + "])"; return "BrunelD3.winkel3()" + LN + translateDefinition() + LN + scaleDefinition(ext) + LN + center; } public Point transform(Point p) { double x = Math.toRadians(p.x); double y = Math.toRadians(p.y); double a = Math.acos(Math.cos(y) * Math.cos(x / 2)); double sinca = Math.abs(a) < 1e-6 ? 1 : Math.sin(a) / a; return new Point(Math.cos(y) * Math.sin(x / 2) / sinca + x / Math.PI, (Math.sin(y) * sinca + y) / 2); } public Point inverse(Point p) { throw new UnsupportedOperationException("Inverse not available for Winkel Triple"); } }
1,073
2,081
<filename>tools/iotjs-create-module.py #!/usr/bin/env python # Copyright 2018-present Samsung Electronics Co., Ltd. and other contributors # # 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. from __future__ import print_function import os import re IOTJS_BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) TEMPLATE_BASE_DIR = os.path.join(os.path.dirname(__file__), 'module_templates') MODULE_NAME_RE = "^[a-z0-9][a-z0-9\._]*$" def load_templates(template_dir): for root, dirs, files in os.walk(template_dir): for fp in files: yield os.path.relpath(os.path.join(root, fp), template_dir) def replace_contents(input_file, module_name): with open(input_file) as fp: data = fp.read() data = data.replace("$MODULE_NAME$", module_name) data = data.replace("$IOTJS_PATH$", IOTJS_BASE_DIR) return data def create_module(output_dir, module_name, template_dir, template_files): module_path = os.path.join(output_dir, module_name) print("Creating module in {}".format(module_path)) if os.path.exists(module_path): print("Module path ({}) already exists! Exiting".format(module_path)) return False for file_name in template_files: file_path = os.path.join(template_dir, file_name) print("loading template file: {}".format(file_path)) contents = replace_contents(file_path, module_name) output_path = os.path.join(module_path, file_name) # create sub-dir if required base_dir = os.path.dirname(output_path) if not os.path.exists(base_dir): os.mkdir(base_dir) with open(output_path, "w") as fp: fp.write(contents) return True def valid_module_name(value): if not re.match(MODULE_NAME_RE, value): msg = "Invalid module name, should match regexp: %s" % MODULE_NAME_RE raise argparse.ArgumentTypeError(msg) return value if __name__ == "__main__": import argparse import sys desc = "Create an IoT.js external module using a template" parser = argparse.ArgumentParser(description=desc) parser.add_argument("module_name", metavar="<MODULE NAME>", nargs=1, type=valid_module_name, help="name of the new module ((must be in lowercase " + "and should match regexp: %s)" % MODULE_NAME_RE) parser.add_argument("--path", default=".", help="directory where the module will be created " + "(default: %(default)s)") parser.add_argument("--template", default="basic", choices=["basic", "shared"], help="type of the template which should be used " "(default: %(default)s)") args = parser.parse_args() template_dir = os.path.join(TEMPLATE_BASE_DIR, "%s_module_template" % args.template) template_files = load_templates(template_dir) created = create_module(args.path, args.module_name[0], template_dir, template_files) if created: module_path = os.path.join(args.path, args.module_name[0]) print("Module created in: {}".format(os.path.abspath(module_path)))
1,618
852
<reponame>ckamtsikis/cmssw import FWCore.ParameterSet.Config as cms l1tBasicDemo = cms.EDAnalyzer( "L1TBasicDemo", UseTriggerBxOnly = cms.bool(True), EgTag = cms.InputTag("caloStage2Digis","EGamma"), TauTag = cms.InputTag("caloStage2Digis","Tau"), JetTag = cms.InputTag("caloStage2Digis","Jet"), SumTag = cms.InputTag("caloStage2Digis","EtSum"), MuonTag = cms.InputTag("gmtStage2Digis", "Muon"), )
243
1,082
<reponame>gaoml0904/GmlPhoneEdit /* * Copyright (C) 2016 jarlen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package cn.jarlen.photoedit.filters; /** * @author jarlen */ public class FilterType { public static final int BeitaOfWhiteLOG = 1313; /** * 灰效果 */ public static final int FILTER4GRAY = 1314; /** * 马赛克效果 */ public static final int FILTER4MOSATIC = 1315; /** * 怀旧效果 */ public static final int FILTER4NOSTALGIC = 1316; /** * LOMO 效果 */ public static final int FILTER4LOMO = 1317; /** * 连环画效果 Comics */ public static final int FILTER4COMICS = 1318; /** * * 黑白效果 * */ public static final int FILTER4BlackWhite = 1319; /** * * 反色(底片)效果 */ public static final int FILTER4NEGATIVE = 1320; /** * * 流年风格 */ public static final int FILTER4BROWN = 1321; /** * * 素描效果---铅笔画 * */ public static final int FILTER4SKETCH_PENCIL = 1322; public static final int FILTER4COLORSKETCH = 1324; /** * * 过度曝光 * */ public static final int FILTER4OVEREXPOSURE = 1323; /** * log曲线美白效果 */ public static final int FILTER4WHITELOG = 1325; public static final int FILTER4CONTRAST_LIGHT = 1327; /** * 柔化 * */ public static final int FILTER4SOFTNESS = 1328; /** * 霓虹 * */ public static final int FILTER4NiHong = 1329; /** * 素描 */ public static final int FILTER4SKETCH = 1330; /** * 雕刻 * */ public static final int FILTER4CARVING = 1331; /** * 浮雕 * */ public static final int FILTER4RELIEF = 1332; /** * * 锐化 */ public static final int FILTER4RUIHUA = 1333; }
918
5,133
/* * Copyright MapStruct Authors. * * Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0 */ package org.mapstruct.ap.test.bugs._2347; import org.mapstruct.ap.testutil.IssueKey; import org.mapstruct.ap.testutil.ProcessorTest; import org.mapstruct.ap.testutil.WithClasses; import org.mapstruct.ap.testutil.compilation.annotation.CompilationResult; import org.mapstruct.ap.testutil.compilation.annotation.Diagnostic; import org.mapstruct.ap.testutil.compilation.annotation.ExpectedCompilationOutcome; /** * @author <NAME> */ @IssueKey("2347") @WithClasses({ ErroneousClassWithPrivateMapper.class }) public class Issue2347Test { @ExpectedCompilationOutcome(value = CompilationResult.FAILED, diagnostics = { @Diagnostic( type = ErroneousClassWithPrivateMapper.class, kind = javax.tools.Diagnostic.Kind.ERROR, line = 41, message = "Cannot create an implementation for mapper PrivateInterfaceMapper," + " because it is a private interface." ), @Diagnostic( type = ErroneousClassWithPrivateMapper.class, kind = javax.tools.Diagnostic.Kind.ERROR, line = 47, message = "Cannot create an implementation for mapper PrivateClassMapper," + " because it is a private class." ) } ) @ProcessorTest public void shouldGenerateCompileErrorWhenMapperIsPrivate() { } }
654
808
<gh_stars>100-1000 #ifndef SYMENGINE_UTILITIES_MATCHPYCPP_HOPCROFT_KARP_H_ #define SYMENGINE_UTILITIES_MATCHPYCPP_HOPCROFT_KARP_H_ #include <vector> #include <map> #include <iostream> #include <tuple> #include <deque> #include <set> #include <climits> using namespace std; /* * Implementation of the Hopcroft-Karp algorithm on a bipartite graph. * * The bipartite graph has types TLeft and TRight on the two partitions. * * The constructor accepts a `map` mapping the left vertices to the set of * connected right vertices. * * The method `.hopcroft_karp()` finds the maximum cardinality matching, * returning its cardinality. The matching will be stored in the file * `pair_left` * and `pair_right` after the matching is found. */ template <typename TLeft, typename TRight> class HopcroftKarp { public: HopcroftKarp(map<TLeft, set<TRight>> &_graph_left) : _graph_left(_graph_left) { reference_distance = INT_MAX; get_left_indices_vector(_graph_left); } int hopcroft_karp() { pair_left.clear(); pair_right.clear(); dist_left.clear(); for (const TLeft &left : _left) { dist_left[left] = INT_MAX; } int matchings = 0; while (true) { if (!_bfs_hopcroft_karp()) break; for (const TLeft &left : _left) { if (pair_left.find(left) != pair_left.end()) { continue; } if (_dfs_hopcroft_karp(left)) { matchings++; } } } return matchings; } map<TLeft, TRight> pair_left; map<TRight, TLeft> pair_right; private: vector<TLeft> _left; map<TLeft, set<TRight>> _graph_left; map<TLeft, int> dist_left; int reference_distance; void get_left_indices_vector(const map<TLeft, set<TRight>> &m) { _left.reserve(m.size()); for (const pair<const TLeft, set<TRight>> &p : m) { _left.push_back(p.first); } } bool _bfs_hopcroft_karp() { deque<TLeft> vertex_queue; for (const TLeft &left_vert : _left) { if (pair_left.find(left_vert) == pair_left.end()) { vertex_queue.push_back(left_vert); dist_left[left_vert] = 0; } else { dist_left[left_vert] = INT_MAX; } } reference_distance = INT_MAX; while (true) { if (vertex_queue.empty()) break; TLeft &left_vertex = vertex_queue.front(); vertex_queue.pop_front(); if (dist_left.at(left_vertex) >= reference_distance) continue; for (const TRight &right_vertex : _graph_left.at(left_vertex)) { if (pair_right.find(right_vertex) == pair_right.end()) { if (reference_distance == INT_MAX) { reference_distance = dist_left[left_vertex] + 1; } } else { TLeft &other_left = pair_right.at(right_vertex); if (dist_left.at(other_left) == INT_MAX) { dist_left[other_left] = dist_left[left_vertex] + 1; vertex_queue.push_back(other_left); } } } } return reference_distance < INT_MAX; } inline void swap_lr(const TLeft &left, const TRight &right) { pair_left[left] = right; pair_right[right] = left; } bool _dfs_hopcroft_karp(const TLeft &left) { for (const TRight &right : _graph_left.at(left)) { if (pair_right.find(right) == pair_right.end()) { if (reference_distance == dist_left.at(left) + 1) { swap_lr(left, right); return true; } } else { TLeft &other_left = pair_right.at(right); if (dist_left.at(other_left) == dist_left.at(left) + 1) { if (_dfs_hopcroft_karp(other_left)) { swap_lr(left, right); return true; } } } } dist_left[left] = INT_MAX; return false; } }; #endif /* SYMENGINE_UTILITIES_MATCHPYCPP_HOPCROFT_KARP_H_ */
2,322
539
<reponame>tenomoto/optim /*################################################################################ ## ## Copyright (C) 2016-2020 <NAME> ## ## This file is part of the OptimLib C++ library. ## ## 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 OPTIMLIB_TEST_INCLUDES #define OPTIMLIB_TEST_INCLUDES using optim::Vec_t; using optim::Mat_t; #define OPTIM_PI 3.14159265358979 #include "unconstr_test_fn_1.hpp" #include "unconstr_test_fn_2.hpp" #include "unconstr_test_fn_3.hpp" #include "unconstr_test_fn_4.hpp" #include "unconstr_test_fn_5.hpp" #include "unconstr_test_fn_6.hpp" #include "unconstr_test_fn_7.hpp" #include "unconstr_test_fn_8.hpp" #include "unconstr_test_fn_9.hpp" #include "unconstr_test_fn_10.hpp" #include "constr_test_fn_1.hpp" #include "constr_test_fn_2.hpp" #include "constr_test_fn_3.hpp" #include "zeros_test_fn_1.hpp" #include "zeros_test_fn_2.hpp" #include "test_solutions.hpp" #endif
571
709
<reponame>emadurandal/OpenSiv3D //----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2021 <NAME> // Copyright (c) 2016-2021 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # include <Siv3D/Physics2D/P2Circle.hpp> # include "P2Common.hpp" namespace s3d { P2Circle::P2Circle(b2Body& body, const Circle& circle, const P2Material& material, const P2Filter& filter, const bool isSensor) : m_pShape{ std::make_unique<b2CircleShape>() } { m_pShape->m_radius = static_cast<float>(circle.r); m_pShape->m_p.Set(static_cast<float>(circle.x), static_cast<float>(circle.y)); const b2FixtureDef fixtureDef = detail::MakeFixtureDef(m_pShape.get(), material, filter, isSensor); m_fixtures.push_back(body.CreateFixture(&fixtureDef)); } P2ShapeType P2Circle::getShapeType() const noexcept { return P2ShapeType::Circle; } const P2Shape& P2Circle::draw(const ColorF& color) const { getCircle().draw(color); return *this; } const P2Shape& P2Circle::drawFrame(const double thickness, const ColorF& color) const { getCircle().drawFrame(detail::AdjustThickness(thickness), color); return *this; } const P2Shape& P2Circle::drawWireframe(double thickness, const ColorF& color) const { const Circle circle = getCircle(); const double angle = m_fixtures.front()->GetBody()->GetAngle(); thickness = detail::AdjustThickness(thickness); circle.drawFrame(thickness, color); Line{ circle.center, circle.getPointByAngle(angle) }.draw(thickness, color); return *this; } Circle P2Circle::getCircle() const { return{ detail::CalcVec2(m_pShape->m_p, m_fixtures.front()->GetBody()->GetTransform()), m_pShape->m_radius }; } }
662
1,056
<reponame>arusinha/incubator-netbeans<filename>ide/properties/src/org/netbeans/modules/properties/FindPanel.java /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.properties; import java.awt.event.KeyEvent; import java.awt.event.KeyAdapter; import java.awt.ContainerOrderFocusTraversalPolicy; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import org.openide.util.NbBundle; /** * Find panel for Resource Bundles table view component. GUI represenation only. * * @author <NAME> */ public class FindPanel extends javax.swing.JPanel { /** Creates new form FindPanel. */ public FindPanel() { initComponents (); initAccessibility (); findCombo.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() { public void keyTyped(KeyEvent evt) { if (evt.getKeyChar() == '\n') { findButton.doClick(20); evt.consume(); } } }); } private String getBundleString(String s){ return NbBundle.getMessage(FindPanel.class, s); } // Accessor methods. /** Accessor to buttons. */ public JButton[] getButtons() { return new JButton[] { findButton, cancelButton}; } /** Accessor to combo box. */ public JComboBox getComboBox() { return findCombo; } /** Accessor to highlight check box. */ public JCheckBox getHighlightCheck() { return highlightCheck; } /** Accessor to match case check box. */ public JCheckBox getMatchCaseCheck() { return matchCaseCheck; } /** Accessor to backward check box. */ public JCheckBox getBackwardCheck() { return backwardCheck; } /** Accessor to wrap check box. */ public JCheckBox getWrapCheck() { return wrapCheck; } /** Accessor to row check box. */ public JCheckBox getRowCheck() { return rowCheck; } private void initAccessibility () { this.getAccessibleContext().setAccessibleDescription(getBundleString("ACS_FindPanel")); findButton.getAccessibleContext().setAccessibleDescription(getBundleString("ACS_CTL_Find")); rowCheck.getAccessibleContext().setAccessibleDescription(getBundleString("ACS_CTL_SearchByRows")); wrapCheck.getAccessibleContext().setAccessibleDescription(getBundleString("ACS_CTL_WrapSearch")); matchCaseCheck.getAccessibleContext().setAccessibleDescription(getBundleString("ACS_CTL_MatchCaseCheck")); cancelButton.getAccessibleContext().setAccessibleDescription(getBundleString("ACS_CTL_Cancel")); backwardCheck.getAccessibleContext().setAccessibleDescription(getBundleString("ACS_CTL_BackwardCheck")); findCombo.getAccessibleContext().setAccessibleDescription(getBundleString("ACS_CTL_FindCombo")); highlightCheck.getAccessibleContext().setAccessibleDescription(getBundleString("ACS_CTL_HighlightCheck")); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; findLabel = new javax.swing.JLabel(); findCombo = new javax.swing.JComboBox(); highlightCheck = new javax.swing.JCheckBox(); matchCaseCheck = new javax.swing.JCheckBox(); backwardCheck = new javax.swing.JCheckBox(); wrapCheck = new javax.swing.JCheckBox(); rowCheck = new javax.swing.JCheckBox(); findButton = new javax.swing.JButton(); cancelButton = new javax.swing.JButton(); setFocusCycleRoot(true); setFocusTraversalPolicy(new ContainerOrderFocusTraversalPolicy()); setLayout(new java.awt.GridBagLayout()); findLabel.setLabelFor(findCombo); org.openide.awt.Mnemonics.setLocalizedText(findLabel, getBundleString("LBL_Find")); // NOI18N findLabel.setFocusable(false); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(12, 12, 0, 0); add(findLabel, gridBagConstraints); findCombo.setEditable(true); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(12, 11, 0, 0); add(findCombo, gridBagConstraints); org.openide.awt.Mnemonics.setLocalizedText(highlightCheck, getBundleString("CTL_HighlightCheck")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.gridwidth = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 12, 0, 0); add(highlightCheck, gridBagConstraints); org.openide.awt.Mnemonics.setLocalizedText(matchCaseCheck, getBundleString("CTL_MatchCaseCheck")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.gridwidth = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTHWEST; gridBagConstraints.insets = new java.awt.Insets(0, 12, 0, 0); add(matchCaseCheck, gridBagConstraints); org.openide.awt.Mnemonics.setLocalizedText(backwardCheck, getBundleString("CTL_BackwardCheck")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.gridwidth = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 12, 11, 0); add(backwardCheck, gridBagConstraints); org.openide.awt.Mnemonics.setLocalizedText(wrapCheck, getBundleString("CTL_WrapSearch")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 12, 0, 0); add(wrapCheck, gridBagConstraints); org.openide.awt.Mnemonics.setLocalizedText(rowCheck, getBundleString("CTL_SearchByRows")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 11, 0, 0); add(rowCheck, gridBagConstraints); findButton.setText(getBundleString("CTL_Find")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints.insets = new java.awt.Insets(12, 11, 0, 11); add(findButton, gridBagConstraints); cancelButton.setText(getBundleString("CTL_Cancel")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHEAST; gridBagConstraints.insets = new java.awt.Insets(5, 11, 0, 11); add(cancelButton, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents public boolean requestFocusInWindow() { return findCombo.requestFocusInWindow(); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JCheckBox backwardCheck; private javax.swing.JButton cancelButton; private javax.swing.JButton findButton; private javax.swing.JComboBox findCombo; private javax.swing.JLabel findLabel; private javax.swing.JCheckBox highlightCheck; private javax.swing.JCheckBox matchCaseCheck; private javax.swing.JCheckBox rowCheck; private javax.swing.JCheckBox wrapCheck; // End of variables declaration//GEN-END:variables }
4,011
458
<gh_stars>100-1000 // Copyright 2015-2021 Swim Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package swim.structure; import java.math.BigInteger; import swim.codec.Format; import swim.codec.Output; import swim.codec.OutputSettings; import swim.util.HashGenCacheMap; public class Text extends Value { protected final String value; protected Text(String value) { this.value = value; } @Override public boolean isConstant() { return true; } public int size() { return this.value.length(); } @Override public String stringValue() { return this.value; } @Override public String stringValue(String orElse) { return this.value; } @Override public byte byteValue() { try { return Byte.parseByte(this.value); } catch (NumberFormatException cause) { throw new UnsupportedOperationException(cause); } } @Override public byte byteValue(byte orElse) { try { return Byte.parseByte(this.value); } catch (NumberFormatException cause) { return orElse; } } @Override public short shortValue() { try { return Short.parseShort(this.value); } catch (NumberFormatException cause) { throw new UnsupportedOperationException(cause); } } @Override public short shortValue(short orElse) { try { return Short.parseShort(this.value); } catch (NumberFormatException cause) { return orElse; } } @Override public int intValue() { try { return Integer.parseInt(this.value); } catch (NumberFormatException cause) { throw new UnsupportedOperationException(cause); } } @Override public int intValue(int orElse) { try { return Integer.parseInt(this.value); } catch (NumberFormatException cause) { return orElse; } } @Override public long longValue() { try { return Long.parseLong(this.value); } catch (NumberFormatException cause) { throw new UnsupportedOperationException(cause); } } @Override public long longValue(long orElse) { try { return Long.parseLong(this.value); } catch (NumberFormatException cause) { return orElse; } } @Override public float floatValue() { try { return Float.parseFloat(this.value); } catch (NumberFormatException cause) { throw new UnsupportedOperationException(cause); } } @Override public float floatValue(float orElse) { try { return Float.parseFloat(this.value); } catch (NumberFormatException cause) { return orElse; } } @Override public double doubleValue() { try { return Double.parseDouble(this.value); } catch (NumberFormatException cause) { throw new UnsupportedOperationException(cause); } } @Override public double doubleValue(double orElse) { try { return Double.parseDouble(this.value); } catch (NumberFormatException cause) { return orElse; } } @Override public BigInteger integerValue() { try { return new BigInteger(this.value); } catch (NumberFormatException cause) { throw new UnsupportedOperationException(cause); } } @Override public BigInteger integerValue(BigInteger orElse) { try { return new BigInteger(this.value); } catch (NumberFormatException cause) { return orElse; } } @Override public Number numberValue() { return Num.from(this.value).numberValue(); } @Override public Number numberValue(Number orElse) { try { return Num.from(this.value).numberValue(); } catch (NumberFormatException cause) { return orElse; } } @Override public char charValue() { if (this.value.length() == 1) { return this.value.charAt(0); } else { throw new UnsupportedOperationException(); } } @Override public char charValue(char orElse) { try { return this.charValue(); } catch (UnsupportedOperationException cause) { return orElse; } } @Override public boolean booleanValue() { if ("true".equals(this.value)) { return true; } else if ("false".equals(this.value)) { return false; } else { throw new UnsupportedOperationException(); } } @Override public boolean booleanValue(boolean orElse) { if ("true".equals(this.value)) { return true; } else if ("false".equals(this.value)) { return false; } else { return orElse; } } @Override public Value plus(Value that) { if (that instanceof Text) { return this.plus((Text) that); } return super.plus(that); } public Text plus(Text that) { return Text.from(this.value + that.value); } @Override public Text branch() { return this; } @Override public Text commit() { return this; } @Override public int typeOrder() { return 5; } @Override public final int compareTo(Item other) { if (other instanceof Text) { return this.value.compareTo(((Text) other).value); } return Integer.compare(this.typeOrder(), other.typeOrder()); } @Override public final boolean equals(Object other) { if (this == other) { return true; } else if (other instanceof Text) { final Text that = (Text) other; return this.value.equals(that.value); } return false; } @Override public final int hashCode() { // Text hashCode *must* equal String hashCode to ensure that RecordMap // hashtable lookups work with String keys. return this.value.hashCode(); } @Override public <T> Output<T> debug(Output<T> output) { output = output.write("Text").write('.'); if (this.value.length() == 0) { output = output.write("empty").write('(').write(')'); } else { output = output.write("from").write('(').debug(this.value).write(')'); } return output; } @Override public <T> Output<T> display(Output<T> output) { return Format.debug(output, this.value); } private static Text empty; public static Text empty() { if (Text.empty == null) { Text.empty = new Text(""); } return Text.empty; } public static Text from(String value) { final int n = value.length(); if (n == 0) { return Text.empty(); } else if (n <= 64) { final HashGenCacheMap<String, Text> cache = Text.cache(); Text text = cache.get(value); if (text == null) { text = cache.put(value, new Text(value)); } return text; } else { return new Text(value); } } public static Text fromObject(Object object) { if (object instanceof Text) { return (Text) object; } else if (object instanceof String) { return Text.from((String) object); } else { throw new IllegalArgumentException(object.toString()); } } public static Output<Text> output(OutputSettings settings) { return new TextOutput(new StringBuilder(), settings); } public static Output<Text> output() { return new TextOutput(new StringBuilder(), OutputSettings.standard()); } private static ThreadLocal<HashGenCacheMap<String, Text>> cache = new ThreadLocal<>(); static HashGenCacheMap<String, Text> cache() { HashGenCacheMap<String, Text> cache = Text.cache.get(); if (cache == null) { int cacheSize; try { cacheSize = Integer.parseInt(System.getProperty("swim.structure.text.cache.size")); } catch (NumberFormatException e) { cacheSize = 128; } cache = new HashGenCacheMap<String, Text>(cacheSize); Text.cache.set(cache); } return cache; } }
2,915
1,475
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.cache.operations; /** * Encapsulates a region-level operation in both the pre-operation and post-operation cases. The * operations this class encapsulates are * {@link org.apache.geode.cache.operations.OperationContext.OperationCode#REGION_CLEAR} and * {@link org.apache.geode.cache.operations.OperationContext.OperationCode#REGION_DESTROY}. * * @since GemFire 5.5 * @deprecated since Geode1.0, use {@link org.apache.geode.security.ResourcePermission} instead */ public abstract class RegionOperationContext extends OperationContext { /** Callback object for the operation (if any) */ private Object callbackArg; /** True if this is a post-operation context */ private boolean postOperation; /** * Constructor for a region operation. * * @param postOperation true to set the post-operation flag */ public RegionOperationContext(boolean postOperation) { this.callbackArg = null; this.postOperation = postOperation; } /** * Return the operation associated with the <code>OperationContext</code> object. * * @return The <code>OperationCode</code> of this operation. This is one of * {@link org.apache.geode.cache.operations.OperationContext.OperationCode#REGION_CLEAR} * or * {@link org.apache.geode.cache.operations.OperationContext.OperationCode#REGION_DESTROY}. */ @Override public abstract OperationCode getOperationCode(); /** * True if the context is for post-operation. */ @Override public boolean isPostOperation() { return this.postOperation; } /** * Get the callback argument object for this operation. * * @return the callback argument object for this operation. */ public Object getCallbackArg() { return this.callbackArg; } /** * Set the callback argument object for this operation. * * @param callbackArg the callback argument object for this operation. */ public void setCallbackArg(Object callbackArg) { this.callbackArg = callbackArg; } }
801
2,151
<reponame>zipated/src<filename>chrome/browser/chromeos/login/enrollment/enrollment_screen_unittest.cc // Copyright (c) 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. #include "chrome/browser/chromeos/login/enrollment/enrollment_screen.h" #include "base/bind.h" #include "base/callback.h" #include "base/command_line.h" #include "base/test/scoped_mock_time_message_loop_task_runner.h" #include "base/test/scoped_task_environment.h" #include "base/threading/thread_task_runner_handle.h" #include "chrome/browser/chromeos/login/enrollment/enterprise_enrollment_helper.h" #include "chrome/browser/chromeos/login/enrollment/enterprise_enrollment_helper_mock.h" #include "chrome/browser/chromeos/login/enrollment/mock_enrollment_screen.h" #include "chrome/browser/chromeos/login/screens/mock_base_screen_delegate.h" #include "chrome/browser/chromeos/policy/device_cloud_policy_manager_chromeos.h" #include "chrome/browser/chromeos/policy/enrollment_config.h" #include "chrome/browser/chromeos/policy/enrollment_status_chromeos.h" #include "chrome/test/base/testing_browser_process.h" #include "chromeos/chromeos_switches.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "components/pairing/fake_controller_pairing_controller.h" #include "testing/gtest/include/gtest/gtest.h" using testing::_; using testing::AnyNumber; using testing::Invoke; namespace chromeos { class EnrollmentScreenUnitTest : public testing::Test { public: EnrollmentScreenUnitTest() : fake_controller_("") {} // Creates the EnrollmentScreen and sets required parameters. virtual void SetUpEnrollmentScreen() { enrollment_screen_.reset( new EnrollmentScreen(&mock_delegate_, &mock_view_)); enrollment_screen_->SetParameters(enrollment_config_, &fake_controller_); } // Fast forwards time by the specified amount. void FastForwardTime(base::TimeDelta time) { runner_.task_runner()->FastForwardBy(time); } MockBaseScreenDelegate* GetBaseScreenDelegate() { return &mock_delegate_; } MockEnrollmentScreenView* GetMockScreenView() { return &mock_view_; } // testing::Test: void SetUp() override { // Initialize the thread manager. DBusThreadManager::Initialize(); } void TearDown() override { TestingBrowserProcess::GetGlobal()->SetShuttingDown(true); DBusThreadManager::Shutdown(); } protected: std::unique_ptr<EnrollmentScreen> enrollment_screen_; policy::EnrollmentConfig enrollment_config_; private: base::test::ScopedTaskEnvironment scoped_task_environment_; // Replace main thread's task runner with a mock for duration of test. base::ScopedMockTimeMessageLoopTaskRunner runner_; // Objects required by the EnrollmentScreen that can be re-used. pairing_chromeos::FakeControllerPairingController fake_controller_; MockBaseScreenDelegate mock_delegate_; MockEnrollmentScreenView mock_view_; DISALLOW_COPY_AND_ASSIGN(EnrollmentScreenUnitTest); }; class ZeroTouchEnrollmentScreenUnitTest : public EnrollmentScreenUnitTest { public: ZeroTouchEnrollmentScreenUnitTest() = default; enum AttestationEnrollmentStatus { SUCCESS, DEVICE_NOT_SETUP_FOR_ZERO_TOUCH, DMSERVER_ERROR }; // Closure passed to EnterpriseEnrollmentHelper::SetupEnrollmentHelperMock // which creates the EnterpriseEnrollmentHelperMock object that will // eventually be tied to the EnrollmentScreen. It also sets up the // appropriate expectations for testing with the Google Mock framework. // The template parameter should_enroll indicates whether or not // the EnterpriseEnrollmentHelper should be mocked to successfully enroll. template <AttestationEnrollmentStatus status> static EnterpriseEnrollmentHelper* MockEnrollmentHelperCreator( EnterpriseEnrollmentHelper::EnrollmentStatusConsumer* status_consumer, const policy::EnrollmentConfig& enrollment_config, const std::string& enrolling_user_domain) { EnterpriseEnrollmentHelperMock* mock = new EnterpriseEnrollmentHelperMock(status_consumer); if (status == SUCCESS) { // Define behavior of EnrollUsingAttestation to successfully enroll. EXPECT_CALL(*mock, EnrollUsingAttestation()) .Times(AnyNumber()) .WillRepeatedly(Invoke([mock]() { static_cast<EnrollmentScreen*>(mock->status_consumer()) ->ShowEnrollmentStatusOnSuccess(); })); } else { // Define behavior of EnrollUsingAttestation to fail to enroll. const policy::EnrollmentStatus enrollment_status = policy::EnrollmentStatus::ForRegistrationError( status == DEVICE_NOT_SETUP_FOR_ZERO_TOUCH ? policy::DeviceManagementStatus:: DM_STATUS_SERVICE_DEVICE_NOT_FOUND : policy::DeviceManagementStatus:: DM_STATUS_TEMPORARY_UNAVAILABLE); EXPECT_CALL(*mock, EnrollUsingAttestation()) .Times(AnyNumber()) .WillRepeatedly(Invoke([mock, enrollment_status]() { mock->status_consumer()->OnEnrollmentError(enrollment_status); })); } // Define behavior of ClearAuth to only run the callback it is given. EXPECT_CALL(*mock, ClearAuth(_)) .Times(AnyNumber()) .WillRepeatedly(Invoke( [](const base::RepeatingClosure& callback) { callback.Run(); })); return mock; } void SetUpEnrollmentScreen() override { enrollment_config_.mode = policy::EnrollmentConfig::MODE_ATTESTATION_LOCAL_FORCED; enrollment_config_.auth_mechanism = policy::EnrollmentConfig::AUTH_MECHANISM_ATTESTATION; EnrollmentScreenUnitTest::SetUpEnrollmentScreen(); } virtual void SetUpEnrollmentScreenForFallback() { enrollment_config_.mode = policy::EnrollmentConfig::MODE_ATTESTATION; enrollment_config_.auth_mechanism = policy::EnrollmentConfig::AUTH_MECHANISM_BEST_AVAILABLE; EnrollmentScreenUnitTest::SetUpEnrollmentScreen(); } // testing::Test: void SetUp() override { EnrollmentScreenUnitTest::SetUp(); // Configure the browser to use Hands-Off Enrollment. base::CommandLine::ForCurrentProcess()->AppendSwitchASCII( switches::kEnterpriseEnableZeroTouchEnrollment, "hands-off"); } void TestRetry() { // Define behavior of EnterpriseEnrollmentHelperMock to always fail // enrollment. EnterpriseEnrollmentHelper::SetupEnrollmentHelperMock( &ZeroTouchEnrollmentScreenUnitTest::MockEnrollmentHelperCreator< DMSERVER_ERROR>); SetUpEnrollmentScreen(); // Remove jitter to enable deterministic testing. enrollment_screen_->retry_policy_.jitter_factor = 0; // Start zero-touch enrollment. enrollment_screen_->Show(); // Fast forward time by 1 minute. FastForwardTime(base::TimeDelta::FromMinutes(1)); // Check that we have retried 4 times. EXPECT_EQ(enrollment_screen_->num_retries_, 4); } void TestFinishEnrollmentFlow() { // Define behavior of EnterpriseEnrollmentHelperMock to successfully enroll. EnterpriseEnrollmentHelper::SetupEnrollmentHelperMock( &ZeroTouchEnrollmentScreenUnitTest::MockEnrollmentHelperCreator< SUCCESS>); SetUpEnrollmentScreen(); // Set up expectation for BaseScreenDelegate::OnExit to be called // with BaseScreenDelegate::ENTERPRISE_ENROLLMENT_COMPLETED // This is how we check that the code finishes and cleanly exits // the enterprise enrollment flow. EXPECT_CALL(*GetBaseScreenDelegate(), OnExit(_, ScreenExitCode::ENTERPRISE_ENROLLMENT_COMPLETED, _)) .Times(1); // Start zero-touch enrollment. enrollment_screen_->Show(); } void TestFallback() { // Define behavior of EnterpriseEnrollmentHelperMock to fail // attestation-based enrollment. EnterpriseEnrollmentHelper::SetupEnrollmentHelperMock( &ZeroTouchEnrollmentScreenUnitTest::MockEnrollmentHelperCreator< DEVICE_NOT_SETUP_FOR_ZERO_TOUCH>); SetUpEnrollmentScreenForFallback(); // Once we fallback we show a sign in screen for manual enrollment. EXPECT_CALL(*GetMockScreenView(), ShowSigninScreen()).Times(1); // Start enrollment. enrollment_screen_->Show(); } private: DISALLOW_COPY_AND_ASSIGN(ZeroTouchEnrollmentScreenUnitTest); }; TEST_F(ZeroTouchEnrollmentScreenUnitTest, FinishEnrollmentFlow) { TestFinishEnrollmentFlow(); } TEST_F(ZeroTouchEnrollmentScreenUnitTest, Fallback) { TestFallback(); } TEST_F(ZeroTouchEnrollmentScreenUnitTest, Retry) { TestRetry(); } TEST_F(ZeroTouchEnrollmentScreenUnitTest, DoNotRetryOnTopOfUser) { // Define behavior of EnterpriseEnrollmentHelperMock to always fail // enrollment. EnterpriseEnrollmentHelper::SetupEnrollmentHelperMock( &ZeroTouchEnrollmentScreenUnitTest::MockEnrollmentHelperCreator< DMSERVER_ERROR>); SetUpEnrollmentScreen(); // Remove jitter to enable deterministic testing. enrollment_screen_->retry_policy_.jitter_factor = 0; // Start zero-touch enrollment. enrollment_screen_->Show(); // Schedule user retry button click after 30 sec. base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, base::BindOnce(&EnrollmentScreen::OnRetry, enrollment_screen_->weak_ptr_factory_.GetWeakPtr()), base::TimeDelta::FromSeconds(30)); // Fast forward time by 1 minute. FastForwardTime(base::TimeDelta::FromMinutes(1)); // Check that the number of retries is still 4. EXPECT_EQ(enrollment_screen_->num_retries_, 4); } TEST_F(ZeroTouchEnrollmentScreenUnitTest, DoNotRetryAfterSuccess) { // Define behavior of EnterpriseEnrollmentHelperMock to successfully enroll. EnterpriseEnrollmentHelper::SetupEnrollmentHelperMock( &ZeroTouchEnrollmentScreenUnitTest::MockEnrollmentHelperCreator<SUCCESS>); SetUpEnrollmentScreen(); // Start zero-touch enrollment. enrollment_screen_->Show(); // Fast forward time by 1 minute. FastForwardTime(base::TimeDelta::FromMinutes(1)); // Check that we do not retry. EXPECT_EQ(enrollment_screen_->num_retries_, 0); } /* * We base these tests off ZeroTouchEnrollmenScreenUnitTest for two reasons: * 1. We want to check that some same tests pass in both classes * 2. We want to leverage Zero-Touch Hands Off to test for proper completions */ class AutomaticReenrollmentScreenUnitTest : public ZeroTouchEnrollmentScreenUnitTest { public: AutomaticReenrollmentScreenUnitTest() = default; void SetUpEnrollmentScreen() override { enrollment_config_.mode = policy::EnrollmentConfig::MODE_ATTESTATION_SERVER_FORCED; enrollment_config_.auth_mechanism = policy::EnrollmentConfig::AUTH_MECHANISM_BEST_AVAILABLE; EnrollmentScreenUnitTest::SetUpEnrollmentScreen(); } void SetUpEnrollmentScreenForFallback() override { // Automatic re-enrollment is always setup for fallback. SetUpEnrollmentScreen(); } private: DISALLOW_COPY_AND_ASSIGN(AutomaticReenrollmentScreenUnitTest); }; TEST_F(AutomaticReenrollmentScreenUnitTest, ShowErrorPanel) { // We use Zero-Touch's test for retries as a way to know that there was // an error pane with a Retry button displayed to the user when we encounter // a DMServer error that is not that the device isn't setup for Auto RE. TestRetry(); } TEST_F(AutomaticReenrollmentScreenUnitTest, FinishEnrollmentFlow) { TestFinishEnrollmentFlow(); } TEST_F(AutomaticReenrollmentScreenUnitTest, Fallback) { TestFallback(); } class MultiLicenseEnrollmentScreenUnitTest : public EnrollmentScreenUnitTest { public: MultiLicenseEnrollmentScreenUnitTest() = default; void SetUpEnrollmentScreen() override { enrollment_config_.mode = policy::EnrollmentConfig::MODE_MANUAL; enrollment_config_.auth_mechanism = policy::EnrollmentConfig::AUTH_MECHANISM_INTERACTIVE; EnrollmentScreenUnitTest::SetUpEnrollmentScreen(); } static EnterpriseEnrollmentHelper* MockEnrollmentHelperCreator( EnterpriseEnrollmentHelper::EnrollmentStatusConsumer* status_consumer, const policy::EnrollmentConfig& enrollment_config, const std::string& enrolling_user_domain) { EnterpriseEnrollmentHelperMock* mock = new EnterpriseEnrollmentHelperMock(status_consumer); EXPECT_CALL(*mock, EnrollUsingAuthCode(_, _)) .Times(AnyNumber()) .WillRepeatedly(Invoke([mock](const std::string&, bool) { EnrollmentLicenseMap licenses; static_cast<EnrollmentScreen*>(mock->status_consumer()) ->OnMultipleLicensesAvailable(licenses); })); EXPECT_CALL(*mock, UseLicenseType(::policy::LicenseType::ANNUAL)).Times(1); return mock; } private: DISALLOW_COPY_AND_ASSIGN(MultiLicenseEnrollmentScreenUnitTest); }; // Sign in and check that selected license type is propagated correctly. TEST_F(MultiLicenseEnrollmentScreenUnitTest, TestLicenseSelection) { EnterpriseEnrollmentHelper::SetupEnrollmentHelperMock( &MultiLicenseEnrollmentScreenUnitTest::MockEnrollmentHelperCreator); EXPECT_CALL(*GetMockScreenView(), SetParameters(_, _)).Times(1); SetUpEnrollmentScreen(); EXPECT_CALL(*GetMockScreenView(), Show()).Times(1); EXPECT_CALL(*GetMockScreenView(), ShowSigninScreen()).Times(1); // Start enrollment. enrollment_screen_->Show(); // Once at login, once after picking license type. EXPECT_CALL(*GetMockScreenView(), ShowEnrollmentSpinnerScreen()).Times(2); EXPECT_CALL(*GetMockScreenView(), ShowLicenseTypeSelectionScreen(_)).Times(1); enrollment_screen_->OnLoginDone("<EMAIL>", "oauth"); enrollment_screen_->OnLicenseTypeSelected("annual"); } } // namespace chromeos
4,608
393
package com.marverenic.music.ui.library; import android.content.Context; import androidx.databinding.Bindable; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentPagerAdapter; import com.marverenic.music.BR; import com.marverenic.music.R; import com.marverenic.music.data.annotations.StartPage; import com.marverenic.music.data.store.PreferenceStore; import com.marverenic.music.data.store.ThemeStore; import com.marverenic.music.ui.BaseViewModel; import com.marverenic.music.ui.common.playlist.CreatePlaylistDialogFragment; import com.marverenic.music.ui.library.playlist.contents.edit.AutoPlaylistEditActivity; import com.marverenic.music.view.FABMenu; public class LibraryViewModel extends BaseViewModel { private static final String TAG_MAKE_PLAYLIST = "CreatePlaylistDialog"; private FragmentManager mFragmentManager; private ThemeStore mThemeStore; private FragmentPagerAdapter mPagerAdapter; private boolean mRefreshing; private int mPage; LibraryViewModel(Context context, FragmentManager fragmentManager, PreferenceStore preferenceStore, ThemeStore themeStore) { super(context); mFragmentManager = fragmentManager; mThemeStore = themeStore; int startingPage = preferenceStore.getDefaultPage(); if (startingPage < StartPage.PLAYLISTS || startingPage > StartPage.GENRES) { startingPage = StartPage.SONGS; } setPage(startingPage); mPagerAdapter = new LibraryPagerAdapter(getContext(), fragmentManager); } @Bindable public int getPage() { return mPage; } public void setPage(int page) { if (page != mPage) { mPage = page; notifyPropertyChanged(BR.page); notifyPropertyChanged(BR.fabVisible); } } @Bindable public FragmentPagerAdapter getPagerAdapter() { notifyPropertyChanged(BR.page); return mPagerAdapter; } @Bindable public boolean isFabVisible() { return mPage == 0; } @Bindable public FABMenu.MenuItem[] getFabMenuItems() { return new FABMenu.MenuItem[] { new FABMenu.MenuItem(R.drawable.ic_add_24dp, v -> createPlaylist(), R.string.playlist), new FABMenu.MenuItem(R.drawable.ic_add_24dp, v -> createAutoPlaylist(), R.string.playlist_auto) }; } public void setLibraryRefreshing(boolean refreshing) { mRefreshing = refreshing; notifyPropertyChanged(BR.libraryRefreshing); } @Bindable public boolean isLibraryRefreshing() { return mRefreshing; } @Bindable public int[] getRefreshIndicatorColors() { return new int[] { mThemeStore.getPrimaryColor(), mThemeStore.getAccentColor() }; } private void createPlaylist() { new CreatePlaylistDialogFragment.Builder(mFragmentManager) .showSnackbarIn(R.id.library_pager) .show(TAG_MAKE_PLAYLIST); } private void createAutoPlaylist() { getContext().startActivity(AutoPlaylistEditActivity.newIntent(getContext())); } }
1,327
606
#include "config.h" #include "types.h" u32 skim(const u32 *virgin, const u32 *current, const u32 *current_end); u32 classify_word(u32 word); inline u32 classify_word(u32 word) { u16 mem16[2]; memcpy(mem16, &word, sizeof(mem16)); mem16[0] = count_class_lookup16[mem16[0]]; mem16[1] = count_class_lookup16[mem16[1]]; memcpy(&word, mem16, sizeof(mem16)); return word; } void simplify_trace(afl_state_t *afl, u8 *bytes) { u32 *mem = (u32 *)bytes; u32 i = (afl->fsrv.map_size >> 2); while (i--) { /* Optimize for sparse bitmaps. */ if (unlikely(*mem)) { u8 *mem8 = (u8 *)mem; mem8[0] = simplify_lookup[mem8[0]]; mem8[1] = simplify_lookup[mem8[1]]; mem8[2] = simplify_lookup[mem8[2]]; mem8[3] = simplify_lookup[mem8[3]]; } else *mem = 0x01010101; mem++; } } inline void classify_counts(afl_forkserver_t *fsrv) { u32 *mem = (u32 *)fsrv->trace_bits; u32 i = (fsrv->map_size >> 2); while (i--) { /* Optimize for sparse bitmaps. */ if (unlikely(*mem)) { *mem = classify_word(*mem); } mem++; } } /* Updates the virgin bits, then reflects whether a new count or a new tuple is * seen in ret. */ inline void discover_word(u8 *ret, u32 *current, u32 *virgin) { /* Optimize for (*current & *virgin) == 0 - i.e., no bits in current bitmap that have not been already cleared from the virgin map - since this will almost always be the case. */ if (unlikely(*current & *virgin)) { if (likely(*ret < 2)) { u8 *cur = (u8 *)current; u8 *vir = (u8 *)virgin; /* Looks like we have not found any new bytes yet; see if any non-zero bytes in current[] are pristine in virgin[]. */ if (unlikely((cur[0] && vir[0] == 0xff) || (cur[1] && vir[1] == 0xff) || (cur[2] && vir[2] == 0xff) || (cur[3] && vir[3] == 0xff))) *ret = 2; else *ret = 1; } *virgin &= ~*current; } } #define PACK_SIZE 16 inline u32 skim(const u32 *virgin, const u32 *current, const u32 *current_end) { for (; current < current_end; virgin += 4, current += 4) { if (unlikely(current[0] && classify_word(current[0]) & virgin[0])) return 1; if (unlikely(current[1] && classify_word(current[1]) & virgin[1])) return 1; if (unlikely(current[2] && classify_word(current[2]) & virgin[2])) return 1; if (unlikely(current[3] && classify_word(current[3]) & virgin[3])) return 1; } return 0; }
1,060
953
package canvastoolbox.florent37.github.com.canvastoolbox.views; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.View; import com.github.florent37.mylittlecanvas.animation.ShapeAnimator; import com.github.florent37.mylittlecanvas.shape.CircleShape; import com.github.florent37.mylittlecanvas.shape.RectShape; import static com.github.florent37.mylittlecanvas.CanvasHelper.dpToPx; public class SwitchView extends View { private final RectShape background = new RectShape(); private final CircleShape indicator = new CircleShape(); private final ShapeAnimator shapeAnimator = new ShapeAnimator(this); private boolean checked = false; public SwitchView(Context context) { super(context); init(); } public SwitchView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(); } public SwitchView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { setChecked(!isChecked()); } }); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); background .setCornerRadius(h / 2f) .setColor(Color.parseColor("#DEDEDE")) .setRect(0, 0, w, h); indicator .setColor(Color.WHITE) .setBorderWidth(dpToPx(getContext(), 1)) .setBorderColor(Color.parseColor("#DDDDDD")) .setRadius(h / 2f) .centerVertical(h) .setCenterX(h / 2f); } public boolean isChecked() { return checked; } public void setChecked(boolean checked) { if(checked != this.checked) { this.checked = checked; final float newCenterX = checked ? getWidth() - indicator.getRadius() : indicator.getRadius(); shapeAnimator.clear() .play(indicator.animate().centerXTo(newCenterX)) .play(indicator.animate().radiusBy(1f, 0.9f, 1f)) .start(); } } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); background.onDraw(canvas); indicator.onDraw(canvas); } }
1,158
852
<filename>TrackingTools/GeomPropagators/python/AnyDirectionAnalyticalPropagator_cfi.py import FWCore.ParameterSet.Config as cms AnyDirectionAnalyticalPropagator = cms.ESProducer("AnalyticalPropagatorESProducer", MaxDPhi = cms.double(1.6), ComponentName = cms.string('AnyDirectionAnalyticalPropagator'), PropagationDirection = cms.string('anyDirection') )
129
301
package com.sap.iot.starterkit.mqtt.ingest.type; public class ClientCertificateAuthorization implements Authorization { private String keyStoreLocation; private transient String keyStorePassword; private String trustStoreLocation; private transient String trustStorePassword; public String getKeyStoreLocation() { return keyStoreLocation; } public String getKeyStorePassword() { return keyStorePassword; } public String getTrustStoreLocation() { return trustStoreLocation; } public String getTrustStorePassword() { return trustStorePassword; } }
157
2,151
// 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 COMPONENTS_SYNC_ENGINE_UI_MODEL_WORKER_H_ #define COMPONENTS_SYNC_ENGINE_UI_MODEL_WORKER_H_ #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/single_thread_task_runner.h" #include "components/sync/engine/model_safe_worker.h" namespace syncer { // A ModelSafeWorker for UI models (e.g. bookmarks) that // accepts work requests from the syncapi that need to be fulfilled // from the MessageLoop home to the native model. class UIModelWorker : public ModelSafeWorker { public: explicit UIModelWorker(scoped_refptr<base::SingleThreadTaskRunner> ui_thread); // ModelSafeWorker implementation. ModelSafeGroup GetModelSafeGroup() override; bool IsOnModelSequence() override; private: ~UIModelWorker() override; void ScheduleWork(base::OnceClosure work) override; // A reference to the UI thread's task runner. const scoped_refptr<base::SingleThreadTaskRunner> ui_thread_; DISALLOW_COPY_AND_ASSIGN(UIModelWorker); }; } // namespace syncer #endif // COMPONENTS_SYNC_ENGINE_UI_MODEL_WORKER_H_
409
914
<gh_stars>100-1000 // // WAAVSEExtractSoundCommand.h // YCH // // Created by 黄锐灏 on 2019/1/11. // Copyright © 2019 黄锐灏. All rights reserved. // #import "WAAVSECommand.h" NS_ASSUME_NONNULL_BEGIN @interface WAAVSEExtractSoundCommand : WAAVSECommand @end NS_ASSUME_NONNULL_END
136
655
package com.taobao.bulbasaur.service; /** * User: yunche.ch ... (ว ˙o˙)ง * Date: 14-12-24 * Time: 下午3:43 */ public class NotifyPage { public void doNotify(String taskIds) { System.out.println("将taskId传递给业务bean,可以再来调用 complete 接口!"); System.out.println(taskIds); } }
167
2,742
/* * Copyright 2008-2019 by <NAME> * * This file is part of Java Melody. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.bull.javamelody; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Desktop; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.net.URI; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import javax.swing.AbstractAction; import javax.swing.ImageIcon; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.KeyStroke; import net.bull.javamelody.internal.model.Collector; import net.bull.javamelody.internal.model.Counter.CounterRequestContextComparator; import net.bull.javamelody.internal.model.CounterRequestContext; import net.bull.javamelody.internal.model.JavaInformations; import net.bull.javamelody.internal.model.Period; import net.bull.javamelody.internal.model.Range; import net.bull.javamelody.internal.model.RemoteCollector; import net.bull.javamelody.internal.web.pdf.PdfCoreReport; import net.bull.javamelody.internal.web.pdf.PdfReport; import net.bull.javamelody.swing.MButton; /** * Panel des boutons principaux. * @author <NAME> */ class MainButtonsPanel extends MelodyPanel { private static final Color BACKGROUND = new Color(186, 207, 226); private static final ImageIcon MONITORING_ICON = ImageIconCache .getScaledImageIcon("systemmonitor.png", 16, 16); private static final long serialVersionUID = 1L; private final boolean collectorServer; MainButtonsPanel(RemoteCollector remoteCollector, Range selectedRange, final URL monitoringUrl, boolean collectorServer) { super(remoteCollector, new BorderLayout()); this.collectorServer = collectorServer; setOpaque(true); setBackground(BACKGROUND); final JPanel centerPanel = new JPanel(new FlowLayout(FlowLayout.CENTER)); centerPanel.setOpaque(false); add(centerPanel, BorderLayout.CENTER); final CustomPeriodPanel customPeriodPanel = new CustomPeriodPanel(remoteCollector, selectedRange); final DeploymentPeriodPanel deploymentPeriodPanel = createDeploymentPeriodPanel( remoteCollector, selectedRange); final JPanel customPeriodsPanel = new JPanel(new BorderLayout()); customPeriodsPanel.setOpaque(false); if (deploymentPeriodPanel != null) { customPeriodsPanel.add(deploymentPeriodPanel, BorderLayout.NORTH); } customPeriodsPanel.add(customPeriodPanel, BorderLayout.SOUTH); add(customPeriodsPanel, BorderLayout.SOUTH); final MButton refreshButton = createRefreshButton(); final MButton pdfButton = createPdfButton(); // on ne peut pas instancier defaultSerializable ici car sinon, // les données ne seraient plus à jour après une actualisation, donc on passe la valeur spéciale null final MButton xmlJsonButton = createXmlJsonButton(null); final MButton onlineHelpButton = createOnlineHelpButton(); final MButton monitoringButton = new MButton(getString("Monitoring"), MONITORING_ICON); monitoringButton.setToolTipText( getFormattedString("Monitoring_sur", remoteCollector.getApplication())); centerPanel.add(refreshButton); centerPanel.add(pdfButton); centerPanel.add(xmlJsonButton); centerPanel.add(onlineHelpButton); centerPanel.add(monitoringButton); addPeriodButtons(centerPanel, customPeriodPanel, deploymentPeriodPanel); addCustomPeriodsButtons(centerPanel, customPeriodPanel, deploymentPeriodPanel); refreshButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { actionRefresh(); } }); pdfButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { actionPdf(); } catch (final Exception ex) { showException(ex); } } }); monitoringButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { Desktop.getDesktop().browse(new URI(monitoringUrl.toExternalForm())); } catch (final Exception ex) { showException(ex); } } }); onlineHelpButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { Desktop.getDesktop().browse(new URI( monitoringUrl.toExternalForm() + "?resource=" + getString("help_url"))); } catch (final Exception ex) { showException(ex); } } }); } private DeploymentPeriodPanel createDeploymentPeriodPanel(RemoteCollector remoteCollector, Range selectedRange) { try { final DeploymentPeriodPanel deploymentPeriodPanel = new DeploymentPeriodPanel( remoteCollector, selectedRange); if (deploymentPeriodPanel.getWebappVersions().isEmpty()) { return null; } return deploymentPeriodPanel; } catch (final IOException e) { return null; } } private void addPeriodButtons(JPanel centerPanel, final CustomPeriodPanel customPeriodPanel, final DeploymentPeriodPanel deploymentPeriodPanel) { centerPanel.add(new JLabel(" " + getString("Choix_periode") + " : ")); for (final Period myPeriod : Period.values()) { final String linkLabel = myPeriod.getLinkLabel(); final MButton myPeriodButton = new MButton(linkLabel, ImageIconCache.getImageIcon(myPeriod.getIconName())); myPeriodButton.setToolTipText(getFormattedString("Choisir_periode", linkLabel) + " (Alt-" + linkLabel.charAt(0) + ')'); myPeriodButton.setMnemonic(linkLabel.charAt(0)); centerPanel.add(myPeriodButton); myPeriodButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { customPeriodPanel.setVisible(false); if (deploymentPeriodPanel != null) { deploymentPeriodPanel.setVisible(false); } actionChangePeriod(myPeriod.getRange()); } }); } } private void addCustomPeriodsButtons(JPanel centerPanel, final CustomPeriodPanel customPeriodPanel, final DeploymentPeriodPanel deploymentPeriodPanel) { final String customPeriodLinkLabel = getString("personnalisee"); final MButton customPeriodButton = new MButton(customPeriodLinkLabel, ImageIconCache.getImageIcon("calendar.png")); customPeriodButton .setToolTipText(getFormattedString("Choisir_periode", customPeriodLinkLabel) + " (Alt-" + customPeriodLinkLabel.charAt(0) + ')'); customPeriodButton.setMnemonic(customPeriodLinkLabel.charAt(0)); centerPanel.add(customPeriodButton); customPeriodPanel.setVisible(false); customPeriodButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { customPeriodPanel.setVisible(!customPeriodPanel.isVisible()); if (customPeriodPanel.isVisible()) { customPeriodPanel.requestFocusInStartField(); } if (deploymentPeriodPanel != null) { deploymentPeriodPanel.setVisible(false); } validate(); } }); if (deploymentPeriodPanel != null) { final String deploymentLabel = getString("par_deploiement"); final MButton deploymentButton = new MButton(deploymentLabel, ImageIconCache.getImageIcon("calendar.png")); deploymentButton.setToolTipText( getFormattedString("Choisir_periode", deploymentLabel) + " (Alt-D)"); deploymentButton.setMnemonic('D'); centerPanel.add(deploymentButton); deploymentPeriodPanel.setVisible(false); deploymentButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { deploymentPeriodPanel.setVisible(!deploymentPeriodPanel.isVisible()); if (deploymentPeriodPanel.isVisible()) { deploymentPeriodPanel.requestFocusInVersionField(); } customPeriodPanel.setVisible(false); validate(); } }); } } private MButton createOnlineHelpButton() { final MButton onlineHelpButton = new MButton(getString("Aide_en_ligne"), ImageIconCache.getImageIcon("action_help.png")); onlineHelpButton.setToolTipText(getString("Afficher_aide_en_ligne") + " (F1)"); onlineHelpButton.setActionCommand("help"); onlineHelpButton.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW) .put(KeyStroke.getKeyStroke("F1"), "doHelp"); onlineHelpButton.getActionMap().put("doHelp", new AbstractAction() { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { onlineHelpButton.doClick(); } }); return onlineHelpButton; } void actionRefresh() { try { getRemoteCollector().collectDataIncludingCurrentRequests(); MainPanel.refreshMainTabFromChild(this); } catch (final IOException e) { showException(e); } } void actionChangePeriod(Range newRange) { MainPanel.getParentMainPanelFromChild(this).changeRange(newRange); } void actionPdf() throws IOException { final Range range = MainPanel.getParentMainPanelFromChild(this).getSelectedRange(); final File tempFile = createTempFileForPdf(); final Collector collector = getCollector(); final List<JavaInformations> javaInformationsList = getJavaInformationsList(); final RemoteCollector remoteCollector = getRemoteCollector(); final Map<String, byte[]> smallGraphs = remoteCollector .collectJRobins(PdfCoreReport.SMALL_GRAPH_WIDTH, PdfCoreReport.SMALL_GRAPH_HEIGHT); final Map<String, byte[]> smallOtherGraphs = remoteCollector.collectOtherJRobins( PdfCoreReport.SMALL_GRAPH_WIDTH, PdfCoreReport.SMALL_GRAPH_HEIGHT); final Map<String, byte[]> largeGraphs = remoteCollector .collectJRobins(PdfCoreReport.LARGE_GRAPH_WIDTH, PdfCoreReport.LARGE_GRAPH_HEIGHT); try (OutputStream output = createFileOutputStream(tempFile)) { final PdfReport pdfReport = new PdfReport(collector, collectorServer, javaInformationsList, range, output); try { // PdfReport utilise collector.getRangeCountersToBeDisplayed(range), // mais les counters contiennent les bonnes données pour la période TOUT // et non pas celle de la variable "range" pdfReport.setCounterRange(Period.TOUT.getRange()); pdfReport.preInitGraphs(smallGraphs, smallOtherGraphs, largeGraphs); if (!collectorServer) { final List<CounterRequestContext> currentRequests = new ArrayList<>(); for (final List<CounterRequestContext> requests : getRemoteCollector() .getCurrentRequests().values()) { currentRequests.addAll(requests); } Collections.sort(currentRequests, Collections.reverseOrder( new CounterRequestContextComparator(System.currentTimeMillis()))); pdfReport.setCurrentRequests(currentRequests); } pdfReport.toPdf(); } finally { pdfReport.close(); } } Desktop.getDesktop().open(tempFile); } }
4,282
11,356
/* tests/test_numpy_vectorize.cpp -- auto-vectorize functions over NumPy array arguments Copyright (c) 2016 <NAME> <<EMAIL>> All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. */ #include "pybind11_tests.h" #include <pybind11/numpy.h> double my_func(int x, float y, double z) { py::print("my_func(x:int={}, y:float={:.0f}, z:float={:.0f})"_s.format(x, y, z)); return (float) x*y*z; } std::complex<double> my_func3(std::complex<double> c) { return c * std::complex<double>(2.f); } test_initializer numpy_vectorize([](py::module &m) { // Vectorize all arguments of a function (though non-vector arguments are also allowed) m.def("vectorized_func", py::vectorize(my_func)); // Vectorize a lambda function with a capture object (e.g. to exclude some arguments from the vectorization) m.def("vectorized_func2", [](py::array_t<int> x, py::array_t<float> y, float z) { return py::vectorize([z](int x, float y) { return my_func(x, y, z); })(x, y); } ); // Vectorize a complex-valued function m.def("vectorized_func3", py::vectorize(my_func3)); /// Numpy function which only accepts specific data types m.def("selective_func", [](py::array_t<int, py::array::c_style>) { return "Int branch taken."; }); m.def("selective_func", [](py::array_t<float, py::array::c_style>) { return "Float branch taken."; }); m.def("selective_func", [](py::array_t<std::complex<float>, py::array::c_style>) { return "Complex float branch taken."; }); });
609
325
# -*- coding: utf-8 -*- """Geometry functions. """ from __future__ import absolute_import, division, print_function import numpy as np def create_quad(scale=(1.0,1.0), st=False, rgba=False, dtype='float32', type='triangles'): """Returns a Quad reading for rendering. Output is a tuple of numpy arrays. The first value is the vertex data, the second is the indices. The first dimension of the vertex data contains the list of vertices. The second dimension is the vertex data. Vertex data is always in the following order:: [x, y, z, s, t, r, g, b, a] ST and RGBA are optional. If ST is dropped but RGBA is included the format will be:: [x, y, z, r, g, b, a] If both ST and RGBA are dropped the format will be:: [x, y, z] RGBA can also be of size 3 (RGB) or 4 (RGBA). Output format is as follows:: numpy.array([ # vertex 1 [x, y, z, s, t, r, g, b, a], # vertex 2 [x, y, z, s, t, r, g, b, a], ... # vertex N [x, y, z, s, t, r, g, b, a], ], dtype = dtype) :param bool,scalar,list,tuple,numpy.ndarray st: The ST texture co-ordinates. Default is False, which means ST will not be included in the array. If True is passed, the default ST values will be provided with the bottom-left of the quad being located at ST=(0.0,0.0) and the top-right being located at ST=(1.0,1.0). If a 2d list, tuple or numpy array is passed, it must have one of the following shapes:: (2,2,), (4,2,), If the shape is (2,2,), the values are interpreted as the minimum and maximum values for ST. For example:: st=((0.1,0.3),(0.2,0.4)) S values will be between 0.1 to 0.2. T values will be between 0.3 to 0.4. The bottom left will receive the minimum of both, and the top right will receive the maximum. If the shape is (4,2,), the values are interpreted as being the actual ST values for the 4 vertices of the Quad. The vertices are in counter-clockwise winding order from the top right:: [top-right, top-left, bottom-left, bottom-right,] :param bool,scalar,list,tuple,numpy.ndarray rgba: The RGBA colour. Default is False, which means RGBA will not be included in the array. If True is passed, the default RGBA values will be provided with all vertices being RGBA=(1.0, 1.0, 1.0, 1.0) If a 2d list, tuple or numpy array is passed, it must have one of the following shapes:: (3,), (4,), (4,3,), (4,4,), If the shape is (3,), the values are interpreted as being an RGB value (no alpha) to set on all vertices. If the shape is (4,), the values are intepreted the same as the shape (3,) except the alpha value is included. If the shape is (4,3,), the values are interpreted as being a colour to set on the 4 vertices of the Quad. The vertices are in counter-clockwise winding order from the top right:: [top-right, top-left, bottom-left, bottom-right] If the shape is (4,4,), the values are intepreted the same as the shape (4,3,) except the alpha value is included. :param string type: The type of indices to generate. Valid values are:: ['triangles', 'triangle_strip', 'triangle_fan', 'quads', 'quad_strip',] If you just want the vertices without any index manipulation, use 'quads'. """ shape = [4, 3] rgba_offset = 3 width, height = scale # half the dimensions width /= 2.0 height /= 2.0 vertices = np.array([ # top right ( width, height, 0.0,), # top left (-width, height, 0.0,), # bottom left (-width,-height, 0.0,), # bottom right ( width,-height, 0.0,), ], dtype=dtype) st_values = None rgba_values = None if st: # default st values st_values = np.array([ (1.0, 1.0,), (0.0, 1.0,), (0.0, 0.0,), (1.0, 0.0,), ], dtype=dtype) if isinstance(st, bool): pass elif isinstance(st, (int, float)): st_values *= st elif isinstance(st, (list, tuple, np.ndarray)): st = np.array(st, dtype=dtype) if st.shape == (2,2,): # min / max st_values *= st[1] - st[0] st_values += st[0] elif st.shape == (4,2,): # st values specified manually st_values[:] = st else: raise ValueError('Invalid shape for st') else: raise ValueError('Invalid value for st') shape[-1] += st_values.shape[-1] rgba_offset += st_values.shape[-1] if rgba: # default rgba values rgba_values = np.tile(np.array([1.0, 1.0, 1.0, 1.0], dtype=dtype), (4,1,)) if isinstance(rgba, bool): pass elif isinstance(rgba, (int, float)): # int / float expands to RGBA with all values == value rgba_values *= rgba elif isinstance(rgba, (list, tuple, np.ndarray)): rgba = np.array(rgba, dtype=dtype) if rgba.shape == (3,): rgba_values = np.tile(rgba, (4,1,)) elif rgba.shape == (4,): rgba_values[:] = rgba elif rgba.shape == (4,3,): rgba_values = rgba elif rgba.shape == (4,4,): rgba_values = rgba else: raise ValueError('Invalid shape for rgba') else: raise ValueError('Invalid value for rgba') shape[-1] += rgba_values.shape[-1] data = np.empty(shape, dtype=dtype) data[:,:3] = vertices if st_values is not None: data[:,3:5] = st_values if rgba_values is not None: data[:,rgba_offset:] = rgba_values if type == 'triangles': # counter clockwise # top right -> top left -> bottom left # top right -> bottom left -> bottom right indices = np.array([0, 1, 2, 0, 2, 3]) elif type == 'triangle_strip': # verify indices = np.arange(len(data)) elif type == 'triangle_fan': # verify indices = np.arange(len(data)) elif type == 'quads': indices = np.arange(len(data)) elif type == 'quad_strip': indices = np.arange(len(data)) else: raise ValueError('Unknown type') return data, indices def create_cube(scale=(1.0,1.0,1.0), st=False, rgba=False, dtype='float32', type='triangles'): """Returns a Cube reading for rendering. Output is a tuple of numpy arrays. The first value is the vertex data, the second is the indices. The first dimension of the vertex data contains the list of vertices. The second dimension is the vertex data. Vertex data is always in the following order:: [x, y, z, s, t, r, g, b, a] ST and RGBA are optional. If ST is dropped but RGBA is included the format will be:: [x, y, z, r, g, b, a] If both ST and RGBA are dropped the format will be:: [x, y, z] RGBA can also be of size 3 (RGB) or 4 (RGBA). Output format is as follows:: numpy.array([ # vertex 1 [x, y, z, s, t, r, g, b, a], # vertex 2 [x, y, z, s, t, r, g, b, a], ... # vertex N [x, y, z, s, t, r, g, b, a], ], dtype = dtype) :param bool,scalar,list,tuple,numpy.ndarray st: The ST texture co-ordinates. Default is False, which means ST will not be included in the array. If True is passed, the default ST values will be provided with the bottom-left of the quad being located at ST=(0.0,0.0) and the top-right being located at ST=(1.0,1.0). If a 2d list, tuple or numpy array is passed, it must have one of the following shapes:: (2,2,), (4,2,), (6,2,), If the shape is (2,2,), the values are interpreted as the minimum and maximum values for ST. For example:: st=((0.1,0.3),(0.2,0.4)) S values will be between 0.1 to 0.2. T values will be between 0.3 to 0.4. The bottom left will receive the minimum of both, and the top right will receive the maximum. If the shape is (4,2,), the values are interpreted as being the actual ST values for the 4 vertices of each face. The vertices are in counter-clockwise winding order from the top right:: [top-right, top-left, bottom-left, bottom-right,] If the shape is (6,2,), the values are interpreted as being the minimum and maximum values for each face of the cube. The faces are in the following order:: [front, right, back, left, top, bottom,] :param bool,scalar,list,tuple,numpy.ndarray rgba: The RGBA colour. Default is False, which means RGBA will not be included in the array. If True is passed, the default RGBA values will be provided with all vertices being RGBA=(1.0, 1.0, 1.0, 1.0). If a 2d list, tuple or numpy array is passed, it must have one of the following shapes.:: (3,), (4,), (4,3,), (4,4,), (6,3,), (6,4,), (24,3,), (24,4,), If the shape is (3,), the values are interpreted as being an RGB value (no alpha) to set on all vertices. If the shape is (4,), the values are intepreted the same as the shape (3,) except the alpha value is included. If the shape is (4,3,), the values are interpreted as being a colour to set on the 4 vertices of each face. The vertices are in counter-clockwise winding order from the top right:: [top-right, top-left, bottom-left, bottom-right] If the shape is (4,4,), the values are intepreted the same as the shape (4,3,) except the alpha value is included. If the shape is (6,3,), the values are interpreted as being one RGB value (no alpha) for each face. The faces are in the following order:: [front, right, back, left, top, bottom,] If the shape is (6,4,), the values are interpreted the same as the shape (6,3,) except the alpha value is included. If the shape is (24,3,), the values are interpreted as being an RGB value (no alpha) to set on each vertex of each face (4 * 6). The faces are in the following order:: [front, right, back, left, top, bottom,] The vertices are in counter-clockwise winding order from the top right:: [top-right, top-left, bottom-left, bottom-right] If the shape is (24,4,), the values are interpreted the same as the shape (24,3,) except the alpha value is included. :param string type: The type of indices to generate. Valid values are:: ['triangles', 'triangle_strip', 'triangle_fan', 'quads', 'quad_strip',] If you just want the vertices without any index manipulation, use 'quads'. """ shape = [24, 3] rgba_offset = 3 width, height, depth = scale # half the dimensions width /= 2.0 height /= 2.0 depth /= 2.0 vertices = np.array([ # front # top right ( width, height, depth,), # top left (-width, height, depth,), # bottom left (-width,-height, depth,), # bottom right ( width,-height, depth,), # right # top right ( width, height,-depth), # top left ( width, height, depth), # bottom left ( width,-height, depth), # bottom right ( width,-height,-depth), # back # top right (-width, height,-depth), # top left ( width, height,-depth), # bottom left ( width,-height,-depth), # bottom right (-width,-height,-depth), # left # top right (-width, height, depth), # top left (-width, height,-depth), # bottom left (-width,-height,-depth), # bottom right (-width,-height, depth), # top # top right ( width, height,-depth), # top left (-width, height,-depth), # bottom left (-width, height, depth), # bottom right ( width, height, depth), # bottom # top right ( width,-height, depth), # top left (-width,-height, depth), # bottom left (-width,-height,-depth), # bottom right ( width,-height,-depth), ], dtype=dtype) st_values = None rgba_values = None if st: # default st values st_values = np.tile( np.array([ (1.0, 1.0,), (0.0, 1.0,), (0.0, 0.0,), (1.0, 0.0,), ], dtype=dtype), (6,1,) ) if isinstance(st, bool): pass elif isinstance(st, (int, float)): st_values *= st elif isinstance(st, (list, tuple, np.ndarray)): st = np.array(st, dtype=dtype) if st.shape == (2,2,): # min / max st_values *= st[1] - st[0] st_values += st[0] elif st.shape == (4,2,): # per face st values specified manually st_values[:] = np.tile(st, (6,1,)) elif st.shape == (6,2,): # st values specified manually st_values[:] = st else: raise ValueError('Invalid shape for st') else: raise ValueError('Invalid value for st') shape[-1] += st_values.shape[-1] rgba_offset += st_values.shape[-1] if rgba: # default rgba values rgba_values = np.tile(np.array([1.0, 1.0, 1.0, 1.0], dtype=dtype), (24,1,)) if isinstance(rgba, bool): pass elif isinstance(rgba, (int, float)): # int / float expands to RGBA with all values == value rgba_values *= rgba elif isinstance(rgba, (list, tuple, np.ndarray)): rgba = np.array(rgba, dtype=dtype) if rgba.shape == (3,): rgba_values = np.tile(rgba, (24,1,)) elif rgba.shape == (4,): rgba_values[:] = np.tile(rgba, (24,1,)) elif rgba.shape == (4,3,): rgba_values = np.tile(rgba, (6,1,)) elif rgba.shape == (4,4,): rgba_values = np.tile(rgba, (6,1,)) elif rgba.shape == (6,3,): rgba_values = np.repeat(rgba, 4, axis=0) elif rgba.shape == (6,4,): rgba_values = np.repeat(rgba, 4, axis=0) elif rgba.shape == (24,3,): rgba_values = rgba elif rgba.shape == (24,4,): rgba_values = rgba else: raise ValueError('Invalid shape for rgba') else: raise ValueError('Invalid value for rgba') shape[-1] += rgba_values.shape[-1] data = np.empty(shape, dtype=dtype) data[:,:3] = vertices if st_values is not None: data[:,3:5] = st_values if rgba_values is not None: data[:,rgba_offset:] = rgba_values if type == 'triangles': # counter clockwise # top right -> top left -> bottom left # top right -> bottom left -> bottom right indices = np.tile(np.array([0, 1, 2, 0, 2, 3], dtype='int'), (6,1)) for face in range(6): indices[face] += (face * 4) indices.shape = (-1,) elif type == 'triangle_strip': raise NotImplementedError elif type == 'triangle_fan': raise NotImplementedError elif type == 'quads': raise NotImplementedError elif type == 'quad_strip': raise NotImplementedError else: raise ValueError('Unknown type') return data, indices
7,577
560
<reponame>sowmyavasudeva/SmartBookmark #include <stdio.h> #include <ckd_alloc.h> #include "test_macros.h" int main(int argc, char *argv[]) { int *alloc1; int bad_alloc_did_not_fail = FALSE; ckd_set_jump(NULL, TRUE); /* Guaranteed to fail, we hope!. */ alloc1 = ckd_calloc(-1,-1); TEST_ASSERT(bad_alloc_did_not_fail); return 0; }
156
679
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_tools.hxx" #include <tools/isofallback.hxx> // ----------------------------------------------------------------------- // Return true if valid fallback found sal_Bool GetIsoFallback( ByteString& rLanguage ) { rLanguage.EraseLeadingAndTrailingChars(); if( rLanguage.Len() ){ xub_StrLen nSepPos = rLanguage.Search( '-' ); if ( nSepPos == STRING_NOTFOUND ){ if ( rLanguage.Equals("en")) { // en -> "" rLanguage.Erase(); return false; } else { // de -> en-US ; rLanguage = ByteString("en-US"); return true; } } else if( !( nSepPos == 1 && ( rLanguage.GetChar(0) == 'x' || rLanguage.GetChar(0) == 'X' ) ) ) { // de-CH -> de ; // try erase from - rLanguage = rLanguage.GetToken( 0, '-'); return true; } } // "" -> ""; x-no-translate -> "" rLanguage.Erase(); return false; }
781
3,170
// // BufferedBidirectionalStreamBuf.h // // $Id: //poco/1.4/Foundation/include/Poco/BufferedBidirectionalStreamBuf.h#1 $ // // Library: Foundation // Package: Streams // Module: StreamBuf // // Definition of template BasicBufferedBidirectionalStreamBuf and class BufferedBidirectionalStreamBuf. // // Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // SPDX-License-Identifier: BSL-1.0 // #ifndef Foundation_BufferedBidirectionalStreamBuf_INCLUDED #define Foundation_BufferedBidirectionalStreamBuf_INCLUDED #include "Poco/Foundation.h" #include "Poco/BufferAllocator.h" #include "Poco/StreamUtil.h" #include <streambuf> #include <iosfwd> #include <ios> namespace Poco { template <typename ch, typename tr, typename ba = BufferAllocator<ch> > class BasicBufferedBidirectionalStreamBuf: public std::basic_streambuf<ch, tr> /// This is an implementation of a buffered bidirectional /// streambuf that greatly simplifies the implementation of /// custom streambufs of various kinds. /// Derived classes only have to override the methods /// readFromDevice() or writeToDevice(). /// /// In contrast to BasicBufferedStreambuf, this class supports /// simultaneous read and write access, so in addition to /// istream and ostream this streambuf can also be used /// for implementing an iostream. { protected: typedef std::basic_streambuf<ch, tr> Base; typedef std::basic_ios<ch, tr> IOS; typedef ch char_type; typedef tr char_traits; typedef ba Allocator; typedef typename Base::int_type int_type; typedef typename Base::pos_type pos_type; typedef typename Base::off_type off_type; typedef typename IOS::openmode openmode; public: BasicBufferedBidirectionalStreamBuf(std::streamsize bufferSize, openmode mode): _bufsize(bufferSize), _pReadBuffer(Allocator::allocate(_bufsize)), _pWriteBuffer(Allocator::allocate(_bufsize)), _mode(mode) { resetBuffers(); } ~BasicBufferedBidirectionalStreamBuf() { Allocator::deallocate(_pReadBuffer, _bufsize); Allocator::deallocate(_pWriteBuffer, _bufsize); } virtual int_type overflow(int_type c) { if (!(_mode & IOS::out)) return char_traits::eof(); if (c != char_traits::eof()) { *this->pptr() = char_traits::to_char_type(c); this->pbump(1); } if (flushBuffer() == std::streamsize(-1)) return char_traits::eof(); return c; } virtual int_type underflow() { if (!(_mode & IOS::in)) return char_traits::eof(); if (this->gptr() && (this->gptr() < this->egptr())) return char_traits::to_int_type(*this->gptr()); int putback = int(this->gptr() - this->eback()); if (putback > 4) putback = 4; char_traits::move(_pReadBuffer + (4 - putback), this->gptr() - putback, putback); int n = readFromDevice(_pReadBuffer + 4, _bufsize - 4); if (n <= 0) return char_traits::eof(); this->setg(_pReadBuffer + (4 - putback), _pReadBuffer + 4, _pReadBuffer + 4 + n); // return next character return char_traits::to_int_type(*this->gptr()); } virtual int sync() { if (this->pptr() && this->pptr() > this->pbase()) { if (flushBuffer() == -1) return -1; } return 0; } protected: void setMode(openmode mode) { _mode = mode; } openmode getMode() const { return _mode; } void resetBuffers() { this->setg(_pReadBuffer + 4, _pReadBuffer + 4, _pReadBuffer + 4); this->setp(_pWriteBuffer, _pWriteBuffer + (_bufsize - 1)); } private: virtual int readFromDevice(char_type* /*buffer*/, std::streamsize /*length*/) { return 0; } virtual int writeToDevice(const char_type* /*buffer*/, std::streamsize /*length*/) { return 0; } int flushBuffer() { int n = int(this->pptr() - this->pbase()); if (writeToDevice(this->pbase(), n) == n) { this->pbump(-n); return n; } return -1; } std::streamsize _bufsize; char_type* _pReadBuffer; char_type* _pWriteBuffer; openmode _mode; BasicBufferedBidirectionalStreamBuf(const BasicBufferedBidirectionalStreamBuf&); BasicBufferedBidirectionalStreamBuf& operator = (const BasicBufferedBidirectionalStreamBuf&); }; // // We provide an instantiation for char // typedef BasicBufferedBidirectionalStreamBuf<char, std::char_traits<char> > BufferedBidirectionalStreamBuf; } // namespace Poco #endif // Foundation_BufferedBidirectionalStreamBuf_INCLUDED
1,636
3,263
<filename>value-fixture/src/android/os/SparseBooleanArray.java //THIS IS STUB!!!! package android.os; public interface SparseBooleanArray { int size(); int keyAt(int i); boolean valueAt(int i); }
71
3,434
package com.alicp.jetcache; import com.alicp.jetcache.event.CacheEvent; /** * Created on 2016/10/25. * * @author <a href="mailto:<EMAIL>">huangli</a> */ @FunctionalInterface public interface CacheMonitor { void afterOperation(CacheEvent event); }
95
678
{ "screengrab":{ "OS": ["windows","linux","darwin"], "Server": true, "Arguments": {}, "RunType": ["drop"], "Info": "Screengrab will return a screenshot for each screen the user has", "Example": "module drop screengrab", "ModuleType": "collection" }, "minidump":{ "OS": ["windows"], "Server": true, "Arguments": {"pid":""}, "RunType": ["drop"], "Info": "Minidump will get a minidump of the given process's memory", "Example": "module drop minidump <pid>", "ModuleType": "credentialaccess" }, "shadowdump":{ "OS": ["linux"], "Server": true, "Arguments": {"pid":""}, "RunType": ["drop"], "Info": "ShadowDump will grab the /etc/passwd and /etc/shadow files and format them to a hashcat crackable file", "Example": "module drop shadowdump", "ModuleType": "credentialaccess" }, "lsadump":{ "OS": ["windows"], "Server": true, "Arguments": {"pid":""}, "RunType": ["drop"], "Info": "LSADump will grab the SYSTEM and SECURITY hive files and then extract the LSA Secrets from them", "Example": "module drop lsadump", "ModuleType": "credentialaccess" }, "ntdsdump":{ "OS": ["windows"], "Server": true, "Arguments": {"pid":""}, "RunType": ["drop"], "Info": "NTDSDump will dump the ntds.dit file using the VSS method", "Example": "module drop ntdsdump", "ModuleType": "credentialaccess" }, "samdump":{ "OS": ["windows"], "Server": true, "Arguments": {"pid":""}, "RunType": ["drop"], "Info": "SAMDump will grab the SYSTEM, SAM, and SECURITY hive files and then extract hashes from them", "Example": "module drop samdump", "ModuleType": "credentialaccess" } }
850
2,151
// 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 UI_EVENTS_DEVICES_X11_DEVICE_LIST_CACHE_X11_H_ #define UI_EVENTS_DEVICES_X11_DEVICE_LIST_CACHE_X11_H_ #include <map> #include <memory> #include "base/macros.h" #include "ui/events/devices/x11/events_devices_x11_export.h" #include "ui/gfx/x/x11.h" #include "ui/gfx/x/x11_types.h" namespace base { template <typename T> struct DefaultSingletonTraits; } typedef struct _XDisplay Display; template <typename T, void (*D)(T*)> struct DeviceList { DeviceList() : count(0) {} T& operator[](int x) { return devices[x]; } const T& operator[](int x) const { return devices[x]; } std::unique_ptr<T[], gfx::XObjectDeleter<T, void, D>> devices; int count; }; typedef struct DeviceList<XDeviceInfo, XFreeDeviceList> XDeviceList; typedef struct DeviceList<XIDeviceInfo, XIFreeDeviceInfo> XIDeviceList; namespace ui { // A class to cache the current XInput device list. This minimized the // round-trip time to the X server whenever such a device list is needed. The // update function will be called on each incoming XI_HierarchyChanged event. class EVENTS_DEVICES_X11_EXPORT DeviceListCacheX11 { public: static DeviceListCacheX11* GetInstance(); void UpdateDeviceList(Display* display); // Returns the list of devices associated with |display|. Uses the old X11 // protocol to get the list of the devices. const XDeviceList& GetXDeviceList(Display* display); // Returns the list of devices associated with |display|. Uses the newer // XINPUT2 protocol to get the list of devices. Before making this call, make // sure that XInput2 support is available (e.g. by calling // IsXInput2Available()). const XIDeviceList& GetXI2DeviceList(Display* display); private: friend struct base::DefaultSingletonTraits<DeviceListCacheX11>; DeviceListCacheX11(); ~DeviceListCacheX11(); XDeviceList x_dev_list_; XIDeviceList xi_dev_list_; DISALLOW_COPY_AND_ASSIGN(DeviceListCacheX11); }; } // namespace ui #endif // UI_EVENTS_DEVICES_X11_DEVICE_LIST_CACHE_X11_H_
737
336
<gh_stars>100-1000 /* * Terminal-BASIC is a lightweight BASIC-like language interpreter * * Copyright (C) 2016-2018 <NAME> <<EMAIL>> * Copyright (C) 2019,2020 Terminal-BASIC team * <https://bitbucket.org/%7Bf50d6fee-8627-4ce4-848d-829168eedae5%7D/> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * @file basic_dataparser.hpp */ #ifndef BASIC_DATAPARSER_HPP #define BASIC_DATAPARSER_HPP #include "basic_interpreter.hpp" namespace BASIC { class DataParser { public: DataParser(Interpreter&); bool searchData(const uint8_t*, Parser::Value&); bool read(const uint8_t*, Parser::Value&); const Lexer &lexer() const { return _lexer; } private: bool readValue(Parser::Value&); Lexer _lexer; Interpreter &_interpreter; }; } // namespace BASIC #endif // BASIC_DATAPARSER_HPP
477
2,104
<reponame>0xsan-z/AFLplusplus<filename>unicorn_mode/helper_scripts/unicorn_loader.py """ unicorn_loader.py Loads a process context dumped created using a Unicorn Context Dumper script into a Unicorn Engine instance. Once this is performed emulation can be started. """ import argparse import binascii from collections import namedtuple import datetime import hashlib import json import os import signal import struct import time import zlib # Unicorn imports from unicornafl import * from unicornafl.arm_const import * from unicornafl.arm64_const import * from unicornafl.x86_const import * from unicornafl.mips_const import * # If Capstone libraries are availible (only check once) try: from capstone import * CAPSTONE_EXISTS = 1 except: CAPSTONE_EXISTS = 0 # Name of the index file INDEX_FILE_NAME = "_index.json" # Page size required by Unicorn UNICORN_PAGE_SIZE = 0x1000 # Max allowable segment size (1G) MAX_ALLOWABLE_SEG_SIZE = 1024 * 1024 * 1024 # Alignment functions to align all memory segments to Unicorn page boundaries (4KB pages only) ALIGN_PAGE_DOWN = lambda x: x & ~(UNICORN_PAGE_SIZE - 1) ALIGN_PAGE_UP = lambda x: (x + UNICORN_PAGE_SIZE - 1) & ~(UNICORN_PAGE_SIZE - 1) # --------------------------------------- # ---- Unicorn-based heap implementation class UnicornSimpleHeap(object): """Use this class to provide a simple heap implementation. This should be used if malloc/free calls break things during emulation. This heap also implements basic guard-page capabilities which enable immediate notice of heap overflow and underflows. """ # Helper data-container used to track chunks class HeapChunk(object): def __init__(self, actual_addr, total_size, data_size): self.total_size = ( total_size # Total size of the chunk (including padding and guard page) ) self.actual_addr = actual_addr # Actual start address of the chunk self.data_size = ( data_size # Size requested by the caller of actual malloc call ) self.data_addr = ( actual_addr + UNICORN_PAGE_SIZE ) # Address where data actually starts # Returns true if the specified buffer is completely within the chunk, else false def is_buffer_in_chunk(self, addr, size): if addr >= self.data_addr and ( (addr + size) <= (self.data_addr + self.data_size) ): return True else: return False # Skip the zero-page to avoid weird potential issues with segment registers HEAP_MIN_ADDR = 0x00002000 HEAP_MAX_ADDR = 0xFFFFFFFF _uc = None # Unicorn engine instance to interact with _chunks = [] # List of all known chunks _debug_print = False # True to print debug information def __init__(self, uc, debug_print=False): self._uc = uc self._debug_print = debug_print # Add the watchpoint hook that will be used to implement psuedo-guard page support self._uc.hook_add(UC_HOOK_MEM_WRITE | UC_HOOK_MEM_READ, self.__check_mem_access) def malloc(self, size): # Figure out the overall size to be allocated/mapped # - Allocate at least 1 4k page of memory to make Unicorn happy # - Add guard pages at the start and end of the region total_chunk_size = UNICORN_PAGE_SIZE + ALIGN_PAGE_UP(size) + UNICORN_PAGE_SIZE # Gross but efficient way to find space for the chunk: chunk = None for addr in range(self.HEAP_MIN_ADDR, self.HEAP_MAX_ADDR, UNICORN_PAGE_SIZE): try: self._uc.mem_map(addr, total_chunk_size, UC_PROT_READ | UC_PROT_WRITE) chunk = self.HeapChunk(addr, total_chunk_size, size) if self._debug_print: print( "Allocating 0x{0:x}-byte chunk @ 0x{1:016x}".format( chunk.data_size, chunk.data_addr ) ) break except UcError as e: continue # Something went very wrong if chunk == None: return 0 self._chunks.append(chunk) return chunk.data_addr def calloc(self, size, count): # Simple wrapper around malloc with calloc() args return self.malloc(size * count) def realloc(self, ptr, new_size): # Wrapper around malloc(new_size) / memcpy(new, old, old_size) / free(old) if self._debug_print: print( "Reallocating chunk @ 0x{0:016x} to be 0x{1:x} bytes".format( ptr, new_size ) ) old_chunk = None for chunk in self._chunks: if chunk.data_addr == ptr: old_chunk = chunk new_chunk_addr = self.malloc(new_size) if old_chunk != None: self._uc.mem_write( new_chunk_addr, str(self._uc.mem_read(old_chunk.data_addr, old_chunk.data_size)), ) self.free(old_chunk.data_addr) return new_chunk_addr def free(self, addr): for chunk in self._chunks: if chunk.is_buffer_in_chunk(addr, 1): if self._debug_print: print( "Freeing 0x{0:x}-byte chunk @ 0x{0:016x}".format( chunk.req_size, chunk.data_addr ) ) self._uc.mem_unmap(chunk.actual_addr, chunk.total_size) self._chunks.remove(chunk) return True return False # Implements basic guard-page functionality def __check_mem_access(self, uc, access, address, size, value, user_data): for chunk in self._chunks: if address >= chunk.actual_addr and ( (address + size) <= (chunk.actual_addr + chunk.total_size) ): if chunk.is_buffer_in_chunk(address, size) == False: if self._debug_print: print( "Heap over/underflow attempting to {0} 0x{1:x} bytes @ {2:016x}".format( "write" if access == UC_MEM_WRITE else "read", size, address, ) ) # Force a memory-based crash uc.force_crash(UcError(UC_ERR_READ_PROT)) # --------------------------- # ---- Loading function class AflUnicornEngine(Uc): def __init__(self, context_directory, enable_trace=False, debug_print=False): """ Initializes an AflUnicornEngine instance, which extends standard the UnicornEngine with a bunch of helper routines that are useful for creating afl-unicorn test harnesses. Parameters: - context_directory: Path to the directory generated by one of the context dumper scripts - enable_trace: If True trace information will be printed to STDOUT - debug_print: If True debugging information will be printed while loading the context """ # Make sure the index file exists and load it index_file_path = os.path.join(context_directory, INDEX_FILE_NAME) if not os.path.isfile(index_file_path): raise Exception( "Index file not found. Expected it to be at {}".format(index_file_path) ) # Load the process context from the index file if debug_print: print("Loading process context index from {}".format(index_file_path)) index_file = open(index_file_path, "r") context = json.load(index_file) index_file.close() # Check the context to make sure we have the basic essential components if "arch" not in context: raise Exception("Couldn't find architecture information in index file") if "regs" not in context: raise Exception("Couldn't find register information in index file") if "segments" not in context: raise Exception("Couldn't find segment/memory information in index file") # Set the UnicornEngine instance's architecture and mode self._arch_str = context["arch"]["arch"] arch, mode = self.__get_arch_and_mode(self._arch_str) Uc.__init__(self, arch, mode) # Load the registers regs = context["regs"] reg_map = self.__get_register_map(self._arch_str) self.__load_registers(regs, reg_map, debug_print) # If we have extra FLOATING POINT regs, load them in! if "regs_extended" in context: if context["regs_extended"]: regs_extended = context["regs_extended"] reg_map = self.__get_registers_extended(self._arch_str) self.__load_registers(regs_extended, reg_map, debug_print) # For ARM, sometimes the stack pointer is erased ??? (I think I fixed this (issue with ordering of dumper.py, I'll keep the write anyways) if self.__get_arch_and_mode(self.get_arch_str())[0] == UC_ARCH_ARM: self.reg_write(UC_ARM_REG_SP, regs["sp"]) # Setup the memory map and load memory content self.__map_segments(context["segments"], context_directory, debug_print) if enable_trace: self.hook_add(UC_HOOK_BLOCK, self.__trace_block) self.hook_add(UC_HOOK_CODE, self.__trace_instruction) self.hook_add(UC_HOOK_MEM_WRITE | UC_HOOK_MEM_READ, self.__trace_mem_access) self.hook_add( UC_HOOK_MEM_WRITE_UNMAPPED | UC_HOOK_MEM_READ_INVALID, self.__trace_mem_invalid_access, ) if debug_print: print("Done loading context.") def get_arch(self): return self._arch def get_mode(self): return self._mode def get_arch_str(self): return self._arch_str def force_crash(self, uc_error): """This function should be called to indicate to AFL that a crash occurred during emulation. You can pass the exception received from Uc.emu_start """ mem_errors = [ UC_ERR_READ_UNMAPPED, UC_ERR_READ_PROT, UC_ERR_READ_UNALIGNED, UC_ERR_WRITE_UNMAPPED, UC_ERR_WRITE_PROT, UC_ERR_WRITE_UNALIGNED, UC_ERR_FETCH_UNMAPPED, UC_ERR_FETCH_PROT, UC_ERR_FETCH_UNALIGNED, ] if uc_error.errno in mem_errors: # Memory error - throw SIGSEGV os.kill(os.getpid(), signal.SIGSEGV) elif uc_error.errno == UC_ERR_INSN_INVALID: # Invalid instruction - throw SIGILL os.kill(os.getpid(), signal.SIGILL) else: # Not sure what happened - throw SIGABRT os.kill(os.getpid(), signal.SIGABRT) def dump_regs(self): """ Dumps the contents of all the registers to STDOUT """ for reg in sorted( self.__get_register_map(self._arch_str).items(), key=lambda reg: reg[0] ): print(">>> {0:>4}: 0x{1:016x}".format(reg[0], self.reg_read(reg[1]))) def dump_regs_extended(self): """ Dumps the contents of all the registers to STDOUT """ try: for reg in sorted( self.__get_registers_extended(self._arch_str).items(), key=lambda reg: reg[0], ): print(">>> {0:>4}: 0x{1:016x}".format(reg[0], self.reg_read(reg[1]))) except Exception as e: print("ERROR: Are extended registers loaded?") # TODO: Make this dynamically get the stack pointer register and pointer width for the current architecture """ def dump_stack(self, window=10): arch = self.get_arch() mode = self.get_mode() # Get stack pointers and bit sizes for given architecture if arch == UC_ARCH_X86 and mode == UC_MODE_64: stack_ptr_addr = self.reg_read(UC_X86_REG_RSP) bit_size = 8 elif arch == UC_ARCH_X86 and mode == UC_MODE_32: stack_ptr_addr = self.reg_read(UC_X86_REG_ESP) bit_size = 4 elif arch == UC_ARCH_ARM64: stack_ptr_addr = self.reg_read(UC_ARM64_REG_SP) bit_size = 8 elif arch == UC_ARCH_ARM: stack_ptr_addr = self.reg_read(UC_ARM_REG_SP) bit_size = 4 elif arch == UC_ARCH_ARM and mode == UC_MODE_THUMB: stack_ptr_addr = self.reg_read(UC_ARM_REG_SP) bit_size = 4 elif arch == UC_ARCH_MIPS: stack_ptr_addr = self.reg_read(UC_MIPS_REG_SP) bit_size = 4 print("") print(">>> Stack:") stack_ptr_addr = self.reg_read(UC_X86_REG_RSP) for i in xrange(-window, window + 1): addr = stack_ptr_addr + (i*8) print("{0}0x{1:016x}: 0x{2:016x}".format( \ 'SP->' if i == 0 else ' ', addr, \ struct.unpack('<Q', self.mem_read(addr, 8))[0])) """ # ----------------------------- # ---- Loader Helper Functions def __load_registers(self, regs, reg_map, debug_print): for register, value in regs.items(): if debug_print: print("Reg {0} = {1}".format(register, value)) if register.lower() not in reg_map: if debug_print: print("Skipping Reg: {}".format(register)) else: reg_write_retry = True try: self.reg_write(reg_map[register.lower()], value) reg_write_retry = False except Exception as e: if debug_print: print( "ERROR writing register: {}, value: {} -- {}".format( register, value, repr(e) ) ) if reg_write_retry: if debug_print: print("Trying to parse value ({}) as hex string".format(value)) try: self.reg_write(reg_map[register.lower()], int(value, 16)) except Exception as e: if debug_print: print( "ERROR writing hex string register: {}, value: {} -- {}".format( register, value, repr(e) ) ) def __map_segment(self, name, address, size, perms, debug_print=False): # - size is unsigned and must be != 0 # - starting address must be aligned to 4KB # - map size must be multiple of the page size (4KB) mem_start = address mem_end = address + size mem_start_aligned = ALIGN_PAGE_DOWN(mem_start) mem_end_aligned = ALIGN_PAGE_UP(mem_end) if debug_print: if mem_start_aligned != mem_start or mem_end_aligned != mem_end: print("Aligning segment to page boundary:") print(" name: {}".format(name)) print( " start: {0:016x} -> {1:016x}".format(mem_start, mem_start_aligned) ) print(" end: {0:016x} -> {1:016x}".format(mem_end, mem_end_aligned)) print( "Mapping segment from {0:016x} - {1:016x} with perm={2}: {3}".format( mem_start_aligned, mem_end_aligned, perms, name ) ) if mem_start_aligned < mem_end_aligned: self.mem_map(mem_start_aligned, mem_end_aligned - mem_start_aligned, perms) def __map_segments(self, segment_list, context_directory, debug_print=False): for segment in segment_list: # Get the segment information from the index name = segment["name"] seg_start = segment["start"] seg_end = segment["end"] perms = ( (UC_PROT_READ if segment["permissions"]["r"] == True else 0) | (UC_PROT_WRITE if segment["permissions"]["w"] == True else 0) | (UC_PROT_EXEC if segment["permissions"]["x"] == True else 0) ) if debug_print: print("Handling segment {}".format(name)) # Check for any overlap with existing segments. If there is, it must # be consolidated and merged together before mapping since Unicorn # doesn't allow overlapping segments. found = False overlap_start = False overlap_end = False tmp = 0 for (mem_start, mem_end, mem_perm) in self.mem_regions(): mem_end = mem_end + 1 if seg_start >= mem_start and seg_end < mem_end: found = True break if seg_start >= mem_start and seg_start < mem_end: overlap_start = True tmp = mem_end break if seg_end >= mem_start and seg_end < mem_end: overlap_end = True tmp = mem_start break # Map memory into the address space if it is of an acceptable size. if (seg_end - seg_start) > MAX_ALLOWABLE_SEG_SIZE: if debug_print: print( "Skipping segment (LARGER THAN {0}) from {1:016x} - {2:016x} with perm={3}: {4}".format( MAX_ALLOWABLE_SEG_SIZE, seg_start, seg_end, perms, name ) ) continue elif not found: # Make sure it's not already mapped if overlap_start: # Partial overlap (start) self.__map_segment(name, tmp, seg_end - tmp, perms, debug_print) elif overlap_end: # Patrial overlap (end) self.__map_segment( name, seg_start, tmp - seg_start, perms, debug_print ) else: # Not found self.__map_segment( name, seg_start, seg_end - seg_start, perms, debug_print ) else: if debug_print: print("Segment {} already mapped. Moving on.".format(name)) # Load the content (if available) if "content_file" in segment and len(segment["content_file"]) > 0: content_file_path = os.path.join( context_directory, segment["content_file"] ) if not os.path.isfile(content_file_path): raise Exception( "Unable to find segment content file. Expected it to be at {}".format( content_file_path ) ) # if debug_print: # print("Loading content for segment {} from {}".format(name, segment['content_file'])) content_file = open(content_file_path, "rb") compressed_content = content_file.read() content_file.close() self.mem_write(seg_start, zlib.decompress(compressed_content)) else: if debug_print: print( "No content found for segment {0} @ {1:016x}".format( name, seg_start ) ) self.mem_write(seg_start, b"\x00" * (seg_end - seg_start)) def __get_arch_and_mode(self, arch_str): arch_map = { "x64": [UC_X86_REG_RIP, UC_ARCH_X86, UC_MODE_64], "x86": [UC_X86_REG_EIP, UC_ARCH_X86, UC_MODE_32], "arm64be": [ UC_ARM64_REG_PC, UC_ARCH_ARM64, UC_MODE_ARM | UC_MODE_BIG_ENDIAN, ], "arm64le": [ UC_ARM64_REG_PC, UC_ARCH_ARM64, UC_MODE_ARM | UC_MODE_LITTLE_ENDIAN, ], "armbe": [UC_ARM_REG_PC, UC_ARCH_ARM, UC_MODE_ARM | UC_MODE_BIG_ENDIAN], "armle": [UC_ARM_REG_PC, UC_ARCH_ARM, UC_MODE_ARM | UC_MODE_LITTLE_ENDIAN], "armbethumb": [ UC_ARM_REG_PC, UC_ARCH_ARM, UC_MODE_THUMB | UC_MODE_BIG_ENDIAN, ], "armlethumb": [ UC_ARM_REG_PC, UC_ARCH_ARM, UC_MODE_THUMB | UC_MODE_LITTLE_ENDIAN, ], "mips": [UC_MIPS_REG_PC, UC_ARCH_MIPS, UC_MODE_MIPS32 | UC_MODE_BIG_ENDIAN], "mipsel": [ UC_MIPS_REG_PC, UC_ARCH_MIPS, UC_MODE_MIPS32 | UC_MODE_LITTLE_ENDIAN, ], } return (arch_map[arch_str][1], arch_map[arch_str][2]) def __get_register_map(self, arch): if arch == "arm64le" or arch == "arm64be": arch = "arm64" elif arch == "armle" or arch == "armbe" or "thumb" in arch: arch = "arm" elif arch == "mipsel": arch = "mips" registers = { "x64": { "rax": UC_X86_REG_RAX, "rbx": UC_X86_REG_RBX, "rcx": UC_X86_REG_RCX, "rdx": UC_X86_REG_RDX, "rsi": UC_X86_REG_RSI, "rdi": UC_X86_REG_RDI, "rbp": UC_X86_REG_RBP, "rsp": UC_X86_REG_RSP, "r8": UC_X86_REG_R8, "r9": UC_X86_REG_R9, "r10": UC_X86_REG_R10, "r11": UC_X86_REG_R11, "r12": UC_X86_REG_R12, "r13": UC_X86_REG_R13, "r14": UC_X86_REG_R14, "r15": UC_X86_REG_R15, "rip": UC_X86_REG_RIP, "efl": UC_X86_REG_EFLAGS, "cs": UC_X86_REG_CS, "ds": UC_X86_REG_DS, "es": UC_X86_REG_ES, "fs": UC_X86_REG_FS, "gs": UC_X86_REG_GS, "ss": UC_X86_REG_SS, }, "x86": { "eax": UC_X86_REG_EAX, "ebx": UC_X86_REG_EBX, "ecx": UC_X86_REG_ECX, "edx": UC_X86_REG_EDX, "esi": UC_X86_REG_ESI, "edi": UC_X86_REG_EDI, "ebp": UC_X86_REG_EBP, "eip": UC_X86_REG_EIP, "esp": UC_X86_REG_ESP, "efl": UC_X86_REG_EFLAGS, # Segment registers removed... # They caused segfaults (from unicorn?) when they were here }, "arm": { "r0": UC_ARM_REG_R0, "r1": UC_ARM_REG_R1, "r2": UC_ARM_REG_R2, "r3": UC_ARM_REG_R3, "r4": UC_ARM_REG_R4, "r5": UC_ARM_REG_R5, "r6": UC_ARM_REG_R6, "r7": UC_ARM_REG_R7, "r8": UC_ARM_REG_R8, "r9": UC_ARM_REG_R9, "r10": UC_ARM_REG_R10, "r11": UC_ARM_REG_R11, "r12": UC_ARM_REG_R12, "pc": UC_ARM_REG_PC, "sp": UC_ARM_REG_SP, "lr": UC_ARM_REG_LR, "cpsr": UC_ARM_REG_CPSR, }, "arm64": { "x0": UC_ARM64_REG_X0, "x1": UC_ARM64_REG_X1, "x2": UC_ARM64_REG_X2, "x3": UC_ARM64_REG_X3, "x4": UC_ARM64_REG_X4, "x5": UC_ARM64_REG_X5, "x6": UC_ARM64_REG_X6, "x7": UC_ARM64_REG_X7, "x8": UC_ARM64_REG_X8, "x9": UC_ARM64_REG_X9, "x10": UC_ARM64_REG_X10, "x11": UC_ARM64_REG_X11, "x12": UC_ARM64_REG_X12, "x13": UC_ARM64_REG_X13, "x14": UC_ARM64_REG_X14, "x15": UC_ARM64_REG_X15, "x16": UC_ARM64_REG_X16, "x17": UC_ARM64_REG_X17, "x18": UC_ARM64_REG_X18, "x19": UC_ARM64_REG_X19, "x20": UC_ARM64_REG_X20, "x21": UC_ARM64_REG_X21, "x22": UC_ARM64_REG_X22, "x23": UC_ARM64_REG_X23, "x24": UC_ARM64_REG_X24, "x25": UC_ARM64_REG_X25, "x26": UC_ARM64_REG_X26, "x27": UC_ARM64_REG_X27, "x28": UC_ARM64_REG_X28, "pc": UC_ARM64_REG_PC, "sp": UC_ARM64_REG_SP, "fp": UC_ARM64_REG_FP, "lr": UC_ARM64_REG_LR, "nzcv": UC_ARM64_REG_NZCV, "cpsr": UC_ARM_REG_CPSR, }, "mips": { "0": UC_MIPS_REG_ZERO, "at": UC_MIPS_REG_AT, "v0": UC_MIPS_REG_V0, "v1": UC_MIPS_REG_V1, "a0": UC_MIPS_REG_A0, "a1": UC_MIPS_REG_A1, "a2": UC_MIPS_REG_A2, "a3": UC_MIPS_REG_A3, "t0": UC_MIPS_REG_T0, "t1": UC_MIPS_REG_T1, "t2": UC_MIPS_REG_T2, "t3": UC_MIPS_REG_T3, "t4": UC_MIPS_REG_T4, "t5": UC_MIPS_REG_T5, "t6": UC_MIPS_REG_T6, "t7": UC_MIPS_REG_T7, "t8": UC_MIPS_REG_T8, "t9": UC_MIPS_REG_T9, "s0": UC_MIPS_REG_S0, "s1": UC_MIPS_REG_S1, "s2": UC_MIPS_REG_S2, "s3": UC_MIPS_REG_S3, "s4": UC_MIPS_REG_S4, "s5": UC_MIPS_REG_S5, "s6": UC_MIPS_REG_S6, "s7": UC_MIPS_REG_S7, "s8": UC_MIPS_REG_S8, "k0": UC_MIPS_REG_K0, "k1": UC_MIPS_REG_K1, "gp": UC_MIPS_REG_GP, "pc": UC_MIPS_REG_PC, "sp": UC_MIPS_REG_SP, "fp": UC_MIPS_REG_FP, "ra": UC_MIPS_REG_RA, "hi": UC_MIPS_REG_HI, "lo": UC_MIPS_REG_LO, }, } return registers[arch] def __get_registers_extended(self, arch): # Similar to __get_register_map, but for ARM floating point registers if arch == "arm64le" or arch == "arm64be": arch = "arm64" elif arch == "armle" or arch == "armbe" or "thumb" in arch: arch = "arm" elif arch == "mipsel": arch = "mips" registers = { "arm": { "d0": UC_ARM_REG_D0, "d1": UC_ARM_REG_D1, "d2": UC_ARM_REG_D2, "d3": UC_ARM_REG_D3, "d4": UC_ARM_REG_D4, "d5": UC_ARM_REG_D5, "d6": UC_ARM_REG_D6, "d7": UC_ARM_REG_D7, "d8": UC_ARM_REG_D8, "d9": UC_ARM_REG_D9, "d10": UC_ARM_REG_D10, "d11": UC_ARM_REG_D11, "d12": UC_ARM_REG_D12, "d13": UC_ARM_REG_D13, "d14": UC_ARM_REG_D14, "d15": UC_ARM_REG_D15, "d16": UC_ARM_REG_D16, "d17": UC_ARM_REG_D17, "d18": UC_ARM_REG_D18, "d19": UC_ARM_REG_D19, "d20": UC_ARM_REG_D20, "d21": UC_ARM_REG_D21, "d22": UC_ARM_REG_D22, "d23": UC_ARM_REG_D23, "d24": UC_ARM_REG_D24, "d25": UC_ARM_REG_D25, "d26": UC_ARM_REG_D26, "d27": UC_ARM_REG_D27, "d28": UC_ARM_REG_D28, "d29": UC_ARM_REG_D29, "d30": UC_ARM_REG_D30, "d31": UC_ARM_REG_D31, "fpscr": UC_ARM_REG_FPSCR, } } return registers[arch] # --------------------------- # Callbacks for tracing # TODO: Extra mode for Capstone (i.e. Cs(cs_arch, cs_mode + cs_extra) not implemented def __trace_instruction(self, uc, address, size, user_data): if CAPSTONE_EXISTS == 1: # If Capstone is installed then we'll dump disassembly, otherwise just dump the binary. arch = self.get_arch() mode = self.get_mode() bit_size = self.bit_size_arch() # Map current arch to capstone labeling if arch == UC_ARCH_X86 and mode == UC_MODE_64: cs_arch = CS_ARCH_X86 cs_mode = CS_MODE_64 elif arch == UC_ARCH_X86 and mode == UC_MODE_32: cs_arch = CS_ARCH_X86 cs_mode = CS_MODE_32 elif arch == UC_ARCH_ARM64: cs_arch = CS_ARCH_ARM64 cs_mode = CS_MODE_ARM elif arch == UC_ARCH_ARM and mode == UC_MODE_THUMB: cs_arch = CS_ARCH_ARM cs_mode = CS_MODE_THUMB elif arch == UC_ARCH_ARM: cs_arch = CS_ARCH_ARM cs_mode = CS_MODE_ARM elif arch == UC_ARCH_MIPS: cs_arch = CS_ARCH_MIPS cs_mode = CS_MODE_MIPS32 # No other MIPS supported in program cs = Cs(cs_arch, cs_mode) mem = uc.mem_read(address, size) if bit_size == 4: for (cs_address, cs_size, cs_mnemonic, cs_opstr) in cs.disasm_lite( bytes(mem), size ): print( " Instr: {:#08x}:\t{}\t{}".format( address, cs_mnemonic, cs_opstr ) ) else: for (cs_address, cs_size, cs_mnemonic, cs_opstr) in cs.disasm_lite( bytes(mem), size ): print( " Instr: {:#16x}:\t{}\t{}".format( address, cs_mnemonic, cs_opstr ) ) else: print(" Instr: addr=0x{0:016x}, size=0x{1:016x}".format(address, size)) def __trace_block(self, uc, address, size, user_data): print("Basic Block: addr=0x{0:016x}, size=0x{1:016x}".format(address, size)) def __trace_mem_access(self, uc, access, address, size, value, user_data): if access == UC_MEM_WRITE: print( " >>> Write: addr=0x{0:016x} size={1} data=0x{2:016x}".format( address, size, value ) ) else: print(" >>> Read: addr=0x{0:016x} size={1}".format(address, size)) def __trace_mem_invalid_access(self, uc, access, address, size, value, user_data): if access == UC_MEM_WRITE_UNMAPPED: print( " >>> INVALID Write: addr=0x{0:016x} size={1} data=0x{2:016x}".format( address, size, value ) ) else: print( " >>> INVALID Read: addr=0x{0:016x} size={1}".format( address, size ) ) def bit_size_arch(self): arch = self.get_arch() mode = self.get_mode() # Get bit sizes for given architecture if arch == UC_ARCH_X86 and mode == UC_MODE_64: bit_size = 8 elif arch == UC_ARCH_X86 and mode == UC_MODE_32: bit_size = 4 elif arch == UC_ARCH_ARM64: bit_size = 8 elif arch == UC_ARCH_ARM: bit_size = 4 elif arch == UC_ARCH_MIPS: bit_size = 4 return bit_size
18,053
3,189
<reponame>chengchenwish/evpp<gh_stars>1000+ #pragma once #include <evpp/tcp_conn.h> #include <thrift/protocol/TProtocol.h> #include <thrift/transport/TBufferTransports.h> #include <thrift/transport/TTransportUtils.h> namespace evthrift { using apache::thrift::TProcessor; using apache::thrift::protocol::TProtocol; using apache::thrift::transport::TMemoryBuffer; using apache::thrift::transport::TNullTransport; using apache::thrift::transport::TTransport; using apache::thrift::transport::TTransportException; class ThriftServer; class ThriftConn : public std::enable_shared_from_this<ThriftConn> { public: enum State { kExpectFrameSize, kExpectFrame }; ThriftConn(ThriftServer* server, const evpp::TCPConnPtr& conn); private: friend class ThriftServer; void OnMessage(const evpp::TCPConnPtr& conn, evpp::Buffer* buffer); void Process(); void Close(); private: ThriftServer* server_; evpp::TCPConnPtr conn_; boost::shared_ptr<TNullTransport> nullTransport_; boost::shared_ptr<TMemoryBuffer> inputTransport_; boost::shared_ptr<TMemoryBuffer> outputTransport_; boost::shared_ptr<TTransport> factoryInputTransport_; boost::shared_ptr<TTransport> factoryOutputTransport_; boost::shared_ptr<TProtocol> inputProtocol_; boost::shared_ptr<TProtocol> outputProtocol_; boost::shared_ptr<TProcessor> processor_; enum State state_; uint32_t frameSize_; }; typedef std::shared_ptr<ThriftConn> ThriftConnectionPtr; }
590
5,813
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.druid.query.lookup; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableList; import com.google.inject.Binder; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.Module; import org.apache.druid.guice.GuiceInjectors; import org.apache.druid.guice.JsonConfigProvider; import org.apache.druid.guice.annotations.Json; import org.apache.druid.guice.annotations.Self; import org.apache.druid.initialization.Initialization; import org.apache.druid.server.DruidNode; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.util.Map; public class LookupUtilsTest { private static final TypeReference<Map<String, Object>> LOOKUPS_ALL_GENERIC_REFERENCE = new TypeReference<Map<String, Object>>() { }; private static final TypeReference<Map<String, LookupExtractorFactoryContainer>> LOOKUPS_ALL_REFERENCE = new TypeReference<Map<String, LookupExtractorFactoryContainer>>() { }; private static final String LOOKUP_VALID_INNER = " \"lookup_uri_good\": {\n" + " \"version\": \"2021-12-03T01:04:05.151Z\",\n" + " \"lookupExtractorFactory\": {\n" + " \"type\": \"cachedNamespace\",\n" + " \"extractionNamespace\": {\n" + " \"type\": \"uri\",\n" + " \"uri\": \"file:///home/lookup_data.json\",\n" + " \"namespaceParseSpec\": {\n" + " \"format\": \"simpleJson\"\n" + " },\n" + " \"pollPeriod\": \"PT30S\",\n" + " \"maxHeapPercentage\": 1\n" + " }\n" + " }\n" + " }"; private static final String LOOKUP_VALID = "{\n" + LOOKUP_VALID_INNER + "\n" + "}"; private static final String LOOKUP_WITH_KEY_COLUMN_BUT_NO_VALUE_COLUMN_INNER = " \"lookup_keyColumn_but_no_valueColumn\": {\n" + " \"version\": \"2021-12-03T02:17:01.983Z\",\n" + " \"lookupExtractorFactory\": {\n" + " \"type\": \"cachedNamespace\",\n" + " \"extractionNamespace\": {\n" + " \"type\": \"uri\",\n" + " \"fileRegex\": \".*csv\",\n" + " \"uriPrefix\": \"s3://bucket/path/\",\n" + " \"namespaceParseSpec\": {\n" + " \"format\": \"csv\",\n" + " \"columns\": [\n" + " \"cluster_id\",\n" + " \"account_id\",\n" + " \"manager_host\"\n" + " ],\n" + " \"keyColumn\": \"cluster_id\",\n" + " \"hasHeaderRow\": true,\n" + " \"skipHeaderRows\": 1\n" + " },\n" + " \"pollPeriod\": \"PT30S\"\n" + " }\n" + " }\n" + " }"; private static final String LOOKUP_WITH_KEY_COLUMN_BUT_NO_VALUE_COLUMN = "{\n" + LOOKUP_WITH_KEY_COLUMN_BUT_NO_VALUE_COLUMN_INNER + "\n" + "}"; private static final String LOOKSUPS_INVALID_AND_VALID = "{\n" + LOOKUP_WITH_KEY_COLUMN_BUT_NO_VALUE_COLUMN_INNER + ",\n" + LOOKUP_VALID_INNER + "\n" + "}"; private ObjectMapper mapper; @Before public void setup() { final Injector injector = makeInjector(); mapper = injector.getInstance(Key.get(ObjectMapper.class, Json.class)); mapper.registerSubtypes(NamespaceLookupExtractorFactory.class); } @Test public void test_tryConvertObjectMapToLookupConfigMap_allValid() throws IOException { mapper.registerSubtypes(NamespaceLookupExtractorFactory.class); Map<String, LookupExtractorFactoryContainer> validLookupExpected = mapper.readValue( LOOKUP_VALID, LOOKUPS_ALL_REFERENCE); Map<String, Object> validLookupGeneric = mapper.readValue( LOOKUP_VALID, LOOKUPS_ALL_GENERIC_REFERENCE); Map<String, LookupExtractorFactoryContainer> actualLookup = LookupUtils.tryConvertObjectMapToLookupConfigMap(validLookupGeneric, mapper); Assert.assertEquals(mapper.writeValueAsString(validLookupExpected), mapper.writeValueAsString(actualLookup)); } @Test public void test_tryConvertObjectMapToLookupConfigMap_allInvalid_emptyMap() throws IOException { mapper.registerSubtypes(NamespaceLookupExtractorFactory.class); Map<String, Object> validLookupGeneric = mapper.readValue( LOOKUP_WITH_KEY_COLUMN_BUT_NO_VALUE_COLUMN, LOOKUPS_ALL_GENERIC_REFERENCE); Map<String, LookupExtractorFactoryContainer> actualLookup = LookupUtils.tryConvertObjectMapToLookupConfigMap(validLookupGeneric, mapper); Assert.assertTrue(actualLookup.isEmpty()); } @Test public void test_tryConvertObjectMapToLookupConfigMap_goodAndBadConfigs_skipsBad() throws IOException { mapper.registerSubtypes(NamespaceLookupExtractorFactory.class); Map<String, LookupExtractorFactoryContainer> validLookupExpected = mapper.readValue( LOOKUP_VALID, LOOKUPS_ALL_REFERENCE); Map<String, Object> validLookupGeneric = mapper.readValue( LOOKSUPS_INVALID_AND_VALID, LOOKUPS_ALL_GENERIC_REFERENCE); Map<String, LookupExtractorFactoryContainer> actualLookup = LookupUtils.tryConvertObjectMapToLookupConfigMap(validLookupGeneric, mapper); Assert.assertEquals(mapper.writeValueAsString(validLookupExpected), mapper.writeValueAsString(actualLookup)); } private Injector makeInjector() { return Initialization.makeInjectorWithModules( GuiceInjectors.makeStartupInjector(), ImmutableList.of( new Module() { @Override public void configure(Binder binder) { JsonConfigProvider.bindInstance( binder, Key.get(DruidNode.class, Self.class), new DruidNode("test-inject", null, false, null, null, true, false) ); } } ) ); } }
3,786
348
{"nom":"<NAME>","circ":"5ème circonscription","dpt":"Loire","inscrits":166,"abs":106,"votants":60,"blancs":8,"nuls":2,"exp":50,"res":[{"nuance":"MDM","nom":"<NAME>","voix":37},{"nuance":"LR","nom":"Mme <NAME>","voix":13}]}
91
1,050
import torch from torch.nn import functional as F # TODO: merge these two function def heatmap_focal_loss( inputs, targets, pos_inds, labels, alpha: float = -1, beta: float = 4, gamma: float = 2, reduction: str = 'sum', sigmoid_clamp: float = 1e-4, ignore_high_fp: float = -1., ): """ Loss used in RetinaNet for dense detection: https://arxiv.org/abs/1708.02002. Args: inputs: (sum_l N*Hl*Wl, C) targets: (sum_l N*Hl*Wl, C) pos_inds: N labels: N Returns: Loss tensor with the reduction option applied. """ pred = torch.clamp(inputs.sigmoid_(), min=sigmoid_clamp, max=1-sigmoid_clamp) neg_weights = torch.pow(1 - targets, beta) pos_pred_pix = pred[pos_inds] # N x C pos_pred = pos_pred_pix.gather(1, labels.unsqueeze(1)) pos_loss = torch.log(pos_pred) * torch.pow(1 - pos_pred, gamma) neg_loss = torch.log(1 - pred) * torch.pow(pred, gamma) * neg_weights if ignore_high_fp > 0: not_high_fp = (pred < ignore_high_fp).float() neg_loss = not_high_fp * neg_loss if reduction == "sum": pos_loss = pos_loss.sum() neg_loss = neg_loss.sum() if alpha >= 0: pos_loss = alpha * pos_loss neg_loss = (1 - alpha) * neg_loss return - pos_loss, - neg_loss heatmap_focal_loss_jit = torch.jit.script(heatmap_focal_loss) # heatmap_focal_loss_jit = heatmap_focal_loss def binary_heatmap_focal_loss( inputs, targets, pos_inds, alpha: float = -1, beta: float = 4, gamma: float = 2, sigmoid_clamp: float = 1e-4, ignore_high_fp: float = -1., ): """ Args: inputs: (sum_l N*Hl*Wl,) targets: (sum_l N*Hl*Wl,) pos_inds: N Returns: Loss tensor with the reduction option applied. """ pred = torch.clamp(inputs.sigmoid_(), min=sigmoid_clamp, max=1-sigmoid_clamp) neg_weights = torch.pow(1 - targets, beta) pos_pred = pred[pos_inds] # N pos_loss = torch.log(pos_pred) * torch.pow(1 - pos_pred, gamma) neg_loss = torch.log(1 - pred) * torch.pow(pred, gamma) * neg_weights if ignore_high_fp > 0: not_high_fp = (pred < ignore_high_fp).float() neg_loss = not_high_fp * neg_loss pos_loss = - pos_loss.sum() neg_loss = - neg_loss.sum() if alpha >= 0: pos_loss = alpha * pos_loss neg_loss = (1 - alpha) * neg_loss return pos_loss, neg_loss binary_heatmap_focal_loss_jit = torch.jit.script(binary_heatmap_focal_loss)
1,171
2,739
<filename>models/recall/mind/static_model.py # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # 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. import paddle import paddle.nn as nn import paddle.nn.functional as F import net import numpy as np class StaticModel(): """StaticModel """ def __init__(self, config): self.cost = None self.config = config self._init_hyper_parameters(config) def _init_hyper_parameters(self, config): self.item_count = config.get("hyper_parameters.item_count", None) self.embedding_dim = config.get("hyper_parameters.embedding_dim", 64) self.hidden_size = config.get("hyper_parameters.hidden_size", 64) self.neg_samples = config.get("hyper_parameters.neg_samples", 100) self.maxlen = config.get("hyper_parameters.maxlen", 30) self.pow_p = config.get("hyper_parameters.pow_p", 1.0) self.capsual_iters = config.get("hyper_parameters.capsual.iters", 3) self.capsual_max_k = config.get("hyper_parameters.capsual.max_k", 4) self.capsual_init_std = config.get("hyper_parameters.capsual.init_std", 1.0) self.lr = config.get("hyper_parameters.optimizer.learning_rate", 0.001) # define feeds which convert numpy of batch data to paddle.tensor def create_feeds(self, is_infer=False): # print(batch_data) if not is_infer: hist_item = paddle.static.data( name="hist_item", shape=[-1, self.maxlen], dtype="int64") target_item = paddle.static.data( name="target_item", shape=[-1, 1], dtype="int64") seq_len = paddle.static.data( name="seq_len", shape=[-1, 1], dtype="int64") return [hist_item, target_item, seq_len] else: hist_item = paddle.static.data( name="hist_item", shape=[-1, self.maxlen], dtype="int64") seq_len = paddle.static.data( name="seq_len", shape=[-1, 1], dtype="int64") return [hist_item, seq_len] def net(self, inputs, is_infer=False): mind_model = net.MindLayer(self.item_count, self.embedding_dim, self.hidden_size, self.neg_samples, self.maxlen, self.pow_p, self.capsual_iters, self.capsual_max_k, self.capsual_init_std) # self.model = mind_model if is_infer: mind_model.eval() user_cap, cap_weights = mind_model(*inputs) # self.inference_target_var = user_cap fetch_dict = {"user_cap": user_cap} return fetch_dict hist_item, labels, seqlen = inputs [_, sampled_logist, sampled_labels], weight, user_cap, cap_weights, cap_mask = mind_model( hist_item, seqlen, labels) loss = F.softmax_with_cross_entropy( sampled_logist, sampled_labels, soft_label=True) self._cost = paddle.mean(loss) fetch_dict = {"loss": self._cost} return fetch_dict # define optimizer def create_optimizer(self, strategy=None): optimizer = paddle.optimizer.Adam(learning_rate=self.lr) optimizer.minimize(self._cost) # construct infer forward phase def infer_net(self, inputs): return self.net(inputs, is_infer=True)
1,724
1,604
package org.bouncycastle.tls.test; import java.io.IOException; import java.math.BigInteger; import java.security.KeyPair; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.cert.X509Certificate; import java.util.Date; import java.util.concurrent.atomic.AtomicLong; import javax.security.auth.x500.X500Principal; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x509.BasicConstraints; import org.bouncycastle.asn1.x509.ExtendedKeyUsage; import org.bouncycastle.asn1.x509.Extension; import org.bouncycastle.asn1.x509.KeyPurposeId; import org.bouncycastle.cert.X509CertificateHolder; import org.bouncycastle.cert.X509v1CertificateBuilder; import org.bouncycastle.cert.X509v3CertificateBuilder; import org.bouncycastle.cert.jcajce.JcaX500NameUtil; import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; import org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils; import org.bouncycastle.cert.jcajce.JcaX509v1CertificateBuilder; import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; public class CertChainUtil { public static String BC = "BC"; private static final AtomicLong serialNumber = new AtomicLong(1); /* * we generate the CA's certificate */ public static X509Certificate createMasterCert( String rootDN, KeyPair keyPair) throws Exception { // // create the certificate - version 1 // X509v1CertificateBuilder v1CertBuilder = new JcaX509v1CertificateBuilder( new X500Name(rootDN), BigInteger.valueOf(serialNumber.getAndIncrement()), new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30), new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30)), new X500Name(rootDN), keyPair.getPublic()); X509CertificateHolder cert = v1CertBuilder.build(new JcaContentSignerBuilder("SHA256withRSA").setProvider(BC).build(keyPair.getPrivate())); return new JcaX509CertificateConverter().setProvider(BC).getCertificate(cert); } /* * we generate an intermediate certificate signed by our CA */ public static X509Certificate createIntermediateCert( String interDN, PublicKey pubKey, PrivateKey caPrivKey, X509Certificate caCert) throws Exception { // // create the certificate - version 3 // X509v3CertificateBuilder v3CertBuilder = new JcaX509v3CertificateBuilder( JcaX500NameUtil.getSubject(caCert), BigInteger.valueOf(serialNumber.getAndIncrement()), new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30), new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30)), new X500Name(interDN), pubKey); // // extensions // JcaX509ExtensionUtils utils = new JcaX509ExtensionUtils(); v3CertBuilder.addExtension( Extension.subjectKeyIdentifier, false, utils.createSubjectKeyIdentifier(pubKey)); v3CertBuilder.addExtension( Extension.authorityKeyIdentifier, false, utils.createAuthorityKeyIdentifier(caCert)); v3CertBuilder.addExtension( Extension.basicConstraints, true, new BasicConstraints(0)); X509CertificateHolder cert = v3CertBuilder.build(new JcaContentSignerBuilder("SHA256withRSA").setProvider(BC).build(caPrivKey)); return new JcaX509CertificateConverter().setProvider(BC).getCertificate(cert); } /* * we generate a certificate signed by our CA's intermediate certificate */ public static X509Certificate createEndEntityCert( String endEntityDN, PublicKey pubKey, PrivateKey caPrivKey, X509Certificate caCert) throws Exception { X509v3CertificateBuilder v3CertBuilder = createBaseEndEntityBuilder(endEntityDN, pubKey, caCert); X509CertificateHolder cert = v3CertBuilder.build(new JcaContentSignerBuilder("SHA256withRSA").setProvider(BC).build(caPrivKey)); return new JcaX509CertificateConverter().setProvider(BC).getCertificate(cert); } /* * we generate a certificate signed by our CA's intermediate certificate with ExtendedKeyUsage extension */ public static X509Certificate createEndEntityCert( String endEntityDN, PublicKey pubKey, PrivateKey caPrivKey, X509Certificate caCert, KeyPurposeId keyPurposeId) throws Exception { X509v3CertificateBuilder v3CertBuilder = createBaseEndEntityBuilder(endEntityDN, pubKey, caCert); v3CertBuilder.addExtension( Extension.extendedKeyUsage, true, new ExtendedKeyUsage(keyPurposeId)); X509CertificateHolder cert = v3CertBuilder.build(new JcaContentSignerBuilder("SHA256withRSA").setProvider(BC).build(caPrivKey)); return new JcaX509CertificateConverter().setProvider(BC).getCertificate(cert); } private static X509v3CertificateBuilder createBaseEndEntityBuilder(String endEntityDN, PublicKey pubKey, X509Certificate caCert) throws IOException, NoSuchAlgorithmException { // // create the certificate - version 3 // X509v3CertificateBuilder v3CertBuilder = new JcaX509v3CertificateBuilder( caCert.getIssuerX500Principal(), BigInteger.valueOf(serialNumber.getAndIncrement()), new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30), new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30)), new X500Principal(new X500Name(endEntityDN).getEncoded()), pubKey); // // add the extensions // JcaX509ExtensionUtils utils = new JcaX509ExtensionUtils(); v3CertBuilder.addExtension( Extension.subjectKeyIdentifier, false, utils.createSubjectKeyIdentifier(pubKey)); v3CertBuilder.addExtension( Extension.authorityKeyIdentifier, false, utils.createAuthorityKeyIdentifier(caCert.getPublicKey())); v3CertBuilder.addExtension( Extension.basicConstraints, true, new BasicConstraints(false)); return v3CertBuilder; } }
2,704
1,205
{ "version": 2, "path": "\/api\/resourcepath", "httpMethod": "GET", "headers": { "Content-Length": "0", "Host": "atm5u4y7o1.execute-api.us-west-2.amazonaws.com", "User-Agent": "Mozilla\/5.0 (Macintosh; Intel Mac OS X 10_15_1) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/78.0.3904.108 Safari\/537.36", "X-Amzn-Trace-Id": "Root=1-5dedc82e-bd481757564e9cc529fde959", "X-Forwarded-For": "172.16.31.10", "X-Forwarded-Port": "443", "X-Forwarded-Proto": "https", "accept": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8,application\/signed-exchange;v=b3", "accept-encoding": "gzip, deflate, br", "accept-language": "en-US,en;q=0.9", "sec-fetch-mode": "navigate", "sec-fetch-site": "none", "sec-fetch-user": "?1", "upgrade-insecure-requests": "1" }, "multiValueHeaders": { "Content-Length": [ "0" ], "Host": [ "atm5u4y7o1.execute-api.us-west-2.amazonaws.com" ], "User-Agent": [ "Mozilla\/5.0 (Macintosh; Intel Mac OS X 10_15_1) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/78.0.3904.108 Safari\/537.36" ], "X-Amzn-Trace-Id": [ "Root=1-5dedc82e-<KEY>" ], "X-Forwarded-For": [ "172.16.31.10" ], "X-Forwarded-Port": [ "443" ], "X-Forwarded-Proto": [ "https" ], "accept": [ "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8,application\/signed-exchange;v=b3" ], "accept-encoding": [ "gzip, deflate, br" ], "accept-language": [ "en-US,en;q=0.9" ], "sec-fetch-mode": [ "navigate" ], "sec-fetch-site": [ "none" ], "sec-fetch-user": [ "?1" ], "upgrade-insecure-requests": [ "1" ] }, "queryStringParameters": null, "multiValueQueryStringParameters": null, "requestContext": { "accountId": "626492997873", "apiId": "atm5u4y7o1", "authorizer": { "claims": null, "scopes": null }, "domainName": "atm5u4y7o1.execute-api.us-west-2.amazonaws.com", "domainPrefix": "atm5u4y7o1", "extendedRequestId": null, "httpMethod": "GET", "identity": { "accessKey": null, "accountId": null, "caller": null, "cognitoAuthenticationProvider": null, "cognitoAuthenticationType": null, "cognitoIdentityId": null, "cognitoIdentityPoolId": null, "principalOrgId": null, "sourceIp": "172.16.31.10", "user": null, "userAgent": "Mozilla\/5.0 (Macintosh; Intel Mac OS X 10_15_1) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/78.0.3904.108 Safari\/537.36", "userArn": null }, "path": "\/api\/resourcepath", "protocol": "HTTP\/1.1", "requestId": null, "requestTime": "09\/Dec\/2019:04:06:06 +0000", "requestTimeEpoch": 1575864366708, "resourceId": null, "resourcePath": "\/api\/resourcepath", "stage": "$default" }, "pathParameters": { "proxy": "api\/resourcepath" }, "stageVariables": null, "body": null, "isBase64Encoded": true }
1,515
1,103
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.diff.ui.model; public class HollowObjectPairDiffScore implements Comparable<HollowObjectPairDiffScore> { private final String displayKey; private final int fromOrdinal; private final int toOrdinal; private int diffScore; public HollowObjectPairDiffScore(String displayKey, int fromOrdinal, int toOrdinal) { this(displayKey, fromOrdinal, toOrdinal, 0); } public HollowObjectPairDiffScore(String displayKey, int fromOrdinal, int toOrdinal, int score) { this.displayKey = displayKey; this.fromOrdinal = fromOrdinal; this.toOrdinal = toOrdinal; this.diffScore = score; } public String getDisplayKey() { return displayKey; } public int getFromOrdinal() { return fromOrdinal; } public int getToOrdinal() { return toOrdinal; } public int getDiffScore() { return diffScore; } public void incrementDiffScore(int incrementBy) { diffScore += incrementBy; } @Override public int compareTo(HollowObjectPairDiffScore o) { return o.getDiffScore() - diffScore; } }
632
567
package com.google.cloud.bigquery.utils.queryfixer.errors; import com.google.cloud.bigquery.BigQueryException; import com.google.cloud.bigquery.utils.queryfixer.entity.Position; import lombok.Getter; /** * A class to represent the "Table Not Found" errors from BigQuery. The errors are presented in this * form: "Not found: Table [TableName] was not found", where [TableName] is the incorrect table * name. */ @Getter public class TableNotFoundError extends BigQuerySemanticError { private final String tableName; public TableNotFoundError(String tableName, Position errorPosition, BigQueryException errorSource) { super(errorPosition, errorSource); this.tableName = tableName; } }
202
310
/* !@ MIT License Copyright (c) 2020 Skylicht Technology CO., LTD Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This file is part of the "Skylicht Engine". https://github.com/skylicht-lab/skylicht-engine !# */ #include "pch.h" #include "CScrollBarBar.h" #include "CScrollBar.h" #include "GUI/Theme/CTheme.h" #include "GUI/Theme/CThemeConfig.h" namespace Skylicht { namespace Editor { namespace GUI { CScrollBarBar::CScrollBarBar(CBase *parent, bool horizontal) : CDragger(parent), m_isHoriontal(horizontal) { setTarget(this); setSize(6.0f, 6.0f); enableRenderFillRect(true); setFillRectColor(SGUIColor(255, 255, 255, 255)); } CScrollBarBar::~CScrollBarBar() { } void CScrollBarBar::render() { SGUIColor c = CThemeConfig::ScrollBarBarColor; if (isHovered()) c = CThemeConfig::ScrollBarBarHoverColor; CTheme::getTheme()->drawScrollbar(getRenderBounds(), c, m_isHoriontal); } void CScrollBarBar::onMouseMoved(float x, float y, float deltaX, float deltaY) { CDragger::onMouseMoved(x, y, deltaX, deltaY); if (!m_disabled && m_pressed && OnBarMoved != nullptr) { OnBarMoved(this); } } } } }
764
413
#include "caffe/profiler.hpp" #if defined(_MSC_VER) && _MSC_VER <= 1800 #include <Windows.h> #else #include <chrono> #endif // _MSC_VER #include <fstream> namespace caffe { Profiler::Profiler() : init_(Now()), state_(kNotRunning) { scope_stack_.reserve(10); scopes_.reserve(1024); } Profiler *Profiler::Get() { static Profiler inst; return &inst; } void Profiler::ScopeStart(const char *name) { if (state_ == kNotRunning) return; ScopePtr scope(new Scope); if (!scope_stack_.empty()) { scope->name = scope_stack_.back()->name + ":" + name; } else{ scope->name = name; } scope->start_microsec = Now() - init_; scope_stack_.push_back(scope); } void Profiler::ScopeEnd() { if (state_ == kNotRunning) return; CHECK(!scope_stack_.empty()); ScopePtr current_scope = scope_stack_.back(); current_scope->end_microsec = Now() - init_; scopes_.push_back(current_scope); // pop stack scope_stack_.pop_back(); } uint64_t Profiler::Now() const { #if defined(_MSC_VER) && _MSC_VER <= 1800 LARGE_INTEGER frequency, counter; QueryPerformanceFrequency(&frequency); QueryPerformanceCounter(&counter); return counter.QuadPart * 1000000 / frequency.QuadPart; #else return std::chrono::duration_cast<std::chrono::microseconds>( std::chrono::high_resolution_clock::now().time_since_epoch()).count(); #endif // _MSC_VER } static void ProfilerWriteEvent(std::ofstream &file, const char *name, const char *ph, uint64_t ts) { file << " {" << std::endl; file << " \"name\": \"" << name << "\"," << std::endl; file << " \"cat\": \"category\"," << std::endl; file << " \"ph\": \"" << ph << "\"," << std::endl; file << " \"ts\": " << ts << "," << std::endl; file << " \"pid\": 0," << std::endl; file << " \"tid\": 0" << std::endl; file << " }"; } void Profiler::DumpProfile(const char *fn) const { CHECK(scope_stack_.empty()); CHECK_EQ(state_, kNotRunning); std::ofstream file; file.open(fn); file << "{" << std::endl; file << " \"traceEvents\": ["; bool is_first = true; for (auto scope : scopes_) { if (is_first) { file << std::endl; is_first = false; } else { file << "," << std::endl; } ProfilerWriteEvent(file, scope->name.c_str(), "B", scope->start_microsec); file << "," << std::endl; ProfilerWriteEvent(file, scope->name.c_str(), "E", scope->end_microsec); } file << " ]," << std::endl; file << " \"displayTimeUnit\": \"ms\"" << std::endl; file << "}" << std::endl; } } // namespace caffe
1,101
1,172
<gh_stars>1000+ // Copyright (C) 2007 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.caja.util; import com.google.caja.SomethingWidgyHappenedError; import com.google.caja.lexer.CharProducer; import com.google.caja.lexer.FilePosition; import com.google.caja.lexer.InputSource; import com.google.caja.lexer.ParseException; import com.google.caja.parser.html.Namespaces; import com.google.caja.parser.html.Nodes; import com.google.caja.parser.js.StringLiteral; import com.google.caja.reporting.MessageContext; import com.google.caja.util.Executor.AbnormalExitException; import java.io.File; import java.io.IOException; import java.io.StringReader; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import java.util.Map; import junit.framework.Assert; import junit.framework.AssertionFailedError; import org.w3c.dom.Attr; import org.w3c.dom.DocumentFragment; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.Text; /** * A testbed that allows running javascript via the Rhino interpreter. * TODO(mikesamuel): maybe replace this with the JSR 223 stuff. * * @author <EMAIL> */ // TODO(felix8a): remove SuppressWarnings after full conversion to junit4 @SuppressWarnings("deprecation") public class RhinoTestBed { private static final String HTML_NS = Namespaces.HTML_NAMESPACE_URI; /** * Runs the javascript from the given inputs in order, and returns the * result. */ public static Object runJs(Executor.Input... inputs) { return runJs(null, inputs); } public static Object runJs(Object eval, Executor.Input... inputs) { try { Map<String, Object> actuals = Maps.newHashMap(); actuals.put("stderr", System.err); actuals.put("_junit_", new JunitSandBoxSafe()); actuals.put("caja___", eval); RhinoExecutor exec = new RhinoExecutor(inputs); return exec.run(actuals, Object.class); } catch (AbnormalExitException ex) { Throwable th = ex.getCause(); if (th instanceof Error) { throw (Error) th; } if (th instanceof RuntimeException) { throw (RuntimeException) th; } throw new SomethingWidgyHappenedError(ex); } } /** * Given an HTML file that references javascript sources, load all * the scripts, set up the DOM using env.js, and start JSUnit. * * <p>This lets us write test html files that can be run both * in a browser, and automatically via ANT. * * <p>NOTE: This method interprets the input HTML in an idiosyncratic way to * facilitate conveniently bundling test code into one file. It runs each * {@code <script>} block as plain JavaScript. * * @param html an HTML DOM tree to run in Rhino. */ public static void runJsUnittestFromHtml(DocumentFragment html) throws IOException, ParseException { TestUtil.enableContentUrls(); // Used to get HTML to env.js List<Executor.Input> inputs = Lists.newArrayList(); // Stub out the Browser inputs.add(new Executor.Input( RhinoTestBed.class, "../plugin/console-stubs.js")); inputs.add(new Executor.Input( RhinoTestBed.class, "/js/envjs/env.js")); int injectHtmlIndex = inputs.size(); List<Pair<String, InputSource>> scriptContent = new ArrayList<Pair<String, InputSource>>(); MessageContext mc = new MessageContext(); List<Element> scripts = new ArrayList<Element>(); for (Node root : Nodes.childrenOf(html)) { if (root.getNodeType() == 1) { for (Element script : Nodes.nodeListIterable( ((Element) root).getElementsByTagNameNS(HTML_NS, "script"), Element.class)) { scripts.add(script); } } } for (Element script : scripts) { Attr src = script.getAttributeNodeNS(HTML_NS, "src"); CharProducer scriptBody; if (src != null) { String resourcePath = src.getNodeValue(); InputSource resource; if (resourcePath.startsWith("/")) { try { resource = new InputSource( RhinoTestBed.class.getResource(resourcePath).toURI()); } catch (URISyntaxException ex) { throw new SomethingWidgyHappenedError( "java.net.URL is not a valid java.net.URI", ex); } } else { InputSource baseUri = Nodes.getFilePositionFor(html).source(); resource = new InputSource(baseUri.getUri().resolve(resourcePath)); } scriptBody = loadResource(resource); } else { scriptBody = textContentOf(script); } String scriptText; InputSource isrc = scriptBody.getSourceBreaks(0).source(); // Add blank lines at the front so that Rhino stack traces have correct // line numbers. scriptText = prefixWithBlankLines( scriptBody.toString(0, scriptBody.getLimit()), Nodes.getFilePositionFor(script).startLineNo() - 1); scriptContent.add(Pair.pair(scriptText, isrc)); mc.addInputSource(isrc); script.getParentNode().removeChild(script); } for (Pair<String, InputSource> script : scriptContent) { inputs.add(new Executor.Input(script.a, mc.abbreviate(script.b))); } // Set up the DOM. env.js requires that location be set to a URI before it // creates a DOM. Since it fetches HTML via java.net.URL and passes it off // to the org.w3c parser, we use a content: URL which is handled by handlers // registered in TestUtil so that we can provide html without having a file // handy. String domJs = "window.location = " + StringLiteral.toQuotedValue( TestUtil.makeContentUrl(Nodes.render(html))) + ";"; String htmlSource = Nodes.getFilePositionFor(html).source().toString(); inputs.add(injectHtmlIndex, new Executor.Input(domJs, htmlSource)); inputs.add(new Executor.Input( "(function () {\n" + " var onload = document.body.getAttribute('onload');\n" + " onload && eval(onload);\n" + " return document.title;\n" + " })();", htmlSource)); // Execute tests String title = (String) runJs(inputs.toArray(new Executor.Input[inputs.size()])); // Test for success if (title == null || !title.contains("all tests passed")) { throw new junit.framework.AssertionFailedError( "Rhino tests did not pass; title = " + title); } } private static CharProducer loadResource(InputSource resource) throws IOException { File f = new File(resource.getUri()); return CharProducer.Factory.fromFile(f, Charsets.UTF_8); } private static String prefixWithBlankLines(String s, int n) { if (n <= 0) { return s; } StringBuilder sb = new StringBuilder(s.length() + n); while (--n >= 0) { sb.append('\n'); } return sb.append(s).toString(); } private static CharProducer textContentOf(Element script) { List<CharProducer> parts = new ArrayList<CharProducer>(); for (Node child : Nodes.childrenOf(script)) { FilePosition childPos = Nodes.getFilePositionFor(child); switch (child.getNodeType()) { case Node.TEXT_NODE: String rawText = Nodes.getRawText((Text) child); String decodedText = child.getNodeValue(); CharProducer cp = null; if (rawText != null) { cp = CharProducer.Factory.fromHtmlAttribute( CharProducer.Factory.create( new StringReader(rawText), childPos)); if (!String.valueOf(cp.getBuffer(), cp.getOffset(), cp.getLength()) .equals(decodedText)) { // XHTML cp = null; } } if (cp == null) { cp = CharProducer.Factory.create( new StringReader(child.getNodeValue()), childPos); } parts.add(cp); break; case Node.CDATA_SECTION_NODE: parts.add(CharProducer.Factory.create( new StringReader(" " + child.getNodeValue()), childPos)); break; default: break; } } return CharProducer.Factory.chain(parts.toArray(new CharProducer[0])); } @SuppressWarnings("static-method") public static final class JunitSandBoxSafe { public void fail(Object message) { Assert.fail("" + message); } public void fail() { Assert.fail(); } public boolean isAssertionFailedError(Object o) { return o instanceof AssertionFailedError; } public void assertJsonEquals(String message, String x, String y) { Assert.assertEquals(message, renderPrettyJson(x), renderPrettyJson(y)); } private String renderPrettyJson(String s) { try { CajaTestCase t = new CajaTestCase() { { this.setUp(); } }; return CajaTestCase.render( t.js( t.fromString( "(" + s + ");", FilePosition.UNKNOWN))); } catch (Exception e) { throw new RuntimeException(e); } } } private RhinoTestBed() { /* uninstantiable */ } }
3,762
5,865
<filename>server/src/test-integration/java/com/thoughtworks/go/server/materials/MaterialDatabaseGitWithSubmodulesUpdaterTest.java /* * Copyright 2021 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thoughtworks.go.server.materials; import com.thoughtworks.go.config.materials.git.GitMaterial; import com.thoughtworks.go.domain.MaterialRevisions; import com.thoughtworks.go.domain.materials.Material; import com.thoughtworks.go.helper.GitRepoContainingSubmodule; import com.thoughtworks.go.helper.TestRepo; import org.junit.jupiter.api.Test; import java.nio.file.Path; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; public class MaterialDatabaseGitWithSubmodulesUpdaterTest extends TestBaseForDatabaseUpdater { @Override protected Material material() { return new GitMaterial(testRepo.projectRepositoryUrl()); } @Override protected TestRepo repo(Path tempDir) throws Exception { GitRepoContainingSubmodule testRepoWithExternal = new GitRepoContainingSubmodule(tempDir); testRepoWithExternal.addSubmodule("submodule-1", "sub1"); return testRepoWithExternal; } @Test public void shouldUpdateModificationsForExternalsAsWell() throws Exception { updater.updateMaterial(material); MaterialRevisions materialRevisions = materialRepository.findLatestModification(material); assertThat(materialRevisions.numberOfRevisions(), is(1)); } }
632
2,496
<reponame>flamendless/love<gh_stars>1000+ /* ** $Id: lstrlib.c,v 1.254 2016/12/22 13:08:50 roberto Exp $ ** Standard library for string operations and pattern-matching ** Modified by the Kepler Project and the LOVE Development Team to work with ** Lua 5.1's API */ /********************************************************************* * The MIT License (MIT) * * Copyright (c) 2015 Kepler Project. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *********************************************************************/ /********************************************************************* * This file contains parts of Lua 5.2's and Lua 5.3's source code: * * Copyright (C) 1994-2014 Lua.org, PUC-Rio. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *********************************************************************/ #include "lprefix.h" #include <ctype.h> #include <float.h> #include <limits.h> #include <stddef.h> #include <stdlib.h> #include <string.h> #include "lua.h" #include "lauxlib.h" #include "lualib.h" #include "lstrlib.h" #if LUA_VERSION_NUM == 501 typedef size_t lua_Unsigned; #endif #if LUA_VERSION_NUM >= 504 # define LUAL_BUFFER53_BUFFER(B) (B)->b.b #elif LUA_VERSION_NUM == 501 # define LUAL_BUFFER53_BUFFER(B) (B)->b.buffer #else # define LUAL_BUFFER53_BUFFER(B) (B)->b.initb #endif static void luaL_buffinit_53 (lua_State *L, luaL_Buffer_53 *B) { #if LUA_VERSION_NUM == 501 /* make it crash if used via pointer to a 5.1-style luaL_Buffer */ B->b.p = NULL; B->b.L = NULL; B->b.lvl = 0; /* reuse the buffer from the 5.1-style luaL_Buffer though! */ B->ptr = B->b.buffer; B->capacity = LUAL_BUFFERSIZE; B->nelems = 0; B->L2 = L; #else return luaL_buffinit(L, (luaL_Buffer*) B); #endif } static char *luaL_prepbuffsize_53 (luaL_Buffer_53 *B, size_t s) { #if LUA_VERSION_NUM == 501 if (B->capacity - B->nelems < s) { /* needs to grow */ char* newptr = NULL; size_t newcap = B->capacity * 2; if (newcap - B->nelems < s) newcap = B->nelems + s; if (newcap < B->capacity) /* overflow */ luaL_error(B->L2, "buffer too large"); newptr = (char*)lua_newuserdata(B->L2, newcap); memcpy(newptr, B->ptr, B->nelems); if (B->ptr != B->b.buffer) lua_replace(B->L2, -2); /* remove old buffer */ B->ptr = newptr; B->capacity = newcap; } return B->ptr+B->nelems; #else return luaL_prepbuffsize((luaL_Buffer*) B, s); #endif } #define luaL_addsize_53(B, s) \ ((B)->nelems += (s)) #define luaL_addchar_53(B, c) \ ((void)((B)->nelems < (B)->capacity || luaL_prepbuffsize_53((B), 1)), \ ((B)->ptr[(B)->nelems++] = (c))) static void luaL_addlstring_53 (luaL_Buffer_53 *B, const char *s, size_t l) { memcpy(luaL_prepbuffsize_53(B, l), s, l); luaL_addsize_53(B, l); } void lua53_pushresult (luaL_Buffer_53 *B) { lua_pushlstring(B->L2, B->ptr, B->nelems); if (B->ptr != LUAL_BUFFER53_BUFFER(B)) lua_replace(B->L2, -2); /* remove userdata buffer */ } void lua53_cleanupbuffer (luaL_Buffer_53 *B) { if (B->ptr != LUAL_BUFFER53_BUFFER(B)) lua_replace(B->L2, -1); /* remove userdata buffer */ } /* ** Some sizes are better limited to fit in 'int', but must also fit in ** 'size_t'. (We assume that 'lua_Integer' cannot be smaller than 'int'.) */ #define MAX_SIZET ((size_t)(~(size_t)0)) #define MAXSIZE \ (sizeof(size_t) < sizeof(int) ? MAX_SIZET : (size_t)(INT_MAX)) /* translate a relative string position: negative means back from end */ static lua_Integer posrelat (lua_Integer pos, size_t len) { if (pos >= 0) return pos; else if (0u - (size_t)pos > len) return 0; else return (lua_Integer)len + pos + 1; } /* ** {====================================================== ** PACK/UNPACK ** ======================================================= */ /* value used for padding */ #if !defined(LUAL_PACKPADBYTE) #define LUAL_PACKPADBYTE 0x00 #endif /* maximum size for the binary representation of an integer */ #define MAXINTSIZE 16 /* number of bits in a character */ #define NB CHAR_BIT /* mask for one character (NB 1's) */ #define MC ((1 << NB) - 1) /* size of a lua_Integer */ #define SZINT ((int)sizeof(lua_Integer)) /* dummy union to get native endianness */ static const union { int dummy; char little; /* true iff machine is little endian */ } nativeendian = {1}; /* dummy structure to get native alignment requirements */ struct cD { char c; union { double d; void *p; lua_Integer i; lua_Number n; } u; }; #define MAXALIGN (offsetof(struct cD, u)) /* ** Union for serializing floats */ typedef union Ftypes { float f; double d; lua_Number n; char buff[5 * sizeof(lua_Number)]; /* enough for any float type */ } Ftypes; /* ** information to pack/unpack stuff */ typedef struct Header { lua_State *L; int islittle; int maxalign; } Header; /* ** options for pack/unpack */ typedef enum KOption { Kint, /* signed integers */ Kuint, /* unsigned integers */ Kfloat, /* floating-point numbers */ Kchar, /* fixed-length strings */ Kstring, /* strings with prefixed length */ Kzstr, /* zero-terminated strings */ Kpadding, /* padding */ Kpaddalign, /* padding for alignment */ Knop /* no-op (configuration or spaces) */ } KOption; /* ** Read an integer numeral from string 'fmt' or return 'df' if ** there is no numeral */ static int digit (int c) { return '0' <= c && c <= '9'; } static int getnum (const char **fmt, int df) { if (!digit(**fmt)) /* no number? */ return df; /* return default value */ else { int a = 0; do { a = a*10 + (*((*fmt)++) - '0'); } while (digit(**fmt) && a <= ((int)MAXSIZE - 9)/10); return a; } } /* ** Read an integer numeral and raises an error if it is larger ** than the maximum size for integers. */ static int getnumlimit (Header *h, const char **fmt, int df) { int sz = getnum(fmt, df); if (sz > MAXINTSIZE || sz <= 0) luaL_error(h->L, "integral size (%d) out of limits [1,%d]", sz, MAXINTSIZE); return sz; } /* ** Initialize Header */ static void initheader (lua_State *L, Header *h) { h->L = L; h->islittle = nativeendian.little; h->maxalign = 1; } /* ** Read and classify next option. 'size' is filled with option's size. */ static KOption getoption (Header *h, const char **fmt, int *size) { int opt = *((*fmt)++); *size = 0; /* default */ switch (opt) { case 'b': *size = sizeof(char); return Kint; case 'B': *size = sizeof(char); return Kuint; case 'h': *size = sizeof(short); return Kint; case 'H': *size = sizeof(short); return Kuint; case 'l': *size = sizeof(long); return Kint; case 'L': *size = sizeof(long); return Kuint; case 'j': *size = sizeof(lua_Integer); return Kint; case 'J': *size = sizeof(lua_Integer); return Kuint; case 'T': *size = sizeof(size_t); return Kuint; case 'f': *size = sizeof(float); return Kfloat; case 'd': *size = sizeof(double); return Kfloat; case 'n': *size = sizeof(lua_Number); return Kfloat; case 'i': *size = getnumlimit(h, fmt, sizeof(int)); return Kint; case 'I': *size = getnumlimit(h, fmt, sizeof(int)); return Kuint; case 's': *size = getnumlimit(h, fmt, sizeof(size_t)); return Kstring; case 'c': *size = getnum(fmt, -1); if (*size == -1) luaL_error(h->L, "missing size for format option 'c'"); return Kchar; case 'z': return Kzstr; case 'x': *size = 1; return Kpadding; case 'X': return Kpaddalign; case ' ': break; case '<': h->islittle = 1; break; case '>': h->islittle = 0; break; case '=': h->islittle = nativeendian.little; break; case '!': h->maxalign = getnumlimit(h, fmt, MAXALIGN); break; default: luaL_error(h->L, "invalid format option '%c'", opt); } return Knop; } /* ** Read, classify, and fill other details about the next option. ** 'psize' is filled with option's size, 'notoalign' with its ** alignment requirements. ** Local variable 'size' gets the size to be aligned. (Kpadal option ** always gets its full alignment, other options are limited by ** the maximum alignment ('maxalign'). Kchar option needs no alignment ** despite its size. */ static KOption getdetails (Header *h, size_t totalsize, const char **fmt, int *psize, int *ntoalign) { KOption opt = getoption(h, fmt, psize); int align = *psize; /* usually, alignment follows size */ if (opt == Kpaddalign) { /* 'X' gets alignment from following option */ if (**fmt == '\0' || getoption(h, fmt, &align) == Kchar || align == 0) luaL_argerror(h->L, 1, "invalid next option for option 'X'"); } if (align <= 1 || opt == Kchar) /* need no alignment? */ *ntoalign = 0; else { if (align > h->maxalign) /* enforce maximum alignment */ align = h->maxalign; if ((align & (align - 1)) != 0) /* is 'align' not a power of 2? */ luaL_argerror(h->L, 1, "format asks for alignment not power of 2"); *ntoalign = (align - (int)(totalsize & (align - 1))) & (align - 1); } return opt; } /* ** Pack integer 'n' with 'size' bytes and 'islittle' endianness. ** The final 'if' handles the case when 'size' is larger than ** the size of a Lua integer, correcting the extra sign-extension ** bytes if necessary (by default they would be zeros). */ static void packint (luaL_Buffer_53 *b, lua_Unsigned n, int islittle, int size, int neg) { char *buff = luaL_prepbuffsize_53(b, size); int i; buff[islittle ? 0 : size - 1] = (char)(n & MC); /* first byte */ for (i = 1; i < size; i++) { n >>= NB; buff[islittle ? i : size - 1 - i] = (char)(n & MC); } if (neg && size > SZINT) { /* negative number need sign extension? */ for (i = SZINT; i < size; i++) /* correct extra bytes */ buff[islittle ? i : size - 1 - i] = (char)MC; } luaL_addsize_53(b, size); /* add result to buffer */ } /* ** Copy 'size' bytes from 'src' to 'dest', correcting endianness if ** given 'islittle' is different from native endianness. */ static void copywithendian (volatile char *dest, volatile const char *src, int size, int islittle) { if (islittle == nativeendian.little) { while (size-- != 0) *(dest++) = *(src++); } else { dest += size - 1; while (size-- != 0) *(dest--) = *(src++); } } void lua53_str_pack (lua_State *L, const char *fmt, int startidx, luaL_Buffer_53 *b) { Header h; int arg = startidx - 1; /* current argument to pack */ size_t totalsize = 0; /* accumulate total size of result */ initheader(L, &h); lua_pushnil(L); /* mark to separate arguments from string buffer */ luaL_buffinit_53(L, b); while (*fmt != '\0') { int size, ntoalign; KOption opt = getdetails(&h, totalsize, &fmt, &size, &ntoalign); totalsize += ntoalign + size; while (ntoalign-- > 0) luaL_addchar_53(b, LUAL_PACKPADBYTE); /* fill alignment */ arg++; switch (opt) { case Kint: { /* signed integers */ lua_Integer n = luaL_checkinteger(L, arg); if (size < SZINT) { /* need overflow check? */ lua_Integer lim = (lua_Integer)1 << ((size * NB) - 1); luaL_argcheck(L, -lim <= n && n < lim, arg, "integer overflow"); } packint(b, (lua_Unsigned)n, h.islittle, size, (n < 0)); break; } case Kuint: { /* unsigned integers */ lua_Integer n = luaL_checkinteger(L, arg); if (size < SZINT) /* need overflow check? */ luaL_argcheck(L, (lua_Unsigned)n < ((lua_Unsigned)1 << (size * NB)), arg, "unsigned overflow"); packint(b, (lua_Unsigned)n, h.islittle, size, 0); break; } case Kfloat: { /* floating-point options */ volatile Ftypes u; char *buff = luaL_prepbuffsize_53(b, size); lua_Number n = luaL_checknumber(L, arg); /* get argument */ if (size == sizeof(u.f)) u.f = (float)n; /* copy it into 'u' */ else if (size == sizeof(u.d)) u.d = (double)n; else u.n = n; /* move 'u' to final result, correcting endianness if needed */ copywithendian(buff, u.buff, size, h.islittle); luaL_addsize_53(b, size); break; } case Kchar: { /* fixed-size string */ size_t len; const char *s = luaL_checklstring(L, arg, &len); luaL_argcheck(L, len <= (size_t)size, arg, "string longer than given size"); luaL_addlstring_53(b, s, len); /* add string */ while (len++ < (size_t)size) /* pad extra space */ luaL_addchar_53(b, LUAL_PACKPADBYTE); break; } case Kstring: { /* strings with length count */ size_t len; const char *s = luaL_checklstring(L, arg, &len); luaL_argcheck(L, size >= (int)sizeof(size_t) || len < ((size_t)1 << (size * NB)), arg, "string length does not fit in given size"); packint(b, (lua_Unsigned)len, h.islittle, size, 0); /* pack length */ luaL_addlstring_53(b, s, len); totalsize += len; break; } case Kzstr: { /* zero-terminated string */ size_t len; const char *s = luaL_checklstring(L, arg, &len); luaL_argcheck(L, strlen(s) == len, arg, "string contains zeros"); luaL_addlstring_53(b, s, len); luaL_addchar_53(b, '\0'); /* add zero at the end */ totalsize += len + 1; break; } case Kpadding: luaL_addchar_53(b, LUAL_PACKPADBYTE); /* FALLTHROUGH */ case Kpaddalign: case Knop: arg--; /* undo increment */ break; } } } int lua53_str_packsize (lua_State *L) { Header h; const char *fmt = luaL_checkstring(L, 1); /* format string */ size_t totalsize = 0; /* accumulate total size of result */ initheader(L, &h); while (*fmt != '\0') { int size, ntoalign; KOption opt = getdetails(&h, totalsize, &fmt, &size, &ntoalign); size += ntoalign; /* total space used by option */ luaL_argcheck(L, totalsize <= MAXSIZE - size, 1, "format result too large"); totalsize += size; switch (opt) { case Kstring: /* strings with length count */ case Kzstr: /* zero-terminated string */ luaL_argerror(L, 1, "variable-length format"); /* call never return, but to avoid warnings: *//* FALLTHROUGH */ default: break; } } lua_pushinteger(L, (lua_Integer)totalsize); return 1; } /* ** Unpack an integer with 'size' bytes and 'islittle' endianness. ** If size is smaller than the size of a Lua integer and integer ** is signed, must do sign extension (propagating the sign to the ** higher bits); if size is larger than the size of a Lua integer, ** it must check the unread bytes to see whether they do not cause an ** overflow. */ static lua_Integer unpackint (lua_State *L, const char *str, int islittle, int size, int issigned) { lua_Unsigned res = 0; int i; int limit = (size <= SZINT) ? size : SZINT; for (i = limit - 1; i >= 0; i--) { res <<= NB; res |= (lua_Unsigned)(unsigned char)str[islittle ? i : size - 1 - i]; } if (size < SZINT) { /* real size smaller than lua_Integer? */ if (issigned) { /* needs sign extension? */ lua_Unsigned mask = (lua_Unsigned)1 << (size*NB - 1); res = ((res ^ mask) - mask); /* do sign extension */ } } else if (size > SZINT) { /* must check unread bytes */ int mask = (!issigned || (lua_Integer)res >= 0) ? 0 : MC; for (i = limit; i < size; i++) { if ((unsigned char)str[islittle ? i : size - 1 - i] != mask) luaL_error(L, "%d-byte integer does not fit into Lua Integer", size); } } return (lua_Integer)res; } int lua53_str_unpack (lua_State *L, const char *fmt, const char *data, size_t ld, int dataidx, int posidx) { Header h; size_t pos = (size_t)posrelat(luaL_optinteger(L, posidx, 1), ld) - 1; int n = 0; /* number of results */ luaL_argcheck(L, pos <= ld, posidx, "initial position out of string"); initheader(L, &h); while (*fmt != '\0') { int size, ntoalign; KOption opt = getdetails(&h, pos, &fmt, &size, &ntoalign); if ((size_t)ntoalign + size > ~pos || pos + ntoalign + size > ld) luaL_argerror(L, dataidx, "data string too short"); pos += ntoalign; /* skip alignment */ /* stack space for item + next position */ luaL_checkstack(L, dataidx, "too many results"); n++; switch (opt) { case Kint: case Kuint: { lua_Integer res = unpackint(L, data + pos, h.islittle, size, (opt == Kint)); lua_pushinteger(L, res); break; } case Kfloat: { volatile Ftypes u; lua_Number num; copywithendian(u.buff, data + pos, size, h.islittle); if (size == sizeof(u.f)) num = (lua_Number)u.f; else if (size == sizeof(u.d)) num = (lua_Number)u.d; else num = u.n; lua_pushnumber(L, num); break; } case Kchar: { lua_pushlstring(L, data + pos, size); break; } case Kstring: { size_t len = (size_t)unpackint(L, data + pos, h.islittle, size, 0); luaL_argcheck(L, pos + len + size <= ld, dataidx, "data string too short"); lua_pushlstring(L, data + pos + size, len); pos += len; /* skip string */ break; } case Kzstr: { size_t len = (int)strlen(data + pos); lua_pushlstring(L, data + pos, len); pos += len + 1; /* skip string plus final '\0' */ break; } case Kpaddalign: case Kpadding: case Knop: n--; /* undo increment */ break; } pos += size; } lua_pushinteger(L, pos + 1); /* next position */ return n + 1; } /* }====================================================== */
7,923
532
<reponame>vinaym815/opensim-core /* -------------------------------------------------------------------------- * * OpenSim: testJointReactions.cpp * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2005-2017 Stanford University and the Authors * * Author(s): <NAME> * * * * 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. * * -------------------------------------------------------------------------- */ // INCLUDE #include <OpenSim/OpenSim.h> #include <OpenSim/Auxiliary/auxiliaryTestFunctions.h> using namespace OpenSim; using namespace std; int main() { try { AnalyzeTool analyze("SinglePin_Setup_JointReaction.xml"); analyze.run(); Storage result1("SinglePin_JointReaction_ReactionLoads.sto"), standard1("std_SinglePin_JointReaction_ReactionLoads.sto"); CHECK_STORAGE_AGAINST_STANDARD(result1, standard1, std::vector<double>(standard1.getSmallestNumberOfStates(), 1e-5), __FILE__, __LINE__, "SinglePin failed"); cout << "SinglePin passed" << endl; AnalyzeTool analyze2("DoublePendulum3D_Setup_JointReaction.xml"); analyze2.run(); Storage result2("DoublePendulum3D_JointReaction_ReactionLoads.sto"), standard2("std_DoublePendulum3D_JointReaction_ReactionLoads.sto"); CHECK_STORAGE_AGAINST_STANDARD(result2, standard2, std::vector<double>(standard2.getSmallestNumberOfStates(), 1e-5), __FILE__, __LINE__, "DoublePendulum3D failed"); cout << "DoublePendulum3D passed" << endl; AnalyzeTool analyze3("SinglePin_Setup_JointReaction_FrameKeyword.xml"); analyze.run(); Storage result3("SinglePin_JointReaction_ReactionLoads.sto"), standard3("std_SinglePin_JointReaction_ReactionLoads_FrameKeyword.sto"); CHECK_STORAGE_AGAINST_STANDARD(result3, standard3, std::vector<double>(standard3.getSmallestNumberOfStates(), 1e-5), __FILE__, __LINE__, "SinglePin_FrameKeyword failed"); cout << "SinglePin_FrameKeyword passed" << endl; AnalyzeTool analyze4("DoublePendulum3D_Setup_JointReaction.xml"); analyze2.run(); Storage result4("DoublePendulum3D_JointReaction_ReactionLoads.sto"), standard4("std_DoublePendulum3D_JointReaction_ReactionLoads_FrameKeyword.sto"); CHECK_STORAGE_AGAINST_STANDARD(result4, standard4, std::vector<double>(standard4.getSmallestNumberOfStates(), 1e-5), __FILE__, __LINE__, "DoublePendulum3D_FrameKeyword failed"); cout << "DoublePendulum3D_FrameKeyword passed" << endl; } catch (const std::exception& e) { cout << e.what() << endl; return 1; } cout << "Done" << endl; return 0; }
1,808
4,798
// Copyright 2020-present the Material Components for iOS authors. All Rights Reserved. // // 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. #import <UIKit/UIKit.h> @class MDCFlexibleHeaderView; @class MDCFlexibleHeaderViewController; /** An object may conform to this protocol in order to receive layout change events caused by a MDCFlexibleHeaderView. */ @protocol MDCFlexibleHeaderViewLayoutDelegate <NSObject> @required /** Informs the receiver that the flexible header view's frame has changed. The receiver should use the MDCFlexibleHeader scrollPhase APIs in order to react to the frame changes. */ - (void)flexibleHeaderViewController: (nonnull MDCFlexibleHeaderViewController *)flexibleHeaderViewController flexibleHeaderViewFrameDidChange:(nonnull MDCFlexibleHeaderView *)flexibleHeaderView; @end
360
621
// // MessagePack for C++ deserializing routine // // Copyright (C) 2016 <NAME> // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #ifndef MSGPACK_V2_UNPACK_DECL_HPP #define MSGPACK_V2_UNPACK_DECL_HPP #include "msgpack/v1/unpack_decl.hpp" namespace msgpack { /// @cond MSGPACK_API_VERSION_NAMESPACE(v2) { /// @endcond using v1::unpack_reference_func; using v1::unpack_error; using v1::parse_error; using v1::insufficient_bytes; using v1::size_overflow; using v1::array_size_overflow; using v1::map_size_overflow; using v1::str_size_overflow; using v1::bin_size_overflow; using v1::ext_size_overflow; using v1::depth_size_overflow; using v1::unpack_limit; namespace detail { using v1::detail::unpack_user; using v1::detail::unpack_uint8; using v1::detail::unpack_uint16; using v1::detail::unpack_uint32; using v1::detail::unpack_uint64; using v1::detail::unpack_int8; using v1::detail::unpack_int16; using v1::detail::unpack_int32; using v1::detail::unpack_int64; using v1::detail::unpack_float; using v1::detail::unpack_double; using v1::detail::unpack_nil; using v1::detail::unpack_true; using v1::detail::unpack_false; using v1::detail::unpack_array; using v1::detail::unpack_array_item; using v1::detail::unpack_map; using v1::detail::unpack_map_item; using v1::detail::unpack_str; using v1::detail::unpack_bin; using v1::detail::unpack_ext; using v1::detail::unpack_stack; using v1::detail::init_count; using v1::detail::decr_count; using v1::detail::incr_count; using v1::detail::get_count; using v1::detail::fix_tag; using v1::detail::value; using v1::detail::load; using v1::detail::context; } // detail using v1::unpacked; using v1::unpacker; using v1::unpack; using v1::unpack_return; namespace detail { using v1::detail::unpack_imp; } // detail /// @cond } // MSGPACK_API_VERSION_NAMESPACE(v2) /// @endcond } // namespace msgpack #endif // MSGPACK_V2_UNPACK_DECL_HPP
827
1,630
# -*- coding: utf-8 -*- """Account family test constants.""" # Fakers FIRST_NAME = "Quentin" LAST_NAME = "TARANTINO" FULL_NAME = FIRST_NAME + " " + LAST_NAME PERSON_ID = (FIRST_NAME + LAST_NAME).lower() PRIMARY_EMAIL = PERSON_ID + "@hotmail.fr" APPLE_ID_EMAIL = PERSON_ID + "@me.com" ICLOUD_ID_EMAIL = PERSON_ID + "@icloud.com" MEMBER_1_FIRST_NAME = "John" MEMBER_1_LAST_NAME = "TRAVOLTA" MEMBER_1_FULL_NAME = MEMBER_1_FIRST_NAME + " " + MEMBER_1_LAST_NAME MEMBER_1_PERSON_ID = (MEMBER_1_FIRST_NAME + MEMBER_1_LAST_NAME).lower() MEMBER_1_APPLE_ID = MEMBER_1_PERSON_ID + "@icloud.com" MEMBER_2_FIRST_NAME = "Uma" MEMBER_2_LAST_NAME = "THURMAN" MEMBER_2_FULL_NAME = MEMBER_2_FIRST_NAME + " " + MEMBER_2_LAST_NAME MEMBER_2_PERSON_ID = (MEMBER_2_FIRST_NAME + MEMBER_2_LAST_NAME).lower() MEMBER_2_APPLE_ID = MEMBER_2_PERSON_ID + "@outlook.fr" FAMILY_ID = "family_" + PERSON_ID # Data ACCOUNT_FAMILY_WORKING = { "status-message": "Member of a family.", "familyInvitations": [], "outgoingTransferRequests": [], "isMemberOfFamily": True, "family": { "familyId": FAMILY_ID, "transferRequests": [], "invitations": [], "organizer": PERSON_ID, "members": [PERSON_ID, MEMBER_2_PERSON_ID, MEMBER_1_PERSON_ID], "outgoingTransferRequests": [], "etag": "12", }, "familyMembers": [ { "lastName": LAST_NAME, "dsid": PERSON_ID, "originalInvitationEmail": PRIMARY_EMAIL, "fullName": FULL_NAME, "ageClassification": "ADULT", "appleIdForPurchases": PRIMARY_EMAIL, "appleId": PRIMARY_EMAIL, "familyId": FAMILY_ID, "firstName": FIRST_NAME, "hasParentalPrivileges": True, "hasScreenTimeEnabled": False, "hasAskToBuyEnabled": False, "hasSharePurchasesEnabled": True, "shareMyLocationEnabledFamilyMembers": [], "hasShareMyLocationEnabled": True, "dsidForPurchases": PERSON_ID, }, { "lastName": MEMBER_2_LAST_NAME, "dsid": MEMBER_2_PERSON_ID, "originalInvitationEmail": MEMBER_2_APPLE_ID, "fullName": MEMBER_2_FULL_NAME, "ageClassification": "ADULT", "appleIdForPurchases": MEMBER_2_APPLE_ID, "appleId": MEMBER_2_APPLE_ID, "familyId": FAMILY_ID, "firstName": MEMBER_2_FIRST_NAME, "hasParentalPrivileges": False, "hasScreenTimeEnabled": False, "hasAskToBuyEnabled": False, "hasSharePurchasesEnabled": False, "hasShareMyLocationEnabled": False, "dsidForPurchases": MEMBER_2_PERSON_ID, }, { "lastName": MEMBER_1_LAST_NAME, "dsid": MEMBER_1_PERSON_ID, "originalInvitationEmail": MEMBER_1_APPLE_ID, "fullName": MEMBER_1_FULL_NAME, "ageClassification": "ADULT", "appleIdForPurchases": MEMBER_1_APPLE_ID, "appleId": MEMBER_1_APPLE_ID, "familyId": FAMILY_ID, "firstName": MEMBER_1_FIRST_NAME, "hasParentalPrivileges": False, "hasScreenTimeEnabled": False, "hasAskToBuyEnabled": False, "hasSharePurchasesEnabled": True, "hasShareMyLocationEnabled": True, "dsidForPurchases": MEMBER_1_PERSON_ID, }, ], "status": 0, "showAddMemberButton": True, }
1,793
746
package org.protege.editor.owl.ui.selector; import org.protege.editor.core.ui.view.ViewComponent; import org.protege.editor.core.ui.view.ViewComponentPlugin; import org.protege.editor.core.ui.view.ViewComponentPluginAdapter; import org.protege.editor.core.ui.workspace.Workspace; import org.protege.editor.owl.OWLEditorKit; import org.protege.editor.owl.ui.renderer.OWLSystemColors; import org.protege.editor.owl.ui.view.individual.OWLIndividualListViewComponent; import org.semanticweb.owlapi.model.OWLNamedIndividual; import org.semanticweb.owlapi.model.OWLOntology; import javax.swing.*; import javax.swing.event.ChangeListener; import java.awt.*; import java.util.Set; /** * Author: <NAME><br> * The University Of Manchester<br> * Medical Informatics Group<br> * Date: 05-Jul-2006<br> * <br> <EMAIL><br> * www.cs.man.ac.uk/~horridgm<br> * <br> */ public class OWLIndividualSelectorPanel extends AbstractSelectorPanel<OWLNamedIndividual> { private OWLIndividualListViewComponent vc; private Set<OWLOntology> ontologies; public OWLIndividualSelectorPanel(OWLEditorKit eKit) { this(eKit, true); } public OWLIndividualSelectorPanel(OWLEditorKit eKit, boolean editable) { this(eKit, editable, eKit.getModelManager().getActiveOntologies()); } public OWLIndividualSelectorPanel(OWLEditorKit eKit, boolean editable, Set<OWLOntology> ontologies) { this(eKit, editable, ontologies, ListSelectionModel.SINGLE_SELECTION); } public OWLIndividualSelectorPanel(OWLEditorKit eKit, int selectionMode) { this(eKit, true, null, selectionMode); } /** * Builds an OWLIndividualSelectorPanel with the input selection mode. The * valid values are the same described in the constants in * javax.swing.ListSelectionModel (the default is * ListSelectionModel.SINGLE_SELECTION) * * @param eKit * @param selectionMode */ public OWLIndividualSelectorPanel(OWLEditorKit eKit, boolean editable, Set<OWLOntology> ontologies, int selectionMode) { super(eKit, editable, false); this.ontologies = ontologies; createUI(); this.vc.setSelectionMode(selectionMode); } public void setSelection(OWLNamedIndividual ind) { if (vc.getView() != null) { vc.getView().setPinned(false); } vc.setSelectedIndividual(ind); } public void setSelection(Set<OWLNamedIndividual> entities) { vc.setSelectedIndividuals(entities); } public OWLNamedIndividual getSelectedObject() { return vc.getSelectedIndividual(); } public Set<OWLNamedIndividual> getSelectedObjects() { return vc.getSelectedIndividuals(); } public void dispose() { vc.dispose(); } protected ViewComponentPlugin getViewComponentPlugin() { return new ViewComponentPluginAdapter() { public String getLabel() { return "Individuals"; } public Workspace getWorkspace() { return getOWLEditorKit().getWorkspace(); } public ViewComponent newInstance() throws ClassNotFoundException, IllegalAccessException, InstantiationException { vc = new OWLIndividualListViewComponent(){ protected void setupActions() { if (isEditable()){ super.setupActions(); } } protected Set<OWLOntology> getOntologies() { if (ontologies != null){ return ontologies; } return super.getOntologies(); } }; vc.setup(this); return vc; } public Color getBackgroundColor() { return OWLSystemColors.getOWLIndividualColor(); } }; } public void setOntologies(Set<OWLOntology> ontologies) { } public void addSelectionListener(ChangeListener listener) { vc.addChangeListener(listener); } public void removeSelectionListener(ChangeListener listener) { vc.removeChangeListener(listener); } }
1,853
385
/** * @file ParameterObj.h * @brief Parameter instance object. */ #pragma once #include "types.h" namespace al { class ParameterObj { public: ParameterObj(); u64 _0; u64 _8; u64 _10; u64 _18; u8 _20[0x78-0x20]; }; };
156
358
<reponame>kristi/qfs /* * GF-Complete: A Comprehensive Open Source Library for Galois Field Arithmetic * <NAME>, <NAME>, <NAME>, * <NAME>, <NAME>, <NAME>, <NAME>. * * gf_example_7.c * * Demonstrating extract_word and Cauchy */ #include <stdio.h> #include <getopt.h> #include <stdint.h> #include <string.h> #include <stdlib.h> #include <time.h> #include "gf_complete.h" #include "gf_rand.h" void usage(char *s) { fprintf(stderr, "usage: gf_example_7\n"); exit(1); } int main(int argc, char **argv) { uint8_t *a, *b; int i, j; gf_t gf; if (gf_init_hard(&gf, 3, GF_MULT_TABLE, GF_REGION_CAUCHY, GF_DIVIDE_DEFAULT, 0, 0, 0, NULL, NULL) == 0) { fprintf(stderr, "gf_init_hard failed\n"); exit(1); } a = (uint8_t *) malloc(3); b = (uint8_t *) malloc(3); MOA_Seed(0); for (i = 0; i < 3; i++) a[i] = MOA_Random_W(8, 1); gf.multiply_region.w32(&gf, a, b, 5, 3, 0); printf("a: 0x%lx b: 0x%lx\n", (unsigned long) a, (unsigned long) b); printf("\n"); printf("a: 0x%02x 0x%02x 0x%02x\n", a[0], a[1], a[2]); printf("b: 0x%02x 0x%02x 0x%02x\n", b[0], b[1], b[2]); printf("\n"); printf("a bits:"); for (i = 0; i < 3; i++) { printf(" "); for (j = 7; j >= 0; j--) printf("%c", (a[i] & (1 << j)) ? '1' : '0'); } printf("\n"); printf("b bits:"); for (i = 0; i < 3; i++) { printf(" "); for (j = 7; j >= 0; j--) printf("%c", (b[i] & (1 << j)) ? '1' : '0'); } printf("\n"); printf("\n"); for (i = 0; i < 8; i++) { printf("Word %2d: %d * 5 = %d\n", i, gf.extract_word.w32(&gf, a, 3, i), gf.extract_word.w32(&gf, b, 3, i)); } return 0; }
832
3,102
<gh_stars>1000+ // RUN: %clang_cc1 %s -fsyntax-only -Wno-unused-value -Wmicrosoft -verify -fms-compatibility // PR15845 int foo(xxx); // expected-error{{unknown type name}} struct cls { char *m; }; char * cls::* __uptr wrong2 = &cls::m; // expected-error {{'__uptr' attribute cannot be used with pointers to members}}
120
777
<reponame>Sun-Joong/aifh<filename>vol1/c-examples/ExampleRandom.c /* * Artificial Intelligence for Humans * Volume 1: Fundamental Algorithms * C/C++ Version * http://www.aifh.org * http://www.jeffheaton.com * * Code repository: * https://github.com/jeffheaton/aifh * Copyright 2013 by <NAME> * * 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. * * For more information on Heaton Research copyrights, licenses * and trademarks visit: * http://www.heatonresearch.com/copyright */ #include "aifh-vol1-examples.h" static void UniformHisto(RANDOM_GENERATE *prng) { int i,idx,j; int hist[20]; int maxIndex; double d; double started, current; int done; long total; double minResult = 1000; double maxResult = -1000; for(i=0;i<20;i++) { hist[i] = 0; } printf("Generating random numbers for 5 seconds...\nPlease wait...\n"); started = omp_get_wtime(); done = 0; total = 0; while(!done) { double d = RandNextDouble(prng); idx = MIN((int)(d*20),19); if( idx>=0 && idx<20 ) { hist[idx]++; } total++; if( d<minResult ) { minResult = d; } if( d>maxResult ) { maxResult = d; } if( total%10000 == 0 ) { current = (omp_get_wtime() - started); done = current>5; } } printf("Random numbers generated: %ldK\n",total/1000); printf("Max random number: %f\n",maxResult); printf("Min random number: %f\n",minResult); maxIndex = 1; for(i=1;i<20;i++) { if( hist[i]>hist[maxIndex] ) { maxIndex = i; } } for(i=0;i<20;i++) { d = ((double)hist[i])/((double)hist[maxIndex]); j = (int)(d*60); while(j>=0) { printf("*"); j--; } printf("\n"); } } static void NormalHisto(RANDOM_GENERATE *prng) { int i,idx,j; int hist[20]; int maxIndex; double d; double started, current; int done; long total; double minResult = 1000; double maxResult = -1000; for(i=0;i<20;i++) { hist[i] = 0; } printf("Generating random numbers for 5 seconds...\nPlease wait...\n"); started = omp_get_wtime(); done = 0; total = 0; while(!done) { double d = RandNextGaussian(prng); idx = (int)((d*3)+10); if( idx<0 ) { idx = 0; } else if(idx>=20 ) { idx = 19; } if( d<minResult ) { minResult = d; } if( d>maxResult ) { maxResult = d; } hist[idx]++; total++; if( total%10000 == 0 ) { current = (omp_get_wtime() - started); done = current>5; } } printf("Random numbers generated: %ldK\n",total/1000); printf("Max random number: %f\n",maxResult); printf("Min random number: %f\n",minResult); maxIndex = 1; for(i=1;i<20;i++) { if( hist[i]>hist[maxIndex] ) { maxIndex = i; } } for(i=0;i<20;i++) { d = ((double)hist[i])/((double)hist[maxIndex]); j = (int)(d*60); while(j>=0) { printf("*"); j--; } printf("\n"); } } /* This utility generates random numbers via several PRNG's in either normal or uniform distribution. Sample output: Usage: random [prng] [dist] Where prng = mt, mwc, c or lcg and dist = uniform or normal i.e. random mt normal Generating random numbers for 5 seconds... Please wait... Random numbers generated: 383180K Max random number: 1.000000 Min random number: 0.000000 ************************************************************ ************************************************************ ************************************************************ ************************************************************ ************************************************************ ************************************************************ ************************************************************ ************************************************************ ************************************************************ ************************************************************ ************************************************************ ************************************************************ ************************************************************ ************************************************************ ************************************************************* ************************************************************ ************************************************************ ************************************************************ ************************************************************ ************************************************************ */ void ExampleRandom(int argIndex, int argc, char **argv) { RANDOM_GENERATE *prng; if( argc-argIndex != 2 ) { printf("Usage: \nrandom [prng] [dist]\nWhere prng = mt, mwc, c or lcg\nand dist = uniform or normal\ni.e. random mt normal\n"); prng = RandCreate(TYPE_RANDOM_MT,(long)time(NULL)); UniformHisto(prng); } else { if(!strcasecmp(argv[argIndex],"c") ) { prng = RandCreate(TYPE_RANDOM_C,(long)time(NULL)); } else if(!strcasecmp(argv[argIndex],"lcg") ) { prng = RandCreate(TYPE_RANDOM_LCG,(long)time(NULL)); } else if(!strcasecmp(argv[argIndex],"mwc") ) { prng = RandCreate(TYPE_RANDOM_MWC,(long)time(NULL)); } else if(!strcasecmp(argv[argIndex],"mt") ) { prng = RandCreate(TYPE_RANDOM_MT,(long)time(NULL)); } else { printf("Unknown PRNG: %s\n",argv[argIndex]); exit(1); } if(!strcasecmp(argv[argIndex+1],"normal") ) { NormalHisto(prng); } else if(!strcasecmp(argv[argIndex+1],"uniform") ) { UniformHisto(prng); } else { printf("Unknown distribution: %s\n",argv[argIndex+1]); exit(1); } } }
2,038
765
/***************************************************************************** Licensed to Accellera Systems Initiative Inc. (Accellera) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Accellera licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *****************************************************************************/ /***************************************************************************** scfx_ieee.h - Original Author: <NAME>, Synopsys, Inc. *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation, Date: Description of Modification: *****************************************************************************/ // $Log: scfx_ieee.h,v $ // Revision 1.3 2011/08/24 22:05:43 acg // <NAME>: initialization changes to remove warnings. // // Revision 1.2 2011/08/07 18:55:24 acg // <NAME>: added guard for __clang__ to get the clang platform // working. // // Revision 1.1.1.1 2006/12/15 20:20:04 acg // SystemC 2.3 // // Revision 1.3 2006/01/13 18:53:58 acg // <NAME>: added $Log command so that CVS comments are reproduced in // the source. // #ifndef __SYSTEMC_EXT_DT_FX_SCFX_IEEE_HH__ #define __SYSTEMC_EXT_DT_FX_SCFX_IEEE_HH__ #include "../../utils/endian.hh" #include "sc_fxdefs.hh" namespace sc_dt { // classes defined in this module union ieee_double; class scfx_ieee_double; union ieee_float; class scfx_ieee_float; #define SCFX_MASK_(Size) ((1u << (Size))-1u) // ---------------------------------------------------------------------------- // UNION : ieee_double // // IEEE 754 double-precision format. // ---------------------------------------------------------------------------- union ieee_double { double d; struct { #if defined(SC_BOOST_BIG_ENDIAN) unsigned negative:1; unsigned exponent:11; unsigned mantissa0:20; unsigned mantissa1:32; #elif defined(SC_BOOST_LITTLE_ENDIAN) unsigned mantissa1:32; unsigned mantissa0:20; unsigned exponent:11; unsigned negative:1; #endif } s; }; const unsigned int SCFX_IEEE_DOUBLE_BIAS = 1023U; const int SCFX_IEEE_DOUBLE_E_MAX = 1023; const int SCFX_IEEE_DOUBLE_E_MIN = -1022; const unsigned int SCFX_IEEE_DOUBLE_M_SIZE = 52; const unsigned int SCFX_IEEE_DOUBLE_M0_SIZE = 20; const unsigned int SCFX_IEEE_DOUBLE_M1_SIZE = 32; const unsigned int SCFX_IEEE_DOUBLE_E_SIZE = 11; // ---------------------------------------------------------------------------- // CLASS : scfx_ieee_double // // Convenient interface to union ieee_double. // ---------------------------------------------------------------------------- class scfx_ieee_double { ieee_double m_id; public: scfx_ieee_double(); scfx_ieee_double(double); scfx_ieee_double(const scfx_ieee_double &); scfx_ieee_double &operator = (double); scfx_ieee_double &operator = (const scfx_ieee_double &); operator double() const; unsigned int negative() const; void negative(unsigned int); int exponent() const; void exponent(int); unsigned int mantissa0() const; void mantissa0(unsigned int); unsigned int mantissa1() const; void mantissa1(unsigned int); bool is_zero() const; bool is_subnormal() const; bool is_normal() const; bool is_inf() const; bool is_nan() const; void set_inf(); void set_nan(); int msb() const; // most significant non-zero bit int lsb() const; // least significant non-zero bit static const scfx_ieee_double nan(); static const scfx_ieee_double inf(int); }; // IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII inline scfx_ieee_double::scfx_ieee_double() : m_id() { m_id.d = 0.0; } inline scfx_ieee_double::scfx_ieee_double(double d) : m_id() { m_id.d = d; } inline scfx_ieee_double::scfx_ieee_double(const scfx_ieee_double &a) : m_id(a.m_id) { // m_id.d = a.m_id.d; } inline scfx_ieee_double & scfx_ieee_double::operator = (double d) { m_id.d = d; return *this; } inline scfx_ieee_double & scfx_ieee_double::operator = (const scfx_ieee_double &a) { m_id.d = a.m_id.d; return *this; } inline scfx_ieee_double::operator double() const { return m_id.d; } inline unsigned int scfx_ieee_double::negative() const { return m_id.s.negative; } inline void scfx_ieee_double::negative(unsigned int a) { m_id.s.negative = a & SCFX_MASK_(1); } inline int scfx_ieee_double::exponent() const { return m_id.s.exponent - SCFX_IEEE_DOUBLE_BIAS; } inline void scfx_ieee_double::exponent(int a) { m_id.s.exponent = (SCFX_IEEE_DOUBLE_BIAS + a) & SCFX_MASK_(SCFX_IEEE_DOUBLE_E_SIZE); } inline unsigned int scfx_ieee_double::mantissa0() const { return m_id.s.mantissa0; } inline void scfx_ieee_double::mantissa0(unsigned int a) { m_id.s.mantissa0 = a & SCFX_MASK_(SCFX_IEEE_DOUBLE_M0_SIZE); } inline unsigned int scfx_ieee_double::mantissa1() const { return m_id.s.mantissa1; } inline void scfx_ieee_double::mantissa1(unsigned int a) { m_id.s.mantissa1 = a; // & SCFX_MASK_(SCFX_IEEE_DOUBLE_M1_SIZE); } inline bool scfx_ieee_double::is_zero() const { return (exponent() == SCFX_IEEE_DOUBLE_E_MIN - 1 && mantissa0() == 0U && mantissa1() == 0U); } inline bool scfx_ieee_double::is_subnormal() const { return (exponent() == SCFX_IEEE_DOUBLE_E_MIN - 1 && (mantissa0() != 0U || mantissa1() != 0U)); } inline bool scfx_ieee_double::is_normal() const { return (exponent() >= SCFX_IEEE_DOUBLE_E_MIN && exponent() <= SCFX_IEEE_DOUBLE_E_MAX); } inline bool scfx_ieee_double::is_inf() const { return (exponent() == SCFX_IEEE_DOUBLE_E_MAX + 1 && mantissa0() == 0U && mantissa1() == 0U); } inline bool scfx_ieee_double::is_nan() const { return (exponent() == SCFX_IEEE_DOUBLE_E_MAX + 1 && (mantissa0() != 0U || mantissa1() != 0U)); } inline void scfx_ieee_double::set_inf() { exponent(SCFX_IEEE_DOUBLE_E_MAX + 1); mantissa0(0U); mantissa1(0U); } inline void scfx_ieee_double::set_nan() { exponent(SCFX_IEEE_DOUBLE_E_MAX + 1); mantissa0((unsigned int)-1); mantissa1((unsigned int)-1); } #define MSB_STATEMENT(x,n) if ( x >> n ) { x >>= n; i += n; } inline int scfx_ieee_double::msb() const { unsigned int m0 = mantissa0(); unsigned int m1 = mantissa1(); if (m0 != 0) { int i = 0; MSB_STATEMENT(m0, 16); MSB_STATEMENT(m0, 8); MSB_STATEMENT(m0, 4); MSB_STATEMENT(m0, 2); MSB_STATEMENT(m0, 1); return (i - 20); } else if (m1 != 0) { int i = 0; MSB_STATEMENT(m1, 16); MSB_STATEMENT(m1, 8); MSB_STATEMENT(m1, 4); MSB_STATEMENT(m1, 2); MSB_STATEMENT(m1, 1); return (i - 52); } else { return 0; } } #undef MSB_STATEMENT #define LSB_STATEMENT(x,n) if ( x << n ) { x <<= n; i -= n; } inline int scfx_ieee_double::lsb() const { unsigned int m0 = mantissa0(); unsigned int m1 = mantissa1(); if (m1 != 0) { int i = 31; LSB_STATEMENT(m1, 16); LSB_STATEMENT(m1, 8); LSB_STATEMENT(m1, 4); LSB_STATEMENT(m1, 2); LSB_STATEMENT(m1, 1); return (i - 52); } else if (m0 != 0) { int i = 31; LSB_STATEMENT(m0, 16); LSB_STATEMENT(m0, 8); LSB_STATEMENT(m0, 4); LSB_STATEMENT(m0, 2); LSB_STATEMENT(m0, 1); return (i - 20); } else { return 0; } } #undef LSB_STATEMENT inline const scfx_ieee_double scfx_ieee_double::nan() { scfx_ieee_double id; id.set_nan(); return id; } inline const scfx_ieee_double scfx_ieee_double::inf(int sign) { scfx_ieee_double id(sign); id.set_inf(); return id; } // ---------------------------------------------------------------------------- // UNION : ieee_float // // IEEE 754 single-precision format. // ---------------------------------------------------------------------------- union ieee_float { float f; struct { #if defined(SC_BOOST_BIG_ENDIAN) unsigned negative:1; unsigned exponent:8; unsigned mantissa:23; #elif defined(SC_BOOST_LITTLE_ENDIAN) unsigned mantissa:23; unsigned exponent:8; unsigned negative:1; #endif } s; }; const unsigned int SCFX_IEEE_FLOAT_BIAS = 127U; const int SCFX_IEEE_FLOAT_E_MAX = 127; const int SCFX_IEEE_FLOAT_E_MIN = -126; const unsigned int SCFX_IEEE_FLOAT_M_SIZE = 23; const unsigned int SCFX_IEEE_FLOAT_E_SIZE = 8; // ---------------------------------------------------------------------------- // CLASS : scfx_ieee_float // // Convenient wrapper to union ieee_float. // ---------------------------------------------------------------------------- class scfx_ieee_float { ieee_float m_if; public: scfx_ieee_float(); scfx_ieee_float(float); scfx_ieee_float(const scfx_ieee_float &); scfx_ieee_float &operator = (float); scfx_ieee_float &operator = (const scfx_ieee_float &); operator float() const; unsigned int negative() const; void negative(unsigned int); int exponent() const; void exponent(int); unsigned int mantissa() const; void mantissa(unsigned int); bool is_zero() const; bool is_subnormal() const; bool is_normal() const; bool is_inf() const; bool is_nan() const; void set_inf(); void set_nan(); }; // IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII inline scfx_ieee_float::scfx_ieee_float() : m_if() { m_if.f = 0.0; } inline scfx_ieee_float::scfx_ieee_float(float f) : m_if() { m_if.f = f; } inline scfx_ieee_float::scfx_ieee_float(const scfx_ieee_float &a) : m_if(a.m_if) { // m_if.f = a.m_if.f; } inline scfx_ieee_float & scfx_ieee_float::operator = (float f) { m_if.f = f; return *this; } inline scfx_ieee_float & scfx_ieee_float::operator = (const scfx_ieee_float &a) { m_if.f = a.m_if.f; return *this; } inline scfx_ieee_float::operator float() const { return m_if.f; } inline unsigned int scfx_ieee_float::negative() const { return m_if.s.negative; } inline void scfx_ieee_float::negative(unsigned int a) { m_if.s.negative = a & SCFX_MASK_(1); } inline int scfx_ieee_float::exponent() const { return m_if.s.exponent - SCFX_IEEE_FLOAT_BIAS; } inline void scfx_ieee_float::exponent(int a) { m_if.s.exponent = (SCFX_IEEE_FLOAT_BIAS + a) & SCFX_MASK_(SCFX_IEEE_FLOAT_E_SIZE); } inline unsigned int scfx_ieee_float::mantissa() const { return m_if.s.mantissa; } inline void scfx_ieee_float::mantissa(unsigned int a) { m_if.s.mantissa = a & SCFX_MASK_(SCFX_IEEE_FLOAT_M_SIZE); } inline bool scfx_ieee_float::is_zero() const { return (exponent() == SCFX_IEEE_FLOAT_E_MIN - 1 && mantissa() == 0U); } inline bool scfx_ieee_float::is_subnormal() const { return (exponent() == SCFX_IEEE_FLOAT_E_MIN - 1 && mantissa() != 0U); } inline bool scfx_ieee_float::is_normal() const { return (exponent() >= SCFX_IEEE_FLOAT_E_MIN && exponent() <= SCFX_IEEE_FLOAT_E_MAX); } inline bool scfx_ieee_float::is_inf() const { return (exponent() == SCFX_IEEE_FLOAT_E_MAX + 1 && mantissa() == 0U); } inline bool scfx_ieee_float::is_nan() const { return (exponent() == SCFX_IEEE_FLOAT_E_MAX + 1 && mantissa() != 0U); } inline void scfx_ieee_float::set_inf() { exponent(SCFX_IEEE_FLOAT_E_MAX + 1); mantissa(0U); } inline void scfx_ieee_float::set_nan() { exponent(SCFX_IEEE_FLOAT_E_MAX + 1); mantissa((unsigned int)-1); } // ---------------------------------------------------------------------------- // FUNCTION : scfx_pow2 // // Computes 2.0**exp in double-precision. // ---------------------------------------------------------------------------- inline double scfx_pow2(int exp) { scfx_ieee_double r; if (exp < SCFX_IEEE_DOUBLE_E_MIN) { r = 0.0; // handle subnormal case exp -= SCFX_IEEE_DOUBLE_E_MIN; if ((exp += 20) >= 0) { r.mantissa0(1U << exp); } else if ((exp += 32) >= 0) { r.mantissa1(1U << exp); } } else if (exp > SCFX_IEEE_DOUBLE_E_MAX) { r.set_inf(); } else { r = 1.0; r.exponent(exp); } return r; } // ---------------------------------------------------------------------------- // FUNCTION : uint64_to_double // // Platform independent conversion from double uint64 to double. // Needed because VC++6 doesn't support this conversion. // ---------------------------------------------------------------------------- inline double uint64_to_double(uint64 a) { #if defined(__clang__) // conversion from uint64 to double not implemented; use int64 double tmp = static_cast<double>(static_cast<int64>(a)); return (tmp >= 0) ? tmp : tmp + sc_dt::scfx_pow2(64); #else return static_cast<double>(a); #endif } } // namespace sc_dt #undef SCFX_MASK_ #endif // __SYSTEMC_EXT_DT_FX_SCFX_IEEE_HH__
5,733
471
<filename>corehq/util/workbook_reading/adapters/__init__.py from .csv import open_csv_workbook from .xls import open_xls_workbook from .xlsx import open_xlsx_workbook from .generic import open_any_workbook, valid_extensions from .raw_data import make_worksheet __all__ = [ 'open_csv_workbook', 'open_xls_workbook', 'open_xlsx_workbook', 'open_any_workbook', 'make_worksheet', 'valid_extensions' ]
169
984
<gh_stars>100-1000 /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.phoenix.parse; import java.sql.SQLException; import org.apache.phoenix.compile.ColumnResolver; /** * * Node representing the selection of all columns (*) in the SELECT clause of SQL * * * @since 0.1 */ public class WildcardParseNode extends TerminalParseNode { public static final String NAME = "*"; public static final WildcardParseNode INSTANCE = new WildcardParseNode(false); public static final WildcardParseNode REWRITE_INSTANCE = new WildcardParseNode(true); private final boolean isRewrite; private WildcardParseNode(boolean isRewrite) { this.isRewrite = isRewrite; } @Override public <T> T accept(ParseNodeVisitor<T> visitor) throws SQLException { return visitor.visit(this); } public boolean isRewrite() { return isRewrite; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (isRewrite ? 1231 : 1237); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; WildcardParseNode other = (WildcardParseNode) obj; if (isRewrite != other.isRewrite) return false; return true; } @Override public void toSQL(ColumnResolver resolver, StringBuilder buf) { buf.append(' '); buf.append(NAME); buf.append(' '); } }
752
359
/* Copyright 2018 New Vector Ltd 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. */ #import <Foundation/Foundation.h> @class MXEventScanStore, MXEventScan; /** `MXEventScanStoreDelegate` is used to inform changes in the `MXEventScanStore`. */ @protocol MXEventScanStoreDelegate <NSObject> /** Inform of `MXEventScan` changes in a `MXEventScanStore`. @param eventScanStore The `MXEventScanStore` having changes. @param insertions `MXEventScan`s inserted. @param modifications `MXEventScan`s modified. @param deletions `MXEventScan`s deleted. */ - (void)eventScanStore:(nonnull MXEventScanStore*)eventScanStore didObserveChangesWithInsertions:(nonnull NSArray<MXEventScan*>*)insertions modifications:(nonnull NSArray<MXEventScan*>*)modifications deletions:(nonnull NSArray<MXEventScan*>*)deletions; @end
359
1,104
<gh_stars>1000+ package com.cg.baseproject.utils.android; import android.graphics.ColorMatrixColorFilter; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.widget.ImageView; /** * @Description:主要功能:控件点击效果动画工具类 * @Prject: CommonUtilLibrary * @Package: com.jingewenku.abrahamcaijin.commonutil * @author: AbrahamCaiJin * @date: 2017年05月15日 11:42 * @Copyright: 个人版权所有 * @Company: * @version: 1.0.0 */ public class AnimationUtils { /** * 给视图添加点击效果,让背景变深 * */ public static void addTouchDrak(View view, boolean isClick) { view.setOnTouchListener(VIEW_TOUCH_DARK); if (!isClick) { view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); } } /** * 给视图添加点击效果,让背景变暗 * */ public static void addTouchLight(View view, boolean isClick) { view.setOnTouchListener(VIEW_TOUCH_LIGHT); if (!isClick) { view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); } } /** * 让控件点击时,颜色变深 * */ public static final OnTouchListener VIEW_TOUCH_DARK = new OnTouchListener() { public final float[] BT_SELECTED = new float[] { 1, 0, 0, 0, -50, 0, 1, 0, 0, -50, 0, 0, 1, 0, -50, 0, 0, 0, 1, 0 }; public final float[] BT_NOT_SELECTED = new float[] { 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0 }; @SuppressWarnings("deprecation") @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { if (v instanceof ImageView) { ImageView iv = (ImageView) v; iv.setColorFilter(new ColorMatrixColorFilter(BT_SELECTED)); } else { v.getBackground().setColorFilter( new ColorMatrixColorFilter(BT_SELECTED)); v.setBackgroundDrawable(v.getBackground()); } } else if (event.getAction() == MotionEvent.ACTION_UP) { if (v instanceof ImageView) { ImageView iv = (ImageView) v; iv.setColorFilter(new ColorMatrixColorFilter( BT_NOT_SELECTED)); } else { v.getBackground().setColorFilter( new ColorMatrixColorFilter(BT_NOT_SELECTED)); v.setBackgroundDrawable(v.getBackground()); } } return false; } }; /** * 让控件点击时,颜色变暗 * */ public static final OnTouchListener VIEW_TOUCH_LIGHT = new OnTouchListener() { public final float[] BT_SELECTED = new float[] { 1, 0, 0, 0, 50, 0, 1, 0, 0, 50, 0, 0, 1, 0, 50, 0, 0, 0, 1, 0 }; public final float[] BT_NOT_SELECTED = new float[] { 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0 }; @SuppressWarnings("deprecation") @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { if (v instanceof ImageView) { ImageView iv = (ImageView) v; iv.setDrawingCacheEnabled(true); iv.setColorFilter(new ColorMatrixColorFilter(BT_SELECTED)); } else { v.getBackground().setColorFilter( new ColorMatrixColorFilter(BT_SELECTED)); v.setBackgroundDrawable(v.getBackground()); } } else if (event.getAction() == MotionEvent.ACTION_UP) { if (v instanceof ImageView) { ImageView iv = (ImageView) v; iv.setColorFilter(new ColorMatrixColorFilter( BT_NOT_SELECTED)); } else { v.getBackground().setColorFilter( new ColorMatrixColorFilter(BT_NOT_SELECTED)); v.setBackgroundDrawable(v.getBackground()); } } return false; } }; }
2,396
777
// 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. #ifndef EXTENSIONS_COMMON_FEATURES_BASE_FEATURE_PROVIDER_H_ #define EXTENSIONS_COMMON_FEATURES_BASE_FEATURE_PROVIDER_H_ #include <map> #include <memory> #include <string> #include <vector> #include "base/macros.h" #include "base/strings/string_piece.h" #include "extensions/common/features/feature_provider.h" namespace extensions { class Feature; // A FeatureProvider contains the mapping of all feature names specified in the // _*_features.json files to the Feature classes. Look up a Feature by its name // to determine whether or not it is available in a certain context. // Subclasses implement the specific logic for how the features are populated; // this class handles vending the features given the query. // TODO(devlin): We could probably combine this and FeatureProvider, since both // contain common functionality and neither are designed to be full // implementations. class BaseFeatureProvider : public FeatureProvider { public: ~BaseFeatureProvider() override; // Gets the feature |feature_name|, if it exists. Feature* GetFeature(const std::string& feature_name) const override; Feature* GetParent(Feature* feature) const override; std::vector<Feature*> GetChildren(const Feature& parent) const override; const FeatureMap& GetAllFeatures() const override; protected: BaseFeatureProvider(); void AddFeature(base::StringPiece name, std::unique_ptr<Feature> feature); // Takes ownership. Used in preference to unique_ptr variant to reduce size // of generated code. void AddFeature(base::StringPiece name, Feature* feature); private: std::map<std::string, std::unique_ptr<Feature>> features_; DISALLOW_COPY_AND_ASSIGN(BaseFeatureProvider); }; } // namespace extensions #endif // EXTENSIONS_COMMON_FEATURES_BASE_FEATURE_PROVIDER_H_
541
12,252
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.keycloak.models.sessions.infinispan.stream; import org.keycloak.models.sessions.infinispan.changes.SessionEntityWrapper; import org.keycloak.models.sessions.infinispan.entities.LoginFailureEntity; import org.keycloak.models.sessions.infinispan.entities.LoginFailureKey; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Map; import java.util.function.Predicate; import org.infinispan.commons.marshall.Externalizer; import org.infinispan.commons.marshall.MarshallUtil; import org.infinispan.commons.marshall.SerializeWith; /** * @author <a href="mailto:<EMAIL>"><NAME></a> */ @SerializeWith(UserLoginFailurePredicate.ExternalizerImpl.class) public class UserLoginFailurePredicate implements Predicate<Map.Entry<LoginFailureKey, SessionEntityWrapper<LoginFailureEntity>>> { private final String realm; private UserLoginFailurePredicate(String realm) { this.realm = realm; } public static UserLoginFailurePredicate create(String realm) { return new UserLoginFailurePredicate(realm); } @Override public boolean test(Map.Entry<LoginFailureKey, SessionEntityWrapper<LoginFailureEntity>> entry) { LoginFailureEntity e = entry.getValue().getEntity(); return realm.equals(e.getRealmId()); } public static class ExternalizerImpl implements Externalizer<UserLoginFailurePredicate> { private static final int VERSION_1 = 1; @Override public void writeObject(ObjectOutput output, UserLoginFailurePredicate obj) throws IOException { output.writeByte(VERSION_1); MarshallUtil.marshallString(obj.realm, output); } @Override public UserLoginFailurePredicate readObject(ObjectInput input) throws IOException, ClassNotFoundException { switch (input.readByte()) { case VERSION_1: return readObjectVersion1(input); default: throw new IOException("Unknown version"); } } public UserLoginFailurePredicate readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException { UserLoginFailurePredicate res = new UserLoginFailurePredicate(MarshallUtil.unmarshallString(input)); return res; } } }
1,021
8,575
// // SFPreferencePane.h // Soundfly // // Created by <NAME> on 15/02/08. // Copyright 2008 abyssoft. All rights reserved. // #import <PreferencePanes/PreferencePanes.h> @class SFVersionTextField; @interface SFPreferencePane : NSPreferencePane { BOOL _active; int _senderStatus; int _receiverStatus; IBOutlet NSWindow * _aboutWindow; IBOutlet SFVersionTextField * _versionTextField; } - (BOOL)isLeopardOrBetter; - (IBAction)showAboutSheet:(id)sender; - (void)closeAboutSheet; - (NSImage*)receiverConnectionImage; - (NSString*)receiverConnectionTooltip; - (NSImage*)senderConnectionImage; - (NSString*)senderConnectionTooltip; @end
255
316
<reponame>roblabs/maplibre-gl-native [ "BaseLocationActivity", "MapSnapshotterMarkerActivity", "MapSnapshotterReuseActivity", "MapSnapshotterLocalStyleActivity", "LatLngBoundsActivity", "BottomSheetActivity", "MockLocationEngine", "DeleteRegionActivity", "RealTimeGeoJsonActivity", "UpdateMetadataActivity", "CarDrivingActivity", "MyLocationTrackingModeActivity", "MyLocationToggleActivity", "MyLocationTintActivity", "MyLocationDrawableActivity", "DoubleMapActivity", "LocationPickerActivity", "GeoJsonClusteringActivity", "RuntimeStyleTestActivity", "AnimatedSymbolLayerActivity", "ViewPagerActivity", "MapFragmentActivity", "SupportMapFragmentActivity", "SnapshotActivity", "NavigationDrawerActivity", "QueryRenderedFeaturesBoxHighlightActivity", "MultiMapActivity", "MapInDialogActivity", "ManualZoomActivity", "MaxMinZoomActivity", "ScrollByActivity", "ZoomFunctionSymbolLayerActivity", "SymbolGeneratorActivity", "TextureViewTransparentBackgroundActivity", "SimpleMapActivity", "RenderTestActivity", "SymbolLayerActivity", "LocationFragmentActivity", "MergeOfflineRegionsActivity", "NestedViewPagerActivity", "DebugModeActivity", "TextureViewDebugModeActivity", "RuntimeStyleActivity", "GridSourceActivity", "AnimatedImageSourceActivity", "EspressoTestActivity", "ChangeResourcesCachePathActivity", "EspressoTestActivity", "FragmentBackStackActivity", "ChildFragmentMapInDialogActivity", "PerformanceMeasurementActivity" ]
471
4,879
#import "MWMTableViewController.h" #include <string> #include <vector> #include <utility> @interface MWMTTSSettingsViewController : MWMTableViewController - (void)setAdditionalTTSLanguage:(std::pair<std::string, std::string> const &)l; - (std::vector<std::pair<std::string, std::string>> const &)languages; @end
107
327
package com.honvay.cola.cloud.framework.base.configuration; import com.honvay.cola.cloud.framework.core.constant.ErrorStatus; import com.honvay.cola.cloud.framework.core.exception.ServiceException; import com.honvay.cola.cloud.framework.core.protocol.Result; import org.hibernate.validator.internal.engine.path.PathImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.validation.BindException; import org.springframework.validation.FieldError; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.bind.annotation.*; import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; import org.springframework.web.multipart.MultipartException; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 全局 验证 异常 处理 * @author LIQIU * @date 2017-12-20 */ @ControllerAdvice(annotations = {RestController.class,Controller.class}) public class GlobalExceptionHandler { @Value("${spring.profiles.active:dev}") public String activeProfile; private static final String DEV_MODE = "dev"; private static final String TEST_MODE = "test"; private Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class); private String getMessage(Exception exception,ErrorStatus status){ if(activeProfile.equalsIgnoreCase(DEV_MODE) || activeProfile.equalsIgnoreCase(TEST_MODE)){ return exception.getMessage() != null ? exception.getMessage() : status.getMessage(); }else{ return status.getMessage(); } } /** * 构建返回错误 * @param status * @param exception * @param data * @return */ private Result failure(ErrorStatus status,Exception exception,Object data){ String meesage = null; if(exception != null){ meesage = this.getMessage(exception,status); } return Result.buildFailure(status.value(),meesage,data); } /** * 构建返回错误 * @param status * @param data * @return */ private Result failure(ErrorStatus status,Object data){ return failure(status,null,data); } /** * 构建返回错误 * @param status * @param exception * @return */ private Result failure(ErrorStatus status,Exception exception){ return failure(status,exception,null); } /** * 构建返回错误 * @param status * @return */ private Result failure(ErrorStatus status){ return Result.buildFailure(status); } @ResponseBody @ResponseStatus(HttpStatus.OK) @ExceptionHandler(ConstraintViolationException.class) public Result handleValidationException(ConstraintViolationException e) { log.error(ErrorStatus.ILLEGAL_DATA.getMessage() + ":" + e.getMessage()); List<Map<String, Object>> fields = new ArrayList<>(); for (ConstraintViolation<?> cv : e.getConstraintViolations()) { String fieldName = ((PathImpl) cv.getPropertyPath()).getLeafNode().asString(); String message = cv.getMessage(); Map<String, Object> field = new HashMap<>(); field.put("field", fieldName); field.put("message", message); fields.add(field); } return failure(ErrorStatus.ILLEGAL_DATA, fields); } @ResponseBody @ExceptionHandler(BindException.class) @ResponseStatus(HttpStatus.OK) public Result handleBindException(BindException e) { log.error(ErrorStatus.ILLEGAL_DATA.getMessage() + ":" + e.getMessage()); List<Map<String, Object>> fields = new ArrayList<>(); for (FieldError error : e.getFieldErrors()) { Map<String, Object> field = new HashMap<>(); field.put("field", error.getField()); field.put("message", error.getDefaultMessage()); fields.add(field); } return failure(ErrorStatus.ILLEGAL_DATA, fields); } @ResponseBody @ExceptionHandler(MultipartException.class) @ResponseStatus(HttpStatus.OK) public Result handleMultipartException(){ return failure(ErrorStatus.MULTIPART_TOO_LARGE); } @ResponseBody @ExceptionHandler(IllegalArgumentException.class) @ResponseStatus(HttpStatus.OK) public Result handleIllegalArgumentException(IllegalArgumentException e) { log.error(ErrorStatus.ILLEGAL_ARGUMENT.getMessage() + ":" + e.getMessage()); return failure(ErrorStatus.ILLEGAL_ARGUMENT,e); } @ResponseBody @ExceptionHandler(MissingServletRequestParameterException.class) @ResponseStatus(HttpStatus.OK) public Result handleMissingServletRequestParameterException( MissingServletRequestParameterException e) { log.error(ErrorStatus.MISSING_ARGUMENT.getMessage() + ":" + e.getMessage()); return failure(ErrorStatus.MISSING_ARGUMENT,e); } @ResponseBody @ExceptionHandler(MethodArgumentTypeMismatchException.class) @ResponseStatus(HttpStatus.OK) public Result handleMethodArgumentTypeMismatchExceptionException( MethodArgumentTypeMismatchException e) { log.error(ErrorStatus.ILLEGAL_ARGUMENT_TYPE.getMessage() + ":" + e.getMessage()); return failure(ErrorStatus.ILLEGAL_ARGUMENT_TYPE,e); } @ResponseBody @ExceptionHandler(Exception.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public Result handleException(Exception e) { e.printStackTrace(); log.error(ErrorStatus.INTERNAL_SERVER_ERROR.getMessage() + ":" + e.getMessage()); return failure(ErrorStatus.INTERNAL_SERVER_ERROR,e); } @ResponseBody @ExceptionHandler(HttpRequestMethodNotSupportedException.class) @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED) public Result handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) { log.error(ErrorStatus.METHOD_NOT_ALLOWED.getMessage() + ":" + e.getMessage()); return failure(ErrorStatus.METHOD_NOT_ALLOWED,e); } @ResponseBody @ExceptionHandler(ServiceException.class) @ResponseStatus(HttpStatus.OK) public Result handleServiceException(ServiceException e) { log.error(ErrorStatus.SERVICE_EXCEPTION.getMessage() + ":" + e.getMessage()); if(e.getCode() == null){ return failure(ErrorStatus.SERVICE_EXCEPTION,e); }else{ return Result.buildFailure(e.getCode(),e.getMessage()); } } @ResponseBody @ExceptionHandler(IllegalStateException.class) @ResponseStatus(HttpStatus.OK) public Result handleIllegalStateException(IllegalStateException e) { log.warn("exception",e); return failure(ErrorStatus.ILLEGAL_STATE,e); } }
2,699
4,612
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Tests for loading tests by name. """ import os import sys import unittest as pyunit from hashlib import md5 from twisted.python import filepath, util from twisted.python.modules import getModule from twisted.python.reflect import ModuleNotFound from twisted.trial import reporter, runner, unittest from twisted.trial._asyncrunner import _iterateTests from twisted.trial.itrial import ITestCase from twisted.trial.test import packages def testNames(tests): """ Return the id of each test within the given test suite or case. """ names = [] for test in _iterateTests(tests): names.append(test.id()) return names class FinderPy3Tests(packages.SysPathManglingTest): def setUp(self): super().setUp() self.loader = runner.TestLoader() def test_findNonModule(self): """ findByName, if given something findable up until the last entry, will raise AttributeError (as it cannot tell if 'nonexistent' here is supposed to be a module or a class). """ self.assertRaises( AttributeError, self.loader.findByName, "twisted.trial.test.nonexistent" ) def test_findNonPackage(self): self.assertRaises(ModuleNotFound, self.loader.findByName, "nonextant") def test_findNonFile(self): """ findByName, given a file path that doesn't exist, will raise a ValueError saying that it is not a Python file. """ path = util.sibpath(__file__, "nonexistent.py") self.assertRaises(ValueError, self.loader.findByName, path) def test_findFileWithImportError(self): """ findByName will re-raise ImportErrors inside modules that it has found and imported. """ self.assertRaises( ImportError, self.loader.findByName, "unimportablepackage.test_module" ) class FileTests(packages.SysPathManglingTest): """ Tests for L{runner.filenameToModule}. """ def test_notFile(self): """ L{runner.filenameToModule} raises a C{ValueError} when a non-existing file is passed. """ err = self.assertRaises(ValueError, runner.filenameToModule, "it") self.assertEqual(str(err), "'it' doesn't exist") def test_moduleInPath(self): """ If the file in question is a module on the Python path, then it should properly import and return that module. """ sample1 = runner.filenameToModule(util.sibpath(__file__, "sample.py")) from twisted.trial.test import sample as sample2 self.assertEqual(sample2, sample1) def test_moduleNotInPath(self): """ If passed the path to a file containing the implementation of a module within a package which is not on the import path, L{runner.filenameToModule} returns a module object loosely resembling the module defined by that file anyway. """ self.mangleSysPath(self.oldPath) sample1 = runner.filenameToModule( os.path.join(self.parent, "goodpackage", "test_sample.py") ) self.assertEqual(sample1.__name__, "goodpackage.test_sample") self.cleanUpModules() self.mangleSysPath(self.newPath) from goodpackage import test_sample as sample2 # type: ignore[import] self.assertIsNot(sample1, sample2) self.assertEqual(sample1.__spec__, sample2.__spec__) def test_packageInPath(self): """ If the file in question is a package on the Python path, then it should properly import and return that package. """ package1 = runner.filenameToModule(os.path.join(self.parent, "goodpackage")) self.assertIs(package1, sys.modules["goodpackage"]) def test_packageNotInPath(self): """ If passed the path to a directory which represents a package which is not on the import path, L{runner.filenameToModule} returns a module object loosely resembling the package defined by that directory anyway. """ self.mangleSysPath(self.oldPath) package1 = runner.filenameToModule(os.path.join(self.parent, "goodpackage")) self.assertEqual(package1.__name__, "goodpackage") self.cleanUpModules() self.mangleSysPath(self.newPath) import goodpackage self.assertIsNot(package1, goodpackage) self.assertEqual(package1.__spec__, goodpackage.__spec__) def test_directoryNotPackage(self): """ L{runner.filenameToModule} raises a C{ValueError} when the name of an empty directory is passed that isn't considered a valid Python package because it doesn't contain a C{__init__.py} file. """ emptyDir = filepath.FilePath(self.parent).child("emptyDirectory") emptyDir.createDirectory() err = self.assertRaises(ValueError, runner.filenameToModule, emptyDir.path) self.assertEqual(str(err), f"{emptyDir.path!r} is not a package directory") def test_filenameNotPython(self): """ L{runner.filenameToModule} raises a C{SyntaxError} when a non-Python file is passed. """ filename = filepath.FilePath(self.parent).child("notpython") filename.setContent(b"This isn't python") self.assertRaises(SyntaxError, runner.filenameToModule, filename.path) def test_filenameMatchesPackage(self): """ The C{__file__} attribute of the module should match the package name. """ filename = filepath.FilePath(self.parent).child("goodpackage.py") filename.setContent(packages.testModule.encode("utf8")) try: module = runner.filenameToModule(filename.path) self.assertEqual(filename.path, module.__file__) finally: filename.remove() def test_directory(self): """ Test loader against a filesystem directory containing an empty C{__init__.py} file. It should handle 'path' and 'path/' the same way. """ goodDir = filepath.FilePath(self.parent).child("goodDirectory") goodDir.createDirectory() goodDir.child("__init__.py").setContent(b"") try: module = runner.filenameToModule(goodDir.path) self.assertTrue(module.__name__.endswith("goodDirectory")) module = runner.filenameToModule(goodDir.path + os.path.sep) self.assertTrue(module.__name__.endswith("goodDirectory")) finally: goodDir.remove() class LoaderTests(packages.SysPathManglingTest): """ Tests for L{trial.TestLoader}. """ def setUp(self): self.loader = runner.TestLoader() packages.SysPathManglingTest.setUp(self) def test_sortCases(self): from twisted.trial.test import sample suite = self.loader.loadClass(sample.AlphabetTest) self.assertEqual( ["test_a", "test_b", "test_c"], [test._testMethodName for test in suite._tests], ) newOrder = ["test_b", "test_c", "test_a"] sortDict = dict(zip(newOrder, range(3))) self.loader.sorter = lambda x: sortDict.get(x.shortDescription(), -1) suite = self.loader.loadClass(sample.AlphabetTest) self.assertEqual(newOrder, [test._testMethodName for test in suite._tests]) def test_loadFailure(self): """ Loading a test that fails and getting the result of it ends up with one test ran and one failure. """ suite = self.loader.loadByName( "twisted.trial.test.erroneous.TestRegularFail.test_fail" ) result = reporter.TestResult() suite.run(result) self.assertEqual(result.testsRun, 1) self.assertEqual(len(result.failures), 1) def test_loadBadDecorator(self): """ A decorated test method for which the decorator has failed to set the method's __name__ correctly is loaded and its name in the class scope discovered. """ from twisted.trial.test import sample suite = self.loader.loadAnything( sample.DecorationTest.test_badDecorator, parent=sample.DecorationTest, qualName=["sample", "DecorationTest", "test_badDecorator"], ) self.assertEqual(1, suite.countTestCases()) self.assertEqual("test_badDecorator", suite._testMethodName) def test_loadGoodDecorator(self): """ A decorated test method for which the decorator has set the method's __name__ correctly is loaded and the only name by which it goes is used. """ from twisted.trial.test import sample suite = self.loader.loadAnything( sample.DecorationTest.test_goodDecorator, parent=sample.DecorationTest, qualName=["sample", "DecorationTest", "test_goodDecorator"], ) self.assertEqual(1, suite.countTestCases()) self.assertEqual("test_goodDecorator", suite._testMethodName) def test_loadRenamedDecorator(self): """ Load a decorated method which has been copied to a new name inside the class. Thus its __name__ and its key in the class's __dict__ no longer match. """ from twisted.trial.test import sample suite = self.loader.loadAnything( sample.DecorationTest.test_renamedDecorator, parent=sample.DecorationTest, qualName=["sample", "DecorationTest", "test_renamedDecorator"], ) self.assertEqual(1, suite.countTestCases()) self.assertEqual("test_renamedDecorator", suite._testMethodName) def test_loadClass(self): from twisted.trial.test import sample suite = self.loader.loadClass(sample.FooTest) self.assertEqual(2, suite.countTestCases()) self.assertEqual( ["test_bar", "test_foo"], [test._testMethodName for test in suite._tests] ) def test_loadNonClass(self): from twisted.trial.test import sample self.assertRaises(TypeError, self.loader.loadClass, sample) self.assertRaises(TypeError, self.loader.loadClass, sample.FooTest.test_foo) self.assertRaises(TypeError, self.loader.loadClass, "string") self.assertRaises(TypeError, self.loader.loadClass, ("foo", "bar")) def test_loadNonTestCase(self): from twisted.trial.test import sample self.assertRaises(ValueError, self.loader.loadClass, sample.NotATest) def test_loadModule(self): from twisted.trial.test import sample suite = self.loader.loadModule(sample) self.assertEqual(10, suite.countTestCases()) def test_loadNonModule(self): from twisted.trial.test import sample self.assertRaises(TypeError, self.loader.loadModule, sample.FooTest) self.assertRaises(TypeError, self.loader.loadModule, sample.FooTest.test_foo) self.assertRaises(TypeError, self.loader.loadModule, "string") self.assertRaises(TypeError, self.loader.loadModule, ("foo", "bar")) def test_loadPackage(self): import goodpackage suite = self.loader.loadPackage(goodpackage) self.assertEqual(7, suite.countTestCases()) def test_loadNonPackage(self): from twisted.trial.test import sample self.assertRaises(TypeError, self.loader.loadPackage, sample.FooTest) self.assertRaises(TypeError, self.loader.loadPackage, sample.FooTest.test_foo) self.assertRaises(TypeError, self.loader.loadPackage, "string") self.assertRaises(TypeError, self.loader.loadPackage, ("foo", "bar")) def test_loadModuleAsPackage(self): from twisted.trial.test import sample ## XXX -- should this instead raise a ValueError? -- jml self.assertRaises(TypeError, self.loader.loadPackage, sample) def test_loadPackageRecursive(self): import goodpackage suite = self.loader.loadPackage(goodpackage, recurse=True) self.assertEqual(14, suite.countTestCases()) def test_loadAnythingOnModule(self): from twisted.trial.test import sample suite = self.loader.loadAnything(sample) self.assertEqual( sample.__name__, suite._tests[0]._tests[0].__class__.__module__ ) def test_loadAnythingOnClass(self): from twisted.trial.test import sample suite = self.loader.loadAnything(sample.FooTest) self.assertEqual(2, suite.countTestCases()) def test_loadAnythingOnPackage(self): import goodpackage suite = self.loader.loadAnything(goodpackage) self.assertTrue(isinstance(suite, self.loader.suiteFactory)) self.assertEqual(7, suite.countTestCases()) def test_loadAnythingOnPackageRecursive(self): import goodpackage suite = self.loader.loadAnything(goodpackage, recurse=True) self.assertTrue(isinstance(suite, self.loader.suiteFactory)) self.assertEqual(14, suite.countTestCases()) def test_loadAnythingOnString(self): # the important thing about this test is not the string-iness # but the non-handledness. self.assertRaises(TypeError, self.loader.loadAnything, "goodpackage") def test_importErrors(self): import package # type: ignore[import] suite = self.loader.loadPackage(package, recurse=True) result = reporter.Reporter() suite.run(result) self.assertEqual(False, result.wasSuccessful()) self.assertEqual(2, len(result.errors)) errors = [test.id() for test, error in result.errors] errors.sort() self.assertEqual( errors, ["package.test_bad_module", "package.test_import_module"] ) def test_differentInstances(self): """ L{TestLoader.loadClass} returns a suite with each test method represented by a different instances of the L{TestCase} they are defined on. """ class DistinctInstances(pyunit.TestCase): def test_1(self): self.first = "test1Run" def test_2(self): self.assertFalse(hasattr(self, "first")) suite = self.loader.loadClass(DistinctInstances) result = reporter.Reporter() suite.run(result) self.assertTrue(result.wasSuccessful()) def test_loadModuleWith_test_suite(self): """ Check that C{test_suite} is used when present and other L{TestCase}s are not included. """ from twisted.trial.test import mockcustomsuite suite = self.loader.loadModule(mockcustomsuite) self.assertEqual(0, suite.countTestCases()) self.assertEqual("MyCustomSuite", getattr(suite, "name", None)) def test_loadModuleWith_testSuite(self): """ Check that C{testSuite} is used when present and other L{TestCase}s are not included. """ from twisted.trial.test import mockcustomsuite2 suite = self.loader.loadModule(mockcustomsuite2) self.assertEqual(0, suite.countTestCases()) self.assertEqual("MyCustomSuite", getattr(suite, "name", None)) def test_loadModuleWithBothCustom(self): """ Check that if C{testSuite} and C{test_suite} are both present in a module then C{testSuite} gets priority. """ from twisted.trial.test import mockcustomsuite3 suite = self.loader.loadModule(mockcustomsuite3) self.assertEqual("testSuite", getattr(suite, "name", None)) def test_customLoadRaisesAttributeError(self): """ Make sure that any C{AttributeError}s raised by C{testSuite} are not swallowed by L{TestLoader}. """ def testSuite(): raise AttributeError("should be reraised") from twisted.trial.test import mockcustomsuite2 mockcustomsuite2.testSuite, original = (testSuite, mockcustomsuite2.testSuite) try: self.assertRaises(AttributeError, self.loader.loadModule, mockcustomsuite2) finally: mockcustomsuite2.testSuite = original # XXX - duplicated and modified from test_script def assertSuitesEqual(self, test1, test2): names1 = testNames(test1) names2 = testNames(test2) names1.sort() names2.sort() self.assertEqual(names1, names2) def test_loadByNamesDuplicate(self): """ Check that loadByNames ignores duplicate names """ module = "twisted.trial.test.test_log" suite1 = self.loader.loadByNames([module, module], True) suite2 = self.loader.loadByName(module, True) self.assertSuitesEqual(suite1, suite2) def test_loadByNamesPreservesOrder(self): """ L{TestLoader.loadByNames} preserves the order of tests provided to it. """ modules = [ "inheritancepackage.test_x.A.test_foo", "twisted.trial.test.sample", "goodpackage", "twisted.trial.test.test_log", "twisted.trial.test.sample.FooTest", "package.test_module", ] suite1 = self.loader.loadByNames(modules) suite2 = runner.TestSuite(map(self.loader.loadByName, modules)) self.assertEqual(testNames(suite1), testNames(suite2)) def test_loadDifferentNames(self): """ Check that loadByNames loads all the names that it is given """ modules = ["goodpackage", "package.test_module"] suite1 = self.loader.loadByNames(modules) suite2 = runner.TestSuite(map(self.loader.loadByName, modules)) self.assertSuitesEqual(suite1, suite2) def test_loadInheritedMethods(self): """ Check that test methods names which are inherited from are all loaded rather than just one. """ methods = [ "inheritancepackage.test_x.A.test_foo", "inheritancepackage.test_x.B.test_foo", ] suite1 = self.loader.loadByNames(methods) suite2 = runner.TestSuite(map(self.loader.loadByName, methods)) self.assertSuitesEqual(suite1, suite2) class ZipLoadingTests(LoaderTests): def setUp(self): from twisted.python.test.test_zippath import zipit LoaderTests.setUp(self) zipit(self.parent, self.parent + ".zip") self.parent += ".zip" self.mangleSysPath(self.oldPath + [self.parent]) class PackageOrderingTests(packages.SysPathManglingTest): def setUp(self): self.loader = runner.TestLoader() self.topDir = self.mktemp() parent = os.path.join(self.topDir, "uberpackage") os.makedirs(parent) open(os.path.join(parent, "__init__.py"), "wb").close() packages.SysPathManglingTest.setUp(self, parent) self.mangleSysPath(self.oldPath + [self.topDir]) def _trialSortAlgorithm(self, sorter): """ Right now, halfway by accident, trial sorts like this: 1. all modules are grouped together in one list and sorted. 2. within each module, the classes are grouped together in one list and sorted. 3. finally within each class, each test method is grouped together in a list and sorted. This attempts to return a sorted list of testable thingies following those rules, so that we can compare the behavior of loadPackage. The things that show as 'cases' are errors from modules which failed to import, and test methods. Let's gather all those together. """ pkg = getModule("uberpackage") testModules = [] for testModule in pkg.walkModules(): if testModule.name.split(".")[-1].startswith("test_"): testModules.append(testModule) sortedModules = sorted(testModules, key=sorter) # ONE for modinfo in sortedModules: # Now let's find all the classes. module = modinfo.load(None) if module is None: yield modinfo else: testClasses = [] for attrib in modinfo.iterAttributes(): if runner.isTestCase(attrib.load()): testClasses.append(attrib) sortedClasses = sorted(testClasses, key=sorter) # TWO for clsinfo in sortedClasses: testMethods = [] for attr in clsinfo.iterAttributes(): if attr.name.split(".")[-1].startswith("test"): testMethods.append(attr) sortedMethods = sorted(testMethods, key=sorter) # THREE yield from sortedMethods def loadSortedPackages(self, sorter=runner.name): """ Verify that packages are loaded in the correct order. """ import uberpackage # type: ignore[import] self.loader.sorter = sorter suite = self.loader.loadPackage(uberpackage, recurse=True) # XXX: Work around strange, unexplained Zope crap. # jml, 2007-11-15. suite = unittest.decorate(suite, ITestCase) resultingTests = list(_iterateTests(suite)) manifest = list(self._trialSortAlgorithm(sorter)) for number, (manifestTest, actualTest) in enumerate( zip(manifest, resultingTests) ): self.assertEqual( manifestTest.name, actualTest.id(), "#%d: %s != %s" % (number, manifestTest.name, actualTest.id()), ) self.assertEqual(len(manifest), len(resultingTests)) def test_sortPackagesDefaultOrder(self): self.loadSortedPackages() def test_sortPackagesSillyOrder(self): def sillySorter(s): # This has to work on fully-qualified class names and class # objects, which is silly, but it's the "spec", such as it is. # if isinstance(s, type): # return s.__module__+'.'+s.__name__ n = runner.name(s) d = md5(n.encode("utf8")).hexdigest() return d self.loadSortedPackages(sillySorter)
9,311
678
package utils; public class CurrencyConverterGlobal { public static int global_image_id; public static String global_country_name; public static String country_id; }
54
507
<filename>spring-aot/src/main/java/org/springframework/aot/nativex/ConfigurationContributor.java /* * Copyright 2019-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.aot.nativex; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.aop.framework.BuildTimeProxyDescriptor; import org.springframework.aop.framework.ProxyConfiguration; import org.springframework.aop.framework.ProxyGenerator; import org.springframework.aot.BootstrapContributor; import org.springframework.aot.BuildContext; import org.springframework.aot.ResourceFile; import org.springframework.boot.loader.tools.MainClassFinder; import org.springframework.nativex.AotOptions; import org.springframework.nativex.domain.proxies.AotProxyDescriptor; import org.springframework.nativex.domain.proxies.JdkProxyDescriptor; import org.springframework.nativex.domain.reflect.ClassDescriptor; import org.springframework.nativex.domain.reflect.ReflectionDescriptor; import org.springframework.nativex.hint.Flag; import org.springframework.nativex.support.ConfigurationCollector; import org.springframework.nativex.support.SpringAnalyzer; import org.springframework.nativex.type.TypeSystem; import net.bytebuddy.description.type.TypeDescription; import net.bytebuddy.dynamic.DynamicType.Unloaded; /** * Contributes the configuration files for native image construction. This includes the reflection, * resource and proxy configuration in addition to the native-image.properties file that includes * special args and initialization configuration. * * @author <NAME> */ public class ConfigurationContributor implements BootstrapContributor { private static Log logger = LogFactory.getLog(ConfigurationContributor.class); @Override public void contribute(BuildContext context, AotOptions aotOptions) { TypeSystem typeSystem = new TypeSystem(context.getClasspath(), context.getMainClass()); typeSystem.setAotOptions(aotOptions); SpringAnalyzer springAnalyzer = new SpringAnalyzer(typeSystem, aotOptions); springAnalyzer.analyze(); ConfigurationCollector configurationCollector = springAnalyzer.getConfigurationCollector(); processBuildTimeClassProxyRequests(context, configurationCollector); context.describeReflection(reflect -> reflect.merge(configurationCollector.getReflectionDescriptor())); context.describeResources(resources -> resources.merge(configurationCollector.getResourcesDescriptors())); context.describeProxies(proxies -> proxies.merge(configurationCollector.getProxyDescriptors())); context.describeSerialization(serial -> serial.merge(configurationCollector.getSerializationDescriptor())); context.describeJNIReflection(jniReflect -> jniReflect.merge(configurationCollector.getJNIReflectionDescriptor())); context.describeInitialization(init -> init.merge(configurationCollector.getInitializationDescriptor())); context.getOptions().forEach(option -> configurationCollector.addOption(option)); String mainClass = getMainClass(context); if (mainClass != null) { configurationCollector.addOption("-H:Class=" + mainClass); } byte[] springComponentsFileContents = configurationCollector.getResources("META-INF/spring.components"); if (springComponentsFileContents!=null) { logger.debug("Storing synthesized META-INF/spring.components"); context.addResources(new ResourceFile() { @Override public void writeTo(Path resourcesPath) throws IOException { Path metaInfFolder = resourcesPath.resolve(Paths.get("META-INF")); Files.createDirectories(metaInfFolder); try (FileOutputStream fos = new FileOutputStream(resourcesPath.resolve(ResourceFile.SPRING_COMPONENTS_PATH).toFile())) { fos.write(springComponentsFileContents); } } }); } // Create native-image.properties context.addResources(new ResourceFile() { @Override public void writeTo(Path rootPath) throws IOException { Path nativeConfigFolder = rootPath.resolve(ResourceFile.NATIVE_CONFIG_PATH); Files.createDirectories(nativeConfigFolder); Path nativeImagePropertiesFile = nativeConfigFolder.resolve("native-image.properties"); try (FileOutputStream fos = new FileOutputStream(nativeImagePropertiesFile.toFile())) { fos.write(configurationCollector.getNativeImagePropertiesContent().getBytes()); } } }); } private String getMainClass(BuildContext context) { if (context.getMainClass() != null) { return context.getMainClass(); } for (String path : context.getClasspath()) { String mainClass = null; try { mainClass = MainClassFinder.findSingleMainClass(new File(path)); } catch (IOException e) { logger.error(e); } if (mainClass != null) { logger.debug("ManifestContributor found Spring Boot main class: " + mainClass); return mainClass; } } logger.debug("Unable to find main class"); return null; } /** * If the configuration has requested any class proxies to be constructed at build time, create them and register * reflective access to their necessary parts. */ private void processBuildTimeClassProxyRequests(BuildContext context, ConfigurationCollector configurationCollector) { List<String> classProxyNames = generateBuildTimeClassProxies(configurationCollector, context); ReflectionDescriptor reflectionDescriptor = new ReflectionDescriptor(); if (!classProxyNames.isEmpty()) { for (String classProxyName: classProxyNames) { ClassDescriptor classDescriptor = ClassDescriptor.of(classProxyName); classDescriptor.setFlag(Flag.allDeclaredConstructors); // TODO [build time proxies] not all proxy variants will need method access - depends on what // it is for - perhaps surface access bit configuration in the classproxyhint to allow flexibility? classDescriptor.setFlag(Flag.allDeclaredMethods); reflectionDescriptor.add(classDescriptor); } configurationCollector.addReflectionDescriptor(reflectionDescriptor, false); } } public List<String> generateBuildTimeClassProxies(ConfigurationCollector configurationCollector, BuildContext context) { List<String> classProxyNames = new ArrayList<>(); Set<AotProxyDescriptor> classProxyDescriptors = configurationCollector.getClassProxyDescriptors(); for (JdkProxyDescriptor proxyDescriptor : context.getProxiesDescriptor().getProxyDescriptors()) { if (proxyDescriptor.isClassProxy()) { classProxyDescriptors.add((AotProxyDescriptor) proxyDescriptor); } } for (AotProxyDescriptor classProxyDescriptor: classProxyDescriptors) { if(context.getTypeSystem().resolve(classProxyDescriptor.getTargetClassType()) == null) { logger.debug("Cannot reach class proxy target type of: "+classProxyDescriptor); continue; } classProxyNames.add(generateBuildTimeClassProxy(classProxyDescriptor, context)); } return classProxyNames; } @SuppressWarnings("deprecation") private String generateBuildTimeClassProxy(AotProxyDescriptor cpd, BuildContext context) { BuildTimeProxyDescriptor c = cpd.asCPDescriptor(); ProxyConfiguration proxyConfiguration = ProxyConfiguration.get(c, null); List<String> classpath = context.getClasspath(); URL[] urls = new URL[classpath.size()]; for (int i=0;i<classpath.size();i++) { try { urls[i] = new File(classpath.get(i)).toURI().toURL(); } catch (MalformedURLException e) { throw new IllegalStateException(e); } } // TODO [build time proxies] is this parent OK? URLClassLoader ucl = new URLClassLoader(urls,ConfigurationContributor.class.getClassLoader()); logger.debug("Creating build time class proxy for class "+c.getTargetClassType()); Unloaded<?> unloadedProxy = ProxyGenerator.getProxyBytes(c, ucl); Path primaryProxyFilepath = Paths.get(proxyConfiguration.getProxyClassName().replace(".", "/") + ".class"); context.addResources(new ResourceFile() { @Override public void writeTo(Path resourcesPath) throws IOException { Path primaryProxyRelativeFolder = primaryProxyFilepath.getParent(); Path primaryProxyFilename = primaryProxyFilepath.getFileName(); Path primaryProxyFolder = resourcesPath.resolve(primaryProxyRelativeFolder); Files.createDirectories(primaryProxyFolder); Path primaryProxyAbsolutePath = primaryProxyFolder.resolve(primaryProxyFilename); logger.debug("Writing out build time class proxy as resource for type "+primaryProxyFilepath); try (FileOutputStream fos = new FileOutputStream(primaryProxyAbsolutePath.toFile())) { fos.write(unloadedProxy.getBytes()); } } }); Map<TypeDescription, byte[]> auxiliaryTypes = unloadedProxy.getAuxiliaryTypes(); if (auxiliaryTypes!=null) { for (Map.Entry<TypeDescription, byte[]> auxiliaryType: auxiliaryTypes.entrySet()) { context.addResources(new ProxyAuxResourceFile(auxiliaryType.getKey(), auxiliaryType.getValue())); } } return proxyConfiguration.getProxyClassName(); } /** * Represents one of the auxiliary classes generated to support each method * invocation that needs delegation in a proxy class. */ static class ProxyAuxResourceFile implements ResourceFile { private Path auxProxyFilepath; private byte[] data; ProxyAuxResourceFile(TypeDescription td, byte[] data) { this.data = data; auxProxyFilepath = Paths.get(td.getName().replace(".", "/") + ".class"); } @Override public void writeTo(Path resourcesPath) throws IOException { Path auxProxyRelativeFolder = auxProxyFilepath.getParent(); Path auxProxyFilename = auxProxyFilepath.getFileName(); Path auxProxyFolder = resourcesPath.resolve(auxProxyRelativeFolder); Files.createDirectories(auxProxyFolder); Path auxProxyAbsolutePath = auxProxyFolder.resolve(auxProxyFilename); logger.debug("Writing out build time class proxy support class as resource for type "+auxProxyFilepath); try (FileOutputStream fos = new FileOutputStream(auxProxyAbsolutePath.toFile())) { fos.write(data); } } } }
3,376
2,293
/* universal.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, * 2005, 2006, 2007, 2008 by <NAME> and others * * You may distribute under the terms of either the GNU General Public * License or the Artistic License, as specified in the README file. * */ /* * '"The roots of those mountains must be roots indeed; there must be * great secrets buried there which have not been discovered since the * beginning."' --Gandalf, relating Gollum's history * * [p.54 of _The Lord of the Rings_, I/ii: "The Shadow of the Past"] */ /* This file contains the code that implements the functions in Perl's * UNIVERSAL package, such as UNIVERSAL->can(). * * It is also used to store XS functions that need to be present in * miniperl for a lack of a better place to put them. It might be * clever to move them to seperate XS files which would then be pulled * in by some to-be-written build process. */ #include "EXTERN.h" #define PERL_IN_UNIVERSAL_C #include "perl.h" #ifdef USE_PERLIO #include "perliol.h" /* For the PERLIO_F_XXX */ #endif static HV * S_get_isa_hash(pTHX_ HV *const stash) { dVAR; struct mro_meta *const meta = HvMROMETA(stash); PERL_ARGS_ASSERT_GET_ISA_HASH; if (!meta->isa) { AV *const isa = mro_get_linear_isa(stash); if (!meta->isa) { HV *const isa_hash = newHV(); /* Linearisation didn't build it for us, so do it here. */ SV *const *svp = AvARRAY(isa); SV *const *const svp_end = svp + AvFILLp(isa) + 1; const HEK *const canon_name = HvNAME_HEK(stash); while (svp < svp_end) { (void) hv_store_ent(isa_hash, *svp++, &PL_sv_undef, 0); } (void) hv_common(isa_hash, NULL, HEK_KEY(canon_name), HEK_LEN(canon_name), HEK_FLAGS(canon_name), HV_FETCH_ISSTORE, &PL_sv_undef, HEK_HASH(canon_name)); (void) hv_store(isa_hash, "UNIVERSAL", 9, &PL_sv_undef, 0); SvREADONLY_on(isa_hash); meta->isa = isa_hash; } } return meta->isa; } /* * Contributed by <NAME> <<EMAIL>> * The main guts of traverse_isa was actually copied from gv_fetchmeth */ STATIC bool S_isa_lookup(pTHX_ HV *stash, const char * const name) { dVAR; const struct mro_meta *const meta = HvMROMETA(stash); HV *const isa = meta->isa ? meta->isa : S_get_isa_hash(aTHX_ stash); STRLEN len = strlen(name); const HV *our_stash; PERL_ARGS_ASSERT_ISA_LOOKUP; if (hv_common(isa, NULL, name, len, 0 /* No "UTF-8" flag possible with only a char * argument*/, HV_FETCH_ISEXISTS, NULL, 0)) { /* Direct name lookup worked. */ return TRUE; } /* A stash/class can go by many names (ie. User == main::User), so we use the name in the stash itself, which is canonical. */ our_stash = gv_stashpvn(name, len, 0); if (our_stash) { HEK *const canon_name = HvNAME_HEK(our_stash); if (hv_common(isa, NULL, HEK_KEY(canon_name), HEK_LEN(canon_name), HEK_FLAGS(canon_name), HV_FETCH_ISEXISTS, NULL, HEK_HASH(canon_name))) { return TRUE; } } return FALSE; } /* =head1 SV Manipulation Functions =for apidoc sv_derived_from Returns a boolean indicating whether the SV is derived from the specified class I<at the C level>. To check derivation at the Perl level, call C<isa()> as a normal Perl method. =cut */ bool Perl_sv_derived_from(pTHX_ SV *sv, const char *const name) { dVAR; HV *stash; PERL_ARGS_ASSERT_SV_DERIVED_FROM; SvGETMAGIC(sv); if (SvROK(sv)) { const char *type; sv = SvRV(sv); type = sv_reftype(sv,0); if (type && strEQ(type,name)) return TRUE; stash = SvOBJECT(sv) ? SvSTASH(sv) : NULL; } else { stash = gv_stashsv(sv, 0); } return stash ? isa_lookup(stash, name) : FALSE; } /* =for apidoc sv_does Returns a boolean indicating whether the SV performs a specific, named role. The SV can be a Perl object or the name of a Perl class. =cut */ #include "XSUB.h" bool Perl_sv_does(pTHX_ SV *sv, const char *const name) { const char *classname; bool does_it; SV *methodname; dSP; PERL_ARGS_ASSERT_SV_DOES; ENTER; SAVETMPS; SvGETMAGIC(sv); if (!SvOK(sv) || !(SvROK(sv) || (SvPOK(sv) && SvCUR(sv)) || (SvGMAGICAL(sv) && SvPOKp(sv) && SvCUR(sv)))) return FALSE; if (sv_isobject(sv)) { classname = sv_reftype(SvRV(sv),TRUE); } else { classname = SvPV_nolen(sv); } if (strEQ(name,classname)) return TRUE; PUSHMARK(SP); XPUSHs(sv); mXPUSHs(newSVpv(name, 0)); PUTBACK; methodname = newSVpvs_flags("isa", SVs_TEMP); /* ugly hack: use the SvSCREAM flag so S_method_common * can figure out we're calling DOES() and not isa(), * and report eventual errors correctly. --rgs */ SvSCREAM_on(methodname); call_sv(methodname, G_SCALAR | G_METHOD); SPAGAIN; does_it = SvTRUE( TOPs ); FREETMPS; LEAVE; return does_it; } PERL_XS_EXPORT_C void XS_UNIVERSAL_isa(pTHX_ CV *cv); PERL_XS_EXPORT_C void XS_UNIVERSAL_can(pTHX_ CV *cv); PERL_XS_EXPORT_C void XS_UNIVERSAL_DOES(pTHX_ CV *cv); PERL_XS_EXPORT_C void XS_UNIVERSAL_VERSION(pTHX_ CV *cv); XS(XS_version_new); XS(XS_version_stringify); XS(XS_version_numify); XS(XS_version_normal); XS(XS_version_vcmp); XS(XS_version_boolean); #ifdef HASATTRIBUTE_NORETURN XS(XS_version_noop) __attribute__noreturn__; #else XS(XS_version_noop); #endif XS(XS_version_is_alpha); XS(XS_version_qv); XS(XS_version_is_qv); XS(XS_utf8_is_utf8); XS(XS_utf8_valid); XS(XS_utf8_encode); XS(XS_utf8_decode); XS(XS_utf8_upgrade); XS(XS_utf8_downgrade); XS(XS_utf8_unicode_to_native); XS(XS_utf8_native_to_unicode); XS(XS_Internals_SvREADONLY); XS(XS_Internals_SvREFCNT); XS(XS_Internals_hv_clear_placehold); XS(XS_PerlIO_get_layers); XS(XS_Internals_hash_seed); XS(XS_Internals_rehash_seed); XS(XS_Internals_HvREHASH); XS(XS_re_is_regexp); XS(XS_re_regname); XS(XS_re_regnames); XS(XS_re_regnames_count); XS(XS_re_regexp_pattern); XS(XS_Tie_Hash_NamedCapture_FETCH); XS(XS_Tie_Hash_NamedCapture_STORE); XS(XS_Tie_Hash_NamedCapture_DELETE); XS(XS_Tie_Hash_NamedCapture_CLEAR); XS(XS_Tie_Hash_NamedCapture_EXISTS); XS(XS_Tie_Hash_NamedCapture_FIRSTK); XS(XS_Tie_Hash_NamedCapture_NEXTK); XS(XS_Tie_Hash_NamedCapture_SCALAR); XS(XS_Tie_Hash_NamedCapture_flags); void Perl_boot_core_UNIVERSAL(pTHX) { dVAR; static const char file[] = __FILE__; newXS("UNIVERSAL::isa", XS_UNIVERSAL_isa, file); newXS("UNIVERSAL::can", XS_UNIVERSAL_can, file); newXS("UNIVERSAL::DOES", XS_UNIVERSAL_DOES, file); newXS("UNIVERSAL::VERSION", XS_UNIVERSAL_VERSION, file); { /* register the overloading (type 'A') magic */ PL_amagic_generation++; /* Make it findable via fetchmethod */ newXS("version::()", XS_version_noop, file); newXS("version::new", XS_version_new, file); newXS("version::parse", XS_version_new, file); newXS("version::(\"\"", XS_version_stringify, file); newXS("version::stringify", XS_version_stringify, file); newXS("version::(0+", XS_version_numify, file); newXS("version::numify", XS_version_numify, file); newXS("version::normal", XS_version_normal, file); newXS("version::(cmp", XS_version_vcmp, file); newXS("version::(<=>", XS_version_vcmp, file); newXS("version::vcmp", XS_version_vcmp, file); newXS("version::(bool", XS_version_boolean, file); newXS("version::boolean", XS_version_boolean, file); newXS("version::(nomethod", XS_version_noop, file); newXS("version::noop", XS_version_noop, file); newXS("version::is_alpha", XS_version_is_alpha, file); newXS("version::qv", XS_version_qv, file); newXS("version::declare", XS_version_qv, file); newXS("version::is_qv", XS_version_is_qv, file); } newXS("utf8::is_utf8", XS_utf8_is_utf8, file); newXS("utf8::valid", XS_utf8_valid, file); newXS("utf8::encode", XS_utf8_encode, file); newXS("utf8::decode", XS_utf8_decode, file); newXS("utf8::upgrade", XS_utf8_upgrade, file); newXS("utf8::downgrade", XS_utf8_downgrade, file); newXS("utf8::native_to_unicode", XS_utf8_native_to_unicode, file); newXS("utf8::unicode_to_native", XS_utf8_unicode_to_native, file); newXSproto("Internals::SvREADONLY",XS_Internals_SvREADONLY, file, "\\[$%@];$"); newXSproto("Internals::SvREFCNT",XS_Internals_SvREFCNT, file, "\\[$%@];$"); newXSproto("Internals::hv_clear_placeholders", XS_Internals_hv_clear_placehold, file, "\\%"); newXSproto("PerlIO::get_layers", XS_PerlIO_get_layers, file, "*;@"); /* Providing a Regexp::DESTROY fixes #21347. See test in t/op/ref.t */ CvFILE(newCONSTSUB(get_hv("Regexp::", GV_ADD), "DESTROY", NULL)) = (char *)file; newXSproto("Internals::hash_seed",XS_Internals_hash_seed, file, ""); newXSproto("Internals::rehash_seed",XS_Internals_rehash_seed, file, ""); newXSproto("Internals::HvREHASH", XS_Internals_HvREHASH, file, "\\%"); newXSproto("re::is_regexp", XS_re_is_regexp, file, "$"); newXSproto("re::regname", XS_re_regname, file, ";$$"); newXSproto("re::regnames", XS_re_regnames, file, ";$"); newXSproto("re::regnames_count", XS_re_regnames_count, file, ""); newXSproto("re::regexp_pattern", XS_re_regexp_pattern, file, "$"); newXS("Tie::Hash::NamedCapture::FETCH", XS_Tie_Hash_NamedCapture_FETCH, file); newXS("Tie::Hash::NamedCapture::STORE", XS_Tie_Hash_NamedCapture_STORE, file); newXS("Tie::Hash::NamedCapture::DELETE", XS_Tie_Hash_NamedCapture_DELETE, file); newXS("Tie::Hash::NamedCapture::CLEAR", XS_Tie_Hash_NamedCapture_CLEAR, file); newXS("Tie::Hash::NamedCapture::EXISTS", XS_Tie_Hash_NamedCapture_EXISTS, file); newXS("Tie::Hash::NamedCapture::FIRSTKEY", XS_Tie_Hash_NamedCapture_FIRSTK, file); newXS("Tie::Hash::NamedCapture::NEXTKEY", XS_Tie_Hash_NamedCapture_NEXTK, file); newXS("Tie::Hash::NamedCapture::SCALAR", XS_Tie_Hash_NamedCapture_SCALAR, file); newXS("Tie::Hash::NamedCapture::flags", XS_Tie_Hash_NamedCapture_flags, file); } /* =for apidoc croak_xs_usage A specialised variant of C<croak()> for emitting the usage message for xsubs croak_xs_usage(cv, "eee_yow"); works out the package name and subroutine name from C<cv>, and then calls C<croak()>. Hence if C<cv> is C<&ouch::awk>, it would call C<croak> as: Perl_croak(aTHX_ "Usage %s::%s(%s)", "ouch" "awk", "eee_yow"); =cut */ void Perl_croak_xs_usage(pTHX_ const CV *const cv, const char *const params) { const GV *const gv = CvGV(cv); PERL_ARGS_ASSERT_CROAK_XS_USAGE; if (gv) { const char *const gvname = GvNAME(gv); const HV *const stash = GvSTASH(gv); const char *const hvname = stash ? HvNAME_get(stash) : NULL; if (hvname) Perl_croak(aTHX_ "Usage: %s::%s(%s)", hvname, gvname, params); else Perl_croak(aTHX_ "Usage: %s(%s)", gvname, params); } else { /* Pants. I don't think that it should be possible to get here. */ Perl_croak(aTHX_ "Usage: CODE(0x%"UVxf")(%s)", PTR2UV(cv), params); } } XS(XS_UNIVERSAL_isa) { dVAR; dXSARGS; if (items != 2) croak_xs_usage(cv, "reference, kind"); else { SV * const sv = ST(0); const char *name; SvGETMAGIC(sv); if (!SvOK(sv) || !(SvROK(sv) || (SvPOK(sv) && SvCUR(sv)) || (SvGMAGICAL(sv) && SvPOKp(sv) && SvCUR(sv)))) XSRETURN_UNDEF; name = SvPV_nolen_const(ST(1)); ST(0) = boolSV(sv_derived_from(sv, name)); XSRETURN(1); } } XS(XS_UNIVERSAL_can) { dVAR; dXSARGS; SV *sv; const char *name; SV *rv; HV *pkg = NULL; if (items != 2) croak_xs_usage(cv, "object-ref, method"); sv = ST(0); SvGETMAGIC(sv); if (!SvOK(sv) || !(SvROK(sv) || (SvPOK(sv) && SvCUR(sv)) || (SvGMAGICAL(sv) && SvPOKp(sv) && SvCUR(sv)))) XSRETURN_UNDEF; name = SvPV_nolen_const(ST(1)); rv = &PL_sv_undef; if (SvROK(sv)) { sv = MUTABLE_SV(SvRV(sv)); if (SvOBJECT(sv)) pkg = SvSTASH(sv); } else { pkg = gv_stashsv(sv, 0); } if (pkg) { GV * const gv = gv_fetchmethod_autoload(pkg, name, FALSE); if (gv && isGV(gv)) rv = sv_2mortal(newRV(MUTABLE_SV(GvCV(gv)))); } ST(0) = rv; XSRETURN(1); } XS(XS_UNIVERSAL_DOES) { dVAR; dXSARGS; PERL_UNUSED_ARG(cv); if (items != 2) Perl_croak(aTHX_ "Usage: invocant->DOES(kind)"); else { SV * const sv = ST(0); const char *name; name = SvPV_nolen_const(ST(1)); if (sv_does( sv, name )) XSRETURN_YES; XSRETURN_NO; } } XS(XS_UNIVERSAL_VERSION) { dVAR; dXSARGS; HV *pkg; GV **gvp; GV *gv; SV *sv; const char *undef; PERL_UNUSED_ARG(cv); if (SvROK(ST(0))) { sv = MUTABLE_SV(SvRV(ST(0))); if (!SvOBJECT(sv)) Perl_croak(aTHX_ "Cannot find version of an unblessed reference"); pkg = SvSTASH(sv); } else { pkg = gv_stashsv(ST(0), 0); } gvp = pkg ? (GV**)hv_fetchs(pkg, "VERSION", FALSE) : NULL; if (gvp && isGV(gv = *gvp) && (sv = GvSV(gv)) && SvOK(sv)) { SV * const nsv = sv_newmortal(); sv_setsv(nsv, sv); sv = nsv; if ( !sv_derived_from(sv, "version")) upg_version(sv, FALSE); undef = NULL; } else { sv = &PL_sv_undef; undef = "(undef)"; } if (items > 1) { SV *req = ST(1); if (undef) { if (pkg) { const char * const name = HvNAME_get(pkg); Perl_croak(aTHX_ "%s does not define $%s::VERSION--version check failed", name, name); } else { Perl_croak(aTHX_ "%s defines neither package nor VERSION--version check failed", SvPVx_nolen_const(ST(0)) ); } } if ( !sv_derived_from(req, "version")) { /* req may very well be R/O, so create a new object */ req = sv_2mortal( new_version(req) ); } if ( vcmp( req, sv ) > 0 ) { if ( hv_exists(MUTABLE_HV(SvRV(req)), "qv", 2 ) ) { Perl_croak(aTHX_ "%s version %"SVf" required--" "this is only version %"SVf"", HvNAME_get(pkg), SVfARG(vnormal(req)), SVfARG(vnormal(sv))); } else { Perl_croak(aTHX_ "%s version %"SVf" required--" "this is only version %"SVf"", HvNAME_get(pkg), SVfARG(vstringify(req)), SVfARG(vstringify(sv))); } } } if ( SvOK(sv) && sv_derived_from(sv, "version") ) { ST(0) = vstringify(sv); } else { ST(0) = sv; } XSRETURN(1); } XS(XS_version_new) { dVAR; dXSARGS; if (items > 3) croak_xs_usage(cv, "class, version"); SP -= items; { SV *vs = ST(1); SV *rv; const char * const classname = sv_isobject(ST(0)) /* get the class if called as an object method */ ? HvNAME(SvSTASH(SvRV(ST(0)))) : (char *)SvPV_nolen(ST(0)); if ( items == 1 || vs == &PL_sv_undef ) { /* no param or explicit undef */ /* create empty object */ vs = sv_newmortal(); sv_setpvs(vs,""); } else if ( items == 3 ) { vs = sv_newmortal(); Perl_sv_setpvf(aTHX_ vs,"v%s",SvPV_nolen_const(ST(2))); } rv = new_version(vs); if ( strcmp(classname,"version") != 0 ) /* inherited new() */ sv_bless(rv, gv_stashpv(classname, GV_ADD)); mPUSHs(rv); PUTBACK; return; } } XS(XS_version_stringify) { dVAR; dXSARGS; if (items < 1) croak_xs_usage(cv, "lobj, ..."); SP -= items; { SV * lobj; if (sv_derived_from(ST(0), "version")) { lobj = SvRV(ST(0)); } else Perl_croak(aTHX_ "lobj is not of type version"); mPUSHs(vstringify(lobj)); PUTBACK; return; } } XS(XS_version_numify) { dVAR; dXSARGS; if (items < 1) croak_xs_usage(cv, "lobj, ..."); SP -= items; { SV * lobj; if (sv_derived_from(ST(0), "version")) { lobj = SvRV(ST(0)); } else Perl_croak(aTHX_ "lobj is not of type version"); mPUSHs(vnumify(lobj)); PUTBACK; return; } } XS(XS_version_normal) { dVAR; dXSARGS; if (items < 1) croak_xs_usage(cv, "lobj, ..."); SP -= items; { SV * lobj; if (sv_derived_from(ST(0), "version")) { lobj = SvRV(ST(0)); } else Perl_croak(aTHX_ "lobj is not of type version"); mPUSHs(vnormal(lobj)); PUTBACK; return; } } XS(XS_version_vcmp) { dVAR; dXSARGS; if (items < 1) croak_xs_usage(cv, "lobj, ..."); SP -= items; { SV * lobj; if (sv_derived_from(ST(0), "version")) { lobj = SvRV(ST(0)); } else Perl_croak(aTHX_ "lobj is not of type version"); { SV *rs; SV *rvs; SV * robj = ST(1); const IV swap = (IV)SvIV(ST(2)); if ( ! sv_derived_from(robj, "version") ) { robj = new_version(robj); } rvs = SvRV(robj); if ( swap ) { rs = newSViv(vcmp(rvs,lobj)); } else { rs = newSViv(vcmp(lobj,rvs)); } mPUSHs(rs); } PUTBACK; return; } } XS(XS_version_boolean) { dVAR; dXSARGS; if (items < 1) croak_xs_usage(cv, "lobj, ..."); SP -= items; if (sv_derived_from(ST(0), "version")) { SV * const lobj = SvRV(ST(0)); SV * const rs = newSViv( vcmp(lobj,new_version(newSVpvs("0"))) ); mPUSHs(rs); PUTBACK; return; } else Perl_croak(aTHX_ "lobj is not of type version"); } XS(XS_version_noop) { dVAR; dXSARGS; if (items < 1) croak_xs_usage(cv, "lobj, ..."); if (sv_derived_from(ST(0), "version")) Perl_croak(aTHX_ "operation not supported with version object"); else Perl_croak(aTHX_ "lobj is not of type version"); #ifndef HASATTRIBUTE_NORETURN XSRETURN_EMPTY; #endif } XS(XS_version_is_alpha) { dVAR; dXSARGS; if (items != 1) croak_xs_usage(cv, "lobj"); SP -= items; if (sv_derived_from(ST(0), "version")) { SV * const lobj = ST(0); if ( hv_exists(MUTABLE_HV(SvRV(lobj)), "alpha", 5 ) ) XSRETURN_YES; else XSRETURN_NO; PUTBACK; return; } else Perl_croak(aTHX_ "lobj is not of type version"); } XS(XS_version_qv) { dVAR; dXSARGS; PERL_UNUSED_ARG(cv); SP -= items; { SV * ver = ST(0); SV * rv; const char * classname = ""; if ( items == 2 && (ST(1)) != &PL_sv_undef ) { /* getting called as object or class method */ ver = ST(1); classname = sv_isobject(ST(0)) /* class called as an object method */ ? HvNAME_get(SvSTASH(SvRV(ST(0)))) : (char *)SvPV_nolen(ST(0)); } if ( !SvVOK(ver) ) { /* not already a v-string */ rv = sv_newmortal(); sv_setsv(rv,ver); /* make a duplicate */ upg_version(rv, TRUE); } else { rv = sv_2mortal(new_version(ver)); } if ( items == 2 && strcmp(classname,"version") ) { /* inherited new() */ sv_bless(rv, gv_stashpv(classname, GV_ADD)); } PUSHs(rv); } PUTBACK; return; } XS(XS_version_is_qv) { dVAR; dXSARGS; if (items != 1) croak_xs_usage(cv, "lobj"); SP -= items; if (sv_derived_from(ST(0), "version")) { SV * const lobj = ST(0); if ( hv_exists(MUTABLE_HV(SvRV(lobj)), "qv", 2 ) ) XSRETURN_YES; else XSRETURN_NO; PUTBACK; return; } else Perl_croak(aTHX_ "lobj is not of type version"); } XS(XS_utf8_is_utf8) { dVAR; dXSARGS; if (items != 1) croak_xs_usage(cv, "sv"); else { const SV * const sv = ST(0); if (SvUTF8(sv)) XSRETURN_YES; else XSRETURN_NO; } XSRETURN_EMPTY; } XS(XS_utf8_valid) { dVAR; dXSARGS; if (items != 1) croak_xs_usage(cv, "sv"); else { SV * const sv = ST(0); STRLEN len; const char * const s = SvPV_const(sv,len); if (!SvUTF8(sv) || is_utf8_string((const U8*)s,len)) XSRETURN_YES; else XSRETURN_NO; } XSRETURN_EMPTY; } XS(XS_utf8_encode) { dVAR; dXSARGS; if (items != 1) croak_xs_usage(cv, "sv"); sv_utf8_encode(ST(0)); XSRETURN_EMPTY; } XS(XS_utf8_decode) { dVAR; dXSARGS; if (items != 1) croak_xs_usage(cv, "sv"); else { SV * const sv = ST(0); const bool RETVAL = sv_utf8_decode(sv); ST(0) = boolSV(RETVAL); sv_2mortal(ST(0)); } XSRETURN(1); } XS(XS_utf8_upgrade) { dVAR; dXSARGS; if (items != 1) croak_xs_usage(cv, "sv"); else { SV * const sv = ST(0); STRLEN RETVAL; dXSTARG; RETVAL = sv_utf8_upgrade(sv); XSprePUSH; PUSHi((IV)RETVAL); } XSRETURN(1); } XS(XS_utf8_downgrade) { dVAR; dXSARGS; if (items < 1 || items > 2) croak_xs_usage(cv, "sv, failok=0"); else { SV * const sv = ST(0); const bool failok = (items < 2) ? 0 : (int)SvIV(ST(1)); const bool RETVAL = sv_utf8_downgrade(sv, failok); ST(0) = boolSV(RETVAL); sv_2mortal(ST(0)); } XSRETURN(1); } XS(XS_utf8_native_to_unicode) { dVAR; dXSARGS; const UV uv = SvUV(ST(0)); if (items > 1) croak_xs_usage(cv, "sv"); ST(0) = sv_2mortal(newSViv(NATIVE_TO_UNI(uv))); XSRETURN(1); } XS(XS_utf8_unicode_to_native) { dVAR; dXSARGS; const UV uv = SvUV(ST(0)); if (items > 1) croak_xs_usage(cv, "sv"); ST(0) = sv_2mortal(newSViv(UNI_TO_NATIVE(uv))); XSRETURN(1); } XS(XS_Internals_SvREADONLY) /* This is dangerous stuff. */ { dVAR; dXSARGS; SV * const sv = SvRV(ST(0)); PERL_UNUSED_ARG(cv); if (items == 1) { if (SvREADONLY(sv)) XSRETURN_YES; else XSRETURN_NO; } else if (items == 2) { if (SvTRUE(ST(1))) { SvREADONLY_on(sv); XSRETURN_YES; } else { /* I hope you really know what you are doing. */ SvREADONLY_off(sv); XSRETURN_NO; } } XSRETURN_UNDEF; /* Can't happen. */ } XS(XS_Internals_SvREFCNT) /* This is dangerous stuff. */ { dVAR; dXSARGS; SV * const sv = SvRV(ST(0)); PERL_UNUSED_ARG(cv); if (items == 1) XSRETURN_IV(SvREFCNT(sv) - 1); /* Minus the ref created for us. */ else if (items == 2) { /* I hope you really know what you are doing. */ SvREFCNT(sv) = SvIV(ST(1)); XSRETURN_IV(SvREFCNT(sv)); } XSRETURN_UNDEF; /* Can't happen. */ } XS(XS_Internals_hv_clear_placehold) { dVAR; dXSARGS; if (items != 1) croak_xs_usage(cv, "hv"); else { HV * const hv = MUTABLE_HV(SvRV(ST(0))); hv_clear_placeholders(hv); XSRETURN(0); } } XS(XS_PerlIO_get_layers) { dVAR; dXSARGS; if (items < 1 || items % 2 == 0) croak_xs_usage(cv, "filehandle[,args]"); #ifdef USE_PERLIO { SV * sv; GV * gv; IO * io; bool input = TRUE; bool details = FALSE; if (items > 1) { SV * const *svp; for (svp = MARK + 2; svp <= SP; svp += 2) { SV * const * const varp = svp; SV * const * const valp = svp + 1; STRLEN klen; const char * const key = SvPV_const(*varp, klen); switch (*key) { case 'i': if (klen == 5 && memEQ(key, "input", 5)) { input = SvTRUE(*valp); break; } goto fail; case 'o': if (klen == 6 && memEQ(key, "output", 6)) { input = !SvTRUE(*valp); break; } goto fail; case 'd': if (klen == 7 && memEQ(key, "details", 7)) { details = SvTRUE(*valp); break; } goto fail; default: fail: Perl_croak(aTHX_ "get_layers: unknown argument '%s'", key); } } SP -= (items - 1); } sv = POPs; gv = MUTABLE_GV(sv); if (!isGV(sv)) { if (SvROK(sv) && isGV(SvRV(sv))) gv = MUTABLE_GV(SvRV(sv)); else if (SvPOKp(sv)) gv = gv_fetchsv(sv, 0, SVt_PVIO); } if (gv && (io = GvIO(gv))) { AV* const av = PerlIO_get_layers(aTHX_ input ? IoIFP(io) : IoOFP(io)); I32 i; const I32 last = av_len(av); I32 nitem = 0; for (i = last; i >= 0; i -= 3) { SV * const * const namsvp = av_fetch(av, i - 2, FALSE); SV * const * const argsvp = av_fetch(av, i - 1, FALSE); SV * const * const flgsvp = av_fetch(av, i, FALSE); const bool namok = namsvp && *namsvp && SvPOK(*namsvp); const bool argok = argsvp && *argsvp && SvPOK(*argsvp); const bool flgok = flgsvp && *flgsvp && SvIOK(*flgsvp); if (details) { /* Indents of 5? Yuck. */ /* We know that PerlIO_get_layers creates a new SV for the name and flags, so we can just take a reference and "steal" it when we free the AV below. */ XPUSHs(namok ? sv_2mortal(SvREFCNT_inc_simple_NN(*namsvp)) : &PL_sv_undef); XPUSHs(argok ? newSVpvn_flags(SvPVX_const(*argsvp), SvCUR(*argsvp), (SvUTF8(*argsvp) ? SVf_UTF8 : 0) | SVs_TEMP) : &PL_sv_undef); XPUSHs(flgok ? sv_2mortal(SvREFCNT_inc_simple_NN(*flgsvp)) : &PL_sv_undef); nitem += 3; } else { if (namok && argok) XPUSHs(sv_2mortal(Perl_newSVpvf(aTHX_ "%"SVf"(%"SVf")", SVfARG(*namsvp), SVfARG(*argsvp)))); else if (namok) XPUSHs(sv_2mortal(SvREFCNT_inc_simple_NN(*namsvp))); else XPUSHs(&PL_sv_undef); nitem++; if (flgok) { const IV flags = SvIVX(*flgsvp); if (flags & PERLIO_F_UTF8) { XPUSHs(newSVpvs_flags("utf8", SVs_TEMP)); nitem++; } } } } SvREFCNT_dec(av); XSRETURN(nitem); } } #endif XSRETURN(0); } XS(XS_Internals_hash_seed) { dVAR; /* Using dXSARGS would also have dITEM and dSP, * which define 2 unused local variables. */ dAXMARK; PERL_UNUSED_ARG(cv); PERL_UNUSED_VAR(mark); XSRETURN_UV(PERL_HASH_SEED); } XS(XS_Internals_rehash_seed) { dVAR; /* Using dXSARGS would also have dITEM and dSP, * which define 2 unused local variables. */ dAXMARK; PERL_UNUSED_ARG(cv); PERL_UNUSED_VAR(mark); XSRETURN_UV(PL_rehash_seed); } XS(XS_Internals_HvREHASH) /* Subject to change */ { dVAR; dXSARGS; PERL_UNUSED_ARG(cv); if (SvROK(ST(0))) { const HV * const hv = (const HV *) SvRV(ST(0)); if (items == 1 && SvTYPE(hv) == SVt_PVHV) { if (HvREHASH(hv)) XSRETURN_YES; else XSRETURN_NO; } } Perl_croak(aTHX_ "Internals::HvREHASH $hashref"); } XS(XS_re_is_regexp) { dVAR; dXSARGS; PERL_UNUSED_VAR(cv); if (items != 1) croak_xs_usage(cv, "sv"); SP -= items; if (SvRXOK(ST(0))) { XSRETURN_YES; } else { XSRETURN_NO; } } XS(XS_re_regnames_count) { REGEXP *rx = PL_curpm ? PM_GETRE(PL_curpm) : NULL; SV * ret; dVAR; dXSARGS; if (items != 0) croak_xs_usage(cv, ""); SP -= items; if (!rx) XSRETURN_UNDEF; ret = CALLREG_NAMED_BUFF_COUNT(rx); SPAGAIN; if (ret) { mXPUSHs(ret); PUTBACK; return; } else { XSRETURN_UNDEF; } } XS(XS_re_regname) { dVAR; dXSARGS; REGEXP * rx; U32 flags; SV * ret; if (items < 1 || items > 2) croak_xs_usage(cv, "name[, all ]"); SP -= items; rx = PL_curpm ? PM_GETRE(PL_curpm) : NULL; if (!rx) XSRETURN_UNDEF; if (items == 2 && SvTRUE(ST(1))) { flags = RXapif_ALL; } else { flags = RXapif_ONE; } ret = CALLREG_NAMED_BUFF_FETCH(rx, ST(0), (flags | RXapif_REGNAME)); if (ret) { mXPUSHs(ret); XSRETURN(1); } XSRETURN_UNDEF; } XS(XS_re_regnames) { dVAR; dXSARGS; REGEXP * rx; U32 flags; SV *ret; AV *av; I32 length; I32 i; SV **entry; if (items > 1) croak_xs_usage(cv, "[all]"); rx = PL_curpm ? PM_GETRE(PL_curpm) : NULL; if (!rx) XSRETURN_UNDEF; if (items == 1 && SvTRUE(ST(0))) { flags = RXapif_ALL; } else { flags = RXapif_ONE; } SP -= items; ret = CALLREG_NAMED_BUFF_ALL(rx, (flags | RXapif_REGNAMES)); SPAGAIN; SP -= items; if (!ret) XSRETURN_UNDEF; av = MUTABLE_AV(SvRV(ret)); length = av_len(av); for (i = 0; i <= length; i++) { entry = av_fetch(av, i, FALSE); if (!entry) Perl_croak(aTHX_ "NULL array element in re::regnames()"); mXPUSHs(SvREFCNT_inc_simple_NN(*entry)); } SvREFCNT_dec(ret); PUTBACK; return; } XS(XS_re_regexp_pattern) { dVAR; dXSARGS; REGEXP *re; if (items != 1) croak_xs_usage(cv, "sv"); SP -= items; /* Checks if a reference is a regex or not. If the parameter is not a ref, or is not the result of a qr// then returns false in scalar context and an empty list in list context. Otherwise in list context it returns the pattern and the modifiers, in scalar context it returns the pattern just as it would if the qr// was stringified normally, regardless as to the class of the variable and any strigification overloads on the object. */ if ((re = SvRX(ST(0)))) /* assign deliberate */ { /* Housten, we have a regex! */ SV *pattern; STRLEN left = 0; char reflags[6]; if ( GIMME_V == G_ARRAY ) { /* we are in list context so stringify the modifiers that apply. We ignore "negative modifiers" in this scenario. */ const char *fptr = INT_PAT_MODS; char ch; U16 match_flags = (U16)((RX_EXTFLAGS(re) & PMf_COMPILETIME) >> RXf_PMf_STD_PMMOD_SHIFT); while((ch = *fptr++)) { if(match_flags & 1) { reflags[left++] = ch; } match_flags >>= 1; } pattern = newSVpvn_flags(RX_PRECOMP(re),RX_PRELEN(re), (RX_UTF8(re) ? SVf_UTF8 : 0) | SVs_TEMP); /* return the pattern and the modifiers */ XPUSHs(pattern); XPUSHs(newSVpvn_flags(reflags, left, SVs_TEMP)); XSRETURN(2); } else { /* Scalar, so use the string that Perl would return */ /* return the pattern in (?msix:..) format */ #if PERL_VERSION >= 11 pattern = sv_2mortal(newSVsv(MUTABLE_SV(re))); #else pattern = newSVpvn_flags(RX_WRAPPED(re), RX_WRAPLEN(re), (RX_UTF8(re) ? SVf_UTF8 : 0) | SVs_TEMP); #endif XPUSHs(pattern); XSRETURN(1); } } else { /* It ain't a regexp folks */ if ( GIMME_V == G_ARRAY ) { /* return the empty list */ XSRETURN_UNDEF; } else { /* Because of the (?:..) wrapping involved in a stringified pattern it is impossible to get a result for a real regexp that would evaluate to false. Therefore we can return PL_sv_no to signify that the object is not a regex, this means that one can say if (regex($might_be_a_regex) eq '(?:foo)') { } and not worry about undefined values. */ XSRETURN_NO; } } /* NOT-REACHED */ } XS(XS_Tie_Hash_NamedCapture_FETCH) { dVAR; dXSARGS; REGEXP * rx; U32 flags; SV * ret; if (items != 2) croak_xs_usage(cv, "$key, $flags"); rx = PL_curpm ? PM_GETRE(PL_curpm) : NULL; if (!rx) XSRETURN_UNDEF; SP -= items; flags = (U32)INT2PTR(IV,SvIV(SvRV(MUTABLE_SV(ST(0))))); ret = CALLREG_NAMED_BUFF_FETCH(rx, ST(1), flags); SPAGAIN; if (ret) { mXPUSHs(ret); PUTBACK; return; } XSRETURN_UNDEF; } XS(XS_Tie_Hash_NamedCapture_STORE) { dVAR; dXSARGS; REGEXP * rx; U32 flags; if (items != 3) croak_xs_usage(cv, "$key, $value, $flags"); rx = PL_curpm ? PM_GETRE(PL_curpm) : NULL; if (!rx) { if (!PL_localizing) Perl_croak(aTHX_ "%s", PL_no_modify); else XSRETURN_UNDEF; } SP -= items; flags = (U32)INT2PTR(IV,SvIV(SvRV(MUTABLE_SV(ST(0))))); CALLREG_NAMED_BUFF_STORE(rx,ST(1), ST(2), flags); } XS(XS_Tie_Hash_NamedCapture_DELETE) { dVAR; dXSARGS; REGEXP * rx = PL_curpm ? PM_GETRE(PL_curpm) : NULL; U32 flags; if (items != 2) croak_xs_usage(cv, "$key, $flags"); if (!rx) Perl_croak(aTHX_ "%s", PL_no_modify); SP -= items; flags = (U32)INT2PTR(IV,SvIV(SvRV(MUTABLE_SV(ST(0))))); CALLREG_NAMED_BUFF_DELETE(rx, ST(1), flags); } XS(XS_Tie_Hash_NamedCapture_CLEAR) { dVAR; dXSARGS; REGEXP * rx; U32 flags; if (items != 1) croak_xs_usage(cv, "$flags"); rx = PL_curpm ? PM_GETRE(PL_curpm) : NULL; if (!rx) Perl_croak(aTHX_ "%s", PL_no_modify); SP -= items; flags = (U32)INT2PTR(IV,SvIV(SvRV(MUTABLE_SV(ST(0))))); CALLREG_NAMED_BUFF_CLEAR(rx, flags); } XS(XS_Tie_Hash_NamedCapture_EXISTS) { dVAR; dXSARGS; REGEXP * rx; U32 flags; SV * ret; if (items != 2) croak_xs_usage(cv, "$key, $flags"); rx = PL_curpm ? PM_GETRE(PL_curpm) : NULL; if (!rx) XSRETURN_UNDEF; SP -= items; flags = (U32)INT2PTR(IV,SvIV(SvRV(MUTABLE_SV(ST(0))))); ret = CALLREG_NAMED_BUFF_EXISTS(rx, ST(1), flags); SPAGAIN; XPUSHs(ret); PUTBACK; return; } XS(XS_Tie_Hash_NamedCapture_FIRSTK) { dVAR; dXSARGS; REGEXP * rx; U32 flags; SV * ret; if (items != 1) croak_xs_usage(cv, ""); rx = PL_curpm ? PM_GETRE(PL_curpm) : NULL; if (!rx) XSRETURN_UNDEF; SP -= items; flags = (U32)INT2PTR(IV,SvIV(SvRV(MUTABLE_SV(ST(0))))); ret = CALLREG_NAMED_BUFF_FIRSTKEY(rx, flags); SPAGAIN; if (ret) { mXPUSHs(ret); PUTBACK; } else { XSRETURN_UNDEF; } } XS(XS_Tie_Hash_NamedCapture_NEXTK) { dVAR; dXSARGS; REGEXP * rx; U32 flags; SV * ret; if (items != 2) croak_xs_usage(cv, "$lastkey"); rx = PL_curpm ? PM_GETRE(PL_curpm) : NULL; if (!rx) XSRETURN_UNDEF; SP -= items; flags = (U32)INT2PTR(IV,SvIV(SvRV(MUTABLE_SV(ST(0))))); ret = CALLREG_NAMED_BUFF_NEXTKEY(rx, ST(1), flags); SPAGAIN; if (ret) { mXPUSHs(ret); } else { XSRETURN_UNDEF; } PUTBACK; } XS(XS_Tie_Hash_NamedCapture_SCALAR) { dVAR; dXSARGS; REGEXP * rx; U32 flags; SV * ret; if (items != 1) croak_xs_usage(cv, ""); rx = PL_curpm ? PM_GETRE(PL_curpm) : NULL; if (!rx) XSRETURN_UNDEF; SP -= items; flags = (U32)INT2PTR(IV,SvIV(SvRV(MUTABLE_SV(ST(0))))); ret = CALLREG_NAMED_BUFF_SCALAR(rx, flags); SPAGAIN; if (ret) { mXPUSHs(ret); PUTBACK; return; } else { XSRETURN_UNDEF; } } XS(XS_Tie_Hash_NamedCapture_flags) { dVAR; dXSARGS; if (items != 0) croak_xs_usage(cv, ""); mXPUSHu(RXapif_ONE); mXPUSHu(RXapif_ALL); PUTBACK; return; } /* * Local variables: * c-indentation-style: bsd * c-basic-offset: 4 * indent-tabs-mode: t * End: * * ex: set ts=8 sts=4 sw=4 noet: */
18,310
17,242
<filename>mediapipe/framework/stream_handler/fixed_size_input_stream_handler.cc // Copyright 2019 The MediaPipe Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <memory> #include <vector> #include "mediapipe/framework/stream_handler/default_input_stream_handler.h" // TODO: Move protos in another CL after the C++ code migration. #include "mediapipe/framework/stream_handler/fixed_size_input_stream_handler.pb.h" namespace mediapipe { // Input stream handler that limits each input queue to a maximum of // target_queue_size packets, discarding older packets as needed. When a // timestamp is dropped from a stream, it is dropped from all others as well. // // For example, a calculator node with one input stream and the following input // stream handler specs: // // node { // calculator: "CalculatorRunningAtOneFps" // input_stream: "packets_streaming_in_at_ten_fps" // input_stream_handler { // input_stream_handler: "FixedSizeInputStreamHandler" // } // } // // will always try to keep the newest packet in the input stream. // // A few details: FixedSizeInputStreamHandler takes action when any stream grows // to trigger_queue_size or larger. It then keeps at most target_queue_size // packets in every InputStreamImpl. Every stream is truncated at the same // timestamp, so that each included timestamp delivers the same packets as // DefaultInputStreamHandler includes. // class FixedSizeInputStreamHandler : public DefaultInputStreamHandler { public: FixedSizeInputStreamHandler() = delete; FixedSizeInputStreamHandler(std::shared_ptr<tool::TagMap> tag_map, CalculatorContextManager* cc_manager, const MediaPipeOptions& options, bool calculator_run_in_parallel) : DefaultInputStreamHandler(std::move(tag_map), cc_manager, options, calculator_run_in_parallel) { const auto& ext = options.GetExtension(FixedSizeInputStreamHandlerOptions::ext); trigger_queue_size_ = ext.trigger_queue_size(); target_queue_size_ = ext.target_queue_size(); fixed_min_size_ = ext.fixed_min_size(); pending_ = false; kept_timestamp_ = Timestamp::Unset(); // TODO: Either re-enable SetLatePreparation(true) with // CalculatorContext::InputTimestamp set correctly, or remove the // implementation of SetLatePreparation. } private: // Drops packets if all input streams exceed trigger_queue_size. void EraseAllSurplus() ABSL_EXCLUSIVE_LOCKS_REQUIRED(erase_mutex_) { Timestamp min_timestamp_all_streams = Timestamp::Max(); for (const auto& stream : input_stream_managers_) { // Check whether every InputStreamImpl grew beyond trigger_queue_size. if (stream->QueueSize() < trigger_queue_size_) { return; } Timestamp min_timestamp = stream->GetMinTimestampAmongNLatest(target_queue_size_); // Record the min timestamp among the newest target_queue_size_ packets // across all InputStreamImpls. min_timestamp_all_streams = std::min(min_timestamp_all_streams, min_timestamp); } for (auto& stream : input_stream_managers_) { stream->ErasePacketsEarlierThan(min_timestamp_all_streams); } } // Returns the latest timestamp allowed before a bound. Timestamp PreviousAllowedInStream(Timestamp bound) { return bound.IsRangeValue() ? bound - 1 : bound; } // Returns the lowest timestamp at which a packet may arrive at any stream. Timestamp MinStreamBound() { Timestamp min_bound = Timestamp::Done(); for (const auto& stream : input_stream_managers_) { Timestamp stream_bound = stream->GetMinTimestampAmongNLatest(1); if (stream_bound > Timestamp::Unset()) { stream_bound = stream_bound.NextAllowedInStream(); } else { stream_bound = stream->MinTimestampOrBound(nullptr); } min_bound = std::min(min_bound, stream_bound); } return min_bound; } // Returns the lowest timestamp of a packet ready to process. Timestamp MinTimestampToProcess() { Timestamp min_bound = Timestamp::Done(); for (const auto& stream : input_stream_managers_) { bool empty; Timestamp stream_timestamp = stream->MinTimestampOrBound(&empty); // If we're using the stream's *bound*, we only want to process up to the // packet *before* the bound, because a packet may still arrive at that // time. if (empty) { stream_timestamp = PreviousAllowedInStream(stream_timestamp); } min_bound = std::min(min_bound, stream_timestamp); } return min_bound; } // Keeps only the most recent target_queue_size packets in each stream // exceeding trigger_queue_size. Also, discards all packets older than the // first kept timestamp on any stream. void EraseAnySurplus(bool keep_one) ABSL_EXCLUSIVE_LOCKS_REQUIRED(erase_mutex_) { // Record the most recent first kept timestamp on any stream. for (const auto& stream : input_stream_managers_) { int32 queue_size = (stream->QueueSize() >= trigger_queue_size_) ? target_queue_size_ : trigger_queue_size_ - 1; if (stream->QueueSize() > queue_size) { kept_timestamp_ = std::max( kept_timestamp_, stream->GetMinTimestampAmongNLatest(queue_size + 1) .NextAllowedInStream()); } } if (keep_one) { // In order to preserve one viable timestamp, do not truncate past // the timestamp bound of the least current stream. kept_timestamp_ = std::min(kept_timestamp_, PreviousAllowedInStream(MinStreamBound())); } for (auto& stream : input_stream_managers_) { stream->ErasePacketsEarlierThan(kept_timestamp_); } } void EraseSurplusPackets(bool keep_one) ABSL_EXCLUSIVE_LOCKS_REQUIRED(erase_mutex_) { return (fixed_min_size_) ? EraseAllSurplus() : EraseAnySurplus(keep_one); } NodeReadiness GetNodeReadiness(Timestamp* min_stream_timestamp) override { DCHECK(min_stream_timestamp); absl::MutexLock lock(&erase_mutex_); // kReadyForProcess is returned only once until FillInputSet completes. // In late_preparation mode, GetNodeReadiness must return kReadyForProcess // exactly once for each input-set produced. Here, GetNodeReadiness // releases just one input-set at a time and then disables input queue // truncation until that promised input-set is consumed. if (pending_) { return NodeReadiness::kNotReady; } EraseSurplusPackets(false); NodeReadiness result = DefaultInputStreamHandler::GetNodeReadiness(min_stream_timestamp); // If a packet has arrived below kept_timestamp_, recalculate. while (*min_stream_timestamp < kept_timestamp_ && result == NodeReadiness::kReadyForProcess) { EraseSurplusPackets(false); result = DefaultInputStreamHandler::GetNodeReadiness(min_stream_timestamp); } pending_ = (result == NodeReadiness::kReadyForProcess); return result; } void AddPackets(CollectionItemId id, const std::list<Packet>& packets) override { InputStreamHandler::AddPackets(id, packets); absl::MutexLock lock(&erase_mutex_); if (!pending_) { EraseSurplusPackets(false); } } void MovePackets(CollectionItemId id, std::list<Packet>* packets) override { InputStreamHandler::MovePackets(id, packets); absl::MutexLock lock(&erase_mutex_); if (!pending_) { EraseSurplusPackets(false); } } void FillInputSet(Timestamp input_timestamp, InputStreamShardSet* input_set) override { CHECK(input_set); absl::MutexLock lock(&erase_mutex_); if (!pending_) { LOG(ERROR) << "FillInputSet called without GetNodeReadiness."; } // input_timestamp is recalculated here to process the most recent packets. EraseSurplusPackets(true); input_timestamp = MinTimestampToProcess(); DefaultInputStreamHandler::FillInputSet(input_timestamp, input_set); pending_ = false; } private: int32 trigger_queue_size_; int32 target_queue_size_; bool fixed_min_size_; // Indicates that GetNodeReadiness has returned kReadyForProcess once, and // the corresponding call to FillInputSet has not yet completed. bool pending_ ABSL_GUARDED_BY(erase_mutex_); // The timestamp used to truncate all input streams. Timestamp kept_timestamp_ ABSL_GUARDED_BY(erase_mutex_); absl::Mutex erase_mutex_; }; REGISTER_INPUT_STREAM_HANDLER(FixedSizeInputStreamHandler); } // namespace mediapipe
3,269