max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
3,428
<gh_stars>1000+ {"id":"00342","group":"spam-1","checksum":{"type":"MD5","value":"0dab365fab3be83284b08ac5783335da"},"text":"From <EMAIL> Tue Sep 17 11:28:48 2002\nReturn-Path: <<EMAIL>>\nDelivered-To: zzzz<EMAIL>.spamassassin.taint.org\nReceived: from localhost (jalapeno [1192.168.3.11])\n\tby zzzzason.org (Postfix) with ESMTP id BB90F16F03\n\tfor <zzzz@localhost>; Tue, 17 Sep 2002 11:28:47 +0100 (IST)\nReceived: from jalapeno [127.0.0.1]\n\tby localhost with IMAP (fetchmail-5.9.0)\n\tfor zzzz@localhost (single-drop); Tue, 17 Sep 2002 11:28:47 +0100 (IST)\nReceived: from lugh.tuatha.org (<EMAIL> [172.16.58.35]) by\n dogma.slashnull.org (8.11.6/8.11.6) with ESMTP id g8GNjBC14706 for\n <<EMAIL>>; Tue, 17 Sep 2002 00:45:11 +0100\nReceived: from lugh (root@localhost [127.0.0.1]) by lugh.tuatha.org\n (8.9.3/8.9.3) with ESMTP id AAA20824; Tue, 17 Sep 2002 00:44:29 +0100\nX-Authentication-Warning: lugh.tuatha.org: Host root@localhost [127.0.0.1]\n claimed to be lugh\nReceived: from server759.instantinternetempires.net\n (server759.instantinternetempires.net [216.10.23.30]) by lugh.tuatha.org\n (8.9.3/8.9.3) with ESMTP id AAA20786 for <<EMAIL>>; Tue,\n 17 Sep 2002 00:44:20 +0100\nReceived: from nobody by server759.instantinternetempires.net with local\n (Exim 3.36 #1) id 17r5X6-0003dr-00 for <EMAIL>; Mon, 16 Sep 2002\n 19:44:00 -0400\nTo: <EMAIL>\nFrom: <EMAIL>.net\nContent-Type: text/plain; charset=us-ascii\nX-Header: Reply-To: [email protected]\nX-Loop-Prevention: 1\nMessage-Id: <<EMAIL>>\nDate: Mon, 16 Sep 2002 19:44:00 -0400\nX-Antiabuse: This header was added to track abuse, please include it with\n any abuse report\nX-Antiabuse: Primary Hostname - server759.instantinternetempires.net\nX-Antiabuse: Original Domain - linux.ie\nX-Antiabuse: Originator/Caller UID/GID - [99 99] / [99 99]\nX-Antiabuse: Sender Address Domain - server759.instantinternetempires.net\nSubject: [ILUG] Here is the information you requested\nSender: <EMAIL>\nErrors-To: [email protected]\nX-Mailman-Version: 1.1\nPrecedence: bulk\nList-Id: Irish Linux Users' Group <ilug.linux.ie>\nX-Beenthere: [email protected]\n\nAre you interested in making some extra money on the internet?\nwell have i got something for you. Last week i made $3500 ,I am offering you 5 yes 5 web sites that have already been made and are waiting for you to put up to make money with. There is also a few videos that are included that tell you Exactly what you have to do to be successful. I am going to also Offer you the rights to the web pages and to 5 Ebooks that you can sell.. These Ebooks aren't just any Ebooks these are books on how to make money on the internet. I am selling this package deal for a short time only at the low price of $39.77 my friends all say that i am Crazy.. The web site alone is worth over $1500 and its yours for only $39.77. Each eBook you will receive is worth around $350. my web page is. www.Home-Business-onthe-net.com . please come take a look. \nif you have any questions please feel free to give me a email.\nif you'd like a Free Ebook just give me a email and ill email you one ASAP.\n\nSincerly \nYour friend\nKeegan\n\nClick on the link below to remove yourself\nhttp://www.hotresponders.com/cgi-bin/varpro/r.cgi?id=keegan007&[email protected]\n\nAOL Users\n<a href=\"http://www.hotresponders.com/cgi-bin/varpro/r.cgi?id=keegan007&a=<EMAIL>\"> Remove Me</a>\n\n-- \nIrish Linux Users' Group: <EMAIL>\nhttp://www.linux.ie/mailman/listinfo/ilug for (un)subscription information.\nList maintainer: <EMAIL>\n\n\n"}
1,328
723
<reponame>Acidburn0zzz/LiveReload #import <AppKit/AppKit.h> @interface NodeAppWindow : NSWindow @end @interface NSObject (NodeAppWindowDelegate) - (void)window:(NSWindow *)window didChangeFirstResponder:(NSResponder *)responder; @end
84
545
/* * Copyright © 2017-2018 <NAME> * * This file is part of "apulse" 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. */ #include "apulse.h" #include "trace.h" #include <pulse/ext-device-manager.h> #include <pulse/ext-device-restore.h> #include <pulse/ext-stream-restore.h> APULSE_EXPORT pa_operation * pa_ext_device_manager_test(pa_context *c, pa_ext_device_manager_test_cb_t cb, void *userdata) { trace_info_z("Z %s\n", __func__); return NULL; } APULSE_EXPORT pa_operation * pa_ext_device_manager_read(pa_context *c, pa_ext_device_manager_read_cb_t cb, void *userdata) { trace_info_z("Z %s\n", __func__); return NULL; } APULSE_EXPORT pa_operation * pa_ext_device_manager_set_device_description(pa_context *c, const char *device, const char *description, pa_context_success_cb_t cb, void *userdata) { trace_info_z("Z %s\n", __func__); return NULL; } APULSE_EXPORT pa_operation * pa_ext_device_manager_delete(pa_context *c, const char *const s[], pa_context_success_cb_t cb, void *userdata) { trace_info_z("Z %s\n", __func__); return NULL; } APULSE_EXPORT pa_operation * pa_ext_device_manager_enable_role_device_priority_routing( pa_context *c, int enable, pa_context_success_cb_t cb, void *userdata) { trace_info_z("Z %s\n", __func__); return NULL; } APULSE_EXPORT pa_operation * pa_ext_device_manager_reorder_devices_for_role(pa_context *c, const char *role, const char **devices, pa_context_success_cb_t cb, void *userdata) { trace_info_z("Z %s\n", __func__); return NULL; } APULSE_EXPORT pa_operation * pa_ext_device_manager_subscribe(pa_context *c, int enable, pa_context_success_cb_t cb, void *userdata) { trace_info_z("Z %s\n", __func__); return NULL; } APULSE_EXPORT void pa_ext_device_manager_set_subscribe_cb(pa_context *c, pa_ext_device_manager_subscribe_cb_t cb, void *userdata) { trace_info_z("Z %s\n", __func__); } APULSE_EXPORT pa_operation * pa_ext_device_restore_test(pa_context *c, pa_ext_device_restore_test_cb_t cb, void *userdata) { trace_info_z("Z %s\n", __func__); return NULL; } APULSE_EXPORT pa_operation * pa_ext_device_restore_subscribe(pa_context *c, int enable, pa_context_success_cb_t cb, void *userdata) { trace_info_z("Z %s\n", __func__); return NULL; } APULSE_EXPORT void pa_ext_device_restore_set_subscribe_cb(pa_context *c, pa_ext_device_restore_subscribe_cb_t cb, void *userdata) { trace_info_z("Z %s\n", __func__); } APULSE_EXPORT pa_operation * pa_ext_device_restore_read_formats_all( pa_context *c, pa_ext_device_restore_read_device_formats_cb_t cb, void *userdata) { trace_info_z("Z %s\n", __func__); return NULL; } APULSE_EXPORT pa_operation * pa_ext_device_restore_read_formats( pa_context *c, pa_device_type_t type, uint32_t idx, pa_ext_device_restore_read_device_formats_cb_t cb, void *userdata) { trace_info_z("Z %s\n", __func__); return NULL; } APULSE_EXPORT pa_operation * pa_ext_device_restore_save_formats(pa_context *c, pa_device_type_t type, uint32_t idx, uint8_t n_formats, pa_format_info **formats, pa_context_success_cb_t cb, void *userdata) { trace_info_z("Z %s\n", __func__); return NULL; } APULSE_EXPORT pa_operation * pa_ext_stream_restore_test(pa_context *c, pa_ext_stream_restore_test_cb_t cb, void *userdata) { trace_info_z("Z %s\n", __func__); return NULL; } APULSE_EXPORT pa_operation * pa_ext_stream_restore_read(pa_context *c, pa_ext_stream_restore_read_cb_t cb, void *userdata) { trace_info_z("Z %s\n", __func__); return NULL; } APULSE_EXPORT pa_operation * pa_ext_stream_restore_write(pa_context *c, pa_update_mode_t mode, const pa_ext_stream_restore_info data[], unsigned n, int apply_immediately, pa_context_success_cb_t cb, void *userdata) { trace_info_z("Z %s\n", __func__); return NULL; } APULSE_EXPORT pa_operation * pa_ext_stream_restore_delete(pa_context *c, const char *const s[], pa_context_success_cb_t cb, void *userdata); APULSE_EXPORT pa_operation * pa_ext_stream_restore_subscribe(pa_context *c, int enable, pa_context_success_cb_t cb, void *userdata) { trace_info_z("Z %s\n", __func__); return NULL; } APULSE_EXPORT void pa_ext_stream_restore_set_subscribe_cb(pa_context *c, pa_ext_stream_restore_subscribe_cb_t cb, void *userdata) { trace_info_z("Z %s\n", __func__); }
3,123
14,668
<filename>chrome/credential_provider/gaiacp/auth_utils.h // 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_CREDENTIAL_PROVIDER_GAIACP_AUTH_UTILS_H_ #define CHROME_CREDENTIAL_PROVIDER_GAIACP_AUTH_UTILS_H_ #include <string> #include "chrome/credential_provider/gaiacp/stdafx.h" namespace credential_provider { // Gets the auth package id for NEGOSSP_NAME_A. HRESULT GetAuthenticationPackageId(ULONG* id); HRESULT DetermineUserSidFromAuthenticationBuffer( const CREDENTIAL_PROVIDER_CREDENTIAL_SERIALIZATION* cpcs, std::wstring* sid); HRESULT BuildCredPackAuthenticationBuffer( BSTR domain, BSTR username, BSTR password, CREDENTIAL_PROVIDER_USAGE_SCENARIO cpus, CREDENTIAL_PROVIDER_CREDENTIAL_SERIALIZATION* cpcs); } // namespace credential_provider #endif // CHROME_CREDENTIAL_PROVIDER_GAIACP_AUTH_UTILS_H_
368
841
package org.jboss.resteasy.core.interception.jaxrs; import java.io.IOException; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.concurrent.CompletionException; import java.util.concurrent.CompletionStage; import java.util.function.Consumer; import java.util.function.Supplier; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.MultivaluedMap; import jakarta.ws.rs.ext.MessageBodyWriter; import jakarta.ws.rs.ext.WriterInterceptor; import org.jboss.resteasy.core.NoMessageBodyWriterFoundFailure; import org.jboss.resteasy.core.providerfactory.ResteasyProviderFactoryImpl; import org.jboss.resteasy.spi.AsyncMessageBodyWriter; import org.jboss.resteasy.spi.AsyncOutputStream; import org.jboss.resteasy.spi.HttpRequest; import org.jboss.resteasy.spi.ResteasyProviderFactory; import org.jboss.resteasy.tracing.RESTEasyTracingLogger; /** * @author <a href="mailto:<EMAIL>"><NAME></a> * @version $Revision: 1 $ */ @SuppressWarnings("rawtypes") public class ServerWriterInterceptorContext extends AbstractWriterInterceptorContext { private HttpRequest request; private Consumer<Throwable> onWriteComplete; public ServerWriterInterceptorContext(final WriterInterceptor[] interceptors, final ResteasyProviderFactory providerFactory, final Object entity, final Class type, final Type genericType, final Annotation[] annotations, final MediaType mediaType, final MultivaluedMap<String, Object> headers, final OutputStream outputStream, final HttpRequest request, final Consumer<Throwable> onWriteComplete) { // server side must use request instead of provider factory to get tracing logger. super(interceptors, annotations, entity, genericType, mediaType, type, outputStream, providerFactory, headers, RESTEasyTracingLogger.getInstance(request)); this.request = request; this.onWriteComplete = onWriteComplete; } @SuppressWarnings(value = "unchecked") @Override protected MessageBodyWriter resolveWriter() { return ((ResteasyProviderFactoryImpl)providerFactory).getServerMessageBodyWriter( type, genericType, annotations, mediaType, tracingLogger); } @Override void throwWriterNotFoundException() { throw new NoMessageBodyWriterFoundFailure(type, mediaType); } @Override public Object getProperty(String name) { return request.getAttribute(name); } @Override public CompletionStage<Void> getStarted() { return aroundWriteTo(() -> super.getStarted()); } @SuppressWarnings(value = "unchecked") protected CompletionStage<Void> writeTo(MessageBodyWriter writer) throws IOException { return request.getAsyncContext().executeBlockingIo(() -> writer.writeTo(entity, type, genericType, annotations, mediaType, headers, outputStream), interceptors != null && interceptors.length > 0); } @SuppressWarnings(value = "unchecked") protected CompletionStage<Void> writeTo(AsyncMessageBodyWriter writer) { return request.getAsyncContext().executeAsyncIo( writer.asyncWriteTo(entity, type, genericType, annotations, mediaType, headers, (AsyncOutputStream)outputStream)); } private CompletionStage<Void> aroundWriteTo(Supplier<CompletionStage<Void>> ret) { boolean startedSuspended = request.getAsyncContext().isSuspended(); return ret.get().whenComplete((v, t) -> { // make sure we unwrap these horrors if(t instanceof CompletionException) t = t.getCause(); onWriteComplete.accept(t); // make sure we complete any async request after we've written the body or exception if(!startedSuspended && request.getAsyncContext().isSuspended()) { request.getAsyncContext().complete(); } }); } @Override public Collection<String> getPropertyNames() { ArrayList<String> names = new ArrayList<String>(); Enumeration<String> enames = request.getAttributeNames(); while (enames.hasMoreElements()) { names.add(enames.nextElement()); } return names; } @Override public void setProperty(String name, Object object) { if (object == null) { request.removeAttribute(name); } else { request.setAttribute(name, object); } } @Override public void removeProperty(String name) { request.removeAttribute(name); } }
1,856
575
// 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 COMPONENTS_LEVELDB_PROTO_INTERNAL_SHARED_PROTO_DATABASE_H_ #define COMPONENTS_LEVELDB_PROTO_INTERNAL_SHARED_PROTO_DATABASE_H_ #include <memory> #include <string> #include "base/bind.h" #include "base/callback_helpers.h" #include "base/cancelable_callback.h" #include "base/component_export.h" #include "base/containers/queue.h" #include "base/memory/ref_counted.h" #include "base/sequence_checker.h" #include "components/leveldb_proto/internal/proto/shared_db_metadata.pb.h" #include "components/leveldb_proto/internal/shared_proto_database_client.h" #include "components/leveldb_proto/public/proto_database.h" namespace leveldb_proto { // Controls a single LevelDB database to be used by many clients, and provides // a way to get SharedProtoDatabaseClients that allow shared access to the // underlying single database. class COMPONENT_EXPORT(LEVELDB_PROTO) SharedProtoDatabase : public base::RefCountedThreadSafe<SharedProtoDatabase> { public: using SharedClientInitCallback = base::OnceCallback<void(Enums::InitStatus, SharedDBMetadataProto::MigrationStatus)>; // Always returns a SharedProtoDatabaseClient pointer, but that should ONLY // be used if the callback returns success. std::unique_ptr<SharedProtoDatabaseClient> GetClientForTesting( ProtoDbType db_type, bool create_if_missing, SharedClientInitCallback callback); // A version of GetClient that returns the client in a callback instead of // giving back a client instance immediately. void GetClientAsync( ProtoDbType db_type, bool create_if_missing, base::OnceCallback<void(std::unique_ptr<SharedProtoDatabaseClient>, Enums::InitStatus)> callback); void GetDatabaseInitStatusAsync(const std::string& client_db_id, Callbacks::InitStatusCallback callback); void UpdateClientMetadataAsync( const std::string& client_db_id, SharedDBMetadataProto::MigrationStatus migration_status, Callbacks::UpdateCallback callback); protected: SharedProtoDatabase(const std::string& client_db_id, const base::FilePath& db_dir); virtual ~SharedProtoDatabase(); private: friend class base::RefCountedThreadSafe<SharedProtoDatabase>; friend class ProtoDatabaseProvider; template <typename T> friend class ProtoDatabaseImplTest; friend class SharedProtoDatabaseTest; friend class SharedProtoDatabaseClientTest; friend class TestSharedProtoDatabase; friend class TestSharedProtoDatabaseClient; FRIEND_TEST_ALL_PREFIXES(SharedProtoDatabaseTest, CancelDeleteObsoleteClients); FRIEND_TEST_ALL_PREFIXES(SharedProtoDatabaseTest, DeleteObsoleteClients); enum InitState { // Initialization hasn't been attempted. kNotAttempted, // Initialization is in progress, new requests will be enqueued. kInProgress, // Initialization successful, new requests will return existing DB. kSuccess, // Initialization failed, new requests will return InitStatus::kError. kFailure, // Shared database doesn't exist, new requests with create_if_missing == // true will attempt to create it, if create_if_missing == false then will // return InitStatus::kInvalidOperation. kNotFound, }; struct InitRequest { InitRequest(SharedClientInitCallback callback, const scoped_refptr<base::SequencedTaskRunner>& task_runner, const std::string& client_db_id); ~InitRequest(); SharedClientInitCallback callback; scoped_refptr<base::SequencedTaskRunner> task_runner; std::string client_db_id; }; // Make sure to give enough time after startup so that we have less chance of // affecting startup or navigations. static const base::TimeDelta kDelayToClearObsoleteDatabase; void Shutdown(); void ProcessInitRequests(Enums::InitStatus status); std::unique_ptr<SharedProtoDatabaseClient> GetClientInternal( ProtoDbType db_type); void OnGetClientMetadata( const std::string& client_db_id, SharedClientInitCallback callback, scoped_refptr<base::SequencedTaskRunner> callback_task_runner, bool success, std::unique_ptr<SharedDBMetadataProto> proto); // |callback_task_runner| should be the same sequence that Init was called // from. virtual void Init( bool create_if_missing, const std::string& client_db_id, SharedClientInitCallback callback, scoped_refptr<base::SequencedTaskRunner> callback_task_runner); void InitMetadataDatabase(int attempt, bool corruption); void OnMetadataInitComplete(int attempt, bool corruption, leveldb_proto::Enums::InitStatus status); void OnGetGlobalMetadata(bool corruption, bool success, std::unique_ptr<SharedDBMetadataProto> proto); void OnFinishCorruptionCountWrite(bool success); void InitDatabase(); void OnDatabaseInit(bool create_if_missing, Enums::InitStatus status); void CheckCorruptionAndRunInitCallback( const std::string& client_db_id, SharedClientInitCallback callback, scoped_refptr<base::SequencedTaskRunner> callback_task_runner, Enums::InitStatus status); void GetClientMetadataAsync( const std::string& client_db_id, SharedClientInitCallback callback, scoped_refptr<base::SequencedTaskRunner> callback_task_runner); void OnUpdateCorruptionCountAtInit(bool success); void CommitUpdatedGlobalMetadata(Callbacks::UpdateCallback callback); void RunInitCallback( Callbacks::InitStatusCallback callback, scoped_refptr<base::SequencedTaskRunner> callback_task_runner); // |done| will be called on |task_runner|. virtual void DestroyObsoleteSharedProtoDatabaseClients( Callbacks::UpdateCallback done); LevelDB* GetLevelDBForTesting() const; void set_delete_obsolete_delay_for_testing(base::TimeDelta delay) { delete_obsolete_delay_ = delay; } scoped_refptr<base::SequencedTaskRunner> database_task_runner_for_testing() const { return task_runner_; } SEQUENCE_CHECKER(on_task_runner_); InitState init_state_ = InitState::kNotAttempted; // This TaskRunner is used to properly sequence Init calls and checks for the // current init state. When clients request the current InitState as part of // their call to their Init function, the request is put into this TaskRunner. scoped_refptr<base::SequencedTaskRunner> task_runner_; base::FilePath db_dir_; std::unique_ptr<LevelDB> db_; std::unique_ptr<ProtoLevelDBWrapper> db_wrapper_; std::unique_ptr<ProtoDatabase<SharedDBMetadataProto>> metadata_db_wrapper_; std::unique_ptr<SharedDBMetadataProto> metadata_; // Used to return to the Init callback in the case of an error, so we can // report corruptions. Enums::InitStatus init_status_ = Enums::InitStatus::kNotInitialized; base::queue<std::unique_ptr<InitRequest>> outstanding_init_requests_; bool create_if_missing_ = false; base::TimeDelta delete_obsolete_delay_ = base::TimeDelta::FromSeconds(120); base::CancelableOnceClosure delete_obsolete_task_; DISALLOW_COPY_AND_ASSIGN(SharedProtoDatabase); }; } // namespace leveldb_proto #endif // COMPONENTS_LEVELDB_PROTO_INTERNAL_SHARED_PROTO_DATABASE_H_
2,606
2,151
/* * Copyright (C) 2010 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef THIRD_PARTY_BLINK_RENDERER_CONTROLLER_DEV_TOOLS_FRONTEND_IMPL_H_ #define THIRD_PARTY_BLINK_RENDERER_CONTROLLER_DEV_TOOLS_FRONTEND_IMPL_H_ #include "base/macros.h" #include "mojo/public/cpp/bindings/associated_binding.h" #include "third_party/blink/public/web/devtools_frontend.mojom-blink.h" #include "third_party/blink/renderer/core/inspector/inspector_frontend_client.h" #include "third_party/blink/renderer/platform/heap/handle.h" #include "third_party/blink/renderer/platform/supplementable.h" #include "third_party/blink/renderer/platform/wtf/hash_map.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" namespace blink { class DevToolsHost; class LocalFrame; // This class lives as long as a frame (being a supplement), or until // it's host (mojom.DevToolsFrontendHost) is destroyed. class DevToolsFrontendImpl final : public GarbageCollectedFinalized<DevToolsFrontendImpl>, public Supplement<LocalFrame>, public mojom::blink::DevToolsFrontend, public InspectorFrontendClient { USING_GARBAGE_COLLECTED_MIXIN(DevToolsFrontendImpl); public: static const char kSupplementName[]; static void BindMojoRequest(LocalFrame*, mojom::blink::DevToolsFrontendAssociatedRequest); static DevToolsFrontendImpl* From(LocalFrame*); ~DevToolsFrontendImpl() override; void DidClearWindowObject(); void Trace(blink::Visitor*) override; private: DevToolsFrontendImpl(LocalFrame&, mojom::blink::DevToolsFrontendAssociatedRequest); void DestroyOnHostGone(); // mojom::blink::DevToolsFrontend implementation. void SetupDevToolsFrontend( const String& api_script, mojom::blink::DevToolsFrontendHostAssociatedPtrInfo) override; void SetupDevToolsExtensionAPI(const String& extension_api) override; // InspectorFrontendClient implementation. void SendMessageToEmbedder(const String&) override; Member<DevToolsHost> devtools_host_; String api_script_; mojom::blink::DevToolsFrontendHostAssociatedPtr host_; mojo::AssociatedBinding<mojom::blink::DevToolsFrontend> binding_; DISALLOW_COPY_AND_ASSIGN(DevToolsFrontendImpl); }; } // namespace blink #endif
1,230
342
#include <iostream> #include "function/expressions/shared/shared.h" #include "region/common/controlblock.h" #include "translatetype.h" #include "function/expression.h" Ref translateInterfaceCall( GlobalState* globalState, FunctionState* functionState, BlockState* blockState, LLVMBuilderRef builder, InterfaceCall* call) { auto argExprs = call->argExprs; auto virtualParamIndex = call->virtualParamIndex; auto interfaceRef = call->interfaceRef; auto indexInEdge = call->indexInEdge; auto functionType = call->functionType; auto argExprsLE = translateExpressions(globalState, functionState, blockState, builder, call->argExprs); auto argsLE = std::vector<Ref>{}; argsLE.reserve(call->argExprs.size()); for (int i = 0; i < call->argExprs.size(); i++) { auto argLE = translateExpression(globalState, functionState, blockState, builder, call->argExprs[i]); globalState->getRegion(call->functionType->params[i]) ->checkValidReference(FL(), functionState, builder, call->functionType->params[i], argLE); argsLE.push_back(argLE); } auto virtualArgRefMT = functionType->params[virtualParamIndex]; auto virtualArgRef = argsLE[virtualParamIndex]; auto methodFunctionPtrLE = globalState->getRegion(virtualArgRefMT) ->getInterfaceMethodFunctionPtr(functionState, builder, virtualArgRefMT, virtualArgRef, indexInEdge); auto resultLE = buildInterfaceCall( globalState, functionState, builder, call->functionType, methodFunctionPtrLE, argExprsLE, call->virtualParamIndex); globalState->getRegion(call->functionType->returnType) ->checkValidReference(FL(), functionState, builder, call->functionType->returnType, resultLE); if (call->functionType->returnType->kind == globalState->metalCache->never) { return wrap( globalState->getRegion(globalState->metalCache->neverRef), globalState->metalCache->neverRef, LLVMBuildRet(builder, LLVMGetUndef(functionState->returnTypeL))); } else { return resultLE; } }
743
3,353
<reponame>bsipocmpi/jetty.project // // ======================================================================== // Copyright (c) 1995-2021 Mort Bay Consulting Pty Ltd and others. // // This program and the accompanying materials are made available under the // terms of the Eclipse Public License v. 2.0 which is available at // https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 // which is available at https://www.apache.org/licenses/LICENSE-2.0. // // SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 // ======================================================================== // package org.eclipse.jetty.maven.plugin; import java.io.Console; import java.util.EventListener; import java.util.HashSet; import java.util.Set; /** * ConsoleReader * * Reads lines from the System console and supplies them * to ConsoleReader.Listeners. */ public class ConsoleReader implements Runnable { public interface Listener extends EventListener { public void consoleEvent(String line); } public Set<ConsoleReader.Listener> listeners = new HashSet<>(); public void addListener(ConsoleReader.Listener listener) { listeners.add(listener); } public void removeListener(ConsoleReader.Listener listener) { listeners.remove(listener); } public void run() { Console console = System.console(); if (console == null) return; String line = ""; while (true && line != null) { line = console.readLine("%nHit <enter> to redeploy:%n%n"); if (line != null) signalEvent(line); } } private void signalEvent(String line) { for (ConsoleReader.Listener l:listeners) l.consoleEvent(line); } }
654
420
from .nn_utils import * from .odst import * from .utils import * from .data import * from .arch import * from .trainer import *
40
1,538
<reponame>attilabukor/kudu<filename>java/kudu-client/src/main/java/org/apache/kudu/client/ServerInfo.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.apache.kudu.client; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.Locale; import java.util.concurrent.ConcurrentHashMap; import com.google.common.base.Preconditions; import org.apache.yetus.audience.InterfaceAudience; import org.apache.kudu.util.NetUtil; /** * Container class for server information that never changes, like UUID and hostname. */ @InterfaceAudience.Private public class ServerInfo { private final String uuid; private final HostAndPort hostPort; private final InetSocketAddress resolvedAddr; private final String location; private final boolean local; private static final ConcurrentHashMap<InetAddress, Boolean> isLocalAddressCache = new ConcurrentHashMap<>(); /** * Constructor for all the fields. The intent is that there should only be one ServerInfo * instance per UUID the client is connected to. * @param uuid server's UUID * @param hostPort server's hostname and port * @param resolvedAddr resolved address used to check if the server is local * @param location the location assigned by the leader master, or an empty string if no location * is assigned */ public ServerInfo(String uuid, HostAndPort hostPort, InetAddress resolvedAddr, String location) { Preconditions.checkNotNull(uuid); Preconditions.checkArgument(hostPort.getPort() > 0); Preconditions.checkNotNull(location); this.uuid = uuid; this.hostPort = hostPort; this.resolvedAddr = new InetSocketAddress(resolvedAddr, hostPort.getPort()); this.location = location; this.local = isLocalAddressCache.computeIfAbsent(resolvedAddr, inetAddress -> NetUtil.isLocalAddress(resolvedAddr)); } /** * Returns this server's uuid. * @return a string that contains this server's uuid */ public String getUuid() { return uuid; } /** * Returns this server's canonical hostname. * @return a string that contains this server's canonical hostname */ public String getAndCanonicalizeHostname() { try { return InetAddress.getByName( hostPort.getHost()).getCanonicalHostName().toLowerCase(Locale.ENGLISH); } catch (UnknownHostException e) { return hostPort.getHost(); } } /** * Returns this server's hostname and port. * @return a HostAndPort that describes where this server can be reached. */ public HostAndPort getHostAndPort() { return hostPort; } /** * Returns this server's port. * @return a port number that this server is bound to */ public int getPort() { return hostPort.getPort(); } /** * Returns this server's location. If no location is assigned, returns an empty string. * @return the server's location */ public String getLocation() { return location; } /** * Returns true if the server is in the same location as 'location'. * @return true if the server is in 'location'. */ public boolean inSameLocation(String loc) { Preconditions.checkNotNull(loc); return !loc.isEmpty() && loc.equals(location); } /** * Returns if this server is on this client's host. * @return true if the server is local, else false */ public boolean isLocal() { return local; } /** * @return the cached resolved address for this server */ public InetSocketAddress getResolvedAddress() { return resolvedAddr; } @Override public String toString() { return uuid + "(" + hostPort + ")"; } }
1,389
17,337
<reponame>SSYSS000/Proton #include "steam_defs.h" #pragma push_macro("__cdecl") #undef __cdecl #include "steamworks_sdk_142/steam_api.h" #pragma pop_macro("__cdecl") #include "steamclient_private.h" #ifdef __cplusplus extern "C" { #endif #define SDKVER_142 #include "struct_converters.h" #include "cppISteamInventory_STEAMINVENTORY_INTERFACE_V002.h" EResult cppISteamInventory_STEAMINVENTORY_INTERFACE_V002_GetResultStatus(void *linux_side, SteamInventoryResult_t resultHandle) { return ((ISteamInventory*)linux_side)->GetResultStatus((SteamInventoryResult_t)resultHandle); } bool cppISteamInventory_STEAMINVENTORY_INTERFACE_V002_GetResultItems(void *linux_side, SteamInventoryResult_t resultHandle, SteamItemDetails_t * pOutItemsArray, uint32 * punOutItemsArraySize) { return ((ISteamInventory*)linux_side)->GetResultItems((SteamInventoryResult_t)resultHandle, (SteamItemDetails_t *)pOutItemsArray, (uint32 *)punOutItemsArraySize); } bool cppISteamInventory_STEAMINVENTORY_INTERFACE_V002_GetResultItemProperty(void *linux_side, SteamInventoryResult_t resultHandle, uint32 unItemIndex, const char * pchPropertyName, char * pchValueBuffer, uint32 * punValueBufferSizeOut) { return ((ISteamInventory*)linux_side)->GetResultItemProperty((SteamInventoryResult_t)resultHandle, (uint32)unItemIndex, (const char *)pchPropertyName, (char *)pchValueBuffer, (uint32 *)punValueBufferSizeOut); } uint32 cppISteamInventory_STEAMINVENTORY_INTERFACE_V002_GetResultTimestamp(void *linux_side, SteamInventoryResult_t resultHandle) { return ((ISteamInventory*)linux_side)->GetResultTimestamp((SteamInventoryResult_t)resultHandle); } bool cppISteamInventory_STEAMINVENTORY_INTERFACE_V002_CheckResultSteamID(void *linux_side, SteamInventoryResult_t resultHandle, CSteamID steamIDExpected) { return ((ISteamInventory*)linux_side)->CheckResultSteamID((SteamInventoryResult_t)resultHandle, (CSteamID)steamIDExpected); } void cppISteamInventory_STEAMINVENTORY_INTERFACE_V002_DestroyResult(void *linux_side, SteamInventoryResult_t resultHandle) { ((ISteamInventory*)linux_side)->DestroyResult((SteamInventoryResult_t)resultHandle); } bool cppISteamInventory_STEAMINVENTORY_INTERFACE_V002_GetAllItems(void *linux_side, SteamInventoryResult_t * pResultHandle) { return ((ISteamInventory*)linux_side)->GetAllItems((SteamInventoryResult_t *)pResultHandle); } bool cppISteamInventory_STEAMINVENTORY_INTERFACE_V002_GetItemsByID(void *linux_side, SteamInventoryResult_t * pResultHandle, const SteamItemInstanceID_t * pInstanceIDs, uint32 unCountInstanceIDs) { return ((ISteamInventory*)linux_side)->GetItemsByID((SteamInventoryResult_t *)pResultHandle, (const SteamItemInstanceID_t *)pInstanceIDs, (uint32)unCountInstanceIDs); } bool cppISteamInventory_STEAMINVENTORY_INTERFACE_V002_SerializeResult(void *linux_side, SteamInventoryResult_t resultHandle, void * pOutBuffer, uint32 * punOutBufferSize) { return ((ISteamInventory*)linux_side)->SerializeResult((SteamInventoryResult_t)resultHandle, (void *)pOutBuffer, (uint32 *)punOutBufferSize); } bool cppISteamInventory_STEAMINVENTORY_INTERFACE_V002_DeserializeResult(void *linux_side, SteamInventoryResult_t * pOutResultHandle, const void * pBuffer, uint32 unBufferSize, bool bRESERVED_MUST_BE_FALSE) { return ((ISteamInventory*)linux_side)->DeserializeResult((SteamInventoryResult_t *)pOutResultHandle, (const void *)pBuffer, (uint32)unBufferSize, (bool)bRESERVED_MUST_BE_FALSE); } bool cppISteamInventory_STEAMINVENTORY_INTERFACE_V002_GenerateItems(void *linux_side, SteamInventoryResult_t * pResultHandle, const SteamItemDef_t * pArrayItemDefs, const uint32 * punArrayQuantity, uint32 unArrayLength) { return ((ISteamInventory*)linux_side)->GenerateItems((SteamInventoryResult_t *)pResultHandle, (const SteamItemDef_t *)pArrayItemDefs, (const uint32 *)punArrayQuantity, (uint32)unArrayLength); } bool cppISteamInventory_STEAMINVENTORY_INTERFACE_V002_GrantPromoItems(void *linux_side, SteamInventoryResult_t * pResultHandle) { return ((ISteamInventory*)linux_side)->GrantPromoItems((SteamInventoryResult_t *)pResultHandle); } bool cppISteamInventory_STEAMINVENTORY_INTERFACE_V002_AddPromoItem(void *linux_side, SteamInventoryResult_t * pResultHandle, SteamItemDef_t itemDef) { return ((ISteamInventory*)linux_side)->AddPromoItem((SteamInventoryResult_t *)pResultHandle, (SteamItemDef_t)itemDef); } bool cppISteamInventory_STEAMINVENTORY_INTERFACE_V002_AddPromoItems(void *linux_side, SteamInventoryResult_t * pResultHandle, const SteamItemDef_t * pArrayItemDefs, uint32 unArrayLength) { return ((ISteamInventory*)linux_side)->AddPromoItems((SteamInventoryResult_t *)pResultHandle, (const SteamItemDef_t *)pArrayItemDefs, (uint32)unArrayLength); } bool cppISteamInventory_STEAMINVENTORY_INTERFACE_V002_ConsumeItem(void *linux_side, SteamInventoryResult_t * pResultHandle, SteamItemInstanceID_t itemConsume, uint32 unQuantity) { return ((ISteamInventory*)linux_side)->ConsumeItem((SteamInventoryResult_t *)pResultHandle, (SteamItemInstanceID_t)itemConsume, (uint32)unQuantity); } bool cppISteamInventory_STEAMINVENTORY_INTERFACE_V002_ExchangeItems(void *linux_side, SteamInventoryResult_t * pResultHandle, const SteamItemDef_t * pArrayGenerate, const uint32 * punArrayGenerateQuantity, uint32 unArrayGenerateLength, const SteamItemInstanceID_t * pArrayDestroy, const uint32 * punArrayDestroyQuantity, uint32 unArrayDestroyLength) { return ((ISteamInventory*)linux_side)->ExchangeItems((SteamInventoryResult_t *)pResultHandle, (const SteamItemDef_t *)pArrayGenerate, (const uint32 *)punArrayGenerateQuantity, (uint32)unArrayGenerateLength, (const SteamItemInstanceID_t *)pArrayDestroy, (const uint32 *)punArrayDestroyQuantity, (uint32)unArrayDestroyLength); } bool cppISteamInventory_STEAMINVENTORY_INTERFACE_V002_TransferItemQuantity(void *linux_side, SteamInventoryResult_t * pResultHandle, SteamItemInstanceID_t itemIdSource, uint32 unQuantity, SteamItemInstanceID_t itemIdDest) { return ((ISteamInventory*)linux_side)->TransferItemQuantity((SteamInventoryResult_t *)pResultHandle, (SteamItemInstanceID_t)itemIdSource, (uint32)unQuantity, (SteamItemInstanceID_t)itemIdDest); } void cppISteamInventory_STEAMINVENTORY_INTERFACE_V002_SendItemDropHeartbeat(void *linux_side) { ((ISteamInventory*)linux_side)->SendItemDropHeartbeat(); } bool cppISteamInventory_STEAMINVENTORY_INTERFACE_V002_TriggerItemDrop(void *linux_side, SteamInventoryResult_t * pResultHandle, SteamItemDef_t dropListDefinition) { return ((ISteamInventory*)linux_side)->TriggerItemDrop((SteamInventoryResult_t *)pResultHandle, (SteamItemDef_t)dropListDefinition); } bool cppISteamInventory_STEAMINVENTORY_INTERFACE_V002_TradeItems(void *linux_side, SteamInventoryResult_t * pResultHandle, CSteamID steamIDTradePartner, const SteamItemInstanceID_t * pArrayGive, const uint32 * pArrayGiveQuantity, uint32 nArrayGiveLength, const SteamItemInstanceID_t * pArrayGet, const uint32 * pArrayGetQuantity, uint32 nArrayGetLength) { return ((ISteamInventory*)linux_side)->TradeItems((SteamInventoryResult_t *)pResultHandle, (CSteamID)steamIDTradePartner, (const SteamItemInstanceID_t *)pArrayGive, (const uint32 *)pArrayGiveQuantity, (uint32)nArrayGiveLength, (const SteamItemInstanceID_t *)pArrayGet, (const uint32 *)pArrayGetQuantity, (uint32)nArrayGetLength); } bool cppISteamInventory_STEAMINVENTORY_INTERFACE_V002_LoadItemDefinitions(void *linux_side) { return ((ISteamInventory*)linux_side)->LoadItemDefinitions(); } bool cppISteamInventory_STEAMINVENTORY_INTERFACE_V002_GetItemDefinitionIDs(void *linux_side, SteamItemDef_t * pItemDefIDs, uint32 * punItemDefIDsArraySize) { return ((ISteamInventory*)linux_side)->GetItemDefinitionIDs((SteamItemDef_t *)pItemDefIDs, (uint32 *)punItemDefIDsArraySize); } bool cppISteamInventory_STEAMINVENTORY_INTERFACE_V002_GetItemDefinitionProperty(void *linux_side, SteamItemDef_t iDefinition, const char * pchPropertyName, char * pchValueBuffer, uint32 * punValueBufferSizeOut) { return ((ISteamInventory*)linux_side)->GetItemDefinitionProperty((SteamItemDef_t)iDefinition, (const char *)pchPropertyName, (char *)pchValueBuffer, (uint32 *)punValueBufferSizeOut); } SteamAPICall_t cppISteamInventory_STEAMINVENTORY_INTERFACE_V002_RequestEligiblePromoItemDefinitionsIDs(void *linux_side, CSteamID steamID) { return ((ISteamInventory*)linux_side)->RequestEligiblePromoItemDefinitionsIDs((CSteamID)steamID); } bool cppISteamInventory_STEAMINVENTORY_INTERFACE_V002_GetEligiblePromoItemDefinitionIDs(void *linux_side, CSteamID steamID, SteamItemDef_t * pItemDefIDs, uint32 * punItemDefIDsArraySize) { return ((ISteamInventory*)linux_side)->GetEligiblePromoItemDefinitionIDs((CSteamID)steamID, (SteamItemDef_t *)pItemDefIDs, (uint32 *)punItemDefIDsArraySize); } SteamAPICall_t cppISteamInventory_STEAMINVENTORY_INTERFACE_V002_StartPurchase(void *linux_side, const SteamItemDef_t * pArrayItemDefs, const uint32 * punArrayQuantity, uint32 unArrayLength) { return ((ISteamInventory*)linux_side)->StartPurchase((const SteamItemDef_t *)pArrayItemDefs, (const uint32 *)punArrayQuantity, (uint32)unArrayLength); } SteamAPICall_t cppISteamInventory_STEAMINVENTORY_INTERFACE_V002_RequestPrices(void *linux_side) { return ((ISteamInventory*)linux_side)->RequestPrices(); } uint32 cppISteamInventory_STEAMINVENTORY_INTERFACE_V002_GetNumItemsWithPrices(void *linux_side) { return ((ISteamInventory*)linux_side)->GetNumItemsWithPrices(); } bool cppISteamInventory_STEAMINVENTORY_INTERFACE_V002_GetItemsWithPrices(void *linux_side, SteamItemDef_t * pArrayItemDefs, uint64 * pPrices, uint32 unArrayLength) { return ((ISteamInventory*)linux_side)->GetItemsWithPrices((SteamItemDef_t *)pArrayItemDefs, (uint64 *)pPrices, (uint32)unArrayLength); } bool cppISteamInventory_STEAMINVENTORY_INTERFACE_V002_GetItemPrice(void *linux_side, SteamItemDef_t iDefinition, uint64 * pPrice) { return ((ISteamInventory*)linux_side)->GetItemPrice((SteamItemDef_t)iDefinition, (uint64 *)pPrice); } SteamInventoryUpdateHandle_t cppISteamInventory_STEAMINVENTORY_INTERFACE_V002_StartUpdateProperties(void *linux_side) { return ((ISteamInventory*)linux_side)->StartUpdateProperties(); } bool cppISteamInventory_STEAMINVENTORY_INTERFACE_V002_RemoveProperty(void *linux_side, SteamInventoryUpdateHandle_t handle, SteamItemInstanceID_t nItemID, const char * pchPropertyName) { return ((ISteamInventory*)linux_side)->RemoveProperty((SteamInventoryUpdateHandle_t)handle, (SteamItemInstanceID_t)nItemID, (const char *)pchPropertyName); } bool cppISteamInventory_STEAMINVENTORY_INTERFACE_V002_SetProperty(void *linux_side, SteamInventoryUpdateHandle_t handle, SteamItemInstanceID_t nItemID, const char * pchPropertyName, const char * pchPropertyValue) { return ((ISteamInventory*)linux_side)->SetProperty((SteamInventoryUpdateHandle_t)handle, (SteamItemInstanceID_t)nItemID, (const char *)pchPropertyName, (const char *)pchPropertyValue); } bool cppISteamInventory_STEAMINVENTORY_INTERFACE_V002_SetProperty_2(void *linux_side, SteamInventoryUpdateHandle_t handle, SteamItemInstanceID_t nItemID, const char * pchPropertyName, bool bValue) { return ((ISteamInventory*)linux_side)->SetProperty((SteamInventoryUpdateHandle_t)handle, (SteamItemInstanceID_t)nItemID, (const char *)pchPropertyName, (bool)bValue); } bool cppISteamInventory_STEAMINVENTORY_INTERFACE_V002_SetProperty_3(void *linux_side, SteamInventoryUpdateHandle_t handle, SteamItemInstanceID_t nItemID, const char * pchPropertyName, int64 nValue) { return ((ISteamInventory*)linux_side)->SetProperty((SteamInventoryUpdateHandle_t)handle, (SteamItemInstanceID_t)nItemID, (const char *)pchPropertyName, (int64)nValue); } bool cppISteamInventory_STEAMINVENTORY_INTERFACE_V002_SetProperty_4(void *linux_side, SteamInventoryUpdateHandle_t handle, SteamItemInstanceID_t nItemID, const char * pchPropertyName, float flValue) { return ((ISteamInventory*)linux_side)->SetProperty((SteamInventoryUpdateHandle_t)handle, (SteamItemInstanceID_t)nItemID, (const char *)pchPropertyName, (float)flValue); } bool cppISteamInventory_STEAMINVENTORY_INTERFACE_V002_SubmitUpdateProperties(void *linux_side, SteamInventoryUpdateHandle_t handle, SteamInventoryResult_t * pResultHandle) { return ((ISteamInventory*)linux_side)->SubmitUpdateProperties((SteamInventoryUpdateHandle_t)handle, (SteamInventoryResult_t *)pResultHandle); } #ifdef __cplusplus } #endif
4,198
2,989
<gh_stars>1000+ package com.linkedin.databus2.relay; /* * * Copyright 2013 LinkedIn Corp. 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 java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.List; import javax.management.MBeanServer; import javax.sql.DataSource; import org.apache.log4j.Logger; import com.linkedin.databus.monitoring.mbean.DBStatistics; import com.linkedin.databus.monitoring.mbean.DBStatisticsMBean; import com.linkedin.databus.monitoring.mbean.SourceDBStatistics; import com.linkedin.databus2.producers.EventProducer; import com.linkedin.databus2.producers.db.EventReaderSummary; import com.linkedin.databus2.producers.db.OracleTriggerMonitoredSourceInfo; import com.linkedin.databus2.util.DBHelper; public class MonitoringEventProducer implements EventProducer , Runnable { private final List<OracleTriggerMonitoredSourceInfo> _sources ; private final String _name; private final String _dbname; protected enum MonitorState {INIT,RUNNING, PAUSE,SHUT} MonitorState _state; private final HashMap<Short, String> _monitorQueriesBySource; static protected final long MAX_SCN_POLL_TIME = 10*60*1000; static protected final long PER_SRC_MAX_SCN_POLL_TIME = 30*1000; private Thread _curThread; private final String _uri; /** Logger for error and debug messages. */ private final Logger _log = Logger.getLogger(getClass()); private String _schema; //stored as state ; as it may be required for graceful shutdown ; in case of exception private Connection _con; private DataSource _dataSource; private final DBStatistics _dbStats; private final MBeanServer _mbeanServer; public MonitoringEventProducer(String name,String dbname, String uri,List<OracleTriggerMonitoredSourceInfo> sources,MBeanServer mbeanServer) { _sources = sources; _name = name; _dbname = dbname; _state = MonitorState.INIT; _con = null; _dataSource = null; _uri = uri; _schema = null; _mbeanServer = mbeanServer; // Generate the event queries for each source _monitorQueriesBySource = new HashMap<Short, String>(); _dbStats = new DBStatistics(dbname); for(OracleTriggerMonitoredSourceInfo sourceInfo : sources) { if (null==_schema) { //all logical sources have same schema _schema = sourceInfo.getEventSchema()==null ? "" : sourceInfo.getEventSchema()+"."; _log.info("Reading source: _schema = |" + _schema + "|"); } _dbStats.addSrcStats(new SourceDBStatistics(sourceInfo.getSourceName())); String eventQuery = generateEventQuery(sourceInfo); _monitorQueriesBySource.put(sourceInfo.getSourceId(), eventQuery); } _dbStats.registerAsMbean(_mbeanServer); _log.info("Created " + name + " producer "); } @Override public String getName() { return _name; } @Override public long getSCN() { return 0; } public DBStatisticsMBean getDBStats() { return _dbStats; } public void unregisterMBeans() { _dbStats.unregisterAsMbean(_mbeanServer); } @Override public synchronized void start(long sinceSCN) { if (_state == MonitorState.INIT || _state == MonitorState.SHUT) { _state = MonitorState.RUNNING; _curThread = new Thread(this); _curThread.start(); } } @Override public synchronized boolean isRunning() { return _state==MonitorState.RUNNING; } @Override public synchronized boolean isPaused() { return false; } @Override public synchronized void unpause() { _state = MonitorState.RUNNING; } @Override public synchronized void pause() { } @Override public synchronized void shutdown() { _state=MonitorState.SHUT; } protected boolean createDataSource() { try { if (_dataSource==null) { _dataSource = OracleJarUtils.createOracleDataSource(_uri); } } catch (Exception e) { _log.error("Error creating data source", e); _dataSource = null; return false; } return true; } @Override public void run() { //check state and behave accordingly if (createDataSource() && openDbConn()) { do { PreparedStatement pstmt = null; ResultSet rs = null; try { long maxDBScn = getMaxTxlogSCN(_con); _log.info("Max DB Scn = " + maxDBScn); _dbStats.setMaxDBScn(maxDBScn); for (OracleTriggerMonitoredSourceInfo source: _sources) { String eventQuery = _monitorQueriesBySource.get(source.getSourceId()); pstmt = _con.prepareStatement(eventQuery); pstmt.setFetchSize(10); //get max scn - exactly one row; rs = pstmt.executeQuery(); if (rs.next()) { long maxScn = rs.getLong(1); _log.info("Source: " + source.getSourceId() + " Max Scn=" + maxScn); _dbStats.setSrcMaxScn(source.getSourceName(), maxScn); } DBHelper.commit(_con); DBHelper.close(rs,pstmt, null); if (_state != MonitorState.SHUT) { Thread.sleep(PER_SRC_MAX_SCN_POLL_TIME); } } if (_state != MonitorState.SHUT) { Thread.sleep(MAX_SCN_POLL_TIME); } } catch (InterruptedException e) { _log.error("Exception trace", e); shutDown(); } catch (SQLException e) { try { DBHelper.rollback(_con); } catch (SQLException s){} _log.error("Exception trace", e); shutDown(); } finally { DBHelper.close(rs, pstmt, null); } } while (_state != MonitorState.SHUT); _log.info("Shutting down dbMonitor thread"); DBHelper.close(_con); } } protected synchronized void shutDown() { _state = MonitorState.SHUT; _curThread = null; } private String generateEventQuery(OracleTriggerMonitoredSourceInfo sourceInfo) { /* select scn from sy$txlog where txn = (select max(txn) from sy$member_account); */ StringBuilder sql = new StringBuilder(); sql.append("select scn from ").append(_schema).append("sy$txlog "); sql.append("where txn = "); sql.append (" ( select max(txn) from ").append(_schema).append("sy$").append(sourceInfo.getEventView()).append(" )"); _log.info("Monitoring Query: " + sql.toString()); return sql.toString(); } /** * * Returns the max SCN from the sy$txlog table * @param db * @return the max scn * @throws SQLException */ private long getMaxTxlogSCN(Connection db) throws SQLException { long maxScn = EventReaderSummary.NO_EVENTS_SCN; String sql = "select " + "max(" + _schema + "sync_core.getScn(scn,ora_rowscn)) " + "from " + _schema + "sy$txlog where " + "scn >= (select max(scn) from " + _schema + "sy$txlog)"; PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = db.prepareStatement(sql); rs = pstmt.executeQuery(); if(rs.next()) { maxScn = rs.getLong(1); } } finally { DBHelper.close(rs, pstmt, null); } return maxScn; } protected boolean openDbConn() { if (_dataSource == null) return false; // Create the OracleDataSource used to get DB connection(s) try { // Open the database connection if it is closed (at start or after an SQLException) if(_con == null || _con.isClosed()) { _con = _dataSource.getConnection(); _con.setAutoCommit(false); _con.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); } } catch (SQLException e) { _log.error("Exception trace", e); return false; } return true; } @Override public void waitForShutdown() throws InterruptedException, IllegalStateException { // TODO Auto-generated method stub } @Override public void waitForShutdown(long arg0) throws InterruptedException, IllegalStateException { // TODO Auto-generated method stub } }
3,217
903
package com.github.vole.portal.common.permission; import com.github.vole.passport.common.permission.AccessPermission; import com.github.vole.portal.common.fegin.MenuService; import com.github.vole.portal.common.vo.SysMenuVO; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.stereotype.Service; import org.springframework.util.AntPathMatcher; import javax.servlet.http.HttpServletRequest; import java.util.HashSet; import java.util.List; import java.util.Set; @Slf4j @Service public class PermissionService implements AccessPermission { @Autowired private MenuService menuService; public void setMenuService(MenuService menuService) { this.menuService = menuService; } public MenuService getMenuService() { return menuService; } private AntPathMatcher antPathMatcher = new AntPathMatcher(); @Override public boolean hasPermission(HttpServletRequest request, Authentication authentication) { Object principal = authentication.getPrincipal(); List<SimpleGrantedAuthority> grantedAuthorityList = (List<SimpleGrantedAuthority>) authentication.getAuthorities(); boolean hasPermission = false; if (principal != null) { if (CollectionUtils.isEmpty(grantedAuthorityList)) { log.warn("角色列表为空:{}", authentication.getPrincipal()); return hasPermission; } Set<SysMenuVO> menuVOS = new HashSet<>(); for (SimpleGrantedAuthority authority : grantedAuthorityList) { Set<SysMenuVO> menuVOSet = menuService.findMenusByRole(authority.getAuthority()); if (CollectionUtils.isNotEmpty(menuVOSet)) { menuVOS.addAll(menuVOSet); } } for (SysMenuVO menuVO : menuVOS) { if (StringUtils.isNotBlank(menuVO.getResource())) { String[] urls = StringUtils.split(menuVO.getResource(), ","); for (int i = 0; i < urls.length; i++) { if (antPathMatcher.match(urls[i], request.getRequestURI())){ hasPermission = true; break; } } if (hasPermission) break; } } } return hasPermission; } }
1,169
1,414
#ifdef NALL_STRING_INTERNAL_HPP namespace nall { // //strmcpy, strmcat created by byuu // //return = strlen(target) unsigned strmcpy(char *target, const char *source, unsigned length) { const char *origin = target; if(length) { while(*source && --length) *target++ = *source++; *target = 0; } return target - origin; } //return = strlen(target) unsigned strmcat(char *target, const char *source, unsigned length) { const char *origin = target; while(*target && length) target++, length--; return (target - origin) + strmcpy(target, source, length); } //return = true when all of source was copied bool strccpy(char *target, const char *source, unsigned length) { return !source[strmcpy(target, source, length)]; } //return = true when all of source was copied bool strccat(char *target, const char *source, unsigned length) { while(*target && length) target++, length--; return !source[strmcpy(target, source, length)]; } //return = reserved for future use void strpcpy(char *&target, const char *source, unsigned &length) { unsigned offset = strmcpy(target, source, length); target += offset, length -= offset; } } #endif
376
1,738
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #include "PhysX_precompiled.h" #include <AzCore/Component/ComponentApplication.h> #include <AzFramework/Application/Application.h> #include <AzFramework/Components/TransformComponent.h> #include <AzCore/UnitTest/UnitTest.h> #include <AzCore/Memory/MemoryComponent.h> #include <AzCore/Asset/AssetManagerComponent.h> #include <AzCore/UnitTest/TestTypes.h> #include <AzFramework/IO/LocalFileIO.h> #include <AzCore/Memory/SystemAllocator.h> #include <AzQtComponents/Utilities/QtPluginPaths.h> #include <QApplication> namespace Physics { class PhysXEditorTestEnvironment : public AZ::Test::ITestEnvironment { protected: void SetupEnvironment() override { AZ::AllocatorInstance<AZ::SystemAllocator>::Create(); } void TeardownEnvironment() override { AZ::AllocatorInstance<AZ::SystemAllocator>::Destroy(); } }; class PhysXEditorTest : public ::testing::Test { protected: void SetUp() override { } void TearDown() override { } }; TEST_F(PhysXEditorTest, EditorDummyTest_NoState_TrivialPass) { EXPECT_TRUE(true); } AZTEST_EXPORT int AZ_UNIT_TEST_HOOK_NAME(int argc, char** argv) { ::testing::InitGoogleMock(&argc, argv); AzQtComponents::PrepareQtPaths(); QApplication app(argc, argv); AZ::Test::excludeIntegTests(); AZ::Test::ApplyGlobalParameters(&argc, argv); AZ::Test::printUnusedParametersWarning(argc, argv); AZ::Test::addTestEnvironments({ new PhysXEditorTestEnvironment }); int result = RUN_ALL_TESTS(); return result; } } // namespace Physics
866
1,165
<filename>src/galaxy/__init__.py<gh_stars>1000+ import logging logging.getLogger(__name__).setLevel(logging.INFO) __path__: str = __import__('pkgutil').extend_path(__path__, __name__) # type: ignore
78
1,738
<gh_stars>1000+ /* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #pragma once // include the required headers #include "EMotionFXConfig.h" #include <AzCore/std/string/string.h> namespace EMotionFX { // forward declarations class ActorInstance; class MotionInstance; class AnimGraphNode; class MotionEvent; /** * Triggered event info. * This class holds the information for each event that gets triggered. */ class EMFX_API EventInfo { MCORE_MEMORYOBJECTCATEGORY(EventInfo, EMFX_DEFAULT_ALIGNMENT, EMFX_MEMCATEGORY_EVENTS); public: enum EventState { START, ACTIVE, END }; float mTimeValue; /**< The time value of the event, in seconds. */ ActorInstance* mActorInstance; /**< The actor instance that triggered this event. */ const MotionInstance* mMotionInstance; /**< The motion instance which triggered this event, can be nullptr. */ AnimGraphNode* mEmitter; /**< The animgraph node which originally did emit this event. This parameter can be nullptr. */ const MotionEvent* mEvent; /**< The event itself. */ float mGlobalWeight; /**< The global weight of the event. */ float mLocalWeight; /**< The local weight of the event. */ EventState m_eventState; /**< Is this the start of a ranged event? Ticked events will always have this set to true. */ bool IsEventStart() const { return m_eventState == EventState::START; } explicit EventInfo( float timeValue = 0.0f, ActorInstance* actorInstance = nullptr, const MotionInstance* motionInstance = nullptr, MotionEvent* event = nullptr, EventState eventState = START ) : mTimeValue(timeValue) , mActorInstance(actorInstance) , mMotionInstance(motionInstance) , mEmitter(nullptr) , mEvent(event) , mGlobalWeight(1.0f) , mLocalWeight(1.0f) , m_eventState(eventState) { } }; } // namespace EMotionFX
1,122
852
<filename>CalibMuon/DTCalibration/plugins/DTT0WireInChamberReferenceCorrection.h #ifndef CalibMuon_DTT0WireInChamberReferenceCorrection_H #define CalibMuon_DTT0WireInChamberReferenceCorrection_H /** \class DTT0WireInChamberReferenceCorrection * Concrete implementation of a DTT0BaseCorrection. * Computes correction for t0 * * $Revision: 1.1 $ * \author <NAME> */ #include "CalibMuon/DTCalibration/interface/DTT0BaseCorrection.h" #include "DataFormats/MuonDetId/interface/DTChamberId.h" #include "FWCore/Framework/interface/ESHandle.h" #include "CondFormats/DataRecord/interface/DTT0Rcd.h" #include "CondFormats/DTObjects/interface/DTT0.h" #include "Geometry/Records/interface/MuonGeometryRecord.h" #include "FWCore/Framework/interface/ConsumesCollector.h" #include "FWCore/Utilities/interface/ESGetToken.h" #include <string> namespace edm { class ParameterSet; } class DTT0; class DTGeometry; namespace dtCalibration { class DTT0WireInChamberReferenceCorrection : public DTT0BaseCorrection { public: // Constructor DTT0WireInChamberReferenceCorrection(const edm::ParameterSet&, edm::ConsumesCollector); // Destructor ~DTT0WireInChamberReferenceCorrection() override; void setES(const edm::EventSetup& setup) override; DTT0Data correction(const DTWireId&) override; private: DTT0Data defaultT0(const DTWireId&); std::string calibChamber_; DTChamberId chosenChamberId_; const DTT0* t0Map_; edm::ESHandle<DTGeometry> dtGeom_; edm::ESGetToken<DTT0, DTT0Rcd> t0Token_; edm::ESGetToken<DTGeometry, MuonGeometryRecord> dtGeomToken_; }; } // namespace dtCalibration #endif
612
324
/* * 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.jclouds.cloudwatch.xml; import com.google.common.collect.Sets; import com.google.inject.Inject; import org.jclouds.cloudwatch.domain.Dimension; import org.jclouds.cloudwatch.domain.Metric; import org.jclouds.http.functions.ParseSax; import org.jclouds.util.SaxUtils; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import java.util.Set; /** * @see <a href="http://docs.amazonwebservices.com/AmazonCloudWatch/latest/APIReference/API_Metric.html" /> */ public class MetricHandler extends ParseSax.HandlerForGeneratedRequestWithResult<Metric> { private final DimensionHandler dimensionHandler; private StringBuilder currentText = new StringBuilder(); private Set<Dimension> dimensions = Sets.newLinkedHashSet(); private boolean inDimensions; private String metricName; private String namespace; @Inject public MetricHandler(DimensionHandler dimensionHandler) { this.dimensionHandler = dimensionHandler; } public boolean inDimensions() { return inDimensions; } /** * {@inheritDoc} */ @Override public Metric getResult() { Metric metric = new Metric(metricName, namespace, dimensions); // Reset since this handler is created once but produces N results dimensions = Sets.newLinkedHashSet(); metricName = null; namespace = null; return metric; } /** * {@inheritDoc} */ @Override public void startElement(String url, String name, String qName, Attributes attributes) throws SAXException { if (!inDimensions && SaxUtils.equalsOrSuffix(qName, "member")) { inDimensions = true; } if (inDimensions) { dimensionHandler.startElement(url, name, qName, attributes); } } /** * {@inheritDoc} */ @Override public void endElement(String uri, String name, String qName) throws SAXException { if (inDimensions) { if (qName.equals("Dimensions")) { inDimensions = false; } else if (qName.equals("member")) { dimensions.add(dimensionHandler.getResult()); } else { dimensionHandler.endElement(uri, name, qName); } } else if (qName.equals("MetricName")) { metricName = SaxUtils.currentOrNull(currentText); } else if (qName.equals("Namespace")) { namespace = SaxUtils.currentOrNull(currentText); } currentText.setLength(0); } /** * {@inheritDoc} */ @Override public void characters(char[] ch, int start, int length) { if (inDimensions) { dimensionHandler.characters(ch, start, length); } else { currentText.append(ch, start, length); } } }
1,231
1,031
<reponame>MADEAPPS/newton-dynamics<filename>newton-4.00/applications/ndSandbox/ndPhysicsWorld.cpp /* Copyright (c) <2003-2021> <Newton Game Dynamics> * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely */ #include "ndSandboxStdafx.h" #include "ndDemoMesh.h" #include "ndDemoCamera.h" #include "ndPhysicsWorld.h" #include "ndSoundManager.h" #include "ndContactCallback.h" #include "ndDemoEntityManager.h" #include "ndDemoCameraManager.h" #include "ndDemoMeshInterface.h" #include "ndBasicPlayerCapsule.h" #include "ndArchimedesBuoyancyVolume.h" #define MAX_PHYSICS_STEPS 1 #define MAX_PHYSICS_FPS 60.0f //#define MAX_PHYSICS_RECOVER_STEPS 2 class ndPhysicsWorldSettings : public ndWordSettings { public: D_CLASS_REFLECTION(ndPhysicsWorldSettings); ndPhysicsWorldSettings(ndPhysicsWorld* const world) :ndWordSettings() ,m_cameraMatrix(dGetIdentityMatrix()) ,m_world(world) { } ndPhysicsWorldSettings(const dLoadSaveBase::dLoadDescriptor& desc) :ndWordSettings(dLoadSaveBase::dLoadDescriptor(desc)) ,m_world(nullptr) { } virtual void Load(const dLoadSaveBase::dLoadDescriptor& desc) { dLoadSaveBase::dLoadDescriptor childDesc(desc); ndWordSettings::Load(childDesc); // load application specific settings here m_cameraMatrix = xmlGetMatrix(desc.m_rootNode, "cameraMatrix"); } virtual void Save(const dLoadSaveBase::dSaveDescriptor& desc) const { nd::TiXmlElement* const childNode = new nd::TiXmlElement(ClassName()); desc.m_rootNode->LinkEndChild(childNode); ndWordSettings::Save(dLoadSaveBase::dSaveDescriptor(desc, childNode)); ndDemoEntityManager* const manager = m_world->GetManager(); ndDemoCamera* const camera = manager->GetCamera(); dMatrix cameraMatrix (camera->GetCurrentMatrix()); xmlSaveParam(childNode, "description", "string", "this scene was saved from Newton 4.0 sandbox demos"); xmlSaveParam(childNode, "cameraMatrix", cameraMatrix); } dMatrix m_cameraMatrix; ndPhysicsWorld* m_world; }; D_CLASS_REFLECTION_IMPLEMENT_LOADER(ndPhysicsWorldSettings); ndPhysicsWorld::ndPhysicsWorld(ndDemoEntityManager* const manager) :ndWorld() ,m_manager(manager) ,m_soundManager(new ndSoundManager(manager)) ,m_timeAccumulator(0.0f) ,m_deletedBodies() ,m_hasPendingObjectToDelete(false) ,m_deletedLock() { ClearCache(); SetContactNotify(new ndContactCallback); } ndPhysicsWorld::~ndPhysicsWorld() { if (m_soundManager) { delete m_soundManager; } } ndDemoEntityManager* ndPhysicsWorld::GetManager() const { return m_manager; } void ndPhysicsWorld::QueueBodyForDelete(ndBody* const body) { dScopeSpinLock lock(m_deletedLock); m_hasPendingObjectToDelete.store(true); m_deletedBodies.PushBack(body); } void ndPhysicsWorld::DeletePendingObjects() { if (m_hasPendingObjectToDelete.load()) { Sync(); m_hasPendingObjectToDelete.store(false); for (dInt32 i = 0; i < m_deletedBodies.GetCount(); i++) { DeleteBody(m_deletedBodies[i]); } m_deletedBodies.SetCount(0); } } void ndPhysicsWorld::AdvanceTime(dFloat32 timestep) { const dFloat32 descreteStep = (1.0f / MAX_PHYSICS_FPS); dInt32 maxSteps = MAX_PHYSICS_STEPS; m_timeAccumulator += timestep; // if the time step is more than max timestep par frame, throw away the extra steps. if (m_timeAccumulator > descreteStep * maxSteps) { dFloat32 steps = dFloor(m_timeAccumulator / descreteStep) - maxSteps; dAssert(steps >= 0.0f); m_timeAccumulator -= descreteStep * steps; } while (m_timeAccumulator > descreteStep) { Update(descreteStep); m_timeAccumulator -= descreteStep; DeletePendingObjects(); } if (m_manager->m_synchronousPhysicsUpdate) { Sync(); } } ndSoundManager* ndPhysicsWorld::GetSoundManager() const { return m_soundManager; } void ndPhysicsWorld::OnPostUpdate(dFloat32 timestep) { m_manager->m_cameraManager->FixUpdate(m_manager, timestep); if (m_manager->m_updateCamera) { m_manager->m_updateCamera(m_manager, m_manager->m_updateCameraContext, timestep); } if (m_soundManager) { m_soundManager->Update(this, timestep); } } void ndPhysicsWorld::SaveScene(const char* const path) { ndLoadSave loadScene; ndPhysicsWorldSettings setting(this); loadScene.SaveScene(path, this, &setting); } void ndPhysicsWorld::SaveSceneModel(const char* const path) { ndLoadSave loadScene; loadScene.SaveModel(path, m_manager->m_selectedModel); } bool ndPhysicsWorld::LoadScene(const char* const path) { ndLoadSave loadScene; loadScene.LoadScene(path); // iterate over the loaded scene and add all objects to the world. if (loadScene.m_setting && (strcmp("ndPhysicsWorldSettings", loadScene.m_setting->SubClassName()) == 0)) { ndPhysicsWorldSettings* const settings = (ndPhysicsWorldSettings*)loadScene.m_setting; ndDemoEntityManager* const manager = GetManager(); manager->SetCameraMatrix(settings->m_cameraMatrix, settings->m_cameraMatrix.m_posit); } ndBodyLoaderCache::Iterator bodyIter(loadScene.m_bodyMap); for (bodyIter.Begin(); bodyIter; bodyIter++) { const ndBody* const body = (ndBody*)bodyIter.GetNode()->GetInfo(); AddBody((ndBody*)body); } ndJointLoaderCache::Iterator jointIter(loadScene.m_jointMap); for (jointIter.Begin(); jointIter; jointIter++) { const ndJointBilateralConstraint* const joint = (ndJointBilateralConstraint*)jointIter.GetNode()->GetInfo(); AddJoint((ndJointBilateralConstraint*)joint); } ndModelLoaderCache::Iterator modelIter(loadScene.m_modelMap); for (modelIter.Begin(); modelIter; modelIter++) { const ndModel* const model = modelIter.GetNode()->GetInfo(); AddModel((ndModel*)model); } // add some visualization dMatrix scale(dGetIdentityMatrix()); scale[0][0] = 0.5f; scale[1][1] = 0.5f; scale[2][2] = 0.5f; for (bodyIter.Begin(); bodyIter; bodyIter++) { ndBodyKinematic* const body = (ndBodyKinematic*)bodyIter.GetNode()->GetInfo(); dAssert(body->GetAsBodyKinematic()); const ndShapeInstance& collision = body->GetCollisionShape(); ndDemoMesh* const mesh = new ndDemoMesh("importMesh", m_manager->GetShaderCache(), &collision, "marbleCheckBoard.tga", "marbleCheckBoard.tga", "marbleCheckBoard.tga", 1.0f, scale); ndDemoEntity* const entity = new ndDemoEntity(body->GetMatrix(), nullptr); entity->SetMesh(mesh, dGetIdentityMatrix()); m_manager->AddEntity(entity); body->SetNotifyCallback(new ndDemoEntityNotify(m_manager, entity)); mesh->Release(); } return true; }
2,444
308
<gh_stars>100-1000 package burp.json; import burp.Config; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.reflect.TypeToken; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; /** * @author EvilChen */ public class ProcessJson { public List<String> jsonKeys = new ArrayList<>(); /** * 遍历JSON的下键给到jsonKeys */ public void foreachJsonKey(JsonElement e) { if (e.isJsonArray()) { JsonArray ja = e.getAsJsonArray(); if (null != ja) { for (JsonElement ae : ja) { foreachJsonKey(ae); } } } if (e.isJsonObject()) { Set<Map.Entry<String, JsonElement>> es = e.getAsJsonObject().entrySet(); for (Map.Entry<String, JsonElement> en : es) { jsonKeys.add(en.getKey()); foreachJsonKey(en.getValue()); } } } /** * 解析配置文件中的JSON */ public static Map<String, String> parseJson() { BufferedReader configReader = null; try { configReader = new BufferedReader(new FileReader(Config.CaAConfig)); } catch (FileNotFoundException e) { e.printStackTrace(); } assert configReader != null; return new Gson().fromJson( configReader, new TypeToken<Map<String, String>>() { }.getType() ); } /** * 写入JSON到配置文件 */ public static void writeJson(Map<String, String> map) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); try { BufferedWriter writer = new BufferedWriter(new FileWriter(Config.CaAConfig)); writer.write(gson.toJson(map)); writer.flush(); } catch (IOException e) { e.printStackTrace(); } } }
1,060
861
package cn.springcloud.gray.server.module.route.policy.jpa; import cn.springcloud.gray.event.server.GrayEventTrigger; import cn.springcloud.gray.event.server.TriggerType; import cn.springcloud.gray.function.Predicate3; import cn.springcloud.gray.model.RoutePolicy; import cn.springcloud.gray.server.exception.NonAuthorityException; import cn.springcloud.gray.server.module.NamespaceFinder; import cn.springcloud.gray.server.module.gray.domain.GrayModelType; import cn.springcloud.gray.server.module.route.policy.RoutePolicyModule; import cn.springcloud.gray.server.module.route.policy.domain.RoutePolicyRecord; import cn.springcloud.gray.server.module.route.policy.domain.RouteResourcePolicies; import cn.springcloud.gray.server.module.route.policy.domain.query.RoutePolicyQuery; import cn.springcloud.gray.server.module.user.AuthorityModule; import cn.springcloud.gray.server.service.RoutePolicyRecordService; import lombok.extern.slf4j.Slf4j; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.transaction.annotation.Transactional; import java.util.*; import java.util.concurrent.ConcurrentHashMap; /** * @author saleson * @date 2020-03-22 09:27 */ @Slf4j public class JPARoutePolicyModule implements RoutePolicyModule { private RoutePolicyRecordService routePolicyRecordService; private GrayEventTrigger grayEventTrigger; private NamespaceFinder namespaceFinder; private AuthorityModule authorityModule; private Map<String, Predicate3<String, String, RoutePolicy>> authorityPredicate = new ConcurrentHashMap<>(); public JPARoutePolicyModule( RoutePolicyRecordService routePolicyRecordService, GrayEventTrigger grayEventTrigger, NamespaceFinder namespaceFinder, AuthorityModule authorityModule) { this.routePolicyRecordService = routePolicyRecordService; this.grayEventTrigger = grayEventTrigger; this.namespaceFinder = namespaceFinder; this.authorityModule = authorityModule; } @Override public Page<RoutePolicyRecord> queryRoutePolicies(RoutePolicyQuery query, Pageable pageable) { return routePolicyRecordService.queryRoutePolicies(query, pageable); } @Override public List<RoutePolicyRecord> findAllRoutePolicies(RoutePolicyQuery query) { return routePolicyRecordService.queryRoutePolicies(query); } @Override public RoutePolicyRecord addRoutePolicy(String ns, RoutePolicy routePolicy, String operatorId) { RoutePolicyQuery query = RoutePolicyQuery.of(routePolicy); query.setNs(ns); RoutePolicyRecord routePolicyRecord = routePolicyRecordService.findFirstAscByDelFlag(query); if (Objects.isNull(routePolicyRecord)) { routePolicyRecord = createRoutePolicyRecord(ns, routePolicy, operatorId); int state = saveRoutePolicyRecord(routePolicyRecord); if (state > 0) { triggerGrayEvent(TriggerType.ADD, routePolicyRecord); } return routePolicyRecord; } if (Objects.isNull(routePolicyRecord.getDelFlag()) || routePolicyRecord.getDelFlag()) { updateRoutePolicyDelFlag(routePolicyRecord.getId(), false, operatorId); return routePolicyRecordService.findOneModel(routePolicyRecord.getId()); } return routePolicyRecord; } @Override public void physicsDeleteRoutePolicy(String type, String moduleId, String resource) { RoutePolicyQuery irpQuery = RoutePolicyQuery.builder() .type(type) .moduleId(moduleId) .resource(resource) .build(); List<RoutePolicyRecord> routePolicyRecords = Optional.ofNullable(routePolicyRecordService.queryRoutePolicies(irpQuery)).orElse(Collections.EMPTY_LIST); routePolicyRecordService.deleteModel(routePolicyRecords); } @Override public void updateRoutePolicyDelFlag(Long id, boolean newDelFlag, String operatorId) { RoutePolicyRecord record = getRoutePolicy(id); if (Objects.isNull(record) || Objects.equals(record.getDelFlag(), newDelFlag)) { return; } record.setDelFlag(newDelFlag); record.setOperator(operatorId); record.setOperateTime(new Date()); routePolicyRecordService.saveModel(record); TriggerType triggerType = newDelFlag ? TriggerType.DELETE : TriggerType.MODIFY; triggerGrayEvent(triggerType, record); } @Transactional @Override public int saveRoutePolicies(RouteResourcePolicies routeResourcePolicies, String operatorId, boolean needAuthority) { int count = 0; List<RoutePolicyRecord> routePolicyRecordList = new ArrayList<>(); for (String resource : routeResourcePolicies.getResources()) { for (Long policyId : routeResourcePolicies.getPolicyIds()) { RoutePolicyRecord routePolicyRecord = createRoutePolicyRecord( routeResourcePolicies.getNamespace(), routeResourcePolicies.getType(), routeResourcePolicies.getModuleId(), resource, policyId, operatorId); if (needAuthority && !hasResourceAuthority(operatorId, routePolicyRecord)) { throw new NonAuthorityException(); } int state = saveRoutePolicyRecord(routePolicyRecord); if (state > 0) { routePolicyRecordList.add(routePolicyRecord); } count++; } } routePolicyRecordList.forEach(record -> triggerGrayEvent(TriggerType.ADD, record)); return count; } @Override public RoutePolicyRecord getRoutePolicy(Long id) { return routePolicyRecordService.findOneModel(id); } @Override public boolean hasResourceAuthority(String userId, RoutePolicyRecord routePolicyRecord) { return hasResourceAuthority(routePolicyRecord.getNamespace(), userId, routePolicyRecord.toRoutePolicy()); } @Override public boolean hasResourceAuthority(String ns, String userId, RoutePolicy routePolicy) { if (!authorityModule.hasResourceAuthority(ns, userId)) { return false; } if (!Objects.equals(ns, namespaceFinder.getNamespaceCode(GrayModelType.POLICY, routePolicy.getPolicyId()))) { log.error("policy id '{}' 不属于 namespace -> '{}'", routePolicy.getPolicyId(), ns); return false; } Predicate3<String, String, RoutePolicy> authorityPredicate = getResourceAuthorityPredicate(routePolicy.getType()); if (Objects.isNull(authorityPredicate)) { log.error("没有找到Type为'{}'的权限断言器", routePolicy.getType()); return false; } return authorityPredicate.test(ns, userId, routePolicy); } @Override public void registerResourceAuthorityPredicate(String type, Predicate3<String, String, RoutePolicy> predicate) { authorityPredicate.put(type.toLowerCase(), predicate); } @Override public Predicate3<String, String, RoutePolicy> getResourceAuthorityPredicate(String type) { return authorityPredicate.get(type.toLowerCase()); } protected void triggerGrayEvent(TriggerType triggerType, RoutePolicyRecord routePolicyRecord) { triggerEvent(triggerType, routePolicyRecord); } protected void triggerEvent(TriggerType triggerType, Object source) { grayEventTrigger.triggering(source, triggerType); } /** * @param routePolicyRecord 返回时会补全Id * @return 0: 有纪录,且原纪录未删除, 1: 原先纪录, 2: 有纪录,且原纪录已删除,并已恢复 */ private int saveRoutePolicyRecord(RoutePolicyRecord routePolicyRecord) { RoutePolicyRecord record = routePolicyRecordService.find( routePolicyRecord.getType(), routePolicyRecord.getModuleId(), routePolicyRecord.getResource(), routePolicyRecord.getPolicyId()); if (Objects.nonNull(record)) { routePolicyRecord.setId(record.getId()); } RoutePolicyRecord newRecord = routePolicyRecordService.saveModel(routePolicyRecord); routePolicyRecord.setId(newRecord.getId()); if (Objects.isNull(record)) { return 1; } if (Objects.equals(record.getDelFlag(), true)) { return 2; } return 0; } private RoutePolicyRecord createRoutePolicyRecord(String ns, RoutePolicy routePolicy, String operatorId) { RoutePolicyRecord record = createRoutePolicyRecord( ns, routePolicy.getType(), routePolicy.getModuleId(), routePolicy.getResource(), routePolicy.getPolicyId(), operatorId); record.setId(routePolicy.getId()); return record; } private RoutePolicyRecord createRoutePolicyRecord( String ns, String type, String moduleId, String resource, Long policyId, String operatorId) { return RoutePolicyRecord.builder() .type(type) .namespace(ns) .moduleId(moduleId) .resource(resource) .policyId(policyId) .operator(operatorId) .operateTime(new Date()) .delFlag(false) .build(); } }
3,611
892
{ "schema_version": "1.2.0", "id": "GHSA-6925-q744-qcx6", "modified": "2022-05-17T00:01:43Z", "published": "2022-05-05T00:00:16Z", "aliases": [ "CVE-2022-23724" ], "details": "Use of static encryption key material allows forging an authentication token to other users within a tenant organization. MFA may be bypassed by redirecting an authentication flow to a target user. To exploit the vulnerability, must have compromised user credentials.", "severity": [ { "type": "CVSS_V3", "score": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:N" } ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23724" }, { "type": "WEB", "url": "https://docs.pingidentity.com/bundle/pingid/page/xqz1597139945488.html" }, { "type": "WEB", "url": "https://www.pingidentity.com/en/resources/downloads/pingid.html" } ], "database_specific": { "cwe_ids": [ "CWE-287" ], "severity": "HIGH", "github_reviewed": false } }
496
2,180
package com.xiaojukeji.kafka.manager.common.entity.ao.expert; import com.xiaojukeji.kafka.manager.common.entity.pojo.ClusterDO; import java.util.List; /** * @author zengqiao * @date 20/3/30 */ public class TopicInsufficientPartition { private ClusterDO clusterDO; private String topicName; private Integer presentPartitionNum; private Integer suggestedPartitionNum; private List<Double> maxAvgBytesInList; private Double bytesInPerPartition; private List<Integer> brokerIdList; public TopicInsufficientPartition( ClusterDO clusterDO, String topicName, Integer presentPartitionNum, Integer suggestedPartitionNum, List<Double> maxAvgBytesInList, Double bytesInPerPartition, List<Integer> brokerIdList) { this.clusterDO = clusterDO; this.topicName = topicName; this.presentPartitionNum = presentPartitionNum; this.suggestedPartitionNum = suggestedPartitionNum; this.maxAvgBytesInList = maxAvgBytesInList; this.bytesInPerPartition = bytesInPerPartition; this.brokerIdList = brokerIdList; } public ClusterDO getClusterDO() { return clusterDO; } public void setClusterDO(ClusterDO clusterDO) { this.clusterDO = clusterDO; } public String getTopicName() { return topicName; } public void setTopicName(String topicName) { this.topicName = topicName; } public Integer getPresentPartitionNum() { return presentPartitionNum; } public void setPresentPartitionNum(Integer presentPartitionNum) { this.presentPartitionNum = presentPartitionNum; } public Integer getSuggestedPartitionNum() { return suggestedPartitionNum; } public void setSuggestedPartitionNum(Integer suggestedPartitionNum) { this.suggestedPartitionNum = suggestedPartitionNum; } public List<Double> getMaxAvgBytesInList() { return maxAvgBytesInList; } public void setMaxAvgBytesInList(List<Double> maxAvgBytesInList) { this.maxAvgBytesInList = maxAvgBytesInList; } public Double getBytesInPerPartition() { return bytesInPerPartition; } public void setBytesInPerPartition(Double bytesInPerPartition) { this.bytesInPerPartition = bytesInPerPartition; } public List<Integer> getBrokerIdList() { return brokerIdList; } public void setBrokerIdList(List<Integer> brokerIdList) { this.brokerIdList = brokerIdList; } @Override public String toString() { return "TopicInsufficientPartition{" + "clusterDO=" + clusterDO + ", topicName='" + topicName + '\'' + ", presentPartitionNum=" + presentPartitionNum + ", suggestedPartitionNum=" + suggestedPartitionNum + ", maxAvgBytesInList=" + maxAvgBytesInList + ", bytesInPerPartition=" + bytesInPerPartition + ", brokerIdList=" + brokerIdList + '}'; } }
1,248
312
/******************************************************************************* * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Distribution License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/org/documents/edl-v10.php. *******************************************************************************/ package org.eclipse.rdf4j.repository.sparql.query; import org.eclipse.rdf4j.common.iteration.CloseableIteration; import org.eclipse.rdf4j.common.iteration.IterationWrapper; import org.eclipse.rdf4j.query.Binding; import org.eclipse.rdf4j.query.BindingSet; import org.eclipse.rdf4j.query.QueryEvaluationException; /** * Adds more bindings to each of the results. * * @author <NAME> */ public class InsertBindingSetCursor extends IterationWrapper<BindingSet, QueryEvaluationException> { private BindingSet bindings; public InsertBindingSetCursor(CloseableIteration<BindingSet, QueryEvaluationException> delegate, BindingSet bindings) { super(delegate); this.bindings = bindings; } @Override public BindingSet next() throws QueryEvaluationException { BindingSet next = super.next(); if (next == null) { return null; } int size = bindings.size() + next.size(); SPARQLQueryBindingSet set = new SPARQLQueryBindingSet(size); set.addAll(bindings); for (Binding binding : next) { set.setBinding(binding); } return set; } }
474
1,383
<filename>src/chrono/multicore_math/simd.h // ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2021 projectchrono.org // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: <NAME>, <NAME> // ============================================================================= #pragma once #include "chrono/core/ChApiCE.h" #include "chrono/ChConfig.h" #include "chrono/multicore_math/ChCudaDefines.h" #ifndef __CUDACC__ // Include appropriate SSE header, depending on supported level #ifdef CHRONO_HAS_SSE #ifdef CHRONO_SSE_1_0 #include <xmmintrin.h> #elif defined CHRONO_SSE_2_0 #include <emmintrin.h> #elif defined CHRONO_SSE_3_0 #include <pmmintrin.h> #elif defined CHRONO_SSE_4_1 #include <smmintrin.h> #elif defined CHRONO_SSE_4_2 #include <nmmintrin.h> #endif #endif // Include AVX header #ifdef CHRONO_HAS_AVX #include <immintrin.h> #endif // Decide whether to use AVX, SSE, or neither #if defined(CHRONO_HAS_AVX) && defined(CHRONO_SIMD_ENABLED) && defined(USE_COLLISION_DOUBLE) #define USE_AVX #undef USE_SSE #elif defined(CHRONO_HAS_SSE) && defined(CHRONO_SIMD_ENABLED) && !defined(USE_COLLISION_DOUBLE) #undef USE_AVX #define USE_SSE #else #undef USE_AVX #undef USE_SSE #endif #endif
729
5,169
<gh_stars>1000+ { "name": "JSONRPCom", "version": "0.0.4", "summary": "JSON RPC implementation", "homepage": "https://github.com/andrewBatutin/JSONRPCom", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "andrewBatutin": "<EMAIL>" }, "source": { "git": "https://github.com/andrewBatutin/JSONRPCom.git", "tag": "0.0.4" }, "source_files": "JSONRPCom/**/*", "frameworks": "Foundation", "platforms": { "ios": "5.0", "osx": "10.7" }, "requires_arc": true, "dependencies": { "Mantle": [ ] } }
263
974
// Blend2D - 2D Vector Graphics Powered by a JIT Compiler // // * Official Blend2D Home Page: https://blend2d.com // * Official Github Repository: https://github.com/blend2d/blend2d // // Copyright (c) 2017-2020 The Blend2D Authors // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. // The JPEG codec is based on stb_image <https://github.com/nothings/stb> // released into PUBLIC DOMAIN. Blend2D's JPEG codec can be distributed // under Blend2D's ZLIB license or under STB's PUBLIC DOMAIN as well. #include "../api-build_p.h" #ifdef BL_TARGET_OPT_SSE2 #include "../rgba_p.h" #include "../simd_p.h" #include "../support_p.h" #include "../codec/jpegops_p.h" // ============================================================================ // [BLJpegOps - IDCT@SSE2] // ============================================================================ struct alignas(16) BLJpegSSE2Constants { // IDCT. int16_t idct_rot0a[8], idct_rot0b[8]; int16_t idct_rot1a[8], idct_rot1b[8]; int16_t idct_rot2a[8], idct_rot2b[8]; int16_t idct_rot3a[8], idct_rot3b[8]; int32_t idct_col_bias[4]; int32_t idct_row_bias[4]; // YCbCr. int32_t ycbcr_allones[4]; int16_t ycbcr_tosigned[8]; int32_t ycbcr_round[4]; int16_t ycbcr_yycrMul[8]; int16_t ycbcr_yycbMul[8]; int16_t ycbcr_cbcrMul[8]; }; #define DATA_4X(...) { __VA_ARGS__, __VA_ARGS__, __VA_ARGS__, __VA_ARGS__ } static const BLJpegSSE2Constants blJpegSSE2Constants = { // IDCT. DATA_4X(BL_JPEG_IDCT_P_0_541196100 , BL_JPEG_IDCT_P_0_541196100 + BL_JPEG_IDCT_M_1_847759065), DATA_4X(BL_JPEG_IDCT_P_0_541196100 + BL_JPEG_IDCT_P_0_765366865 , BL_JPEG_IDCT_P_0_541196100 ), DATA_4X(BL_JPEG_IDCT_P_1_175875602 + BL_JPEG_IDCT_M_0_899976223 , BL_JPEG_IDCT_P_1_175875602 ), DATA_4X(BL_JPEG_IDCT_P_1_175875602 , BL_JPEG_IDCT_P_1_175875602 + BL_JPEG_IDCT_M_2_562915447), DATA_4X(BL_JPEG_IDCT_M_1_961570560 + BL_JPEG_IDCT_P_0_298631336 , BL_JPEG_IDCT_M_1_961570560 ), DATA_4X(BL_JPEG_IDCT_M_1_961570560 , BL_JPEG_IDCT_M_1_961570560 + BL_JPEG_IDCT_P_3_072711026), DATA_4X(BL_JPEG_IDCT_M_0_390180644 + BL_JPEG_IDCT_P_2_053119869 , BL_JPEG_IDCT_M_0_390180644 ), DATA_4X(BL_JPEG_IDCT_M_0_390180644 , BL_JPEG_IDCT_M_0_390180644 + BL_JPEG_IDCT_P_1_501321110), DATA_4X(BL_JPEG_IDCT_COL_BIAS), DATA_4X(BL_JPEG_IDCT_ROW_BIAS), // YCbCr. DATA_4X(-1), DATA_4X(-128, -128), DATA_4X(1 << (BL_JPEG_YCBCR_PREC - 1)), DATA_4X( BL_JPEG_YCBCR_FIXED(1.00000), BL_JPEG_YCBCR_FIXED(1.40200)), DATA_4X( BL_JPEG_YCBCR_FIXED(1.00000), BL_JPEG_YCBCR_FIXED(1.77200)), DATA_4X(-BL_JPEG_YCBCR_FIXED(0.34414), -BL_JPEG_YCBCR_FIXED(0.71414)) }; #undef DATA_4X #define BL_JPEG_CONST_XMM(C) (*(const Vec128I*)(blJpegSSE2Constants.C)) #define BL_JPEG_IDCT_INTERLEAVE8_XMM(a, b) { Vec128I t = a; a = _mm_unpacklo_epi8(a, b); b = _mm_unpackhi_epi8(t, b); } #define BL_JPEG_IDCT_INTERLEAVE16_XMM(a, b) { Vec128I t = a; a = _mm_unpacklo_epi16(a, b); b = _mm_unpackhi_epi16(t, b); } // out(0) = c0[even]*x + c0[odd]*y (in 16-bit, out 32-bit). // out(1) = c1[even]*x + c1[odd]*y (in 16-bit, out 32-bit). #define BL_JPEG_IDCT_ROTATE_XMM(dst0, dst1, x, y, c0, c1) \ Vec128I c0##_l = _mm_unpacklo_epi16(x, y); \ Vec128I c0##_h = _mm_unpackhi_epi16(x, y); \ \ Vec128I dst0##_l = v_madd_i16_i32(c0##_l, BL_JPEG_CONST_XMM(c0)); \ Vec128I dst0##_h = v_madd_i16_i32(c0##_h, BL_JPEG_CONST_XMM(c0)); \ Vec128I dst1##_l = v_madd_i16_i32(c0##_l, BL_JPEG_CONST_XMM(c1)); \ Vec128I dst1##_h = v_madd_i16_i32(c0##_h, BL_JPEG_CONST_XMM(c1)); // out = in << 12 (in 16-bit, out 32-bit) #define BL_JPEG_IDCT_WIDEN_XMM(dst, in) \ Vec128I dst##_l = v_sra_i32<4>(_mm_unpacklo_epi16(v_zero_i128(), in)); \ Vec128I dst##_h = v_sra_i32<4>(_mm_unpackhi_epi16(v_zero_i128(), in)); // Wide add (32-bit). #define BL_JPEG_IDCT_WADD_XMM(dst, a, b) \ Vec128I dst##_l = v_add_i32(a##_l, b##_l); \ Vec128I dst##_h = v_add_i32(a##_h, b##_h); // Wide sub (32-bit). #define BL_JPEG_IDCT_WSUB_XMM(dst, a, b) \ Vec128I dst##_l = v_sub_i32(a##_l, b##_l); \ Vec128I dst##_h = v_sub_i32(a##_h, b##_h); // Butterfly a/b, add bias, then shift by `norm` and pack to 16-bit. #define BL_JPEG_IDCT_BFLY_XMM(dst0, dst1, a, b, bias, norm) { \ Vec128I abiased_l = v_add_i32(a##_l, bias); \ Vec128I abiased_h = v_add_i32(a##_h, bias); \ \ BL_JPEG_IDCT_WADD_XMM(sum, abiased, b) \ BL_JPEG_IDCT_WSUB_XMM(diff, abiased, b) \ \ dst0 = v_packs_i32_i16(v_sra_i32<norm>(sum_l), v_sra_i32<norm>(sum_h)); \ dst1 = v_packs_i32_i16(v_sra_i32<norm>(diff_l), v_sra_i32<norm>(diff_h)); \ } #define BL_JPEG_IDCT_IDCT_PASS_XMM(bias, norm) { \ /* Even part. */ \ BL_JPEG_IDCT_ROTATE_XMM(t2e, t3e, row2, row6, idct_rot0a, idct_rot0b) \ \ Vec128I sum04 = _mm_add_epi16(row0, row4); \ Vec128I dif04 = _mm_sub_epi16(row0, row4); \ \ BL_JPEG_IDCT_WIDEN_XMM(t0e, sum04) \ BL_JPEG_IDCT_WIDEN_XMM(t1e, dif04) \ \ BL_JPEG_IDCT_WADD_XMM(x0, t0e, t3e) \ BL_JPEG_IDCT_WSUB_XMM(x3, t0e, t3e) \ BL_JPEG_IDCT_WADD_XMM(x1, t1e, t2e) \ BL_JPEG_IDCT_WSUB_XMM(x2, t1e, t2e) \ \ /* Odd part */ \ BL_JPEG_IDCT_ROTATE_XMM(y0o, y2o, row7, row3, idct_rot2a, idct_rot2b) \ BL_JPEG_IDCT_ROTATE_XMM(y1o, y3o, row5, row1, idct_rot3a, idct_rot3b) \ Vec128I sum17 = _mm_add_epi16(row1, row7); \ Vec128I sum35 = _mm_add_epi16(row3, row5); \ BL_JPEG_IDCT_ROTATE_XMM(y4o,y5o, sum17, sum35, idct_rot1a, idct_rot1b) \ \ BL_JPEG_IDCT_WADD_XMM(x4, y0o, y4o) \ BL_JPEG_IDCT_WADD_XMM(x5, y1o, y5o) \ BL_JPEG_IDCT_WADD_XMM(x6, y2o, y5o) \ BL_JPEG_IDCT_WADD_XMM(x7, y3o, y4o) \ \ BL_JPEG_IDCT_BFLY_XMM(row0, row7, x0, x7, bias, norm) \ BL_JPEG_IDCT_BFLY_XMM(row1, row6, x1, x6, bias, norm) \ BL_JPEG_IDCT_BFLY_XMM(row2, row5, x2, x5, bias, norm) \ BL_JPEG_IDCT_BFLY_XMM(row3, row4, x3, x4, bias, norm) \ } void BL_CDECL blJpegIDCT8_SSE2(uint8_t* dst, intptr_t dstStride, const int16_t* src, const uint16_t* qTable) noexcept { using namespace SIMD; // Load and dequantize (`src` is aligned to 16 bytes, `qTable` doesn't have to be). Vec128I row0 = v_mul_i16(v_loadu_i128(qTable + 0), *(const Vec128I*)(src + 0)); Vec128I row1 = v_mul_i16(v_loadu_i128(qTable + 8), *(const Vec128I*)(src + 8)); Vec128I row2 = v_mul_i16(v_loadu_i128(qTable + 16), *(const Vec128I*)(src + 16)); Vec128I row3 = v_mul_i16(v_loadu_i128(qTable + 24), *(const Vec128I*)(src + 24)); Vec128I row4 = v_mul_i16(v_loadu_i128(qTable + 32), *(const Vec128I*)(src + 32)); Vec128I row5 = v_mul_i16(v_loadu_i128(qTable + 40), *(const Vec128I*)(src + 40)); Vec128I row6 = v_mul_i16(v_loadu_i128(qTable + 48), *(const Vec128I*)(src + 48)); Vec128I row7 = v_mul_i16(v_loadu_i128(qTable + 56), *(const Vec128I*)(src + 56)); // IDCT columns. BL_JPEG_IDCT_IDCT_PASS_XMM(BL_JPEG_CONST_XMM(idct_col_bias), BL_JPEG_IDCT_COL_NORM) // Transpose. BL_JPEG_IDCT_INTERLEAVE16_XMM(row0, row4) // [a0a4|b0b4|c0c4|d0d4] | [e0e4|f0f4|g0g4|h0h4] BL_JPEG_IDCT_INTERLEAVE16_XMM(row2, row6) // [a2a6|b2b6|c2c6|d2d6] | [e2e6|f2f6|g2g6|h2h6] BL_JPEG_IDCT_INTERLEAVE16_XMM(row1, row5) // [a1a5|b1b5|c2c5|d1d5] | [e1e5|f1f5|g1g5|h1h5] BL_JPEG_IDCT_INTERLEAVE16_XMM(row3, row7) // [a3a7|b3b7|c3c7|d3d7] | [e3e7|f3f7|g3g7|h3h7] BL_JPEG_IDCT_INTERLEAVE16_XMM(row0, row2) // [a0a2|a4a6|b0b2|b4b6] | [c0c2|c4c6|d0d2|d4d6] BL_JPEG_IDCT_INTERLEAVE16_XMM(row1, row3) // [a1a3|a5a7|b1b3|b5b7] | [c1c3|c5c7|d1d3|d5d7] BL_JPEG_IDCT_INTERLEAVE16_XMM(row4, row6) // [e0e2|e4e6|f0f2|f4f6] | [g0g2|g4g6|h0h2|h4h6] BL_JPEG_IDCT_INTERLEAVE16_XMM(row5, row7) // [e1e3|e5e7|f1f3|f5f7] | [g1g3|g5g7|h1h3|h5h7] BL_JPEG_IDCT_INTERLEAVE16_XMM(row0, row1) // [a0a1|a2a3|a4a5|a6a7] | [b0b1|b2b3|b4b5|b6b7] BL_JPEG_IDCT_INTERLEAVE16_XMM(row2, row3) // [c0c1|c2c3|c4c5|c6c7] | [d0d1|d2d3|d4d5|d6d7] BL_JPEG_IDCT_INTERLEAVE16_XMM(row4, row5) // [e0e1|e2e3|e4e5|e6e7] | [f0f1|f2f3|f4f5|f6f7] BL_JPEG_IDCT_INTERLEAVE16_XMM(row6, row7) // [g0g1|g2g3|g4g5|g6g7] | [h0h1|h2h3|h4h5|h6h7] // IDCT rows. BL_JPEG_IDCT_IDCT_PASS_XMM(BL_JPEG_CONST_XMM(idct_row_bias), BL_JPEG_IDCT_ROW_NORM) // Pack to 8-bit unsigned integers with saturation. row0 = v_packs_i16_u8(row0, row1); // [a0a1a2a3|a4a5a6a7|b0b1b2b3|b4b5b6b7] row2 = v_packs_i16_u8(row2, row3); // [c0c1c2c3|c4c5c6c7|d0d1d2d3|d4d5d6d7] row4 = v_packs_i16_u8(row4, row5); // [e0e1e2e3|e4e5e6e7|f0f1f2f3|f4f5f6f7] row6 = v_packs_i16_u8(row6, row7); // [g0g1g2g3|g4g5g6g7|h0h1h2h3|h4h5h6h7] // Transpose. BL_JPEG_IDCT_INTERLEAVE8_XMM(row0, row4) // [a0e0a1e1|a2e2a3e3|a4e4a5e5|a6e6a7e7] | [b0f0b1f1|b2f2b3f3|b4f4b5f5|b6f6b7f7] BL_JPEG_IDCT_INTERLEAVE8_XMM(row2, row6) // [c0g0c1g1|c2g2c3g3|c4g4c5g5|c6g6c7g7] | [d0h0d1h1|d2h2d3h3|d4h4d5h5|d6h6d7h7] BL_JPEG_IDCT_INTERLEAVE8_XMM(row0, row2) // [a0c0e0g0|a1c1e1g1|a2c2e2g2|a3c3e3g3] | [a4c4e4g4|a5c5e5g5|a6c6e6g6|a7c7e7g7] BL_JPEG_IDCT_INTERLEAVE8_XMM(row4, row6) // [b0d0f0h0|b1d1f1h1|b2d2f2h2|b3d3f3h3| | [b4d4f4h4|b5d5f5h5|b6d6f6h6|b7d7f7h7] BL_JPEG_IDCT_INTERLEAVE8_XMM(row0, row4) // [a0b0c0d0|e0f0g0h0|a1b1c1d1|e1f1g1h1] | [a2b2c2d2|e2f2g2h2|a3b3c3d3|e3f3g3h3] BL_JPEG_IDCT_INTERLEAVE8_XMM(row2, row6) // [a4b4c4d4|e4f4g4h4|a5b5c5d5|e5f5g5h5] | [a6b6c6d6|e6f6g6h6|a7b7c7d7|e7f7g7h7] // Store. uint8_t* dst0 = dst; uint8_t* dst1 = dst + dstStride; intptr_t dstStride2 = dstStride * 2; v_storel_i64(dst0, row0); dst0 += dstStride2; v_storeh_i64(dst1, row0); dst1 += dstStride2; v_storel_i64(dst0, row4); dst0 += dstStride2; v_storeh_i64(dst1, row4); dst1 += dstStride2; v_storel_i64(dst0, row2); dst0 += dstStride2; v_storeh_i64(dst1, row2); dst1 += dstStride2; v_storel_i64(dst0, row6); v_storeh_i64(dst1, row6); } // ============================================================================ // [BLJpegOps - RGB32FromYCbCr8@SSE2] // ============================================================================ void BL_CDECL blJpegRGB32FromYCbCr8_SSE2(uint8_t* dst, const uint8_t* pY, const uint8_t* pCb, const uint8_t* pCr, uint32_t count) noexcept { using namespace SIMD; uint32_t i = count; while (i >= 8) { Vec128I yy = _mm_loadl_epi64(reinterpret_cast<const __m128i*>(pY)); Vec128I cb = _mm_loadl_epi64(reinterpret_cast<const __m128i*>(pCb)); Vec128I cr = _mm_loadl_epi64(reinterpret_cast<const __m128i*>(pCr)); yy = v_unpack_lo_u8_u16(yy); cb = v_add_i16(v_unpack_lo_u8_u16(cb), BL_JPEG_CONST_XMM(ycbcr_tosigned)); cr = v_add_i16(v_unpack_lo_u8_u16(cr), BL_JPEG_CONST_XMM(ycbcr_tosigned)); Vec128I r_l = v_madd_i16_i32(_mm_unpacklo_epi16(yy, cr), BL_JPEG_CONST_XMM(ycbcr_yycrMul)); Vec128I r_h = v_madd_i16_i32(_mm_unpackhi_epi16(yy, cr), BL_JPEG_CONST_XMM(ycbcr_yycrMul)); Vec128I b_l = v_madd_i16_i32(_mm_unpacklo_epi16(yy, cb), BL_JPEG_CONST_XMM(ycbcr_yycbMul)); Vec128I b_h = v_madd_i16_i32(_mm_unpackhi_epi16(yy, cb), BL_JPEG_CONST_XMM(ycbcr_yycbMul)); Vec128I g_l = v_madd_i16_i32(_mm_unpacklo_epi16(cb, cr), BL_JPEG_CONST_XMM(ycbcr_cbcrMul)); Vec128I g_h = v_madd_i16_i32(_mm_unpackhi_epi16(cb, cr), BL_JPEG_CONST_XMM(ycbcr_cbcrMul)); g_l = v_add_i32(g_l, v_sll_i32<BL_JPEG_YCBCR_PREC>(v_unpack_lo_u16_u32(yy))); g_h = v_add_i32(g_h, v_sll_i32<BL_JPEG_YCBCR_PREC>(v_unpack_hi_u16_u32(yy))); r_l = v_add_i32(r_l, BL_JPEG_CONST_XMM(ycbcr_round)); r_h = v_add_i32(r_h, BL_JPEG_CONST_XMM(ycbcr_round)); b_l = v_add_i32(b_l, BL_JPEG_CONST_XMM(ycbcr_round)); b_h = v_add_i32(b_h, BL_JPEG_CONST_XMM(ycbcr_round)); g_l = v_add_i32(g_l, BL_JPEG_CONST_XMM(ycbcr_round)); g_h = v_add_i32(g_h, BL_JPEG_CONST_XMM(ycbcr_round)); r_l = v_sra_i32<BL_JPEG_YCBCR_PREC>(r_l); r_h = v_sra_i32<BL_JPEG_YCBCR_PREC>(r_h); b_l = v_sra_i32<BL_JPEG_YCBCR_PREC>(b_l); b_h = v_sra_i32<BL_JPEG_YCBCR_PREC>(b_h); g_l = v_sra_i32<BL_JPEG_YCBCR_PREC>(g_l); g_h = v_sra_i32<BL_JPEG_YCBCR_PREC>(g_h); __m128i r = v_packz_u32_u8(r_l, r_h); __m128i g = v_packz_u32_u8(g_l, g_h); __m128i b = v_packz_u32_u8(b_l, b_h); __m128i ra = v_interleave_lo_i8(r, BL_JPEG_CONST_XMM(ycbcr_allones)); __m128i bg = v_interleave_lo_i8(b, g); __m128i bgra0 = v_interleave_lo_i16(bg, ra); __m128i bgra1 = v_interleave_hi_i16(bg, ra); _mm_storeu_si128(reinterpret_cast<__m128i*>(dst + 0), bgra0); _mm_storeu_si128(reinterpret_cast<__m128i*>(dst + 16), bgra1); dst += 32; pY += 8; pCb += 8; pCr += 8; i -= 8; } while (i) { int yy = (int(pY[0]) << BL_JPEG_YCBCR_PREC) + (1 << (BL_JPEG_YCBCR_PREC - 1)); int cr = int(pCr[0]) - 128; int cb = int(pCb[0]) - 128; int r = yy + cr * BL_JPEG_YCBCR_FIXED(1.40200); int g = yy - cr * BL_JPEG_YCBCR_FIXED(0.71414) - cb * BL_JPEG_YCBCR_FIXED(0.34414); int b = yy + cb * BL_JPEG_YCBCR_FIXED(1.77200); uint32_t rgba32 = blRgba32Pack( blClampToByte(r >> BL_JPEG_YCBCR_PREC), blClampToByte(g >> BL_JPEG_YCBCR_PREC), blClampToByte(b >> BL_JPEG_YCBCR_PREC)); blMemWriteU32a(dst, rgba32); dst += 4; pY += 1; pCb += 1; pCr += 1; i -= 1; } } #endif
7,987
303
<gh_stars>100-1000 /* Copyright (C) 2005-2011 <NAME> */ package com.lightcrafts.ui.operation; /** * Notify listeners of changes to the selection state in an OpStack. */ public interface OpStackListener { /** * A new OpControl has appeared. * @param control */ void opAdded(OpControl control); /** * A preexisting OpControl has become selected. * @param control The selected OpControl. */ void opChanged(OpControl control); /** * The current selection is not an OpControl. * @param control The current SelectedControl. */ void opChanged(SelectableControl control); /** * The current selection has toggled between locked and unlocked. */ void opLockChanged(OpControl control); /** * An OpControl has been deleted. */ void opRemoved(OpControl control); }
295
701
#pragma once #include <brutal/base.h> #include <stdint.h> #define EXT2_SIGNATURE 0xef53 #define EXT2_SUPER_BLOCK_BASE 1024 #define EXT2_SUPER_BLOCK_SIZE 1024 typedef enum { EXT2_STATE_CLEAN = 1, EXT2_STATE_ERROR = 2, } Ext2FsState; typedef enum { EXT2_ERROR_IGNORE = 1, EXT2_ERROR_REMOUNT_IN_RO = 2, EXT2_ERROR_KERNEL_PANIC = 3, } Ext2FsErrorHandling; typedef enum { EXT2_OS_LINUX = 0, EXT2_OS_HURD = 1, EXT2_OS_MASIX = 2, EXT2_OS_FREEBSD = 3, EXT2_OS_LITES = 4, /* EXT2_OS_BRUTAL = 5, one day maybe ? */ } Ext2FsOSId; typedef enum { EXT2_FEAT_RESERVE_BLOCK = 1 << 0, EXT2_FEAT_AFS_SERVER = 1 << 1, EXT2_FEAT_JOURNAL = 1 << 2, EXT2_FEAT_EXTENDED_INODE_ATTRIBUTES = 1 << 3, EXT2_FEAT_RESIZABLE_FS = 1 << 4, EXT2_FEAT_HASH_IDX = 1 << 5, } Ext2OptionalFeatures; typedef enum { EXT2_FEAT_COMPRESSION = 1 << 0, EXT2_FEAT_TYPE_DIRECTORY = 1 << 1, EXT2_FEAT_JOURNAL_REPLAY = 1 << 2, EXT2_FEAT_JOURNAL_DEVICE = 1 << 3, } Ext2RequiredFeatures; typedef enum { EXT2_FEAT_SPARSE_BLOCKS = 1 << 0, EXT2_FEAT_64BIT_FILE_SIZE = 1 << 1, EXT2_FEAT_BINARY_TREE_STORAGE = 1 << 2, } Ext2ReadOnlyFeatures; typedef struct { uint32_t inode_count; uint32_t block_count; uint32_t reserved_block_count; uint32_t free_block_count; uint32_t free_inode_count; uint32_t super_block_id; uint32_t block_size; // real block size = 2 ** (10 + value) uint32_t fragment_size; // same formula as block_size uint32_t group_block_count; uint32_t group_fragment_count; uint32_t group_inode_count; uint32_t last_mount_time; uint32_t last_write_time; uint16_t mount_count_since_last_check; uint16_t mount_count_before_check; uint16_t signature; uint16_t fs_state; uint16_t error_handling; uint16_t version_minor; uint32_t time_since_last_check; uint32_t time_before_forced_check; uint32_t creator_os_id; uint32_t version_major; uint16_t user_id_reserved_block; uint16_t group_id_reserved_block; // only exist if major version is greater or equal to 1 uint32_t first_non_reserved_inode; uint16_t inode_size; uint16_t superblock_group_location; uint32_t optional_features; uint32_t required_features; uint32_t read_only_feature; uint8_t file_system_id[16]; uint8_t volume_name[16]; uint8_t mount_path[64]; uint32_t compression_algorithm; uint8_t preallocated_file_block_count; uint8_t preallocated_dir_block_count; uint16_t _unused; uint8_t journal_id[16]; uint32_t journal_inode; uint32_t journal_device; uint32_t orphaned_inode_list; uint8_t _unused2[788]; } Ext2SuperBlock; typedef struct { uint32_t block_usage_bitmap_addr; uint32_t inode_usage_bitmap_addr; uint32_t inode_table_addr; uint16_t unallocated_block_count; uint16_t unallocated_inodes_count; uint16_t dir_count; uint16_t _reserved[7]; } Ext2GroupBlockDescTable; typedef enum { EXT2_INODE_FIFO = 0x1, EXT2_INODE_CHARDEV = 0x2, EXT2_INODE_DIRECTORY = 0x4, EXT2_INODE_BLOCK_DEVICE = 0x6, EXT2_INODE_REGULAR_FILE = 0x8, EXT2_INODE_LINK = 0xA, EXT2_INODE_UNIX_SOCKET = 0xC, } Ext2InodeType; typedef struct PACKED { uint16_t mode; uint16_t user_id; uint32_t size_low; uint32_t last_access_time; uint32_t creation_time; uint32_t last_modification_time; uint32_t deletion_time; uint16_t group_id; uint16_t directory_count; uint32_t disk_sector_usage_count; uint32_t flags; uint32_t os_specific_value; uint32_t blocks_ptr[12]; uint32_t single_indirect_block_ptr; uint32_t double_indirect_block_ptr; uint32_t triple_indirect_block_ptr; uint32_t generation_number; uint32_t extended_attribute_block; uint32_t size_upper; uint32_t fragment_addr; uint8_t os_specific_2[12]; } Ext2InodeBlock; typedef enum { EXT2_FT_UNKOWN = 0, EXT2_FT_REGULAR_FILE = 1, EXT2_FT_DIRECTORY = 2, EXT2_FT_CHARDEV = 3, EXT2_FT_BLOCK_DEV = 4, EXT2_FT_FIFO = 5, EXT2_FT_SOCKET = 6, EXT2_FT_SYMLINK = 7, } Ext2FileType; typedef struct { uint32_t inode; uint16_t size; uint8_t name_len; uint8_t type; uint8_t name_chars[255]; } Ext2Directory; void ext2_dump_superblock(Ext2SuperBlock *superblock); void ext2_dump_inodeblock(Ext2InodeBlock *block);
2,100
435
{ "alias": "video/2238/python-ruby-go-oh-my", "category": "PyCon AU 2013", "copyright_text": "CC-BY-SA", "description": "", "duration": 30, "id": 2238, "language": "eng", "quality_notes": "", "recorded": "2013-07-07", "slug": "python-ruby-go-oh-my", "speakers": [ "<NAME>" ], "summary": "Brett covers the things that excite him about each of Python, Ruby and\nGo. He covers some of cool stuff he's seen lately, some of the lessons\nlearned from different ecosystems, and more specifically where he thinks\nPython could improve, or what it excels at.\n", "tags": [], "thumbnail_url": "https://i1.ytimg.com/vi/9rjTDfZqgq4/hqdefault.jpg", "title": "Python? Ruby? Go? Oh My!", "videos": [ { "type": "mp4", "url": "http://s3.us.archive.org/ndvpyconau2013/Python_Ruby_Go_Oh_My.mp4" }, { "length": 0, "type": "youtube", "url": "https://www.youtube.com/watch?v=9rjTDfZqgq4" } ] }
406
677
/* * Copyright (C) 2016 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "B3DuplicateTails.h" #if ENABLE(B3_JIT) #include "B3BasicBlockInlines.h" #include "B3BreakCriticalEdges.h" #include "B3Dominators.h" #include "B3FixSSA.h" #include "B3InsertionSetInlines.h" #include "B3PhaseScope.h" #include "B3ProcedureInlines.h" #include "B3SwitchValue.h" #include "B3UpsilonValue.h" #include "B3ValueInlines.h" #include <wtf/IndexSet.h> namespace JSC { namespace B3 { namespace { const bool verbose = false; class DuplicateTails { public: DuplicateTails(Procedure& proc) : m_proc(proc) , m_insertionSet(proc) , m_maxSize(Options::maxB3TailDupBlockSize()) , m_maxSuccessors(Options::maxB3TailDupBlockSuccessors()) { } void run() { // Breaking critical edges introduces blocks that jump to things. Those Jumps' successors // become candidates for tail duplication. Prior to critical edge breaking, some of those // Jumps would have been Branches, and so no tail duplication would have happened. breakCriticalEdges(m_proc); // Find blocks that would be candidates for tail duplication. They must be small enough // and they much not have too many successors. m_proc.resetValueOwners(); IndexSet<BasicBlock*> candidates; for (BasicBlock* block : m_proc) { if (block->size() > m_maxSize) continue; if (block->numSuccessors() > m_maxSuccessors) continue; if (block->last()->type() != Void) // Demoting doesn't handle terminals with values. continue; candidates.add(block); } // Collect the set of values that must be de-SSA'd. IndexSet<Value*> valuesToDemote; for (BasicBlock* block : m_proc) { for (Value* value : *block) { if (value->opcode() == Phi && candidates.contains(block)) valuesToDemote.add(value); for (Value* child : value->children()) { if (child->owner != block && candidates.contains(child->owner)) valuesToDemote.add(child); } } } demoteValues(m_proc, valuesToDemote); if (verbose) { dataLog("Procedure after value demotion:\n"); dataLog(m_proc); } for (BasicBlock* block : m_proc) { if (block->last()->opcode() != Jump) continue; BasicBlock* tail = block->successorBlock(0); if (!candidates.contains(tail)) continue; // Don't tail duplicate a trivial self-loop, because the code below can't handle block and // tail being the same block. if (block == tail) continue; // We're about to change 'block'. Make sure that nobody duplicates block after this // point. candidates.remove(block); if (verbose) dataLog("Duplicating ", *tail, " into ", *block, "\n"); block->removeLast(m_proc); HashMap<Value*, Value*> map; for (Value* value : *tail) { Value* clone = m_proc.clone(value); for (Value*& child : clone->children()) { if (Value* replacement = map.get(child)) child = replacement; } if (value->type() != Void) map.add(value, clone); block->append(clone); } block->successors() = tail->successors(); } m_proc.resetReachability(); m_proc.invalidateCFG(); } private: Procedure& m_proc; InsertionSet m_insertionSet; unsigned m_maxSize; unsigned m_maxSuccessors; }; } // anonymous namespace void duplicateTails(Procedure& proc) { PhaseScope phaseScope(proc, "duplicateTails"); DuplicateTails duplicateTails(proc); duplicateTails.run(); } } } // namespace JSC::B3 #endif // ENABLE(B3_JIT)
2,276
892
<filename>advisories/github-reviewed/2021/09/GHSA-22gh-3r9q-xf38/GHSA-22gh-3r9q-xf38.json<gh_stars>100-1000 { "schema_version": "1.2.0", "id": "GHSA-22gh-3r9q-xf38", "modified": "2021-10-21T14:26:23Z", "published": "2021-09-20T19:53:30Z", "aliases": [ "CVE-2021-39214" ], "summary": "Lacking Protection against HTTP Request Smuggling in mitmproxy", "details": "### Impact\n\nIn mitmproxy 7.0.2 and below, a malicious client or server is able to perform [HTTP request smuggling](https://en.wikipedia.org/wiki/HTTP_request_smuggling) attacks through mitmproxy. This means that a malicious client/server could smuggle a request/response through mitmproxy as part of another request/response's HTTP message body. While mitmproxy would only see one request, the target server would see multiple requests. A smuggled request is still captured as part of another request's body, but it does not appear in the request list and does not go through the usual mitmproxy event hooks, where users may have implemented custom access control checks or input sanitization.\n\nUnless you use mitmproxy to protect an HTTP/1 service, no action is required.\n\n\n### Patches\n\nThe vulnerability has been fixed in mitmproxy 7.0.3 and above.\n\n\n### Acknowledgements\n\nWe thank <NAME> (@chinchila) for responsibly disclosing this vulnerability to the mitmproxy team.\n\n\n### Timeline\n\n- **2021-09-08**: Received initial report for mitmproxy <= 6.0.2.\n- **2021-09-08**: Requested clarification if 7.x is affected.\n- **2021-09-10**: Received additional details, 7.x situation still unclear.\n- **2021-09-13**: Internally determined that 7.x is also affected.\n- **2021-09-13**: Shared initial fix with researcher.\n- **2021-09-14**: Received confirmation that fix is working, but H2.TE/H2.CL should also be looked at.\n- **2021-09-14**: Shared revised fix that includes additional H2.TE mitigations.\n- **2021-09-14**: Received confirmation that revised fix is working.\n- **2021-09-16**: Completed internal patch review.\n- **2021-09-16**: Published patch release and advisory.", "severity": [ { "type": "CVSS_V3", "score": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:H" } ], "affected": [ { "package": { "ecosystem": "PyPI", "name": "mitmproxy" }, "ranges": [ { "type": "ECOSYSTEM", "events": [ { "introduced": "0" }, { "fixed": "7.0.3" } ] } ] } ], "references": [ { "type": "WEB", "url": "https://github.com/mitmproxy/mitmproxy/security/advisories/GHSA-22gh-3r9q-xf38" }, { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2021-39214" }, { "type": "PACKAGE", "url": "https://github.com/mitmproxy/mitmproxy" } ], "database_specific": { "cwe_ids": [ "CWE-444" ], "severity": "HIGH", "github_reviewed": true } }
1,239
379
<filename>client/oim-client-base/src/main/java/com/onlyxiahui/im/bean/UserCategoryMember.java package com.onlyxiahui.im.bean; /** * 描述:好友分组成员 * * @author XiaHui * @date 2014-06-15 2:32:18 * @version 0.0.1 */ public class UserCategoryMember implements CategoryMember { private String id; private String ownUserId; private String userCategoryId; private String memberUserId; private String remark; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getOwnUserId() { return ownUserId; } public void setOwnUserId(String ownUserId) { this.ownUserId = ownUserId; } public String getUserCategoryId() { return userCategoryId; } public void setUserCategoryId(String userCategoryId) { this.userCategoryId = userCategoryId; } public String getMemberUserId() { return memberUserId; } public void setMemberUserId(String memberUserId) { this.memberUserId = memberUserId; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } @Override public String getCategoryId() { return this.getUserCategoryId(); } @Override public String getMemberId() { return this.getMemberUserId(); } }
450
2,206
/* * * Copyright (c) 2006-2020, Speedment, 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. */ package com.speedment.test.connector.support; import com.speedment.runtime.config.Dbms; import com.speedment.runtime.config.DbmsUtil; import com.speedment.runtime.config.trait.HasNameUtil; import java.util.HashMap; import java.util.Map; public final class Dummies { private Dummies() { } public static Dbms dbms() { final Map<String, Object> data = new HashMap<>(); data.put(DbmsUtil.IP_ADDRESS, "localhost"); data.put(DbmsUtil.PORT, 3066); data.put(DbmsUtil.USERNAME, "username"); data.put(DbmsUtil.SERVER_NAME, "server"); data.put(HasNameUtil.NAME, "name"); return Dbms.create(null, data); } }
449
834
// Copyright 2004-present Facebook. All Rights Reserved. #pragma once #include "fboss/agent/platforms/common/PlatformMapping.h" namespace facebook::fboss { class Wedge400CEbbLabPlatformMapping : public PlatformMapping { public: Wedge400CEbbLabPlatformMapping(); private: Wedge400CEbbLabPlatformMapping(Wedge400CEbbLabPlatformMapping const&) = delete; Wedge400CEbbLabPlatformMapping& operator=( Wedge400CEbbLabPlatformMapping const&) = delete; }; } // namespace facebook::fboss
164
2,151
<gh_stars>1000+ // 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 <fcntl.h> #include <string.h> #include <unistd.h> #include <fstream> #include <iostream> #include <string> #include <vector> #include "tools/cddl/codegen.h" #include "tools/cddl/logging.h" #include "tools/cddl/parse.h" #include "tools/cddl/sema.h" std::string ReadEntireFile(const std::string& filename) { std::ifstream input(filename); if (!input) { return {}; } input.seekg(0, std::ios_base::end); size_t length = input.tellg(); std::string input_data(length + 1, 0); input.seekg(0, std::ios_base::beg); input.read(const_cast<char*>(input_data.data()), length); input_data[length] = 0; return input_data; } struct CommandLineArguments { std::string header_filename; std::string cc_filename; std::string gen_dir; std::string cddl_filename; }; CommandLineArguments ParseCommandLineArguments(int argc, char** argv) { --argc; ++argv; CommandLineArguments result; while (argc) { if (strcmp(*argv, "--header") == 0) { // Parse the filename of the output header file. This is also the name // that will be used for the include guard and as the include path in the // source file. if (!result.header_filename.empty()) { return {}; } if (!argc) { return {}; } --argc; ++argv; result.header_filename = *argv; } else if (strcmp(*argv, "--cc") == 0) { // Parse the filename of the output source file. if (!result.cc_filename.empty()) { return {}; } if (!argc) { return {}; } --argc; ++argv; result.cc_filename = *argv; } else if (strcmp(*argv, "--gen-dir") == 0) { // Parse the directory prefix that should be added to the output header. // and source file if (!result.gen_dir.empty()) { return {}; } if (!argc) { return {}; } --argc; ++argv; result.gen_dir = *argv; } else if (!result.cddl_filename.empty()) { return {}; } else { // The input file which contains the CDDL spec. result.cddl_filename = *argv; } --argc; ++argv; } // If one of the required properties is missed, return empty. Else, return // generated struct. if (result.header_filename.empty() || result.cc_filename.empty() || result.gen_dir.empty() || result.cddl_filename.empty()) { return {}; } return result; } int main(int argc, char** argv) { // Parse and validate all cmdline arguments. CommandLineArguments args = ParseCommandLineArguments(argc, argv); if (args.cddl_filename.empty()) { std::cerr << "Usage: " << std::endl << "cddl --header parsed.h --cc parsed.cc --gen-dir " "output/generated input.cddl" << std::endl << "All flags are required." << std::endl << "Example: " << std::endl << "./cddl --header osp_messages.h --cc osp_messages.cc " "--gen-dir gen/msgs ../../msgs/osp_messages.cddl" << std::endl; return 1; } size_t pos = args.cddl_filename.find_last_of('.'); if (pos == std::string::npos) { return 1; } // Validate and open the provided header file. std::string header_filename = args.gen_dir + "/" + args.header_filename; int header_fd = open(header_filename.c_str(), O_CREAT | O_TRUNC | O_WRONLY, S_IRUSR | S_IWUSR | S_IRGRP); if (header_fd == -1) { std::cerr << "failed to open " << args.header_filename << std::endl; return 1; } // Validate and open the provided output source file. std::string cc_filename = args.gen_dir + "/" + args.cc_filename; int cc_fd = open(cc_filename.c_str(), O_CREAT | O_TRUNC | O_WRONLY, S_IRUSR | S_IWUSR | S_IRGRP); if (cc_fd == -1) { std::cerr << "failed to open " << args.cc_filename << std::endl; return 1; } // Read and parse the CDDL spec file. std::string data = ReadEntireFile(args.cddl_filename); if (data.empty()) { return 1; } Logger::Log("Successfully initialized CDDL Code generator!"); // Parse the full CDDL into a graph structure. Logger::Log("Parsing CDDL input file..."); ParseResult parse_result = ParseCddl(data); if (!parse_result.root) { Logger::Error("Failed to parse CDDL input file"); return 1; } Logger::Log("Successfully parsed CDDL input file!"); // Build the Symbol table from this graph structure. Logger::Log("Generating CDDL Symbol Table..."); std::pair<bool, CddlSymbolTable> cddl_result = BuildSymbolTable(*parse_result.root); if (!cddl_result.first) { Logger::Error("Failed to generate CDDL symbol table"); return 1; } Logger::Log("Successfully generated CDDL symbol table!"); Logger::Log("Generating CPP symbol table..."); std::pair<bool, CppSymbolTable> cpp_result = BuildCppTypes(cddl_result.second); if (!cpp_result.first) { Logger::Error("Failed to generate CPP symbol table"); return 1; } Logger::Log("Successfully generated CPP symbol table!"); // Validate that the provided CDDL doesnt have duplicated indices. if (!ValidateCppTypes(cpp_result.second)) { return 1; } // Create the C++ files from the Symbol table. Logger::Log("Writing Header prologue..."); if (!WriteHeaderPrologue(header_fd, args.header_filename)) { Logger::Error("WriteHeaderPrologue failed"); return 1; } Logger::Log("Successfully wrote header prologue!"); Logger::Log("Writing type definitions..."); if (!WriteTypeDefinitions(header_fd, &cpp_result.second)) { Logger::Error("WriteTypeDefinitions failed"); return 1; } Logger::Log("Successfully wrote type definitions!"); Logger::Log("Writing function declaration..."); if (!WriteFunctionDeclarations(header_fd, &cpp_result.second)) { Logger::Error("WriteFunctionDeclarations failed"); return 1; } Logger::Log("Successfully wrote function declarations!"); Logger::Log("Writing header epilogue..."); if (!WriteHeaderEpilogue(header_fd, args.header_filename)) { Logger::Error("WriteHeaderEpilogue failed"); return 1; } Logger::Log("Successfully wrote header epilogue!"); Logger::Log("Writing source prologue..."); if (!WriteSourcePrologue(cc_fd, args.header_filename)) { Logger::Error("WriteSourcePrologue failed"); return 1; } Logger::Log("Successfully wrote source prologue!"); Logger::Log("Writing encoders..."); if (!WriteEncoders(cc_fd, &cpp_result.second)) { Logger::Error("WriteEncoders failed"); return 1; } Logger::Log("Successfully wrote encoders!"); Logger::Log("Writing decoders..."); if (!WriteDecoders(cc_fd, &cpp_result.second)) { Logger::Error("WriteDecoders failed"); return 1; } Logger::Log("Successfully wrote decoders!"); Logger::Log("Writing equality operators..."); if (!WriteEqualityOperators(cc_fd, &cpp_result.second)) { Logger::Error("WriteStructEqualityOperators failed"); return 1; } Logger::Log("Successfully wrote equality operators!"); Logger::Log("Writing source epilogue..."); if (!WriteSourceEpilogue(cc_fd)) { Logger::Error("WriteSourceEpilogue failed"); return 1; } Logger::Log("Successfully wrote source epilogue!"); close(header_fd); close(cc_fd); Logger::Log("SUCCESSFULLY COMPLETED ALL OPERATIONS"); return 0; }
2,916
420
<gh_stars>100-1000 # Copyright (c) 2012-2019 Seafile Ltd. # encoding: utf-8 from django.conf import settings ENABLE_WEIXIN = getattr(settings, 'ENABLE_WEIXIN', False) WEIXIN_OAUTH_APP_ID = getattr(settings, 'WEIXIN_OAUTH_APP_ID', '') WEIXIN_OAUTH_APP_SECRET = getattr(settings, 'WEIXIN_OAUTH_APP_SECRET', '') WEIXIN_OAUTH_SCOPE = getattr(settings, 'WEIXIN_OAUTH_SCOPE', 'snsapi_login') WEIXIN_OAUTH_RESPONSE_TYPE = getattr(settings, 'WEIXIN_OAUTH_RESPONSE_TYPE', 'code') WEIXIN_OAUTH_QR_CONNECT_URL = getattr(settings, 'WEIXIN_OAUTH_QR_CONNECT_URL', 'https://open.weixin.qq.com/connect/qrconnect') WEIXIN_OAUTH_GRANT_TYPE = getattr(settings, 'WEIXIN_OAUTH_GRANT_TYPE', 'authorization_code') WEIXIN_OAUTH_ACCESS_TOKEN_URL = getattr(settings, 'WEIXIN_OAUTH_ACCESS_TOKEN_URL', 'https://api.weixin.qq.com/sns/oauth2/access_token') WEIXIN_OAUTH_USER_INFO_URL = getattr(settings, 'WEIXIN_OAUTH_USER_INFO_URL', 'https://api.weixin.qq.com/sns/userinfo') WEIXIN_OAUTH_CREATE_UNKNOWN_USER = getattr(settings, 'WEIXIN_OAUTH_CREATE_UNKNOWN_USER', True) WEIXIN_OAUTH_ACTIVATE_USER_AFTER_CREATION = getattr(settings, 'WEIXIN_OAUTH_ACTIVATE_USER_AFTER_CREATION', True)
494
335
<reponame>est31/jsparagus /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- * vim: set ts=8 sts=2 et sw=2 tw=80: * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef vm_CheckIsObjectKind_h #define vm_CheckIsObjectKind_h #include <stdint.h> // uint8_t namespace js { enum class CheckIsObjectKind : uint8_t { IteratorNext, IteratorReturn, IteratorThrow, GetIterator, GetAsyncIterator }; } // namespace js #endif /* vm_CheckIsObjectKind_h */
238
2,062
import pytest from .app import create_app @pytest.fixture def flask_client(): with create_app().test_client() as client: yield client
53
453
import sympy import torch from pixyz.losses.losses import Loss from pixyz.losses.divergences import KullbackLeibler def Entropy(p, analytical=True, sample_shape=torch.Size([1])): r""" Entropy (Analytical or Monte Carlo approximation). .. math:: H(p) &= -\mathbb{E}_{p(x)}[\log p(x)] \qquad \text{(analytical)}\\ &\approx -\frac{1}{L}\sum_{l=1}^L \log p(x_l), \quad \text{where} \quad x_l \sim p(x) \quad \text{(MC approximation)}. Examples -------- >>> import torch >>> from pixyz.distributions import Normal >>> p = Normal(loc=torch.tensor(0.), scale=torch.tensor(1.), var=["x"], features_shape=[64]) >>> loss_cls = Entropy(p,analytical=True) >>> print(loss_cls) H \left[ {p(x)} \right] >>> loss_cls.eval() tensor([90.8121]) >>> loss_cls = Entropy(p,analytical=False,sample_shape=[10]) >>> print(loss_cls) - \mathbb{E}_{p(x)} \left[\log p(x) \right] >>> loss_cls.eval() # doctest: +SKIP tensor([90.5991]) """ if analytical: loss = AnalyticalEntropy(p) else: loss = -p.log_prob().expectation(p, sample_shape=sample_shape) return loss class AnalyticalEntropy(Loss): def __init__(self, p): _input_var = p.input_var.copy() super().__init__(_input_var) self.p = p @property def _symbol(self): p_text = "{" + self.p.prob_text + "}" return sympy.Symbol("H \\left[ {} \\right]".format(p_text)) def forward(self, x_dict, **kwargs): if not hasattr(self.p, 'distribution_torch_class'): raise ValueError("Entropy of this distribution cannot be evaluated, " "got %s." % self.p.distribution_name) entropy = self.p.get_entropy(x_dict) return entropy, {} def CrossEntropy(p, q, analytical=False, sample_shape=torch.Size([1])): r""" Cross entropy, a.k.a., the negative expected value of log-likelihood (Monte Carlo approximation or Analytical). .. math:: H(p,q) &= -\mathbb{E}_{p(x)}[\log q(x)] \qquad \text{(analytical)}\\ &\approx -\frac{1}{L}\sum_{l=1}^L \log q(x_l), \quad \text{where} \quad x_l \sim p(x) \quad \text{(MC approximation)}. Examples -------- >>> import torch >>> from pixyz.distributions import Normal >>> p = Normal(loc=torch.tensor(0.), scale=torch.tensor(1.), var=["x"], features_shape=[64], name="p") >>> q = Normal(loc=torch.tensor(1.), scale=torch.tensor(1.), var=["x"], features_shape=[64], name="q") >>> loss_cls = CrossEntropy(p,q,analytical=True) >>> print(loss_cls) D_{KL} \left[p(x)||q(x) \right] + H \left[ {p(x)} \right] >>> loss_cls.eval() tensor([122.8121]) >>> loss_cls = CrossEntropy(p,q,analytical=False,sample_shape=[10]) >>> print(loss_cls) - \mathbb{E}_{p(x)} \left[\log q(x) \right] >>> loss_cls.eval() # doctest: +SKIP tensor([123.2192]) """ if analytical: loss = Entropy(p) + KullbackLeibler(p, q) else: loss = -q.log_prob().expectation(p, sample_shape=sample_shape) return loss class StochasticReconstructionLoss(Loss): def __init__(self, encoder, decoder, sample_shape=torch.Size([1])): raise NotImplementedError("This function is obsolete." " please use `-decoder.log_prob().expectation(encoder)` instead of it.")
1,515
399
<reponame>PranavPurwar/procyon /* * VariableTests.java * * Copyright (c) 2015 <NAME> * * This source code is subject to terms and conditions of the Apache License, Version 2.0. * A copy of the license can be found in the License.html file at the root of this distribution. * By using this source code in any fashion, you are agreeing to be bound by the terms of the * Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. */ package com.strobel.decompiler; import org.junit.Test; public class VariableTests extends DecompilerTest { @SuppressWarnings("UnusedDeclaration") private static class A { public void test1() { final int min = Integer.parseInt("1"); final int max = Integer.parseInt("2"); final int min2 = Integer.parseInt("3"); final int max2 = Integer.parseInt("4"); final int min3 = Integer.parseInt("5"); final int max3 = Integer.parseInt("6"); System.out.println(max - min); System.out.println(max2 - min2); System.out.println(max3 - min3); } public void test2() { final int min1 = Integer.parseInt("1"); final int max1 = Integer.parseInt("2"); final int min2 = Integer.parseInt("3"); final int max2 = Integer.parseInt("4"); final int min3 = Integer.parseInt("5"); final int max3 = Integer.parseInt("6"); System.out.println(max1 - min1); System.out.println(max2 - min2); System.out.println(max3 - min3); } public void test3() { final int min2 = Integer.parseInt("1"); final int max2 = Integer.parseInt("2"); final int min3 = Integer.parseInt("3"); final int max3 = Integer.parseInt("4"); System.out.println(max2 - min2); System.out.println(max3 - min3); } public void test4() { final int min3 = Integer.parseInt("3"); final int max3 = Integer.parseInt("4"); final int min4 = Integer.parseInt("5"); final int max4 = Integer.parseInt("6"); System.out.println(max3 - min3); System.out.println(max4 - min4); } public void test5() { final int min3 = Integer.parseInt("3"); final int max3 = Integer.parseInt("4"); final int min = Integer.parseInt("5"); final int max = Integer.parseInt("6"); System.out.println(max3 - min3); System.out.println(max - min); } } @Test public void testNumberedVariablesDoNotBreakVariableNaming() throws Throwable { verifyOutput( A.class, defaultSettings(), "private static class A {\n" + " public void test1() {\n" + " final int min = Integer.parseInt(\"1\");\n" + " final int max = Integer.parseInt(\"2\");\n" + " final int min2 = Integer.parseInt(\"3\");\n" + " final int max2 = Integer.parseInt(\"4\");\n" + " final int min3 = Integer.parseInt(\"5\");\n" + " final int max3 = Integer.parseInt(\"6\");\n" + " System.out.println(max - min);\n" + " System.out.println(max2 - min2);\n" + " System.out.println(max3 - min3);\n" + " }\n" + " public void test2() {\n" + " final int min1 = Integer.parseInt(\"1\");\n" + " final int max1 = Integer.parseInt(\"2\");\n" + " final int min2 = Integer.parseInt(\"3\");\n" + " final int max2 = Integer.parseInt(\"4\");\n" + " final int min3 = Integer.parseInt(\"5\");\n" + " final int max3 = Integer.parseInt(\"6\");\n" + " System.out.println(max1 - min1);\n" + " System.out.println(max2 - min2);\n" + " System.out.println(max3 - min3);\n" + " }\n" + " public void test3() {\n" + " final int min2 = Integer.parseInt(\"1\");\n" + " final int max2 = Integer.parseInt(\"2\");\n" + " final int min3 = Integer.parseInt(\"3\");\n" + " final int max3 = Integer.parseInt(\"4\");\n" + " System.out.println(max2 - min2);\n" + " System.out.println(max3 - min3);\n" + " }\n" + " public void test4() {\n" + " final int min3 = Integer.parseInt(\"3\");\n" + " final int max3 = Integer.parseInt(\"4\");\n" + " final int min4 = Integer.parseInt(\"5\");\n" + " final int max4 = Integer.parseInt(\"6\");\n" + " System.out.println(max3 - min3);\n" + " System.out.println(max4 - min4);\n" + " }\n" + " public void test5() {\n" + " final int min3 = Integer.parseInt(\"3\");\n" + " final int max3 = Integer.parseInt(\"4\");\n" + " final int min4 = Integer.parseInt(\"5\");\n" + " final int max4 = Integer.parseInt(\"6\");\n" + " System.out.println(max3 - min3);\n" + " System.out.println(max4 - min4);\n" + " }\n" + "}\n" ); } }
3,007
474
/*************************************************************************** * Captures a rendered texture to a buffer. ***************************************************************************/ #include <gl/gl_render_texture.h> #include "glm/glm.hpp" #include "glm/gtc/constants.hpp" #include "glm/gtc/type_ptr.hpp" #include "glm/gtc/matrix_inverse.hpp" #include "glm/gtc/matrix_transform.hpp" #include "component.h" #include "render_data.h" #include "texture_capturer.h" #include "shaders/shader.h" #include "gl/gl_render_texture.h" #include "component.inl" #include "util/gvr_time.h" #define TOL 1e-8 namespace gvr { extern "C" { void Java_org_gearvrf_NativeTextureCapturer_callbackFromNative( JNIEnv *env, jobject obj, jint index, char *info); } TextureCapturer::TextureCapturer(ShaderManager *shaderManager) : Component(TextureCapturer::getComponentType()) , mShaderManager(shaderManager) , mMaterial(NULL) , mRenderTexture(0) , mPendingCapture(false) , mHasNewCapture(false) , mCaptureIntervalNS(0) , mLastCaptureTimeNS(0) , mJNIEnv(0) , mCapturerObject(0) { Renderer* renderer = Renderer::getInstance(); mMaterial = renderer->createMaterial("float4 ambient_color; float4 diffuse_color; float4 specular_color; float4 emissive_color; float specular_exponent", ""); mMaterial->setTexture("diffuseTexture", mRenderTexture); // OpenGL default mMaterial->setVec4("ambient_color", glm::vec4(0.2f, 0.2f, 0.2f, 1.0f)); mMaterial->setVec4("diffuse_color", glm::vec4(0.8f, 0.8f, 0.8f, 1.0f)); mMaterial->setVec4("specular_color", glm::vec4(0.0f, 0.0f, 0.0f, 1.0f)); mMaterial->setFloat("specular_exponent", 0.0f); } TextureCapturer::~TextureCapturer() { if (mJNIEnv && mCapturerObject) { mJNIEnv->DeleteGlobalRef(mCapturerObject); } } void TextureCapturer::setCapturerObject(JNIEnv *env, jobject capturer) { mJNIEnv = env; if (mCapturerObject) { mJNIEnv->DeleteGlobalRef(mCapturerObject); } mCapturerObject = env->NewGlobalRef(capturer); } void TextureCapturer::setRenderTexture(RenderTexture *renderTexture) { mRenderTexture = renderTexture; } void TextureCapturer::setCapture(bool capture, float fps) { mPendingCapture = capture; if (capture && fabs(fps) > TOL) { mCaptureIntervalNS = (long long)(1000000000.f / fps); } else { mCaptureIntervalNS = 0; } } bool TextureCapturer::getAndClearPendingCapture() { // periodic capture if (mCaptureIntervalNS) { long long now = getNanoTime(); if (now - mLastCaptureTimeNS >= mCaptureIntervalNS) { mPendingCapture = true; } } bool rv = mPendingCapture; mPendingCapture = false; return rv; } void TextureCapturer::beginCapture() { // Save states glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &mSavedFBO); glGetIntegerv(GL_VIEWPORT, mSavedViewport); glGetIntegerv(GL_SCISSOR_BOX, mSavedScissor); mIsCullFace = glIsEnabled(GL_CULL_FACE); mIsBlend = glIsEnabled(GL_BLEND); mIsPolygonOffsetFill = glIsEnabled(GL_POLYGON_OFFSET_FILL); // Setup FBO glBindFramebuffer(GL_DRAW_FRAMEBUFFER, mRenderTexture->getFrameBufferId()); glDisable(GL_CULL_FACE); glEnable (GL_BLEND); glBlendEquation (GL_FUNC_ADD); glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); glDisable (GL_POLYGON_OFFSET_FILL); // Setup viewport glViewport(0, 0, mRenderTexture->width(), mRenderTexture->height()); glClearColor(0, 0, 0, 0); // transparency is needed glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); mLastCaptureTimeNS = getNanoTime(); } void TextureCapturer::startReadBack() { mRenderTexture->startReadBack(); } void TextureCapturer::endCapture() { // Restore GL settings glBindFramebuffer(GL_DRAW_FRAMEBUFFER, mSavedFBO); glViewport(mSavedViewport[0], mSavedViewport[1], mSavedViewport[2], mSavedViewport[3]); glScissor(mSavedScissor[0], mSavedScissor[1], mSavedScissor[2], mSavedScissor[3]); if (mIsCullFace) glEnable(GL_CULL_FACE); else glDisable(GL_CULL_FACE); if (mIsBlend) glEnable(GL_BLEND); else glDisable(GL_BLEND); if (mIsPolygonOffsetFill) glEnable(GL_POLYGON_OFFSET_FILL); else glDisable(GL_POLYGON_OFFSET_FILL); } void TextureCapturer::render(RenderState* rstate, RenderData* render_data) { ShaderData* material = render_data->pass(0)->material(); Renderer* renderer = Renderer::getInstance(); float opacity = 1.0f; if (material == NULL) { LOGE("No material"); return; } material->getFloat("opacity", opacity); mMaterial->setFloat("opacity", opacity); if (render_data->isValid(renderer, *rstate)) { int id = render_data->get_shader(rstate->is_multiview); if (id > 0) { Shader* shader = mShaderManager->getShader(id); renderer->renderWithShader(*rstate, shader, render_data, mMaterial, 0); } } } glm::mat4 TextureCapturer::getModelViewMatrix() { // Apply rotation glm::quat rot_quat = glm::angleAxis(glm::radians(180.f), glm::vec3(1.f, 0.f, 0.f)); glm::mat4 mv = glm::mat4_cast(rot_quat); return mv; } glm::mat4 TextureCapturer::getMvpMatrix(float half_width, float half_height) { // Orthographic projection glm::mat4 proj = glm::ortho(-half_width, half_width, -half_height, half_height, -1.f, 1.f); return glm::mat4(proj * getModelViewMatrix()); } void TextureCapturer::callback(int msg, char *info) { Java_org_gearvrf_NativeTextureCapturer_callbackFromNative( mJNIEnv, mCapturerObject, msg, info); } }
2,506
609
package org.consenlabs.tokencore.wallet.transaction; import org.consenlabs.tokencore.foundation.crypto.Hash; import org.consenlabs.tokencore.foundation.utils.ByteUtil; import org.consenlabs.tokencore.foundation.utils.NumericUtil; import org.consenlabs.tokencore.wallet.Wallet; import org.consenlabs.tokencore.wallet.keystore.V3Keystore; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class EOSTransaction implements TransactionSigner { private byte[] txBuf; private List<ToSignObj> txsToSign; public EOSTransaction(byte[] txBuf) { this.txBuf = txBuf; } public EOSTransaction(List<ToSignObj> txsToSign) { this.txsToSign = txsToSign; } @Deprecated @Override public TxSignResult signTransaction(String chainId, String password, Wallet wallet) { String transactionID = NumericUtil.bytesToHex(Hash.sha256(txBuf)); txBuf = ByteUtil.concat(NumericUtil.hexToBytes(chainId), txBuf); byte[] zeroBuf = new byte[32]; Arrays.fill(zeroBuf, (byte) 0); txBuf = ByteUtil.concat(txBuf, zeroBuf); String wif = wallet.exportPrivateKey(password); String signed = EOSSign.sign(Hash.sha256(txBuf), wif); return new TxSignResult(signed, transactionID); } public List<TxMultiSignResult> signTransactions(String chainId, String password, Wallet wallet) { List<TxMultiSignResult> results = new ArrayList<>(txsToSign.size()); for (ToSignObj toSignObj : txsToSign) { byte[] txBuf = NumericUtil.hexToBytes(toSignObj.txHex); String transactionID = NumericUtil.bytesToHex(Hash.sha256(txBuf)); byte[] txChainIDBuf = ByteUtil.concat(NumericUtil.hexToBytes(chainId), txBuf); byte[] zeroBuf = new byte[32]; Arrays.fill(zeroBuf, (byte) 0); byte[] fullTxBuf = ByteUtil.concat(txChainIDBuf, zeroBuf); byte[] hashedTx = Hash.sha256(fullTxBuf); List<String> signatures = new ArrayList<>(toSignObj.publicKeys.size()); for (String pubKey : toSignObj.publicKeys) { String signed; if (wallet.getKeystore().getVersion() == V3Keystore.VERSION) { signed = EOSSign.sign(hashedTx, wallet.exportPrivateKey(password)); } else { signed = EOSSign.sign(hashedTx, wallet.decryptPrvKeyFor(pubKey, password)); } signatures.add(signed); } TxMultiSignResult signedResult = new TxMultiSignResult(transactionID, signatures); results.add(signedResult); } return results; } public static class ToSignObj { private String txHex; private List<String> publicKeys; public String getTxHex() { return txHex; } public void setTxHex(String txHex) { this.txHex = txHex; } public List<String> getPublicKeys() { return publicKeys; } public void setPublicKeys(List<String> publicKeys) { this.publicKeys = publicKeys; } } }
1,123
1,444
package mage.game.command.emblems; import mage.abilities.Ability; import mage.abilities.common.BeginningOfCombatTriggeredAbility; import mage.abilities.effects.common.CreateTokenEffect; import mage.abilities.effects.common.counter.AddCountersAllEffect; import mage.constants.TargetController; import mage.constants.Zone; import mage.counters.CounterType; import mage.filter.StaticFilters; import mage.game.command.Emblem; import mage.game.permanent.token.SoldierToken; public final class BasriKetEmblem extends Emblem { /** * Emblem with "At the beginning of combat on your turn, create a 1/1 white Soldier creature token, then put a +1/+1 counter on each creature you control." */ public BasriKetEmblem() { setName("Emblem Basri"); Ability ability = new BeginningOfCombatTriggeredAbility( Zone.COMMAND, new CreateTokenEffect(new SoldierToken()), TargetController.YOU, false, false); ability.addEffect( new AddCountersAllEffect(CounterType.P1P1.createInstance(), StaticFilters.FILTER_PERMANENT_CREATURE_CONTROLLED) .setText(", then put a +1/+1 counter on each creature you control") ); this.getAbilities().add(ability); } }
458
5,964
<filename>third_party/skia/src/gpu/GrProcessorDataManager.cpp<gh_stars>1000+ /* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GrProcessorDataManager.h"
83
4,140
<reponame>FANsZL/hive /* * 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.hadoop.hive.ql.optimizer.calcite.stats; import org.apache.calcite.rel.core.Union; import org.apache.calcite.rel.metadata.BuiltInMetadata; import org.apache.calcite.rel.metadata.MetadataDef; import org.apache.calcite.rel.metadata.MetadataHandler; import org.apache.calcite.rel.metadata.ReflectiveRelMetadataProvider; import org.apache.calcite.rel.metadata.RelMetadataProvider; import org.apache.calcite.rel.metadata.RelMetadataQuery; import org.apache.calcite.rex.RexNode; import org.apache.calcite.util.BuiltInMethod; import org.apache.calcite.util.ImmutableBitSet; import org.apache.hadoop.hive.ql.optimizer.calcite.RelOptHiveTable; import org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveTableScan; import org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveUnion; import java.util.Set; public final class HiveRelMdExpressionLineage implements MetadataHandler<BuiltInMetadata.ExpressionLineage> { public static final RelMetadataProvider SOURCE = ReflectiveRelMetadataProvider.reflectiveSource( BuiltInMethod.EXPRESSION_LINEAGE.method, new HiveRelMdExpressionLineage()); //~ Constructors ----------------------------------------------------------- private HiveRelMdExpressionLineage() {} //~ Methods ---------------------------------------------------------------- public MetadataDef<BuiltInMetadata.ExpressionLineage> getDef() { return BuiltInMetadata.ExpressionLineage.DEF; } // Union returns NULL instead of actually determining the lineage because // Union may return multiple lineage expressions - one corresponding to each branch // this could cause exponential possible combinations of lineage expressions // as you go up in the operator tree. // As the possible number of expressions increases it could lead to OOM. // To prevent this UNION returns NULL. // sample query could be found in union_lineage.q public Set<RexNode> getExpressionLineage(HiveUnion rel, RelMetadataQuery mq, RexNode outputExpression) { return null; } } // End HiveRelMdExpressionLineage
833
3,182
//CONF: lombok.fieldNameConstants.uppercase = true import lombok.AccessLevel; import lombok.experimental.FieldNameConstants; @FieldNameConstants(level = AccessLevel.PACKAGE) public class FieldNameConstantsUppercased { String iAmADvdPlayer; int $skipMe; static double skipMeToo; @FieldNameConstants.Exclude int andMe; String butPrintMePlease; }
120
852
<reponame>malbouis/cmssw #ifndef CondTools_SiPixel_PixelPopConCalibChecker_H #define CondTools_SiPixel_PixelPopConCalibChecker_H // -*- C++ -*- // // Package: PixelPopConCalibChecker // Class: PixelPopConCalibChecker // /**\class PixelPopConCalibChecker PixelPopConCalibChecker.h SiPixel/test/PixelPopConCalibChecker.h Description: Test analyzer for checking calib configuration objects written to db Implementation: <Notes on implementation> */ // // Original Author: <NAME> // Created: August 2008 // // // system include files #include <memory> #include <string> // user include files #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/one/EDAnalyzer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "CondFormats/SiPixelObjects/interface/SiPixelCalibConfiguration.h" #include "CondFormats/DataRecord/interface/SiPixelCalibConfigurationRcd.h" // // class decleration // class PixelPopConCalibChecker : public edm::one::EDAnalyzer<> { public: explicit PixelPopConCalibChecker(const edm::ParameterSet&); ~PixelPopConCalibChecker() override; void analyze(const edm::Event&, const edm::EventSetup&) override; private: // ----------member data --------------------------- edm::ESGetToken<SiPixelCalibConfiguration, SiPixelCalibConfigurationRcd> gainCalibToken_; std::string _filename; int _messageLevel; }; #endif
504
839
from django.dispatch import receiver from baserow.core.trash.signals import permanently_deleted from baserow_premium.row_comments.models import RowComment @receiver(permanently_deleted, sender="row", dispatch_uid="row_comment_cleanup") def permanently_deleted(sender, **kwargs): table_id = kwargs["parent_id"] trash_item_id = kwargs["trash_item_id"] RowComment.objects.filter(table_id=table_id, row_id=trash_item_id).delete()
156
12,278
<gh_stars>1000+ // Boost.Units - A C++ library for zero-overhead dimensional analysis and // unit/quantity manipulation and conversion // // Copyright (C) 2003-2008 <NAME> // Copyright (C) 2007-2008 <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 BOOST_UNITS_DIM_HPP #define BOOST_UNITS_DIM_HPP #include <boost/static_assert.hpp> #include <boost/type_traits/is_same.hpp> #include <boost/mpl/arithmetic.hpp> #include <boost/units/config.hpp> #include <boost/units/static_rational.hpp> #include <boost/units/detail/dim_impl.hpp> /// \file dim.hpp /// \brief Handling of fundamental dimension/exponent pairs. namespace boost { namespace units { namespace detail { struct dim_tag { }; } /// \brief Dimension tag/exponent pair for a single fundamental dimension. /// /// \details /// The dim class represents a single dimension tag/dimension exponent pair. /// That is, @c dim<tag_type,value_type> is a pair where @c tag_type represents the /// fundamental dimension being represented and @c value_type represents the /// exponent of that fundamental dimension as a @c static_rational. @c tag_type must /// be a derived from a specialization of @c base_dimension. /// Specialization of the following Boost.MPL metafunctions are provided /// /// - @c mpl::plus for two @c dims /// - @c mpl::minus for two @c dims /// - @c mpl::negate for a @c dim /// /// These metafunctions all operate on the exponent, and require /// that the @c dim operands have the same base dimension tag. /// In addition, multiplication and division by @c static_rational /// is supported. /// /// - @c mpl::times for a @c static_rational and a @c dim in either order /// - @c mpl::divides for a @c static_rational and a @c dim in either order /// /// These metafunctions likewise operate on the exponent only. template<typename T,typename V> struct dim { typedef dim type; typedef detail::dim_tag tag; typedef T tag_type; typedef V value_type; }; } // namespace units } // namespace boost #if BOOST_UNITS_HAS_BOOST_TYPEOF #include BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP() BOOST_TYPEOF_REGISTER_TEMPLATE(boost::units::dim, 2) #endif #ifndef BOOST_UNITS_DOXYGEN namespace boost { namespace mpl { // define MPL operators acting on dim<T,V> template<> struct plus_impl<boost::units::detail::dim_tag,boost::units::detail::dim_tag> { template<class T0, class T1> struct apply { BOOST_STATIC_ASSERT((boost::is_same<typename T0::tag_type,typename T1::tag_type>::value == true)); typedef boost::units::dim<typename T0::tag_type, typename mpl::plus<typename T0::value_type, typename T1::value_type>::type> type; }; }; template<> struct minus_impl<boost::units::detail::dim_tag,boost::units::detail::dim_tag> { template<class T0, class T1> struct apply { BOOST_STATIC_ASSERT((boost::is_same<typename T0::tag_type,typename T1::tag_type>::value == true)); typedef boost::units::dim<typename T0::tag_type, typename mpl::minus<typename T0::value_type, typename T1::value_type>::type> type; }; }; template<> struct times_impl<boost::units::detail::dim_tag,boost::units::detail::static_rational_tag> { template<class T0, class T1> struct apply { typedef boost::units::dim<typename T0::tag_type, typename mpl::times<typename T0::value_type, T1>::type> type; }; }; template<> struct times_impl<boost::units::detail::static_rational_tag,boost::units::detail::dim_tag> { template<class T0, class T1> struct apply { typedef boost::units::dim<typename T1::tag_type, typename mpl::times<T0, typename T1::value_type>::type> type; }; }; template<> struct divides_impl<boost::units::detail::dim_tag,boost::units::detail::static_rational_tag> { template<class T0, class T1> struct apply { typedef boost::units::dim<typename T0::tag_type, typename mpl::divides<typename T0::value_type, T1>::type> type; }; }; template<> struct divides_impl<boost::units::detail::static_rational_tag,boost::units::detail::dim_tag> { template<class T0, class T1> struct apply { typedef boost::units::dim<typename T1::tag_type, typename mpl::divides<T0, typename T1::value_type>::type> type; }; }; template<> struct negate_impl<boost::units::detail::dim_tag> { template<class T0> struct apply { typedef boost::units::dim<typename T0::tag_type,typename mpl::negate<typename T0::value_type>::type> type; }; }; } // namespace mpl } // namespace boost #endif #endif // BOOST_UNITS_DIM_HPP
1,804
348
<gh_stars>100-1000 {"nom":"Reyniès","circ":"1ère circonscription","dpt":"Tarn-et-Garonne","inscrits":703,"abs":342,"votants":361,"blancs":42,"nuls":23,"exp":296,"res":[{"nuance":"SOC","nom":"<NAME>","voix":174},{"nuance":"REM","nom":"<NAME>","voix":122}]}
105
1,162
<filename>digdag-spi/src/main/java/io/digdag/spi/SecretStoreManager.java package io.digdag.spi; public interface SecretStoreManager { SecretStore getSecretStore(int siteId); }
67
19,046
<gh_stars>1000+ /* * Copyright (c) Facebook, Inc. and its affiliates. * * 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 <folly/Math.h> #include <algorithm> #include <array> #include <type_traits> #include <utility> #include <vector> #include <glog/logging.h> #include <folly/Portability.h> #include <folly/functional/Invoke.h> #include <folly/portability/GTest.h> using namespace folly; using namespace folly::detail; namespace { // Workaround for https://llvm.org/bugs/show_bug.cgi?id=16404, // issues with __int128 multiplication and UBSAN template <typename T> T mul(T lhs, T rhs) { if (rhs < 0) { rhs = -rhs; lhs = -lhs; } T accum = 0; while (rhs != 0) { if ((rhs & 1) != 0) { accum += lhs; } lhs += lhs; rhs >>= 1; } return accum; } template <typename T, typename B> T referenceDivFloor(T numer, T denom) { // rv = largest integral value <= numer / denom B n = numer; B d = denom; if (d < 0) { d = -d; n = -n; } B r = n / d; while (mul(r, d) > n) { --r; } while (mul(r + 1, d) <= n) { ++r; } T rv = static_cast<T>(r); assert(static_cast<B>(rv) == r); return rv; } template <typename T, typename B> T referenceDivCeil(T numer, T denom) { // rv = smallest integral value >= numer / denom B n = numer; B d = denom; if (d < 0) { d = -d; n = -n; } B r = n / d; while (mul(r, d) < n) { ++r; } while (mul(r - 1, d) >= n) { --r; } T rv = static_cast<T>(r); assert(static_cast<B>(rv) == r); return rv; } template <typename T, typename B> T referenceDivRoundAway(T numer, T denom) { if ((numer < 0) != (denom < 0)) { return referenceDivFloor<T, B>(numer, denom); } else { return referenceDivCeil<T, B>(numer, denom); } } template <typename T> std::vector<T> cornerValues() { std::vector<T> rv; for (T i = 1; i < 24; ++i) { rv.push_back(i); rv.push_back(T(std::numeric_limits<T>::max() / i)); rv.push_back(T(std::numeric_limits<T>::max() - i)); rv.push_back(T(std::numeric_limits<T>::max() / T(2) - i)); if (std::is_signed<T>::value) { rv.push_back(-i); rv.push_back(T(std::numeric_limits<T>::min() / i)); rv.push_back(T(std::numeric_limits<T>::min() + i)); rv.push_back(T(std::numeric_limits<T>::min() / T(2) + i)); } } return rv; } template <typename A, typename B, typename C> void runDivTests() { using T = decltype(static_cast<A>(1) / static_cast<B>(1)); auto numers = cornerValues<A>(); numers.push_back(0); auto denoms = cornerValues<B>(); for (A n : numers) { for (B d : denoms) { if (std::is_signed<T>::value && n == std::numeric_limits<T>::min() && d == static_cast<T>(-1)) { // n / d overflows in two's complement continue; } EXPECT_EQ(divCeil(n, d), (referenceDivCeil<T, C>(n, d))) << n << "/" << d; EXPECT_EQ(divFloor(n, d), (referenceDivFloor<T, C>(n, d))) << n << "/" << d; EXPECT_EQ(divTrunc(n, d), n / d) << n << "/" << d; EXPECT_EQ(divRoundAway(n, d), (referenceDivRoundAway<T, C>(n, d))) << n << "/" << d; T nn = n; T dd = d; EXPECT_EQ(divCeilBranchless(nn, dd), divCeilBranchful(nn, dd)); EXPECT_EQ(divFloorBranchless(nn, dd), divFloorBranchful(nn, dd)); EXPECT_EQ(divRoundAwayBranchless(nn, dd), divRoundAwayBranchful(nn, dd)); } } } } // namespace TEST(Bits, divTestInt8) { runDivTests<int8_t, int8_t, int64_t>(); runDivTests<int8_t, uint8_t, int64_t>(); runDivTests<int8_t, int16_t, int64_t>(); runDivTests<int8_t, uint16_t, int64_t>(); runDivTests<int8_t, int32_t, int64_t>(); runDivTests<int8_t, uint32_t, int64_t>(); #if FOLLY_HAVE_INT128_T runDivTests<int8_t, int64_t, __int128>(); runDivTests<int8_t, uint64_t, __int128>(); #endif } TEST(Bits, divTestInt16) { runDivTests<int16_t, int8_t, int64_t>(); runDivTests<int16_t, uint8_t, int64_t>(); runDivTests<int16_t, int16_t, int64_t>(); runDivTests<int16_t, uint16_t, int64_t>(); runDivTests<int16_t, int32_t, int64_t>(); runDivTests<int16_t, uint32_t, int64_t>(); #if FOLLY_HAVE_INT128_T runDivTests<int16_t, int64_t, __int128>(); runDivTests<int16_t, uint64_t, __int128>(); #endif } TEST(Bits, divTestInt32) { runDivTests<int32_t, int8_t, int64_t>(); runDivTests<int32_t, uint8_t, int64_t>(); runDivTests<int32_t, int16_t, int64_t>(); runDivTests<int32_t, uint16_t, int64_t>(); runDivTests<int32_t, int32_t, int64_t>(); runDivTests<int32_t, uint32_t, int64_t>(); #if FOLLY_HAVE_INT128_T runDivTests<int32_t, int64_t, __int128>(); runDivTests<int32_t, uint64_t, __int128>(); #endif } #if FOLLY_HAVE_INT128_T TEST(Bits, divTestInt64) { runDivTests<int64_t, int8_t, __int128>(); runDivTests<int64_t, uint8_t, __int128>(); runDivTests<int64_t, int16_t, __int128>(); runDivTests<int64_t, uint16_t, __int128>(); runDivTests<int64_t, int32_t, __int128>(); runDivTests<int64_t, uint32_t, __int128>(); runDivTests<int64_t, int64_t, __int128>(); runDivTests<int64_t, uint64_t, __int128>(); } #endif TEST(Bits, divTestUint8) { runDivTests<uint8_t, int8_t, int64_t>(); runDivTests<uint8_t, uint8_t, int64_t>(); runDivTests<uint8_t, int16_t, int64_t>(); runDivTests<uint8_t, uint16_t, int64_t>(); runDivTests<uint8_t, int32_t, int64_t>(); runDivTests<uint8_t, uint32_t, int64_t>(); #if FOLLY_HAVE_INT128_T runDivTests<uint8_t, int64_t, __int128>(); runDivTests<uint8_t, uint64_t, __int128>(); #endif } TEST(Bits, divTestUint16) { runDivTests<uint16_t, int8_t, int64_t>(); runDivTests<uint16_t, uint8_t, int64_t>(); runDivTests<uint16_t, int16_t, int64_t>(); runDivTests<uint16_t, uint16_t, int64_t>(); runDivTests<uint16_t, int32_t, int64_t>(); runDivTests<uint16_t, uint32_t, int64_t>(); #if FOLLY_HAVE_INT128_T runDivTests<uint16_t, int64_t, __int128>(); runDivTests<uint16_t, uint64_t, __int128>(); #endif } TEST(Bits, divTestUint32) { runDivTests<uint32_t, int8_t, int64_t>(); runDivTests<uint32_t, uint8_t, int64_t>(); runDivTests<uint32_t, int16_t, int64_t>(); runDivTests<uint32_t, uint16_t, int64_t>(); runDivTests<uint32_t, int32_t, int64_t>(); runDivTests<uint32_t, uint32_t, int64_t>(); #if FOLLY_HAVE_INT128_T runDivTests<uint32_t, int64_t, __int128>(); runDivTests<uint32_t, uint64_t, __int128>(); #endif } #if FOLLY_HAVE_INT128_T TEST(Bits, divTestUint64) { runDivTests<uint64_t, int8_t, __int128>(); runDivTests<uint64_t, uint8_t, __int128>(); runDivTests<uint64_t, int16_t, __int128>(); runDivTests<uint64_t, uint16_t, __int128>(); runDivTests<uint64_t, int32_t, __int128>(); runDivTests<uint64_t, uint32_t, __int128>(); runDivTests<uint64_t, int64_t, __int128>(); runDivTests<uint64_t, uint64_t, __int128>(); } #endif FOLLY_CREATE_FREE_INVOKER(midpoint_invoke, midpoint); TEST(MidpointTest, MidpointTest) { EXPECT_EQ(midpoint<int8_t>(2, 4), 3); EXPECT_EQ(midpoint<int8_t>(3, 4), 3); EXPECT_EQ(midpoint<int8_t>(-2, 2), 0); EXPECT_EQ(midpoint<int8_t>(-4, -2), -3); EXPECT_EQ(midpoint<int8_t>(102, 104), 103); EXPECT_EQ(midpoint<int8_t>(126, 126), 126); EXPECT_EQ(midpoint<int8_t>(-104, -102), -103); // Perform some simple tests. Note that because these are small integers // they can be represented exactly, so we do not have floating-point error. EXPECT_EQ(midpoint(2.0, 4.0), 3.0); EXPECT_EQ(midpoint(-2.0, 2.0), 0.0); EXPECT_EQ(midpoint(-2.1, 2.1), 0.0); EXPECT_EQ(midpoint(-4.0, -2.0), -3.0); EXPECT_EQ(midpoint(102.0, 104.0), 103.0); EXPECT_EQ(midpoint(-104.0, -102.0), -103.0); // Double EXPECT_EQ(midpoint(2.0, 4.0), 3.0); EXPECT_EQ(midpoint(0.0, 0.4), 0.2); EXPECT_EQ(midpoint(0.0, -0.0), 0.0); EXPECT_EQ(midpoint(9e9, -9e9), 0.0); EXPECT_EQ( midpoint( std::numeric_limits<double>::max(), std::numeric_limits<double>::max()), std::numeric_limits<double>::max()); EXPECT_TRUE(std::isnan(midpoint( -std::numeric_limits<double>::infinity(), std::numeric_limits<double>::infinity()))); // Float EXPECT_EQ(midpoint(2.0f, 4.0f), 3.0f); EXPECT_EQ(midpoint(0.0f, 0.4f), 0.2f); EXPECT_EQ(midpoint(0.0f, -0.0f), 0.0f); EXPECT_EQ(midpoint(9e9f, -9e9f), 0.0f); EXPECT_EQ( midpoint( std::numeric_limits<float>::max(), std::numeric_limits<float>::max()), std::numeric_limits<float>::max()); EXPECT_TRUE(std::isnan(midpoint( -std::numeric_limits<float>::infinity(), std::numeric_limits<float>::infinity()))); // Long double EXPECT_EQ(midpoint(2.0l, 4.0l), 3.0l); EXPECT_EQ(midpoint(0.0l, 0.4l), 0.2l); EXPECT_EQ(midpoint(0.0l, -0.0l), 0.0l); EXPECT_EQ(midpoint(9e9l, -9e9l), 0.0l); EXPECT_EQ( midpoint( std::numeric_limits<long double>::max(), std::numeric_limits<long double>::max()), std::numeric_limits<long double>::max()); EXPECT_TRUE(std::isnan(midpoint( -std::numeric_limits<long double>::infinity(), std::numeric_limits<long double>::infinity()))); EXPECT_TRUE(noexcept(midpoint(1, 2))); EXPECT_FALSE((is_invocable_v<midpoint_invoke, bool>)); EXPECT_FALSE((is_invocable_v<midpoint_invoke, const bool>)); EXPECT_FALSE((is_invocable_v<midpoint_invoke, volatile int>)); constexpr auto MY_INT_MAX = std::numeric_limits<int>::max(); constexpr auto MY_INT_MIN = std::numeric_limits<int>::min(); constexpr auto MY_UINT_MAX = std::numeric_limits<unsigned int>::max(); constexpr auto MY_SHRT_MAX = std::numeric_limits<short>::max(); constexpr auto MY_SHRT_MIN = std::numeric_limits<short>::min(); constexpr auto MY_SCHAR_MAX = std::numeric_limits<signed char>::max(); constexpr auto MY_SCHAR_MIN = std::numeric_limits<signed char>::min(); EXPECT_EQ(midpoint(0, 0), 0); EXPECT_EQ(midpoint(1, 1), 1); EXPECT_EQ(midpoint(0, 1), 0); EXPECT_EQ(midpoint(1, 0), 1); EXPECT_EQ(midpoint(0, 2), 1); EXPECT_EQ(midpoint(3, 2), 3); EXPECT_EQ(midpoint(-5, 4), -1); EXPECT_EQ(midpoint(5, -4), 1); EXPECT_EQ(midpoint(-5, -4), -5); EXPECT_EQ(midpoint(-4, -5), -4); EXPECT_EQ(midpoint(MY_INT_MIN, MY_INT_MAX), -1); EXPECT_EQ(midpoint(MY_INT_MAX, MY_INT_MIN), 0); EXPECT_EQ(midpoint(MY_INT_MAX, MY_INT_MAX), MY_INT_MAX); EXPECT_EQ(midpoint(MY_INT_MAX, MY_INT_MAX - 1), MY_INT_MAX); EXPECT_EQ(midpoint(MY_INT_MAX - 1, MY_INT_MAX - 1), MY_INT_MAX - 1); EXPECT_EQ(midpoint(MY_INT_MAX - 1, MY_INT_MAX), MY_INT_MAX - 1); EXPECT_EQ(midpoint(MY_INT_MAX, MY_INT_MAX - 2), MY_INT_MAX - 1); EXPECT_EQ(midpoint(0u, 0u), 0); EXPECT_EQ(midpoint(0u, 1u), 0); EXPECT_EQ(midpoint(1u, 0u), 1); EXPECT_EQ(midpoint(0u, 2u), 1); EXPECT_EQ(midpoint(3u, 2u), 3); EXPECT_EQ(midpoint(0u, MY_UINT_MAX), MY_UINT_MAX / 2); EXPECT_EQ(midpoint(MY_UINT_MAX, 0u), (MY_UINT_MAX / 2 + 1)); EXPECT_EQ(midpoint(MY_UINT_MAX, MY_UINT_MAX), MY_UINT_MAX); EXPECT_EQ(midpoint(MY_UINT_MAX, MY_UINT_MAX - 1), MY_UINT_MAX); EXPECT_EQ(midpoint(MY_UINT_MAX - 1, MY_UINT_MAX - 1), MY_UINT_MAX - 1); EXPECT_EQ(midpoint(MY_UINT_MAX - 1, MY_UINT_MAX), MY_UINT_MAX - 1); EXPECT_EQ(midpoint(MY_UINT_MAX, MY_UINT_MAX - 2), MY_UINT_MAX - 1); EXPECT_EQ(midpoint<short>(0, 0), 0); EXPECT_EQ(midpoint<short>(0, 1), 0); EXPECT_EQ(midpoint<short>(1, 0), 1); EXPECT_EQ(midpoint<short>(0, 2), 1); EXPECT_EQ(midpoint<short>(3, 2), 3); EXPECT_EQ(midpoint<short>(-5, 4), -1); EXPECT_EQ(midpoint<short>(5, -4), 1); EXPECT_EQ(midpoint<short>(-5, -4), -5); EXPECT_EQ(midpoint<short>(-4, -5), -4); EXPECT_EQ(midpoint<short>(MY_SHRT_MIN, MY_SHRT_MAX), -1); EXPECT_EQ(midpoint<short>(MY_SHRT_MAX, MY_SHRT_MIN), 0); EXPECT_EQ(midpoint<short>(MY_SHRT_MAX, MY_SHRT_MAX), MY_SHRT_MAX); EXPECT_EQ(midpoint<short>(MY_SHRT_MAX, MY_SHRT_MAX - 1), MY_SHRT_MAX); EXPECT_EQ(midpoint<short>(MY_SHRT_MAX - 1, MY_SHRT_MAX - 1), MY_SHRT_MAX - 1); EXPECT_EQ(midpoint<short>(MY_SHRT_MAX - 1, MY_SHRT_MAX), MY_SHRT_MAX - 1); EXPECT_EQ(midpoint<short>(MY_SHRT_MAX, MY_SHRT_MAX - 2), MY_SHRT_MAX - 1); EXPECT_EQ(midpoint<signed char>(0, 0), 0); EXPECT_EQ(midpoint<signed char>(1, 1), 1); EXPECT_EQ(midpoint<signed char>(0, 1), 0); EXPECT_EQ(midpoint<signed char>(1, 0), 1); EXPECT_EQ(midpoint<signed char>(0, 2), 1); EXPECT_EQ(midpoint<signed char>(3, 2), 3); EXPECT_EQ(midpoint<signed char>(-5, 4), -1); EXPECT_EQ(midpoint<signed char>(5, -4), 1); EXPECT_EQ(midpoint<signed char>(-5, -4), -5); EXPECT_EQ(midpoint<signed char>(-4, -5), -4); EXPECT_EQ(midpoint<signed char>(MY_SCHAR_MIN, MY_SCHAR_MAX), -1); EXPECT_EQ(midpoint<signed char>(MY_SCHAR_MAX, MY_SCHAR_MIN), 0); EXPECT_EQ(midpoint<signed char>(MY_SCHAR_MAX, MY_SCHAR_MAX), MY_SCHAR_MAX); EXPECT_EQ( midpoint<signed char>(MY_SCHAR_MAX, MY_SCHAR_MAX - 1), MY_SCHAR_MAX); constexpr auto MY_SIZE_T_MAX = std::numeric_limits<size_t>::max(); EXPECT_EQ(midpoint<size_t>(0, 0), 0); EXPECT_EQ(midpoint<size_t>(1, 1), 1); EXPECT_EQ(midpoint<size_t>(0, 1), 0); EXPECT_EQ(midpoint<size_t>(1, 0), 1); EXPECT_EQ(midpoint<size_t>(0, 2), 1); EXPECT_EQ(midpoint<size_t>(3, 2), 3); EXPECT_EQ(midpoint<size_t>((size_t)0, MY_SIZE_T_MAX), MY_SIZE_T_MAX / 2); EXPECT_EQ( midpoint<size_t>(MY_SIZE_T_MAX, (size_t)0), (MY_SIZE_T_MAX / 2 + 1)); EXPECT_EQ(midpoint<size_t>(MY_SIZE_T_MAX, MY_SIZE_T_MAX), MY_SIZE_T_MAX); EXPECT_EQ(midpoint<size_t>(MY_SIZE_T_MAX, MY_SIZE_T_MAX - 1), MY_SIZE_T_MAX); EXPECT_EQ( midpoint<size_t>(MY_SIZE_T_MAX - 1, MY_SIZE_T_MAX - 1), MY_SIZE_T_MAX - 1); EXPECT_EQ( midpoint<size_t>(MY_SIZE_T_MAX - 1, MY_SIZE_T_MAX), MY_SIZE_T_MAX - 1); EXPECT_EQ( midpoint<size_t>(MY_SIZE_T_MAX, MY_SIZE_T_MAX - 2), MY_SIZE_T_MAX - 1); #if FOLLY_HAVE_INT128_T const auto I128_MIN = std::numeric_limits<__int128_t>::min(); const auto I128_MAX = std::numeric_limits<__int128_t>::max(); EXPECT_EQ(midpoint<__int128_t>(0, 0), 0); EXPECT_EQ(midpoint<__int128_t>(1, 1), 1); EXPECT_EQ(midpoint<__int128_t>(0, 1), 0); EXPECT_EQ(midpoint<__int128_t>(1, 0), 1); EXPECT_EQ(midpoint<__int128_t>(0, 2), 1); EXPECT_EQ(midpoint<__int128_t>(3, 2), 3); EXPECT_EQ(midpoint<__int128_t>(-5, 4), -1); EXPECT_EQ(midpoint<__int128_t>(5, -4), 1); EXPECT_EQ(midpoint<__int128_t>(-5, -4), -5); EXPECT_EQ(midpoint<__int128_t>(-4, -5), -4); EXPECT_EQ(midpoint<__int128_t>(I128_MIN, I128_MAX), -1); EXPECT_EQ(midpoint<__int128_t>(I128_MAX, I128_MIN), 0); EXPECT_EQ(midpoint<__int128_t>(I128_MAX, I128_MAX), I128_MAX); EXPECT_EQ(midpoint<__int128_t>(I128_MAX, I128_MAX - 1), I128_MAX); #endif // Test every possibility for signed char. for (int a = MY_SCHAR_MIN; a <= MY_SCHAR_MAX; ++a) for (int b = MY_SCHAR_MIN; b <= MY_SCHAR_MAX; ++b) EXPECT_EQ(midpoint(a, b), midpoint<int>(a, b)); EXPECT_FALSE((is_invocable_v<midpoint_invoke, void>)); EXPECT_FALSE((is_invocable_v<midpoint_invoke, int()>)); EXPECT_FALSE((is_invocable_v<midpoint_invoke, int&>)); EXPECT_FALSE((is_invocable_v<midpoint_invoke, struct Incomplete>)); constexpr std::array<int, 3> ca = {0, 1, 2}; EXPECT_EQ(midpoint(ca.data(), ca.data() + 3), ca.data() + 1); constexpr std::array<int, 4> a = {0, 1, 2, 3}; EXPECT_EQ(midpoint(a.data(), a.data()), a.data()); EXPECT_EQ(midpoint(a.data(), a.data() + 1), a.data()); EXPECT_EQ(midpoint(a.data(), a.data() + 2), a.data() + 1); EXPECT_EQ(midpoint(a.data(), a.data() + 3), a.data() + 1); EXPECT_EQ(midpoint(a.data(), a.data() + 4), a.data() + 2); EXPECT_EQ(midpoint(a.data() + 1, a.data()), a.data() + 1); EXPECT_EQ(midpoint(a.data() + 2, a.data()), a.data() + 1); EXPECT_EQ(midpoint(a.data() + 3, a.data()), a.data() + 2); EXPECT_EQ(midpoint(a.data() + 4, a.data()), a.data() + 2); }
7,745
8,905
from __future__ import print_function, division, absolute_import from .voc import Voc2007Classification
23
2,094
<gh_stars>1000+ //////////////////////////////////////////////////////////////////////////////////////////////////// // // Project: Embedded Learning Library (ELL) // File: MultivariateLoss.h (optimization) // Authors: <NAME> // //////////////////////////////////////////////////////////////////////////////////////////////////// #pragma once #include <math/include/Vector.h> namespace ell { namespace optimization { /// <summary> Adapter that extends a scalar loss class to vector inputs. </summary> template <typename LossType> class MultivariateLoss { public: /// <summary> Constructor. </summary> MultivariateLoss(LossType univariateLoss = {}); /// <summary> Checks if an output is compatible with this loss. </summary> template <typename OutputElementType> bool VerifyOutput(math::ConstRowVectorReference<OutputElementType> output) const; /// <summary> Returns the loss of a vector prediction, given the true vector output. </summary> /// /// <param name="prediction"> The predicted output. </param> /// <param name="output"> The true output. </param> /// /// <returns> The loss. </returns> template <typename OutputElementType> double Value(math::ConstRowVectorReference<double> prediction, math::ConstRowVectorReference<OutputElementType> output) const; /// <summary> Returns the loss gradient at a given vector point. </summary> /// /// <param name="prediction"> The predicted output. </param> /// <param name="output"> The true output. </param> /// /// <returns> The loss gradient. </returns> template <typename OutputElementType> math::RowVector<double> Derivative(math::ConstRowVectorReference<double> prediction, math::ConstRowVectorReference<OutputElementType> output) const; /// <summary> Returns the value of the loss conjugate at a given vector point. </summary> /// /// <param name="dual"> The dual variable. </param> /// <param name="output"> The output. </param> /// /// <returns> Value of the loss conjugate. </returns> template <typename OutputElementType> double Conjugate(math::ConstRowVectorReference<double> dual, math::ConstRowVectorReference<OutputElementType> output) const; /// <summary> /// Returns the value of the proximal operator of the conjugate of the loss, which is /// /// argmin_b {theta*g(b) + (1/2)*||b - a||_2^2} /// /// where ||x||_2 is the 2-norm and g() is the convex conjugate of f() /// </summary> /// /// <param name="sigma"> The sigma parameter. </param> /// <param name="prediction"> The prediction. </param> /// <param name="output"> The output. </param> /// /// <returns> Value of the loss conjugate prox. </returns> template <typename OutputElementType> math::RowVector<double> ConjugateProx(double sigma, math::ConstRowVectorReference<double> prediction, math::ConstRowVectorReference<OutputElementType> output) const; private: LossType _univariateLoss; }; } // namespace optimization } // namespace ell #pragma region implementation namespace ell { namespace optimization { template <typename LossType> MultivariateLoss<LossType>::MultivariateLoss(LossType univariateLoss) : _univariateLoss(std::move(univariateLoss)) {} template <typename LossType> template <typename OutputElementType> bool MultivariateLoss<LossType>::VerifyOutput(math::ConstRowVectorReference<OutputElementType> output) const { for (size_t i = 0; i < output.Size(); ++i) { if (!_univariateLoss.VerifyOutput(output[i])) { return false; } } return true; } template <typename LossType> template <typename OutputElementType> double MultivariateLoss<LossType>::Value(math::ConstRowVectorReference<double> prediction, math::ConstRowVectorReference<OutputElementType> output) const { double result = 0; for (size_t i = 0; i < prediction.Size(); ++i) { result += _univariateLoss.Value(prediction[i], output[i]); } return result; } template <typename LossType> template <typename OutputElementType> math::RowVector<double> MultivariateLoss<LossType>::Derivative(math::ConstRowVectorReference<double> prediction, math::ConstRowVectorReference<OutputElementType> output) const { math::RowVector<double> result(prediction.Size()); for (size_t i = 0; i < prediction.Size(); ++i) { result[i] = _univariateLoss.Derivative(prediction[i], output[i]); } return result; } template <typename LossType> template <typename OutputElementType> double MultivariateLoss<LossType>::Conjugate(math::ConstRowVectorReference<double> dual, math::ConstRowVectorReference<OutputElementType> output) const { double result = 0; for (size_t i = 0; i < dual.Size(); ++i) { result += _univariateLoss.Conjugate(dual[i], output[i]); } return result; } template <typename LossType> template <typename OutputElementType> math::RowVector<double> MultivariateLoss<LossType>::ConjugateProx(double sigma, math::ConstRowVectorReference<double> prediction, math::ConstRowVectorReference<OutputElementType> output) const { math::RowVector<double> result(prediction.Size()); for (size_t i = 0; i < prediction.Size(); ++i) { result[i] = _univariateLoss.ConjugateProx(sigma, prediction[i], output[i]); } return result; } } // namespace optimization } // namespace ell #pragma endregion implementation
2,198
6,958
// // ResizeFunction.h // MNN // // Created by MNN on 2018/07/23. // Copyright © 2018, Alibaba Group Holding Limited // #ifndef ResizeFunction_h #define ResizeFunction_h #include <stdint.h> #include <stdio.h> #ifdef __cplusplus extern "C" { #endif void MNNCubicSampleC4(const float* src, float* dst, int32_t* position, const float* factor, size_t number); void MNNCubicLineC4(float* dst, const float* A, const float* B, const float* C, const float* D, float* t, size_t number); #ifdef __cplusplus } #endif #endif /* ResizeFunction_hpp */
226
1,253
<reponame>bakuryuthem0/al-go-rithms<gh_stars>1000+ #include <bits/stdc++.h> using namespace std; int sum_arr(int freq[], int i, int j){ int sum = 0; for(int k=i; k<=j; k++){ sum+=freq[k]; } return sum; } int optimal_binary_tree(int arr[], int freq[], int n){ /*int sum_arr[n+1]; sum_arr[0]=0; for(int i=1; i<=n; i++){ sum_arr[i] = sum_arr[i-1] + freq[i-1]; } for(int i=0; i<=n; i++) cout<<sum_arr[i]<<" "; cout<<endl;*/ int dp[n][n]; for(int i=0; i<n; i++) dp[i][i] = freq[i]; for(int l=2; l<=n; l++){ for(int i=0; i<=n-l; i++){ int j = i+l-1; dp[i][j] = INT_MAX; for(int k=i; k<=j; k++){ int sum = sum_arr(freq, i, j) + ((k>i)? dp[i][k-1]:0) + ((k<j)? dp[k+1][j]:0); if(sum<dp[i][j]) dp[i][j] = sum; } } } for(int i=0; i<n; i++){ for(int j=0; j<n; j++){ cout<<dp[i][j]<<" "; } cout<<endl; } return dp[0][n-1]; } int main(){ int n; cout<<"Enter the no. of elements in array: "; cin>>n; int arr[n]; cout<<"\nEnter array of elements: "; for(int i=0; i<n; i++){ cin>>arr[i]; } cout<<"\nEnter the search frequencies for each element: "; int freq[n]; for(int i=0; i<n; i++) cin>>freq[i]; int optimal_cost = optimal_binary_tree(arr, freq, n); cout<<"\nOptimal cost: "<<optimal_cost<<endl; return 0; }
914
393
package com.marverenic.music.ui.library.playlist.contents.edit; import android.content.Context; import android.content.Intent; import android.os.Bundle; import androidx.fragment.app.Fragment; import com.marverenic.music.model.AutoPlaylist; import com.marverenic.music.ui.SingleFragmentActivity; public class AutoPlaylistEditActivity extends SingleFragmentActivity { private static final String PLAYLIST_EXTRA = "AutoPlaylistEditActivity.PLAYLIST"; public static Intent newIntent(Context context) { return newIntent(context, null); } public static Intent newIntent(Context context, AutoPlaylist target) { Intent intent = new Intent(context, AutoPlaylistEditActivity.class); intent.putExtra(PLAYLIST_EXTRA, target); return intent; } @Override protected Fragment onCreateFragment(Bundle savedInstanceState) { AutoPlaylist playlist = getIntent().getParcelableExtra(PLAYLIST_EXTRA); return AutoPlaylistEditFragment.newInstance(this, playlist); } }
342
14,668
<gh_stars>1000+ // 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 BASE_TASK_SEQUENCE_MANAGER_TIME_DOMAIN_H_ #define BASE_TASK_SEQUENCE_MANAGER_TIME_DOMAIN_H_ #include "base/check.h" #include "base/task/sequence_manager/lazy_now.h" #include "base/task/sequence_manager/tasks.h" #include "base/time/tick_clock.h" #include "base/values.h" #include "third_party/abseil-cpp/absl/types/optional.h" namespace base { namespace sequence_manager { class SequenceManager; namespace internal { class SequenceManagerImpl; } // namespace internal // TimeDomain allows subclasses to enable clock overriding // (e.g. auto-advancing virtual time, throttled clock, etc). class BASE_EXPORT TimeDomain : public TickClock { public: TimeDomain(const TimeDomain&) = delete; TimeDomain& operator=(const TimeDomain&) = delete; ~TimeDomain() override = default; // Returns the desired ready time based on the predetermined `next_wake_up`, // is_null() if ready immediately, or is_max() to ignore the wake-up. This is // typically aligned with `next_wake_up.time` but virtual time domains may // elect otherwise. Can be called from main thread only. // TODO(857101): Pass `lazy_now` by reference. virtual TimeTicks GetNextDelayedTaskTime(WakeUp next_wake_up, LazyNow* lazy_now) const = 0; // Invoked when the thread reaches idle. Gives an opportunity to a virtual // time domain impl to fast-forward time and return true to indicate that // there's more work to run. If RunLoop::QuitWhenIdle has been called then // `quit_when_idle_requested` will be true. virtual bool MaybeFastForwardToWakeUp(absl::optional<WakeUp> next_wake_up, bool quit_when_idle_requested) = 0; // Debug info. Value AsValue() const; protected: TimeDomain() = default; virtual const char* GetName() const = 0; // Tells SequenceManager that internal policy might have changed to // re-evaluate GetNextDelayedTaskTime()/MaybeFastForwardToWakeUp(). void NotifyPolicyChanged(); // Called when the TimeDomain is assigned to a SequenceManagerImpl. // `sequence_manager` is expected to be valid for the duration of TimeDomain's // existence. TODO(scheduler-dev): Pass SequenceManager in the constructor. void OnAssignedToSequenceManager( internal::SequenceManagerImpl* sequence_manager); private: friend class internal::SequenceManagerImpl; internal::SequenceManagerImpl* sequence_manager_ = nullptr; // Not owned. }; } // namespace sequence_manager } // namespace base #endif // BASE_TASK_SEQUENCE_MANAGER_TIME_DOMAIN_H_
896
606
package org.arend.typechecking.implicitargs; import org.arend.Matchers; import org.arend.core.context.binding.Binding; import org.arend.core.context.binding.LevelVariable; import org.arend.core.context.binding.TypedBinding; import org.arend.core.context.param.SingleDependentLink; import org.arend.core.expr.Expression; import org.arend.core.expr.PiExpression; import org.arend.core.sort.Level; import org.arend.ext.core.ops.NormalizationMode; import org.arend.typechecking.TypeCheckingTestCase; import org.arend.typechecking.error.local.PathEndpointMismatchError; import org.arend.typechecking.error.local.inference.ArgInferenceError; import org.arend.typechecking.result.TypecheckingResult; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static org.arend.ExpressionFactory.*; import static org.arend.core.expr.ExpressionFactory.*; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.*; public class ImplicitArgumentsTest extends TypeCheckingTestCase { @Test public void inferId() { // f : {A : Type0} -> A -> A |- f 0 : N List<Binding> context = new ArrayList<>(); SingleDependentLink A = singleParams(false, vars("A"), Universe(0)); context.add(new TypedBinding("f", Pi(A, Pi(Ref(A), Ref(A))))); TypecheckingResult result = typeCheckExpr(context, "f 0", null); Expression expr = Apps(Ref(context.get(0)), Nat(), Zero()); assertEquals(expr, result.expression); assertEquals(Nat(), result.type); } @Test public void unexpectedImplicit() { // f : N -> N |- f {0} 0 : N List<Binding> context = new ArrayList<>(); context.add(new TypedBinding("f", Pi(Nat(), Nat()))); assertThat(typeCheckExpr(context, "f {0} 0", null, 1), is(nullValue())); } @Test public void tooManyArguments() { // f : (x : N) {y : N} (z : N) -> N |- f 0 0 0 : N List<Binding> context = new ArrayList<>(); context.add(new TypedBinding("f", Pi(singleParam("x", Nat()), Pi(singleParams(false, vars("y"), Nat()), Pi(singleParam("z", Nat()), Nat()))))); assertThat(typeCheckExpr(context, "f 0 0 0", null, 1), is(nullValue())); } @Test public void cannotInfer() { // f : {A B : Type0} -> A -> A |- f 0 : N List<Binding> context = new ArrayList<>(); SingleDependentLink params = singleParams(false, vars("A", "B"), Universe(0)); context.add(new TypedBinding("f", Pi(params, Pi(Ref(params), Ref(params))))); typeCheckExpr(context, "f 0", null, 1); assertTrue(errorList.get(0) instanceof ArgInferenceError); } @Test public void inferLam() { // f : {A : Type0} -> ((A -> Nat) -> Nat) -> A |- f (\g. g 0) : Nat List<Binding> context = new ArrayList<>(); SingleDependentLink A = singleParams(false, vars("A"), Universe(0)); context.add(new TypedBinding("f", Pi(A, Pi(Pi(Pi(Ref(A), Nat()), Nat()), Ref(A))))); TypecheckingResult result = typeCheckExpr(context, "f (\\lam g => g 0)", null); SingleDependentLink g = singleParam("g", Pi(Nat(), Nat())); Expression expr = Apps(Ref(context.get(0)), Nat(), Lam(g, Apps(Ref(g), Zero()))); assertEquals(expr, result.expression); assertEquals(Nat(), result.type); } @Test public void inferFromFunction() { // s : Nat -> Nat, f : {A : Type0} -> (Nat -> A) -> A |- f s : Nat List<Binding> context = new ArrayList<>(2); SingleDependentLink A = singleParams(false, vars("A"), Universe(0)); context.add(new TypedBinding("s", Pi(Nat(), Nat()))); context.add(new TypedBinding("f", Pi(A, Pi(Pi(Nat(), Ref(A)), Ref(A))))); TypecheckingResult result = typeCheckExpr(context, "f s", null); Expression expr = Apps(Ref(context.get(1)), Nat(), Ref(context.get(0))); assertEquals(expr, result.expression); assertEquals(Nat(), result.type); } @Test public void inferFromLam() { // f : {A : Type0} -> (Nat -> A) -> A |- f (\x y. suc y) : Nat -> Nat List<Binding> context = new ArrayList<>(); SingleDependentLink A = singleParams(false, vars("A"), Universe(0)); context.add(new TypedBinding("f", Pi(A, Pi(Pi(Nat(), Ref(A)), Ref(A))))); TypecheckingResult result = typeCheckExpr(context, "f (\\lam x y => suc y)", null); SingleDependentLink xy = singleParams(true, vars("x", "y"), Nat()); Expression expr = Apps(Ref(context.get(0)), Pi(Nat(), Nat()), Lam(xy, Suc(Ref(xy.getNext())))); assertEquals(expr, result.expression); assertEquals(Pi(Nat(), Nat()), result.type); } @Test public void inferFromLamType() { // f : {A : Type0} -> (Nat -> A) -> A |- f (\x (y : Nat -> Nat). y x) : (Nat -> Nat) -> Nat List<Binding> context = new ArrayList<>(); SingleDependentLink A = singleParams(false, vars("A"), Universe(0)); context.add(new TypedBinding("f", Pi(A, Pi(Pi(Nat(), Ref(A)), Ref(A))))); TypecheckingResult result = typeCheckExpr(context, "f (\\lam x (y : Nat -> Nat) => y x)", null); SingleDependentLink x = singleParam("x", Nat()); SingleDependentLink y = singleParam("y", Pi(Nat(), Nat())); Expression arg = Lam(x, Lam(y, Apps(Ref(y), Ref(x)))); Expression expr = Apps(Ref(context.get(0)), Pi(Pi(Nat(), Nat()), Nat()), arg); assertEquals(expr, result.expression); assertEquals(Pi(Pi(Nat(), Nat()), Nat()), result.type); } @Test public void inferFromSecondArg() { // f : {A : Type0} -> (A -> A) -> (A -> Nat) -> Nat |- f (\x. x) (\x. x) : Nat List<Binding> context = new ArrayList<>(); SingleDependentLink A = singleParams(false, vars("A"), Universe(0)); context.add(new TypedBinding("f", Pi(A, Pi(Pi(Ref(A), Ref(A)), Pi(Pi(Ref(A), Nat()), Nat()))))); TypecheckingResult result = typeCheckExpr(context, "f (\\lam x => x) (\\lam x => x)", null); SingleDependentLink x = singleParam("x", Nat()); Expression expr = Apps(Ref(context.get(0)), Nat(), Lam(x, Ref(x)), Lam(x, Ref(x))); assertEquals(expr, result.expression); assertEquals(Nat(), result.type); } @Test public void inferFromSecondArgLam() { // f : {A : Type0} -> (A -> A) -> (A -> Nat) -> Nat |- f (\x. x) (\(x : Nat). x) : Nat List<Binding> context = new ArrayList<>(); SingleDependentLink A = singleParams(false, vars("A"), Universe(0)); context.add(new TypedBinding("f", Pi(A, Pi(Pi(Ref(A), Ref(A)), Pi(Pi(Ref(A), Nat()), Nat()))))); TypecheckingResult result = typeCheckExpr(context, "f (\\lam x => x) (\\lam (x : Nat) => x)", null); SingleDependentLink x = singleParam("x", Nat()); Expression expr = Apps(Ref(context.get(0)), Nat(), Lam(x, Ref(x)), Lam(x, Ref(x))); assertEquals(expr, result.expression); assertEquals(Nat(), result.type); } @Test public void inferFromTheGoal() { // f : {A : Type0} -> Nat -> A -> A |- f 0 : Nat -> Nat List<Binding> context = new ArrayList<>(); SingleDependentLink A = singleParams(false, vars("A"), Universe(0)); context.add(new TypedBinding("f", Pi(A, Pi(Nat(), Pi(Ref(A), Ref(A)))))); TypecheckingResult result = typeCheckExpr(context, "f 0", Pi(Nat(), Nat())); Expression expr = Apps(Ref(context.get(0)), Nat(), Zero()); assertEquals(expr, result.expression); assertEquals(Pi(Nat(), Nat()), result.type); } @Test public void inferFromTheGoalError() { // f : {A : Type0} -> Nat -> A -> A |- f 0 : Nat -> Nat -> Nat List<Binding> context = new ArrayList<>(); SingleDependentLink A = singleParams(false, vars("A"), Universe(0)); context.add(new TypedBinding("f", Pi(A, Pi(Nat(), Pi(Ref(A), Ref(A)))))); typeCheckExpr(context, "f 0", Pi(Nat(), Pi(Nat(), Nat())), 1); } @Test public void inferCheckTypeError() { // I : Type1 -> Type1, i : I Type0, f : {A : Type0} -> I A -> Nat |- f i : Nat List<Binding> context = new ArrayList<>(); context.add(new TypedBinding("I", Pi(Universe(1), Universe(1)))); context.add(new TypedBinding("i", Apps(Ref(context.get(0)), Universe(0)))); SingleDependentLink A = singleParams(false, vars("A"), Universe(0)); context.add(new TypedBinding("f", Pi(A, Pi(Apps(Ref(context.get(0)), Ref(A)), Nat())))); typeCheckExpr(context, "f i", null, 1); } @Test public void inferTail() { // I : Nat -> Type0, i : {x : Nat} -> I (suc x) |- i : I (suc (suc 0)) List<Binding> context = new ArrayList<>(); context.add(new TypedBinding("I", Pi(Nat(), Universe(0)))); SingleDependentLink x = singleParams(false, vars("x"), Nat()); context.add(new TypedBinding("i", Pi(x, Apps(Ref(context.get(0)), Suc(Ref(x)))))); Expression type = Apps(Ref(context.get(0)), Suc(Suc(Zero()))); TypecheckingResult result = typeCheckExpr(context, "i", type); Expression expr = Apps(Ref(context.get(1)), Suc(Zero())); assertEquals(expr, result.expression); assertEquals(type, result.type); } @Test public void inferTail2() { // I : Nat -> Type0, i : {x : Nat} -> I x |- i : {x : Nat} -> I x List<Binding> context = new ArrayList<>(); context.add(new TypedBinding("I", Pi(Nat(), Universe(0)))); SingleDependentLink x = singleParams(false, vars("x"), Nat()); PiExpression type = Pi(x, Apps(Ref(context.get(0)), Ref(x))); context.add(new TypedBinding("i", type)); TypecheckingResult result = typeCheckExpr(context, "i", type); assertEquals(Ref(context.get(1)), result.expression); assertEquals(type, result.type); } @Test public void inferTailError() { // I : Type1 -> Type1, i : {x : Type0} -> I x |- i : I Type0 List<Binding> context = new ArrayList<>(); context.add(new TypedBinding("I", Pi(Universe(1), Universe(1)))); SingleDependentLink x = singleParams(false, vars("x"), Universe(0)); context.add(new TypedBinding("i", Pi(x, Apps(Ref(context.get(0)), Ref(x))))); typeCheckExpr(context, "i", Apps(Ref(context.get(0)), Universe(0)), 1); } @Test public void inferUnderLet() { // f : {A : Type0} -> (A -> A) -> A -> A |- let | x {A : Type0} (y : A -> A) = f y | z (x : Nat) = x \in x z : List<Binding> context = new ArrayList<>(); SingleDependentLink A = singleParams(false, vars("A"), Universe(0)); context.add(new TypedBinding("f", Pi(A, Pi(singleParam(null, Pi(Ref(A), Ref(A))), Pi(singleParam(null, Ref(A)), Ref(A)))))); String term = "\\let\n" + " | x {A : \\oo-Type0} (y : A -> A) => f y\n" + " | z (x : Nat) => x\n" + "\\in x z"; TypecheckingResult result = typeCheckExpr(context, term, null); assertEquals(Pi(Nat(), Nat()), result.type.normalize(NormalizationMode.WHNF)); } @Test public void untypedLambda1() { // f : (A : \Type0) (a : A) -> Nat |- \x1 x2. f x1 x2 SingleDependentLink A = singleParam("A", Universe(0)); PiExpression type = Pi(A, Pi(singleParam("a", Ref(A)), Nat())); List<Binding> context = new ArrayList<>(); context.add(new TypedBinding("f", type)); typeCheckExpr(context, "\\lam x1 x2 => f x1 x2", null); } @Test public void untypedLambda2() { // f : (A : Type) (B : A -> Type) (a : A) -> B a |- \x1 x2 x3. f x1 x2 x3 SingleDependentLink A = singleParam("A", Universe(0)); SingleDependentLink B = singleParam("B", Pi(Ref(A), Universe(0))); SingleDependentLink a = singleParam("a", Ref(A)); PiExpression type = Pi(A, Pi(B, Pi(a, Apps(Ref(B), Ref(a))))); List<Binding> context = new ArrayList<>(); context.add(new TypedBinding("f", type)); TypecheckingResult result = typeCheckExpr(context, "\\lam x1 x2 x3 => f x1 x2 x3", null); A.setType(Universe(new Level(0), new Level(LevelVariable.HVAR))); B.setType(Pi(Ref(A), Universe(new Level(0), new Level(LevelVariable.HVAR)))); assertEquals(type, result.type); } @Test public void untypedLambdaError1() { // f : (A : \Type0) (a : A) -> Nat |- \x1 x2. f x2 x1 SingleDependentLink A = singleParam("A", Universe(0)); PiExpression type = Pi(A, Pi(singleParam("a", Ref(A)), Nat())); List<Binding> context = new ArrayList<>(); context.add(new TypedBinding("f", type)); typeCheckExpr(context, "\\lam x1 x2 => f x2 x1", null, 1); } @Test public void untypedLambdaError2() { // f : (A : Type0) (B : A -> Type0) (a : A) -> B a |- \x1 x2 x3. f x2 x1 x3 SingleDependentLink A = singleParam("A", Universe(0)); SingleDependentLink B = singleParam("B", Pi(Ref(A), Universe(0))); SingleDependentLink a = singleParam("a", Ref(A)); PiExpression type = Pi(A, Pi(B, Pi(a, Apps(Ref(B), Ref(a))))); List<Binding> context = new ArrayList<>(); context.add(new TypedBinding("f", type)); typeCheckExpr(context, "\\lam x1 x2 x3 => f x2 x1 x3", null, 1); } @Test public void inferLater() { // f : {A : \Type0} (B : \Type1) -> A -> B -> A |- f Nat (\lam x => x) 0 : Nat -> Nat List<Binding> context = new ArrayList<>(); SingleDependentLink A = singleParams(false, vars("A"), Universe(0)); SingleDependentLink B = singleParams(true, vars("B"), Universe(1)); context.add(new TypedBinding("f", Pi(A, Pi(B, Pi(Ref(A), Pi(Ref(B), Ref(A))))))); typeCheckExpr(context, "f Nat (\\lam x => x) 0", Pi(Nat(), Nat())); } @Test public void inferUnderPi() { typeCheckModule( "\\func $ {X Y : \\Type0} (f : X -> Y) (x : X) => f x\n" + "\\func foo (A : \\Type0) (B : A -> \\Type0) (f : \\Pi (a : A) -> B a) (a' : A) => f $ a'", 1); } @Test public void inferUnderPiExpected() { typeCheckModule( "\\func $ {X Y : \\Type0} (f : X -> Y) (x : X) => f x\n" + "\\func foo (A : \\Type0) (B : A -> \\Type0) (f : \\Pi (a : A) -> B a) (a' : A) : B a' => f $ a'", 1); } @Test public void inferPathCon() { typeCheckDef("\\func f : 1 = 1 => path (\\lam _ => 0)", 2); assertThatErrorsAre(Matchers.typecheckingError(PathEndpointMismatchError.class), Matchers.typecheckingError(PathEndpointMismatchError.class)); } @Test public void inferPathCon0() { typeCheckDef("\\func f : 1 = 1 => path {\\lam _ => Nat} (\\lam _ => 0)", 1); assertThatErrorsAre(Matchers.typeMismatchError()); } @Test public void inferPathCon1() { typeCheckDef("\\func f : 1 = 0 => path {\\lam _ => Nat} {1} (\\lam _ => 0)", 1); assertThatErrorsAre(Matchers.typecheckingError(PathEndpointMismatchError.class)); } @Test public void inferPathCon2() { typeCheckDef("\\func f : 1 = 1 => path {\\lam _ => Nat} {0} (\\lam _ => 0)", 1); assertThatErrorsAre(Matchers.typeMismatchError()); } @Test public void inferPathCon3() { typeCheckDef("\\func f : 1 = 1 => path {\\lam _ => Nat} {1} {1} (\\lam _ => 0)", 2); assertThatErrorsAre(Matchers.typecheckingError(PathEndpointMismatchError.class), Matchers.typecheckingError(PathEndpointMismatchError.class)); } @Test public void pathWithoutArg() { typeCheckDef("\\func f => path", 1); } @Test public void pathWithoutArg1() { typeCheckDef("\\func f : \\Pi {A : I -> \\Type0} {a : A left} {a' : A right} (\\Pi (i : I) -> A i) -> Path A a a' => path", 1); } @Test public void pathWithoutArg2() { typeCheckDef("\\func f => path {\\lam _ => Nat}", 1); } @Test public void pathWithoutArg3() { typeCheckDef("\\func f => path {\\lam _ => Nat} {0}", 1); } @Test public void pathWithoutArg4() { typeCheckDef("\\func f => path {\\lam _ => Nat} {0} {0}", 1); } @Test public void orderTest1() { typeCheckModule( "\\func idpOver (A : I -> \\Type0) (a : A left) : Path A a (coe A a right) => path (coe A a)\n" + "\\func test {A : \\Type0} (P : A -> \\Type0) {a a' : A} (q : a = a') (pa : P a) (i : I)\n" + " => idpOver (\\lam (j : I) => P (q @ j)) pa @ i\n"); } @Test public void orderTest2() { typeCheckModule( "\\func idpOver (A : I -> \\Type0) (a : A left) : Path A a (coe A a right) => path (coe A a)\n" + "\\func test {A : \\Type0} (P : A -> \\Type0) {a : A} (pa : P a) (i : I)\n" + " => \\lam (a' : A) (q : a = a') => idpOver (\\lam (j : I) => P (q @ j)) pa @ i"); } @Test public void differentLevels() { typeCheckModule( "\\func F (X : \\Type \\lp) (B : X -> \\Type \\lp) => zero\n" + "\\func g (X : \\Type \\lp) => F X (\\lam _ => X = X)"); } @Test public void piTest() { typeCheckDef("\\func f (A : \\Type \\lp) (B : A -> \\Type \\lp) (f g : \\Pi (x : A) -> B x) => f = g"); } @Test public void etaExpansionTest() { typeCheckModule( "\\func \\infixr 9 $ {A B : \\Set0} (f : A -> B) (a : A) => f a\n" + "\\data Fin Nat \\with | n => fzero | suc n => fsuc (Fin n)\n" + "\\func unsuc {n : Nat} (x : Fin (suc n)) : Fin n \\elim n, x\n" + " | _, fzero => fzero\n" + " | zero, fsuc x => fzero\n" + " | suc n, fsuc x => fsuc (unsuc x)\n" + "\\func foo {n : Nat} (x : Fin n) : Nat \\elim n\n" + " | zero => zero\n" + " | suc n' => foo $ unsuc x"); } @Test public void freeVars() { typeCheckModule( "\\func f {n : Nat} {g : Nat -> Nat} (p : g = (\\lam x => n)) => 0\n" + "\\func h => f (path (\\lam _ x => x))", 1); } }
6,875
2,151
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chromeos/components/tether/fake_ble_connection_manager.h" #include "chromeos/components/tether/timer_factory.h" #include "device/bluetooth/bluetooth_adapter.h" namespace chromeos { namespace tether { FakeBleConnectionManager::StatusAndRegisteredConnectionReasons:: StatusAndRegisteredConnectionReasons() : status(cryptauth::SecureChannel::Status::DISCONNECTED) {} FakeBleConnectionManager::StatusAndRegisteredConnectionReasons:: StatusAndRegisteredConnectionReasons( const StatusAndRegisteredConnectionReasons& other) = default; FakeBleConnectionManager::StatusAndRegisteredConnectionReasons:: ~StatusAndRegisteredConnectionReasons() = default; FakeBleConnectionManager::FakeBleConnectionManager() : BleConnectionManager(nullptr, nullptr, nullptr, nullptr, nullptr, nullptr) {} FakeBleConnectionManager::~FakeBleConnectionManager() = default; void FakeBleConnectionManager::SetDeviceStatus( const std::string& device_id, const cryptauth::SecureChannel::Status& status, BleConnectionManager::StateChangeDetail state_change_detail) { const auto iter = device_id_map_.find(device_id); DCHECK(iter != device_id_map_.end()); cryptauth::SecureChannel::Status old_status = iter->second.status; if (old_status == status) { // If the status has not changed, do not do anything. return; } iter->second.status = status; NotifySecureChannelStatusChanged(device_id, old_status, status, state_change_detail); } void FakeBleConnectionManager::ReceiveMessage(const std::string& device_id, const std::string& payload) { DCHECK(device_id_map_.find(device_id) != device_id_map_.end()); NotifyMessageReceived(device_id, payload); } void FakeBleConnectionManager::SetMessageSent(int sequence_number) { DCHECK(sequence_number < next_sequence_number_); NotifyMessageSent(sequence_number); } void FakeBleConnectionManager::SimulateUnansweredConnectionAttempts( const std::string& device_id, size_t num_attempts) { for (size_t i = 0; i < num_attempts; ++i) { SetDeviceStatus(device_id, cryptauth::SecureChannel::Status::CONNECTING, StateChangeDetail::STATE_CHANGE_DETAIL_NONE); SetDeviceStatus( device_id, cryptauth::SecureChannel::Status::DISCONNECTED, StateChangeDetail::STATE_CHANGE_DETAIL_COULD_NOT_ATTEMPT_CONNECTION); } } void FakeBleConnectionManager::SimulateGattErrorConnectionAttempts( const std::string& device_id, size_t num_attempts) { for (size_t i = 0; i < num_attempts; ++i) { SetDeviceStatus(device_id, cryptauth::SecureChannel::Status::CONNECTING, StateChangeDetail::STATE_CHANGE_DETAIL_NONE); SetDeviceStatus(device_id, cryptauth::SecureChannel::Status::CONNECTED, StateChangeDetail::STATE_CHANGE_DETAIL_NONE); SetDeviceStatus(device_id, cryptauth::SecureChannel::Status::AUTHENTICATING, StateChangeDetail::STATE_CHANGE_DETAIL_NONE); SetDeviceStatus( device_id, cryptauth::SecureChannel::Status::DISCONNECTED, StateChangeDetail::STATE_CHANGE_DETAIL_GATT_CONNECTION_WAS_ATTEMPTED); } } bool FakeBleConnectionManager::IsRegistered(const std::string& device_id) { return base::ContainsKey(device_id_map_, device_id); } void FakeBleConnectionManager::RegisterRemoteDevice( const std::string& device_id, const ConnectionReason& connection_reason) { StatusAndRegisteredConnectionReasons& value = device_id_map_[device_id]; value.registered_message_types.insert(connection_reason); } void FakeBleConnectionManager::UnregisterRemoteDevice( const std::string& device_id, const ConnectionReason& connection_reason) { StatusAndRegisteredConnectionReasons& value = device_id_map_[device_id]; value.registered_message_types.erase(connection_reason); if (value.registered_message_types.empty()) device_id_map_.erase(device_id); } int FakeBleConnectionManager::SendMessage(const std::string& device_id, const std::string& message) { sent_messages_.push_back({device_id, message}); return next_sequence_number_++; } bool FakeBleConnectionManager::GetStatusForDevice( const std::string& device_id, cryptauth::SecureChannel::Status* status) const { const auto iter = device_id_map_.find(device_id); if (iter == device_id_map_.end()) return false; *status = iter->second.status; return true; } } // namespace tether } // namespace chromeos
1,784
1,159
#ifndef TEXT_NATURALCMP #define TEXT_NATURALCMP #include <string> namespace Text { class NaturalCmp { public: NaturalCmp(bool ignoreCase = true, bool ignoreSpace = true); bool operator()(const std::string &, const std::string &) const; private: bool ignoreCase; bool ignoreSpace; int cmp(const char *&, const char *&) const; int cmpChar(const char *&, const char *&) const; static int cmpNum(const char *&, const char *&); static void skipSpaces(const char *&); }; } #endif
177
698
<filename>third_party/tests/Opentitan/hw/vendor/lowrisc_ibex/dv/cs_registers/rst_driver/reset_driver.cc<gh_stars>100-1000 // Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 #include "reset_driver.h" extern "C" void rst_register_intf(std::string name, ResetDriver *intf); extern "C" void rst_deregister_intf(std::string name); ResetDriver::ResetDriver(std::string name) : reset_delay_(1), reset_duration_(0), name_(name) {} void ResetDriver::OnInitial(unsigned int seed) { generator_.seed(seed); // 100 to 1000 cycles between resets delay_dist_ = std::uniform_int_distribution<int>(100, 1000); rst_register_intf(name_, this); } void ResetDriver::OnFinal() { rst_deregister_intf(name_); } void ResetDriver::DriveReset(unsigned char *rst_n) { reset_delay_--; if (reset_delay_ == 0) { reset_delay_ = delay_dist_(generator_); reset_duration_ = 0; } if (reset_duration_ < 3) { reset_duration_++; *rst_n = false; } else { *rst_n = true; } }
414
2,921
<gh_stars>1000+ { "name": "ShibaKen.Finance", "website": "https://shibaken.io", "description": "A community-first protocol procuring a bridge to the blockchain - enabling individuals to purchase cryptocurrency.", "explorer": "https://etherscan.io/token/0xa4Cf2aFD3B165975afFFBf7e487CDd40C894Ab6B", "type": "ERC20", "symbol": "SHIBAKEN", "status": "active", "decimals": 0, "id": "0xa4Cf2aFD3B165975afFFBf7e487CDd40C894Ab6B" }
202
409
// Copyright (c) 2013-2020 <NAME> // License: Academic Free License ("AFL") v. 3.0 // AFL License page: https://opensource.org/licenses/AFL-3.0 #pragma once #include <SFML/Window/Mouse.hpp> #include <SFML/Window/Keyboard.hpp> namespace ssvs::Input { class Trigger; class Combo; } // namespace ssvs::Input namespace sf { template <typename T> class Vector2; using Vector2f = Vector2<float>; class Color; } // namespace sf namespace Json { class Value; } namespace ssvuj { using Obj = Json::Value; template <typename> struct Converter; } // namespace ssvuj namespace ssvuj { template <> struct Converter<sf::Vector2f> { using T = sf::Vector2f; static void fromObj(const Obj& mObj, T& mValue); static void toObj(Obj& mObj, const T& mValue); }; template <> struct Converter<sf::Color> { using T = sf::Color; static void fromObj(const Obj& mObj, T& mValue); static void toObj(Obj& mObj, const T& mValue); }; template <> struct Converter<ssvs::Input::Trigger> { using T = ssvs::Input::Trigger; static void fromObj(const Obj& mObj, T& mValue); static void toObj(Obj& mObj, const T& mValue); }; template <> struct Converter<sf::Keyboard::Key> { using T = sf::Keyboard::Key; static void fromObj(const Obj& mObj, T& mValue); static void toObj(Obj& mObj, const T& mValue); }; template <> struct Converter<sf::Mouse::Button> { using T = sf::Mouse::Button; static void fromObj(const Obj& mObj, T& mValue); static void toObj(Obj& mObj, const T& mValue); }; template <> struct Converter<ssvs::Input::Combo> { using T = ssvs::Input::Combo; static void fromObj(const Obj& mObj, T& mValue); static void toObj(Obj& mObj, const T& mValue); }; } // namespace ssvuj
668
427
//===-- DWARFDebugMacro.cpp -------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "DWARFDebugMacro.h" #include "SymbolFileDWARF.h" #include "lldb/Symbol/DebugMacros.h" #include "DWARFDataExtractor.h" using namespace lldb_private; DWARFDebugMacroHeader DWARFDebugMacroHeader::ParseHeader(const DWARFDataExtractor &debug_macro_data, lldb::offset_t *offset) { DWARFDebugMacroHeader header; // Skip over the version field in header. header.m_version = debug_macro_data.GetU16(offset); uint8_t flags = debug_macro_data.GetU8(offset); header.m_offset_is_64_bit = flags & OFFSET_SIZE_MASK ? true : false; if (flags & DEBUG_LINE_OFFSET_MASK) { if (header.m_offset_is_64_bit) header.m_debug_line_offset = debug_macro_data.GetU64(offset); else header.m_debug_line_offset = debug_macro_data.GetU32(offset); } // Skip over the operands table if it is present. if (flags & OPCODE_OPERANDS_TABLE_MASK) SkipOperandTable(debug_macro_data, offset); return header; } void DWARFDebugMacroHeader::SkipOperandTable( const DWARFDataExtractor &debug_macro_data, lldb::offset_t *offset) { uint8_t entry_count = debug_macro_data.GetU8(offset); for (uint8_t i = 0; i < entry_count; i++) { // Skip over the opcode number. debug_macro_data.GetU8(offset); uint64_t operand_count = debug_macro_data.GetULEB128(offset); for (uint64_t j = 0; j < operand_count; j++) { // Skip over the operand form debug_macro_data.GetU8(offset); } } } void DWARFDebugMacroEntry::ReadMacroEntries( const DWARFDataExtractor &debug_macro_data, const DWARFDataExtractor &debug_str_data, const bool offset_is_64_bit, lldb::offset_t *offset, SymbolFileDWARF *sym_file_dwarf, DebugMacrosSP &debug_macros_sp) { #if TODO_REQUIRES_LLVM_ORG_SYNC // This code can go back in once llvm.org macros support is in the relevant // GitHub llvm branch. llvm::dwarf::MacroEntryType type = static_cast<llvm::dwarf::MacroEntryType>(debug_macro_data.GetU8(offset)); while (type != 0) { lldb::offset_t new_offset = 0, str_offset = 0; uint32_t line = 0; const char *macro_str = nullptr; uint32_t debug_line_file_idx = 0; switch (type) { case DW_MACRO_define: case DW_MACRO_undef: line = debug_macro_data.GetULEB128(offset); macro_str = debug_macro_data.GetCStr(offset); if (type == DW_MACRO_define) debug_macros_sp->AddMacroEntry( DebugMacroEntry::CreateDefineEntry(line, macro_str)); else debug_macros_sp->AddMacroEntry( DebugMacroEntry::CreateUndefEntry(line, macro_str)); break; case DW_MACRO_define_strp: case DW_MACRO_undef_strp: line = debug_macro_data.GetULEB128(offset); if (offset_is_64_bit) str_offset = debug_macro_data.GetU64(offset); else str_offset = debug_macro_data.GetU32(offset); macro_str = debug_str_data.GetCStr(&str_offset); if (type == DW_MACRO_define_strp) debug_macros_sp->AddMacroEntry( DebugMacroEntry::CreateDefineEntry(line, macro_str)); else debug_macros_sp->AddMacroEntry( DebugMacroEntry::CreateUndefEntry(line, macro_str)); break; case DW_MACRO_start_file: line = debug_macro_data.GetULEB128(offset); debug_line_file_idx = debug_macro_data.GetULEB128(offset); debug_macros_sp->AddMacroEntry( DebugMacroEntry::CreateStartFileEntry(line, debug_line_file_idx)); break; case DW_MACRO_end_file: // This operation has no operands. debug_macros_sp->AddMacroEntry(DebugMacroEntry::CreateEndFileEntry()); break; case DW_MACRO_import: if (offset_is_64_bit) new_offset = debug_macro_data.GetU64(offset); else new_offset = debug_macro_data.GetU32(offset); debug_macros_sp->AddMacroEntry(DebugMacroEntry::CreateIndirectEntry( sym_file_dwarf->ParseDebugMacros(&new_offset))); break; default: // TODO: Add support for other standard operations. // TODO: Provide mechanism to hook handling of non-standard/extension // operands. return; } type = static_cast<llvm::dwarf::MacroEntryType>( debug_macro_data.GetU8(offset)); } #endif }
1,927
2,054
<reponame>w136111526/zqcnn<filename>ZQCNN/layers_nchwc/zq_cnn_softmax_nchwc.h #ifndef _ZQ_CNN_SOFTMAX_NCHWC_H_ #define _ZQ_CNN_SOFTMAX_NCHWC_H_ #include "../ZQ_CNN_CompileConfig.h" #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif void zq_cnn_softmax_nchwc1_C( float* in_tensor4D_data, // in & out int in_N, int in_H, int in_W, int in_C, int in_widthStep, int in_sliceStep, int in_imStep ); #if __ARM_NEON || (ZQ_CNN_USE_SSETYPE >= ZQ_CNN_SSETYPE_SSE) void zq_cnn_softmax_nchwc4_C( float* in_tensor4D_data, // in & out int in_N, int in_H, int in_W, int in_C, int in_widthStep, int in_sliceStep, int in_imStep ); #endif //__ARM_NEON || (ZQ_CNN_USE_SSETYPE >= ZQ_CNN_SSETYPE_SSE) #if ZQ_CNN_USE_SSETYPE >= ZQ_CNN_SSETYPE_AVX void zq_cnn_softmax_nchwc8_C( float* in_tensor4D_data, // in & out int in_N, int in_H, int in_W, int in_C, int in_widthStep, int in_sliceStep, int in_imStep ); #endif void zq_cnn_softmax_nchwc1_H( float* in_tensor4D_data, // in & out int in_N, int in_H, int in_W, int in_C, int in_widthStep, int in_sliceStep, int in_imStep ); void zq_cnn_softmax_nchwc1_W( float* in_tensor4D_data, // in & out int in_N, int in_H, int in_W, int in_C, int in_widthStep, int in_sliceStep, int in_imStep ); #if defined(__cplusplus) || defined(c_plusplus) //跨平台定义方法 } #endif #endif
780
831
<reponame>phpc0de/idea-android<gh_stars>100-1000 /* * Copyright (C) 2016 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 com.android.tools.profilers; import static com.android.tools.idea.transport.faketransport.FakeTransportService.VERSION; import static com.google.common.truth.Truth.assertThat; import com.android.sdklib.AndroidVersion; import com.android.tools.adtui.model.FakeTimer; import com.android.tools.idea.transport.faketransport.FakeGrpcServer; import com.android.tools.idea.transport.faketransport.FakeTransportService; import com.android.tools.profiler.proto.Common; import com.android.tools.profiler.proto.Transport.VersionRequest; import com.android.tools.profiler.proto.Transport.VersionResponse; import com.android.tools.profilers.cpu.CpuProfilerStage; import com.android.tools.profilers.cpu.CpuProfilerTestUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; public final class StudioProfilersCommonTest { private final FakeTimer myTimer = new FakeTimer(); private final FakeTransportService myTransportService = new FakeTransportService(myTimer, false); @Rule public FakeGrpcServer myGrpcServer = FakeGrpcServer.createFakeGrpcServer("StudioProfilerCommonTestChannel", myTransportService, new FakeProfilerService(myTimer)); private ProfilerClient myProfilerClient; @Before public void setUp() { myProfilerClient = new ProfilerClient(myGrpcServer.getChannel()); } @Test public void testVersion() { VersionResponse response = myProfilerClient.getTransportClient().getVersion(VersionRequest.getDefaultInstance()); assertThat(response.getVersion()).isEqualTo(VERSION); } @Test public void testClearedOnMonitorStage() { StudioProfilers profilers = getProfilersWithDeviceAndProcess(); assertThat(profilers.getTimeline().getSelectionRange().isEmpty()).isTrue(); profilers.setStage(new CpuProfilerStage(profilers)); profilers.getTimeline().getSelectionRange().set(10, 10); profilers.setMonitoringStage(); assertThat(profilers.getTimeline().getSelectionRange().isEmpty()).isTrue(); } @Test public void testProfilerModeChange() throws Exception { StudioProfilers profilers = getProfilersWithDeviceAndProcess(); assertThat(profilers.getMode()).isEqualTo(ProfilerMode.NORMAL); CpuProfilerStage stage = new CpuProfilerStage(profilers); profilers.setStage(stage); assertThat(profilers.getMode()).isEqualTo(ProfilerMode.NORMAL); stage.setAndSelectCapture(CpuProfilerTestUtils.getValidCapture()); assertThat(profilers.getMode()).isEqualTo(ProfilerMode.EXPANDED); profilers.setMonitoringStage(); assertThat(profilers.getMode()).isEqualTo(ProfilerMode.NORMAL); } private StudioProfilers getProfilersWithDeviceAndProcess() { FakeTimer timer = new FakeTimer(); StudioProfilers profilers = new StudioProfilers(myProfilerClient, new FakeIdeProfilerServices(), timer); timer.tick(FakeTimer.ONE_SECOND_IN_NS); Common.Device device = Common.Device.newBuilder() .setDeviceId("FakeDevice".hashCode()) .setFeatureLevel(AndroidVersion.VersionCodes.BASE) .setSerial("FakeDevice") .setState(Common.Device.State.ONLINE) .build(); myTransportService.addDevice(device); timer.tick(FakeTimer.ONE_SECOND_IN_NS); // One second must be enough for new devices to be picked up profilers.setProcess(device, null); assertThat(profilers.getDevice()).isEqualTo(device); assertThat(profilers.getProcess()).isNull(); Common.Process process = Common.Process.newBuilder() .setDeviceId(device.getDeviceId()) .setPid(20) .setName("FakeProcess") .setState(Common.Process.State.ALIVE) .build(); myTransportService.addProcess(device, process); timer.tick(FakeTimer.ONE_SECOND_IN_NS); // One second must be enough for new devices to be picked up profilers.setProcess(device, process); assertThat(profilers.getProcess()).isEqualTo(process); return profilers; } }
1,474
335
<gh_stars>100-1000 { "word": "Present", "definitions": [ "In a particular place.", "Existing or occurring in a place or thing.", "Fully focused on or involved in what one is doing or experiencing.", "Existing or occurring now.", "Now being considered or discussed.", "(of a tense or participle) expressing an action now going on or habitually performed, or a condition now existing." ], "parts-of-speech": "Adjective" }
171
474
<reponame>lzwjava/MCAlbum // // CNCommon.h // LZAlbum // // Created by lzw on 15/3/10. // Copyright (c) 2015年 lzw. All rights reserved. // #ifndef LZAlbum_MCCommon_h #define LZAlbum_MCCommon_h #import<AVOSCloud/AVOSCloud.h> #import "LZMacros.h" #endif
128
852
#include "DataFormats/L1THGCal/interface/HGCalMulticluster.h" using namespace l1t; HGCalMulticluster::HGCalMulticluster(const LorentzVector p4, int pt, int eta, int phi) : HGCalClusterT<l1t::HGCalCluster>(p4, pt, eta, phi), hOverE_(-99), hOverEValid_(false) {} HGCalMulticluster::HGCalMulticluster(const edm::Ptr<l1t::HGCalCluster> &clusterSeed, float fraction) : HGCalClusterT<l1t::HGCalCluster>(clusterSeed, fraction), hOverE_(-99), hOverEValid_(false) {} HGCalMulticluster::~HGCalMulticluster() {} void HGCalMulticluster::saveEnergyInterpretation(const HGCalMulticluster::EnergyInterpretation eInt, double energy) { energyInterpretationFractions_[eInt] = energy / this->energy(); } double HGCalMulticluster::interpretationFraction(const HGCalMulticluster::EnergyInterpretation eInt) const { auto intAndEnergyFraction = energyInterpretationFractions_.find(eInt); if (intAndEnergyFraction == energyInterpretationFractions_.end()) { // NOTE: this is an arbitary choice: we return the default cluster energy if this interpreation is not available! return 1; } return intAndEnergyFraction->second; }
394
5,169
{ "name": "SPDevKit", "version": "0.0.11", "summary": "Personal dev kit", "description": "develop kit", "homepage": "https://cocoapods.org", "license": "MIT", "authors": "Superwave", "platforms": { "ios": null }, "source": { "git": "https://github.com/superwave/SPDevKit.git", "tag": "0.0.11" }, "source_files": [ "SPDevKit/**/*.{h}", "SPDevKit/framework" ], "exclude_files": "Classes/Exclude", "vendored_frameworks": "SPDevKit/framework/SPDevKit.framework", "swift_versions": "4.2", "frameworks": "AFNetworking", "dependencies": { "AFNetworking": [ ] }, "swift_version": "4.2" }
279
679
<filename>main/qadevOOo/java/OOoRunner/src/main/java/ifc/sheet/_SheetSortDescriptor.java<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 ifc.sheet; import lib.MultiMethodTest; import util.ValueChanger; import com.sun.star.beans.PropertyValue; import com.sun.star.beans.XPropertySet; import com.sun.star.table.CellAddress; import com.sun.star.util.XSortable; /** * Testing <code>com.sun.star.sheet.SheetSortDescriptor</code> * service properties: <p> * <ul> * <li><code>BindFormatsToContent</code></li> * <li><code>CopyOutputData</code></li> * <li><code>IsCaseSensitive</code></li> * <li><code>IsUserListEnabled</code></li> * <li><code>OutputPosition</code></li> * <li><code>SortAscending</code></li> * <li><code>UserListIndex</code></li> * </ul> <p> * @see com.sun.star.sheet.SheetSortDescriptor */ public class _SheetSortDescriptor extends MultiMethodTest { public XPropertySet oObj = null; public XSortable xSORT = null; public PropertyValue[] props = null; public void _BindFormatsToContent() { xSORT = (XSortable) tEnv.getObjRelation("xSORT"); props = xSORT.createSortDescriptor(); changeProp("BindFormatsToContent",5); } public void _CopyOutputData() { changeProp("CopyOutputData",6); } public void _IsCaseSensitive() { changeProp("IsCaseSensitive",4); } public void _IsUserListEnabled() { changeProp("IsUserListEnabled",8); } public void _OutputPosition() { changeProp("OutputPosition",7); } public void _SortAscending() { //changeProp("SortAscending",3); log.println("Property 'SortAscending' is not part of the "+ "property array"); log.println("Available properties:"); for (int i=0; i<props.length;i++) { log.println("\t"+props[i].Name); } tRes.tested("SortAscending",false); } public void _UserListIndex() { changeProp("UserListIndex",9); } public void changeProp(String name, int nr) { Object gValue = null; Object sValue = null; Object ValueToSet = null; int gInt = 0; int sInt = 0; if ( ! name.equals(props[nr].Name) ) { log.println("Property '"+props[nr].Name+"' is tested"); log.println("But the status is for '"+name+"'"); } try { //waitForAllThreads(); gValue = props[nr].Value; if ( name.equals("OutputPosition")) { gInt = ((CellAddress) gValue).Row; } //waitForAllThreads(); ValueToSet = ValueChanger.changePValue(gValue); //waitForAllThreads(); props[nr].Value=ValueToSet; sValue = props[nr].Value; if ( name.equals("OutputPosition")) { sInt = ((CellAddress) sValue).Row; gValue = new Integer(gInt); sValue = new Integer(sInt); } //check get-set methods if ( (gValue.equals(sValue)) || (sValue == null) ) { log.println("Value for '"+name+"' hasn't changed"); tRes.tested(name, false); } else { log.println("Property '"+name+"' OK"); tRes.tested(name, true); } } catch (Exception e) { log.println("Exception occurred while testing property '" + name + "'"); e.printStackTrace(log); tRes.tested(name, false); } }// end of changeProp } // finish class _SheetSortDescriptor
1,876
892
<reponame>westonsteimel/advisory-database-github { "schema_version": "1.2.0", "id": "GHSA-p55g-6f9f-5v5g", "modified": "2022-05-01T18:02:45Z", "published": "2022-05-01T18:02:45Z", "aliases": [ "CVE-2007-2358" ], "details": "** DISPUTED ** Multiple PHP remote file inclusion vulnerabilities in b2evolution allow remote attackers to execute arbitrary PHP code via a URL in the (1) inc_path parameter to (a) a_noskin.php, (b) a_stub.php, (c) admin.php, (d) contact.php, (e) default.php, (f) index.php, and (g) multiblogs.php in blogs/; the (2) view_path and (3) control_path parameters to blogs/admin.php; and the (4) skins_path parameter to (h) blogs/contact.php and (i) blogs/multiblogs.php. NOTE: this issue is disputed by CVE, since the inc_path, view_path, control_path, and skins_path variables are all initialized in conf/_advanced.php before they are used.", "severity": [ ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2007-2358" }, { "type": "WEB", "url": "https://exchange.xforce.ibmcloud.com/vulnerabilities/33907" }, { "type": "WEB", "url": "http://attrition.org/pipermail/vim/2007-April/001566.html" }, { "type": "WEB", "url": "http://osvdb.org/35609" }, { "type": "WEB", "url": "http://www.osvdb.org/34152" }, { "type": "WEB", "url": "http://www.securityfocus.com/archive/1/466886/100/0/threaded" } ], "database_specific": { "cwe_ids": [ ], "severity": "HIGH", "github_reviewed": false } }
715
1,374
<gh_stars>1000+ package source.overload; import def.test.AmbientWithOverload; import jsweet.lang.Ambient; @Ambient class AmbientWithOverload2 { public native void mm(String s); public native void mm(String s, int i); } public class WithAmbients { void m(AmbientWithOverload a, AmbientWithOverload2 a2) { a.m("a", 100); a2.mm("b", 200); } }
136
3,799
/* * Copyright 2020 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 androidx.work.impl.workers; import static androidx.work.impl.Scheduler.MAX_GREEDY_SCHEDULER_LIMIT; import android.content.Context; import android.os.Build; import android.text.TextUtils; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RestrictTo; import androidx.work.Logger; import androidx.work.Worker; import androidx.work.WorkerParameters; import androidx.work.impl.WorkDatabase; import androidx.work.impl.WorkManagerImpl; import androidx.work.impl.model.SystemIdInfo; import androidx.work.impl.model.SystemIdInfoDao; import androidx.work.impl.model.WorkNameDao; import androidx.work.impl.model.WorkSpec; import androidx.work.impl.model.WorkSpecDao; import androidx.work.impl.model.WorkTagDao; import java.util.List; import java.util.concurrent.TimeUnit; /** * The {@link androidx.work.Worker} which dumps diagnostic information. * * @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public class DiagnosticsWorker extends Worker { private static final String TAG = Logger.tagWithPrefix("DiagnosticsWrkr"); public DiagnosticsWorker(@NonNull Context context, @NonNull WorkerParameters parameters) { super(context, parameters); } @NonNull @Override public Result doWork() { WorkManagerImpl workManager = WorkManagerImpl.getInstance(getApplicationContext()); WorkDatabase database = workManager.getWorkDatabase(); WorkSpecDao workSpecDao = database.workSpecDao(); WorkNameDao workNameDao = database.workNameDao(); WorkTagDao workTagDao = database.workTagDao(); SystemIdInfoDao systemIdInfoDao = database.systemIdInfoDao(); long startAt = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(1); List<WorkSpec> completed = workSpecDao.getRecentlyCompletedWork(startAt); List<WorkSpec> running = workSpecDao.getRunningWork(); List<WorkSpec> enqueued = workSpecDao.getAllEligibleWorkSpecsForScheduling( MAX_GREEDY_SCHEDULER_LIMIT); if (completed != null && !completed.isEmpty()) { Logger.get().info(TAG, "Recently completed work:\n\n"); Logger.get().info(TAG, workSpecRows(workNameDao, workTagDao, systemIdInfoDao, completed)); } if (running != null && !running.isEmpty()) { Logger.get().info(TAG, "Running work:\n\n"); Logger.get().info(TAG, workSpecRows(workNameDao, workTagDao, systemIdInfoDao, running)); } if (enqueued != null && !enqueued.isEmpty()) { Logger.get().info(TAG, "Enqueued work:\n\n"); Logger.get().info(TAG, workSpecRows(workNameDao, workTagDao, systemIdInfoDao, enqueued)); } return Result.success(); } @NonNull private static String workSpecRows( @NonNull WorkNameDao workNameDao, @NonNull WorkTagDao workTagDao, @NonNull SystemIdInfoDao systemIdInfoDao, @NonNull List<WorkSpec> workSpecs) { StringBuilder sb = new StringBuilder(); String systemIdHeader = Build.VERSION.SDK_INT >= 23 ? "Job Id" : "Alarm Id"; String header = String.format("\n Id \t Class Name\t %s\t State\t Unique Name\t Tags\t", systemIdHeader); sb.append(header); for (WorkSpec workSpec : workSpecs) { Integer systemId = null; SystemIdInfo info = systemIdInfoDao.getSystemIdInfo(workSpec.id); if (info != null) { systemId = info.systemId; } List<String> names = workNameDao.getNamesForWorkSpecId(workSpec.id); List<String> tags = workTagDao.getTagsForWorkSpecId(workSpec.id); sb.append(workSpecRow( workSpec, TextUtils.join(",", names), systemId, TextUtils.join(",", tags) )); } return sb.toString(); } @NonNull private static String workSpecRow( @NonNull WorkSpec workSpec, @Nullable String name, @Nullable Integer systemId, @NonNull String tags) { return String.format( "\n%s\t %s\t %s\t %s\t %s\t %s\t", workSpec.id, workSpec.workerClassName, systemId, workSpec.state.name(), name, tags); } }
2,140
571
/*************************************************************************** Copyright 2015 Ufora 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. ****************************************************************************/ #include "ThreadPoolWithDependencies.hpp" #include "../UnitTest.hpp" #include "../containers/ImmutableTreeSet.hppml" #include "Queue.hpp" namespace Ufora { BOOST_AUTO_TEST_SUITE( test_ThreadPoolWithDependencies ) BOOST_AUTO_TEST_CASE( test_construction ) { ThreadPoolWithDependencies<> pool(1); } BOOST_AUTO_TEST_CASE( test_execute_a_task ) { ThreadPoolWithDependencies<> pool(1); Queue<long> resultQueue; pool.addTask( "task", boost::function0<void>( [&]() { resultQueue.write(0); } ), 0, std::set<std::string>(), false ); long res = 0; BOOST_CHECK(resultQueue.getTimeout(res, 1.0)); BOOST_CHECK(res == 0); } BOOST_AUTO_TEST_CASE( test_out_of_order_definition ) { ThreadPoolWithDependencies<> pool(1); Queue<long> resultQueue; pool.addTask( "task", boost::function0<void>( [&]() { resultQueue.write(0); } ), 0, ImmutableTreeSet<std::string>() + std::string("subtask"), false ); long res = 0; //we shouldn't be able to complete BOOST_CHECK(!resultQueue.getTimeout(res, .01)); pool.addTask( "subtask", boost::function0<void>( [&]() { resultQueue.write(1); } ), 0, ImmutableTreeSet<std::string>(), false ); //now the subtask should execute first (so we get a 1) BOOST_CHECK(resultQueue.getTimeout(res, 1.0)); BOOST_CHECK(res == 1); //and then the main task BOOST_CHECK(resultQueue.getTimeout(res, 1.0)); BOOST_CHECK(res == 0); } BOOST_AUTO_TEST_CASE( test_task_tree ) { ThreadPoolWithDependencies<long> pool(4); Queue<long> resultQueue; const static long testSize = 10000; for (long k = 0; k < testSize;k++) { std::set<long> deps; if (k/2 < k) deps.insert(k/2); if (k/2+1 < k) deps.insert(k/2+1); pool.addTask( k, boost::function0<void>( boost::bind( boost::function1<void, long>( [&](long k) { if (k/2 < k) lassert(pool.hasTaskExecuted(k/2)); if (k/2+1 < k) lassert(pool.hasTaskExecuted(k/2+1)); resultQueue.write(k); sleepSeconds(.0001); } ), k ) ), 0, deps, false ); } long res = 0; std::set<long> finished; while (finished.size() < testSize) { lassert(resultQueue.getTimeout(res, 1.0)); finished.insert(res); } } BOOST_AUTO_TEST_SUITE_END( ) }
1,814
1,711
import pytest from kubernetes.client import V2beta2CrossVersionObjectReference from kubernetes.client import V2beta2ExternalMetricSource from kubernetes.client import V2beta2ExternalMetricStatus from kubernetes.client import V2beta2MetricIdentifier from kubernetes.client import V2beta2MetricSpec from kubernetes.client import V2beta2MetricStatus from kubernetes.client import V2beta2MetricTarget from kubernetes.client import V2beta2MetricValueStatus from kubernetes.client import V2beta2ObjectMetricSource from kubernetes.client import V2beta2PodsMetricSource from kubernetes.client import V2beta2PodsMetricStatus from kubernetes.client import V2beta2ResourceMetricSource from kubernetes.client import V2beta2ResourceMetricStatus from kubernetes.client.models.v2beta2_object_metric_status import ( V2beta2ObjectMetricStatus, ) from paasta_tools.instance.hpa_metrics_parser import HPAMetricsParser @pytest.fixture def parser(): return HPAMetricsParser(hpa=None) def test_parse_target_external_metric_value(parser): metric_spec = V2beta2MetricSpec( type="External", external=V2beta2ExternalMetricSource( metric=V2beta2MetricIdentifier(name="foo"), target=V2beta2MetricTarget(type="Value", average_value=12,), ), ) status = parser.parse_target(metric_spec) assert status["name"] == "foo" assert status["target_value"] == "12" def test_parse_target_external_metric_average_value(parser): # The parser handles this case, but it's not currently # used in kubernetes_tools metric_spec = V2beta2MetricSpec( type="External", external=V2beta2ExternalMetricSource( metric=V2beta2MetricIdentifier(name="foo"), target=V2beta2MetricTarget(type="AverageValue", average_value=0.5,), ), ) status = parser.parse_target(metric_spec) assert status["name"] == "foo" assert status["target_value"] == "0.5" def test_parse_target_pod_metric(parser): metric_spec = V2beta2MetricSpec( type="Pods", pods=V2beta2PodsMetricSource( metric=V2beta2MetricIdentifier(name="foo"), target=V2beta2MetricTarget(type="AverageValue", average_value=0.5,), ), ) status = parser.parse_target(metric_spec) assert status["name"] == "foo" assert status["target_value"] == "0.5" def test_parse_target_resource_metric(parser): metric_spec = V2beta2MetricSpec( type="Resource", resource=V2beta2ResourceMetricSource( name="cpu", target=V2beta2MetricTarget(type="Utilization", average_utilization=0.5,), ), ) status = parser.parse_target(metric_spec) assert status["name"] == "cpu" assert status["target_value"] == "0.5" def test_parse_target_object_metric(parser): metric_spec = V2beta2MetricSpec( type="Object", object=V2beta2ObjectMetricSource( metric=V2beta2MetricIdentifier(name="some-metric"), described_object=V2beta2CrossVersionObjectReference( api_version="apps/v1", kind="Deployment", name="deployment" ), target=V2beta2MetricTarget(type="Value", value=1,), ), ) status = parser.parse_target(metric_spec) assert status["name"] == "some-metric" assert status["target_value"] == "1" def test_parse_current_external_metric_value(parser): metric_status = V2beta2MetricStatus( type="External", external=V2beta2ExternalMetricStatus( current=V2beta2MetricValueStatus(value=4,), metric=V2beta2MetricIdentifier(name="foo"), ), ) status = parser.parse_current(metric_status) assert status["name"] == "foo" assert status["current_value"] == "4" def test_parse_current_external_metric_average_value(parser): # The parser handles this case, but it's not currently # used in kubernetes_tools metric_status = V2beta2MetricStatus( type="External", external=V2beta2ExternalMetricStatus( current=V2beta2MetricValueStatus(average_value=0.4,), metric=V2beta2MetricIdentifier(name="foo"), ), ) status = parser.parse_current(metric_status) assert status["name"] == "foo" assert status["current_value"] == "0.4" def test_parse_current_pod_metric(parser): metric_status = V2beta2MetricStatus( type="Pods", pods=V2beta2PodsMetricStatus( current=V2beta2MetricValueStatus(average_value=0.4,), metric=V2beta2MetricIdentifier(name="foo"), ), ) status = parser.parse_current(metric_status) assert status["name"] == "foo" assert status["current_value"] == "0.4" def test_parse_current_resource_metric(parser): metric_status = V2beta2MetricStatus( type="Resource", resource=V2beta2ResourceMetricStatus( current=V2beta2MetricValueStatus(average_utilization=0.4,), name="cpu", ), ) status = parser.parse_current(metric_status) assert status["name"] == "cpu" assert status["current_value"] == "0.4" def test_parse_current_object_metric(parser): metric_status = V2beta2MetricStatus( type="Object", object=V2beta2ObjectMetricStatus( current=V2beta2MetricValueStatus(value=0.1), metric=V2beta2MetricIdentifier(name="some-metric"), described_object=V2beta2CrossVersionObjectReference( api_version="apps/v1", kind="Deployment", name="deployment" ), ), ) status = parser.parse_current(metric_status) assert status["name"] == "some-metric" assert status["current_value"] == "0.1" def test_parse_current_empty_string_metric(parser): metric_status = V2beta2MetricStatus(type="",) status = parser.parse_current(metric_status) assert status is None
2,409
1,144
package de.metas.handlingunits.shipmentschedule.api; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import de.metas.handlingunits.IHUShipperTransportationBL; import de.metas.handlingunits.model.I_M_HU; import de.metas.handlingunits.shipmentschedule.async.GenerateInOutFromHU.BillAssociatedInvoiceCandidates; import de.metas.handlingunits.shipmentschedule.spi.impl.CalculateShippingDateRule; import de.metas.inout.model.I_M_InOut; import de.metas.inoutcandidate.api.InOutGenerateResult; import de.metas.invoicecandidate.InvoiceCandidateId; import de.metas.invoicecandidate.api.IInvoiceCandBL; import de.metas.invoicecandidate.api.IInvoiceCandDAO; import de.metas.invoicecandidate.api.IInvoiceCandidateEnqueueResult; import de.metas.invoicecandidate.api.impl.PlainInvoicingParams; import de.metas.logging.LogManager; import de.metas.shipper.gateway.commons.ShipperGatewayFacade; import de.metas.shipper.gateway.spi.model.DeliveryOrderCreateRequest; import de.metas.shipping.IShipperDAO; import de.metas.shipping.ShipperId; import de.metas.shipping.model.I_M_ShipperTransportation; import de.metas.shipping.model.ShipperTransportationId; import de.metas.util.Check; import de.metas.util.GuavaCollectors; import de.metas.util.Loggables; import de.metas.util.Services; import de.metas.common.util.CoalesceUtil; import lombok.Builder; import lombok.NonNull; import lombok.Singular; import lombok.ToString; import org.adempiere.ad.trx.api.ITrxManager; import org.adempiere.ad.trx.processor.api.FailTrxItemExceptionHandler; import org.adempiere.exceptions.AdempiereException; import org.compiere.SpringContextHolder; import org.compiere.model.I_M_Package; import org.compiere.model.I_M_Shipper; import org.compiere.util.TimeUtil; import org.slf4j.Logger; import javax.annotation.Nullable; import java.time.LocalDate; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Set; import java.util.function.Supplier; import static org.adempiere.model.InterfaceWrapperHelper.load; /* * #%L * de.metas.handlingunits.base * %% * Copyright (C) 2017 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ /** * Facade which is able to generate shipping documents (generate shipment, add to shipper transportation, generate invoice). * * @author metas-dev <<EMAIL>> */ @ToString(exclude = { "huShipperTransportationBL", "huShipmentScheduleDAO", "huShipmentScheduleBL", "invoiceCandDAO", "invoiceCandBL", "trxManager" }) public class HUShippingFacade { private static final Logger logger = LogManager.getLogger(HUShippingFacade.class); private final IHUShipperTransportationBL huShipperTransportationBL = Services.get(IHUShipperTransportationBL.class); private final IHUShipmentScheduleDAO huShipmentScheduleDAO = Services.get(IHUShipmentScheduleDAO.class); private final IHUShipmentScheduleBL huShipmentScheduleBL = Services.get(IHUShipmentScheduleBL.class); private final IInvoiceCandDAO invoiceCandDAO = Services.get(IInvoiceCandDAO.class); private final IInvoiceCandBL invoiceCandBL = Services.get(IInvoiceCandBL.class); private final ITrxManager trxManager = Services.get(ITrxManager.class); private final Supplier<ShipperGatewayFacade> shipperGatewayFacadeSupplier = // () -> SpringContextHolder.instance.getBean(ShipperGatewayFacade.class); // // Parameters private final int addToShipperTransportationId; private final boolean completeShipments; private final BillAssociatedInvoiceCandidates invoiceMode; private final boolean createShipperDeliveryOrders; private final ImmutableList<I_M_HU> hus; private final boolean failIfNoShipmentCandidatesFound; // // State private List<ShipmentScheduleWithHU> _candidates; // lazy private InOutGenerateResult shipmentsGenerateResult; private final ArrayList<I_M_Package> mPackagesCreated = new ArrayList<>(); @Builder private HUShippingFacade( @NonNull @Singular("hu") final List<I_M_HU> hus, final int addToShipperTransportationId, final boolean completeShipments, @Nullable final BillAssociatedInvoiceCandidates invoiceMode, final boolean createShipperDeliveryOrders, final boolean failIfNoShipmentCandidatesFound) { Check.assumeNotEmpty(hus, "hus is not empty"); this.hus = ImmutableList.copyOf(hus); this.addToShipperTransportationId = addToShipperTransportationId; this.completeShipments = completeShipments; this.invoiceMode = invoiceMode; this.createShipperDeliveryOrders = createShipperDeliveryOrders; this.failIfNoShipmentCandidatesFound = failIfNoShipmentCandidatesFound; } @VisibleForTesting public List<ShipmentScheduleWithHU> getCandidates() { if (_candidates == null) { _candidates = huShipmentScheduleDAO.retrieveShipmentSchedulesWithHUsFromHUs(hus); } return _candidates; } @VisibleForTesting public List<I_M_InOut> getGeneratedShipments() { Check.assumeNotNull(shipmentsGenerateResult, "shipments were generated"); return shipmentsGenerateResult.getInOuts(); } public InOutGenerateResult generateShippingDocuments() { trxManager.runInThreadInheritedTrx(this::generateShippingDocuments0); return shipmentsGenerateResult; } private void generateShippingDocuments0() { addHUsToShipperTransportationIfNeeded(); generateShipmentsFromCandidates(); generateInvoicesIfNeeded(); generateShipperDeliveryOrdersIfNeeded(); } /** * Adds given list of HUs to shipper transportation, by creating the needed M_Packages. */ private void addHUsToShipperTransportationIfNeeded() { if (addToShipperTransportationId > 0) { final List<I_M_Package> result = huShipperTransportationBL.addHUsToShipperTransportation(ShipperTransportationId.ofRepoId(addToShipperTransportationId), hus); mPackagesCreated.addAll(result); Loggables.addLog("HUs added to M_ShipperTransportation_ID={}", addToShipperTransportationId); } } private void generateShipmentsFromCandidates() { final List<ShipmentScheduleWithHU> candidates = getCandidates(); if (candidates.isEmpty()) { //noinspection ThrowableNotThrown new AdempiereException("No shipment candidates found") .appendParametersToMessage() .setParameter("context", this) .throwOrLogWarning(failIfNoShipmentCandidatesFound, logger); return; } shipmentsGenerateResult = huShipmentScheduleBL .createInOutProducerFromShipmentSchedule() .setProcessShipments(completeShipments) .setCreatePackingLines(false) // the packing lines shall only be created when the shipments are completed .computeShipmentDate(CalculateShippingDateRule.FORCE_SHIPMENT_DATE_TODAY) // if this is ever used, it should be on true to keep legacy // Fail on any exception, because we cannot create just a part of those shipments. // Think about HUs which are linked to multiple shipments: you will not see then in Aggregation POS because are already assigned, but u are not able to create shipment from them again. .setTrxItemExceptionHandler(FailTrxItemExceptionHandler.instance) .createShipments(candidates); Loggables.addLog("Generated {}", shipmentsGenerateResult); } private void generateInvoicesIfNeeded() { Check.assumeNotNull(shipmentsGenerateResult, "shipments generated"); final List<I_M_InOut> shipments = shipmentsGenerateResult.getInOuts(); if (shipments.isEmpty()) { return; } if (invoiceMode == BillAssociatedInvoiceCandidates.NO) { return; } final Set<InvoiceCandidateId> invoiceCandidateIds = invoiceCandDAO.retrieveInvoiceCandidatesQueryForInOuts(shipments) .listIds(InvoiceCandidateId::ofRepoId); if (invoiceCandidateIds.isEmpty()) { throw new AdempiereException("@NotFound@ @C_Invoice_Candidate_ID@") .setParameter("shipments", shipments); } final PlainInvoicingParams invoicingParams = new PlainInvoicingParams(); final boolean adhereToInvoiceSchedule = invoiceMode == BillAssociatedInvoiceCandidates.IF_INVOICE_SCHEDULE_PERMITS; invoicingParams.setIgnoreInvoiceSchedule(!adhereToInvoiceSchedule); final IInvoiceCandidateEnqueueResult enqueueResult = invoiceCandBL.enqueueForInvoicing() .setFailOnChanges(false) .setInvoicingParams(invoicingParams) // .enqueueInvoiceCandidateIds(invoiceCandidateIds); Loggables.addLog("Invoice candidates enqueued: {}", enqueueResult); } private void generateShipperDeliveryOrdersIfNeeded() { if (!createShipperDeliveryOrders) { return; } Check.errorIf(addToShipperTransportationId <= 0, "If createShipperDeliveryOrders=true, then addToShipperTransportationId needs to be > 0; this={}", this); mPackagesCreated .stream() .collect(GuavaCollectors.toImmutableListMultimap(HUShippingFacade::extractShipperId)) .asMap() .forEach(this::generateShipperDeliveryOrderIfNeeded); } @NonNull private static ShipperId extractShipperId(@NonNull final I_M_Package mPackage) { return ShipperId.ofRepoId(mPackage.getM_Shipper_ID()); } private void generateShipperDeliveryOrderIfNeeded( final ShipperId shipperId, @NonNull final Collection<I_M_Package> mPackages) { final I_M_Shipper shipper = Services.get(IShipperDAO.class).getById(shipperId); final String shipperGatewayId = shipper.getShipperGateway(); if (Check.isEmpty(shipperGatewayId, true)) { return; } final ShipperGatewayFacade shipperGatewayFacade = shipperGatewayFacadeSupplier.get(); if (!shipperGatewayFacade.hasServiceSupport(shipperGatewayId)) { return; } final Set<Integer> mPackageIds = mPackages.stream() .map(I_M_Package::getM_Package_ID) .collect(ImmutableSet.toImmutableSet()); Check.assume(addToShipperTransportationId > 0, "addToShipperTransportationId > 0"); final I_M_ShipperTransportation shipperTransportation = load(addToShipperTransportationId, I_M_ShipperTransportation.class); final DeliveryOrderCreateRequest request = DeliveryOrderCreateRequest.builder() .pickupDate(getPickupDate(shipperTransportation)) .timeFrom(TimeUtil.asLocalTime(shipperTransportation.getPickupTimeFrom())) .timeTo(TimeUtil.asLocalTime(shipperTransportation.getPickupTimeTo())) .packageIds(mPackageIds) .shipperTransportationId(ShipperTransportationId.ofRepoId(addToShipperTransportationId)) .shipperGatewayId(shipperGatewayId) .build(); shipperGatewayFacade.createAndSendDeliveryOrdersForPackages(request); } private LocalDate getPickupDate(@NonNull final I_M_ShipperTransportation shipperTransportation) { return CoalesceUtil.coalesce(TimeUtil.asLocalDate(shipperTransportation.getDateToBeFetched()), TimeUtil.asLocalDate(shipperTransportation.getDateDoc())); } }
3,817
1,189
<gh_stars>1000+ /* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ /** * Metric aggregators. * * <p>This package is internal and is hence not for public use. Its APIs are unstable and can change * at any time. */ @ParametersAreNonnullByDefault package io.opentelemetry.sdk.metrics.internal.aggregator; import javax.annotation.ParametersAreNonnullByDefault;
125
436
<filename>src/main/java/com/jdon/jivejdon/presentation/action/query/ThreadHotAction.java /* * Copyright 2003-2006 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 * * 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.jdon.jivejdon.presentation.action.query; import javax.servlet.http.HttpServletRequest; import com.jdon.controller.WebAppUtil; import com.jdon.controller.model.PageIterator; import com.jdon.jivejdon.domain.model.ForumThread; import com.jdon.jivejdon.domain.model.query.HoThreadCriteria; import com.jdon.jivejdon.api.query.ForumMessageQueryService; import com.jdon.strutsutil.ModelListAction; import com.jdon.util.Debug; import com.jdon.util.UtilValidate; /** * difference with ThreadPopularAction ThreadPopularAction is simple, only for * one page , no multi pages. ThreadPopularAction is no messageReplyCountWindow, * donot need sorted by message replies ThreadHotAction is simple than * ThreadQueryAction. * * @author banq(http://www.jdon.com) * */ public class ThreadHotAction extends ModelListAction { private final static String module = ThreadHotAction.class.getName(); private ForumMessageQueryService forumMessageQueryService; public ForumMessageQueryService getForumMessageQueryService() { if (forumMessageQueryService == null) forumMessageQueryService = (ForumMessageQueryService) WebAppUtil.getService("forumMessageQueryService", this.servlet.getServletContext()); return forumMessageQueryService; } public PageIterator getPageIterator(HttpServletRequest request, int start, int count) { HoThreadCriteria queryCriteria = new HoThreadCriteria(); String dateRange = "1"; if (request.getParameter("dateRange") != null) dateRange = request.getParameter("dateRange"); queryCriteria.setDateRange(dateRange); Debug.logVerbose("ThreadHotAction dateRange=" + dateRange + " count=" + count, module); String messageReplyCountWindowS = request.getParameter("messageReplyCountWindow"); int messageReplyCountWindow = 10; // if reply num is greate than 10, // it // is hot thread if (!UtilValidate.isEmpty(messageReplyCountWindowS)) { messageReplyCountWindow = Integer.parseInt(messageReplyCountWindowS); } queryCriteria.setMessageReplyCountWindow(messageReplyCountWindow); return getForumMessageQueryService().getHotThreads(queryCriteria, start, count); } public Object findModelIFByKey(HttpServletRequest request, Object key) { ForumThread thread = null; try { thread = getForumMessageQueryService().getThread((Long) key); } catch (Exception e) { Debug.logError("getThread error:" + e, module); } return thread; } }
932
892
{ "schema_version": "1.2.0", "id": "GHSA-c4wx-x65q-h4fx", "modified": "2022-05-13T01:35:33Z", "published": "2022-05-13T01:35:33Z", "aliases": [ "CVE-2018-0240" ], "details": "Multiple vulnerabilities in the Application Layer Protocol Inspection feature of Cisco Adaptive Security Appliance (ASA) Software and Cisco Firepower Threat Defense (FTD) Software could allow an unauthenticated, remote attacker to trigger a reload of an affected device, resulting in a denial of service (DoS) condition. The vulnerabilities are due to logical errors during traffic inspection. An attacker could exploit these vulnerabilities by sending a high volume of malicious traffic across an affected device. An exploit could allow the attacker to cause a deadlock condition, resulting in a reload of an affected device. These vulnerabilities affect Cisco ASA Software and Cisco FTD Software configured for Application Layer Protocol Inspection running on the following Cisco products: 3000 Series Industrial Security Appliance (ISA), ASA 5500 Series Adaptive Security Appliances, ASA 5500-X Series Next-Generation Firewalls, ASA Services Module for Cisco Catalyst 6500 Series Switches and Cisco 7600 Series Routers, Adaptive Security Virtual Appliance (ASAv), Firepower 2100 Series Security Appliance, Firepower 4100 Series Security Appliance, Firepower 9300 ASA Security Module, FTD Virtual (FTDv). Cisco Bug IDs: CSCve61540, CSCvh23085, CSCvh95456.", "severity": [ { "type": "CVSS_V3", "score": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:C/C:N/I:N/A:H" } ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2018-0240" }, { "type": "WEB", "url": "https://ics-cert.us-cert.gov/advisories/ICSA-18-184-01" }, { "type": "WEB", "url": "https://tools.cisco.com/security/center/content/CiscoSecurityAdvisory/cisco-sa-20180418-asa_inspect" }, { "type": "WEB", "url": "http://www.securityfocus.com/bid/103934" }, { "type": "WEB", "url": "http://www.securitytracker.com/id/1040722" } ], "database_specific": { "cwe_ids": [ ], "severity": "HIGH", "github_reviewed": false } }
796
21,382
<filename>java/runtime/src/main/java/io/ray/runtime/util/JniExceptionUtil.java package io.ray.runtime.util; import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; // Required by JNI macro RAY_CHECK_JAVA_EXCEPTION public final class JniExceptionUtil { private static final Logger LOGGER = LoggerFactory.getLogger(JniExceptionUtil.class); public static String getStackTrace( String fileName, int lineNumber, String function, Throwable throwable) { LOGGER.error( "An unexpected exception occurred while executing Java code from JNI ({}:{} {}).", fileName, lineNumber, function, throwable); // Return the exception in string form to JNI. return ExceptionUtils.getStackTrace(throwable); } }
289
879
<filename>sdk/src/main/java/org/zstack/sdk/zwatch/alarm/EventDataAckInventory.java<gh_stars>100-1000 package org.zstack.sdk.zwatch.alarm; public class EventDataAckInventory extends org.zstack.sdk.zwatch.alarm.AlertDataAckInventory { public java.lang.String eventSubscriptionUuid; public void setEventSubscriptionUuid(java.lang.String eventSubscriptionUuid) { this.eventSubscriptionUuid = eventSubscriptionUuid; } public java.lang.String getEventSubscriptionUuid() { return this.eventSubscriptionUuid; } }
203
2,151
<gh_stars>1000+ // Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <stdint.h> #include <limits> #include <memory> #include <vector> #include "base/bind.h" #include "base/command_line.h" #include "base/files/file_path.h" #include "base/files/memory_mapped_file.h" #include "base/logging.h" #include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/memory/ref_counted.h" #include "base/path_service.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" #include "base/test/scoped_task_environment.h" #include "base/threading/thread.h" #include "base/threading/thread_checker.h" #include "base/threading/thread_task_runner_handle.h" #include "base/time/time.h" #include "chromecast/base/task_runner_impl.h" #include "chromecast/media/cma/base/decoder_buffer_adapter.h" #include "chromecast/media/cma/base/decoder_config_adapter.h" #include "chromecast/media/cma/test/frame_segmenter_for_test.h" #include "chromecast/public/cast_media_shlib.h" #include "chromecast/public/media/cast_decoder_buffer.h" #include "chromecast/public/media/decoder_config.h" #include "chromecast/public/media/media_capabilities_shlib.h" #include "chromecast/public/media/media_pipeline_backend.h" #include "chromecast/public/media/media_pipeline_device_params.h" #include "chromecast/public/volume_control.h" #include "media/audio/audio_device_description.h" #include "media/base/audio_decoder_config.h" #include "media/base/audio_timestamp_helper.h" #include "media/base/decoder_buffer.h" #include "media/base/encryption_scheme.h" #include "media/base/video_decoder_config.h" #include "testing/gtest/include/gtest/gtest.h" namespace chromecast { namespace media { class AudioVideoPipelineDeviceTest; namespace { const base::TimeDelta kMonitorLoopDelay = base::TimeDelta::FromMilliseconds(20); // Call Start() with an initial PTS of 1 second, to test the behaviour if // we push buffers with a PTS before the start PTS. In this case the backend // should report the PTS as no later than the last pushed buffers. const int64_t kStartPts = 1000 * 1000; // Amount that PTS is allowed to progress past the time that Pause() was called. const int kPausePtsSlackMs = 75; // Number of effects streams to open simultaneously when also playing a // non-effects stream. const int kNumEffectsStreams = 1; void IgnoreEos() {} AudioConfig DefaultAudioConfig() { AudioConfig default_config; default_config.codec = kCodecPCM; default_config.sample_format = kSampleFormatS16; default_config.channel_number = 2; default_config.bytes_per_channel = 2; default_config.samples_per_second = 48000; return default_config; } VideoConfig DefaultVideoConfig() { VideoConfig default_config; default_config.codec = kCodecH264; default_config.profile = kH264Main; default_config.additional_config = nullptr; default_config.encryption_scheme = Unencrypted(); return default_config; } base::FilePath GetTestDataFilePath(const std::string& name) { base::FilePath file_path; CHECK(base::PathService::Get(base::DIR_SOURCE_ROOT, &file_path)); file_path = file_path.Append(FILE_PATH_LITERAL("media")) .Append(FILE_PATH_LITERAL("test")).Append(FILE_PATH_LITERAL("data")) .AppendASCII(name); return file_path; } class BufferFeeder : public MediaPipelineBackend::Decoder::Delegate { public: explicit BufferFeeder(const base::Closure& eos_cb); ~BufferFeeder() override {} static std::unique_ptr<BufferFeeder> LoadAudio(MediaPipelineBackend* backend, const std::string& filename, const base::Closure& eos_cb); static std::unique_ptr<BufferFeeder> LoadVideo(MediaPipelineBackend* backend, const std::string& filename, bool raw_h264, const base::Closure& eos_cb); bool eos() const { return eos_; } MediaPipelineBackend::Decoder* decoder() const { return decoder_; } int64_t last_pushed_pts() const { return last_pushed_pts_; } void SetAudioConfig(const AudioConfig& config) { audio_config_ = config; } void SetVideoConfig(const VideoConfig& config) { video_config_ = config; } void FeedContinuousPcm(); void PauseBeforeEos(); void Initialize(MediaPipelineBackend* backend, MediaPipelineBackend::Decoder* decoder, const BufferList& buffers); void Start(); void Stop(); void ScheduleConfigTest(); void TestAudioConfigs(); void TestAudioVolume(); void TestVideoConfigs(); // MediaPipelineBackend::Decoder::Delegate implementation: void OnPushBufferComplete(MediaPipelineBackend::BufferStatus status) override; void OnEndOfStream() override; void OnDecoderError() override; void OnKeyStatusChanged(const std::string& key_id, CastKeyStatus key_status, uint32_t system_code) override; void OnVideoResolutionChanged(const Size& size) override; private: void FeedBuffer(); void FeedPcm(); void TestConfigs(); base::Closure eos_cb_; bool within_push_buffer_call_; bool expecting_buffer_complete_; bool feeding_completed_; bool eos_; bool pause_before_eos_; bool test_config_after_next_push_; bool feed_continuous_pcm_; MediaPipelineBackend* backend_; MediaPipelineBackend::Decoder* decoder_; BufferList buffers_; BufferList buffers_copy_; scoped_refptr<DecoderBufferBase> pending_buffer_; base::ThreadChecker thread_checker_; AudioConfig audio_config_; VideoConfig video_config_; int64_t last_pushed_pts_; std::unique_ptr<::media::AudioTimestampHelper> timestamp_helper_; DISALLOW_COPY_AND_ASSIGN(BufferFeeder); }; } // namespace class AudioVideoPipelineDeviceTest : public testing::Test { public: struct PauseInfo { PauseInfo() {} PauseInfo(base::TimeDelta d, base::TimeDelta l) : delay(d), length(l) {} ~PauseInfo() {} base::TimeDelta delay; base::TimeDelta length; }; AudioVideoPipelineDeviceTest(); ~AudioVideoPipelineDeviceTest() override; MediaPipelineBackend* backend() const { return backend_.get(); } void set_sync_type(MediaPipelineDeviceParams::MediaSyncType sync_type) { sync_type_ = sync_type; } void set_audio_type(MediaPipelineDeviceParams::AudioStreamType audio_type) { audio_type_ = audio_type; } void SetUp() override { CastMediaShlib::Initialize( base::CommandLine::ForCurrentProcess()->argv()); if (VolumeControl::Initialize) { VolumeControl::Initialize(base::CommandLine::ForCurrentProcess()->argv()); } } void TearDown() override { // Pipeline must be destroyed before finalizing media shlib. backend_.reset(); effects_backends_.clear(); if (VolumeControl::Finalize) { VolumeControl::Finalize(); } CastMediaShlib::Finalize(); } void ConfigureForFile(const std::string& filename); void ConfigureForAudioOnly(const std::string& filename); void ConfigureForVideoOnly(const std::string& filename, bool raw_h264); // Pattern loops, waiting >= pattern[i].delay against media clock between // pauses, then pausing for >= pattern[i].length against MessageLoop // A pause with delay <0 signals to stop sequence and do not loop void SetPausePattern(const std::vector<PauseInfo> pattern); // Adds a pause to the end of pause pattern void AddPause(base::TimeDelta delay, base::TimeDelta length); void PauseBeforeEos(); void AddEffectsStreams(); void Initialize(); void Start(); void OnEndOfStream(); void SetAudioFeeder(std::unique_ptr<BufferFeeder> audio_feeder) { audio_feeder_ = std::move(audio_feeder); } void SetVideoFeeder(std::unique_ptr<BufferFeeder> video_feeder) { video_feeder_ = std::move(video_feeder); } void RunStoppedChecks(); void RunPlaybackChecks(); void TestBackendStates(); void StartImmediateEosTest(); void EndImmediateEosTest(); private: void MonitorLoop(); void OnPauseCompleted(); base::test::ScopedTaskEnvironment scoped_task_environment_; MediaPipelineDeviceParams::MediaSyncType sync_type_; MediaPipelineDeviceParams::AudioStreamType audio_type_; std::unique_ptr<TaskRunnerImpl> task_runner_; std::unique_ptr<MediaPipelineBackend> backend_; std::vector<std::unique_ptr<MediaPipelineBackend>> effects_backends_; std::vector<std::unique_ptr<BufferFeeder>> effects_feeders_; std::unique_ptr<BufferFeeder> audio_feeder_; std::unique_ptr<BufferFeeder> video_feeder_; bool stopped_; bool ran_playing_playback_checks_; bool backwards_pts_change_; int64_t last_pts_; // Current media time. base::TimeDelta pause_time_; // Pause settings std::vector<PauseInfo> pause_pattern_; int pause_pattern_idx_; DISALLOW_COPY_AND_ASSIGN(AudioVideoPipelineDeviceTest); }; namespace { BufferFeeder::BufferFeeder(const base::Closure& eos_cb) : eos_cb_(eos_cb), within_push_buffer_call_(false), expecting_buffer_complete_(false), feeding_completed_(false), eos_(false), pause_before_eos_(false), test_config_after_next_push_(false), feed_continuous_pcm_(false), backend_(nullptr) { CHECK(!eos_cb_.is_null()); } void BufferFeeder::FeedContinuousPcm() { feed_continuous_pcm_ = true; } void BufferFeeder::PauseBeforeEos() { pause_before_eos_ = true; } void BufferFeeder::Initialize(MediaPipelineBackend* backend, MediaPipelineBackend::Decoder* decoder, const BufferList& buffers) { CHECK(backend); CHECK(decoder); backend_ = backend; decoder_ = decoder; decoder_->SetDelegate(this); buffers_ = buffers; buffers_.push_back(scoped_refptr<DecoderBufferBase>( new DecoderBufferAdapter(::media::DecoderBuffer::CreateEOSBuffer()))); } void BufferFeeder::Start() { if (feed_continuous_pcm_) { timestamp_helper_.reset( new ::media::AudioTimestampHelper(audio_config_.samples_per_second)); timestamp_helper_->SetBaseTimestamp(base::TimeDelta()); } last_pushed_pts_ = std::numeric_limits<int64_t>::min(); buffers_copy_ = buffers_; base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&BufferFeeder::FeedBuffer, base::Unretained(this))); } void BufferFeeder::Stop() { feeding_completed_ = true; } void BufferFeeder::ScheduleConfigTest() { if (expecting_buffer_complete_) { test_config_after_next_push_ = true; } else { TestConfigs(); } } void BufferFeeder::FeedBuffer() { CHECK(decoder_); if (feeding_completed_) return; if (feed_continuous_pcm_) { FeedPcm(); return; } // Possibly feed one buffer. CHECK(!buffers_.empty()); pending_buffer_ = buffers_.front(); if (pending_buffer_->end_of_stream()) { if (pause_before_eos_) ASSERT_TRUE(backend_->Pause()); } else { last_pushed_pts_ = pending_buffer_->timestamp(); } expecting_buffer_complete_ = true; within_push_buffer_call_ = true; BufferStatus status = decoder_->PushBuffer(pending_buffer_.get()); within_push_buffer_call_ = false; EXPECT_NE(status, MediaPipelineBackend::kBufferFailed); buffers_.pop_front(); if (pending_buffer_->end_of_stream() && pause_before_eos_) ASSERT_TRUE(backend_->Resume()); // Feeding is done, just wait for the end of stream callback. if (pending_buffer_->end_of_stream() || buffers_.empty()) { if (buffers_.empty() && !pending_buffer_->end_of_stream()) LOG(WARNING) << "Stream emptied without feeding EOS frame"; if (!buffers_.empty()) LOG(WARNING) << "Stream has more buffers after EOS frame"; feeding_completed_ = true; } if (status == MediaPipelineBackend::kBufferPending) return; OnPushBufferComplete(MediaPipelineBackend::kBufferSuccess); } void BufferFeeder::FeedPcm() { const int num_frames = 512; scoped_refptr<::media::DecoderBuffer> silence_buffer( new ::media::DecoderBuffer(num_frames * audio_config_.channel_number * audio_config_.bytes_per_channel)); memset(silence_buffer->writable_data(), 0, silence_buffer->data_size()); pending_buffer_ = new media::DecoderBufferAdapter(silence_buffer); pending_buffer_->set_timestamp(timestamp_helper_->GetTimestamp()); timestamp_helper_->AddFrames(num_frames); expecting_buffer_complete_ = true; within_push_buffer_call_ = true; BufferStatus status = decoder_->PushBuffer(pending_buffer_.get()); within_push_buffer_call_ = false; ASSERT_NE(status, MediaPipelineBackend::kBufferFailed); if (status == MediaPipelineBackend::kBufferPending) return; OnPushBufferComplete(MediaPipelineBackend::kBufferSuccess); } void BufferFeeder::OnEndOfStream() { DCHECK(thread_checker_.CalledOnValidThread()); EXPECT_FALSE(expecting_buffer_complete_) << "Got OnEndOfStream() before the EOS buffer completed"; eos_ = true; eos_cb_.Run(); } void BufferFeeder::OnPushBufferComplete(BufferStatus status) { DCHECK(thread_checker_.CalledOnValidThread()); pending_buffer_ = nullptr; EXPECT_FALSE(within_push_buffer_call_) << "OnPushBufferComplete() called during a call to PushBuffer()"; EXPECT_TRUE(expecting_buffer_complete_) << "OnPushBufferComplete() called unexpectedly"; expecting_buffer_complete_ = false; if (!feed_continuous_pcm_ || !feeding_completed_) { ASSERT_NE(status, MediaPipelineBackend::kBufferFailed); } EXPECT_FALSE(eos_) << "Got OnPushBufferComplete() after OnEndOfStream()"; if (test_config_after_next_push_) { test_config_after_next_push_ = false; TestConfigs(); } if (feeding_completed_) return; base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&BufferFeeder::FeedBuffer, base::Unretained(this))); } void BufferFeeder::OnDecoderError() { DCHECK(thread_checker_.CalledOnValidThread()); if (feed_continuous_pcm_) { feeding_completed_ = true; } else { ASSERT_TRUE(false); } } void BufferFeeder::OnKeyStatusChanged(const std::string& key_id, CastKeyStatus key_status, uint32_t system_code) { DCHECK(thread_checker_.CalledOnValidThread()); ASSERT_TRUE(false); } void BufferFeeder::OnVideoResolutionChanged(const Size& size) { DCHECK(thread_checker_.CalledOnValidThread()); } void BufferFeeder::TestConfigs() { if (IsValidConfig(audio_config_)) TestAudioConfigs(); if (IsValidConfig(video_config_)) TestVideoConfigs(); } void BufferFeeder::TestAudioConfigs() { MediaPipelineBackend::AudioDecoder* audio_decoder = static_cast<MediaPipelineBackend::AudioDecoder*>(decoder_); AudioConfig config; // First, make sure that kAudioCodecUnknown is not accepted. config.codec = kAudioCodecUnknown; config.sample_format = kSampleFormatS16; config.channel_number = 2; config.bytes_per_channel = 2; config.samples_per_second = 48000; // Set invalid config first, to test that the decoder still accepts valid // config after an invalid config. audio_decoder->SetConfig(config); // Next, test required sample formats. config.codec = kCodecPCM; EXPECT_TRUE(audio_decoder->SetConfig(config)) << "Audio decoder does not accept kCodecPCM"; config.sample_format = kSampleFormatPlanarF32; config.bytes_per_channel = 4; EXPECT_TRUE(audio_decoder->SetConfig(config)) << "Audio decoder does not accept kCodecPCM with " << "planar float (required for multiroom audio)"; config.codec = kCodecAAC; // TODO(kmackay) Determine required sample formats/channel numbers. config.sample_format = kSampleFormatS16; config.bytes_per_channel = 2; config.codec = kCodecPCM; EXPECT_TRUE(audio_decoder->SetConfig(config)) << "Audio decoder does not accept kCodecPCM"; config.codec = kCodecPCM_S16BE; EXPECT_TRUE(audio_decoder->SetConfig(config)) << "Audio decoder does not accept kCodecPCM_S16BE"; config.codec = kCodecAAC; EXPECT_TRUE(audio_decoder->SetConfig(config)) << "Audio decoder does not accept kCodecAAC"; config.codec = kCodecMP3; EXPECT_TRUE(audio_decoder->SetConfig(config)) << "Audio decoder does not accept kCodecMP3"; // Test supported sample rates. const int kRequiredSampleRates[] = {8000, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000}; const int kHiResSampleRates[] = {64000, 88200, 96000}; config.codec = kCodecPCM; for (int rate : kRequiredSampleRates) { config.samples_per_second = rate; EXPECT_TRUE(audio_decoder->SetConfig(config)) << "Audio decoder does not accept sample rate " << rate; } for (int rate : kHiResSampleRates) { config.samples_per_second = rate; if (!audio_decoder->SetConfig(config)) LOG(INFO) << "Audio decoder does not accept hi-res sample rate " << rate; } EXPECT_TRUE(audio_decoder->SetConfig(audio_config_)); } void BufferFeeder::TestAudioVolume() { MediaPipelineBackend::AudioDecoder* audio_decoder = static_cast<MediaPipelineBackend::AudioDecoder*>(decoder_); EXPECT_TRUE(audio_decoder->SetVolume(1.0)) << "Failed to set audio volume to 1.0"; EXPECT_TRUE(audio_decoder->SetVolume(0.0)) << "Failed to set audio volume to 0.0"; EXPECT_TRUE(audio_decoder->SetVolume(0.2)) << "Failed to set audio volume to 0.2"; } void BufferFeeder::TestVideoConfigs() { MediaPipelineBackend::VideoDecoder* video_decoder = static_cast<MediaPipelineBackend::VideoDecoder*>(decoder_); // Set invalid config first, to test that the decoder still accepts valid // config after an invalid config. VideoConfig config; config.codec = kVideoCodecUnknown; video_decoder->SetConfig(config); EXPECT_TRUE(video_decoder->SetConfig(video_config_)); } // static std::unique_ptr<BufferFeeder> BufferFeeder::LoadAudio( MediaPipelineBackend* backend, const std::string& filename, const base::Closure& eos_cb) { CHECK(backend); base::FilePath file_path = GetTestDataFilePath(filename); DemuxResult demux_result = FFmpegDemuxForTest(file_path, true /* audio */); MediaPipelineBackend::AudioDecoder* decoder = backend->CreateAudioDecoder(); CHECK(decoder); AudioConfig config = DecoderConfigAdapter::ToCastAudioConfig( kPrimary, demux_result.audio_config); bool success = decoder->SetConfig(config); CHECK(success); VLOG(2) << "Got " << demux_result.frames.size() << " audio input frames"; std::unique_ptr<BufferFeeder> feeder(new BufferFeeder(eos_cb)); feeder->audio_config_ = config; feeder->Initialize(backend, decoder, demux_result.frames); return feeder; } // static std::unique_ptr<BufferFeeder> BufferFeeder::LoadVideo( MediaPipelineBackend* backend, const std::string& filename, bool raw_h264, const base::Closure& eos_cb) { CHECK(backend); VideoConfig video_config; BufferList buffers; if (raw_h264) { base::FilePath file_path = GetTestDataFilePath(filename); base::MemoryMappedFile video_stream; CHECK(video_stream.Initialize(file_path)) << "Couldn't open stream file: " << file_path.MaybeAsASCII(); buffers = H264SegmenterForTest(video_stream.data(), video_stream.length()); // TODO(erickung): Either pull data from stream or make caller specify value video_config.codec = kCodecH264; video_config.profile = kH264Main; video_config.additional_config = nullptr; video_config.encryption_scheme = Unencrypted(); } else { base::FilePath file_path = GetTestDataFilePath(filename); DemuxResult demux_result = FFmpegDemuxForTest(file_path, false /* audio */); buffers = demux_result.frames; video_config = DecoderConfigAdapter::ToCastVideoConfig( kPrimary, demux_result.video_config); } MediaPipelineBackend::VideoDecoder* decoder = backend->CreateVideoDecoder(); CHECK(decoder); bool success = decoder->SetConfig(video_config); CHECK(success); VLOG(2) << "Got " << buffers.size() << " video input frames"; std::unique_ptr<BufferFeeder> feeder(new BufferFeeder(eos_cb)); feeder->video_config_ = video_config; feeder->Initialize(backend, decoder, buffers); return feeder; } } // namespace AudioVideoPipelineDeviceTest::AudioVideoPipelineDeviceTest() : sync_type_(MediaPipelineDeviceParams::kModeSyncPts), audio_type_(MediaPipelineDeviceParams::kAudioStreamNormal), stopped_(false), ran_playing_playback_checks_(false), backwards_pts_change_(false), pause_pattern_() {} AudioVideoPipelineDeviceTest::~AudioVideoPipelineDeviceTest() {} void AudioVideoPipelineDeviceTest::Initialize() { // Create the media device. task_runner_.reset(new TaskRunnerImpl()); MediaPipelineDeviceParams params( sync_type_, audio_type_, task_runner_.get(), AudioContentType::kMedia, ::media::AudioDeviceDescription::kDefaultDeviceId); backend_.reset(CastMediaShlib::CreateMediaPipelineBackend(params)); CHECK(backend_); } void AudioVideoPipelineDeviceTest::AddPause(base::TimeDelta delay, base::TimeDelta length) { DCHECK_EQ(MediaPipelineDeviceParams::kModeSyncPts, sync_type_); pause_pattern_.push_back(PauseInfo(delay, length)); } void AudioVideoPipelineDeviceTest::PauseBeforeEos() { if (audio_feeder_) audio_feeder_->PauseBeforeEos(); if (video_feeder_) video_feeder_->PauseBeforeEos(); } void AudioVideoPipelineDeviceTest::AddEffectsStreams() { for (int i = 0; i < kNumEffectsStreams; ++i) { MediaPipelineDeviceParams params( MediaPipelineDeviceParams::kModeIgnorePts, MediaPipelineDeviceParams::kAudioStreamSoundEffects, task_runner_.get(), AudioContentType::kMedia, ::media::AudioDeviceDescription::kDefaultDeviceId); MediaPipelineBackend* effects_backend = CastMediaShlib::CreateMediaPipelineBackend(params); CHECK(effects_backend); effects_backends_.push_back(base::WrapUnique(effects_backend)); MediaPipelineBackend::AudioDecoder* audio_decoder = effects_backend->CreateAudioDecoder(); audio_decoder->SetConfig(DefaultAudioConfig()); std::unique_ptr<BufferFeeder> feeder( new BufferFeeder(base::Bind(&IgnoreEos))); feeder->FeedContinuousPcm(); feeder->Initialize(effects_backend, audio_decoder, BufferList()); feeder->SetAudioConfig(DefaultAudioConfig()); effects_feeders_.push_back(std::move(feeder)); ASSERT_TRUE(effects_backend->Initialize()); } } void AudioVideoPipelineDeviceTest::SetPausePattern( const std::vector<PauseInfo> pattern) { DCHECK_EQ(MediaPipelineDeviceParams::kModeSyncPts, sync_type_); pause_pattern_ = pattern; } void AudioVideoPipelineDeviceTest::ConfigureForAudioOnly( const std::string& filename) { Initialize(); audio_feeder_ = BufferFeeder::LoadAudio( backend_.get(), filename, base::Bind(&AudioVideoPipelineDeviceTest::OnEndOfStream, base::Unretained(this))); ASSERT_TRUE(backend_->Initialize()); } void AudioVideoPipelineDeviceTest::ConfigureForVideoOnly( const std::string& filename, bool raw_h264) { Initialize(); video_feeder_ = BufferFeeder::LoadVideo( backend_.get(), filename, raw_h264, base::Bind(&AudioVideoPipelineDeviceTest::OnEndOfStream, base::Unretained(this))); ASSERT_TRUE(backend_->Initialize()); } void AudioVideoPipelineDeviceTest::ConfigureForFile( const std::string& filename) { Initialize(); base::Closure eos_cb = base::Bind( &AudioVideoPipelineDeviceTest::OnEndOfStream, base::Unretained(this)); video_feeder_ = BufferFeeder::LoadVideo(backend_.get(), filename, false /* raw_h264 */, eos_cb); audio_feeder_ = BufferFeeder::LoadAudio(backend_.get(), filename, eos_cb); ASSERT_TRUE(backend_->Initialize()); } void AudioVideoPipelineDeviceTest::Start() { pause_time_ = base::TimeDelta(); pause_pattern_idx_ = 0; stopped_ = false; ran_playing_playback_checks_ = false; last_pts_ = std::numeric_limits<int64_t>::min(); if (audio_feeder_) audio_feeder_->Start(); if (video_feeder_) video_feeder_->Start(); for (auto& feeder : effects_feeders_) feeder->Start(); for (auto& backend : effects_backends_) backend->Start(kStartPts); RunStoppedChecks(); backend_->Start(kStartPts); int64_t current_pts = backend()->GetCurrentPts(); EXPECT_TRUE(current_pts == kStartPts || current_pts == std::numeric_limits<int64_t>::min()); last_pts_ = current_pts; base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&AudioVideoPipelineDeviceTest::MonitorLoop, base::Unretained(this))); } void AudioVideoPipelineDeviceTest::RunStoppedChecks() { if (audio_feeder_) { audio_feeder_->ScheduleConfigTest(); audio_feeder_->TestAudioVolume(); } if (video_feeder_) video_feeder_->ScheduleConfigTest(); } void AudioVideoPipelineDeviceTest::RunPlaybackChecks() { if (sync_type_ != MediaPipelineDeviceParams::kModeSyncPts) return; RunStoppedChecks(); EXPECT_TRUE(backend_->SetPlaybackRate(1.0f)); if (!backend_->SetPlaybackRate(0.1f)) LOG(INFO) << "Playback rate 0.1 not supported"; if (!backend_->SetPlaybackRate(0.5f)) LOG(INFO) << "Playback rate 0.5 not supported"; if (!backend_->SetPlaybackRate(1.5f)) LOG(INFO) << "Playback rate 1.5 not supported"; EXPECT_TRUE(backend_->SetPlaybackRate(1.0f)); } void AudioVideoPipelineDeviceTest::OnEndOfStream() { if ((!audio_feeder_ || audio_feeder_->eos()) && (!video_feeder_ || video_feeder_->eos())) { RunPlaybackChecks(); backend_->Stop(); stopped_ = true; RunStoppedChecks(); for (auto& feeder : effects_feeders_) feeder->Stop(); base::RunLoop::QuitCurrentWhenIdleDeprecated(); } } void AudioVideoPipelineDeviceTest::MonitorLoop() { // Backend is stopped, no need to monitor the loop any more. if (stopped_ || !backend_) return; // Run checks while playing (once). if (!ran_playing_playback_checks_) { RunPlaybackChecks(); ran_playing_playback_checks_ = true; } int64_t pts = backend_->GetCurrentPts(); base::TimeDelta media_time = base::TimeDelta::FromMicroseconds(pts); if (sync_type_ == MediaPipelineDeviceParams::kModeSyncPts) { // Check that the current PTS is no more than 100ms past the last pushed // PTS. if (audio_feeder_ && audio_feeder_->last_pushed_pts() != std::numeric_limits<int64_t>::min()) { EXPECT_LE(pts, std::max(kStartPts, audio_feeder_->last_pushed_pts() + 100 * 1000)); } if (video_feeder_ && video_feeder_->last_pushed_pts() != std::numeric_limits<int64_t>::min()) { EXPECT_LE(pts, std::max(kStartPts, video_feeder_->last_pushed_pts() + 100 * 1000)); } // PTS is allowed to move backwards once to allow for updates when the first // buffers are pushed. if (!backwards_pts_change_) { if (pts < last_pts_) backwards_pts_change_ = true; } else { EXPECT_GE(pts, last_pts_); } last_pts_ = pts; } if (!pause_pattern_.empty() && pause_pattern_[pause_pattern_idx_].delay >= base::TimeDelta() && media_time >= pause_time_ + pause_pattern_[pause_pattern_idx_].delay) { // Do Pause backend_->Pause(); pause_time_ = base::TimeDelta::FromMicroseconds(backend_->GetCurrentPts()); RunPlaybackChecks(); VLOG(2) << "Pausing at " << pause_time_.InMilliseconds() << "ms for " << pause_pattern_[pause_pattern_idx_].length.InMilliseconds() << "ms"; // Wait for pause finish base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, base::BindOnce(&AudioVideoPipelineDeviceTest::OnPauseCompleted, base::Unretained(this)), pause_pattern_[pause_pattern_idx_].length); return; } // Check state again in a little while base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, base::BindOnce(&AudioVideoPipelineDeviceTest::MonitorLoop, base::Unretained(this)), kMonitorLoopDelay); } void AudioVideoPipelineDeviceTest::OnPauseCompleted() { // Make sure the media time didn't move during that time. base::TimeDelta media_time = base::TimeDelta::FromMicroseconds(backend_->GetCurrentPts()); // Make sure that the PTS did not advance too much while paused. EXPECT_LT(media_time, pause_time_ + base::TimeDelta::FromMilliseconds(kPausePtsSlackMs)); pause_time_ = media_time; pause_pattern_idx_ = (pause_pattern_idx_ + 1) % pause_pattern_.size(); VLOG(2) << "Pause complete, restarting media clock"; RunPlaybackChecks(); // Resume playback and frame feeding. backend_->Resume(); RunPlaybackChecks(); MonitorLoop(); } void AudioVideoPipelineDeviceTest::TestBackendStates() { ASSERT_TRUE(backend()->Initialize()); base::RunLoop().RunUntilIdle(); RunStoppedChecks(); base::RunLoop().RunUntilIdle(); const int64_t start_pts = 222; ASSERT_TRUE(backend()->Start(start_pts)); base::RunLoop().RunUntilIdle(); RunPlaybackChecks(); ASSERT_TRUE(backend()->Pause()); base::RunLoop().RunUntilIdle(); RunPlaybackChecks(); ASSERT_TRUE(backend()->Resume()); base::RunLoop().RunUntilIdle(); RunPlaybackChecks(); backend()->Stop(); base::RunLoop().RunUntilIdle(); RunStoppedChecks(); base::RunLoop().RunUntilIdle(); } void AudioVideoPipelineDeviceTest::StartImmediateEosTest() { RunStoppedChecks(); ASSERT_TRUE(backend()->Initialize()); base::RunLoop().RunUntilIdle(); Start(); } void AudioVideoPipelineDeviceTest::EndImmediateEosTest() { RunPlaybackChecks(); ASSERT_TRUE(backend_->Pause()); base::RunLoop().RunUntilIdle(); RunPlaybackChecks(); backend_->Stop(); base::RunLoop().RunUntilIdle(); RunStoppedChecks(); base::RunLoop::QuitCurrentWhenIdleDeprecated(); } TEST_F(AudioVideoPipelineDeviceTest, PcmPlayback) { set_sync_type(MediaPipelineDeviceParams::kModeSyncPts); ConfigureForAudioOnly("bear_pcm.wav"); PauseBeforeEos(); Start(); base::RunLoop().Run(); } TEST_F(AudioVideoPipelineDeviceTest, Mp3Playback) { set_sync_type(MediaPipelineDeviceParams::kModeSyncPts); ConfigureForAudioOnly("sfx.mp3"); PauseBeforeEos(); Start(); base::RunLoop().Run(); } TEST_F(AudioVideoPipelineDeviceTest, AacPlayback) { set_sync_type(MediaPipelineDeviceParams::kModeSyncPts); ConfigureForAudioOnly("sfx.m4a"); PauseBeforeEos(); Start(); base::RunLoop().Run(); } TEST_F(AudioVideoPipelineDeviceTest, VorbisPlayback) { set_sync_type(MediaPipelineDeviceParams::kModeIgnorePts); ConfigureForAudioOnly("sfx.ogg"); Start(); base::RunLoop().Run(); } // TODO(kmackay) FFmpegDemuxForTest can't handle AC3 or EAC3. TEST_F(AudioVideoPipelineDeviceTest, H264Playback) { set_sync_type(MediaPipelineDeviceParams::kModeSyncPts); ConfigureForVideoOnly("bear.h264", true /* raw_h264 */); PauseBeforeEos(); Start(); base::RunLoop().Run(); } TEST_F(AudioVideoPipelineDeviceTest, WebmPlaybackWithPause) { if (!MediaCapabilitiesShlib::IsSupportedVideoConfig(kCodecVP8, kVideoProfileUnknown, 1)) return; set_sync_type(MediaPipelineDeviceParams::kModeSyncPts); // Setup to pause for 100ms every 500ms AddPause(base::TimeDelta::FromMilliseconds(500), base::TimeDelta::FromMilliseconds(100)); ConfigureForVideoOnly("bear-640x360.webm", false /* raw_h264 */); Start(); base::RunLoop().Run(); } TEST_F(AudioVideoPipelineDeviceTest, Vp8Playback) { if (!MediaCapabilitiesShlib::IsSupportedVideoConfig(kCodecVP8, kVideoProfileUnknown, 1)) return; set_sync_type(MediaPipelineDeviceParams::kModeSyncPts); ConfigureForVideoOnly("bear-vp8a.webm", false /* raw_h264 */); Start(); base::RunLoop().Run(); } TEST_F(AudioVideoPipelineDeviceTest, WebmPlayback) { if (!MediaCapabilitiesShlib::IsSupportedVideoConfig(kCodecVP8, kVideoProfileUnknown, 1)) return; set_sync_type(MediaPipelineDeviceParams::kModeSyncPts); ConfigureForFile("bear-640x360.webm"); PauseBeforeEos(); Start(); base::RunLoop().Run(); } // TODO(kmackay) FFmpegDemuxForTest can't handle HEVC or VP9. TEST_F(AudioVideoPipelineDeviceTest, AudioBackendStates) { Initialize(); MediaPipelineBackend::AudioDecoder* audio_decoder = backend()->CreateAudioDecoder(); // Test setting config before Initialize(). std::unique_ptr<BufferFeeder> feeder( new BufferFeeder(base::Bind(&IgnoreEos))); feeder->Initialize(backend(), audio_decoder, BufferList()); feeder->SetAudioConfig(DefaultAudioConfig()); feeder->TestAudioConfigs(); SetAudioFeeder(std::move(feeder)); TestBackendStates(); } TEST_F(AudioVideoPipelineDeviceTest, AudioEffectsBackendStates) { set_audio_type(MediaPipelineDeviceParams::kAudioStreamSoundEffects); set_sync_type(MediaPipelineDeviceParams::kModeIgnorePts); Initialize(); MediaPipelineBackend::AudioDecoder* audio_decoder = backend()->CreateAudioDecoder(); std::unique_ptr<BufferFeeder> feeder( new BufferFeeder(base::Bind(&IgnoreEos))); feeder->Initialize(backend(), audio_decoder, BufferList()); feeder->SetAudioConfig(DefaultAudioConfig()); ASSERT_TRUE(audio_decoder->SetConfig(DefaultAudioConfig())); SetAudioFeeder(std::move(feeder)); TestBackendStates(); } TEST_F(AudioVideoPipelineDeviceTest, VideoBackendStates) { Initialize(); MediaPipelineBackend::VideoDecoder* video_decoder = backend()->CreateVideoDecoder(); // Test setting config before Initialize(). std::unique_ptr<BufferFeeder> feeder( new BufferFeeder(base::Bind(&IgnoreEos))); feeder->Initialize(backend(), video_decoder, BufferList()); feeder->SetVideoConfig(DefaultVideoConfig()); feeder->TestVideoConfigs(); SetVideoFeeder(std::move(feeder)); TestBackendStates(); } TEST_F(AudioVideoPipelineDeviceTest, AudioImmediateEos) { Initialize(); MediaPipelineBackend::AudioDecoder* audio_decoder = backend()->CreateAudioDecoder(); std::unique_ptr<BufferFeeder> feeder(new BufferFeeder( base::Bind(&AudioVideoPipelineDeviceTest::EndImmediateEosTest, base::Unretained(this)))); feeder->Initialize(backend(), audio_decoder, BufferList()); feeder->SetAudioConfig(DefaultAudioConfig()); SetAudioFeeder(std::move(feeder)); StartImmediateEosTest(); base::RunLoop().RunUntilIdle(); } TEST_F(AudioVideoPipelineDeviceTest, VideoImmediateEos) { Initialize(); MediaPipelineBackend::VideoDecoder* video_decoder = backend()->CreateVideoDecoder(); std::unique_ptr<BufferFeeder> video_feeder(new BufferFeeder( base::Bind(&AudioVideoPipelineDeviceTest::EndImmediateEosTest, base::Unretained(this)))); video_feeder->Initialize(backend(), video_decoder, BufferList()); video_feeder->SetVideoConfig(DefaultVideoConfig()); SetVideoFeeder(std::move(video_feeder)); MediaPipelineBackend::AudioDecoder* audio_decoder = backend()->CreateAudioDecoder(); std::unique_ptr<BufferFeeder> audio_feeder( new BufferFeeder(base::Bind(&IgnoreEos))); audio_feeder->Initialize(backend(), audio_decoder, BufferList()); audio_feeder->SetAudioConfig(DefaultAudioConfig()); SetAudioFeeder(std::move(audio_feeder)); StartImmediateEosTest(); base::RunLoop().RunUntilIdle(); } TEST_F(AudioVideoPipelineDeviceTest, Mp3Playback_WithEffectsStreams) { set_sync_type(MediaPipelineDeviceParams::kModeSyncPts); ConfigureForAudioOnly("sfx.mp3"); PauseBeforeEos(); AddEffectsStreams(); Start(); base::RunLoop().Run(); } TEST_F(AudioVideoPipelineDeviceTest, AacPlayback_WithEffectsStreams) { set_sync_type(MediaPipelineDeviceParams::kModeSyncPts); ConfigureForAudioOnly("sfx.m4a"); PauseBeforeEos(); AddEffectsStreams(); Start(); base::RunLoop().Run(); } TEST_F(AudioVideoPipelineDeviceTest, VorbisPlayback_WithEffectsStreams) { set_sync_type(MediaPipelineDeviceParams::kModeIgnorePts); ConfigureForAudioOnly("sfx.ogg"); AddEffectsStreams(); Start(); base::RunLoop().Run(); } // TODO(kmackay) FFmpegDemuxForTest can't handle AC3 or EAC3. TEST_F(AudioVideoPipelineDeviceTest, H264Playback_WithEffectsStreams) { set_sync_type(MediaPipelineDeviceParams::kModeSyncPts); ConfigureForVideoOnly("bear.h264", true /* raw_h264 */); PauseBeforeEos(); AddEffectsStreams(); Start(); base::RunLoop().Run(); } TEST_F(AudioVideoPipelineDeviceTest, WebmPlaybackWithPause_WithEffectsStreams) { if (!MediaCapabilitiesShlib::IsSupportedVideoConfig(kCodecVP8, kVideoProfileUnknown, 1)) return; set_sync_type(MediaPipelineDeviceParams::kModeSyncPts); // Setup to pause for 100ms every 500ms AddPause(base::TimeDelta::FromMilliseconds(500), base::TimeDelta::FromMilliseconds(100)); ConfigureForVideoOnly("bear-640x360.webm", false /* raw_h264 */); AddEffectsStreams(); Start(); base::RunLoop().Run(); } TEST_F(AudioVideoPipelineDeviceTest, Vp8Playback_WithEffectsStreams) { if (!MediaCapabilitiesShlib::IsSupportedVideoConfig(kCodecVP8, kVideoProfileUnknown, 1)) return; set_sync_type(MediaPipelineDeviceParams::kModeSyncPts); ConfigureForVideoOnly("bear-vp8a.webm", false /* raw_h264 */); AddEffectsStreams(); Start(); base::RunLoop().Run(); } TEST_F(AudioVideoPipelineDeviceTest, WebmPlayback_WithEffectsStreams) { if (!MediaCapabilitiesShlib::IsSupportedVideoConfig(kCodecVP8, kVideoProfileUnknown, 1)) return; set_sync_type(MediaPipelineDeviceParams::kModeSyncPts); ConfigureForFile("bear-640x360.webm"); PauseBeforeEos(); AddEffectsStreams(); Start(); base::RunLoop().Run(); } } // namespace media } // namespace chromecast
14,444
397
import os import pickle from studio import fs_tracker def clientFunction(args, files): print('client function call with args ' + str(args) + ' and files ' + str(files)) modelfile = 'model.dat' filename = files.get('model') or \ os.path.join(fs_tracker.get_artifact('modeldir'), modelfile) print("Trying to load file {}".format(filename)) if os.path.exists(filename): with open(filename, 'rb') as f: args = pickle.loads(f.read()) + 1 else: print("Trying to write file {}".format(filename)) with open(filename, 'wb') as f: f.write(pickle.dumps(args, protocol=2)) return args if __name__ == "__main__": clientFunction('test', {})
297
740
<reponame>StephenHwang/vg #ifndef VG_GBWTGRAPH_HELPER_HPP_INCLUDED #define VG_GBWTGRAPH_HELPER_HPP_INCLUDED /** \file * Utility classes and functions for working with GBWTGraph. */ #include <gbwtgraph/gbz.h> #include <gbwtgraph/minimizer.h> namespace vg { //------------------------------------------------------------------------------ /* These are the proper ways of saving and loading GBWTGraph structures. Loading with `vg::io::VPKG::load_one` is also supported. */ /// Load GBWTGraph from the file. /// NOTE: Call `graph.set_gbwt()` afterwards with the appropriate GBWT index. void load_gbwtgraph(gbwtgraph::GBWTGraph& graph, const std::string& filename, bool show_progress = false); /// Load GBZ from the file. void load_gbz(gbwtgraph::GBZ& gbz, const std::string& filename, bool show_progress = false); /// Load GBZ from separate GBWT / GBWTGraph files. void load_gbz(gbwtgraph::GBZ& gbz, const std::string& gbwt_name, const std::string& graph_name, bool show_progress = false); /// Load GBWT and GBWTGraph from the GBZ file. void load_gbz(gbwt::GBWT& index, gbwtgraph::GBWTGraph& graph, const std::string& filename, bool show_progress = false); /// Load a minimizer index from the file. void load_minimizer(gbwtgraph::DefaultMinimizerIndex& index, const std::string& filename, bool show_progress = false); /// Save GBWTGraph to the file. void save_gbwtgraph(const gbwtgraph::GBWTGraph& graph, const std::string& filename, bool show_progress = false); /// Save GBZ to the file. void save_gbz(const gbwtgraph::GBZ& gbz, const std::string& filename, bool show_progress = false); /// Save GBWT and GBWTGraph to the GBZ file. void save_gbz(const gbwt::GBWT& index, gbwtgraph::GBWTGraph& graph, const std::string& filename, bool show_progress = false); /// Save GBZ to separate GBWT / GBWTGraph files. void save_gbz(const gbwtgraph::GBZ& gbz, const std::string& gbwt_name, const std::string& graph_name, bool show_progress = false); /// Save a minimizer index to the file. void save_minimizer(const gbwtgraph::DefaultMinimizerIndex& index, const std::string& filename, bool show_progress = false); //------------------------------------------------------------------------------ } // namespace vg #endif // VG_GBWTGRAPH_HELPER_HPP_INCLUDED
748
2,766
<reponame>DeltaEpsilon7787/XlsxWriter ############################################################################### # # Tests for XlsxWriter. # # Copyright (c), 2013-2021, <NAME>, <EMAIL> # import unittest from io import StringIO from ..helperfunctions import _xml_to_list from ...worksheet import Worksheet class TestAssembleWorksheet(unittest.TestCase): """ Test assembling a complete Worksheet file. """ def test_assemble_xml_file(self): """Test writing a worksheet with no cell data.""" self.maxDiff = None fh = StringIO() worksheet = Worksheet() worksheet._set_filehandle(fh) worksheet.select() worksheet.name = 'Sheet1' worksheet.excel_version = 2010 data = [-2, 2, 3, -1, 0] worksheet.write_row('A1', data) # Set up sparklines. worksheet.add_sparkline('F1', {'range': 'A1:E1', 'high_point': True, 'low_point': True, 'negative_points': True, 'first_point': True, 'last_point': True, 'markers': True, 'series_color': '#C00000', 'negative_color': '#FF0000', 'markers_color': '#FFC000', 'first_color': '#00B050', 'last_color': '#00B0F0', 'high_color': '#FFFF00', 'low_color': '#92D050', }) worksheet._assemble_xml_file() exp = _xml_to_list(""" <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:x14ac="http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac" mc:Ignorable="x14ac"> <dimension ref="A1:E1"/> <sheetViews> <sheetView tabSelected="1" workbookViewId="0"/> </sheetViews> <sheetFormatPr defaultRowHeight="15" x14ac:dyDescent="0.25"/> <sheetData> <row r="1" spans="1:5" x14ac:dyDescent="0.25"> <c r="A1"> <v>-2</v> </c> <c r="B1"> <v>2</v> </c> <c r="C1"> <v>3</v> </c> <c r="D1"> <v>-1</v> </c> <c r="E1"> <v>0</v> </c> </row> </sheetData> <pageMargins left="0.7" right="0.7" top="0.75" bottom="0.75" header="0.3" footer="0.3"/> <extLst> <ext xmlns:x14="http://schemas.microsoft.com/office/spreadsheetml/2009/9/main" uri="{05C60535-1F16-4fd2-B633-F4F36F0B64E0}"> <x14:sparklineGroups xmlns:xm="http://schemas.microsoft.com/office/excel/2006/main"> <x14:sparklineGroup displayEmptyCellsAs="gap" markers="1" high="1" low="1" first="1" last="1" negative="1"> <x14:colorSeries rgb="FFC00000"/> <x14:colorNegative rgb="FFFF0000"/> <x14:colorAxis rgb="FF000000"/> <x14:colorMarkers rgb="FFFFC000"/> <x14:colorFirst rgb="FF00B050"/> <x14:colorLast rgb="FF00B0F0"/> <x14:colorHigh rgb="FFFFFF00"/> <x14:colorLow rgb="FF92D050"/> <x14:sparklines> <x14:sparkline> <xm:f>Sheet1!A1:E1</xm:f> <xm:sqref>F1</xm:sqref> </x14:sparkline> </x14:sparklines> </x14:sparklineGroup> </x14:sparklineGroups> </ext> </extLst> </worksheet> """) got = _xml_to_list(fh.getvalue()) self.assertEqual(got, exp)
2,941
913
""" Implementation of the command-line I{pyflakes} tool. """ from __future__ import absolute_import # For backward compatibility __all__ = ['check', 'checkPath', 'checkRecursive', 'iterSourceCode', 'main'] from pyflakes.api import check, checkPath, checkRecursive, iterSourceCode, main
82
412
/*******************************************************************\ Module: Unit tests helpers for arrays Author: <NAME>, <EMAIL> \*******************************************************************/ #ifndef CPROVER_ANALYSES_VARIABLE_SENSITIVITY_FULL_ARRAY_ABSTRACT_OBJECT_ARRAY_BUILDER_H #define CPROVER_ANALYSES_VARIABLE_SENSITIVITY_FULL_ARRAY_ABSTRACT_OBJECT_ARRAY_BUILDER_H #include <analyses/variable-sensitivity/full_array_abstract_object.h> full_array_abstract_objectt::full_array_pointert build_array( const exprt &array_expr, abstract_environmentt &environment, const namespacet &ns); const int TOP_MEMBER = std::numeric_limits<int>::max(); full_array_abstract_objectt::full_array_pointert build_array( const std::vector<int> &array, abstract_environmentt &environment, const namespacet &ns); full_array_abstract_objectt::full_array_pointert build_top_array(); full_array_abstract_objectt::full_array_pointert build_bottom_array(); #endif
319
2,577
/* * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH * under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. Camunda licenses this file to you under the Apache License, * Version 2.0; 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.camunda.bpm.integrationtest.functional.spin; import org.camunda.bpm.application.ProcessApplicationContext; import org.camunda.bpm.engine.runtime.ProcessInstance; import org.camunda.bpm.engine.variable.Variables; import org.camunda.bpm.engine.variable.value.ObjectValue; import org.camunda.bpm.integrationtest.functional.spin.dataformat.Foo; import org.camunda.bpm.integrationtest.functional.spin.dataformat.FooDataFormat; import org.camunda.bpm.integrationtest.functional.spin.dataformat.FooDataFormatProvider; import org.camunda.bpm.integrationtest.functional.spin.dataformat.FooSpin; import org.camunda.bpm.integrationtest.util.AbstractFoxPlatformIntegrationTest; import org.camunda.spin.spi.DataFormatProvider; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import static org.camunda.bpm.engine.variable.Variables.serializedObjectValue; /** * @author <NAME> * */ @RunWith(Arquillian.class) public class PaDataFormatProviderTest extends AbstractFoxPlatformIntegrationTest { @Deployment public static WebArchive createDeployment() { WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "PaDataFormatTest.war") .addAsResource("META-INF/processes.xml") .addClass(AbstractFoxPlatformIntegrationTest.class) .addAsResource("org/camunda/bpm/integrationtest/oneTaskProcess.bpmn") .addClass(Foo.class) .addClass(FooDataFormat.class) .addClass(FooDataFormatProvider.class) .addClass(FooSpin.class) .addAsServiceProvider(DataFormatProvider.class, FooDataFormatProvider.class) .addClass(ReferenceStoringProcessApplication.class); return webArchive; } /** * Tests that * 1) a serialized value can be set OUT OF process application context * even if the data format is not available (using the fallback serializer) * 2) and that this value can be deserialized IN process application context * by using the PA-local serializer */ @Test public void customFormatCanBeUsedForVariableSerialization() { final ProcessInstance pi = runtimeService.startProcessInstanceByKey("testProcess", Variables.createVariables() .putValue("serializedObject", serializedObjectValue("foo") .serializationDataFormat(FooDataFormat.NAME) .objectTypeName(Foo.class.getName()))); ObjectValue objectValue = null; try { ProcessApplicationContext.setCurrentProcessApplication(ReferenceStoringProcessApplication.INSTANCE); objectValue = runtimeService.getVariableTyped(pi.getId(), "serializedObject", true); } finally { ProcessApplicationContext.clear(); } Object value = objectValue.getValue(); Assert.assertNotNull(value); Assert.assertTrue(value instanceof Foo); } }
1,234
1,025
<reponame>jeongjoonyoo/CodeXL<gh_stars>1000+ //================================================================================== // Copyright (c) 2016 , Advanced Micro Devices, Inc. All rights reserved. // /// \author AMD Developer Tools Team /// \file gdDebuggedProcessEventsView.cpp /// //================================================================================== //------------------------------ gdDebuggedProcessEventsView.cpp ------------------------------ // Qt #include <AMDTApplicationComponents/Include/acQtIncludes.h> // Infra: #include <AMDTBaseTools/Include/AMDTDefinitions.h> #include <AMDTBaseTools/Include/gtAssert.h> #include <AMDTOSWrappers/Include/osTime.h> #include <AMDTOSWrappers/Include/osDebugLog.h> #include <AMDTOSWrappers/Include/osThread.h> #include <AMDTOSWrappers/Include/osStringConstants.h> #include <AMDTAPIClasses/Include/apStringConstants.h> #include <AMDTAPIClasses/Include/Events/apEventsHandler.h> #include <AMDTAPIClasses/Include/Events/apBreakpointHitEvent.h> #include <AMDTAPIClasses/Include/Events/apDebuggedProcessDetectedErrorEvent.h> #include <AMDTAPIClasses/Include/Events/apDebuggedProcessCreationFailureEvent.h> #include <AMDTAPIClasses/Include/Events/apDebuggedProcessTerminatedEvent.h> #include <AMDTAPIClasses/Include/Events/apInfrastructureFailureEvent.h> #include <AMDTAPIClasses/Include/Events/apModuleLoadedEvent.h> #include <AMDTAPIClasses/Include/Events/apOpenCLErrorEvent.h> #include <AMDTAPIClasses/Include/Events/apTechnologyMonitorFailureEvent.h> #include <AMDTAPIClasses/Include/Events/apMemoryLeakEvent.h> #include <AMDTApplicationComponents/Include/acFunctions.h> #include <AMDTApplicationComponents/Include/acIcons.h> #include <AMDTApplicationComponents/Include/acMessageBox.h> #include <AMDTApiFunctions/Include/gaGRApiFunctions.h> #include <AMDTOpenGLServer/Include/gsPublicStringConstants.h> // AMDTApplicationFramework: #include <AMDTApplicationFramework/Include/afAppStringConstants.h> #include <AMDTApplicationFramework/Include/afHTMLUtils.h> #include <AMDTApplicationFramework/Include/afProjectManager.h> #include <AMDTApplicationFramework/Include/afGlobalVariableChangedEvent.h> // Local: #include <AMDTGpuDebuggingComponents/Include/gdApplicationCommands.h> #include <AMDTGpuDebuggingComponents/Include/views/gdDebuggedProcessEventsView.h> #include <AMDTGpuDebuggingComponents/Include/commands/gdStopDebuggingCommand.h> #include <AMDTGpuDebuggingComponents/Include/gdGDebuggerGlobalVariablesManager.h> #include <AMDTGpuDebuggingComponents/Include/gdCommandIDs.h> #include <AMDTGpuDebuggingComponents/Include/gdPropertiesEventObserver.h> #include <AMDTGpuDebuggingComponents/Include/gdStringConstants.h> #include <AMDTGpuDebuggingComponents/Include/gdAidFunctions.h> #include <AMDTGpuDebuggingComponents/Include/gdHTMLProperties.h> #include <AMDTGpuDebuggingComponents/Include/gdEventStringBuilder.h> #define GD_DEBUGGED_PROCESS_EVENTS_SCROLL_TIMER_DURATION 100 // --------------------------------------------------------------------------- // Name: gdDebuggedProcessEventsView::gdDebuggedProcessEventsView // Description: Constructor. // Arguments: parent - My parent window. // Author: <NAME> // Date: 1/11/2003 // --------------------------------------------------------------------------- gdDebuggedProcessEventsView::gdDebuggedProcessEventsView(QWidget* pParent) : acListCtrl(pParent), m_interceptionWarningShown(false), _wasGremedyOGLServerLoaded(false), _wasGremedyOGLESServerLoaded(false), _shouldDisplayEventProperties(true), m_pClearViewAction(NULL) { // Create and load the image list: createAndLoadImageList(); bool rcConnect = connect(this, SIGNAL(itemClicked(QTableWidgetItem*)), this, SLOT(onDebugProcessEventsSelected(QTableWidgetItem*))); GT_ASSERT(rcConnect); rcConnect = connect(this, SIGNAL(itemPressed(QTableWidgetItem*)), this, SLOT(onDebugProcessEventsSelected(QTableWidgetItem*))); GT_ASSERT(rcConnect); rcConnect = connect(this, SIGNAL(itemActivated(QTableWidgetItem*)), this, SLOT(onDebugProcessEventsSelected(QTableWidgetItem*))); GT_ASSERT(rcConnect); rcConnect = connect(this, SIGNAL(itemChanged(QTableWidgetItem*)), this, SLOT(onDebugProcessEventsSelected(QTableWidgetItem*))); GT_ASSERT(rcConnect); rcConnect = connect(this, SIGNAL(currentItemChanged(QTableWidgetItem*, QTableWidgetItem*)), this, SLOT(onDebugProcessEventsCurrentItemChanged(QTableWidgetItem*, QTableWidgetItem*))); GT_ASSERT(rcConnect); // Register myself to listen to debugged process events: apEventsHandler::instance().registerEventsObserver(*this, AP_APPLICATION_COMPONENTS_EVENTS_HANDLING_PRIORITY); // Hide horizontal headers: horizontalHeader()->hide(); verticalHeader()->hide(); setColumnCount(1); // Extend the context menu: extendContextMenu(); } // --------------------------------------------------------------------------- // Name: gdDebuggedProcessEventsView::~gdDebuggedProcessEventsView // Description: Destructor // Author: <NAME> // Date: 1/11/2003 // --------------------------------------------------------------------------- gdDebuggedProcessEventsView::~gdDebuggedProcessEventsView() { // Uri, 23/8/09: When quitting CodeXL Mac (usually after debugging an iPhone app), // this function is sometimes called after the properties view was already destroyed // and throws a selection event. Avoid updating the (nonexistant) view in this case: _shouldDisplayEventProperties = false; // Delete just the items' data, wx will clean up the items themselves: clearItemsData(); // Unregister myself from listening to debugged process events: apEventsHandler::instance().unregisterEventsObserver(*this); } // --------------------------------------------------------------------------- // Name: gdDebuggedProcessEventsView::clearView // Description: Clear the event view // Return Val: void // Author: <NAME> // Date: 6/7/2009 // --------------------------------------------------------------------------- void gdDebuggedProcessEventsView::clearView() { clearEventsList(); } // --------------------------------------------------------------------------- // Name: gdDebuggedProcessEventsView::createAndLoadImageList // Description: Creates this view image list, and loads its images // from disk. // Author: <NAME> // Date: 1/11/2003 // --------------------------------------------------------------------------- void gdDebuggedProcessEventsView::createAndLoadImageList() { // Create the pixmap items: QPixmap* pBreakOnDeprecated = new QPixmap; acSetIconInPixmap(*pBreakOnDeprecated, AC_ICON_DEBUG_EVENTSVIEW_BREAK_DEPRECATED); QPixmap* pBreakOnDetectedError = new QPixmap; acSetIconInPixmap(*pBreakOnDetectedError, AC_ICON_DEBUG_EVENTSVIEW_BREAK_DETECTED); QPixmap* pBreakOnMemoryLeak = new QPixmap; acSetIconInPixmap(*pBreakOnMemoryLeak, AC_ICON_DEBUG_EVENTSVIEW_BREAK_MEMORY); QPixmap* pBreakOnOpenGLError = new QPixmap; acSetIconInPixmap(*pBreakOnOpenGLError, AC_ICON_DEBUG_EVENTSVIEW_BREAK_GLERROR); QPixmap* pBreakOnOpenCLError = new QPixmap; acSetIconInPixmap(*pBreakOnOpenCLError, AC_ICON_DEBUG_EVENTSVIEW_BREAK_CLERROR); QPixmap* pBreakOnRedundant = new QPixmap; acSetIconInPixmap(*pBreakOnRedundant, AC_ICON_DEBUG_EVENTSVIEW_BREAK_REDUNDANT); QPixmap* pBreakOnSoftwareFallback = new QPixmap; acSetIconInPixmap(*pBreakOnSoftwareFallback, AC_ICON_DEBUG_EVENTSVIEW_BREAK_SWFALLBACK); QPixmap* pBreakpoint = new QPixmap; acSetIconInPixmap(*pBreakpoint, AC_ICON_DEBUG_EVENTSVIEW_BREAK_POINT); QPixmap* pBreak = new QPixmap; acSetIconInPixmap(*pBreak, AC_ICON_DEBUG_EVENTSVIEW_BREAK); QPixmap* pConnectionEnded = new QPixmap; acSetIconInPixmap(*pConnectionEnded, AC_ICON_DEBUG_EVENTSVIEW_CONNECTION_MINUS); QPixmap* pConnectionEstablished = new QPixmap; acSetIconInPixmap(*pConnectionEstablished, AC_ICON_DEBUG_EVENTSVIEW_CONNECTION_PLUS); QPixmap* pRenderContextCreated = new QPixmap; acSetIconInPixmap(*pRenderContextCreated, AC_ICON_DEBUG_EVENTSVIEW_GLCONTEXT_PLUS); QPixmap* pRenderContextDeleted = new QPixmap; acSetIconInPixmap(*pRenderContextDeleted, AC_ICON_DEBUG_EVENTSVIEW_GLCONTEXT_MINUS); QPixmap* pComputeContextCreated = new QPixmap; acSetIconInPixmap(*pComputeContextCreated, AC_ICON_DEBUG_EVENTSVIEW_CLCONTEXT_PLUS); QPixmap* pComputeContextDeleted = new QPixmap; acSetIconInPixmap(*pComputeContextDeleted, AC_ICON_DEBUG_EVENTSVIEW_CLCONTEXT_MINUS); QPixmap* pCLProgramBuild = new QPixmap; acSetIconInPixmap(*pCLProgramBuild, AC_ICON_DEBUG_EVENTSVIEW_CLPROGRAM_BUILD); QPixmap* pDetectedError = new QPixmap; acSetIconInPixmap(*pDetectedError, AC_ICON_DEBUG_EVENTSVIEW_DETECTED); QPixmap* pDrawStep = new QPixmap; acSetIconInPixmap(*pDrawStep, AC_ICON_DEBUG_EVENTSVIEW_BREAK_DRAWSTEP); QPixmap* pException = new QPixmap; acSetIconInPixmap(*pException, AC_ICON_DEBUG_EVENTSVIEW_EXCEPTION); QPixmap* pForeignBreak = new QPixmap; acSetIconInPixmap(*pForeignBreak, AC_ICON_DEBUG_EVENTSVIEW_BREAK_UNKNOWN); QPixmap* pFrameStep = new QPixmap; acSetIconInPixmap(*pFrameStep, AC_ICON_DEBUG_EVENTSVIEW_BREAK_FRAMESTEP); QPixmap* pModuleLoaded = new QPixmap; acSetIconInPixmap(*pModuleLoaded, AC_ICON_DEBUG_EVENTSVIEW_MODULE_PLUS); QPixmap* pModuleUnloaded = new QPixmap; acSetIconInPixmap(*pModuleUnloaded, AC_ICON_DEBUG_EVENTSVIEW_MODULE_MINUS); QPixmap* pOutputString = new QPixmap; acSetIconInPixmap(*pOutputString, AC_ICON_DEBUG_EVENTSVIEW_OUTPUT); QPixmap* pProcessCreated = new QPixmap; acSetIconInPixmap(*pProcessCreated, AC_ICON_DEBUG_EVENTSVIEW_PROCESS_PLUS); QPixmap* pProcessRunStarted = new QPixmap; acSetIconInPixmap(*pProcessRunStarted, AC_ICON_DEBUG_EVENTSVIEW_PROCESS_RUN); QPixmap* pProcessTerminated = new QPixmap; acSetIconInPixmap(*pProcessTerminated, AC_ICON_DEBUG_EVENTSVIEW_PROCESS_MINUS); QPixmap* pStep = new QPixmap; acSetIconInPixmap(*pStep, AC_ICON_DEBUG_EVENTSVIEW_BREAK_APISTEP); QPixmap* pThreadCreated = new QPixmap; acSetIconInPixmap(*pThreadCreated, AC_ICON_DEBUG_EVENTSVIEW_THREAD_PLUS); QPixmap* pThreadTerminated = new QPixmap; acSetIconInPixmap(*pThreadTerminated, AC_ICON_DEBUG_EVENTSVIEW_THREAD_MINUS); QPixmap* pGDBIcon = new QPixmap; acSetIconInPixmap(*pGDBIcon, AC_ICON_DEBUG_EVENTSVIEW_GDB); QPixmap* pYellowWarningIcon = new QPixmap; acSetIconInPixmap(*pYellowWarningIcon, AC_ICON_WARNING_YELLOW); QPixmap* pMemoryViewerIcon = new QPixmap; acSetIconInPixmap(*pMemoryViewerIcon, AC_ICON_DEBUG_VIEW_MEMORY); QPixmap* pOpenCLError = new QPixmap; acSetIconInPixmap(*pOpenCLError, AC_ICON_DEBUG_EVENTSVIEW_CLERROR); QPixmap* pqueueCreated = new QPixmap; acSetIconInPixmap(*pqueueCreated, AC_ICON_DEBUG_EVENTSVIEW_CLQUEUE_PLUS); QPixmap* pqueueDeleted = new QPixmap; acSetIconInPixmap(*pqueueDeleted, AC_ICON_DEBUG_EVENTSVIEW_CLQUEUE_MINUS); QPixmap* pclProgramCreated = new QPixmap; acSetIconInPixmap(*pclProgramCreated, AC_ICON_DEBUG_EVENTSVIEW_CLPROGRAM_PLUS); QPixmap* pclProgramDeleted = new QPixmap; acSetIconInPixmap(*pclProgramDeleted, AC_ICON_DEBUG_EVENTSVIEW_CLPROGRAM_MINUS); QPixmap* pdebugOutput = new QPixmap; acSetIconInPixmap(*pdebugOutput, AC_ICON_WARNING_YELLOW); // Add the icons to the image list, and add the icon index to a mapping for later use: _listIconsVec.push_back(pProcessCreated); _eventTypeToIconIndexMap[apEvent::AP_DEBUGGED_PROCESS_CREATED] = _listIconsVec.size() - 1; _listIconsVec.push_back(pProcessRunStarted); _eventTypeToIconIndexMap[apEvent::AP_DEBUGGED_PROCESS_RUN_STARTED] = _listIconsVec.size() - 1; _listIconsVec.push_back(pProcessTerminated); _eventTypeToIconIndexMap[apEvent::AP_DEBUGGED_PROCESS_TERMINATED] = _listIconsVec.size() - 1; _eventTypeToIconIndexMap[apEvent::AP_DEBUGGED_PROCESS_CREATION_FAILURE] = _listIconsVec.size() - 1; _listIconsVec.push_back(pThreadCreated); _eventTypeToIconIndexMap[apEvent::AP_THREAD_CREATED] = _listIconsVec.size() - 1; _listIconsVec.push_back(pThreadTerminated); _eventTypeToIconIndexMap[apEvent::AP_THREAD_TERMINATED] = _listIconsVec.size() - 1; _listIconsVec.push_back(pModuleLoaded); _eventTypeToIconIndexMap[apEvent::AP_MODULE_LOADED] = _listIconsVec.size() - 1; _listIconsVec.push_back(pModuleUnloaded); _eventTypeToIconIndexMap[apEvent::AP_MODULE_UNLOADED] = _listIconsVec.size() - 1; _listIconsVec.push_back(pRenderContextCreated); _eventTypeToIconIndexMap[apEvent::AP_RENDER_CONTEXT_CREATED_EVENT] = _listIconsVec.size() - 1; _listIconsVec.push_back(pRenderContextDeleted); _eventTypeToIconIndexMap[apEvent::AP_RENDER_CONTEXT_DELETED_EVENT] = _listIconsVec.size() - 1; _listIconsVec.push_back(pComputeContextCreated); _eventTypeToIconIndexMap[apEvent::AP_COMPUTE_CONTEXT_CREATED_EVENT] = _listIconsVec.size() - 1; _listIconsVec.push_back(pCLProgramBuild); _eventTypeToIconIndexMap[apEvent::AP_OPENCL_PROGRAM_BUILD_EVENT] = _listIconsVec.size() - 1; _listIconsVec.push_back(pComputeContextDeleted); _eventTypeToIconIndexMap[apEvent::AP_COMPUTE_CONTEXT_DELETED_EVENT] = _listIconsVec.size() - 1; _listIconsVec.push_back(pConnectionEstablished); _eventTypeToIconIndexMap[apEvent::AP_API_CONNECTION_ESTABLISHED] = _listIconsVec.size() - 1; _listIconsVec.push_back(pConnectionEnded); _eventTypeToIconIndexMap[apEvent::AP_API_CONNECTION_ENDED] = _listIconsVec.size() - 1; _eventTypeToIconIndexMap[apEvent::AP_TECHNOLOGY_MONITOR_FAILURE_EVENT] = _listIconsVec.size() - 1; _listIconsVec.push_back(pException); _eventTypeToIconIndexMap[apEvent::AP_EXCEPTION] = _listIconsVec.size() - 1; _listIconsVec.push_back(pOutputString); _eventTypeToIconIndexMap[apEvent::AP_DEBUGGED_PROCESS_OUTPUT_STRING] = _listIconsVec.size() - 1; _eventTypeToIconIndexMap[apEvent::AP_USER_WARNING] = _listIconsVec.size() - 1; _eventTypeToIconIndexMap[apEvent::AP_OUTPUT_DEBUG_STRING] = _listIconsVec.size() - 1; _listIconsVec.push_back(pdebugOutput); _eventTypeToIconIndexMap[apEvent::AP_GL_DEBUG_OUTPUT_MESSAGE] = _listIconsVec.size() - 1; _listIconsVec.push_back(pGDBIcon); _eventTypeToIconIndexMap[apEvent::AP_GDB_OUTPUT_STRING] = _listIconsVec.size() - 1; _eventTypeToIconIndexMap[apEvent::AP_GDB_ERROR] = _listIconsVec.size() - 1; _listIconsVec.push_back(pOpenCLError); _eventTypeToIconIndexMap[apEvent::AP_OPENCL_ERROR] = _listIconsVec.size() - 1; _listIconsVec.push_back(pBreakOnOpenCLError); // Add the breakpoints events icons: _listIconsVec.push_back(pBreak); _eventTypeToIconIndexMap[apEvent::AP_BREAKPOINT_HIT] = _listIconsVec.size() - 1; _listIconsVec.push_back(pStep); _listIconsVec.push_back(pDrawStep); _listIconsVec.push_back(pFrameStep); _listIconsVec.push_back(pBreakpoint); _listIconsVec.push_back(pBreakOnOpenGLError); _listIconsVec.push_back(pBreakOnRedundant); _listIconsVec.push_back(pBreakOnDeprecated); _listIconsVec.push_back(pBreakOnSoftwareFallback); _listIconsVec.push_back(pForeignBreak); _listIconsVec.push_back(pBreakOnMemoryLeak); // Memory leak (without break & with break): _listIconsVec.push_back(pYellowWarningIcon); _eventTypeToIconIndexMap[apEvent::AP_MEMORY_LEAK] = _listIconsVec.size() - 1; // Check for memory leaks: _listIconsVec.push_back(pMemoryViewerIcon); _eventTypeToIconIndexMap[apEvent::AP_SEARCHING_FOR_MEMORY_LEAKS] = _listIconsVec.size() - 1; // Detected error and break on detected error: _listIconsVec.push_back(pDetectedError); _eventTypeToIconIndexMap[apEvent::AP_DETECTED_ERROR_EVENT] = _listIconsVec.size() - 1; _listIconsVec.push_back(pBreakOnDetectedError); // Queue created and deleted events: _listIconsVec.push_back(pqueueCreated); _eventTypeToIconIndexMap[apEvent::AP_OPENCL_QUEUE_CREATED_EVENT] = _listIconsVec.size() - 1; _listIconsVec.push_back(pqueueDeleted); _eventTypeToIconIndexMap[apEvent::AP_OPENCL_QUEUE_DELETED_EVENT] = _listIconsVec.size() - 1; // OpenCL program created and deleted events: _listIconsVec.push_back(pclProgramCreated); _eventTypeToIconIndexMap[apEvent::AP_OPENCL_PROGRAM_CREATED_EVENT] = _listIconsVec.size() - 1; _listIconsVec.push_back(pclProgramDeleted); _eventTypeToIconIndexMap[apEvent::AP_OPENCL_PROGRAM_DELETED_EVENT] = _listIconsVec.size() - 1; } // --------------------------------------------------------------------------- // Name: gdDebuggedProcessEventsView::clearEventsList // Description: Clear the events list. // Author: <NAME> // Date: 17/5/2007 // --------------------------------------------------------------------------- void gdDebuggedProcessEventsView::clearEventsList() { // Delete the items data: clearItemsData(); // Delete Items from the list clearList(); } // --------------------------------------------------------------------------- // Name: gdDebuggedProcessEventsView::clearItemsData // Description: Deletes the data of all items. Note that this does not set the // items' data to NULL - use clearEventsList instead. // This function should only be used by itsself in the destructor, // where calling wxListCtrl::DeleteAllItems() causes a wx assert // on Mac. // Author: <NAME> // Date: 16/9/2009 // --------------------------------------------------------------------------- void gdDebuggedProcessEventsView::clearItemsData() { // Delete all item's attached data objects: int listSize = rowCount(); for (int i = 0; i < listSize; i++) { apEvent* pEvent = (apEvent*)(getItemData(i)); if (pEvent != NULL) { delete pEvent; } } } // --------------------------------------------------------------------------- // Name: gdDebuggedProcessEventsView::onEvent // Description: Is called when a debugged process event occurs. // Send the event to the appropriate event function for displaying // it to the user. // Arguments: event - The debugged process eve. // Author: <NAME> // Date: 4/4/2004 // --------------------------------------------------------------------------- void gdDebuggedProcessEventsView::onEvent(const apEvent& eve, bool& vetoEvent) { (void)(vetoEvent); // unused // Build the string and add to the list view: gtString eventAsString; gdEventStringBuilder stringEventBuilder; stringEventBuilder.buildEventString(eve, eventAsString); if (!eventAsString.isEmpty()) { insertListItem(eventAsString, eve); } // Get the event type: apEvent::EventType eventType = eve.eventType(); // Down cast the event according to its type, and call the appropriate // event handling function: switch (eventType) { case apEvent::AP_DEBUGGED_PROCESS_CREATED: { const apDebuggedProcessCreatedEvent& processCreatedEvent = (const apDebuggedProcessCreatedEvent&)eve; onProcessCreation(processCreatedEvent); } break; case apEvent::AP_DEBUGGED_PROCESS_TERMINATED: { const apDebuggedProcessTerminatedEvent& processTermiatedEvent = (const apDebuggedProcessTerminatedEvent&)eve; onProcessTermination(processTermiatedEvent); } break; case apEvent::AP_DEBUGGED_PROCESS_CREATION_FAILURE: { const apDebuggedProcessCreationFailureEvent& processCreationFailureEvent = (const apDebuggedProcessCreationFailureEvent&)eve; onProcessCreationFailure(processCreationFailureEvent); } break; case apEvent::AP_MODULE_LOADED: { const apModuleLoadedEvent& moduleLoadedEvent = (const apModuleLoadedEvent&)eve; onModuleLoad(moduleLoadedEvent); } break; case apEvent::AP_EXCEPTION: { focusLastItem(); } break; case apEvent::AP_GDB_ERROR: { const apGDBErrorEvent& gdbErrorEvent = (const apGDBErrorEvent&)eve; onGDBError(gdbErrorEvent); } break; case apEvent::AP_BREAKPOINT_HIT: { const apBreakpointHitEvent& breakpointEvent = (const apBreakpointHitEvent&)eve; if (breakpointEvent.breakReason() == AP_MEMORY_LEAK_BREAKPOINT_HIT) { onMemoryLeakBreak(breakpointEvent); } } break; case apEvent::AP_DETECTED_ERROR_EVENT: { const apDebuggedProcessDetectedErrorEvent& errorEvent = (const apDebuggedProcessDetectedErrorEvent&)eve; // Focus the last item if break was generated: bool wasErrorBrokenOn = errorEvent.wasGeneratedByBreak(); // If this is a break, highlight the item: if (wasErrorBrokenOn) { focusLastItem(); } } break; case apEvent::APP_GLOBAL_VARIABLE_CHANGED: { // Down cast the event: const afGlobalVariableChangedEvent& variableChangedEvent = (const afGlobalVariableChangedEvent&)eve; // Handle it: if (variableChangedEvent.changedVariableId() == afGlobalVariableChangedEvent::CURRENT_PROJECT) { clearView(); } } break; case apEvent::AP_INFRASTRUCTURE_FAILURE_EVENT: { const apInfrastructureFailureEvent& infraFailureEvent = (const apInfrastructureFailureEvent&)eve; onInfrastructureFailureEvent(infraFailureEvent); } break; case apEvent::AP_EXECUTION_MODE_CHANGED_EVENT: { onExecutionModeChangedEvent(eve); } break; default: // We do not report these events to the user. break; } } // --------------------------------------------------------------------------- // Name: gdDebuggedProcessEventsView::onProcessCreation // Description: Is called when a debugged process is created by our debugger. // Adds the process creation report to this view list. // Arguments: processCreatedEvent - A class representing the process creation event. // Return Val: bool - Success / failure. // Author: <NAME> // Date: 1/11/2003 // --------------------------------------------------------------------------- void gdDebuggedProcessEventsView::onProcessCreation(const apDebuggedProcessCreatedEvent& processCreatedEvent) { (void)(processCreatedEvent); // unused // Get the current project name: gtString projectName = afProjectManager::instance().currentProjectSettings().projectName(); gtString logMsg; logMsg.appendFormattedString(GD_STR_LogMsg_processCreated, projectName.asCharArray()); // Output an "Project name" log printout: OS_OUTPUT_DEBUG_LOG(logMsg.asCharArray(), OS_DEBUG_LOG_INFO); // Make the list empty: clearEventsList(); } // --------------------------------------------------------------------------- // Name: gdDebuggedProcessEventsView::onInfrastructureFailureEvent // Description: Is called when an infrastructure failure happens. // Arguments: infraFailureEvent - A class containing the failure details. // Author: <NAME> // Date: 5/8/2008 // --------------------------------------------------------------------------- void gdDebuggedProcessEventsView::onInfrastructureFailureEvent(const apInfrastructureFailureEvent& infraFailureEvent) { // Get the infrastructure failure reason: apInfrastructureFailureEvent::FailureReason failureReason = infraFailureEvent.failureReason(); if (failureReason == apInfrastructureFailureEvent::FAILED_TO_INITIALIZE_GDB) { // Raise an appropriate message box: QString errString = GD_STR_ErrorGDBIsNotInstalled; acMessageBox::instance().critical(GD_STR_ErrorGDBIsNotInstalledMsgHeader, errString, QMessageBox::Ok); } } // --------------------------------------------------------------------------- // Name: gdDebuggedProcessEventsView::onProcessTermination // Description: Is called when the debugged process terminates (exits). // Adds the process exit report to this view list // Arguments: processTerminatedEvent - A class representing the process termination event. // Author: <NAME> // Date: 20/12/2003 // --------------------------------------------------------------------------- void gdDebuggedProcessEventsView::onProcessTermination(const apDebuggedProcessTerminatedEvent& processTerminatedEvent) { (void)(processTerminatedEvent); // unused // Clear the interception failure cache: m_apiModuleLoaded.clear(); m_interceptionWarningShown = false; // Initialize the Spy loading check _wasGremedyOGLServerLoaded = false; // Initialize the OpenGL ES Common dll flag: _wasGremedyOGLESServerLoaded = false; } // --------------------------------------------------------------------------- // Name: gdDebuggedProcessEventsView::onProcessCreationFailure // Description: Is called when the debugged process terminates (exits). // Adds the process exit report to this view list // Arguments: processTermiatedEvent - A class representing the process termination event. // Author: <NAME> // Date: 11/2/2010 // --------------------------------------------------------------------------- void gdDebuggedProcessEventsView::onProcessCreationFailure(const apDebuggedProcessCreationFailureEvent& processCreationFailureEvent) { // Get the failure reason: apDebuggedProcessCreationFailureEvent::ProcessCreationFailureReason failureReason = processCreationFailureEvent.processCreationFailureReason(); switch (failureReason) { case apDebuggedProcessCreationFailureEvent::AUTOMATIC_CONFIGURATION_FAILED: { // Display a message box suggesting to switch to manual setup if the problem persists: acMessageBox::instance().critical(AF_STR_ErrorA, GD_STR_ErrorAutomaticConfigurationFailed, QMessageBox::Ok); } break; case apDebuggedProcessCreationFailureEvent::COULD_NOT_CREATE_PROCESS: { gtString errMsgGTString = GD_STR_ErrorCouldNotCreateProcess; errMsgGTString += L"\n"; // Get the failure reason string: errMsgGTString += processCreationFailureEvent.processCreationError(); if (processCreationFailureEvent.processCreationError().isEmpty()) { if (afProjectManager::instance().currentProjectSettings().isRemoteTarget()) { // If we are in a remote session, let the user know that we have failed to connect to the remote agent. errMsgGTString += AF_STR_REMOTE_GENERAL_ERROR_MSG; } else { errMsgGTString += GD_STR_ErrorCouldNotCreateProcessGenericReason; } } QString errMsg = acGTStringToQString(errMsgGTString); acMessageBox::instance().critical(AF_STR_ErrorA, errMsg, QMessageBox::Ok); } break; case apDebuggedProcessCreationFailureEvent::REMOTE_HANDSHAKE_MISMATCH: { // Output the error to the user. QString errMsg = acGTStringToQString(processCreationFailureEvent.processCreationError()); acMessageBox::instance().critical(AF_STR_ErrorA, errMsg, QMessageBox::Ok); } break; default: { // Unexpected value! GT_ASSERT(false); } break; } // Clear the interception failure cache: m_apiModuleLoaded.clear(); m_interceptionWarningShown = false; // Initialize the Spy loading check _wasGremedyOGLServerLoaded = false; // Initialize the OpenGL ES Common dll flag: _wasGremedyOGLESServerLoaded = false; } // --------------------------------------------------------------------------- // Name: gdDebuggedProcessEventsView::onModuleLoad // Description: Is called when the debugged process loads a DLL. // Updates this view list with the name of the loaded DLL. // Arguments: dllLoadedEvent - A class representing the dll load event. // Return Val: bool - Success / failure. // Author: <NAME> // Date: 1/11/2003 // --------------------------------------------------------------------------- void gdDebuggedProcessEventsView::onModuleLoad(const apModuleLoadedEvent& dllLoadedEvent) { // Get the loaded module path: const gtString& modulePath = dllLoadedEvent.modulePath(); // Perform module load related sanity checks: checkLoadedModule(modulePath); } // --------------------------------------------------------------------------- // Name: gdDebuggedProcessEventsView::focusLastItem // Description: Focus the last item added to the list // Author: <NAME> // Date: 4/7/2011 // --------------------------------------------------------------------------- void gdDebuggedProcessEventsView::focusLastItem() { // Ensure the item is visible: int lastItem = rowCount() - 1; if (lastItem >= 0) { // Get the widget item: QTableWidgetItem* pItem = item(lastItem, 0); if (pItem != NULL) { scrollToItem(pItem, QAbstractItemView::EnsureVisible); } } } // --------------------------------------------------------------------------- // Name: gdDebuggedProcessEventsView::onGDBError // Description: Is called when a GDB Error occurs // Author: <NAME> // Date: 13/1/2009 // --------------------------------------------------------------------------- void gdDebuggedProcessEventsView::onGDBError(const apGDBErrorEvent& gdbErrorEvent) { (void)(gdbErrorEvent); // unused #if ((AMDT_BUILD_TARGET == AMDT_LINUX_OS) && (AMDT_LINUX_VARIANT == AMDT_MAC_OS_X_LINUX_VARIANT)) static gtString sMacArchitectureErrorString = "Architecture of file not recognized."; if (gdbErrorString == sMacArchitectureErrorString) { // The user tried to debug a PowerPC or 64-bit application, so notify them about this: acMessageBox::instance().critical(AF_STR_ErrorA, GD_STR_ErrorMacOSXArchitectureError, QMessageBox::Ok); } #endif } // --------------------------------------------------------------------------- // Name: gdDebuggedProcessEventsView::onBreakpointHit // Description: Is called when the debugged application hits a breakpoint. // Adds a "Breakpoint hit" event to the process events list. // Arguments: breakpointEvent - A class representing the breakpoint hit. // Author: <NAME> // Date: 20/5/2004 // --------------------------------------------------------------------------- void gdDebuggedProcessEventsView::onBreakpointHit(const apBreakpointHitEvent& breakpointEvent) { // Get the break reason: apBreakReason breakReason = breakpointEvent.breakReason(); // On most breakpoints (error types and foreign breakpoints) we don't want // this view to display the event properties in the properties view. // So, to we mark a flag that disables onDebugProcessEventsSelected() to display // the event properties (SetItemState calls indirectly onDebugProcessEventsSelected) if (!((breakReason == AP_OPENGL_ERROR_BREAKPOINT_HIT) || (breakReason == AP_OPENCL_ERROR_BREAKPOINT_HIT) || (breakReason == AP_DETECTED_ERROR_BREAKPOINT_HIT) || (breakReason == AP_SOFTWARE_FALLBACK_BREAKPOINT_HIT) || (breakReason == AP_FOREIGN_BREAK_HIT) || (breakReason == AP_REDUNDANT_STATE_CHANGE_BREAKPOINT_HIT) || (breakReason == AP_DEPRECATED_FUNCTION_BREAKPOINT_HIT) )) { _shouldDisplayEventProperties = false; } else { // Make me the window that receives keyboard input: setFocus(); } // Focus the last item added: focusLastItem(); } // --------------------------------------------------------------------------- // Name: gdDebuggedProcessEventsView::onMemoryLeakBreak // Description: Is called when the debugged application hits a memory leak breakpoint. // Since we already handle memory leak when we get the memory leak event, // we only need to turn it into a breakpoint. // Arguments: breakpointEvent - A class representing the breakpoint hit. // Author: <NAME> // Date: 20/5/2004 // --------------------------------------------------------------------------- void gdDebuggedProcessEventsView::onMemoryLeakBreak(const apBreakpointHitEvent& breakpointEvent) { // Make me the window that receives keyboard input: setFocus(); // Look for the last memory leak event item: int lastMemoryLeakEventIndex = -1; // Get the last event index: int lastEventIndex = rowCount() - 1; for (int i = lastEventIndex; i >= 0; i--) { // Get the item data: QString text; (void) getItemText(i, 0, text); gtString itemText; itemText.fromASCIIString(text.toLatin1().data()); if (itemText.startsWith(AP_STR_MemoryLeakStart)) { // We found the memory leak event item: lastMemoryLeakEventIndex = i; break; } } // If the event was added: GT_IF_WITH_ASSERT_EX((lastMemoryLeakEventIndex >= 0), L"Memory leak breakpoint was raised, but no memory leak event was found") { QTableWidgetItem* pItem = item(lastMemoryLeakEventIndex, 0); if (pItem != NULL) { // Focus the memory leak event item: setItemSelected(pItem, true); scrollToItem(pItem, QAbstractItemView::EnsureVisible); // Get the icon for memory leaks break: int imageIndex = apEventToIconIndex(&breakpointEvent); if ((imageIndex >= 0) && (imageIndex < (int)_listIconsVec.size())) { // Get the pixmap: QPixmap* pPixmap = _listIconsVec[imageIndex]; // Change the memory leak event image index: pItem->setIcon(QIcon(*pPixmap)); } } } } // --------------------------------------------------------------------------- // Name: gdDebuggedProcessEventsView::onSetFocus // Description: Is called when the view get focus // Arguments: event - get the event that triggered the context menu // Author: <NAME> // Date: 29/6/2008 // --------------------------------------------------------------------------- void gdDebuggedProcessEventsView::focusInEvent(QFocusEvent* pEvent) { (void)(pEvent); // unused // Get the currently selected item: if (!selectedItems().isEmpty()) { // Get the first selected item: QTableWidgetItem* pSelected = selectedItems().first(); if (pSelected != NULL) { // Call and process the event: onDebugProcessEventsSelected(pSelected); } } } // --------------------------------------------------------------------------- // Name: gdDebuggedProcessEventsView::onDebugProcessEventsSelected // Description: Write the details of the selected item to the properties view // Arguments: wxListEvent &eve // Author: <NAME> // Date: 3/5/2004 // --------------------------------------------------------------------------- void gdDebuggedProcessEventsView::onDebugProcessEventsSelected(QTableWidgetItem* pSelectedItem) { if (_shouldDisplayEventProperties) { // If we selected more than one item, multipleItemsSelected = true bool multipleItemsSelected = (selectedItems().size() > 1); // Remove the recoding warning: if (multipleItemsSelected) { gdHTMLProperties htmlBuilder; gtString propertiesViewMessage; // Multiple items were selected, show the "Multiple items selected" message: afHTMLContent htmlContent; htmlBuilder.buildMultipleItemPropertiesString(GD_STR_ProcessEventsViewPropertiesTitle, GD_STR_ProcessEventsViewPropertiesDebugProcessEventName, htmlContent); htmlContent.toString(propertiesViewMessage); // Display the HTML message: gdPropertiesEventObserver::instance().setPropertiesFromText(acGTStringToQString(propertiesViewMessage)); } else if (_shouldDisplayEventProperties) { // Id displaying the event properties was not temporarily disabled: gtString itemData; // Clear the properties view gdPropertiesEventObserver::instance().setPropertiesFromText(acGTStringToQString(gdHTMLProperties::emptyHTML())); // We selected only one item, show its properties if (pSelectedItem != NULL) { apEvent* pEvent = (apEvent*)(getItemData(pSelectedItem->row())); afHTMLContent htmlContent; if (pEvent != NULL) { // Get the process creation data: gdGDebuggerGlobalVariablesManager& theStateManager = gdGDebuggerGlobalVariablesManager::instance(); const apDebugProjectSettings& processCreationData = theStateManager.currentDebugProjectSettings(); // Define an HTML builder object: gdHTMLProperties htmlBuilder; afHTMLUtils htmlUtils; // Define an HTML properties string (which is built according to event type): gtString htmlPropertiesString; apEvent::EventType eventType = pEvent->eventType(); switch (eventType) { case apEvent::AP_DEBUGGED_PROCESS_CREATED: { const apDebuggedProcessCreatedEvent& processCreatedEvent = (*(apDebuggedProcessCreatedEvent*)pEvent); htmlUtils.buildProcessCreatedEventPropertiesString(processCreationData, processCreatedEvent, htmlPropertiesString); break; } case apEvent::AP_DEBUGGED_PROCESS_RUN_STARTED: { const apDebuggedProcessRunStartedEvent& processRunStartedEvent = (*(apDebuggedProcessRunStartedEvent*)pEvent); htmlUtils.buildProcessRunStartedEventPropertiesString(processCreationData, processRunStartedEvent, htmlPropertiesString); break; } case apEvent::AP_DEBUGGED_PROCESS_TERMINATED: { const apDebuggedProcessTerminatedEvent& processTerminatedEvent = (*(apDebuggedProcessTerminatedEvent*)pEvent); htmlUtils.buildProcessTerminationEventPropertiesString(processCreationData, processTerminatedEvent, htmlPropertiesString); break; } case apEvent::AP_DEBUGGED_PROCESS_CREATION_FAILURE: { const apDebuggedProcessCreationFailureEvent& event = (*(apDebuggedProcessCreationFailureEvent*)pEvent); htmlBuilder.buildProcessCreationFailureEventPropertiesString(processCreationData, event, htmlContent); break; } case apEvent::AP_MODULE_LOADED: { const apModuleLoadedEvent& event = (*(apModuleLoadedEvent*)pEvent); htmlBuilder.buildDLLLoadPropertiesString(event, htmlContent); break; } case apEvent::AP_MODULE_UNLOADED: { const apModuleUnloadedEvent& event = (*(apModuleUnloadedEvent*)pEvent); htmlBuilder.buildDLLUnloadPropertiesString(event, htmlContent); break; } case apEvent::AP_EXCEPTION: { const apExceptionEvent& event = (*(apExceptionEvent*)pEvent); htmlBuilder.buildExceptionPropertiesString(event, htmlContent); break; } case apEvent::AP_GDB_OUTPUT_STRING: { const apGDBOutputStringEvent& event = (*(apGDBOutputStringEvent*)pEvent); htmlBuilder.buildGDBOutputStringEventPropertiesString(event, htmlContent); break; } case apEvent::AP_GDB_ERROR: { const apGDBErrorEvent& event = (*(apGDBErrorEvent*)pEvent); htmlBuilder.buildGDBErrorPropertiesString(event, htmlContent); break; } case apEvent::AP_BREAKPOINT_HIT: { const apBreakpointHitEvent& breakpointEvent = (*(apBreakpointHitEvent*)pEvent); gtString funcName, funcArgs; bool rc = gdGetCurrentBreakpointFunction(breakpointEvent.breakedOnFunctionCall(), funcName, funcArgs); apExecutionMode currentExecMode = AP_DEBUGGING_MODE; rc = rc && gaGetDebuggedProcessExecutionMode(currentExecMode); if (currentExecMode == AP_PROFILING_MODE) { // Profiling mode funcArgs.makeEmpty(); } htmlBuilder.buildBreakpointPropertiesString(funcName, funcArgs, breakpointEvent, htmlContent); break; } case apEvent::AP_DEBUGGED_PROCESS_OUTPUT_STRING: { const apDebuggedProcessOutputStringEvent& event = (*(apDebuggedProcessOutputStringEvent*)pEvent); htmlBuilder.buildDebuggedProcessOutputStringEventString(event, htmlContent); break; } case apEvent::AP_DETECTED_ERROR_EVENT: { const apDebuggedProcessDetectedErrorEvent& event = (*(apDebuggedProcessDetectedErrorEvent*)pEvent); htmlBuilder.buildErrorEventPropertiesString(event, htmlContent); break; } case apEvent::AP_THREAD_CREATED: { const apThreadCreatedEvent& event = (*(apThreadCreatedEvent*)pEvent); htmlBuilder.buildThreadCreatedEventPropertiesString(event, htmlContent); break; } case apEvent::AP_THREAD_TERMINATED: { const apThreadTerminatedEvent& event = (*(apThreadTerminatedEvent*)pEvent); htmlBuilder.buildThreadTerminatedEventPropertiesString(event, htmlContent); break; } case apEvent::AP_MEMORY_LEAK: { const apMemoryLeakEvent& event = (*(apMemoryLeakEvent*)pEvent); htmlBuilder.buildMemoryLeakEventHTMLPropertiesString(event, false, htmlContent); break; } case apEvent::AP_SEARCHING_FOR_MEMORY_LEAKS: { const apSearchingForMemoryLeaksEvent& event = (*(apSearchingForMemoryLeaksEvent*)pEvent); htmlBuilder.buildSearchingForMemoryLeakEventHTMLPropertiesString(event, htmlContent); break; } case apEvent::AP_API_CONNECTION_ESTABLISHED: { const apApiConnectionEstablishedEvent& event = (*(apApiConnectionEstablishedEvent*)pEvent); htmlBuilder.buildAPIConnectionEstablishedEventProperties(event, htmlContent); break; } case apEvent::AP_OUTPUT_DEBUG_STRING: { const apOutputDebugStringEvent& event = (*(apOutputDebugStringEvent*)pEvent); htmlBuilder.buildOutputDebugStringEventString(event, htmlContent); break; } case apEvent::AP_API_CONNECTION_ENDED: { const apApiConnectionEndedEvent& event = (*(apApiConnectionEndedEvent*)pEvent); htmlBuilder.buildAPIConnectionEndedEventProperties(event, htmlContent); break; } case apEvent::AP_RENDER_CONTEXT_CREATED_EVENT: { const apRenderContextCreatedEvent& event = (*(apRenderContextCreatedEvent*)pEvent); htmlBuilder.buildRenderContextCreatedEventProperties(event, htmlContent); break; } case apEvent::AP_RENDER_CONTEXT_DELETED_EVENT: { const apRenderContextDeletedEvent& event = (*(apRenderContextDeletedEvent*)pEvent); htmlBuilder.buildRenderContextDeletedEventProperties(event, htmlContent); break; } case apEvent::AP_COMPUTE_CONTEXT_CREATED_EVENT: { const apComputeContextCreatedEvent& event = (*(apComputeContextCreatedEvent*)pEvent); htmlBuilder.buildComputeContextCreatedEventProperties(event, htmlContent); break; } case apEvent::AP_COMPUTE_CONTEXT_DELETED_EVENT: { const apComputeContextDeletedEvent& event = (*(apComputeContextDeletedEvent*)pEvent); htmlBuilder.buildComputeContextDeletedEventProperties(event, htmlContent); break; } case apEvent::AP_OPENCL_QUEUE_CREATED_EVENT: { const apOpenCLQueueCreatedEvent& event = (*(apOpenCLQueueCreatedEvent*)pEvent); htmlBuilder.buildOpenCLQueueCreatedEventProperties(event, htmlContent); break; } case apEvent::AP_OPENCL_QUEUE_DELETED_EVENT: { const apOpenCLQueueDeletedEvent& event = (*(apOpenCLQueueDeletedEvent*)pEvent); htmlBuilder.buildOpenCLQueueDeletedEventProperties(event, htmlContent); break; } case apEvent::AP_OPENCL_PROGRAM_CREATED_EVENT: { const apOpenCLProgramCreatedEvent& event = (*(apOpenCLProgramCreatedEvent*)pEvent); htmlBuilder.buildOpenCLProgramCreatedEventProperties(event, htmlContent); break; } case apEvent::AP_OPENCL_PROGRAM_DELETED_EVENT: { const apOpenCLProgramDeletedEvent& event = (*(apOpenCLProgramDeletedEvent*)pEvent); htmlBuilder.buildOpenCLProgramDeletedEventProperties(event, htmlContent); break; } case apEvent::AP_OPENCL_PROGRAM_BUILD_EVENT: { const apOpenCLProgramBuildEvent& event = (*(apOpenCLProgramBuildEvent*)pEvent); htmlBuilder.buildOpenCLProgramBuildEventProperties(event, htmlContent); break; } case apEvent::AP_TECHNOLOGY_MONITOR_FAILURE_EVENT: { const apTechnologyMonitorFailureEvent& event = (*(const apTechnologyMonitorFailureEvent*)pEvent); htmlBuilder.buildTechnologyMonitorFailureEventProperties(event, htmlContent); break; } case apEvent::AP_GL_DEBUG_OUTPUT_MESSAGE: { const apGLDebugOutputMessageEvent& event = (*(apGLDebugOutputMessageEvent*)pEvent); htmlBuilder.buildGLDebugOutputMessageEventProperties(event, htmlContent); break; } case apEvent::AP_OPENCL_ERROR: { const apOpenCLErrorEvent& event = (*(apOpenCLErrorEvent*)pEvent); // Get the function name and arguments strings: gtString funcName, funcArgs; bool rc = gdGetCurrentBreakpointFunction(event.breakedOnFunctionCall(), funcName, funcArgs); // Get the execution mode: apExecutionMode currentExecMode = AP_DEBUGGING_MODE; rc = rc && gaGetDebuggedProcessExecutionMode(currentExecMode); if (currentExecMode == AP_PROFILING_MODE) { // Profiling mode funcArgs.makeEmpty(); } // Build the event string: htmlBuilder.buildCLErrorEventProperties(funcName, funcArgs, event, htmlContent); } default: // Do nothing... break; } // Set the properties text: htmlContent.toString(htmlPropertiesString); gdPropertiesEventObserver::instance().setPropertiesFromText(acGTStringToQString(htmlPropertiesString)); } } } } // Return the flag to its default state: _shouldDisplayEventProperties = true; } // --------------------------------------------------------------------------- // Name: gdDebuggedProcessEventsView::onDebugProcessEventsCurrentItemChanged // Description: Is handling the current item changed signal // Arguments: QTableWidgetItem* pCurrentItem // QTableWidgetItem* pPreviousItem // Author: <NAME> // Date: 18/3/2012 // --------------------------------------------------------------------------- void gdDebuggedProcessEventsView::onDebugProcessEventsCurrentItemChanged(QTableWidgetItem* pCurrentItem, QTableWidgetItem* pPreviousItem) { (void)(pPreviousItem); // unused // Call the selected event: onDebugProcessEventsSelected(pCurrentItem); } // --------------------------------------------------------------------------- // Name: gdDebuggedProcessEventsView::insertListItem // Description: Add the Items to the list and the data to the item data // Arguments: int itemIndex // wxString itemString // int itemImage // apEvent& event // Author: <NAME> // Date: 3/5/2004 // --------------------------------------------------------------------------- void gdDebuggedProcessEventsView::insertListItem(const gtString& itemString, const apEvent& event) { // Add to log: OS_OUTPUT_DEBUG_LOG(itemString.asCharArray(), OS_DEBUG_LOG_INFO); // If any items are selected, de-select them: clearSelection(); // Get the item image index: QPixmap* pItemPixmap = NULL; int imageIndex = apEventToIconIndex(&event); GT_IF_WITH_ASSERT((imageIndex >= 0) && (imageIndex < (int)_listIconsVec.size())) { // Get the pixmap for this item type: pItemPixmap = _listIconsVec[imageIndex]; } QStringList itemStringList; itemStringList << QString::fromWCharArray(itemString.asCharArray()); // Do not change the selection while adding events: blockSignals(true); // Insert the new item to the list apEvent* pEventCopy = event.clone(); addRow(itemStringList, pEventCopy, false, Qt::Unchecked, pItemPixmap); // Ensure the item is visible: focusLastItem(); blockSignals(false); } // --------------------------------------------------------------------------- // Name: gdDebuggedProcessEventsView::checkLoadedModule // Description: Performs sanity checks that should be done after the debugged // process have loaded a new module (dll / shared library). // Arguments: modulePath - The loaded module path. // Author: <NAME> // Date: 14/5/2007 // --------------------------------------------------------------------------- void gdDebuggedProcessEventsView::checkLoadedModule(const gtString& modulePath) { // Transform the module path into a lower case format: gtString modulePathLowerCase = modulePath; modulePathLowerCase.toLowerCase(); // See if interception failed for any API: checkInterceptionFailure(modulePathLowerCase); // Perform OpenGL module related tests: checkLoadedOpenGLModule(modulePathLowerCase); // Perform OpenGL ES module related tests: checkLoadedOpenGLESModule(modulePathLowerCase); } // --------------------------------------------------------------------------- // Name: gdDebuggedProcessEventsView::checkInterceptionFailure // Description: When an API module is loaded, tests to see if the appropriate server // was loaded before it. If it was not, report a warning to the user. // Arguments: modulePathLowerCase - The loaded module path, in lower case format. // Author: <NAME> // Date: 5/4/2015 // --------------------------------------------------------------------------- void gdDebuggedProcessEventsView::checkInterceptionFailure(const gtString& modulePath) { // Show this message once per application run: if (!m_interceptionWarningShown) { static gtString openCLModuleNames[2]; if (openCLModuleNames[0].isEmpty()) { openCLModuleNames[0] = OS_OPENCL_ICD_MODULE_NAME; openCLModuleNames[0].toLowerCase(); openCLModuleNames[1] = OS_OPENCL_ICD_MODULE_ALTERNATIVE_NAME; openCLModuleNames[1].toLowerCase(); } // If this is one of the API dlls: bool isOpenGLModule = (-1 != modulePath.find(OS_OPENGL_MODULE_NAME)); bool isOpenCLModule = ((-1 != modulePath.find(openCLModuleNames[0])) || (-1 != modulePath.find(openCLModuleNames[0]))); if (isOpenGLModule || isOpenCLModule) { // If the module was the server (loaded from the servers folder) bool isCodeXLServerModule = (-1 != modulePath.find(OS_SPIES_SUB_DIR_NAME)); gtString currentProjectExecutableDir; #if AMDT_BUILD_TARGET == AMDT_WINDOWS_OS // Windows also has a spies 64 folder: isCodeXLServerModule = isCodeXLServerModule || (-1 != modulePath.find(OS_SPIES_64_SUB_DIR_NAME)); // We also consider a server in the executable folder, as this is the workaround we suggest for .NET applications: if (!isCodeXLServerModule) { osFilePath currentProjectExecutable = afProjectManager::instance().currentProjectSettings().executablePath(); currentProjectExecutable.clearFileExtension().clearFileName(); currentProjectExecutableDir = currentProjectExecutable.asString(true); currentProjectExecutableDir.toLowerCase(); if (!currentProjectExecutableDir.isEmpty() && modulePath.startsWith(currentProjectExecutableDir)) { isCodeXLServerModule = true; } } #endif // AMDT_BUILD_TARGET == AMDT_WINDOWS_OS apAPIConnectionType connType = AP_AMOUNT_OF_API_CONNECTION_TYPES; if (isOpenCLModule != isOpenGLModule) { if (isOpenCLModule) { connType = AP_OPENCL_API_CONNECTION; } else if (isOpenGLModule) { connType = AP_OPENGL_API_CONNECTION; } else { // Unexpected API type! GT_ASSERT(false); } } else { // This is either both OpenCL and OpenGL (impossible), or neither (not supposed to happen), either way, this should not happen GT_ASSERT(false); } if (isCodeXLServerModule) { // Mark that the module was loaded: m_apiModuleLoaded[connType] = true; } else // !isCodeXLServerModule { // Check if the correct module was already loaded: bool wasLoaded = false; gtMap<apAPIConnectionType, bool>::const_iterator findIter = m_apiModuleLoaded.find(connType); if (m_apiModuleLoaded.end() != findIter) { wasLoaded = m_apiModuleLoaded[connType]; } if (!wasLoaded) { // The teapot sample application loads the OpenCL runtime, specifically, in a way that works around our interception. // In that case, it is expected to fail: osFilePath examplesPath; bool isExample = examplesPath.SetInstallRelatedPath(osFilePath::OS_CODEXL_EXAMPLES_PATH, true); if (isExample) { if (currentProjectExecutableDir.isEmpty()) { osFilePath currentProjectExecutable = afProjectManager::instance().currentProjectSettings().executablePath(); currentProjectExecutable.clearFileExtension().clearFileName(); currentProjectExecutableDir = currentProjectExecutable.asString(true); currentProjectExecutableDir.toLowerCase(); } isExample = currentProjectExecutableDir.startsWith(examplesPath.asString(false)); #if AMDT_BUILD_CONFIGURATION == AMDT_DEBUG_BUILD // For debug mode, any application with the sample name can be considered the sample: isExample = isExample || (-1 != currentProjectExecutableDir.find(OS_STR_CodeXLExmaplesDirName)); #endif } if (!(isExample && isOpenCLModule)) { // Display a warning message to the user: acMessageBox::instance().warning(AF_STR_WarningA, GD_STR_ErrorMessageWarningInterceptionFailure); m_interceptionWarningShown = true; } } } } } } // --------------------------------------------------------------------------- // Name: gdDebuggedProcessEventsView::checkLoadedOpenGLModule // Description: Performs sanity checks that should be done after the debugged // process have loaded an OpenGL module. // Arguments: modulePathLowerCase - The loaded module path, in lower case format. // Author: <NAME> // Date: 14/5/2007 // --------------------------------------------------------------------------- void gdDebuggedProcessEventsView::checkLoadedOpenGLModule(const gtString& modulePathLowerCase) { // If our OpenGL / ES server was not loaded yet: if (!_wasGremedyOGLServerLoaded && !_wasGremedyOGLESServerLoaded) { // If the loaded module is an OpenGL module: if (modulePathLowerCase.find(OS_OPENGL_MODULE_NAME) != -1) { // If the OpenGL server was loaded in a project type that does not support OpenGL/ES, show a message to the user. // Uri, 22/3/10: The other case is currently not "else", since we don't separate Windows and Linux (LD_LIBRARY_PATH interception) // spies, so the OpenCL-only projects would still load the OpenGL spy in this case. If the "else" is uncommented, this message // appears twice in these cases, once for our spy and once for the real OpenGL, loaded by our spy. Also, this message entirely // ignores licensing, does not allow a "don't show me again" feature, etc. // Yaki - 13/12/2010 // From ~ Catalyst 10.8 and until 10.11 at least, AMD's atiocl.dll loads opengl32.dll. This causes us to tell the user that he uses OpenGL in an OpenCL only project // (but he doesn't!), So, until atiocl.dll is fixed, I commented out the below printout: /* if (!apDoesProjectTypeSupportOpenGLOrOpenGLES(currentProjectType)) { acMessageBox::instance().warning(GD_STR_WarningA, GD_STR_ErrorMessageWarningOpenGLServerInOpenCLOnlyProject, QMessageBox::Ok); } else // apDoesProjectTypeSupportOpenGLOrOpenGLES(currentProjectType) */ { // If this is the Windows system's OpenGL module: bool isWinOGLSystemModule = isWindowsSystemOGLModule(modulePathLowerCase); if (!isWinOGLSystemModule) { // We assume that this module is our OpenGL server: _wasGremedyOGLServerLoaded = true; } } } } } // --------------------------------------------------------------------------- // Name: gdDebuggedProcessEventsView::checkLoadedOpenGLESModule // Description: Performs sanity checks that should be done after the debugged // process have loaded an OpenGL ES module. // Arguments: modulePathLowerCase - The loaded module path, in lower case format. // Author: <NAME> // Date: 14/5/2007 // --------------------------------------------------------------------------- void gdDebuggedProcessEventsView::checkLoadedOpenGLESModule(const gtString& modulePathLowerCase) { // Check if the first loaded libgles_cm.dll/libgles_cl.dll is our spy. if ((modulePathLowerCase.find(OS_OPENGL_ES_COMMON_DLL_NAME) != -1) || (modulePathLowerCase.find(OS_OPENGL_ES_COMMON_LITE_DLL_NAME) != -1)) { // Get the current project type: // gdGDebuggerGlobalVariablesManager& globalVarsManager = gdGDebuggerGlobalVariablesManager::instance(); // If we are not in an OpenGL ES project: // Handle the situation in which an OpenGL ES module is loaded while in OpenGL project type: _wasGremedyOGLESServerLoaded = true; handleESModuleWhileInOGLProject(); } } // --------------------------------------------------------------------------- // Name: gdDebuggedProcessEventsView::isGremedyOGLESServer // Description: Inputs an OpenGL ES module path and returns true iff this is // gremedy's OpenGL ES server. // Author: <NAME> // Date: 14/5/2007 // --------------------------------------------------------------------------- bool gdDebuggedProcessEventsView::isGremedyOGLESServer(const gtString& modulePathLowerCase) { bool retVal = false; // Get the OpenGL ES implementation directory: gdGDebuggerGlobalVariablesManager& globalVarsManager = gdGDebuggerGlobalVariablesManager::instance(); const osFilePath& oglESDLLsDirectory = globalVarsManager.getOpenGLESDLLsDirectory(); const gtString& oglESDLLsDirectoryAsStr = oglESDLLsDirectory.asString(); if (!oglESDLLsDirectoryAsStr.isEmpty()) { // Get it's last path separator position: int lastPathSaperatorPos = oglESDLLsDirectoryAsStr.reverseFind(osFilePath::osPathSeparator); if (lastPathSaperatorPos != -1) { // Get the ES implementation directory path last directory name: gtString esImplementationDirName; oglESDLLsDirectoryAsStr.getSubString(lastPathSaperatorPos, oglESDLLsDirectoryAsStr.length(), esImplementationDirName); if (!esImplementationDirName.isEmpty()) { // If the input module path contains the ES implementation directory path last dir name: esImplementationDirName.toLowerCase(); if (modulePathLowerCase.find(esImplementationDirName) != -1) { retVal = true; } } } } return retVal; } // --------------------------------------------------------------------------- // Name: gdDebuggedProcessEventsView::isWindowsSystemOGLModule // Description: Inputs an OpenGL module path and returns true iff this is // Windows OpenGL system module. // Author: <NAME> // Date: 14/5/2007 // --------------------------------------------------------------------------- bool gdDebuggedProcessEventsView::isWindowsSystemOGLModule(const gtString& modulePathLowerCase) { bool retVal = false; #if AMDT_BUILD_TARGET == AMDT_WINDOWS_OS retVal = (modulePathLowerCase.find(L"system") != -1); #else (void)(modulePathLowerCase); // Resolve the compiler warning for the Linux variant #endif return retVal; } // --------------------------------------------------------------------------- // Name: gdDebuggedProcessEventsView::handleForeignOpenGLESImplementation // Description: Handles the case in which the debugged process loaded an OpenGL ES // implementation, but it is not the gremedy implementation. // Author: <NAME> // Date: 14/5/2007 // --------------------------------------------------------------------------- void gdDebuggedProcessEventsView::handleForeignOpenGLESImplementation(const gtString& modulePathLowerCase) { // Stop the debugged process: gdStopDebuggingCommand stopDebuggingCmd; bool rc = stopDebuggingCmd.execute(); GT_ASSERT(rc); // Display a message box: QString errorModule = acGTStringToQString(modulePathLowerCase); QString errorMessage = QString(GD_STR_ErrorMessageFailedToLoadTheESSpy).arg(errorModule).arg(errorModule); acMessageBox::instance().critical(AF_STR_ErrorA, errorMessage, QMessageBox::Ok); } // --------------------------------------------------------------------------- // Name: gdDebuggedProcessEventsView::handleESModuleWhileInOGLProject // Description: Handles the case in which an OpenGL ES module is loaded while // in OpenGL project type. // Author: <NAME> // Date: 14/5/2007 // --------------------------------------------------------------------------- void gdDebuggedProcessEventsView::handleESModuleWhileInOGLProject() { // Output the message into the log file: OS_OUTPUT_DEBUG_LOG(GD_STR_ErrorMessageLoadTheWrongSpyOpenGLESCommonUnicode, OS_DEBUG_LOG_INFO); // Stop the debugged process: gdStopDebuggingCommand stopDebuggingCmd; bool rc = stopDebuggingCmd.execute(); GT_ASSERT(rc); // Display an Error message: acMessageBox::instance().critical(AF_STR_ErrorA, GD_STR_ErrorMessageLoadTheWrongSpyOpenGLESCommon, QMessageBox::Ok); // Get the application commands instance: afApplicationCommands* pApplicationCommands = afApplicationCommands::instance(); GT_IF_WITH_ASSERT(pApplicationCommands != NULL) { // Open the debug settings dialog: pApplicationCommands->OnProjectSettings(); } } // --------------------------------------------------------------------------- // Name: gdDebuggedProcessEventsView::handleOGLModuleWhileInESProject // Description: Handles the case in which our OpenGL server is loaded while // in OpenGL ES project type before the OpenGL ES server is loaded. // Author: <NAME> // Date: 14/5/2007 // --------------------------------------------------------------------------- void gdDebuggedProcessEventsView::handleOGLModuleWhileInESProject() { // Stop the debugged process: gdStopDebuggingCommand stopDebuggingCmd; bool rc = stopDebuggingCmd.execute(); GT_ASSERT(rc); // Output the message into the log file: OS_OUTPUT_DEBUG_LOG(GD_STR_ErrorMessageLoadTheWrongSpyOpenGL32Unicode, OS_DEBUG_LOG_INFO); // Load an Error message: acMessageBox::instance().critical(AF_STR_ErrorA, GD_STR_ErrorMessageLoadTheWrongSpyOpenGL32, QMessageBox::Ok); // Get the application commands instance: afApplicationCommands* pApplicationCommands = afApplicationCommands::instance(); GT_IF_WITH_ASSERT(pApplicationCommands != NULL) { // Open the debug settings dialog: pApplicationCommands->OnProjectSettings(); } } // --------------------------------------------------------------------------- // Name: gdDebuggedProcessEventsView::apEventToIconIndex // Description: Return an icon index for the requested event object // Arguments: apEvent* pEvent // Return Val: int // Author: <NAME> // Date: 21/2/2010 // --------------------------------------------------------------------------- int gdDebuggedProcessEventsView::apEventToIconIndex(const apEvent* pEvent) { int retVal = -1; GT_IF_WITH_ASSERT(pEvent != NULL) { // Get the event type: apEvent::EventType eventType = pEvent->eventType(); // Try to get the icon index from the mapping: gtMap<apEvent::EventType, int>::const_iterator iter = _eventTypeToIconIndexMap.find(eventType); if (iter != _eventTypeToIconIndexMap.end()) { // For most of the events, the icon is simply the mapping: retVal = (*iter).second; // Breakpoint event can have few icons: if (eventType == apEvent::AP_BREAKPOINT_HIT) { apBreakpointHitEvent* pBreakpointHitEvent = (apBreakpointHitEvent*)pEvent; GT_IF_WITH_ASSERT(pBreakpointHitEvent != NULL) { switch (pBreakpointHitEvent->breakReason()) { case AP_BREAK_COMMAND_HIT: // Do nothing, this is the icon mapped: break; case AP_NEXT_MONITORED_FUNCTION_BREAKPOINT_HIT: // TO_DO: choose icons for step over and in. case AP_STEP_IN_BREAKPOINT_HIT: case AP_STEP_OVER_BREAKPOINT_HIT: case AP_STEP_OUT_BREAKPOINT_HIT: retVal++; // Step: break; case AP_DRAW_MONITORED_FUNCTION_BREAKPOINT_HIT: retVal += 2; // Draw: break; case AP_FRAME_BREAKPOINT_HIT: retVal += 3; // FrameStep: break; case AP_MONITORED_FUNCTION_BREAKPOINT_HIT: case AP_KERNEL_SOURCE_CODE_BREAKPOINT_HIT: case AP_KERNEL_FUNCTION_NAME_BREAKPOINT_HIT: case AP_HOST_BREAKPOINT_HIT: retVal += 4; // Breakpoint: break; case AP_OPENGL_ERROR_BREAKPOINT_HIT: retVal += 5; // BreakOnOpenGLError: break; case AP_REDUNDANT_STATE_CHANGE_BREAKPOINT_HIT: retVal += 6; // BreakOnRedundant: break; case AP_DEPRECATED_FUNCTION_BREAKPOINT_HIT: retVal += 7; // BreakOnDeprecated: break; case AP_SOFTWARE_FALLBACK_BREAKPOINT_HIT: retVal += 8; // BreakOnSoftwareFallback: break; case AP_FOREIGN_BREAK_HIT: retVal += 9; // ForeignBreak: break; case AP_MEMORY_LEAK_BREAKPOINT_HIT: retVal += 10; // BreakOnMemoryLeak: break; default: { GT_ASSERT_EX(false, L"Unknown breakpoint type"); break; } } } } else if (eventType == apEvent::AP_MEMORY_LEAK) { apMemoryLeakEvent* pMemoryLeakEvent = (apMemoryLeakEvent*)pEvent; GT_IF_WITH_ASSERT(pMemoryLeakEvent != NULL) { if (!pMemoryLeakEvent->memoryLeakExists()) { // Try to get the icon index from the mapping: gtMap<apEvent::EventType, int>::const_iterator iterEvents = _eventTypeToIconIndexMap.find(apEvent::AP_SEARCHING_FOR_MEMORY_LEAKS); if (iterEvents != _eventTypeToIconIndexMap.end()) { // For most of the events, the icon is simply the mapping: retVal = (*iterEvents).second; } } } } else if (eventType == apEvent::AP_DETECTED_ERROR_EVENT) { bool breakOnDetectedError = false; // Down cast the event to a detected error event: apDebuggedProcessDetectedErrorEvent* pDetectedErrorEvent = (apDebuggedProcessDetectedErrorEvent*)pEvent; GT_IF_WITH_ASSERT(pDetectedErrorEvent != NULL) { breakOnDetectedError = pDetectedErrorEvent->wasGeneratedByBreak(); } if (breakOnDetectedError) { retVal ++; } } else if (pEvent->eventType() == apEvent::AP_OPENCL_ERROR) { bool breakOnOpenCLErrors = false; // Down cast the event to a detected error event: apOpenCLErrorEvent* pOpenCLErrorEvent = (apOpenCLErrorEvent*)pEvent; GT_IF_WITH_ASSERT(pOpenCLErrorEvent != NULL) { breakOnOpenCLErrors = pOpenCLErrorEvent->wasGeneratedByBreak(); } if (breakOnOpenCLErrors) { retVal ++; } } } else // iter == _eventTypeToIconIndexMap.end() { gtString errMsg; errMsg.appendFormattedString(L"Added an event of type %d to list, without icon assigned for this type.", eventType); GT_ASSERT_EX(false, errMsg.asCharArray()); } } return retVal; } // --------------------------------------------------------------------------- // Name: gdDebuggedProcessEventsView::getLastEventOfType // Description: Return the last event of the given type // Arguments: apEvent::EventType eventType // Return Val: apEvent* // Author: <NAME> // Date: 20/7/2010 // --------------------------------------------------------------------------- apEvent* gdDebuggedProcessEventsView::getLastEventOfType(apEvent::EventType eventType) { apEvent* pRetVal = NULL; // Go through the event items, and search for the first event with the requested type: int lastItemIndex = rowCount() - 1; for (int i = lastItemIndex ; i >= 0; i--) { // Get the current item data: apEvent* pCurrentEvent = (apEvent*)(getItemData(i)); if (pCurrentEvent != NULL) { // If the current event has the requested type: if (pCurrentEvent->eventType() == eventType) { pRetVal = pCurrentEvent; break; } } } return pRetVal; } /// ----------------------------------------------------------------------------------------------- /// \brief Name: onExecutionModeChangedEvent /// \brief Description: Is handling CodeXL execution mode change /// \param[in] execChangedEvent /// \return void /// ----------------------------------------------------------------------------------------------- void gdDebuggedProcessEventsView::onExecutionModeChangedEvent(const apEvent& execChangedEvent) { bool isEnabled = false; bool modeChanged = gdDoesModeChangeApplyToDebuggerViews(execChangedEvent, isEnabled); if (modeChanged) { if (!isEnabled) { clearView(); } setEnabled(isEnabled); } } void gdDebuggedProcessEventsView::onAboutToShowContextMenu() { // Call the base class implementation: acListCtrl::onAboutToShowContextMenu(); GT_IF_WITH_ASSERT(m_pClearViewAction != NULL) { // Enable is there are items shown: m_pClearViewAction->setEnabled(rowCount() > 1); } } void gdDebuggedProcessEventsView::extendContextMenu() { // Sanity check: GT_IF_WITH_ASSERT(m_pContextMenu != NULL) { // Add a separator: m_pContextMenu->insertSeparator(m_pContextMenu->actions().first()); // Add "Clear View" action: m_pClearViewAction = new QAction(GD_STR_ProcessEventsViewClear, m_pContextMenu); // Insert the action to the menu, at position 0: m_pContextMenu->insertAction(m_pContextMenu->actions().first(), m_pClearViewAction); // Connect the action to the slot: bool rc = connect(m_pClearViewAction, SIGNAL(triggered()), this, SLOT(clearView())); GT_ASSERT(rc); } }
33,647
713
<filename>server/memcached/src/test/java/org/infinispan/server/memcached/MemcachedDistributionTest.java package org.infinispan.server.memcached; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.stream.Collectors; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.distribution.DistributionTestHelper; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; import net.spy.memcached.MemcachedClient; import net.spy.memcached.internal.OperationFuture; /** * Tests distributed mode with Memcached servers. * * @author <NAME> * @since 6.0 */ @Test(groups = "functional", testName = "server.memcached.MemcachedDistributionTest") public class MemcachedDistributionTest extends MemcachedMultiNodeTest { public EmbeddedCacheManager createCacheManager(int index) { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.clustering().cacheMode(CacheMode.DIST_SYNC).hash().numOwners(1); return TestCacheManagerFactory.createClusteredCacheManager( GlobalConfigurationBuilder.defaultClusteredBuilder().defaultCacheName(cacheName), builder); } public void testGetFromNonOwner() throws InterruptedException, ExecutionException, TimeoutException { MemcachedClient owner = getFirstOwner("1"); OperationFuture<Boolean> f = owner.set("1", 0, "v1"); assertTrue(f.get(timeout, TimeUnit.SECONDS)); MemcachedClient nonOwner = getFirstNonOwner("1"); assertEquals(nonOwner.get("1"), "v1"); } private MemcachedClient getFirstNonOwner(String k) { return getCacheThat(k, false); } private MemcachedClient getFirstOwner(String k) { return getCacheThat(k, true); } private MemcachedClient getCacheThat(String k, Boolean owner) { List<Cache<String, byte[]>> caches = servers.stream().map(s -> { Cache<String, byte[]> cache = s.getCacheManager().getCache(cacheName); return cache; }).collect(Collectors.toList()); Cache<String, byte[]> cache; if (owner) { cache = DistributionTestHelper.getFirstOwner(k, caches); } else { cache = DistributionTestHelper.getFirstNonOwner(k, caches); } return cacheClient.get(cache); } }
912
451
// File Automatically generated by eLiSe #include "general/all.h" #include "private/all.h" #include "cEqCoplanNoDistId.h" cEqCoplanNoDistId::cEqCoplanNoDistId(): cElCompiledFonc(1) { AddIntRef (cIncIntervale("Intr1",0,3)); AddIntRef (cIncIntervale("Or1",3,9)); AddIntRef (cIncIntervale("Or2",9,15)); Close(false); } void cEqCoplanNoDistId::ComputeVal() { double tmp0_ = mCompCoord[3]; double tmp1_ = sin(tmp0_); double tmp2_ = mCompCoord[4]; double tmp3_ = mCompCoord[5]; double tmp4_ = mCompCoord[0]; double tmp5_ = cos(tmp0_); double tmp6_ = sin(tmp3_); double tmp7_ = sin(tmp2_); double tmp8_ = -(tmp7_); double tmp9_ = tmp1_*tmp8_; double tmp10_ = cos(tmp3_); double tmp11_ = mCompCoord[1]; double tmp12_ = mCompCoord[10]; double tmp13_ = mCompCoord[2]; double tmp14_ = cos(tmp12_); double tmp15_ = mCompCoord[11]; double tmp16_ = mLocXL1-tmp11_; double tmp17_ = (tmp16_)/tmp4_; double tmp18_ = cos(tmp2_); double tmp19_ = mLocYL1-tmp13_; double tmp20_ = (tmp19_)/tmp4_; double tmp21_ = mLocXL2-tmp11_; double tmp22_ = (tmp21_)/tmp4_; double tmp23_ = mCompCoord[9]; double tmp24_ = cos(tmp15_); double tmp25_ = sin(tmp23_); double tmp26_ = sin(tmp12_); double tmp27_ = sin(tmp15_); double tmp28_ = mLocYL2-tmp13_; double tmp29_ = (tmp28_)/tmp4_; double tmp30_ = cos(tmp23_); double tmp31_ = -(tmp26_); double tmp32_ = tmp25_*tmp31_; double tmp33_ = tmp7_*(tmp17_); double tmp34_ = tmp18_*tmp6_; double tmp35_ = tmp34_*(tmp20_); double tmp36_ = tmp33_+tmp35_; double tmp37_ = tmp18_*tmp10_; double tmp38_ = tmp36_+tmp37_; double tmp39_ = -(tmp25_); double tmp40_ = -(tmp27_); double tmp41_ = tmp30_*tmp31_; double tmp42_ = -(tmp1_); double tmp43_ = -(tmp6_); double tmp44_ = tmp5_*tmp8_; double tmp45_ = tmp26_*(tmp22_); double tmp46_ = tmp14_*tmp27_; double tmp47_ = tmp46_*(tmp29_); double tmp48_ = tmp45_+tmp47_; double tmp49_ = tmp14_*tmp24_; double tmp50_ = tmp48_+tmp49_; double tmp51_ = tmp5_*tmp18_; double tmp52_ = tmp51_*(tmp17_); double tmp53_ = tmp42_*tmp10_; double tmp54_ = tmp44_*tmp6_; double tmp55_ = tmp53_+tmp54_; double tmp56_ = (tmp55_)*(tmp20_); double tmp57_ = tmp52_+tmp56_; double tmp58_ = tmp42_*tmp43_; double tmp59_ = tmp44_*tmp10_; double tmp60_ = tmp58_+tmp59_; double tmp61_ = tmp57_+tmp60_; double tmp62_ = tmp25_*tmp14_; double tmp63_ = tmp62_*(tmp22_); double tmp64_ = tmp30_*tmp24_; double tmp65_ = tmp32_*tmp27_; double tmp66_ = tmp64_+tmp65_; double tmp67_ = (tmp66_)*(tmp29_); double tmp68_ = tmp63_+tmp67_; double tmp69_ = tmp30_*tmp40_; double tmp70_ = tmp32_*tmp24_; double tmp71_ = tmp69_+tmp70_; double tmp72_ = tmp68_+tmp71_; double tmp73_ = tmp1_*tmp18_; double tmp74_ = tmp73_*(tmp17_); double tmp75_ = tmp5_*tmp10_; double tmp76_ = tmp9_*tmp6_; double tmp77_ = tmp75_+tmp76_; double tmp78_ = (tmp77_)*(tmp20_); double tmp79_ = tmp74_+tmp78_; double tmp80_ = tmp5_*tmp43_; double tmp81_ = tmp9_*tmp10_; double tmp82_ = tmp80_+tmp81_; double tmp83_ = tmp79_+tmp82_; double tmp84_ = tmp30_*tmp14_; double tmp85_ = tmp84_*(tmp22_); double tmp86_ = tmp39_*tmp24_; double tmp87_ = tmp41_*tmp27_; double tmp88_ = tmp86_+tmp87_; double tmp89_ = (tmp88_)*(tmp29_); double tmp90_ = tmp85_+tmp89_; double tmp91_ = tmp39_*tmp40_; double tmp92_ = tmp41_*tmp24_; double tmp93_ = tmp91_+tmp92_; double tmp94_ = tmp90_+tmp93_; double tmp95_ = mCompCoord[12]; double tmp96_ = mCompCoord[6]; double tmp97_ = tmp95_-tmp96_; double tmp98_ = mCompCoord[13]; double tmp99_ = mCompCoord[7]; double tmp100_ = tmp98_-tmp99_; double tmp101_ = mCompCoord[14]; double tmp102_ = mCompCoord[8]; double tmp103_ = tmp101_-tmp102_; mVal[0] = (((tmp83_)*(tmp50_)-(tmp38_)*(tmp72_))*(tmp97_)+((tmp38_)*(tmp94_)-(tmp61_)*(tmp50_))*(tmp100_)+((tmp61_)*(tmp72_)-(tmp83_)*(tmp94_))*(tmp103_))/sqrt((tmp97_)*(tmp97_)+(tmp100_)*(tmp100_)+(tmp103_)*(tmp103_)); } void cEqCoplanNoDistId::ComputeValDeriv() { double tmp0_ = mCompCoord[3]; double tmp1_ = sin(tmp0_); double tmp2_ = mCompCoord[4]; double tmp3_ = mCompCoord[5]; double tmp4_ = mCompCoord[0]; double tmp5_ = cos(tmp0_); double tmp6_ = sin(tmp3_); double tmp7_ = sin(tmp2_); double tmp8_ = -(tmp7_); double tmp9_ = tmp1_*tmp8_; double tmp10_ = cos(tmp3_); double tmp11_ = mCompCoord[1]; double tmp12_ = mCompCoord[10]; double tmp13_ = mCompCoord[2]; double tmp14_ = cos(tmp12_); double tmp15_ = mCompCoord[11]; double tmp16_ = mLocXL1-tmp11_; double tmp17_ = (tmp16_)/tmp4_; double tmp18_ = cos(tmp2_); double tmp19_ = mLocYL1-tmp13_; double tmp20_ = (tmp19_)/tmp4_; double tmp21_ = mLocXL2-tmp11_; double tmp22_ = (tmp21_)/tmp4_; double tmp23_ = mCompCoord[9]; double tmp24_ = cos(tmp15_); double tmp25_ = sin(tmp23_); double tmp26_ = sin(tmp12_); double tmp27_ = sin(tmp15_); double tmp28_ = mLocYL2-tmp13_; double tmp29_ = (tmp28_)/tmp4_; double tmp30_ = cos(tmp23_); double tmp31_ = -(tmp26_); double tmp32_ = tmp25_*tmp31_; double tmp33_ = tmp7_*(tmp17_); double tmp34_ = tmp18_*tmp6_; double tmp35_ = tmp34_*(tmp20_); double tmp36_ = tmp33_+tmp35_; double tmp37_ = tmp18_*tmp10_; double tmp38_ = tmp36_+tmp37_; double tmp39_ = -(tmp25_); double tmp40_ = -(tmp27_); double tmp41_ = tmp30_*tmp31_; double tmp42_ = -(tmp1_); double tmp43_ = -(tmp6_); double tmp44_ = tmp5_*tmp8_; double tmp45_ = tmp26_*(tmp22_); double tmp46_ = tmp14_*tmp27_; double tmp47_ = tmp46_*(tmp29_); double tmp48_ = tmp45_+tmp47_; double tmp49_ = tmp14_*tmp24_; double tmp50_ = tmp48_+tmp49_; double tmp51_ = tmp5_*tmp18_; double tmp52_ = tmp51_*(tmp17_); double tmp53_ = tmp42_*tmp10_; double tmp54_ = tmp44_*tmp6_; double tmp55_ = tmp53_+tmp54_; double tmp56_ = (tmp55_)*(tmp20_); double tmp57_ = tmp52_+tmp56_; double tmp58_ = tmp42_*tmp43_; double tmp59_ = tmp44_*tmp10_; double tmp60_ = tmp58_+tmp59_; double tmp61_ = tmp57_+tmp60_; double tmp62_ = tmp25_*tmp14_; double tmp63_ = tmp62_*(tmp22_); double tmp64_ = tmp30_*tmp24_; double tmp65_ = tmp32_*tmp27_; double tmp66_ = tmp64_+tmp65_; double tmp67_ = (tmp66_)*(tmp29_); double tmp68_ = tmp63_+tmp67_; double tmp69_ = tmp30_*tmp40_; double tmp70_ = tmp32_*tmp24_; double tmp71_ = tmp69_+tmp70_; double tmp72_ = tmp68_+tmp71_; double tmp73_ = tmp1_*tmp18_; double tmp74_ = tmp73_*(tmp17_); double tmp75_ = tmp5_*tmp10_; double tmp76_ = tmp9_*tmp6_; double tmp77_ = tmp75_+tmp76_; double tmp78_ = (tmp77_)*(tmp20_); double tmp79_ = tmp74_+tmp78_; double tmp80_ = tmp5_*tmp43_; double tmp81_ = tmp9_*tmp10_; double tmp82_ = tmp80_+tmp81_; double tmp83_ = tmp79_+tmp82_; double tmp84_ = tmp30_*tmp14_; double tmp85_ = tmp84_*(tmp22_); double tmp86_ = tmp39_*tmp24_; double tmp87_ = tmp41_*tmp27_; double tmp88_ = tmp86_+tmp87_; double tmp89_ = (tmp88_)*(tmp29_); double tmp90_ = tmp85_+tmp89_; double tmp91_ = tmp39_*tmp40_; double tmp92_ = tmp41_*tmp24_; double tmp93_ = tmp91_+tmp92_; double tmp94_ = tmp90_+tmp93_; double tmp95_ = mCompCoord[12]; double tmp96_ = mCompCoord[6]; double tmp97_ = tmp95_-tmp96_; double tmp98_ = mCompCoord[13]; double tmp99_ = mCompCoord[7]; double tmp100_ = tmp98_-tmp99_; double tmp101_ = mCompCoord[14]; double tmp102_ = mCompCoord[8]; double tmp103_ = tmp101_-tmp102_; double tmp104_ = ElSquare(tmp4_); double tmp105_ = -(tmp16_); double tmp106_ = tmp105_/tmp104_; double tmp107_ = -(tmp19_); double tmp108_ = tmp107_/tmp104_; double tmp109_ = -(tmp21_); double tmp110_ = tmp109_/tmp104_; double tmp111_ = -(tmp28_); double tmp112_ = tmp111_/tmp104_; double tmp113_ = (tmp106_)*tmp7_; double tmp114_ = (tmp108_)*tmp34_; double tmp115_ = tmp113_+tmp114_; double tmp116_ = (tmp110_)*tmp26_; double tmp117_ = (tmp112_)*tmp46_; double tmp118_ = tmp116_+tmp117_; double tmp119_ = (tmp106_)*tmp51_; double tmp120_ = (tmp108_)*(tmp55_); double tmp121_ = tmp119_+tmp120_; double tmp122_ = (tmp110_)*tmp62_; double tmp123_ = (tmp112_)*(tmp66_); double tmp124_ = tmp122_+tmp123_; double tmp125_ = (tmp106_)*tmp73_; double tmp126_ = (tmp108_)*(tmp77_); double tmp127_ = tmp125_+tmp126_; double tmp128_ = (tmp110_)*tmp84_; double tmp129_ = (tmp112_)*(tmp88_); double tmp130_ = tmp128_+tmp129_; double tmp131_ = (tmp97_)*(tmp97_); double tmp132_ = (tmp100_)*(tmp100_); double tmp133_ = tmp131_+tmp132_; double tmp134_ = (tmp103_)*(tmp103_); double tmp135_ = tmp133_+tmp134_; double tmp136_ = sqrt(tmp135_); double tmp137_ = -(1); double tmp138_ = tmp137_*tmp4_; double tmp139_ = (tmp138_)/tmp104_; double tmp140_ = (tmp139_)*tmp7_; double tmp141_ = (tmp139_)*tmp26_; double tmp142_ = (tmp139_)*tmp51_; double tmp143_ = (tmp139_)*tmp62_; double tmp144_ = (tmp139_)*tmp73_; double tmp145_ = (tmp139_)*tmp84_; double tmp146_ = ElSquare(tmp136_); double tmp147_ = (tmp139_)*tmp34_; double tmp148_ = (tmp139_)*tmp46_; double tmp149_ = (tmp139_)*(tmp55_); double tmp150_ = (tmp139_)*(tmp66_); double tmp151_ = (tmp139_)*(tmp77_); double tmp152_ = (tmp139_)*(tmp88_); double tmp153_ = tmp137_*tmp1_; double tmp154_ = -(tmp5_); double tmp155_ = tmp153_*tmp8_; double tmp156_ = tmp153_*tmp18_; double tmp157_ = tmp156_*(tmp17_); double tmp158_ = tmp154_*tmp10_; double tmp159_ = tmp155_*tmp6_; double tmp160_ = tmp158_+tmp159_; double tmp161_ = (tmp160_)*(tmp20_); double tmp162_ = tmp157_+tmp161_; double tmp163_ = tmp154_*tmp43_; double tmp164_ = tmp155_*tmp10_; double tmp165_ = tmp163_+tmp164_; double tmp166_ = tmp162_+tmp165_; double tmp167_ = tmp153_*tmp10_; double tmp168_ = tmp167_+tmp54_; double tmp169_ = (tmp168_)*(tmp20_); double tmp170_ = tmp52_+tmp169_; double tmp171_ = tmp153_*tmp43_; double tmp172_ = tmp171_+tmp59_; double tmp173_ = tmp170_+tmp172_; double tmp174_ = -(tmp18_); double tmp175_ = tmp174_*tmp1_; double tmp176_ = tmp137_*tmp7_; double tmp177_ = tmp18_*(tmp17_); double tmp178_ = tmp176_*tmp6_; double tmp179_ = tmp178_*(tmp20_); double tmp180_ = tmp177_+tmp179_; double tmp181_ = tmp176_*tmp10_; double tmp182_ = tmp180_+tmp181_; double tmp183_ = tmp174_*tmp5_; double tmp184_ = tmp176_*tmp5_; double tmp185_ = tmp184_*(tmp17_); double tmp186_ = tmp183_*tmp6_; double tmp187_ = tmp186_*(tmp20_); double tmp188_ = tmp185_+tmp187_; double tmp189_ = tmp183_*tmp10_; double tmp190_ = tmp188_+tmp189_; double tmp191_ = tmp176_*tmp1_; double tmp192_ = tmp191_*(tmp17_); double tmp193_ = tmp175_*tmp6_; double tmp194_ = tmp193_*(tmp20_); double tmp195_ = tmp192_+tmp194_; double tmp196_ = tmp175_*tmp10_; double tmp197_ = tmp195_+tmp196_; double tmp198_ = tmp137_*tmp6_; double tmp199_ = tmp10_*tmp18_; double tmp200_ = tmp199_*(tmp20_); double tmp201_ = tmp198_*tmp18_; double tmp202_ = tmp200_+tmp201_; double tmp203_ = -(tmp10_); double tmp204_ = tmp198_*tmp42_; double tmp205_ = tmp10_*tmp44_; double tmp206_ = tmp204_+tmp205_; double tmp207_ = (tmp206_)*(tmp20_); double tmp208_ = tmp203_*tmp42_; double tmp209_ = tmp198_*tmp44_; double tmp210_ = tmp208_+tmp209_; double tmp211_ = tmp207_+tmp210_; double tmp212_ = tmp198_*tmp5_; double tmp213_ = tmp10_*tmp9_; double tmp214_ = tmp212_+tmp213_; double tmp215_ = (tmp214_)*(tmp20_); double tmp216_ = tmp203_*tmp5_; double tmp217_ = tmp198_*tmp9_; double tmp218_ = tmp216_+tmp217_; double tmp219_ = tmp215_+tmp218_; double tmp220_ = (tmp83_)*(tmp50_); double tmp221_ = (tmp38_)*(tmp72_); double tmp222_ = tmp220_-tmp221_; double tmp223_ = (tmp222_)*(tmp97_); double tmp224_ = (tmp38_)*(tmp94_); double tmp225_ = (tmp61_)*(tmp50_); double tmp226_ = tmp224_-tmp225_; double tmp227_ = (tmp226_)*(tmp100_); double tmp228_ = tmp223_+tmp227_; double tmp229_ = (tmp61_)*(tmp72_); double tmp230_ = (tmp83_)*(tmp94_); double tmp231_ = tmp229_-tmp230_; double tmp232_ = (tmp231_)*(tmp103_); double tmp233_ = tmp228_+tmp232_; double tmp234_ = tmp137_*(tmp97_); double tmp235_ = tmp137_*(tmp100_); double tmp236_ = tmp137_*(tmp103_); double tmp237_ = tmp137_*tmp25_; double tmp238_ = -(tmp30_); double tmp239_ = tmp237_*tmp31_; double tmp240_ = tmp237_*tmp24_; double tmp241_ = tmp240_+tmp87_; double tmp242_ = (tmp241_)*(tmp29_); double tmp243_ = tmp85_+tmp242_; double tmp244_ = tmp237_*tmp40_; double tmp245_ = tmp244_+tmp92_; double tmp246_ = tmp243_+tmp245_; double tmp247_ = tmp237_*tmp14_; double tmp248_ = tmp247_*(tmp22_); double tmp249_ = tmp238_*tmp24_; double tmp250_ = tmp239_*tmp27_; double tmp251_ = tmp249_+tmp250_; double tmp252_ = (tmp251_)*(tmp29_); double tmp253_ = tmp248_+tmp252_; double tmp254_ = tmp238_*tmp40_; double tmp255_ = tmp239_*tmp24_; double tmp256_ = tmp254_+tmp255_; double tmp257_ = tmp253_+tmp256_; double tmp258_ = tmp137_*tmp26_; double tmp259_ = -(tmp14_); double tmp260_ = tmp259_*tmp25_; double tmp261_ = tmp259_*tmp30_; double tmp262_ = tmp14_*(tmp22_); double tmp263_ = tmp258_*tmp27_; double tmp264_ = tmp263_*(tmp29_); double tmp265_ = tmp262_+tmp264_; double tmp266_ = tmp258_*tmp24_; double tmp267_ = tmp265_+tmp266_; double tmp268_ = tmp258_*tmp25_; double tmp269_ = tmp268_*(tmp22_); double tmp270_ = tmp260_*tmp27_; double tmp271_ = tmp270_*(tmp29_); double tmp272_ = tmp269_+tmp271_; double tmp273_ = tmp260_*tmp24_; double tmp274_ = tmp272_+tmp273_; double tmp275_ = tmp258_*tmp30_; double tmp276_ = tmp275_*(tmp22_); double tmp277_ = tmp261_*tmp27_; double tmp278_ = tmp277_*(tmp29_); double tmp279_ = tmp276_+tmp278_; double tmp280_ = tmp261_*tmp24_; double tmp281_ = tmp279_+tmp280_; double tmp282_ = tmp137_*tmp27_; double tmp283_ = -(tmp24_); double tmp284_ = tmp24_*tmp14_; double tmp285_ = tmp284_*(tmp29_); double tmp286_ = tmp282_*tmp14_; double tmp287_ = tmp285_+tmp286_; double tmp288_ = tmp282_*tmp30_; double tmp289_ = tmp24_*tmp32_; double tmp290_ = tmp288_+tmp289_; double tmp291_ = (tmp290_)*(tmp29_); double tmp292_ = tmp283_*tmp30_; double tmp293_ = tmp282_*tmp32_; double tmp294_ = tmp292_+tmp293_; double tmp295_ = tmp291_+tmp294_; double tmp296_ = tmp282_*tmp39_; double tmp297_ = tmp24_*tmp41_; double tmp298_ = tmp296_+tmp297_; double tmp299_ = (tmp298_)*(tmp29_); double tmp300_ = tmp283_*tmp39_; double tmp301_ = tmp282_*tmp41_; double tmp302_ = tmp300_+tmp301_; double tmp303_ = tmp299_+tmp302_; mVal[0] = (tmp233_)/tmp136_; mCompDer[0][0] = (((((tmp127_)*(tmp50_)+(tmp118_)*(tmp83_))-((tmp115_)*(tmp72_)+(tmp124_)*(tmp38_)))*(tmp97_)+(((tmp115_)*(tmp94_)+(tmp130_)*(tmp38_))-((tmp121_)*(tmp50_)+(tmp118_)*(tmp61_)))*(tmp100_)+(((tmp121_)*(tmp72_)+(tmp124_)*(tmp61_))-((tmp127_)*(tmp94_)+(tmp130_)*(tmp83_)))*(tmp103_))*tmp136_)/tmp146_; mCompDer[0][1] = ((((tmp144_*(tmp50_)+tmp141_*(tmp83_))-(tmp140_*(tmp72_)+tmp143_*(tmp38_)))*(tmp97_)+((tmp140_*(tmp94_)+tmp145_*(tmp38_))-(tmp142_*(tmp50_)+tmp141_*(tmp61_)))*(tmp100_)+((tmp142_*(tmp72_)+tmp143_*(tmp61_))-(tmp144_*(tmp94_)+tmp145_*(tmp83_)))*(tmp103_))*tmp136_)/tmp146_; mCompDer[0][2] = ((((tmp151_*(tmp50_)+tmp148_*(tmp83_))-(tmp147_*(tmp72_)+tmp150_*(tmp38_)))*(tmp97_)+((tmp147_*(tmp94_)+tmp152_*(tmp38_))-(tmp149_*(tmp50_)+tmp148_*(tmp61_)))*(tmp100_)+((tmp149_*(tmp72_)+tmp150_*(tmp61_))-(tmp151_*(tmp94_)+tmp152_*(tmp83_)))*(tmp103_))*tmp136_)/tmp146_; mCompDer[0][3] = (((tmp173_)*(tmp50_)*(tmp97_)+-((tmp166_)*(tmp50_))*(tmp100_)+((tmp166_)*(tmp72_)-(tmp173_)*(tmp94_))*(tmp103_))*tmp136_)/tmp146_; mCompDer[0][4] = ((((tmp197_)*(tmp50_)-(tmp182_)*(tmp72_))*(tmp97_)+((tmp182_)*(tmp94_)-(tmp190_)*(tmp50_))*(tmp100_)+((tmp190_)*(tmp72_)-(tmp197_)*(tmp94_))*(tmp103_))*tmp136_)/tmp146_; mCompDer[0][5] = ((((tmp219_)*(tmp50_)-(tmp202_)*(tmp72_))*(tmp97_)+((tmp202_)*(tmp94_)-(tmp211_)*(tmp50_))*(tmp100_)+((tmp211_)*(tmp72_)-(tmp219_)*(tmp94_))*(tmp103_))*tmp136_)/tmp146_; mCompDer[0][6] = (tmp137_*(tmp222_)*tmp136_-(tmp233_)*((0.500000*(tmp234_+tmp234_))/tmp136_))/tmp146_; mCompDer[0][7] = (tmp137_*(tmp226_)*tmp136_-(tmp233_)*((0.500000*(tmp235_+tmp235_))/tmp136_))/tmp146_; mCompDer[0][8] = (tmp137_*(tmp231_)*tmp136_-(tmp233_)*((0.500000*(tmp236_+tmp236_))/tmp136_))/tmp146_; mCompDer[0][9] = ((-((tmp246_)*(tmp38_))*(tmp97_)+(tmp257_)*(tmp38_)*(tmp100_)+((tmp246_)*(tmp61_)-(tmp257_)*(tmp83_))*(tmp103_))*tmp136_)/tmp146_; mCompDer[0][10] = ((((tmp267_)*(tmp83_)-(tmp274_)*(tmp38_))*(tmp97_)+((tmp281_)*(tmp38_)-(tmp267_)*(tmp61_))*(tmp100_)+((tmp274_)*(tmp61_)-(tmp281_)*(tmp83_))*(tmp103_))*tmp136_)/tmp146_; mCompDer[0][11] = ((((tmp287_)*(tmp83_)-(tmp295_)*(tmp38_))*(tmp97_)+((tmp303_)*(tmp38_)-(tmp287_)*(tmp61_))*(tmp100_)+((tmp295_)*(tmp61_)-(tmp303_)*(tmp83_))*(tmp103_))*tmp136_)/tmp146_; mCompDer[0][12] = ((tmp222_)*tmp136_-(tmp233_)*((0.500000*(tmp97_+tmp97_))/tmp136_))/tmp146_; mCompDer[0][13] = ((tmp226_)*tmp136_-(tmp233_)*((0.500000*(tmp100_+tmp100_))/tmp136_))/tmp146_; mCompDer[0][14] = ((tmp231_)*tmp136_-(tmp233_)*((0.500000*(tmp103_+tmp103_))/tmp136_))/tmp146_; } void cEqCoplanNoDistId::ComputeValDerivHessian() { ELISE_ASSERT(false,"Foncteur cEqCoplanNoDistId Has no Der Sec"); } void cEqCoplanNoDistId::SetXL1(double aVal){ mLocXL1 = aVal;} void cEqCoplanNoDistId::SetXL2(double aVal){ mLocXL2 = aVal;} void cEqCoplanNoDistId::SetYL1(double aVal){ mLocYL1 = aVal;} void cEqCoplanNoDistId::SetYL2(double aVal){ mLocYL2 = aVal;} double * cEqCoplanNoDistId::AdrVarLocFromString(const std::string & aName) { if (aName == "XL1") return & mLocXL1; if (aName == "XL2") return & mLocXL2; if (aName == "YL1") return & mLocYL1; if (aName == "YL2") return & mLocYL2; return 0; } cElCompiledFonc::cAutoAddEntry cEqCoplanNoDistId::mTheAuto("cEqCoplanNoDistId",cEqCoplanNoDistId::Alloc); cElCompiledFonc * cEqCoplanNoDistId::Alloc() { return new cEqCoplanNoDistId(); }
8,558
5,597
/* * The MIT License * * Copyright 2020 Intuit Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.intuit.karate.http; import com.intuit.karate.FileUtils; import java.io.File; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author pthomas3 */ public class SslContextFactory { private static final Logger logger = LoggerFactory.getLogger(SslContextFactory.class); public static final String DEFAULT_CERT_NAME = "cert.pem"; public static final String DEFAULT_KEY_NAME = "key.pem"; private String buildDir; private File certFile; private File keyFile; public void setBuildDir(String buildDir) { this.buildDir = buildDir; } public void setCertFile(File certFile) { this.certFile = certFile; } public void setKeyFile(File keyFile) { this.keyFile = keyFile; } public File getCertFile() { return certFile; } public File getKeyFile() { return keyFile; } public void build() { if (buildDir == null) { buildDir = FileUtils.getBuildDir(); } try { if (certFile == null || keyFile == null) { // attempt to re-use as far as possible certFile = new File(buildDir + File.separator + DEFAULT_CERT_NAME); keyFile = new File(buildDir + File.separator + DEFAULT_KEY_NAME); } if (!certFile.exists() || !keyFile.exists()) { logger.warn("ssl - " + certFile + " and / or " + keyFile + " not found, will create"); HttpUtils.createSelfSignedCertificate(certFile, keyFile); } else { logger.info("ssl - re-using existing files: {} and {}", certFile, keyFile); } } catch (Exception e) { throw new RuntimeException(e); } } }
1,063
1,431
<filename>poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestPictures.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.apache.poi.hslf.usermodel; import static org.apache.commons.io.output.NullOutputStream.NULL_OUTPUT_STREAM; import static org.apache.poi.hslf.HSLFTestDataSamples.getSlideShow; import static org.apache.poi.hslf.HSLFTestDataSamples.writeOutAndReadBack; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import java.awt.Dimension; import java.awt.geom.Dimension2D; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.IOException; import java.net.URL; import java.util.Arrays; import java.util.Collections; import java.util.List; import javax.imageio.ImageIO; import org.apache.commons.io.output.CountingOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.ddf.EscherBSERecord; import org.apache.poi.ddf.EscherContainerRecord; import org.apache.poi.ddf.EscherRecord; import org.apache.poi.hslf.blip.EMF; import org.apache.poi.hslf.blip.JPEG; import org.apache.poi.hslf.blip.PICT; import org.apache.poi.hslf.blip.PNG; import org.apache.poi.hslf.blip.WMF; import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey; import org.apache.poi.sl.image.ImageHeaderEMF; import org.apache.poi.sl.image.ImageHeaderPICT; import org.apache.poi.sl.image.ImageHeaderWMF; import org.apache.poi.sl.usermodel.PictureData.PictureType; import org.apache.poi.util.RandomSingleton; import org.apache.poi.util.Units; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; /** * Test adding/reading pictures */ public final class TestPictures { private static final POIDataSamples slTests = POIDataSamples.getSlideShowInstance(); /** * Test add/read/write images */ @ParameterizedTest() @CsvSource(value = { // in PICT the first 512 bytes are MAC specific and may not be preserved, ignore them "PICT, cow.pict, 197, 137, 512, org.apache.poi.hslf.blip.PICT", // in WMF the first 22 bytes - is a metafile header "WMF, santa.wmf, 136, 146, 22, org.apache.poi.hslf.blip.WMF", "EMF, wrench.emf, 190, 115, 0, org.apache.poi.hslf.blip.EMF", "PNG, tomcat.png, 129, 92, 0, org.apache.poi.hslf.blip.PNG", "JPEG, clock.jpg, 192, 176, 0, org.apache.poi.hslf.blip.JPEG", "DIB, clock.dib, 192, 176, 0, org.apache.poi.hslf.blip.DIB" }) void testAddPictures(PictureType pictureType, String imgFile, int expWidth, int expHeight, int headerOffset, Class<?> imgClazz) throws IOException { byte[] src_bytes = slTests.readFile(imgFile); int dataIndex; try (HSLFSlideShow ppt1 = new HSLFSlideShow()) { HSLFSlide slide1 = ppt1.createSlide(); HSLFPictureData data1 = ppt1.addPicture(src_bytes, pictureType); dataIndex = data1.getIndex(); // TODO: Fix the differences in the frame sizes Dimension2D dimN, dimFrame1, dimFrame2; switch (pictureType) { case PICT: dimN = new ImageHeaderPICT(src_bytes, headerOffset).getSize(); dimFrame1 = Units.pointsToPixel(dimN); dimFrame2 = dimN; break; case WMF: dimN = new ImageHeaderWMF(src_bytes, 0).getSize(); dimFrame1 = Units.pointsToPixel(dimN); dimFrame2 = dimN; break; case EMF: dimN = new ImageHeaderEMF(src_bytes, 0).getSize(); dimFrame1 = Units.pointsToPixel(dimN); dimFrame2 = dimN; break; case JPEG: case DIB: case PNG: { BufferedImage png = ImageIO.read(new ByteArrayInputStream(src_bytes)); dimN = new Dimension(png.getWidth(), png.getHeight()); dimFrame1 = dimN; dimFrame2 = Units.pixelToPoints(dimN); break; } default: fail(); return; } assertEquals(expWidth, dimN.getWidth(), 1); assertEquals(expHeight, dimN.getHeight(), 1); Dimension dim1 = data1.getImageDimensionInPixels(); assertEquals(dimFrame1.getWidth(), dim1.getWidth(), 1); assertEquals(dimFrame1.getHeight(), dim1.getHeight(), 1); HSLFPictureShape pict1 = new HSLFPictureShape(data1); assertEquals(data1.getIndex(), pict1.getPictureIndex()); slide1.addShape(pict1); try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) { //make sure we can read this picture shape and it refers to the correct picture data List<HSLFShape> sh2 = ppt2.getSlides().get(0).getShapes(); assertEquals(1, sh2.size()); HSLFPictureShape pict2 = (HSLFPictureShape) sh2.get(0); assertEquals(dataIndex, pict2.getPictureIndex()); //check picture data List<HSLFPictureData> pictures2 = ppt2.getPictureData(); assertEquals(1, pictures2.size()); HSLFPictureData pd2 = pictures2.get(0); Dimension dim2 = pd2.getImageDimension(); assertEquals(dimFrame2.getWidth(), dim2.width, 1); assertEquals(dimFrame2.getHeight(), dim2.height, 1); //the Picture shape refers to the PictureData object in the Presentation assertEquals(pict2.getPictureData(), pd2); assertEquals(1, pictures2.size()); assertEquals(pictureType, pd2.getType()); assertTrue(imgClazz.isInstance(pd2)); //compare the content of the initial file with what is stored in the PictureData byte[] ppt_bytes = pd2.getData(); assertEquals(src_bytes.length, ppt_bytes.length); byte[] b1 = Arrays.copyOfRange(src_bytes, headerOffset, src_bytes.length); byte[] b2 = Arrays.copyOfRange(ppt_bytes, headerOffset, ppt_bytes.length); assertArrayEquals(b1, b2); } } } /** * Read pictures in different formats from a reference slide show */ @Test void testReadPictures() throws IOException { byte[] src_bytes, ppt_bytes, b1, b2; HSLFPictureShape pict; HSLFPictureData pdata; try (HSLFSlideShow ppt = getSlideShow("pictures.ppt")) { List<HSLFSlide> slides = ppt.getSlides(); List<HSLFPictureData> pictures = ppt.getPictureData(); assertEquals(5, pictures.size()); pict = (HSLFPictureShape) slides.get(0).getShapes().get(0); //the first slide contains JPEG pdata = pict.getPictureData(); assertTrue(pdata instanceof JPEG); assertEquals(PictureType.JPEG, pdata.getType()); src_bytes = pdata.getData(); ppt_bytes = slTests.readFile("clock.jpg"); assertArrayEquals(src_bytes, ppt_bytes); pict = (HSLFPictureShape) slides.get(1).getShapes().get(0); //the second slide contains PNG pdata = pict.getPictureData(); assertTrue(pdata instanceof PNG); assertEquals(PictureType.PNG, pdata.getType()); src_bytes = pdata.getData(); ppt_bytes = slTests.readFile("tomcat.png"); assertArrayEquals(src_bytes, ppt_bytes); pict = (HSLFPictureShape) slides.get(2).getShapes().get(0); //the third slide contains WMF pdata = pict.getPictureData(); assertTrue(pdata instanceof WMF); assertEquals(PictureType.WMF, pdata.getType()); src_bytes = pdata.getData(); ppt_bytes = slTests.readFile("santa.wmf"); assertEquals(src_bytes.length, ppt_bytes.length); //ignore the first 22 bytes - it is a WMF metafile header b1 = Arrays.copyOfRange(src_bytes, 22, src_bytes.length); b2 = Arrays.copyOfRange(ppt_bytes, 22, ppt_bytes.length); assertArrayEquals(b1, b2); pict = (HSLFPictureShape) slides.get(3).getShapes().get(0); //the forth slide contains PICT pdata = pict.getPictureData(); assertTrue(pdata instanceof PICT); assertEquals(PictureType.PICT, pdata.getType()); src_bytes = pdata.getData(); ppt_bytes = slTests.readFile("cow.pict"); assertEquals(src_bytes.length, ppt_bytes.length); //ignore the first 512 bytes - it is a MAC specific crap b1 = Arrays.copyOfRange(src_bytes, 512, src_bytes.length); b2 = Arrays.copyOfRange(ppt_bytes, 512, ppt_bytes.length); assertArrayEquals(b1, b2); pict = (HSLFPictureShape) slides.get(4).getShapes().get(0); //the fifth slide contains EMF pdata = pict.getPictureData(); assertTrue(pdata instanceof EMF); assertEquals(PictureType.EMF, pdata.getType()); src_bytes = pdata.getData(); ppt_bytes = slTests.readFile("wrench.emf"); assertArrayEquals(src_bytes, ppt_bytes); } } /** * Test that on a party corrupt powerpoint document, which has * crazy pictures of type 0, we do our best. */ @Test void testZeroPictureType() throws IOException { try (HSLFSlideShowImpl hslf = new HSLFSlideShowImpl(slTests.openResourceAsStream("PictureTypeZero.ppt"))) { // Should still have 2 real pictures assertEquals(2, hslf.getPictureData().size()); // Both are real pictures, both WMF assertEquals(PictureType.WMF, hslf.getPictureData().get(0).getType()); assertEquals(PictureType.WMF, hslf.getPictureData().get(1).getType()); // Now test what happens when we use the SlideShow interface HSLFSlideShow ppt = new HSLFSlideShow(hslf); List<HSLFSlide> slides = ppt.getSlides(); List<HSLFPictureData> pictures = ppt.getPictureData(); assertEquals(12, slides.size()); assertEquals(2, pictures.size()); HSLFPictureShape pict; HSLFPictureData pdata; pict = (HSLFPictureShape) slides.get(0).getShapes().get(1); // 2nd object on 1st slide pdata = pict.getPictureData(); assertTrue(pdata instanceof WMF); assertEquals(PictureType.WMF, pdata.getType()); pict = (HSLFPictureShape) slides.get(0).getShapes().get(2); // 3rd object on 1st slide pdata = pict.getPictureData(); assertTrue(pdata instanceof WMF); assertEquals(PictureType.WMF, pdata.getType()); } } /** * YK: The test is disabled because the owner asked to delete the test file from POI svn. * See "Please remove my file from your svn" on @poi-dev from Dec 12, 2013 */ @Test @Disabled("requires an internet connection to a 3rd party site") // As of 2017-06-20, the file still exists at the specified URL and the test passes. void testZeroPictureLength() throws IOException { // take the data from www instead of test directory URL url = new URL("http://www.cs.sfu.ca/~anoop/courses/CMPT-882-Fall-2002/chris.ppt"); HSLFSlideShowImpl hslf = new HSLFSlideShowImpl(url.openStream()); /* Assume that the file could retrieved... InputStream is; HSLFSlideShowImpl hslf; try { is = url.openStream(); hslf = new HSLFSlideShowImpl(is); is.close(); } catch (final IOException e) { Assume.assumeTrue(e.getMessage(), false); throw e; } */ // Should still have 2 real pictures assertEquals(2, hslf.getPictureData().size()); // Both are real pictures, both WMF assertEquals(PictureType.WMF, hslf.getPictureData().get(0).getType()); assertEquals(PictureType.WMF, hslf.getPictureData().get(1).getType()); // Now test what happens when we use the SlideShow interface try (HSLFSlideShow ppt = new HSLFSlideShow(hslf)) { List<HSLFSlide> slides = ppt.getSlides(); List<HSLFPictureData> pictures = ppt.getPictureData(); assertEquals(27, slides.size()); assertEquals(2, pictures.size()); HSLFPictureShape pict; HSLFPictureData pdata; pict = (HSLFPictureShape) slides.get(6).getShapes().get(13); pdata = pict.getPictureData(); assertTrue(pdata instanceof WMF); assertEquals(PictureType.WMF, pdata.getType()); pict = (HSLFPictureShape) slides.get(7).getShapes().get(13); pdata = pict.getPictureData(); assertTrue(pdata instanceof WMF); assertEquals(PictureType.WMF, pdata.getType()); //add a new picture, it should be correctly appended to the Pictures stream CountingOutputStream out = new CountingOutputStream(NULL_OUTPUT_STREAM); for (HSLFPictureData p : pictures) p.write(out); int streamSize = out.getCount(); HSLFPictureData data = ppt.addPicture(new byte[100], PictureType.JPEG); int offset = data.getOffset(); assertEquals(streamSize, offset); assertEquals(3, ppt.getPictureData().size()); } } @Test void testGetPictureName() throws IOException { try (HSLFSlideShow ppt = getSlideShow("ppt_with_png.ppt")) { HSLFSlide slide = ppt.getSlides().get(0); HSLFPictureShape p = (HSLFPictureShape) slide.getShapes().get(0); //the first slide contains JPEG assertEquals("test", p.getPictureName()); } } @Test void testSetPictureName() throws IOException { try (HSLFSlideShow ppt1 = new HSLFSlideShow()) { HSLFSlide slide = ppt1.createSlide(); byte[] img = slTests.readFile("tomcat.png"); HSLFPictureData data = ppt1.addPicture(img, PictureType.PNG); HSLFPictureShape pict = new HSLFPictureShape(data); pict.setPictureName("tomcat.png"); slide.addShape(pict); //serialize and read again try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) { HSLFPictureShape p = (HSLFPictureShape) ppt2.getSlides().get(0).getShapes().get(0); assertEquals("tomcat.png", p.getPictureName()); } } } @Test void testPictureIndexIsOneBased() throws IOException { try (HSLFSlideShow ppt = getSlideShow("ppt_with_png.ppt")) { HSLFPictureData picture = ppt.getPictureData().get(0); assertEquals(1, picture.getIndex()); } } /** * Verify that it is possible for a user to change the contents of a {@link HSLFPictureData} using * {@link HSLFPictureData#setData(byte[])}, and that the changes are saved to the slideshow. */ @Test void testEditPictureData() throws IOException { byte[] newImage = slTests.readFile("tomcat.png"); // Load an existing slideshow and modify the image try (HSLFSlideShow ppt1 = getSlideShow("ppt_with_png.ppt")) { HSLFPictureData picture1 = ppt1.getPictureData().get(0); picture1.setData(newImage); // Load the modified slideshow and verify the image content try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) { HSLFPictureData picture2 = ppt2.getPictureData().get(0); byte[] modifiedImageData = picture2.getData(); assertArrayEquals(newImage, modifiedImageData); } } } /** * Verify that it is possible for a user to change the contents of an encrypted {@link HSLFPictureData} using * {@link HSLFPictureData#setData(byte[])}, and that the changes are saved to the slideshow. */ @Test void testEditPictureDataEncrypted() throws IOException { byte[] newImage = slTests.readFile("tomcat.png"); Biff8EncryptionKey.setCurrentUserPassword("password"); try { // Load an existing slideshow and modify the image try (HSLFSlideShow ppt1 = getSlideShow("ppt_with_png_encrypted.ppt")) { HSLFPictureData picture1 = ppt1.getPictureData().get(0); picture1.setData(newImage); // Load the modified slideshow and verify the image content try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) { HSLFPictureData picture2 = ppt2.getPictureData().get(0); byte[] modifiedImageData = picture2.getData(); assertArrayEquals(newImage, modifiedImageData); } } } finally { Biff8EncryptionKey.setCurrentUserPassword(null); } } /** * Verify that the {@link EscherBSERecord#getOffset()} values are modified for all images after the image being * changed. */ @Test void testEditPictureDataRecordOffsetsAreShifted() throws IOException { int[] originalOffsets = {0, 12013, 15081, 34162, 59563}; int[] modifiedOffsets = {0, 35, 3103, 22184, 47585}; try (HSLFSlideShow ppt1 = getSlideShow("pictures.ppt")) { int[] offsets1 = ppt1.getPictureData().stream().mapToInt(HSLFPictureData::getOffset).toArray(); assertArrayEquals(originalOffsets, offsets1); HSLFPictureData imageBeingChanged = ppt1.getPictureData().get(0); // It doesn't matter that this isn't a valid image. We are just testing offsets here. imageBeingChanged.setData(new byte[10]); // Verify that the in-memory representations have all been updated offsets1 = ppt1.getPictureData().stream().mapToInt(HSLFPictureData::getOffset).toArray(); assertArrayEquals(modifiedOffsets, offsets1); try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) { // Verify that the persisted representations have all been updated int[] offsets2 = ppt2.getPictureData().stream().mapToInt(HSLFPictureData::getOffset).toArray(); assertArrayEquals(modifiedOffsets, offsets2); } } } /** * Verify that the {@link EscherBSERecord#getOffset()} values are modified for all images after the image being * changed, but assuming that the records are not stored in a sorted-by-offset fashion. * * We have not encountered a file that has meaningful data that is not sorted. However, we have encountered files * that have records with an offset of 0 interspersed between meaningful records. See {@code 53446.ppt} and * {@code alterman_security.ppt} for examples. */ @Test void testEditPictureDataOutOfOrderRecords() throws IOException { int[] modifiedOffsets = {0, 35, 3103, 22184, 47585}; try (HSLFSlideShow ppt1 = getSlideShow("pictures.ppt")) { // For this test we're going to intentionally manipulate the records into a shuffled order. EscherContainerRecord container = ppt1.getPictureData().get(0).bStore; List<EscherRecord> children = container.getChildRecords(); for (EscherRecord child : children) { container.removeChildRecord(child); } Collections.shuffle(children); for (EscherRecord child : children) { container.addChildRecord(child); } HSLFPictureData imageBeingChanged = ppt1.getPictureData().get(0); // It doesn't matter that this isn't a valid image. We are just testing offsets here. imageBeingChanged.setData(new byte[10]); // Verify that the in-memory representations have all been updated int[] offsets1 = ppt1.getPictureData().stream().mapToInt(HSLFPictureData::getOffset).sorted().toArray(); assertArrayEquals(modifiedOffsets, offsets1); try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) { // Verify that the persisted representations have all been updated int[] offsets2 = ppt2.getPictureData().stream().mapToInt(HSLFPictureData::getOffset).sorted().toArray(); assertArrayEquals(modifiedOffsets, offsets2); } } } /** * Verify that a slideshow with records that have offsets not matching those of the pictures in the stream still * correctly pairs the records and pictures. */ @Test void testSlideshowWithIncorrectOffsets() throws IOException { int[] originalOffsets; int originalNumberOfRecords; // Create a presentation that has records with unmatched offsets, but with matched UIDs. try (HSLFSlideShow ppt1 = getSlideShow("pictures.ppt")) { originalOffsets = ppt1.getPictureData().stream().mapToInt(HSLFPictureData::getOffset).toArray(); originalNumberOfRecords = ppt1.getPictureData().get(0).bStore.getChildCount(); for (HSLFPictureData picture : ppt1.getPictureData()) { // Bound is arbitrary and irrelevant to the test. picture.bse.setOffset(RandomSingleton.getInstance().nextInt(500_000)); } try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) { // Verify that the offsets all got fixed. int[] offsets = ppt2.getPictureData().stream().mapToInt(HSLFPictureData::getOffset).toArray(); assertArrayEquals(originalOffsets, offsets); // Verify that there are the same number of records as in the original slideshow. int numberOfRecords = ppt2.getPictureData().get(0).bStore.getChildCount(); assertEquals(originalNumberOfRecords, numberOfRecords); } } } }
10,219
1,341
// // RCOfferingAPI.h // APITester // // Created by <NAME> on 7/9/21. // Copyright © 2021 Purchases. All rights reserved. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @interface RCOfferingAPI : NSObject + (void)checkAPI; @end NS_ASSUME_NONNULL_END
113
30,023
"""Test for the Insteon integration."""
10