max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
348
<gh_stars>100-1000 {"nom":"Bruyères","circ":"2ème circonscription","dpt":"Vosges","inscrits":1939,"abs":1084,"votants":855,"blancs":59,"nuls":30,"exp":766,"res":[{"nuance":"LR","nom":"<NAME>","voix":404},{"nuance":"REM","nom":"<NAME>","voix":362}]}
103
3,508
package com.fishercoder.solutions; public class _313 { public static class Solution1 { public int nthSuperUglyNumber(int n, int[] primes) { int[] ret = new int[n]; ret[0] = 1; int[] indexes = new int[primes.length]; for (int i = 1; i < n; i++) { ret[i] = Integer.MAX_VALUE; for (int j = 0; j < primes.length; j++) { ret[i] = Math.min(ret[i], primes[j] * ret[indexes[j]]); } for (int j = 0; j < indexes.length; j++) { if (ret[i] == primes[j] * ret[indexes[j]]) { indexes[j]++; } } } return ret[n - 1]; } } }
459
4,256
import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.security.KeyStore; import java.io.FileInputStream; import java.io.OutputStream; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.SSLSocket; /* * Simple JDK SSL client for integration testing purposes */ public class SSLSocketClient { public static void main(String[] args) throws Exception { int port = Integer.parseInt(args[0]); String certificatePath = args[1]; String protocol = sslProtocols(args[2]); String[] protocolList = new String[] {protocol}; String[] cipher = new String[] {args[3]}; String host = "localhost"; byte[] buffer = new byte[100]; SSLSocketFactory socketFactory = createSocketFactory(certificatePath, protocol); try ( SSLSocket socket = (SSLSocket)socketFactory.createSocket(host, port); OutputStream out = new BufferedOutputStream(socket.getOutputStream()); BufferedInputStream stdIn = new BufferedInputStream(System.in); ) { socket.setEnabledProtocols(protocolList); socket.setEnabledCipherSuites(cipher); socket.startHandshake(); System.out.println("Starting handshake"); while (true) { int read = stdIn.read(buffer); if (read == -1) break; out.write(buffer, 0, read); } out.flush(); out.close(); socket.close(); } catch (Exception e) { e.printStackTrace(); } } public static SSLSocketFactory createSocketFactory(String certificatePath, String protocol) { try { CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); FileInputStream is = new FileInputStream(certificatePath); X509Certificate cert = (X509Certificate) certFactory.generateCertificate(is); is.close(); KeyStore caKeyStore = KeyStore.getInstance(KeyStore.getDefaultType()); caKeyStore.load(null, null); caKeyStore.setCertificateEntry("ca-certificate", cert); TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance( TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(caKeyStore); SSLContext context = SSLContext.getInstance(protocol); context.init(null, trustManagerFactory.getTrustManagers(), null); return context.getSocketFactory(); } catch(Exception e) { e.printStackTrace(); } return null; } public static String sslProtocols(String s2nProtocol) { switch (s2nProtocol) { case "TLS1.3": return "TLSv1.3"; case "TLS1.2": return "TLSv1.2"; case "TLS1.1": return "TLSv1.1"; case "TLS1.0": return "TLSv1.0"; } return null; } }
1,415
1,350
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.frontdoor.models; import com.azure.core.annotation.Fluent; import com.azure.core.annotation.JsonFlatten; import com.azure.core.management.SubResource; import com.azure.core.util.logging.ClientLogger; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; /** A backend pool is a collection of backends that can be routed to. */ @JsonFlatten @Fluent public class BackendPool extends SubResource { @JsonIgnore private final ClientLogger logger = new ClientLogger(BackendPool.class); /* * Resource name. */ @JsonProperty(value = "name") private String name; /* * Resource type. */ @JsonProperty(value = "type", access = JsonProperty.Access.WRITE_ONLY) private String type; /* * The set of backends for this pool */ @JsonProperty(value = "properties.backends") private List<Backend> backends; /* * Load balancing settings for a backend pool */ @JsonProperty(value = "properties.loadBalancingSettings") private SubResource loadBalancingSettings; /* * L7 health probe settings for a backend pool */ @JsonProperty(value = "properties.healthProbeSettings") private SubResource healthProbeSettings; /* * Resource status. */ @JsonProperty(value = "properties.resourceState", access = JsonProperty.Access.WRITE_ONLY) private FrontDoorResourceState resourceState; /** * Get the name property: Resource name. * * @return the name value. */ public String name() { return this.name; } /** * Set the name property: Resource name. * * @param name the name value to set. * @return the BackendPool object itself. */ public BackendPool withName(String name) { this.name = name; return this; } /** * Get the type property: Resource type. * * @return the type value. */ public String type() { return this.type; } /** * Get the backends property: The set of backends for this pool. * * @return the backends value. */ public List<Backend> backends() { return this.backends; } /** * Set the backends property: The set of backends for this pool. * * @param backends the backends value to set. * @return the BackendPool object itself. */ public BackendPool withBackends(List<Backend> backends) { this.backends = backends; return this; } /** * Get the loadBalancingSettings property: Load balancing settings for a backend pool. * * @return the loadBalancingSettings value. */ public SubResource loadBalancingSettings() { return this.loadBalancingSettings; } /** * Set the loadBalancingSettings property: Load balancing settings for a backend pool. * * @param loadBalancingSettings the loadBalancingSettings value to set. * @return the BackendPool object itself. */ public BackendPool withLoadBalancingSettings(SubResource loadBalancingSettings) { this.loadBalancingSettings = loadBalancingSettings; return this; } /** * Get the healthProbeSettings property: L7 health probe settings for a backend pool. * * @return the healthProbeSettings value. */ public SubResource healthProbeSettings() { return this.healthProbeSettings; } /** * Set the healthProbeSettings property: L7 health probe settings for a backend pool. * * @param healthProbeSettings the healthProbeSettings value to set. * @return the BackendPool object itself. */ public BackendPool withHealthProbeSettings(SubResource healthProbeSettings) { this.healthProbeSettings = healthProbeSettings; return this; } /** * Get the resourceState property: Resource status. * * @return the resourceState value. */ public FrontDoorResourceState resourceState() { return this.resourceState; } /** {@inheritDoc} */ @Override public BackendPool withId(String id) { super.withId(id); return this; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { if (backends() != null) { backends().forEach(e -> e.validate()); } } }
1,714
4,625
// Copyright 2017 JanusGraph 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 org.janusgraph.example; import org.apache.commons.configuration2.Configuration; import org.apache.commons.configuration2.ex.ConfigurationException; import org.apache.tinkerpop.gremlin.process.traversal.P; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; import org.apache.tinkerpop.gremlin.structure.Graph; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.apache.tinkerpop.gremlin.structure.util.GraphFactory; import org.janusgraph.core.attribute.Geoshape; import org.janusgraph.util.system.ConfigurationUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.Optional; public class GraphApp { private static final Logger LOGGER = LoggerFactory.getLogger(GraphApp.class); protected String propFileName; protected Configuration conf; protected Graph graph; protected GraphTraversalSource g; protected boolean supportsTransactions; protected boolean supportsSchema; protected boolean supportsGeoshape; /** * Constructs a graph app using the given properties. * @param fileName location of the properties file */ public GraphApp(final String fileName) { propFileName = fileName; } /** * Opens the graph instance. If the graph instance does not exist, a new * graph instance is initialized. */ public GraphTraversalSource openGraph() throws ConfigurationException, IOException { LOGGER.info("opening graph"); conf = ConfigurationUtil.loadPropertiesConfig(propFileName); graph = GraphFactory.open(conf); g = graph.traversal(); return g; } /** * Closes the graph instance. */ public void closeGraph() throws Exception { LOGGER.info("closing graph"); try { if (g != null) { g.close(); } if (graph != null) { graph.close(); } } finally { g = null; graph = null; } } /** * Drops the graph instance. The default implementation does nothing. */ public void dropGraph() throws Exception { } /** * Creates the graph schema. The default implementation does nothing. */ public void createSchema() { } /** * Adds the vertices, edges, and properties to the graph. */ public void createElements() { try { // naive check if the graph was previously created if (g.V().has("name", "saturn").hasNext()) { if (supportsTransactions) { g.tx().rollback(); } return; } LOGGER.info("creating elements"); // see GraphOfTheGodsFactory.java final Vertex saturn = g.addV("titan").property("name", "saturn").property("age", 10000).next(); final Vertex sky = g.addV("location").property("name", "sky").next(); final Vertex sea = g.addV("location").property("name", "sea").next(); final Vertex jupiter = g.addV("god").property("name", "jupiter").property("age", 5000).next(); final Vertex neptune = g.addV("god").property("name", "neptune").property("age", 4500).next(); final Vertex hercules = g.addV("demigod").property("name", "hercules").property("age", 30).next(); final Vertex alcmene = g.addV("human").property("name", "alcmene").property("age", 45).next(); final Vertex pluto = g.addV("god").property("name", "pluto").property("age", 4000).next(); final Vertex nemean = g.addV("monster").property("name", "nemean").next(); final Vertex hydra = g.addV("monster").property("name", "hydra").next(); final Vertex cerberus = g.addV("monster").property("name", "cerberus").next(); final Vertex tartarus = g.addV("location").property("name", "tartarus").next(); g.V(jupiter).as("a").V(saturn).addE("father").from("a").next(); g.V(jupiter).as("a").V(sky).addE("lives").property("reason", "loves fresh breezes").from("a").next(); g.V(jupiter).as("a").V(neptune).addE("brother").from("a").next(); g.V(jupiter).as("a").V(pluto).addE("brother").from("a").next(); g.V(neptune).as("a").V(sea).addE("lives").property("reason", "loves waves").from("a").next(); g.V(neptune).as("a").V(jupiter).addE("brother").from("a").next(); g.V(neptune).as("a").V(pluto).addE("brother").from("a").next(); g.V(hercules).as("a").V(jupiter).addE("father").from("a").next(); g.V(hercules).as("a").V(alcmene).addE("mother").from("a").next(); if (supportsGeoshape) { g.V(hercules).as("a").V(nemean).addE("battled").property("time", 1) .property("place", Geoshape.point(38.1f, 23.7f)).from("a").next(); g.V(hercules).as("a").V(hydra).addE("battled").property("time", 2) .property("place", Geoshape.point(37.7f, 23.9f)).from("a").next(); g.V(hercules).as("a").V(cerberus).addE("battled").property("time", 12) .property("place", Geoshape.point(39f, 22f)).from("a").next(); } else { g.V(hercules).as("a").V(nemean).addE("battled").property("time", 1) .property("place", getGeoFloatArray(38.1f, 23.7f)).from("a").next(); g.V(hercules).as("a").V(hydra).addE("battled").property("time", 2) .property("place", getGeoFloatArray(37.7f, 23.9f)).from("a").next(); g.V(hercules).as("a").V(cerberus).addE("battled").property("time", 12) .property("place", getGeoFloatArray(39f, 22f)).from("a").next(); } g.V(pluto).as("a").V(jupiter).addE("brother").from("a").next(); g.V(pluto).as("a").V(neptune).addE("brother").from("a").next(); g.V(pluto).as("a").V(tartarus).addE("lives").property("reason", "no fear of death").from("a").next(); g.V(pluto).as("a").V(cerberus).addE("pet").from("a").next(); g.V(cerberus).as("a").V(tartarus).addE("lives").from("a").next(); if (supportsTransactions) { g.tx().commit(); } } catch (Exception e) { LOGGER.error(e.getMessage(), e); if (supportsTransactions) { g.tx().rollback(); } } } /** * Returns the geographical coordinates as a float array. */ protected float[] getGeoFloatArray(final float lat, final float lon) { return new float[]{ lat, lon }; } /** * Runs some traversal queries to get data from the graph. */ public void readElements() { try { if (g == null) { return; } LOGGER.info("reading elements"); // look up vertex by name can use a composite index in JanusGraph final Optional<Map<Object, Object>> v = g.V().has("name", "jupiter").valueMap(true).tryNext(); if (v.isPresent()) { LOGGER.info(v.get().toString()); } else { LOGGER.warn("jupiter not found"); } // look up an incident edge final Optional<Map<Object, Object>> edge = g.V().has("name", "hercules").outE("battled").as("e").inV() .has("name", "hydra").select("e").valueMap(true).tryNext(); if (edge.isPresent()) { LOGGER.info(edge.get().toString()); } else { LOGGER.warn("hercules battled hydra not found"); } // numerical range query can use a mixed index in JanusGraph final List<Object> list = g.V().has("age", P.gte(5000)).values("age").toList(); LOGGER.info(list.toString()); // pluto might be deleted final boolean plutoExists = g.V().has("name", "pluto").hasNext(); if (plutoExists) { LOGGER.info("pluto exists"); } else { LOGGER.warn("pluto not found"); } // look up jupiter's brothers final List<Object> brothers = g.V().has("name", "jupiter").both("brother").values("name").dedup().toList(); LOGGER.info("jupiter's brothers: " + brothers.toString()); } finally { // the default behavior automatically starts a transaction for // any graph interaction, so it is best to finish the transaction // even for read-only graph query operations if (supportsTransactions) { g.tx().rollback(); } } } /** * Makes an update to the existing graph structure. Does not create any * new vertices or edges. */ public void updateElements() { try { if (g == null) { return; } LOGGER.info("updating elements"); final long ts = System.currentTimeMillis(); g.V().has("name", "jupiter").property("ts", ts).iterate(); if (supportsTransactions) { g.tx().commit(); } } catch (Exception e) { LOGGER.error(e.getMessage(), e); if (supportsTransactions) { g.tx().rollback(); } } } /** * Deletes elements from the graph structure. When a vertex is deleted, * its incident edges are also deleted. */ public void deleteElements() { try { if (g == null) { return; } LOGGER.info("deleting elements"); // note that this will succeed whether or not pluto exists g.V().has("name", "pluto").drop().iterate(); if (supportsTransactions) { g.tx().commit(); } } catch (Exception e) { LOGGER.error(e.getMessage(), e); if (supportsTransactions) { g.tx().rollback(); } } } /** * Run the entire application: * 1. Open and initialize the graph * 2. Define the schema * 3. Build the graph * 4. Run traversal queries to get data from the graph * 5. Make updates to the graph * 6. Close the graph */ public void runApp() { try { // open and initialize the graph openGraph(); // define the schema before loading data if (supportsSchema) { createSchema(); } // build the graph structure createElements(); // read to see they were made readElements(); for (int i = 0; i < 3; i++) { try { Thread.sleep((long) (Math.random() * 500) + 500); } catch (InterruptedException e) { LOGGER.error(e.getMessage(), e); } // update some graph elements with changes updateElements(); // read to see the changes were made readElements(); } // delete some graph elements deleteElements(); // read to see the changes were made readElements(); // close the graph closeGraph(); } catch (Exception e) { LOGGER.error(e.getMessage(), e); } } }
5,573
14,668
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/keyed_service/core/simple_dependency_manager.h" #include "base/no_destructor.h" #include "base/trace_event/trace_event.h" #include "components/keyed_service/core/simple_factory_key.h" #ifndef NDEBUG #include "base/command_line.h" #include "base/files/file_util.h" namespace { // Dumps dependency information about our simple keyed services // into a dot file in the browser context directory. const char kDumpSimpleDependencyGraphFlag[] = "dump-simple-graph"; } // namespace #endif // NDEBUG void SimpleDependencyManager::DestroyKeyedServices(SimpleFactoryKey* key) { DependencyManager::DestroyContextServices(key); } // static SimpleDependencyManager* SimpleDependencyManager::GetInstance() { static base::NoDestructor<SimpleDependencyManager> factory; return factory.get(); } void SimpleDependencyManager::RegisterProfilePrefsForServices( user_prefs::PrefRegistrySyncable* pref_registry) { TRACE_EVENT0("browser", "SimpleDependencyManager::RegisterProfilePrefsForServices"); RegisterPrefsForServices(pref_registry); } void SimpleDependencyManager::CreateServicesForTest(SimpleFactoryKey* key) { TRACE_EVENT0("browser", "SimpleDependencyManager::CreateServices"); DependencyManager::CreateContextServices(key, true); } void SimpleDependencyManager::MarkContextLive(SimpleFactoryKey* key) { DependencyManager::MarkContextLive(key); } SimpleDependencyManager::SimpleDependencyManager() = default; SimpleDependencyManager::~SimpleDependencyManager() = default; #ifndef NDEBUG void SimpleDependencyManager::DumpContextDependencies(void* context) const { // Whenever we try to build a destruction ordering, we should also dump a // dependency graph to "/path/to/context/context-dependencies.dot". if (base::CommandLine::ForCurrentProcess()->HasSwitch( kDumpSimpleDependencyGraphFlag)) { base::FilePath dot_file = static_cast<const SimpleFactoryKey*>(context)->GetPath().AppendASCII( "simple-dependencies.dot"); DumpDependenciesAsGraphviz("SimpleDependencyManager", dot_file); } } #endif // NDEBUG
720
445
package me.wangyuwei.banner; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.support.v4.content.ContextCompat; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.view.View; /** * 作者: 巴掌 on 16/6/9 22:37 */ public class BannerLine extends View { private Paint mPaint; private float mWidth; private int mPageSize; private float mPageWidth = 0f; private int mPosition; private float mPositionOffset; private int mLineColor = ContextCompat.getColor(getContext(), R.color.banner_red); public BannerLine(Context context) { this(context, null); } public BannerLine(Context context, AttributeSet attrs) { this(context, attrs, 0); } public BannerLine(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); DisplayMetrics dm = getResources().getDisplayMetrics(); mWidth = dm.widthPixels; mPaint = new Paint(); mPaint.setColor(mLineColor); mPaint.setAntiAlias(true); mPaint.setStrokeWidth(1000f); } @Override protected void onDraw(Canvas canvas) { if (mPosition == 0) { canvas.drawLine((mPageSize - 3) * mPageWidth + mPageWidth * mPositionOffset, 0, (mPageSize - 2) * mPageWidth + mPageWidth * mPositionOffset, 0, mPaint); canvas.drawLine(0, 0, mPageWidth * mPositionOffset, 0, mPaint); } else if (mPosition == mPageSize - 2) { canvas.drawLine((mPosition - 1) * mPageWidth + mPageWidth * mPositionOffset, 0, mPosition * mPageWidth + mPageWidth * mPositionOffset, 0, mPaint); canvas.drawLine(0, 0, mPageWidth * mPositionOffset, 0, mPaint); } else { canvas.drawLine((mPosition - 1) * mPageWidth + mPageWidth * mPositionOffset, 0, mPosition * mPageWidth + mPageWidth * mPositionOffset, 0, mPaint); } } public void setPageWidth(int pageSize) { mPageSize = pageSize; calcPageWidth(); } private void calcPageWidth() { this.mPageWidth = this.mWidth / (this.mPageSize - 2); } public void setPageScrolled(int position, float positionOffset) { mPosition = position; mPositionOffset = positionOffset; invalidate(); } public void setLineColor(int lineColor) { mLineColor = lineColor; mPaint.setColor(mLineColor); } }
982
12,278
// Copyright (c) 2011-present, Facebook, Inc. All rights reserved. // This source code is licensed under both the GPLv2 (found in the // COPYING file in the root directory) and Apache 2.0 License // (found in the LICENSE.Apache file in the root directory). // // This file implements the "bridge" between Java and C++ // for ROCKSDB_NAMESPACE::TransactionDB. #include <jni.h> #include <functional> #include <memory> #include <utility> #include "include/org_rocksdb_TransactionDB.h" #include "rocksdb/options.h" #include "rocksdb/utilities/transaction.h" #include "rocksdb/utilities/transaction_db.h" #include "rocksjni/portal.h" /* * Class: org_rocksdb_TransactionDB * Method: open * Signature: (JJLjava/lang/String;)J */ jlong Java_org_rocksdb_TransactionDB_open__JJLjava_lang_String_2( JNIEnv* env, jclass, jlong joptions_handle, jlong jtxn_db_options_handle, jstring jdb_path) { auto* options = reinterpret_cast<ROCKSDB_NAMESPACE::Options*>(joptions_handle); auto* txn_db_options = reinterpret_cast<ROCKSDB_NAMESPACE::TransactionDBOptions*>( jtxn_db_options_handle); ROCKSDB_NAMESPACE::TransactionDB* tdb = nullptr; const char* db_path = env->GetStringUTFChars(jdb_path, nullptr); if (db_path == nullptr) { // exception thrown: OutOfMemoryError return 0; } ROCKSDB_NAMESPACE::Status s = ROCKSDB_NAMESPACE::TransactionDB::Open( *options, *txn_db_options, db_path, &tdb); env->ReleaseStringUTFChars(jdb_path, db_path); if (s.ok()) { return reinterpret_cast<jlong>(tdb); } else { ROCKSDB_NAMESPACE::RocksDBExceptionJni::ThrowNew(env, s); return 0; } } /* * Class: org_rocksdb_TransactionDB * Method: open * Signature: (JJLjava/lang/String;[[B[J)[J */ jlongArray Java_org_rocksdb_TransactionDB_open__JJLjava_lang_String_2_3_3B_3J( JNIEnv* env, jclass, jlong jdb_options_handle, jlong jtxn_db_options_handle, jstring jdb_path, jobjectArray jcolumn_names, jlongArray jcolumn_options_handles) { const char* db_path = env->GetStringUTFChars(jdb_path, nullptr); if (db_path == nullptr) { // exception thrown: OutOfMemoryError return nullptr; } const jsize len_cols = env->GetArrayLength(jcolumn_names); if (env->EnsureLocalCapacity(len_cols) != 0) { // out of memory env->ReleaseStringUTFChars(jdb_path, db_path); return nullptr; } jlong* jco = env->GetLongArrayElements(jcolumn_options_handles, nullptr); if (jco == nullptr) { // exception thrown: OutOfMemoryError env->ReleaseStringUTFChars(jdb_path, db_path); return nullptr; } std::vector<ROCKSDB_NAMESPACE::ColumnFamilyDescriptor> column_families; for (int i = 0; i < len_cols; i++) { const jobject jcn = env->GetObjectArrayElement(jcolumn_names, i); if (env->ExceptionCheck()) { // exception thrown: ArrayIndexOutOfBoundsException env->ReleaseLongArrayElements(jcolumn_options_handles, jco, JNI_ABORT); env->ReleaseStringUTFChars(jdb_path, db_path); return nullptr; } const jbyteArray jcn_ba = reinterpret_cast<jbyteArray>(jcn); jbyte* jcf_name = env->GetByteArrayElements(jcn_ba, nullptr); if (jcf_name == nullptr) { // exception thrown: OutOfMemoryError env->DeleteLocalRef(jcn); env->ReleaseLongArrayElements(jcolumn_options_handles, jco, JNI_ABORT); env->ReleaseStringUTFChars(jdb_path, db_path); return nullptr; } const int jcf_name_len = env->GetArrayLength(jcn_ba); if (env->EnsureLocalCapacity(jcf_name_len) != 0) { // out of memory env->ReleaseByteArrayElements(jcn_ba, jcf_name, JNI_ABORT); env->DeleteLocalRef(jcn); env->ReleaseLongArrayElements(jcolumn_options_handles, jco, JNI_ABORT); env->ReleaseStringUTFChars(jdb_path, db_path); return nullptr; } const std::string cf_name(reinterpret_cast<char*>(jcf_name), jcf_name_len); const ROCKSDB_NAMESPACE::ColumnFamilyOptions* cf_options = reinterpret_cast<ROCKSDB_NAMESPACE::ColumnFamilyOptions*>(jco[i]); column_families.push_back( ROCKSDB_NAMESPACE::ColumnFamilyDescriptor(cf_name, *cf_options)); env->ReleaseByteArrayElements(jcn_ba, jcf_name, JNI_ABORT); env->DeleteLocalRef(jcn); } env->ReleaseLongArrayElements(jcolumn_options_handles, jco, JNI_ABORT); auto* db_options = reinterpret_cast<ROCKSDB_NAMESPACE::DBOptions*>(jdb_options_handle); auto* txn_db_options = reinterpret_cast<ROCKSDB_NAMESPACE::TransactionDBOptions*>( jtxn_db_options_handle); std::vector<ROCKSDB_NAMESPACE::ColumnFamilyHandle*> handles; ROCKSDB_NAMESPACE::TransactionDB* tdb = nullptr; const ROCKSDB_NAMESPACE::Status s = ROCKSDB_NAMESPACE::TransactionDB::Open( *db_options, *txn_db_options, db_path, column_families, &handles, &tdb); // check if open operation was successful if (s.ok()) { const jsize resultsLen = 1 + len_cols; // db handle + column family handles std::unique_ptr<jlong[]> results = std::unique_ptr<jlong[]>(new jlong[resultsLen]); results[0] = reinterpret_cast<jlong>(tdb); for (int i = 1; i <= len_cols; i++) { results[i] = reinterpret_cast<jlong>(handles[i - 1]); } jlongArray jresults = env->NewLongArray(resultsLen); if (jresults == nullptr) { // exception thrown: OutOfMemoryError return nullptr; } env->SetLongArrayRegion(jresults, 0, resultsLen, results.get()); if (env->ExceptionCheck()) { // exception thrown: ArrayIndexOutOfBoundsException env->DeleteLocalRef(jresults); return nullptr; } return jresults; } else { ROCKSDB_NAMESPACE::RocksDBExceptionJni::ThrowNew(env, s); return nullptr; } } /* * Class: org_rocksdb_TransactionDB * Method: disposeInternal * Signature: (J)V */ void Java_org_rocksdb_TransactionDB_disposeInternal( JNIEnv*, jobject, jlong jhandle) { auto* txn_db = reinterpret_cast<ROCKSDB_NAMESPACE::TransactionDB*>(jhandle); assert(txn_db != nullptr); delete txn_db; } /* * Class: org_rocksdb_TransactionDB * Method: closeDatabase * Signature: (J)V */ void Java_org_rocksdb_TransactionDB_closeDatabase( JNIEnv* env, jclass, jlong jhandle) { auto* txn_db = reinterpret_cast<ROCKSDB_NAMESPACE::TransactionDB*>(jhandle); assert(txn_db != nullptr); ROCKSDB_NAMESPACE::Status s = txn_db->Close(); ROCKSDB_NAMESPACE::RocksDBExceptionJni::ThrowNew(env, s); } /* * Class: org_rocksdb_TransactionDB * Method: beginTransaction * Signature: (JJ)J */ jlong Java_org_rocksdb_TransactionDB_beginTransaction__JJ( JNIEnv*, jobject, jlong jhandle, jlong jwrite_options_handle) { auto* txn_db = reinterpret_cast<ROCKSDB_NAMESPACE::TransactionDB*>(jhandle); auto* write_options = reinterpret_cast<ROCKSDB_NAMESPACE::WriteOptions*>(jwrite_options_handle); ROCKSDB_NAMESPACE::Transaction* txn = txn_db->BeginTransaction(*write_options); return reinterpret_cast<jlong>(txn); } /* * Class: org_rocksdb_TransactionDB * Method: beginTransaction * Signature: (JJJ)J */ jlong Java_org_rocksdb_TransactionDB_beginTransaction__JJJ( JNIEnv*, jobject, jlong jhandle, jlong jwrite_options_handle, jlong jtxn_options_handle) { auto* txn_db = reinterpret_cast<ROCKSDB_NAMESPACE::TransactionDB*>(jhandle); auto* write_options = reinterpret_cast<ROCKSDB_NAMESPACE::WriteOptions*>(jwrite_options_handle); auto* txn_options = reinterpret_cast<ROCKSDB_NAMESPACE::TransactionOptions*>( jtxn_options_handle); ROCKSDB_NAMESPACE::Transaction* txn = txn_db->BeginTransaction(*write_options, *txn_options); return reinterpret_cast<jlong>(txn); } /* * Class: org_rocksdb_TransactionDB * Method: beginTransaction_withOld * Signature: (JJJ)J */ jlong Java_org_rocksdb_TransactionDB_beginTransaction_1withOld__JJJ( JNIEnv*, jobject, jlong jhandle, jlong jwrite_options_handle, jlong jold_txn_handle) { auto* txn_db = reinterpret_cast<ROCKSDB_NAMESPACE::TransactionDB*>(jhandle); auto* write_options = reinterpret_cast<ROCKSDB_NAMESPACE::WriteOptions*>(jwrite_options_handle); auto* old_txn = reinterpret_cast<ROCKSDB_NAMESPACE::Transaction*>(jold_txn_handle); ROCKSDB_NAMESPACE::TransactionOptions txn_options; ROCKSDB_NAMESPACE::Transaction* txn = txn_db->BeginTransaction(*write_options, txn_options, old_txn); // RocksJava relies on the assumption that // we do not allocate a new Transaction object // when providing an old_txn assert(txn == old_txn); return reinterpret_cast<jlong>(txn); } /* * Class: org_rocksdb_TransactionDB * Method: beginTransaction_withOld * Signature: (JJJJ)J */ jlong Java_org_rocksdb_TransactionDB_beginTransaction_1withOld__JJJJ( JNIEnv*, jobject, jlong jhandle, jlong jwrite_options_handle, jlong jtxn_options_handle, jlong jold_txn_handle) { auto* txn_db = reinterpret_cast<ROCKSDB_NAMESPACE::TransactionDB*>(jhandle); auto* write_options = reinterpret_cast<ROCKSDB_NAMESPACE::WriteOptions*>(jwrite_options_handle); auto* txn_options = reinterpret_cast<ROCKSDB_NAMESPACE::TransactionOptions*>( jtxn_options_handle); auto* old_txn = reinterpret_cast<ROCKSDB_NAMESPACE::Transaction*>(jold_txn_handle); ROCKSDB_NAMESPACE::Transaction* txn = txn_db->BeginTransaction(*write_options, *txn_options, old_txn); // RocksJava relies on the assumption that // we do not allocate a new Transaction object // when providing an old_txn assert(txn == old_txn); return reinterpret_cast<jlong>(txn); } /* * Class: org_rocksdb_TransactionDB * Method: getTransactionByName * Signature: (JLjava/lang/String;)J */ jlong Java_org_rocksdb_TransactionDB_getTransactionByName( JNIEnv* env, jobject, jlong jhandle, jstring jname) { auto* txn_db = reinterpret_cast<ROCKSDB_NAMESPACE::TransactionDB*>(jhandle); const char* name = env->GetStringUTFChars(jname, nullptr); if (name == nullptr) { // exception thrown: OutOfMemoryError return 0; } ROCKSDB_NAMESPACE::Transaction* txn = txn_db->GetTransactionByName(name); env->ReleaseStringUTFChars(jname, name); return reinterpret_cast<jlong>(txn); } /* * Class: org_rocksdb_TransactionDB * Method: getAllPreparedTransactions * Signature: (J)[J */ jlongArray Java_org_rocksdb_TransactionDB_getAllPreparedTransactions( JNIEnv* env, jobject, jlong jhandle) { auto* txn_db = reinterpret_cast<ROCKSDB_NAMESPACE::TransactionDB*>(jhandle); std::vector<ROCKSDB_NAMESPACE::Transaction*> txns; txn_db->GetAllPreparedTransactions(&txns); const size_t size = txns.size(); assert(size < UINT32_MAX); // does it fit in a jint? const jsize len = static_cast<jsize>(size); std::vector<jlong> tmp(len); for (jsize i = 0; i < len; ++i) { tmp[i] = reinterpret_cast<jlong>(txns[i]); } jlongArray jtxns = env->NewLongArray(len); if (jtxns == nullptr) { // exception thrown: OutOfMemoryError return nullptr; } env->SetLongArrayRegion(jtxns, 0, len, tmp.data()); if (env->ExceptionCheck()) { // exception thrown: ArrayIndexOutOfBoundsException env->DeleteLocalRef(jtxns); return nullptr; } return jtxns; } /* * Class: org_rocksdb_TransactionDB * Method: getLockStatusData * Signature: (J)Ljava/util/Map; */ jobject Java_org_rocksdb_TransactionDB_getLockStatusData( JNIEnv* env, jobject, jlong jhandle) { auto* txn_db = reinterpret_cast<ROCKSDB_NAMESPACE::TransactionDB*>(jhandle); const std::unordered_multimap<uint32_t, ROCKSDB_NAMESPACE::KeyLockInfo> lock_status_data = txn_db->GetLockStatusData(); const jobject jlock_status_data = ROCKSDB_NAMESPACE::HashMapJni::construct( env, static_cast<uint32_t>(lock_status_data.size())); if (jlock_status_data == nullptr) { // exception occurred return nullptr; } const ROCKSDB_NAMESPACE::HashMapJni::FnMapKV< const int32_t, const ROCKSDB_NAMESPACE::KeyLockInfo, jobject, jobject> fn_map_kv = [env](const std::pair<const int32_t, const ROCKSDB_NAMESPACE::KeyLockInfo>& pair) { const jobject jlong_column_family_id = ROCKSDB_NAMESPACE::LongJni::valueOf(env, pair.first); if (jlong_column_family_id == nullptr) { // an error occurred return std::unique_ptr<std::pair<jobject, jobject>>(nullptr); } const jobject jkey_lock_info = ROCKSDB_NAMESPACE::KeyLockInfoJni::construct(env, pair.second); if (jkey_lock_info == nullptr) { // an error occurred return std::unique_ptr<std::pair<jobject, jobject>>(nullptr); } return std::unique_ptr<std::pair<jobject, jobject>>( new std::pair<jobject, jobject>(jlong_column_family_id, jkey_lock_info)); }; if (!ROCKSDB_NAMESPACE::HashMapJni::putAll( env, jlock_status_data, lock_status_data.begin(), lock_status_data.end(), fn_map_kv)) { // exception occcurred return nullptr; } return jlock_status_data; } /* * Class: org_rocksdb_TransactionDB * Method: getDeadlockInfoBuffer * Signature: (J)[Lorg/rocksdb/TransactionDB/DeadlockPath; */ jobjectArray Java_org_rocksdb_TransactionDB_getDeadlockInfoBuffer( JNIEnv* env, jobject jobj, jlong jhandle) { auto* txn_db = reinterpret_cast<ROCKSDB_NAMESPACE::TransactionDB*>(jhandle); const std::vector<ROCKSDB_NAMESPACE::DeadlockPath> deadlock_info_buffer = txn_db->GetDeadlockInfoBuffer(); const jsize deadlock_info_buffer_len = static_cast<jsize>(deadlock_info_buffer.size()); jobjectArray jdeadlock_info_buffer = env->NewObjectArray( deadlock_info_buffer_len, ROCKSDB_NAMESPACE::DeadlockPathJni::getJClass(env), nullptr); if (jdeadlock_info_buffer == nullptr) { // exception thrown: OutOfMemoryError return nullptr; } jsize jdeadlock_info_buffer_offset = 0; auto buf_end = deadlock_info_buffer.end(); for (auto buf_it = deadlock_info_buffer.begin(); buf_it != buf_end; ++buf_it) { const ROCKSDB_NAMESPACE::DeadlockPath deadlock_path = *buf_it; const std::vector<ROCKSDB_NAMESPACE::DeadlockInfo> deadlock_infos = deadlock_path.path; const jsize deadlock_infos_len = static_cast<jsize>(deadlock_info_buffer.size()); jobjectArray jdeadlock_infos = env->NewObjectArray( deadlock_infos_len, ROCKSDB_NAMESPACE::DeadlockInfoJni::getJClass(env), nullptr); if (jdeadlock_infos == nullptr) { // exception thrown: OutOfMemoryError env->DeleteLocalRef(jdeadlock_info_buffer); return nullptr; } jsize jdeadlock_infos_offset = 0; auto infos_end = deadlock_infos.end(); for (auto infos_it = deadlock_infos.begin(); infos_it != infos_end; ++infos_it) { const ROCKSDB_NAMESPACE::DeadlockInfo deadlock_info = *infos_it; const jobject jdeadlock_info = ROCKSDB_NAMESPACE::TransactionDBJni::newDeadlockInfo( env, jobj, deadlock_info.m_txn_id, deadlock_info.m_cf_id, deadlock_info.m_waiting_key, deadlock_info.m_exclusive); if (jdeadlock_info == nullptr) { // exception occcurred env->DeleteLocalRef(jdeadlock_info_buffer); return nullptr; } env->SetObjectArrayElement(jdeadlock_infos, jdeadlock_infos_offset++, jdeadlock_info); if (env->ExceptionCheck()) { // exception thrown: ArrayIndexOutOfBoundsException or // ArrayStoreException env->DeleteLocalRef(jdeadlock_info); env->DeleteLocalRef(jdeadlock_info_buffer); return nullptr; } } const jobject jdeadlock_path = ROCKSDB_NAMESPACE::DeadlockPathJni::construct( env, jdeadlock_infos, deadlock_path.limit_exceeded); if (jdeadlock_path == nullptr) { // exception occcurred env->DeleteLocalRef(jdeadlock_info_buffer); return nullptr; } env->SetObjectArrayElement(jdeadlock_info_buffer, jdeadlock_info_buffer_offset++, jdeadlock_path); if (env->ExceptionCheck()) { // exception thrown: ArrayIndexOutOfBoundsException or ArrayStoreException env->DeleteLocalRef(jdeadlock_path); env->DeleteLocalRef(jdeadlock_info_buffer); return nullptr; } } return jdeadlock_info_buffer; } /* * Class: org_rocksdb_TransactionDB * Method: setDeadlockInfoBufferSize * Signature: (JI)V */ void Java_org_rocksdb_TransactionDB_setDeadlockInfoBufferSize( JNIEnv*, jobject, jlong jhandle, jint jdeadlock_info_buffer_size) { auto* txn_db = reinterpret_cast<ROCKSDB_NAMESPACE::TransactionDB*>(jhandle); txn_db->SetDeadlockInfoBufferSize(jdeadlock_info_buffer_size); }
6,899
658
/* * Copyright (c) 2003 Sun Microsystems, 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: * * Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistribution 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 Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. * ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. * SUN MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE * FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING * OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL * SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, * OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR * PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF * LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. */ #include <string.h> #include <math.h> #include <ipmitool/ipmi.h> #include <ipmitool/helper.h> #include <ipmitool/log.h> #include <ipmitool/ipmi_intf.h> #include <ipmitool/ipmi_sdr.h> #include <ipmitool/ipmi_sel.h> #include <ipmitool/ipmi_sensor.h> extern int verbose; void print_sensor_get_usage(); void print_sensor_thresh_usage(); // Macro's for Reading the current sensor Data. #define SCANNING_DISABLED 0x40 #define READING_UNAVAILABLE 0x20 #define INVALID_THRESHOLD "Invalid Threshold data values. Cannot Set Threshold Data." // static int ipmi_sensor_get_sensor_reading_factors( struct ipmi_intf * intf, struct sdr_record_full_sensor * sensor, uint8_t reading) { struct ipmi_rq req; struct ipmi_rs * rsp; uint8_t req_data[2]; char id[17]; if (!intf || !sensor) return -1; memset(id, 0, sizeof(id)); memcpy(id, sensor->id_string, 16); req_data[0] = sensor->cmn.keys.sensor_num; req_data[1] = reading; memset(&req, 0, sizeof(req)); req.msg.netfn = IPMI_NETFN_SE; req.msg.lun = sensor->cmn.keys.lun; req.msg.cmd = GET_SENSOR_FACTORS; req.msg.data = req_data; req.msg.data_len = sizeof(req_data); rsp = intf->sendrecv(intf, &req); if (!rsp) { lprintf(LOG_ERR, "Error updating reading factor for sensor %s (#%02x)", id, sensor->cmn.keys.sensor_num); return -1; } else if (rsp->ccode) { return -1; } else { /* Update SDR copy with updated Reading Factors for this reading */ /* Note: * The Format of the returned data is exactly as in the SDR definition (Little Endian Format), * therefore we can use raw copy operation here. * Note: rsp->data[0] would point to the next valid entry in the sampling table */ // BUGBUG: uses 'hardcoded' length information from SDR Definition memcpy(&sensor->mtol, &rsp->data[1], sizeof(sensor->mtol)); memcpy(&sensor->bacc, &rsp->data[3], sizeof(sensor->bacc)); return 0; } } static struct ipmi_rs * ipmi_sensor_set_sensor_thresholds(struct ipmi_intf *intf, uint8_t sensor, uint8_t threshold, uint8_t setting, uint8_t target, uint8_t lun, uint8_t channel) { struct ipmi_rq req; static struct sensor_set_thresh_rq set_thresh_rq; struct ipmi_rs *rsp; uint8_t bridged_request = 0; uint32_t save_addr; uint32_t save_channel; memset(&set_thresh_rq, 0, sizeof (set_thresh_rq)); set_thresh_rq.sensor_num = sensor; set_thresh_rq.set_mask = threshold; if (threshold == UPPER_NON_RECOV_SPECIFIED) set_thresh_rq.upper_non_recov = setting; else if (threshold == UPPER_CRIT_SPECIFIED) set_thresh_rq.upper_crit = setting; else if (threshold == UPPER_NON_CRIT_SPECIFIED) set_thresh_rq.upper_non_crit = setting; else if (threshold == LOWER_NON_CRIT_SPECIFIED) set_thresh_rq.lower_non_crit = setting; else if (threshold == LOWER_CRIT_SPECIFIED) set_thresh_rq.lower_crit = setting; else if (threshold == LOWER_NON_RECOV_SPECIFIED) set_thresh_rq.lower_non_recov = setting; else return NULL; if (BRIDGE_TO_SENSOR(intf, target, channel)) { bridged_request = 1; save_addr = intf->target_addr; intf->target_addr = target; save_channel = intf->target_channel; intf->target_channel = channel; } memset(&req, 0, sizeof (req)); req.msg.netfn = IPMI_NETFN_SE; req.msg.lun = lun; req.msg.cmd = SET_SENSOR_THRESHOLDS; req.msg.data = (uint8_t *) & set_thresh_rq; req.msg.data_len = sizeof (set_thresh_rq); rsp = intf->sendrecv(intf, &req); if (bridged_request) { intf->target_addr = save_addr; intf->target_channel = save_channel; } return rsp; } static int ipmi_sensor_print_fc_discrete(struct ipmi_intf *intf, struct sdr_record_common_sensor *sensor, uint8_t sdr_record_type) { struct sensor_reading *sr; sr = ipmi_sdr_read_sensor_value(intf, sensor, sdr_record_type, 3); if (!sr) { return -1; } if (csv_output) { printf("%s", sr->s_id); if (sr->s_reading_valid) { if (sr->s_has_analog_value) { /* don't show discrete component */ printf(",%s,%s,%s", sr->s_a_str, sr->s_a_units, "ok"); } else { printf(",0x%x,%s,0x%02x%02x", sr->s_reading, "discrete", sr->s_data2, sr->s_data3); } } else { printf(",%s,%s,%s", "na", "discrete", "na"); } printf(",%s,%s,%s,%s,%s,%s", "na", "na", "na", "na", "na", "na"); printf("\n"); } else { if (verbose == 0) { /* output format * id value units status thresholds.... */ printf("%-16s ", sr->s_id); if (sr->s_reading_valid) { if (sr->s_has_analog_value) { /* don't show discrete component */ printf("| %-10s | %-10s | %-6s", sr->s_a_str, sr->s_a_units, "ok"); } else { printf("| 0x%-8x | %-10s | 0x%02x%02x", sr->s_reading, "discrete", sr->s_data2, sr->s_data3); } } else { printf("| %-10s | %-10s | %-6s", "na", "discrete", "na"); } printf("| %-10s| %-10s| %-10s| %-10s| %-10s| %-10s", "na", "na", "na", "na", "na", "na"); printf("\n"); } else { printf("Sensor ID : %s (0x%x)\n", sr->s_id, sensor->keys.sensor_num); printf(" Entity ID : %d.%d\n", sensor->entity.id, sensor->entity.instance); printf(" Sensor Type (Discrete): %s\n", ipmi_get_sensor_type(intf, sensor->sensor. type)); if( sr->s_reading_valid ) { if (sr->s_has_analog_value) { printf(" Sensor Reading : %s %s\n", sr->s_a_str, sr->s_a_units); } ipmi_sdr_print_discrete_state(intf, "States Asserted", sensor->sensor.type, sensor->event_type, sr->s_data2, sr->s_data3); printf("\n"); } else { printf(" Unable to read sensor: Device Not Present\n\n"); } } } return (sr->s_reading_valid ? 0 : -1 ); } static void print_thresh_setting(struct sdr_record_full_sensor *full, uint8_t thresh_is_avail, uint8_t setting, const char *field_sep, const char *analog_fmt, const char *discrete_fmt, const char *na_fmt) { printf("%s", field_sep); if (!thresh_is_avail) { printf(na_fmt, "na"); return; } if (full && !UNITS_ARE_DISCRETE(&full->cmn)) { printf(analog_fmt, sdr_convert_sensor_reading (full, setting)); } else { printf(discrete_fmt, setting); } } static void dump_sensor_fc_thredshold_csv( int thresh_available, const char *thresh_status, struct ipmi_rs *rsp, struct sensor_reading *sr) { printf("%s", sr->s_id); if (sr->s_reading_valid) { if (sr->s_has_analog_value) printf(",%.3f,%s,%s", sr->s_a_val, sr->s_a_units, thresh_status); else printf(",0x%x,%s,%s", sr->s_reading, sr->s_a_units, thresh_status); } else { printf(",%s,%s,%s", "na", sr->s_a_units, "na"); } if (thresh_available && sr->full) { #define PTS(bit, dataidx) { \ print_thresh_setting(sr->full, rsp->data[0] & (bit), \ rsp->data[(dataidx)], ",", "%.3f", "0x%x", "%s"); \ } PTS(LOWER_NON_RECOV_SPECIFIED, 3); PTS(LOWER_CRIT_SPECIFIED, 2); PTS(LOWER_NON_CRIT_SPECIFIED, 1); PTS(UPPER_NON_CRIT_SPECIFIED, 4); PTS(UPPER_CRIT_SPECIFIED, 5); PTS(UPPER_NON_RECOV_SPECIFIED, 6); #undef PTS } else { printf(",%s,%s,%s,%s,%s,%s", "na", "na", "na", "na", "na", "na"); } printf("\n"); } /* output format * id value units status thresholds.... */ static void dump_sensor_fc_thredshold( int thresh_available, const char *thresh_status, struct ipmi_rs *rsp, struct sensor_reading *sr) { printf("%-16s ", sr->s_id); if (sr->s_reading_valid) { if (sr->s_has_analog_value) printf("| %-10.3f | %-10s | %-6s", sr->s_a_val, sr->s_a_units, thresh_status); else printf("| 0x%-8x | %-10s | %-6s", sr->s_reading, sr->s_a_units, thresh_status); } else { printf("| %-10s | %-10s | %-6s", "na", sr->s_a_units, "na"); } if (thresh_available && sr->full) { #define PTS(bit, dataidx) { \ print_thresh_setting(sr->full, rsp->data[0] & (bit), \ rsp->data[(dataidx)], "| ", "%-10.3f", "0x%-8x", "%-10s"); \ } PTS(LOWER_NON_RECOV_SPECIFIED, 3); PTS(LOWER_CRIT_SPECIFIED, 2); PTS(LOWER_NON_CRIT_SPECIFIED, 1); PTS(UPPER_NON_CRIT_SPECIFIED, 4); PTS(UPPER_CRIT_SPECIFIED, 5); PTS(UPPER_NON_RECOV_SPECIFIED, 6); #undef PTS } else { printf("| %-10s| %-10s| %-10s| %-10s| %-10s| %-10s", "na", "na", "na", "na", "na", "na"); } printf("\n"); } static void dump_sensor_fc_thredshold_verbose( int thresh_available, const char *thresh_status, struct ipmi_intf *intf, struct sdr_record_common_sensor *sensor, struct ipmi_rs *rsp, struct sensor_reading *sr) { printf("Sensor ID : %s (0x%x)\n", sr->s_id, sensor->keys.sensor_num); printf(" Entity ID : %d.%d\n", sensor->entity.id, sensor->entity.instance); printf(" Sensor Type (Threshold) : %s\n", ipmi_get_sensor_type(intf, sensor->sensor.type)); printf(" Sensor Reading : "); if (sr->s_reading_valid) { if (sr->full) { uint16_t raw_tol = __TO_TOL(sr->full->mtol); if (sr->s_has_analog_value) { double tol = sdr_convert_sensor_tolerance(sr->full, raw_tol); printf("%.*f (+/- %.*f) %s\n", (sr->s_a_val == (int) sr->s_a_val) ? 0 : 3, sr->s_a_val, (tol == (int) tol) ? 0 : 3, tol, sr->s_a_units); } else { printf("0x%x (+/- 0x%x) %s\n", sr->s_reading, raw_tol, sr->s_a_units); } } else { printf("0x%x %s\n", sr->s_reading, sr->s_a_units); } printf(" Status : %s\n", thresh_status); if (thresh_available) { if (sr->full) { #define PTS(bit, dataidx, str) { \ print_thresh_setting(sr->full, rsp->data[0] & (bit), \ rsp->data[(dataidx)], \ (str), "%.3f\n", "0x%x\n", "%s\n"); \ } PTS(LOWER_NON_RECOV_SPECIFIED, 3, " Lower Non-Recoverable : "); PTS(LOWER_CRIT_SPECIFIED, 2, " Lower Critical : "); PTS(LOWER_NON_CRIT_SPECIFIED, 1, " Lower Non-Critical : "); PTS(UPPER_NON_CRIT_SPECIFIED, 4, " Upper Non-Critical : "); PTS(UPPER_CRIT_SPECIFIED, 5, " Upper Critical : "); PTS(UPPER_NON_RECOV_SPECIFIED, 6, " Upper Non-Recoverable : "); #undef PTS } ipmi_sdr_print_sensor_hysteresis(sensor, sr->full, sr->full ? sr->full->threshold.hysteresis.positive : sr->compact->threshold.hysteresis.positive, "Positive Hysteresis"); ipmi_sdr_print_sensor_hysteresis(sensor, sr->full, sr->full ? sr->full->threshold.hysteresis.negative : sr->compact->threshold.hysteresis.negative, "Negative Hysteresis"); } else { printf(" Sensor Threshold Settings not available\n"); } } else { printf(" Unable to read sensor: Device Not Present\n\n"); } ipmi_sdr_print_sensor_event_status(intf, sensor->keys. sensor_num, sensor->sensor.type, sensor->event_type, ANALOG_SENSOR, sensor->keys.owner_id, sensor->keys.lun, sensor->keys.channel); ipmi_sdr_print_sensor_event_enable(intf, sensor->keys. sensor_num, sensor->sensor.type, sensor->event_type, ANALOG_SENSOR, sensor->keys.owner_id, sensor->keys.lun, sensor->keys.channel); printf("\n"); } static int ipmi_sensor_print_fc_threshold(struct ipmi_intf *intf, struct sdr_record_common_sensor *sensor, uint8_t sdr_record_type) { int thresh_available = 1; struct ipmi_rs *rsp; struct sensor_reading *sr; sr = ipmi_sdr_read_sensor_value(intf, sensor, sdr_record_type, 3); if (!sr) { return -1; } const char *thresh_status = ipmi_sdr_get_thresh_status(sr, "ns"); /* * Get sensor thresholds */ rsp = ipmi_sdr_get_sensor_thresholds(intf, sensor->keys.sensor_num, sensor->keys.owner_id, sensor->keys.lun, sensor->keys.channel); if (!rsp || rsp->ccode || !rsp->data_len) thresh_available = 0; if (csv_output) { dump_sensor_fc_thredshold_csv(thresh_available, thresh_status, rsp, sr); } else { if (verbose == 0) { dump_sensor_fc_thredshold(thresh_available, thresh_status, rsp, sr); } else { dump_sensor_fc_thredshold_verbose(thresh_available, thresh_status, intf, sensor, rsp, sr); } } return (sr->s_reading_valid ? 0 : -1 ); } int ipmi_sensor_print_fc(struct ipmi_intf *intf, struct sdr_record_common_sensor *sensor, uint8_t sdr_record_type) { if (IS_THRESHOLD_SENSOR(sensor)) return ipmi_sensor_print_fc_threshold(intf, sensor, sdr_record_type); else return ipmi_sensor_print_fc_discrete(intf, sensor, sdr_record_type); } static int ipmi_sensor_list(struct ipmi_intf *intf) { struct sdr_get_rs *header; struct ipmi_sdr_iterator *itr; int rc = 0; lprintf(LOG_DEBUG, "Querying SDR for sensor list"); itr = ipmi_sdr_start(intf, 0); if (!itr) { lprintf(LOG_ERR, "Unable to open SDR for reading"); return -1; } while ((header = ipmi_sdr_get_next_header(intf, itr))) { uint8_t *rec; rec = ipmi_sdr_get_record(intf, header, itr); if (!rec) { lprintf(LOG_DEBUG, "rec == NULL"); continue; } switch (header->type) { case SDR_RECORD_TYPE_FULL_SENSOR: case SDR_RECORD_TYPE_COMPACT_SENSOR: ipmi_sensor_print_fc(intf, (struct sdr_record_common_sensor *) rec, header->type); break; } free(rec); rec = NULL; /* fix for CR6604909: */ /* mask failure of individual reads in sensor list command */ /* rc = (r == 0) ? rc : r; */ } ipmi_sdr_end(itr); return rc; } static const struct valstr threshold_vals[] = { {UPPER_NON_RECOV_SPECIFIED, "Upper Non-Recoverable"}, {UPPER_CRIT_SPECIFIED, "Upper Critical"}, {UPPER_NON_CRIT_SPECIFIED, "Upper Non-Critical"}, {LOWER_NON_RECOV_SPECIFIED, "Lower Non-Recoverable"}, {LOWER_CRIT_SPECIFIED, "Lower Critical"}, {LOWER_NON_CRIT_SPECIFIED, "Lower Non-Critical"}, {0x00, NULL}, }; static int __ipmi_sensor_set_threshold(struct ipmi_intf *intf, uint8_t num, uint8_t mask, uint8_t setting, uint8_t target, uint8_t lun, uint8_t channel) { struct ipmi_rs *rsp; rsp = ipmi_sensor_set_sensor_thresholds(intf, num, mask, setting, target, lun, channel); if (!rsp) { lprintf(LOG_ERR, "Error setting threshold"); return -1; } if (rsp->ccode) { lprintf(LOG_ERR, "Error setting threshold: %s", val2str(rsp->ccode, completion_code_vals)); return -1; } return 0; } static uint8_t __ipmi_sensor_threshold_value_to_raw(struct sdr_record_full_sensor *full, double value) { if (!UNITS_ARE_DISCRETE(&full->cmn)) { /* Has an analog reading */ /* Has an analog reading and supports mx+b */ return sdr_convert_sensor_value_to_raw(full, value); } else { /* Does not have an analog reading and/or does not support mx+b */ if (value > 255) { return 255; } else if (value < 0) { return 0; } else { return (uint8_t )value; } } } static int ipmi_sensor_set_threshold(struct ipmi_intf *intf, int argc, char **argv) { char *id, *thresh; uint8_t settingMask = 0; double setting1 = 0.0, setting2 = 0.0, setting3 = 0.0; int allUpper = 0, allLower = 0; int ret = 0; struct ipmi_rs *rsp; int i =0; double val[10] = {0}; struct sdr_record_list *sdr; if (argc < 3 || !strcmp(argv[0], "help")) { print_sensor_thresh_usage(); return 0; } id = argv[0]; thresh = argv[1]; if (!strcmp(thresh, "upper")) { if (argc < 5) { lprintf(LOG_ERR, "usage: sensor thresh <id> upper <unc> <ucr> <unr>"); return -1; } allUpper = 1; if (str2double(argv[2], &setting1) != 0) { lprintf(LOG_ERR, "Given unc '%s' is invalid.", argv[2]); return (-1); } if (str2double(argv[3], &setting2) != 0) { lprintf(LOG_ERR, "Given ucr '%s' is invalid.", argv[3]); return (-1); } if (str2double(argv[4], &setting3) != 0) { lprintf(LOG_ERR, "Given unr '%s' is invalid.", argv[4]); return (-1); } } else if (!strcmp(thresh, "lower")) { if (argc < 5) { lprintf(LOG_ERR, "usage: sensor thresh <id> lower <lnr> <lcr> <lnc>"); return -1; } allLower = 1; if (str2double(argv[2], &setting1) != 0) { lprintf(LOG_ERR, "Given lnc '%s' is invalid.", argv[2]); return (-1); } if (str2double(argv[3], &setting2) != 0) { lprintf(LOG_ERR, "Given lcr '%s' is invalid.", argv[3]); return (-1); } if (str2double(argv[4], &setting3) != 0) { lprintf(LOG_ERR, "Given lnr '%s' is invalid.", argv[4]); return (-1); } } else { if (!strcmp(thresh, "unr")) settingMask = UPPER_NON_RECOV_SPECIFIED; else if (!strcmp(thresh, "ucr")) settingMask = UPPER_CRIT_SPECIFIED; else if (!strcmp(thresh, "unc")) settingMask = UPPER_NON_CRIT_SPECIFIED; else if (!strcmp(thresh, "lnc")) settingMask = LOWER_NON_CRIT_SPECIFIED; else if (!strcmp(thresh, "lcr")) settingMask = LOWER_CRIT_SPECIFIED; else if (!strcmp(thresh, "lnr")) settingMask = LOWER_NON_RECOV_SPECIFIED; else { lprintf(LOG_ERR, "Valid threshold '%s' for sensor '%s' not specified!", thresh, id); return -1; } if (str2double(argv[2], &setting1) != 0) { lprintf(LOG_ERR, "Given %s threshold value '%s' is invalid.", thresh, argv[2]); return (-1); } } printf("Locating sensor record '%s'...\n", id); /* lookup by sensor name */ sdr = ipmi_sdr_find_sdr_byid(intf, id); if (!sdr) { lprintf(LOG_ERR, "Sensor data record not found!"); return -1; } if (sdr->type != SDR_RECORD_TYPE_FULL_SENSOR) { lprintf(LOG_ERR, "Invalid sensor type %02x", sdr->type); return -1; } if (!IS_THRESHOLD_SENSOR(sdr->record.common)) { lprintf(LOG_ERR, "Invalid sensor event type %02x", sdr->record.common->event_type); return -1; } if (allUpper) { settingMask = UPPER_NON_CRIT_SPECIFIED; printf("Setting sensor \"%s\" %s threshold to %.3f\n", sdr->record.full->id_string, val2str(settingMask, threshold_vals), setting1); ret = __ipmi_sensor_set_threshold(intf, sdr->record.common->keys. sensor_num, settingMask, __ipmi_sensor_threshold_value_to_raw(sdr->record.full, setting1), sdr->record.common->keys.owner_id, sdr->record.common->keys.lun, sdr->record.common->keys.channel); settingMask = UPPER_CRIT_SPECIFIED; printf("Setting sensor \"%s\" %s threshold to %.3f\n", sdr->record.full->id_string, val2str(settingMask, threshold_vals), setting2); ret = __ipmi_sensor_set_threshold(intf, sdr->record.common->keys. sensor_num, settingMask, __ipmi_sensor_threshold_value_to_raw(sdr->record.full, setting2), sdr->record.common->keys.owner_id, sdr->record.common->keys.lun, sdr->record.common->keys.channel); settingMask = UPPER_NON_RECOV_SPECIFIED; printf("Setting sensor \"%s\" %s threshold to %.3f\n", sdr->record.full->id_string, val2str(settingMask, threshold_vals), setting3); ret = __ipmi_sensor_set_threshold(intf, sdr->record.common->keys. sensor_num, settingMask, __ipmi_sensor_threshold_value_to_raw(sdr->record.full, setting3), sdr->record.common->keys.owner_id, sdr->record.common->keys.lun, sdr->record.common->keys.channel); } else if (allLower) { settingMask = LOWER_NON_RECOV_SPECIFIED; printf("Setting sensor \"%s\" %s threshold to %.3f\n", sdr->record.full->id_string, val2str(settingMask, threshold_vals), setting1); ret = __ipmi_sensor_set_threshold(intf, sdr->record.common->keys. sensor_num, settingMask, __ipmi_sensor_threshold_value_to_raw(sdr->record.full, setting1), sdr->record.common->keys.owner_id, sdr->record.common->keys.lun, sdr->record.common->keys.channel); settingMask = LOWER_CRIT_SPECIFIED; printf("Setting sensor \"%s\" %s threshold to %.3f\n", sdr->record.full->id_string, val2str(settingMask, threshold_vals), setting2); ret = __ipmi_sensor_set_threshold(intf, sdr->record.common->keys. sensor_num, settingMask, __ipmi_sensor_threshold_value_to_raw(sdr->record.full, setting2), sdr->record.common->keys.owner_id, sdr->record.common->keys.lun, sdr->record.common->keys.channel); settingMask = LOWER_NON_CRIT_SPECIFIED; printf("Setting sensor \"%s\" %s threshold to %.3f\n", sdr->record.full->id_string, val2str(settingMask, threshold_vals), setting3); ret = __ipmi_sensor_set_threshold(intf, sdr->record.common->keys. sensor_num, settingMask, __ipmi_sensor_threshold_value_to_raw(sdr->record.full, setting3), sdr->record.common->keys.owner_id, sdr->record.common->keys.lun, sdr->record.common->keys.channel); } else { /* * Current implementation doesn't check for the valid setting of upper non critical and other thresholds. * In the below logic: * Get all the current reading of the sensor i.e. unc, uc, lc,lnc. * Validate the values given by the user. * If the values are not correct, then popup with the Error message and return. */ /* * Get current reading */ rsp = ipmi_sdr_get_sensor_reading_ipmb(intf, sdr->record.common->keys.sensor_num, sdr->record.common->keys.owner_id, sdr->record.common->keys.lun,sdr->record.common->keys.channel); rsp = ipmi_sdr_get_sensor_thresholds(intf, sdr->record.common->keys.sensor_num, sdr->record.common->keys.owner_id, sdr->record.common->keys.lun, sdr->record.common->keys.channel); if (!rsp || rsp->ccode) { lprintf(LOG_ERR, "Sensor data record not found!"); return -1; } for(i=1;i<=6;i++) { val[i] = sdr_convert_sensor_reading(sdr->record.full, rsp->data[i]); if(val[i] < 0) val[i] = 0; } /* Check for the valid Upper non recovarable Value.*/ if( (settingMask & UPPER_NON_RECOV_SPECIFIED) ) { if( (rsp->data[0] & UPPER_NON_RECOV_SPECIFIED) && (( (rsp->data[0] & UPPER_CRIT_SPECIFIED) && ( setting1 <= val[5])) || ( (rsp->data[0] & UPPER_NON_CRIT_SPECIFIED) && ( setting1 <= val[4]))) ) { lprintf(LOG_ERR, INVALID_THRESHOLD); return -1; } } else if( (settingMask & UPPER_CRIT_SPECIFIED) ) { /* Check for the valid Upper critical Value.*/ if( (rsp->data[0] & UPPER_CRIT_SPECIFIED) && (((rsp->data[0] & UPPER_NON_RECOV_SPECIFIED)&& ( setting1 >= val[6])) || ((rsp->data[0] & UPPER_NON_CRIT_SPECIFIED)&&( setting1 <= val[4]))) ) { lprintf(LOG_ERR, INVALID_THRESHOLD); return -1; } } else if( (settingMask & UPPER_NON_CRIT_SPECIFIED) ) { /* Check for the valid Upper non critical Value.*/ if( (rsp->data[0] & UPPER_NON_CRIT_SPECIFIED) && (((rsp->data[0] & UPPER_NON_RECOV_SPECIFIED)&&( setting1 >= val[6])) || ((rsp->data[0] & UPPER_CRIT_SPECIFIED)&&( setting1 >= val[5])) || ((rsp->data[0] & LOWER_NON_CRIT_SPECIFIED)&&( setting1 <= val[1]))) ) { lprintf(LOG_ERR, INVALID_THRESHOLD); return -1; } } else if( (settingMask & LOWER_NON_CRIT_SPECIFIED) ) { /* Check for the valid lower non critical Value.*/ if( (rsp->data[0] & LOWER_NON_CRIT_SPECIFIED) && (((rsp->data[0] & LOWER_CRIT_SPECIFIED)&&( setting1 <= val[2])) || ((rsp->data[0] & LOWER_NON_RECOV_SPECIFIED)&&( setting1 <= val[3]))|| ((rsp->data[0] & UPPER_NON_CRIT_SPECIFIED)&&( setting1 >= val[4]))) ) { lprintf(LOG_ERR, INVALID_THRESHOLD); return -1; } } else if( (settingMask & LOWER_CRIT_SPECIFIED) ) { /* Check for the valid lower critical Value.*/ if( (rsp->data[0] & LOWER_CRIT_SPECIFIED) && (((rsp->data[0] & LOWER_NON_CRIT_SPECIFIED)&&( setting1 >= val[1])) || ((rsp->data[0] & LOWER_NON_RECOV_SPECIFIED)&&( setting1 <= val[3]))) ) { lprintf(LOG_ERR, INVALID_THRESHOLD); return -1; } } else if( (settingMask & LOWER_NON_RECOV_SPECIFIED) ) { /* Check for the valid lower non recovarable Value.*/ if( (rsp->data[0] & LOWER_NON_RECOV_SPECIFIED) && (((rsp->data[0] & LOWER_NON_CRIT_SPECIFIED)&&( setting1 >= val[1])) || ((rsp->data[0] & LOWER_CRIT_SPECIFIED)&&( setting1 >= val[2]))) ) { lprintf(LOG_ERR, INVALID_THRESHOLD); return -1; } } else { /* None of this Then Return with error messages.*/ lprintf(LOG_ERR, INVALID_THRESHOLD); return -1; } printf("Setting sensor \"%s\" %s threshold to %.3f\n", sdr->record.full->id_string, val2str(settingMask, threshold_vals), setting1); ret = __ipmi_sensor_set_threshold(intf, sdr->record.common->keys. sensor_num, settingMask, __ipmi_sensor_threshold_value_to_raw(sdr->record.full, setting1), sdr->record.common->keys.owner_id, sdr->record.common->keys.lun, sdr->record.common->keys.channel); } return ret; } static int ipmi_sensor_get_reading(struct ipmi_intf *intf, int argc, char **argv) { struct sdr_record_list *sdr; int i, rc=0; if (argc < 1 || !strcmp(argv[0], "help")) { lprintf(LOG_NOTICE, "sensor reading <id> ... [id]"); lprintf(LOG_NOTICE, " id : name of desired sensor"); return -1; } for (i = 0; i < argc; i++) { sdr = ipmi_sdr_find_sdr_byid(intf, argv[i]); if (!sdr) { lprintf(LOG_ERR, "Sensor \"%s\" not found!", argv[i]); rc = -1; continue; } switch (sdr->type) { case SDR_RECORD_TYPE_FULL_SENSOR: case SDR_RECORD_TYPE_COMPACT_SENSOR: { struct sensor_reading *sr; struct sdr_record_common_sensor *sensor = sdr->record.common; sr = ipmi_sdr_read_sensor_value(intf, sensor, sdr->type, 3); if (!sr) { rc = -1; continue; } if (!sr->full) continue; if (!sr->s_reading_valid) continue; if (!sr->s_has_analog_value) { lprintf(LOG_ERR, "Sensor \"%s\" is a discrete sensor!", argv[i]); continue; } if (csv_output) printf("%s,%s\n", argv[i], sr->s_a_str); else printf("%-16s | %s\n", argv[i], sr->s_a_str); break; } default: continue; } } return rc; } static int ipmi_sensor_get(struct ipmi_intf *intf, int argc, char **argv) { int i, v; int rc = 0; struct sdr_record_list *sdr; if (argc < 1) { lprintf(LOG_ERR, "Not enough parameters given."); print_sensor_get_usage(); return (-1); } else if (!strcmp(argv[0], "help")) { print_sensor_get_usage(); return 0; } printf("Locating sensor record...\n"); /* lookup by sensor name */ for (i = 0; i < argc; i++) { sdr = ipmi_sdr_find_sdr_byid(intf, argv[i]); if (!sdr) { lprintf(LOG_ERR, "Sensor data record \"%s\" not found!", argv[i]); rc = -1; continue; } /* need to set verbose level to 1 */ v = verbose; verbose = 1; switch (sdr->type) { case SDR_RECORD_TYPE_FULL_SENSOR: case SDR_RECORD_TYPE_COMPACT_SENSOR: if (ipmi_sensor_print_fc(intf, (struct sdr_record_common_sensor *) sdr->record.common, sdr->type)) { rc = -1; } break; default: if (ipmi_sdr_print_listentry(intf, sdr) < 0) { rc = (-1); } break; } verbose = v; sdr = NULL; } return rc; } int ipmi_sensor_main(struct ipmi_intf *intf, int argc, char **argv) { int rc = 0; if (argc == 0) { rc = ipmi_sensor_list(intf); } else if (!strcmp(argv[0], "help")) { lprintf(LOG_NOTICE, "Sensor Commands: list thresh get reading"); } else if (!strcmp(argv[0], "list")) { rc = ipmi_sensor_list(intf); } else if (!strcmp(argv[0], "thresh")) { rc = ipmi_sensor_set_threshold(intf, argc - 1, &argv[1]); } else if (!strcmp(argv[0], "get")) { rc = ipmi_sensor_get(intf, argc - 1, &argv[1]); } else if (!strcmp(argv[0], "reading")) { rc = ipmi_sensor_get_reading(intf, argc - 1, &argv[1]); } else { lprintf(LOG_ERR, "Invalid sensor command: %s", argv[0]); rc = -1; } return rc; } /* print_sensor_get_usage - print usage for # ipmitool sensor get NAC; * * @returns: void */ void print_sensor_get_usage() { lprintf(LOG_NOTICE, "sensor get <id> ... [id]"); lprintf(LOG_NOTICE, " id : name of desired sensor"); } /* print_sensor_thresh_set_usage - print usage for # ipmitool sensor thresh; * * @returns: void */ void print_sensor_thresh_usage() { lprintf(LOG_NOTICE, "sensor thresh <id> <threshold> <setting>"); lprintf(LOG_NOTICE, " id : name of the sensor for which threshold is to be set"); lprintf(LOG_NOTICE, " threshold : which threshold to set"); lprintf(LOG_NOTICE, " unr = upper non-recoverable"); lprintf(LOG_NOTICE, " ucr = upper critical"); lprintf(LOG_NOTICE, " unc = upper non-critical"); lprintf(LOG_NOTICE, " lnc = lower non-critical"); lprintf(LOG_NOTICE, " lcr = lower critical"); lprintf(LOG_NOTICE, " lnr = lower non-recoverable"); lprintf(LOG_NOTICE, " setting : the value to set the threshold to"); lprintf(LOG_NOTICE, ""); lprintf(LOG_NOTICE, "sensor thresh <id> lower <lnr> <lcr> <lnc>"); lprintf(LOG_NOTICE, " Set all lower thresholds at the same time"); lprintf(LOG_NOTICE, ""); lprintf(LOG_NOTICE, "sensor thresh <id> upper <unc> <ucr> <unr>"); lprintf(LOG_NOTICE, " Set all upper thresholds at the same time"); lprintf(LOG_NOTICE, ""); }
14,291
14,793
<filename>weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/card/WxMpCardCodeCheckcodeResult.java package me.chanjar.weixin.mp.bean.card; import com.google.gson.annotations.SerializedName; import lombok.Data; import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; import java.io.Serializable; import java.util.List; @Data public class WxMpCardCodeCheckcodeResult implements Serializable { private static final long serialVersionUID = -5128692403997016750L; /** * 已经成功存入的code数目 */ @SerializedName("exist_code") private List<String> existCode; @SerializedName("not_exist_code") private List<String> notExistCode; public static WxMpCardCodeCheckcodeResult fromJson(String json) { return WxMpGsonBuilder.create().fromJson(json, WxMpCardCodeCheckcodeResult.class); } @Override public String toString() { return WxMpGsonBuilder.create().toJson(this); } }
339
36,052
<filename>src/unpatched-fonts/Noto/config.json [Subtables] ligatures: [ "Ligature Substitution lookup 14 subtable", "Ligature Substitution lookup 15 subtable", "Ligature Substitution lookup 16 subtable" ]
74
1,405
<reponame>jarekankowski/pegasus_spyware<filename>sample4/decompiled_raw/assets/LenovoSafeWidget115/sources/com/lenovo/lps/reaper/sdk/a/a.java<gh_stars>1000+ package com.lenovo.lps.reaper.sdk.a; /* loaded from: classes.dex */ public final class a { private int a; private String b; private String c; private int d; public a() { this(3); } private a(int i) { this.d = 3; } public a(int i, String str, String str2, int i2) { this.a = i; this.b = str; this.c = str2; this.d = i2; } public final void a() { this.a = 0; } public final void a(int i) { this.a = i; } public final void a(String str) { this.b = str; } public final void b(String str) { this.c = str; } public final boolean b() { return this.a > 0 && this.a <= 5; } public final int c() { return this.a; } public final String d() { return this.b; } public final String e() { return this.c; } public final int f() { return this.d; } public final String toString() { if (!b()) { return ""; } StringBuilder sb = new StringBuilder(200); sb.append("("); sb.append(this.a); sb.append("!"); sb.append(com.lenovo.lps.reaper.sdk.e.a.a(this.b)); sb.append("!"); sb.append(com.lenovo.lps.reaper.sdk.e.a.a(this.c)); sb.append("!"); sb.append(this.d); sb.append(")"); return sb.toString(); } }
818
1,775
# Copyright (c) OpenMMLab. All rights reserved. from .bottom_up_aic import BottomUpAicDataset from .bottom_up_coco import BottomUpCocoDataset from .bottom_up_coco_wholebody import BottomUpCocoWholeBodyDataset from .bottom_up_crowdpose import BottomUpCrowdPoseDataset from .bottom_up_mhp import BottomUpMhpDataset __all__ = [ 'BottomUpCocoDataset', 'BottomUpCrowdPoseDataset', 'BottomUpMhpDataset', 'BottomUpAicDataset', 'BottomUpCocoWholeBodyDataset' ]
176
5,766
// // ActiveRecord.h // // Library: ActiveRecord // Package: ActiveRecord // Module: ActiveRecord // // Copyright (c) 2020, Applied Informatics Software Engineering GmbH. // and Contributors. // // SPDX-License-Identifier: BSL-1.0 // #include "Poco/ActiveRecord/ActiveRecord.h" #include "Poco/NumberFormatter.h" #include "Poco/Exception.h" using namespace Poco::Data::Keywords; using namespace std::string_literals; namespace Poco { namespace ActiveRecord { void ActiveRecordBase::attach(Context::Ptr pContext) { if (_pContext) throw Poco::IllegalStateException("ActiveRecord already has a Context"); if (!pContext) throw Poco::InvalidArgumentException("Cannot attach to a null Context"); _pContext = pContext; } void ActiveRecordBase::detach() { _pContext.reset(); } void ActiveRecordBase::create(Context::Ptr pContext) { attach(pContext); insert(); } bool ActiveRecordBase::isValid() const { return true; } std::string KeylessActiveRecord::toString() const { return ""s; } } } // namespace Poco::ActiveRecord
333
4,392
/*************************************************************************** Copyright (c) 2021, The OpenBLAS Project All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the OpenBLAS project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OPENBLAS PROJECT 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 <stdio.h> #include <immintrin.h> #include "common.h" int CNAME(BLASLONG m, BLASLONG n, IFLOAT *a, BLASLONG lda, IFLOAT *b){ BLASLONG i, j; IFLOAT *boffset0, *boffset1; boffset0 = b; BLASLONG n32 = n & ~31; BLASLONG m4 = m & ~3; BLASLONG m2 = m & ~1; uint32_t permute_table[] = { 0x00, 0x01, 0x02, 0x03, 0x10, 0x11, 0x12, 0x13, 0x04, 0x05, 0x06, 0x07, 0x14, 0x15, 0x16, 0x17, 0x08, 0x09, 0x0a, 0x0b, 0x18, 0x19, 0x1a, 0x1b, 0x0c, 0x0d, 0x0e, 0x0f, 0x1c, 0x1d, 0x1e, 0x1f, }; __m512i idx_lo = _mm512_loadu_si512(permute_table); __m512i idx_hi = _mm512_loadu_si512(permute_table + 16); for (j = 0; j < n32; j += 32) { /* process 2x16 n at the same time */ boffset1 = boffset0 + m * 16; for (i = 0; i < m4; i += 4) { /* bf16 fma need special memory layout: * for memory layout like below: * a00, a01, a02, a03, a04, a05 .... * a10, a11, a12, a13, a14, a15 .... * need to copy as: * a00, a10, a01, a11, a02, a12, a03, a13, ... */ __m512i a0 = _mm512_loadu_si512(&a[(i + 0)*lda + j]); __m512i a1 = _mm512_loadu_si512(&a[(i + 1)*lda + j]); __m512i a2 = _mm512_loadu_si512(&a[(i + 2)*lda + j]); __m512i a3 = _mm512_loadu_si512(&a[(i + 3)*lda + j]); __m512i a00 = _mm512_unpacklo_epi16(a0, a1); __m512i a01 = _mm512_unpackhi_epi16(a0, a1); __m512i a10 = _mm512_unpacklo_epi16(a2, a3); __m512i a11 = _mm512_unpackhi_epi16(a2, a3); a0 = _mm512_permutex2var_epi32(a00, idx_lo, a01); a1 = _mm512_permutex2var_epi32(a00, idx_hi, a01); a2 = _mm512_permutex2var_epi32(a10, idx_lo, a11); a3 = _mm512_permutex2var_epi32(a10, idx_hi, a11); _mm512_storeu_si512(boffset0, a0); _mm512_storeu_si512(boffset1, a1); _mm512_storeu_si512(boffset0 + 32, a2); _mm512_storeu_si512(boffset1 + 32, a3); boffset0 += 64; boffset1 += 64; } for (; i < m2; i += 2) { __m512i a0 = _mm512_loadu_si512(&a[(i + 0)*lda + j]); __m512i a1 = _mm512_loadu_si512(&a[(i + 1)*lda + j]); __m512i a00 = _mm512_unpacklo_epi16(a0, a1); __m512i a01 = _mm512_unpackhi_epi16(a0, a1); a0 = _mm512_permutex2var_epi32(a00, idx_lo, a01); a1 = _mm512_permutex2var_epi32(a00, idx_hi, a01); _mm512_storeu_si512(boffset0, a0); _mm512_storeu_si512(boffset1, a1); boffset0 += 32; boffset1 += 32; } for (; i < m; i++) { /* just copy the only remains row */ __m256i a0 = _mm256_loadu_si256((void *)&a[(i + 0)*lda + j]); __m256i a1 = _mm256_loadu_si256((void *)&a[(i + 0)*lda + j + 16]); _mm256_storeu_si256((void *)boffset0, a0); _mm256_storeu_si256((void *)boffset1, a1); boffset0 += 16; boffset1 += 16; } boffset0 = boffset1; } if (j < n) { uint32_t remains = n - j; __mmask32 r_mask = (1UL << remains) - 1; if (remains > 16) { boffset1 = boffset0 + m * 16; uint32_t tail1 = remains - 16; __mmask16 w_mask1 = (1UL << tail1) - 1; for (i = 0; i < m2; i += 2) { __m512i a0 = _mm512_maskz_loadu_epi16(r_mask, &a[(i + 0)*lda + j]); __m512i a1 = _mm512_maskz_loadu_epi16(r_mask, &a[(i + 1)*lda + j]); __m512i a00 = _mm512_unpacklo_epi16(a0, a1); __m512i a01 = _mm512_unpackhi_epi16(a0, a1); a0 = _mm512_permutex2var_epi32(a00, idx_lo, a01); a1 = _mm512_permutex2var_epi32(a00, idx_hi, a01); _mm512_storeu_si512(boffset0, a0); _mm512_mask_storeu_epi32(boffset1, w_mask1, a1); boffset0 += 32; boffset1 += 2 * tail1; } for (; i < m; i++) { __m256i a0 = _mm256_loadu_si256((void *)&a[(i + 0)*lda + j]); __m256i a1 = _mm256_maskz_loadu_epi16(w_mask1, (void *)&a[(i + 0)*lda + j + 16]); _mm256_storeu_si256((void *)boffset0, a0); _mm256_mask_storeu_epi16((void *)boffset1, w_mask1, a1); boffset0 += 16; boffset1 += tail1; } } else { __mmask16 w_mask = (1UL << remains ) - 1; for (i = 0; i < m2; i += 2) { __m512i a0 = _mm512_maskz_loadu_epi16(r_mask, &a[(i + 0)*lda + j]); __m512i a1 = _mm512_maskz_loadu_epi16(r_mask, &a[(i + 1)*lda + j]); __m512i a00 = _mm512_unpacklo_epi16(a0, a1); __m512i a01 = _mm512_unpackhi_epi16(a0, a1); a0 = _mm512_permutex2var_epi32(a00, idx_lo, a01); _mm512_mask_storeu_epi32(boffset0, w_mask, a0); boffset0 += 2 * remains; } for (; i < m; i++) { __m256i a0 = _mm256_maskz_loadu_epi16(w_mask, &a[(i + 0)*lda + j]); _mm256_mask_storeu_epi16(boffset0, w_mask, a0); boffset0 += remains; } } } return 0; }
2,919
777
// 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 "chrome/browser/chromeos/policy/active_directory_policy_manager.h" #include <string> #include <utility> #include "base/logging.h" #include "base/memory/ptr_util.h" #include "chromeos/dbus/auth_policy_client.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "components/policy/core/common/policy_bundle.h" #include "components/policy/core/common/policy_types.h" #include "components/policy/policy_constants.h" namespace policy { ActiveDirectoryPolicyManager::~ActiveDirectoryPolicyManager() {} // static std::unique_ptr<ActiveDirectoryPolicyManager> ActiveDirectoryPolicyManager::CreateForDevicePolicy( std::unique_ptr<CloudPolicyStore> store) { return base::WrapUnique( new ActiveDirectoryPolicyManager(EmptyAccountId(), std::move(store))); } // static std::unique_ptr<ActiveDirectoryPolicyManager> ActiveDirectoryPolicyManager::CreateForUserPolicy( const AccountId& account_id, std::unique_ptr<CloudPolicyStore> store) { return base::WrapUnique( new ActiveDirectoryPolicyManager(account_id, std::move(store))); } void ActiveDirectoryPolicyManager::Init(SchemaRegistry* registry) { ConfigurationPolicyProvider::Init(registry); store_->AddObserver(this); if (!store_->is_initialized()) { store_->Load(); } // Does nothing if |store_| hasn't yet initialized. PublishPolicy(); RefreshPolicies(); } void ActiveDirectoryPolicyManager::Shutdown() { store_->RemoveObserver(this); ConfigurationPolicyProvider::Shutdown(); } bool ActiveDirectoryPolicyManager::IsInitializationComplete( PolicyDomain domain) const { if (domain == POLICY_DOMAIN_CHROME) return store_->is_initialized(); return true; } void ActiveDirectoryPolicyManager::RefreshPolicies() { chromeos::DBusThreadManager* thread_manager = chromeos::DBusThreadManager::Get(); DCHECK(thread_manager); chromeos::AuthPolicyClient* auth_policy_client = thread_manager->GetAuthPolicyClient(); DCHECK(auth_policy_client); if (account_id_ == EmptyAccountId()) { auth_policy_client->RefreshDevicePolicy( base::Bind(&ActiveDirectoryPolicyManager::OnPolicyRefreshed, weak_ptr_factory_.GetWeakPtr())); } else { auth_policy_client->RefreshUserPolicy( account_id_, base::Bind(&ActiveDirectoryPolicyManager::OnPolicyRefreshed, weak_ptr_factory_.GetWeakPtr())); } } void ActiveDirectoryPolicyManager::OnStoreLoaded( CloudPolicyStore* cloud_policy_store) { DCHECK_EQ(store_.get(), cloud_policy_store); PublishPolicy(); } void ActiveDirectoryPolicyManager::OnStoreError( CloudPolicyStore* cloud_policy_store) { DCHECK_EQ(store_.get(), cloud_policy_store); // Publish policy (even though it hasn't changed) in order to signal load // complete on the ConfigurationPolicyProvider interface. Technically, this is // only required on the first load, but doesn't hurt in any case. PublishPolicy(); } ActiveDirectoryPolicyManager::ActiveDirectoryPolicyManager( const AccountId& account_id, std::unique_ptr<CloudPolicyStore> store) : account_id_(account_id), store_(std::move(store)), weak_ptr_factory_(this) {} void ActiveDirectoryPolicyManager::PublishPolicy() { if (!store_->is_initialized()) { return; } std::unique_ptr<PolicyBundle> bundle = base::MakeUnique<PolicyBundle>(); PolicyMap& policy_map = bundle->Get(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string())); policy_map.CopyFrom(store_->policy_map()); // Overwrite the source which is POLICY_SOURCE_CLOUD by default. // TODO(tnagel): Rename CloudPolicyStore to PolicyStore and make the source // configurable, then drop PolicyMap::SetSourceForAll(). policy_map.SetSourceForAll(POLICY_SOURCE_ACTIVE_DIRECTORY); SetEnterpriseUsersDefaults(&policy_map); UpdatePolicy(std::move(bundle)); } void ActiveDirectoryPolicyManager::OnPolicyRefreshed(bool success) { if (!success) { LOG(ERROR) << "Active Directory policy refresh failed."; } // Load independently of success or failure to keep up to date with whatever // has happened on the authpolicyd / session manager side. store_->Load(); } } // namespace policy
1,399
5,422
// -*- mode: objective-c -*- @import Cocoa; @interface ComplexModificationsAssetsOutlineViewDelegate : NSObject <NSOutlineViewDelegate> @end
48
1,088
/* Copyright 2020 Alibaba Group Holding Limited. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef GRAPHLEARN_CORE_GRAPH_STORAGE_TOPO_STORAGE_H_ #define GRAPHLEARN_CORE_GRAPH_STORAGE_TOPO_STORAGE_H_ #include <cstdint> #include <string> #include <vector> #include "graphlearn/core/graph/storage/edge_storage.h" #include "graphlearn/core/graph/storage/types.h" namespace graphlearn { namespace io { class TopoStorage { public: virtual ~TopoStorage() = default; /// Do some re-organization after data fixed. virtual void Build(EdgeStorage* edges) = 0; /// An EDGE is made up of [ src_id, attributes, dst_id ]. /// Before inserted to the TopoStorage, it should be inserted to /// EdgeStorage to get an unique id. And then use the id and value here. virtual void Add(IdType edge_id, EdgeValue* value) = 0; /// Get all the neighbor node ids of a given id. virtual Array<IdType> GetNeighbors(IdType src_id) const = 0; /// Get all the neighbor edge ids of a given id. virtual Array<IdType> GetOutEdges(IdType src_id) const = 0; /// Get the out-degree value of a given id. virtual IndexType GetOutDegree(IdType src_id) const = 0; /// Get the in-degree value of a given id. virtual IndexType GetInDegree(IdType dst_id) const = 0; /// Get all the distinct ids that appear as the source id of an edge. /// For example, 6 edges like /// [1 2] /// [2 3] /// [2 4] /// [1 3] /// [3 1] /// [3 2] /// GetAllSrcIds() --> {1, 2, 3} virtual const IdList* GetAllSrcIds() const = 0; /// Get all the distinct ids that appear as the destination id of an edge. /// For the above example, GetAllDstIds() --> {2, 3, 4, 1} virtual const IdList* GetAllDstIds() const = 0; /// Get the out-degree values of all ids corresponding to GetAllSrcIds(). /// For the above example, GetAllOutDegrees() --> {2, 2, 2} virtual const IndexList* GetAllOutDegrees() const = 0; /// Get the in-degree values of all ids corresponding to GetAllDstIds(). /// For the above example, GetAllInDegrees() --> {2, 2, 1, 1} virtual const IndexList* GetAllInDegrees() const = 0; }; TopoStorage* NewMemoryTopoStorage(); TopoStorage* NewCompressedMemoryTopoStorage(); } // namespace io } // namespace graphlearn #endif // GRAPHLEARN_CORE_GRAPH_STORAGE_TOPO_STORAGE_H_
915
1,738
<filename>dev/Gems/CloudGemMetric/v1/Code/Include/CloudGemMetric/MetricsAttribute.h /* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates, or * a third party where indicated. * * 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 <AzCore/std/string/string.h> #include <AzCore/JSON/document.h> #include <AzCore/Serialization/SerializeContext.h> #include <AzCore/RTTI/BehaviorContext.h> #include <AzCore/Serialization/EditContext.h> #include <AzCore/RTTI/BehaviorContext.h> #include <AzCore/std/containers/vector.h> /* MetricsAttribute represents one attribute e.g. name: position_x, value: 10 Attribute value can be int, double or string */ namespace CloudGemMetric { class MetricsAttribute { public: AZ_TYPE_INFO(MetricsAttribute, "{f55007a4-f282-11e7-8c3f-9a214cf093ae}") MetricsAttribute(const AZStd::string& name, int intVal) : m_valType(VAL_TYPE::INT), m_name(name), m_intVal(intVal) { }; MetricsAttribute(const AZStd::string& name, double doubleVal) : m_valType(VAL_TYPE::DOUBLE), m_name(name), m_doubleVal(doubleVal) { }; MetricsAttribute(const AZStd::string& name, const AZStd::string& strVal) : m_valType(VAL_TYPE::STR), m_name(name), m_strVal(strVal) { }; MetricsAttribute() {}; ~MetricsAttribute() {}; void SetName(const char* name) { m_name = name; }; const AZStd::string GetName() const { return m_name; }; void SetVal(const char* val) { m_valType = VAL_TYPE::STR; m_strVal = val; }; void SetVal(int val) { m_valType = VAL_TYPE::INT; m_intVal = val; }; void SetVal(double val) { m_valType = VAL_TYPE::DOUBLE; m_doubleVal = val; }; int GetSizeInBytes() const { int nameSize = m_name.size() * sizeof(char); int valSize = 0; if (m_valType == VAL_TYPE::INT) { valSize = sizeof(int); } else if (m_valType == VAL_TYPE::DOUBLE) { valSize = sizeof(double); } else { valSize = m_strVal.size() * sizeof(char); } return nameSize + valSize; }; void SerializeToJson(rapidjson::Document& doc, rapidjson::Value& metricsObjVal) const { if (m_valType == VAL_TYPE::INT) { metricsObjVal.AddMember(rapidjson::StringRef(m_name.c_str()), m_intVal, doc.GetAllocator()); } else if (m_valType == VAL_TYPE::DOUBLE) { metricsObjVal.AddMember(rapidjson::StringRef(m_name.c_str()), m_doubleVal, doc.GetAllocator()); } else { metricsObjVal.AddMember(rapidjson::StringRef(m_name.c_str()), rapidjson::StringRef(m_strVal.c_str()), doc.GetAllocator()); } }; bool ReadFromJson(const rapidjson::Value& name, const rapidjson::Value& val) { if (!val.IsInt() && !val.IsDouble() && !val.IsString()) { return false; } if (val.IsInt()) { m_valType = VAL_TYPE::INT; m_intVal = val.GetInt(); } else if (val.IsDouble()) { m_valType = VAL_TYPE::DOUBLE; m_doubleVal = val.GetDouble(); } else { m_valType = VAL_TYPE::STR; m_strVal = val.GetString(); } m_name = name.GetString(); return true; }; private: enum class VAL_TYPE { INT, DOUBLE, STR }; private: VAL_TYPE m_valType; AZStd::string m_name; int m_intVal{ 0 }; double m_doubleVal{ 0 }; AZStd::string m_strVal; }; } // namespace CloudGemMetric
2,376
5,872
{ "AD_DURATION": "Durada de l'anunci", "AD_PROGRESS": "Anunci [AD_ON] de [NUM_ADS]", "AD_TIME": "Anunci: [AD_TIME]", "AUTO_QUALITY": "Automàtic", "BACK": "Torna", "CAPTIONS": "Subtítols", "CAST": "Emet…", "ENTER_LOOP_MODE": "Reprodueix en bucle el vídeo actual", "ENTER_PICTURE_IN_PICTURE": "Entra al mode de pantalla en pantalla", "EXIT_FULL_SCREEN": "Surt del mode de pantalla completa", "EXIT_LOOP_MODE": "Deixa de reproduir en bucle el vídeo actual", "EXIT_PICTURE_IN_PICTURE": "Surt del mode de pantalla en pantalla", "FAST_FORWARD": "Avança ràpidament", "FULL_SCREEN": "Pantalla completa", "LANGUAGE": "Idioma", "LIVE": "En directe", "LOOP": "Reprodueix en bucle", "MORE_SETTINGS": "Més opcions de configuració", "MULTIPLE_LANGUAGES": "Diversos idiomes", "MUTE": "Silencia", "NOT_APPLICABLE": "No aplicable", "OFF": "Desactivat", "ON": "Activat", "PAUSE": "Atura", "PICTURE_IN_PICTURE": "Pantalla en pantalla", "PLAY": "Reprodueix", "PLAYBACK_RATE": "Velocitat de reproducció", "RESOLUTION": "Resolució", "REWIND": "Rebobina", "SEEK": "Cerca", "SKIP_AD": "Omet l'anunci", "SKIP_TO_LIVE": "Passa a l'emissió en directe", "UNDETERMINED_LANGUAGE": "Sense especificar", "UNMUTE": "Deixa de silenciar", "UNRECOGNIZED_LANGUAGE": "No reconegut", "VOLUME": "Volum" }
612
1,623
<reponame>Erick-Mendez/Pangolin #pragma once #include <pangolin/platform.h> #define GLdouble GLfloat #define glClearDepth glClearDepthf #define glFrustum glFrustumf #define glColor4fv(a) glColor4f(a[0], a[1], a[2], a[3]) #define glColor3fv(a) glColor4f(a[0], a[1], a[2], 1.0f) #define glColor3f(a,b,c) glColor4f(a, b, c, 1.0f) #define glGenFramebuffersEXT glGenFramebuffers #define glDeleteFramebuffersEXT glDeleteFramebuffers #define glBindFramebufferEXT glBindFramebuffer #define glFramebufferTexture2DEXT glFramebufferTexture2D #define glGetDoublev glGetFloatv #include <pangolin/gl/compat/gl2engine.h> inline void glRectf(GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2) { GLfloat verts[] = { x1,y1, x2,y1, x2,y2, x1,y2 }; glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(2, GL_FLOAT, 0, verts); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); glDisableClientState(GL_VERTEX_ARRAY); } inline void glRecti(int x1, int y1, int x2, int y2) { GLfloat verts[] = { (float)x1,(float)y1, (float)x2,(float)y1, (float)x2,(float)y2, (float)x1,(float)y2 }; glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(2, GL_FLOAT, 0, verts); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); glDisableClientState(GL_VERTEX_ARRAY); }
657
386
<reponame>jkrude/charts<filename>src/main/java/eu/hansolo/fx/geometry/FlatteningPathIterator.java /* * Copyright (c) 2017 by <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eu.hansolo.fx.geometry; import eu.hansolo.fx.geometry.Path.WindingRule; import java.util.NoSuchElementException; public class FlatteningPathIterator implements PathIterator { static final int GROW_SIZE = 24; // Multiple of bezierCurve & quadCurve curve size volatile double hold[] = new double[14]; // The cache of interpolated coords PathIterator src; // The source iterator double flatness; // Flatness parameter double squareflat; // Square of the flatness parameter for testing against squared lengths int limit; // Maximum number of recursion levels hold field double curx, cury; // The ending x,y of the last segment double movx, movy; // The x,y of the last move segment int holdType; // The type of the curve being held for interpolation int holdEnd; // The index of the last curve segment being held for interpolation int holdIndex; // The index of the curve segment that was last interpolated. This is the curve segment ready to be returned in the next call to currentSegment(). int levels[]; // The recursion level at which each curve being held in storage was generated. int levelIndex; // The index of the entry in the levels array of the curve segment at the holdIndex boolean done; // True when iteration is done public FlatteningPathIterator(PathIterator src, double flatness) { this(src, flatness, 10); } public FlatteningPathIterator(PathIterator src, double flatness, int limit) { if (flatness < 0) { throw new IllegalArgumentException("flatness must be >= 0"); } if (limit < 0) { throw new IllegalArgumentException("limit must be >= 0"); } this.src = src; this.flatness = flatness; this.squareflat = flatness * flatness; this.limit = limit; this.levels = new int[limit + 1]; // prime the first path segment next(false); } public double getFlatness() { return Math.sqrt(squareflat); } public int getRecursionLimit() { return limit; } void ensureHoldCapacity(final int WANT) { if (holdIndex - WANT < 0) { int have = hold.length - holdIndex; int newsize = hold.length + GROW_SIZE; double newhold[] = new double[newsize]; System.arraycopy(hold, holdIndex, newhold, holdIndex + GROW_SIZE, have); hold = newhold; holdIndex += GROW_SIZE; holdEnd += GROW_SIZE; } } public boolean isDone() { return done; } public void next() { next(true); } private void next(final boolean DO_NEXT) { int level; if (holdIndex >= holdEnd) { if (DO_NEXT) { src.next(); } if (src.isDone()) { done = true; return; } holdType = src.currentSegment(hold); levelIndex = 0; levels[0] = 0; } switch (holdType) { case MOVE_TO: case LINE_TO: curx = hold[0]; cury = hold[1]; if (holdType == MOVE_TO) { movx = curx; movy = cury; } holdIndex = 0; holdEnd = 0; break; case CLOSE: curx = movx; cury = movy; holdIndex = 0; holdEnd = 0; break; case QUAD_TO: if (holdIndex >= holdEnd) { holdIndex = hold.length - 6; holdEnd = hold.length - 2; hold[holdIndex + 0] = curx; hold[holdIndex + 1] = cury; hold[holdIndex + 2] = hold[0]; hold[holdIndex + 3] = hold[1]; hold[holdIndex + 4] = curx = hold[2]; hold[holdIndex + 5] = cury = hold[3]; } level = levels[levelIndex]; while (level < limit) { if (QuadCurve.getFlatnessSq(hold, holdIndex) < squareflat) { break; } ensureHoldCapacity(4); QuadCurve.subdivide(hold, holdIndex, hold, holdIndex - 4, hold, holdIndex); holdIndex -= 4; level++; levels[levelIndex] = level; levelIndex++; levels[levelIndex] = level; } holdIndex += 4; levelIndex--; break; case BEZIER_TO: if (holdIndex >= holdEnd) { holdIndex = hold.length - 8; holdEnd = hold.length - 2; hold[holdIndex + 0] = curx; hold[holdIndex + 1] = cury; hold[holdIndex + 2] = hold[0]; hold[holdIndex + 3] = hold[1]; hold[holdIndex + 4] = hold[2]; hold[holdIndex + 5] = hold[3]; hold[holdIndex + 6] = curx = hold[4]; hold[holdIndex + 7] = cury = hold[5]; } level = levels[levelIndex]; while (level < limit) { if (BezierCurve.getFlatnessSq(hold, holdIndex) < squareflat) { break; } ensureHoldCapacity(6); BezierCurve.subdivide(hold, holdIndex, hold, holdIndex - 6, hold, holdIndex); holdIndex -= 6; level++; levels[levelIndex] = level; levelIndex++; levels[levelIndex] = level; } holdIndex += 6; levelIndex--; break; } } public WindingRule getWindingRule() { return src.getWindingRule(); } public int currentSegment(final double[] COORDS) { if (isDone()) { throw new NoSuchElementException("flattening iterator out of bounds"); } int type = holdType; if (type != CLOSE) { COORDS[0] = hold[holdIndex + 0]; COORDS[1] = hold[holdIndex + 1]; if (type != MOVE_TO) { type = LINE_TO; } } return type; } }
3,521
5,169
<reponame>Gantios/Specs { "name": "Forge", "version": "1.0.0", "summary": "Get up and rendering with Metal via Metalkit without worrying about triple buffering / semaphores", "description": "Forge's Renderer class sets up triple buffering rendering so you don't have to. You also get nice Cinder / Processing / Openframeworks functions you can hook into and do stuff.", "homepage": "https://github.com/Hi-Rez/Forge", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "<NAME>": "<EMAIL>" }, "social_media_url": "https://twitter.com/rezaali", "source": { "git": "https://github.com/Hi-Rez/Forge.git", "tag": "1.0.0" }, "platforms": { "osx": "10.14", "ios": "12.4", "tvos": "12.4" }, "osx": { "source_files": [ "Forge/*.h", "Forge/Shared/**/*.{h,m,swift}", "Forge/macOS/**/*.{h,m,swift}" ], "resources": "Forge/macOS/*.xib" }, "ios": { "source_files": [ "Forge/*.h", "Forge/Shared/**/*.{h,m,swift}", "Forge/iOS/**/*.{h,m,swift}" ], "resources": "Forge/iOS/*.xib" }, "tvos": { "source_files": [ "Forge/*.h", "Forge/Shared/**/*.{h,m,swift}", "Forge/tvOS/**/*.{h,m,swift}" ], "resources": "Forge/tvOS/*.xib" }, "frameworks": [ "Metal", "MetalKit" ], "module_name": "Forge", "swift_versions": "5.1", "swift_version": "5.1" }
649
517
<gh_stars>100-1000 /* * Copyright (C) 2012. * All rights reserved. */ package ro.isdc.wro.extensions.processor.css; import ro.isdc.wro.extensions.processor.support.sass.RubySassEngine; import ro.isdc.wro.model.resource.processor.ResourcePostProcessor; import ro.isdc.wro.model.resource.processor.ResourcePreProcessor; /** * A processor to support the bourbon (http://thoughtbot.com/bourbon/) mixins library for sass. * Using this processor automatically provides sass support, so there is no need to use both this one and * the {@link RubySassCssProcessor}. * <p/> * @author <NAME> * @created 16/05/12 * @since 1.4.7 */ public class BourbonCssProcessor extends RubySassCssProcessor implements ResourcePreProcessor, ResourcePostProcessor { /** * The processor alias. */ public static final String ALIAS = "bourbonCss"; private static final String BOURBON_GEM_REQUIRE = "bourbon"; /** * A getter used for lazy loading, overrides RubySassEngine#getEngine() and ensure the * bourbon gem is imported (required). */ @Override protected RubySassEngine newEngine() { final RubySassEngine engine = super.newEngine(); engine.addRequire(BOURBON_GEM_REQUIRE); return engine; } }
394
3,897
/* mbed Microcontroller Library * Copyright (c) 2006-2020 ARM Limited * * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @file */ #ifndef MBED_BLE_DEVICE_INSTANCE_BASE__ #define MBED_BLE_DEVICE_INSTANCE_BASE__ #include "ble/BLE.h" namespace ble { /** * @addtogroup ble * @{ * @addtogroup porting * @{ */ /** * Private interface used to implement the BLE class. * * The BLE class delegates all its abstract operations to an instance of this * abstract class, which every vendor port of Mbed BLE shall implement. * * The vendor port shall also define an implementation of the freestanding function * createBLEInstance(). The BLE API uses this singleton function to gain * access to a concrete implementation of this class defined in the vendor port. * * @attention This class is part of the porting API and is not meant to be used * by end users of BLE API. * * @see BLE */ class BLEInstanceBase { public: /** * Process ALL pending events living in the vendor BLE subsystem. * * Return once all pending events have been consumed. * * @see BLE::processEvents() */ virtual void processEvents() = 0; /** * Signal to BLE that events needing processing are available. * * The vendor port shall call this function whenever there are events * ready to be processed in the internal stack or BLE subsystem. As a result * of this call, the callback registered by the end user via * BLE::onEventsToProcess will be invoked. * @deprecated Call BLE::signalEventsToProcess directly. */ virtual void signalEventsToProcess() { BLE::Instance().signalEventsToProcess(); }; /** * Start the initialization of the vendor BLE subsystem. * * Calls to this function are initiated by BLE::init, instanceID identify * the BLE instance which issue that call while the initCallback is used to * signal asynchronously the completion of the initialization process. * * @param[in] initCallback Callback which the vendor port shall invoke * when the initialization completes. * * This is an optional parameter set to NULL when not supplied. * * @return BLE_ERROR_NONE if the initialization procedure started * successfully. * * @post initCallback shall be invoked upon completion of the initialization * process. * * @post hasInitialized() shall return false until the initialization is * complete, and it shall return true after succesful completion of the * initialization process. * * @see BLE::init() */ virtual ble_error_t init( FunctionPointerWithContext<BLE::InitializationCompleteCallbackContext *> initCallback ) = 0; /** * Check whether the vendor BLE subsystem has been initialized or not. * * @return true if the initialization has completed for the vendor BLE * subsystem. * * @note this function is invoked by BLE::hasInitialized() * * @see BLE::init() BLE::hasInitialized() */ virtual bool hasInitialized() const = 0; /** * Shutdown the vendor BLE subsystem. * * This operation includes purging the stack of GATT and GAP state and * clearing all state from other BLE components, such as the SecurityManager. * Clearing all states may be realized by a call to Gap::reset(), * GattClient::reset(), GattServer::reset() and SecurityManager::reset(). * * BLE::init() must be called afterward to reinstantiate services and GAP * state. * * @return BLE_ERROR_NONE if the underlying stack and all other services of * the BLE API were shut down correctly. * * @post hasInitialized() shall return false. * * @note This function is invoked by BLE::shutdown(). * * @see BLE::shutdown() BLE::init() BLE::hasInitialized() Gap::reset() * GattClient::reset() GattServer::reset() SecurityManager::reset() . */ virtual ble_error_t shutdown() = 0; /** * Fetches a NULL terminated string representation of the underlying BLE * vendor subsystem. * * @return A pointer to the NULL terminated string representation of the * underlying BLE stack's version. * * @see BLE::getVersion() */ virtual const char *getVersion() = 0; /** * Accessor to the vendor implementation of the Gap interface. * * @return A reference to a Gap object associated to this BLEInstanceBase * instance. * * @see BLE::gap() Gap */ virtual ble::Gap &getGap() = 0; /** * Const alternative to getGap(). * * @return A const reference to a Gap object associated to this * BLEInstanceBase instance. * * @see BLE::gap() Gap */ virtual const ble::Gap &getGap() const = 0; #if BLE_FEATURE_GATT_SERVER /** * Accessor to the vendor implementation of the GattServer interface. * * @return A reference to a GattServer object associated to this * BLEInstanceBase instance. * * @see BLE::gattServer() GattServer */ virtual ble::GattServer &getGattServer() = 0; /** * A const alternative to getGattServer(). * * @return A const reference to a GattServer object associated to this * BLEInstanceBase instance. * * @see BLE::gattServer() GattServer */ virtual const ble::GattServer &getGattServer() const = 0; #endif // BLE_FEATURE_GATT_SERVER #if BLE_FEATURE_GATT_CLIENT /** * Accessor to the vendor implementation of the GattClient interface. * * @return A reference to a GattClient object associated to this * BLEInstanceBase instance. * * @see BLE::gattClient() GattClient */ virtual ble::GattClient &getGattClient() = 0; #endif #if BLE_FEATURE_SECURITY /** * Accessor to the vendor implementation of the SecurityManager interface. * * @return A reference to a SecurityManager object associated to this * BLEInstanceBase instance. * * @see BLE::securityManager() SecurityManager */ virtual ble::SecurityManager &getSecurityManager() = 0; /** * A const alternative to getSecurityManager(). * * @return A const reference to a SecurityManager object associated to this * BLEInstancebase instance. * * @see BLE::securityManager() SecurityManager */ virtual const ble::SecurityManager &getSecurityManager() const = 0; #endif // BLE_FEATURE_SECURITY }; /** * Return the instance of the vendor implementation of BLEInstanceBase. * * @attention Contrary to its name, this function does not return a new instance * at each call. It rather acts like an accessor to a singleton. * * @attention The vendor library must provide an implementation for this function * library. Otherwise, there will be a linker error. */ extern ble::BLEInstanceBase *createBLEInstance(); /** * @} * @} */ } // namespace ble #endif // ifndef MBED_BLE_DEVICE_INSTANCE_BASE__
2,524
597
<gh_stars>100-1000 package com.xiaojukeji.kafka.manager.service.utils; import com.xiaojukeji.kafka.manager.common.entity.ResultStatus; import com.xiaojukeji.kafka.manager.common.entity.pojo.ClusterDO; import com.xiaojukeji.kafka.manager.service.config.BaseTest; import org.testng.Assert; import org.testng.annotations.Test; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.Properties; /** * @author xuguang * @Date 2022/1/6 */ public class TopicCommandsTest extends BaseTest { private final static Long REAL_CLUSTER_ID_IN_MYSQL = 1L; private final static String TEST_CREATE_TOPIC = "createTopicTest"; private final static String REAL_TOPIC1_IN_ZK2 = "expandPartitionTopic"; private final static String REAL_TOPIC_IN_ZK = "moduleTest"; private final static String INVALID_TOPIC = ".,&"; private final static Integer PARTITION_NUM = 1; private final static Integer REPLICA_NUM = 1; private final static Integer BROKER_ID = 1; private final static String REAL_PHYSICAL_CLUSTER_NAME = "LogiKM_moduleTest"; private final static String ZOOKEEPER_ADDRESS = "10.190.12.242:2181,10.190.25.160:2181,10.190.25.41:2181/wyc"; private final static String BOOTSTRAP_SERVERS = "10.190.12.242:9093,10.190.25.160:9093,10.190.25.41:9093"; private final static String SECURITY_PROTOCOL = "{ \t\"security.protocol\": \"SASL_PLAINTEXT\", \t\"sasl.mechanism\": \"PLAIN\", \t\"sasl.jaas.config\": \"org.apache.kafka.common.security.plain.PlainLoginModule required username=\\\"dkm_admin\\\" password=\\\"<PASSWORD>\\\";\" }"; public ClusterDO getClusterDO() { ClusterDO clusterDO = new ClusterDO(); clusterDO.setId(REAL_CLUSTER_ID_IN_MYSQL); clusterDO.setClusterName(REAL_PHYSICAL_CLUSTER_NAME); clusterDO.setZookeeper(ZOOKEEPER_ADDRESS); clusterDO.setBootstrapServers(BOOTSTRAP_SERVERS); clusterDO.setSecurityProperties(SECURITY_PROTOCOL); clusterDO.setStatus(1); clusterDO.setGmtCreate(new Date()); clusterDO.setGmtModify(new Date()); return clusterDO; } @Test(description = "测试创建topic") public void createTopicTest() { // NullPointerException createTopic2NullPointerExceptionTest(); // InvalidPartitions createTopic2InvalidPartitionsTest(); // InvalidReplicationFactor createTopic2InvalidReplicationFactorTest(); // topic exists createTopic2TopicExistsTest(); // invalid topic createTopic2InvalidTopicTest(); // success createTopic2SuccessTest(); } private void createTopic2NullPointerExceptionTest() { ClusterDO clusterDO = getClusterDO(); clusterDO.setZookeeper(null); clusterDO.setBootstrapServers(null); ResultStatus result = TopicCommands.createTopic( clusterDO, TEST_CREATE_TOPIC, PARTITION_NUM, REPLICA_NUM, Arrays.asList(BROKER_ID), new Properties() ); Assert.assertEquals(result.getCode(), ResultStatus.TOPIC_OPERATION_PARAM_NULL_POINTER.getCode()); } private void createTopic2InvalidPartitionsTest() { ClusterDO clusterDO = getClusterDO(); ResultStatus result = TopicCommands.createTopic( clusterDO, TEST_CREATE_TOPIC, -1, REPLICA_NUM, Arrays.asList(BROKER_ID), new Properties() ); Assert.assertEquals(result.getCode(), ResultStatus.TOPIC_OPERATION_PARTITION_NUM_ILLEGAL.getCode()); } private void createTopic2InvalidReplicationFactorTest() { ClusterDO clusterDO = getClusterDO(); ResultStatus result = TopicCommands.createTopic( clusterDO, TEST_CREATE_TOPIC, PARTITION_NUM, REPLICA_NUM, Collections.emptyList(), new Properties() ); Assert.assertEquals(result.getCode(), ResultStatus.BROKER_NUM_NOT_ENOUGH.getCode()); } private void createTopic2TopicExistsTest() { ClusterDO clusterDO = getClusterDO(); ResultStatus result = TopicCommands.createTopic( clusterDO, REAL_TOPIC_IN_ZK, PARTITION_NUM, REPLICA_NUM, Arrays.asList(BROKER_ID), new Properties() ); Assert.assertEquals(result.getCode(), ResultStatus.TOPIC_OPERATION_TOPIC_EXISTED.getCode()); } private void createTopic2InvalidTopicTest() { ClusterDO clusterDO = getClusterDO(); ResultStatus result = TopicCommands.createTopic( clusterDO, INVALID_TOPIC, PARTITION_NUM, REPLICA_NUM, Arrays.asList(BROKER_ID), new Properties() ); Assert.assertEquals(result.getCode(), ResultStatus.TOPIC_OPERATION_TOPIC_NAME_ILLEGAL.getCode()); } private void createTopic2SuccessTest() { ClusterDO clusterDO = getClusterDO(); ResultStatus result = TopicCommands.createTopic( clusterDO, TEST_CREATE_TOPIC, PARTITION_NUM, REPLICA_NUM, Arrays.asList(BROKER_ID), new Properties() ); Assert.assertEquals(result.getCode(), ResultStatus.SUCCESS.getCode()); // 删除这个Topic ResultStatus result1 = TopicCommands.deleteTopic(clusterDO, TEST_CREATE_TOPIC); Assert.assertEquals(result1.getCode(), ResultStatus.SUCCESS.getCode()); } @Test(description = "测试修改topic配置") public void modifyTopicConfigTest() { // AdminOperationException modifyTopicConfig2AdminOperationExceptionTest(); // InvalidConfigurationException modifyTopicConfig2InvalidConfigurationExceptionTest(); // success modifyTopicConfig2SuccessTest(); } private void modifyTopicConfig2AdminOperationExceptionTest() { ClusterDO clusterDO = getClusterDO(); ResultStatus result = TopicCommands.modifyTopicConfig(clusterDO, INVALID_TOPIC, new Properties()); Assert.assertEquals(result.getCode(), ResultStatus.TOPIC_OPERATION_UNKNOWN_TOPIC_PARTITION.getCode()); } private void modifyTopicConfig2InvalidConfigurationExceptionTest() { ClusterDO clusterDO = getClusterDO(); Properties properties = new Properties(); properties.setProperty("xxx", "xxx"); ResultStatus result = TopicCommands.modifyTopicConfig(clusterDO, REAL_TOPIC_IN_ZK, properties); Assert.assertEquals(result.getCode(), ResultStatus.TOPIC_OPERATION_TOPIC_CONFIG_ILLEGAL.getCode()); } private void modifyTopicConfig2SuccessTest() { ClusterDO clusterDO = getClusterDO(); Properties properties = new Properties(); ResultStatus result = TopicCommands.modifyTopicConfig(clusterDO, REAL_TOPIC_IN_ZK, properties); Assert.assertEquals(result.getCode(), ResultStatus.SUCCESS.getCode()); } @Test(description = "测试扩分区") public void expandTopicTest() { // failed expandTopic2FailureTest(); // success expandTopic2SuccessTest(); } private void expandTopic2FailureTest() { ClusterDO clusterDO = getClusterDO(); ResultStatus result = TopicCommands.expandTopic( clusterDO, INVALID_TOPIC, PARTITION_NUM + 1, Arrays.asList(BROKER_ID, 2) ); Assert.assertEquals(result.getCode(), ResultStatus.TOPIC_OPERATION_UNKNOWN_ERROR.getCode()); } private void expandTopic2SuccessTest() { ClusterDO clusterDO = getClusterDO(); ResultStatus result = TopicCommands.expandTopic( clusterDO, REAL_TOPIC1_IN_ZK2, PARTITION_NUM + 1, Arrays.asList(BROKER_ID, 2) ); Assert.assertEquals(result.getCode(), ResultStatus.SUCCESS.getCode()); } @Test(description = "测试删除Topic") public void deleteTopicTest() { // UnknownTopicOrPartitionException deleteTopic2UnknownTopicOrPartitionExceptionTest(); // NullPointerException deleteTopic2NullPointerExceptionTest(); // success deleteTopic2SuccessTest(); } private void deleteTopic2UnknownTopicOrPartitionExceptionTest() { ClusterDO clusterDO = getClusterDO(); ResultStatus result = TopicCommands.deleteTopic(clusterDO, INVALID_TOPIC); Assert.assertEquals(result.getCode(), ResultStatus.TOPIC_OPERATION_UNKNOWN_TOPIC_PARTITION.getCode()); } private void deleteTopic2NullPointerExceptionTest() { ClusterDO clusterDO = getClusterDO(); clusterDO.setBootstrapServers(null); clusterDO.setZookeeper(null); ResultStatus result = TopicCommands.deleteTopic(clusterDO, INVALID_TOPIC); Assert.assertEquals(result.getCode(), ResultStatus.TOPIC_OPERATION_UNKNOWN_ERROR.getCode()); } private void deleteTopic2SuccessTest() { // 需要先创建这个Topic ClusterDO clusterDO = getClusterDO(); ResultStatus result = TopicCommands.createTopic( clusterDO, TEST_CREATE_TOPIC, PARTITION_NUM, REPLICA_NUM, Arrays.asList(BROKER_ID), new Properties() ); Assert.assertEquals(result.getCode(), ResultStatus.SUCCESS.getCode()); ResultStatus result1 = TopicCommands.deleteTopic(clusterDO, TEST_CREATE_TOPIC); Assert.assertEquals(result1.getCode(), ResultStatus.SUCCESS.getCode()); } }
4,242
868
<reponame>AriCheng/flare // Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this // file except in compliance with the License. You may obtain a copy of the // License at // // https://opensource.org/licenses/BSD-3-Clause // // 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 "gflags/gflags.h" #include "flare/base/enum.h" #include "flare/base/thread/latch.h" #include "flare/net/http/http_client.h" #include "flare/init.h" using namespace std::literals; DEFINE_string(url, "", "Http request url."); DEFINE_int32(timeout, 1000, "Timeout in ms."); namespace example::http_echo { int Entry(int argc, char** argv) { flare::HttpClient client; flare::HttpResponse response; flare::HttpClient::RequestOptions opts{ .timeout = FLAGS_timeout * 1ms, }; auto&& resp = client.Get(FLAGS_url, opts); if (!resp) { FLARE_LOG_INFO("Error code {}", flare::HttpClient::ErrorCodeToString(resp.error())); } else { FLARE_LOG_INFO("Status code {}", underlying_value(resp->status())); FLARE_LOG_INFO("Response body {}", *resp->body()); } return 0; } } // namespace example::http_echo int main(int argc, char** argv) { return flare::Start(argc, argv, example::http_echo::Entry); }
540
17,037
# This module is automatically generated by autogen.sh. DO NOT EDIT. from . import _AWS class _Satellite(_AWS): _type = "satellite" _icon_dir = "resources/aws/satellite" class GroundStation(_Satellite): _icon = "ground-station.png" class Satellite(_Satellite): _icon = "satellite.png" # Aliases
112
14,668
<filename>chrome/browser/ash/base/file_flusher.cc // 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 "chrome/browser/ash/base/file_flusher.h" #include <algorithm> #include <set> #include "base/bind.h" #include "base/files/file.h" #include "base/files/file_enumerator.h" #include "base/logging.h" #include "base/synchronization/atomic_flag.h" #include "base/task/thread_pool.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" namespace ash { //////////////////////////////////////////////////////////////////////////////// // FileFlusher::Job class FileFlusher::Job { public: Job(const base::WeakPtr<FileFlusher>& flusher, const base::FilePath& path, bool recursive, const FileFlusher::OnFlushCallback& on_flush_callback, base::OnceClosure callback); Job(const Job&) = delete; Job& operator=(const Job&) = delete; ~Job() = default; void Start(); void Cancel(); const base::FilePath& path() const { return path_; } bool started() const { return started_; } private: // Flush files on a blocking pool thread. void FlushAsync(); // Schedule a FinishOnUIThread task to run on the UI thread. void ScheduleFinish(); // Finish the job by notifying |flusher_| and self destruct on the UI thread. void FinishOnUIThread(); base::WeakPtr<FileFlusher> flusher_; const base::FilePath path_; const bool recursive_; const FileFlusher::OnFlushCallback on_flush_callback_; base::OnceClosure callback_; bool started_ = false; base::AtomicFlag cancel_flag_; bool finish_scheduled_ = false; }; FileFlusher::Job::Job(const base::WeakPtr<FileFlusher>& flusher, const base::FilePath& path, bool recursive, const FileFlusher::OnFlushCallback& on_flush_callback, base::OnceClosure callback) : flusher_(flusher), path_(path), recursive_(recursive), on_flush_callback_(on_flush_callback), callback_(std::move(callback)) {} void FileFlusher::Job::Start() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK(!started()); started_ = true; if (cancel_flag_.IsSet()) { ScheduleFinish(); return; } base::ThreadPool::PostTaskAndReply( FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&FileFlusher::Job::FlushAsync, base::Unretained(this)), base::BindOnce(&FileFlusher::Job::FinishOnUIThread, base::Unretained(this))); } void FileFlusher::Job::Cancel() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); cancel_flag_.Set(); // Cancel() could be called in an iterator/range loop in |flusher_| thus don't // invoke FinishOnUIThread in-place. if (!started()) ScheduleFinish(); } void FileFlusher::Job::FlushAsync() { VLOG(1) << "Flushing files under " << path_.value(); base::FileEnumerator traversal(path_, recursive_, base::FileEnumerator::FILES); for (base::FilePath current = traversal.Next(); !current.empty() && !cancel_flag_.IsSet(); current = traversal.Next()) { base::File currentFile(current, base::File::FLAG_OPEN | base::File::FLAG_WRITE); if (!currentFile.IsValid()) { VLOG(1) << "Unable to flush file:" << current.value(); continue; } currentFile.Flush(); currentFile.Close(); if (!on_flush_callback_.is_null()) on_flush_callback_.Run(current); } } void FileFlusher::Job::ScheduleFinish() { if (finish_scheduled_) return; finish_scheduled_ = true; content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&Job::FinishOnUIThread, base::Unretained(this))); } void FileFlusher::Job::FinishOnUIThread() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (!callback_.is_null()) std::move(callback_).Run(); if (flusher_) flusher_->OnJobDone(this); delete this; } //////////////////////////////////////////////////////////////////////////////// // FileFlusher FileFlusher::FileFlusher() = default; FileFlusher::~FileFlusher() { for (auto* job : jobs_) job->Cancel(); } void FileFlusher::RequestFlush(const base::FilePath& path, bool recursive, base::OnceClosure callback) { for (auto* job : jobs_) { if (path == job->path() || path.IsParent(job->path())) job->Cancel(); } jobs_.push_back(new Job(weak_factory_.GetWeakPtr(), path, recursive, on_flush_callback_for_test_, std::move(callback))); ScheduleJob(); } void FileFlusher::PauseForTest() { DCHECK(std::none_of(jobs_.begin(), jobs_.end(), [](const Job* job) { return job->started(); })); paused_for_test_ = true; } void FileFlusher::ResumeForTest() { paused_for_test_ = false; ScheduleJob(); } void FileFlusher::ScheduleJob() { if (jobs_.empty() || paused_for_test_) return; auto* job = jobs_.front(); if (!job->started()) job->Start(); } void FileFlusher::OnJobDone(FileFlusher::Job* job) { for (auto it = jobs_.begin(); it != jobs_.end(); ++it) { if (*it == job) { jobs_.erase(it); break; } } ScheduleJob(); } } // namespace ash
2,074
651
<filename>pkix/src/main/java/org/spongycastle/pkcs/PKCS12SafeBagBuilder.java<gh_stars>100-1000 package org.spongycastle.pkcs; import java.io.IOException; import org.spongycastle.asn1.ASN1Encodable; import org.spongycastle.asn1.ASN1EncodableVector; import org.spongycastle.asn1.ASN1ObjectIdentifier; import org.spongycastle.asn1.DEROctetString; import org.spongycastle.asn1.DERSet; import org.spongycastle.asn1.pkcs.Attribute; import org.spongycastle.asn1.pkcs.CertBag; import org.spongycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.spongycastle.asn1.pkcs.PrivateKeyInfo; import org.spongycastle.asn1.pkcs.SafeBag; import org.spongycastle.asn1.x509.Certificate; import org.spongycastle.asn1.x509.CertificateList; import org.spongycastle.cert.X509CRLHolder; import org.spongycastle.cert.X509CertificateHolder; import org.spongycastle.operator.OutputEncryptor; public class PKCS12SafeBagBuilder { private ASN1ObjectIdentifier bagType; private ASN1Encodable bagValue; private ASN1EncodableVector bagAttrs = new ASN1EncodableVector(); public PKCS12SafeBagBuilder(PrivateKeyInfo privateKeyInfo, OutputEncryptor encryptor) { this.bagType = PKCSObjectIdentifiers.pkcs8ShroudedKeyBag; this.bagValue = new PKCS8EncryptedPrivateKeyInfoBuilder(privateKeyInfo).build(encryptor).toASN1Structure(); } public PKCS12SafeBagBuilder(PrivateKeyInfo privateKeyInfo) { this.bagType = PKCSObjectIdentifiers.keyBag; this.bagValue = privateKeyInfo; } public PKCS12SafeBagBuilder(X509CertificateHolder certificate) throws IOException { this(certificate.toASN1Structure()); } public PKCS12SafeBagBuilder(X509CRLHolder crl) throws IOException { this(crl.toASN1Structure()); } public PKCS12SafeBagBuilder(Certificate certificate) throws IOException { this.bagType = PKCSObjectIdentifiers.certBag; this.bagValue = new CertBag(PKCSObjectIdentifiers.x509Certificate, new DEROctetString(certificate.getEncoded())); } public PKCS12SafeBagBuilder(CertificateList crl) throws IOException { this.bagType = PKCSObjectIdentifiers.crlBag; this.bagValue = new CertBag(PKCSObjectIdentifiers.x509Crl, new DEROctetString(crl.getEncoded())); } public PKCS12SafeBagBuilder addBagAttribute(ASN1ObjectIdentifier attrType, ASN1Encodable attrValue) { bagAttrs.add(new Attribute(attrType, new DERSet(attrValue))); return this; } public PKCS12SafeBag build() { return new PKCS12SafeBag(new SafeBag(bagType, bagValue, new DERSet(bagAttrs))); } }
1,099
691
<reponame>kevcadieux/Sprout<filename>sprout/container/rebind_type.hpp /*============================================================================= Copyright (c) 2011-2019 <NAME> https://github.com/bolero-MURAKAMI/Sprout 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 SPROUT_CONTAINER_REBIND_TYPE_HPP #define SPROUT_CONTAINER_REBIND_TYPE_HPP #include <sprout/config.hpp> #include <sprout/container/container_transform_traits.hpp> namespace sprout { namespace containers { // // rebind_type // template<typename Container, typename Type> struct rebind_type : public sprout::container_transform_traits<Container>::template rebind_type<Type> {}; } // namespace containers } // namespace sprout #endif // #ifndef SPROUT_CONTAINER_REBIND_TYPE_HPP
338
23,220
<gh_stars>1000+ package com.alibaba.otter.canal.store; import java.util.List; import org.springframework.util.CollectionUtils; import com.alibaba.otter.canal.common.AbstractCanalLifeCycle; import com.alibaba.otter.canal.meta.CanalMetaManager; import com.alibaba.otter.canal.protocol.ClientIdentity; import com.alibaba.otter.canal.protocol.position.LogPosition; import com.alibaba.otter.canal.protocol.position.Position; /** * store回收机制 * * @author jianghang 2012-8-8 下午12:57:36 * @version 1.0.0 */ public abstract class AbstractCanalStoreScavenge extends AbstractCanalLifeCycle implements CanalStoreScavenge { protected String destination; protected CanalMetaManager canalMetaManager; protected boolean onAck = true; protected boolean onFull = false; protected boolean onSchedule = false; protected String scavengeSchedule = null; public void scavenge() { Position position = getLatestAckPosition(destination); cleanUntil(position); } /** * 找出该destination中可被清理掉的position位置 * * @param destination */ private Position getLatestAckPosition(String destination) { List<ClientIdentity> clientIdentitys = canalMetaManager.listAllSubscribeInfo(destination); LogPosition result = null; if (!CollectionUtils.isEmpty(clientIdentitys)) { // 尝试找到一个最小的logPosition for (ClientIdentity clientIdentity : clientIdentitys) { LogPosition position = (LogPosition) canalMetaManager.getCursor(clientIdentity); if (position == null) { continue; } if (result == null) { result = position; } else { result = min(result, position); } } } return result; } /** * 找出一个最小的position位置 */ private LogPosition min(LogPosition position1, LogPosition position2) { if (position1.getIdentity().equals(position2.getIdentity())) { // 首先根据文件进行比较 if (position1.getPostion().getJournalName().compareTo(position2.getPostion().getJournalName()) < 0) { return position2; } else if (position1.getPostion().getJournalName().compareTo(position2.getPostion().getJournalName()) > 0) { return position1; } else { // 根据offest进行比较 if (position1.getPostion().getPosition() < position2.getPostion().getPosition()) { return position2; } else { return position1; } } } else { // 不同的主备库,根据时间进行比较 if (position1.getPostion().getTimestamp() < position2.getPostion().getTimestamp()) { return position2; } else { return position1; } } } public void setOnAck(boolean onAck) { this.onAck = onAck; } public void setOnFull(boolean onFull) { this.onFull = onFull; } public void setOnSchedule(boolean onSchedule) { this.onSchedule = onSchedule; } public String getScavengeSchedule() { return scavengeSchedule; } public void setScavengeSchedule(String scavengeSchedule) { this.scavengeSchedule = scavengeSchedule; } public void setDestination(String destination) { this.destination = destination; } public void setCanalMetaManager(CanalMetaManager canalMetaManager) { this.canalMetaManager = canalMetaManager; } }
1,766
852
<gh_stars>100-1000 #include "SimG4Core/PhysicsLists/interface/HadronPhysicsQGSPCMS_FTFP_BERT.h" #include "G4SystemOfUnits.hh" #include "G4Threading.hh" HadronPhysicsQGSPCMS_FTFP_BERT::HadronPhysicsQGSPCMS_FTFP_BERT(G4int) : HadronPhysicsQGSPCMS_FTFP_BERT( 3. * CLHEP::GeV, 6. * CLHEP::GeV, 12. * CLHEP::GeV, 25. * CLHEP::GeV, 12. * CLHEP::GeV) {} HadronPhysicsQGSPCMS_FTFP_BERT::HadronPhysicsQGSPCMS_FTFP_BERT( G4double e1, G4double e2, G4double e3, G4double e4, G4double e5) : G4HadronPhysicsQGSP_BERT("hInelasticQGSPCMS_FTFP_BERT") { minQGSP_proton = minQGSP_neutron = minQGSP_pik = e5; maxFTFP_proton = maxFTFP_neutron = maxFTFP_pik = e4; minFTFP_proton = minFTFP_neutron = minFTFP_pik = e1; maxBERT_proton = maxBERT_neutron = e2; maxBERT_pik = e3; } HadronPhysicsQGSPCMS_FTFP_BERT::~HadronPhysicsQGSPCMS_FTFP_BERT() {} void HadronPhysicsQGSPCMS_FTFP_BERT::ConstructProcess() { if (G4Threading::IsMasterThread()) { DumpBanner(); } CreateModels(); }
501
432
<reponame>hachreak/keras-maskrcnn """ Copyright 2017-2018 Fizyr (https://fizyr.com) 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 warnings import keras import keras_resnet import keras_resnet.models import keras_retinanet.models.resnet from ..models import retinanet, Backbone class ResNetBackbone(Backbone, keras_retinanet.models.resnet.ResNetBackbone): def maskrcnn(self, *args, **kwargs): """ Returns a maskrcnn model using the correct backbone. """ return resnet_maskrcnn(*args, backbone=self.backbone, **kwargs) def resnet_maskrcnn(num_classes, backbone='resnet50', inputs=None, modifier=None, mask_dtype=keras.backend.floatx(), **kwargs): # choose default input if inputs is None: inputs = keras.layers.Input(shape=(None, None, 3), name='image') # create the resnet backbone if backbone == 'resnet50': resnet = keras_resnet.models.ResNet50(inputs, include_top=False, freeze_bn=True) elif backbone == 'resnet101': resnet = keras_resnet.models.ResNet101(inputs, include_top=False, freeze_bn=True) elif backbone == 'resnet152': resnet = keras_resnet.models.ResNet152(inputs, include_top=False, freeze_bn=True) # invoke modifier if given if modifier: resnet = modifier(resnet) # create the full model model = retinanet.retinanet_mask(inputs=inputs, num_classes=num_classes, backbone_layers=resnet.outputs[1:], mask_dtype=mask_dtype, **kwargs) return model def resnet50_maskrcnn(num_classes, inputs=None, **kwargs): return resnet_maskrcnn(num_classes=num_classes, backbone='resnet50', inputs=inputs, **kwargs) def resnet101_maskrcnn(num_classes, inputs=None, **kwargs): return resnet_maskrcnn(num_classes=num_classes, backbone='resnet101', inputs=inputs, **kwargs) def resnet152_maskrcnn(num_classes, inputs=None, **kwargs): return resnet_maskrcnn(num_classes=num_classes, backbone='resnet152', inputs=inputs, **kwargs)
863
1,526
<reponame>webcoast-dk/mitogen # Copyright 2019, <NAME> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # !mitogen: minify_safe """ Basic signal handler for dumping thread stacks. """ import difflib import logging import os import gc import signal import sys import threading import time import traceback import mitogen.core import mitogen.parent LOG = logging.getLogger(__name__) _last = None def enable_evil_interrupts(): signal.signal(signal.SIGALRM, (lambda a, b: None)) signal.setitimer(signal.ITIMER_REAL, 0.01, 0.01) def disable_evil_interrupts(): signal.setitimer(signal.ITIMER_REAL, 0, 0) def _hex(n): return '%08x' % n def get_subclasses(klass): """ Rather than statically import every interesting subclass, forcing it all to be transferred and potentially disrupting the debugged environment, enumerate only those loaded in memory. Also returns the original class. """ stack = [klass] seen = set() while stack: klass = stack.pop() seen.add(klass) stack.extend(klass.__subclasses__()) return seen def get_routers(): return dict( (_hex(id(router)), router) for klass in get_subclasses(mitogen.core.Router) for router in gc.get_referrers(klass) if isinstance(router, mitogen.core.Router) ) def get_router_info(): return { 'routers': dict( (id_, { 'id': id_, 'streams': len(set(router._stream_by_id.values())), 'contexts': len(set(router._context_by_id.values())), 'handles': len(router._handle_map), }) for id_, router in get_routers().items() ) } def get_stream_info(router_id): router = get_routers().get(router_id) return { 'streams': dict( (_hex(id(stream)), ({ 'name': stream.name, 'remote_id': stream.remote_id, 'sent_module_count': len(getattr(stream, 'sent_modules', [])), 'routes': sorted(getattr(stream, 'routes', [])), 'type': type(stream).__module__, })) for via_id, stream in router._stream_by_id.items() ) } def format_stacks(): name_by_id = dict( (t.ident, t.name) for t in threading.enumerate() ) l = ['', ''] for threadId, stack in sys._current_frames().items(): l += ["# PID %d ThreadID: (%s) %s; %r" % ( os.getpid(), name_by_id.get(threadId, '<no name>'), threadId, stack, )] #stack = stack.f_back.f_back for filename, lineno, name, line in traceback.extract_stack(stack): l += [ 'File: "%s", line %d, in %s' % ( filename, lineno, name ) ] if line: l += [' ' + line.strip()] l += [''] l += ['', ''] return '\n'.join(l) def get_snapshot(): global _last s = format_stacks() snap = s if _last: snap += '\n' diff = list(difflib.unified_diff( a=_last.splitlines(), b=s.splitlines(), fromfile='then', tofile='now' )) if diff: snap += '\n'.join(diff) + '\n' else: snap += '(no change since last time)\n' _last = s return snap def _handler(*_): fp = open('/dev/tty', 'w', 1) fp.write(get_snapshot()) fp.close() def install_handler(): signal.signal(signal.SIGUSR2, _handler) def _logging_main(secs): while True: time.sleep(secs) LOG.info('PERIODIC THREAD DUMP\n\n%s', get_snapshot()) def dump_to_logger(secs=5): th = threading.Thread( target=_logging_main, kwargs={'secs': secs}, name='mitogen.debug.dump_to_logger', ) th.setDaemon(True) th.start() class ContextDebugger(object): @classmethod @mitogen.core.takes_econtext def _configure_context(cls, econtext): mitogen.parent.upgrade_router(econtext) econtext.debugger = cls(econtext.router) def __init__(self, router): self.router = router self.router.add_handler( func=self._on_debug_msg, handle=mitogen.core.DEBUG, persist=True, policy=mitogen.core.has_parent_authority, ) mitogen.core.listen(router, 'register', self._on_stream_register) LOG.debug('Context debugging configured.') def _on_stream_register(self, context, stream): LOG.debug('_on_stream_register: sending configure() to %r', stream) context.call_async(ContextDebugger._configure_context) def _on_debug_msg(self, msg): if msg != mitogen.core._DEAD: threading.Thread( target=self._handle_debug_msg, name='ContextDebuggerHandler', args=(msg,) ).start() def _handle_debug_msg(self, msg): try: method, args, kwargs = msg.unpickle() msg.reply(getattr(self, method)(*args, **kwargs)) except Exception: e = sys.exc_info()[1] msg.reply(mitogen.core.CallError(e))
2,989
348
{"nom":"Villemanoche","circ":"3ème circonscription","dpt":"Yonne","inscrits":459,"abs":234,"votants":225,"blancs":13,"nuls":4,"exp":208,"res":[{"nuance":"REM","nom":"<NAME>","voix":106},{"nuance":"FN","nom":"<NAME>","voix":102}]}
89
3,102
// RUN: %clang_cc1 -emit-llvm %s -o /dev/null /* This testcase doesn't actually test a bug, it's just the result of me * figuring out the syntax for forward declaring a static variable. */ struct list { int x; struct list *Next; }; static struct list B; /* Forward declare static */ static struct list A = { 7, &B }; static struct list B = { 8, &A }; extern struct list D; /* forward declare normal var */ struct list C = { 7, &D }; struct list D = { 8, &C };
153
1,056
<filename>enterprise/websvc.kit/test/qa-functional/src/org/netbeans/modules/ws/qaf/JEE6MavenEjbWsValidation.java<gh_stars>1000+ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.ws.qaf; import junit.framework.Test; import org.netbeans.jellytools.modules.j2ee.J2eeTestCase.Server; import org.netbeans.junit.NbModuleSuite; import org.netbeans.modules.ws.qaf.WebServicesTestBase.JavaEEVersion; /** * * @author lukas */ public class JEE6MavenEjbWsValidation extends MavenEjbWsValidation { public JEE6MavenEjbWsValidation(String name) { super(name); } @Override protected JavaEEVersion getJavaEEversion() { return JavaEEVersion.JAVAEE6; } public static Test suite() { return NbModuleSuite.create(addServerTests(Server.GLASSFISH, NbModuleSuite.createConfiguration(JEE6MavenEjbWsValidation.class), "testCreateNewWs", "testAddOperation", "testSetSOAP", // IZ# 175974 "testGenerateWSDL", "testStartServer", "testWsHandlers", "testRunWsProject", "testTestWS", "testCreateWsClient", "testRefreshClientAndReplaceWSDL", "testCallWsOperationInSessionEJB", "testCallWsOperationInJavaClass", "testWsFromEJBinClientProject", "testWsClientHandlers", "testRunWsClientProject", "testUndeployProjects", "testStopServer").enableModules(".*").clusters(".*")); } }
956
1,909
<reponame>grmkris/XChange package org.knowm.xchange.bl3p.service.params; import org.knowm.xchange.currency.Currency; import org.knowm.xchange.service.trade.params.TradeHistoryParamCurrency; import org.knowm.xchange.service.trade.params.TradeHistoryParamPaging; public class Bl3pTradeHistoryParams implements TradeHistoryParamCurrency, TradeHistoryParamPaging { public enum TransactionType { TRADE, FEE, DEPOSIT, WITHDRAW; @Override public String toString() { return super.toString().toLowerCase(); } } private Currency currency; private int pageLength; private int pageNumber; private TransactionType type; public Bl3pTradeHistoryParams(Currency currency, TransactionType type) { this(currency, type, 1); } public Bl3pTradeHistoryParams(Currency currency, TransactionType type, int pageNumber) { this(currency, type, pageNumber, 50); } public Bl3pTradeHistoryParams( Currency currency, TransactionType type, int pageNumber, int pageLength) { this.currency = currency; this.type = type; this.pageNumber = pageNumber; this.pageLength = pageLength; } @Override public Currency getCurrency() { return currency; } @Override public void setCurrency(Currency currency) { this.currency = currency; } @Override public Integer getPageLength() { return pageLength; } @Override public void setPageLength(Integer pageLength) { this.pageLength = pageLength; } @Override public Integer getPageNumber() { return pageNumber; } @Override public void setPageNumber(Integer pageNumber) { this.pageNumber = pageNumber; } public TransactionType getType() { return type; } public void setType(TransactionType type) { this.type = type; } }
587
474
<reponame>iwanghang/EvilsLive package com.thinkkeep.videolib.model.video; /** * Created by jsson on 17/3/16. */ public interface OnPreviewFrameListener { /** * 预览一帧视频回调 * @param data * @param width * @param height */ void onPreviewFrameListener(byte[] data, int width, int height); }
142
1,093
<filename>spring-integration-core/src/main/java/org/springframework/integration/config/AbstractEvaluationContextFactoryBean.java /* * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.integration.config; import java.lang.reflect.Method; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactoryUtils; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.core.convert.ConversionService; import org.springframework.expression.PropertyAccessor; import org.springframework.expression.TypeConverter; import org.springframework.expression.spel.support.StandardTypeConverter; import org.springframework.integration.expression.SpelPropertyAccessorRegistrar; import org.springframework.integration.support.utils.IntegrationUtils; import org.springframework.util.Assert; /** * Abstract class for integration evaluation context factory beans. * * @author <NAME> * * @since 4.3.15 * */ public abstract class AbstractEvaluationContextFactoryBean implements ApplicationContextAware, InitializingBean { private Map<String, PropertyAccessor> propertyAccessors = new LinkedHashMap<String, PropertyAccessor>(); private Map<String, Method> functions = new LinkedHashMap<String, Method>(); private TypeConverter typeConverter = new StandardTypeConverter(); private ApplicationContext applicationContext; private boolean initialized; protected TypeConverter getTypeConverter() { return this.typeConverter; } protected ApplicationContext getApplicationContext() { return this.applicationContext; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } public void setPropertyAccessors(Map<String, PropertyAccessor> accessors) { Assert.isTrue(!this.initialized, "'propertyAccessors' can't be changed after initialization."); Assert.notNull(accessors, "'accessors' must not be null."); Assert.noNullElements(accessors.values().toArray(), "'accessors' cannot have null values."); this.propertyAccessors = new LinkedHashMap<String, PropertyAccessor>(accessors); } public Map<String, PropertyAccessor> getPropertyAccessors() { return this.propertyAccessors; } public void setFunctions(Map<String, Method> functionsArg) { Assert.isTrue(!this.initialized, "'functions' can't be changed after initialization."); Assert.notNull(functionsArg, "'functions' must not be null."); Assert.noNullElements(functionsArg.values().toArray(), "'functions' cannot have null values."); this.functions = new LinkedHashMap<String, Method>(functionsArg); } public Map<String, Method> getFunctions() { return this.functions; } protected void initialize(String beanName) { if (this.applicationContext != null) { conversionService(); functions(); propertyAccessors(); processParentIfPresent(beanName); } this.initialized = true; } private void conversionService() { ConversionService conversionService = IntegrationUtils.getConversionService(getApplicationContext()); if (conversionService != null) { this.typeConverter = new StandardTypeConverter(conversionService); } } private void functions() { Map<String, SpelFunctionFactoryBean> functionFactoryBeanMap = BeanFactoryUtils .beansOfTypeIncludingAncestors(this.applicationContext, SpelFunctionFactoryBean.class); for (SpelFunctionFactoryBean spelFunctionFactoryBean : functionFactoryBeanMap.values()) { if (!getFunctions().containsKey(spelFunctionFactoryBean.getFunctionName())) { getFunctions().put(spelFunctionFactoryBean.getFunctionName(), spelFunctionFactoryBean.getObject()); } } } private void propertyAccessors() { try { SpelPropertyAccessorRegistrar propertyAccessorRegistrar = this.applicationContext.getBean(SpelPropertyAccessorRegistrar.class); for (Entry<String, PropertyAccessor> entry : propertyAccessorRegistrar.getPropertyAccessors() .entrySet()) { if (!getPropertyAccessors().containsKey(entry.getKey())) { getPropertyAccessors().put(entry.getKey(), entry.getValue()); } } } catch (@SuppressWarnings("unused") NoSuchBeanDefinitionException e) { // There is no 'SpelPropertyAccessorRegistrar' bean in the application context. } } private void processParentIfPresent(String beanName) { ApplicationContext parent = this.applicationContext.getParent(); if (parent != null && parent.containsBean(beanName)) { AbstractEvaluationContextFactoryBean parentFactoryBean = parent.getBean("&" + beanName, getClass()); for (Entry<String, PropertyAccessor> entry : parentFactoryBean.getPropertyAccessors().entrySet()) { if (!getPropertyAccessors().containsKey(entry.getKey())) { getPropertyAccessors().put(entry.getKey(), entry.getValue()); } } for (Entry<String, Method> entry : parentFactoryBean.getFunctions().entrySet()) { if (!getFunctions().containsKey(entry.getKey())) { getFunctions().put(entry.getKey(), entry.getValue()); } } } } }
1,768
630
/* * Copyright (C) 2015, BMW Car IT GmbH * * Author: <NAME> <<EMAIL>> * * 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.bmwcarit.barefoot.util; import java.io.Serializable; /** * Generic 5-tuple (quintuple). * * @param <A> Type of first element. * @param <B> Type of second element. * @param <C> Type of third element. * @param <D> Type of fourth element. * @param <E> Type of fifth element. */ public class Quintuple<A, B, C, D, E> extends Quadruple<A, B, C, D> implements Serializable { private static final long serialVersionUID = 1L; private E five = null; /** * Creates a {@link Quintuple} object. * * @param one First element. * @param two Second element. * @param three Third element. * @param four Fourth element. * @param five Fifth element. */ public Quintuple(A one, B two, C three, D four, E five) { super(one, two, three, four); this.five = five; } /** * Gets fifth element. * * @return Fifth element, may be null if set to null previously. */ public E five() { return five; } /** * Sets fifth element. * * @param five Fifth element. */ public void five(E five) { this.five = five; } }
620
3,603
/* * 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 io.trino.parquet; import java.util.Objects; import static java.lang.String.format; public class ChunkKey { private int column; private int rowGroup; public ChunkKey(int column, int rowGroup) { this.column = column; this.rowGroup = rowGroup; } @Override public int hashCode() { return Objects.hash(column, rowGroup); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } ChunkKey other = (ChunkKey) obj; return Objects.equals(this.column, other.column) && Objects.equals(this.rowGroup, other.rowGroup); } @Override public String toString() { return format("[rowGroup=%s, column=%s]", rowGroup, column); } }
545
6,992
<gh_stars>1000+ package core; import org.junit.jupiter.api.Test; public class HasOptionalTest { @Test public void test() { HasOptional.doStuffWithOptionalDependency(); } }
67
7,567
<filename>sdk-overrides/include/stdlib.h #ifndef _OVERRIDE_STDLIB_H_ #define _OVERRIDE_STDLIB_H_ #include_next "stdlib.h" #include <stdbool.h> #include "mem.h" #define free os_free #define malloc os_malloc #define calloc(n,sz) os_zalloc(n*sz) #define realloc os_realloc #endif
151
794
// // CAClipboard.h // CrossApp // // Created by Zhujian on 15-2-2. // Copyright (c) 2014 http://www.9miao.com All rights reserved. // #ifndef __CrossApp__CAClipboard__ #define __CrossApp__CAClipboard__ #include <string> #include "ccMacros.h" NS_CC_BEGIN class CC_DLL CAClipboard { public: static std::string getText(); static void setText(const std::string& text); }; NS_CC_END #endif /* defined(__CrossApp__CAClipboard__) */
174
663
<filename>druid/datadog_checks/druid/druid.py # (C) Datadog, Inc. 2019-present # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) import requests from datadog_checks.base import AgentCheck, ConfigurationError from datadog_checks.base.errors import CheckException class DruidCheck(AgentCheck): def check(self, _): custom_tags = self.instance.get('tags', []) base_url = self.instance.get('url') if not base_url: raise ConfigurationError('Missing configuration: url') process_properties = self._get_process_properties(base_url, custom_tags) druid_service = process_properties['druid.service'] tags = custom_tags + ['druid_service:{}'.format(druid_service)] self._submit_health_status(base_url, tags) def _submit_health_status(self, base_url, base_tags): url = base_url + "/status/health" tags = ['url:{}'.format(url)] + base_tags resp = self._make_request(url) if resp is True: status = AgentCheck.OK health_value = 1 else: status = AgentCheck.CRITICAL health_value = 0 self.service_check('druid.service.health', status, tags=tags) self.gauge('druid.service.health', health_value, tags=tags) def _get_process_properties(self, base_url, tags): url = base_url + "/status/properties" service_check_tags = ['url:{}'.format(url)] + tags resp = self._make_request(url) if resp is None: status = AgentCheck.CRITICAL else: status = AgentCheck.OK self.service_check('druid.service.can_connect', status, tags=service_check_tags) if resp is None: raise CheckException("Unable to retrieve Druid service properties at {}".format(url)) return resp def _make_request(self, url): try: resp = self.http.get(url) resp.raise_for_status() return resp.json() except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError) as e: self.warning( "Couldn't connect to URL: %s with exception: %s. Please verify the address is reachable", url, e ) except requests.exceptions.Timeout as e: self.warning("Connection timeout when connecting to %s: %s", url, e)
993
302
/** * * Copyright &copy; 2015-2020 <a href="https://gitee.com/JeeHuangBingGui/JeeSpring">JeeSpring</a> All rights reserved.. */ package com.jeespring.modules.sys.service; import java.util.List; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.jeespring.common.service.TreeService; import com.jeespring.common.utils.StringUtils; import com.jeespring.modules.sys.entity.SysDictTree; import com.jeespring.modules.sys.dao.SysDictTreeDao; /** * 数据字典Service * @author JeeSpring * @version 2018-08-22 */ @Service @Transactional(readOnly = true) public class SysDictTreeService extends TreeService<SysDictTreeDao, SysDictTree> { @Override public SysDictTree get(String id) { return super.get(id); } @Override public List<SysDictTree> findList(SysDictTree sysDict) { if (StringUtils.isNotBlank(sysDict.getParentIds())){ sysDict.setParentIds(","+sysDict.getParentIds()+","); } return super.findList(sysDict); } @Override @Transactional(readOnly = false) public void save(SysDictTree sysDict) { super.save(sysDict); } @Override @Transactional(readOnly = false) public void delete(SysDictTree sysDict) { super.delete(sysDict); } }
487
524
{ "name": "react-keyframes", "version": "1.0.0-canary.3", "description": "Create frame-based animations in React", "license": "MIT", "source": "src/index.ts", "main": "./dist/index.js", "module": "dist/index.mjs", "files": [ "dist" ], "scripts": { "build": "rm -rf dist && microbundle --external react,prop-types --format es,cjs", "prepublish": "npm run build" }, "devDependencies": { "microbundle": "0.11.0" } }
190
3,100
<reponame>ehanoj/gdal /****************************************************************************** * * Project: GDAL * Purpose: Implementation of a set of GDALDerivedPixelFunc(s) to be used * with source raster band of virtual GDAL datasets. * Author: <NAME> <<EMAIL>> * ****************************************************************************** * Copyright (c) 2008-2014 <NAME> <<EMAIL>> * * 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 <cmath> #include "gdal.h" #include "vrtdataset.h" #include <limits> CPL_CVSID("$Id$") static CPLErr RealPixelFunc( void **papoSources, int nSources, void *pData, int nXSize, int nYSize, GDALDataType eSrcType, GDALDataType eBufType, int nPixelSpace, int nLineSpace ); static CPLErr ImagPixelFunc( void **papoSources, int nSources, void *pData, int nXSize, int nYSize, GDALDataType eSrcType, GDALDataType eBufType, int nPixelSpace, int nLineSpace ); static CPLErr ComplexPixelFunc( void **papoSources, int nSources, void *pData, int nXSize, int nYSize, GDALDataType eSrcType, GDALDataType eBufType, int nPixelSpace, int nLineSpace ); static CPLErr ModulePixelFunc( void **papoSources, int nSources, void *pData, int nXSize, int nYSize, GDALDataType eSrcType, GDALDataType eBufType, int nPixelSpace, int nLineSpace ); static CPLErr PhasePixelFunc( void **papoSources, int nSources, void *pData, int nXSize, int nYSize, GDALDataType eSrcType, GDALDataType eBufType, int nPixelSpace, int nLineSpace ); static CPLErr ConjPixelFunc( void **papoSources, int nSources, void *pData, int nXSize, int nYSize, GDALDataType eSrcType, GDALDataType eBufType, int nPixelSpace, int nLineSpace ); static CPLErr SumPixelFunc( void **papoSources, int nSources, void *pData, int nXSize, int nYSize, GDALDataType eSrcType, GDALDataType eBufType, int nPixelSpace, int nLineSpace ); static CPLErr DiffPixelFunc( void **papoSources, int nSources, void *pData, int nXSize, int nYSize, GDALDataType eSrcType, GDALDataType eBufType, int nPixelSpace, int nLineSpace ); static CPLErr MulPixelFunc( void **papoSources, int nSources, void *pData, int nXSize, int nYSize, GDALDataType eSrcType, GDALDataType eBufType, int nPixelSpace, int nLineSpace ); static CPLErr CMulPixelFunc( void **papoSources, int nSources, void *pData, int nXSize, int nYSize, GDALDataType eSrcType, GDALDataType eBufType, int nPixelSpace, int nLineSpace ); static CPLErr InvPixelFunc( void **papoSources, int nSources, void *pData, int nXSize, int nYSize, GDALDataType eSrcType, GDALDataType eBufType, int nPixelSpace, int nLineSpace ); static CPLErr IntensityPixelFunc( void **papoSources, int nSources, void *pData, int nXSize, int nYSize, GDALDataType eSrcType, GDALDataType eBufType, int nPixelSpace, int nLineSpace ); static CPLErr SqrtPixelFunc( void **papoSources, int nSources, void *pData, int nXSize, int nYSize, GDALDataType eSrcType, GDALDataType eBufType, int nPixelSpace, int nLineSpace ); static CPLErr Log10PixelFunc( void **papoSources, int nSources, void *pData, int nXSize, int nYSize, GDALDataType eSrcType, GDALDataType eBufType, int nPixelSpace, int nLineSpace ); static CPLErr DBPixelFunc( void **papoSources, int nSources, void *pData, int nXSize, int nYSize, GDALDataType eSrcType, GDALDataType eBufType, int nPixelSpace, int nLineSpace ); static CPLErr dB2AmpPixelFunc( void **papoSources, int nSources, void *pData, int nXSize, int nYSize, GDALDataType eSrcType, GDALDataType eBufType, int nPixelSpace, int nLineSpace ); static CPLErr dB2PowPixelFunc( void **papoSources, int nSources, void *pData, int nXSize, int nYSize, GDALDataType eSrcType, GDALDataType eBufType, int nPixelSpace, int nLineSpace ); static CPLErr PowPixelFuncHelper( void **papoSources, int nSources, void *pData, int nXSize, int nYSize, GDALDataType eSrcType, GDALDataType eBufType, int nPixelSpace, int nLineSpace, double base, double fact ); template<typename T> inline double GetSrcVal(const void* pSource, GDALDataType eSrcType, T ii) { switch( eSrcType ) { case GDT_Unknown: return 0; case GDT_Byte: return static_cast<const GByte*>(pSource)[ii]; case GDT_UInt16: return static_cast<const GUInt16*>(pSource)[ii]; case GDT_Int16: return static_cast<const GInt16*>(pSource)[ii]; case GDT_UInt32: return static_cast<const GUInt32*>(pSource)[ii]; case GDT_Int32: return static_cast<const GInt32*>(pSource)[ii]; case GDT_Float32: return static_cast<const float*>(pSource)[ii]; case GDT_Float64: return static_cast<const double*>(pSource)[ii]; case GDT_CInt16: return static_cast<const GInt16*>(pSource)[2 * ii]; case GDT_CInt32: return static_cast<const GInt32*>(pSource)[2 * ii]; case GDT_CFloat32: return static_cast<const float*>(pSource)[2 * ii]; case GDT_CFloat64: return static_cast<const double*>(pSource)[2 * ii]; case GDT_TypeCount: break; } return 0; } static CPLErr FetchDoubleArg(CSLConstList papszArgs, const char *pszName, double* pdfX) { const char* pszVal = CSLFetchNameValue(papszArgs, pszName); if ( pszVal == nullptr ) { CPLError(CE_Failure, CPLE_AppDefined, "Missing pixel function argument: %s", pszName); return CE_Failure; } char *pszEnd = nullptr; *pdfX = std::strtod(pszVal, &pszEnd); if ( pszEnd == pszVal ) { CPLError(CE_Failure, CPLE_AppDefined, "Failed to parse pixel function argument: %s", pszName); return CE_Failure; } return CE_None; } static CPLErr RealPixelFunc( void **papoSources, int nSources, void *pData, int nXSize, int nYSize, GDALDataType eSrcType, GDALDataType eBufType, int nPixelSpace, int nLineSpace ) { /* ---- Init ---- */ if( nSources != 1 ) return CE_Failure; const int nPixelSpaceSrc = GDALGetDataTypeSizeBytes( eSrcType ); const size_t nLineSpaceSrc = static_cast<size_t>(nPixelSpaceSrc) * nXSize; /* ---- Set pixels ---- */ for( int iLine = 0; iLine < nYSize; ++iLine ) { GDALCopyWords( static_cast<GByte *>(papoSources[0]) + nLineSpaceSrc * iLine, eSrcType, nPixelSpaceSrc, static_cast<GByte *>(pData) + static_cast<GSpacing>(nLineSpace) * iLine, eBufType, nPixelSpace, nXSize ); } /* ---- Return success ---- */ return CE_None; } // RealPixelFunc static CPLErr ImagPixelFunc( void **papoSources, int nSources, void *pData, int nXSize, int nYSize, GDALDataType eSrcType, GDALDataType eBufType, int nPixelSpace, int nLineSpace ) { /* ---- Init ---- */ if( nSources != 1 ) return CE_Failure; if( GDALDataTypeIsComplex( eSrcType ) ) { const GDALDataType eSrcBaseType = GDALGetNonComplexDataType( eSrcType ); const int nPixelSpaceSrc = GDALGetDataTypeSizeBytes( eSrcType ); const size_t nLineSpaceSrc = static_cast<size_t>(nPixelSpaceSrc) * nXSize; const void * const pImag = static_cast<GByte *>(papoSources[0]) + GDALGetDataTypeSizeBytes( eSrcType ) / 2; /* ---- Set pixels ---- */ for( int iLine = 0; iLine < nYSize; ++iLine ) { GDALCopyWords( static_cast<const GByte *>(pImag) + nLineSpaceSrc * iLine, eSrcBaseType, nPixelSpaceSrc, static_cast<GByte *>(pData) + static_cast<GSpacing>(nLineSpace) * iLine, eBufType, nPixelSpace, nXSize ); } } else { const double dfImag = 0; /* ---- Set pixels ---- */ for( int iLine = 0; iLine < nYSize; ++iLine ) { // Always copy from the same location. GDALCopyWords( &dfImag, eSrcType, 0, static_cast<GByte *>(pData) + static_cast<GSpacing>(nLineSpace) * iLine, eBufType, nPixelSpace, nXSize); } } /* ---- Return success ---- */ return CE_None; } // ImagPixelFunc static CPLErr ComplexPixelFunc( void **papoSources, int nSources, void *pData, int nXSize, int nYSize, GDALDataType eSrcType, GDALDataType eBufType, int nPixelSpace, int nLineSpace ) { /* ---- Init ---- */ if( nSources != 2 ) return CE_Failure; const void * const pReal = papoSources[0]; const void * const pImag = papoSources[1]; /* ---- Set pixels ---- */ size_t ii = 0; for( int iLine = 0; iLine < nYSize; ++iLine ) { for( int iCol = 0; iCol < nXSize; ++iCol, ++ii ) { // Source raster pixels may be obtained with GetSrcVal macro. const double adfPixVal[2] = { GetSrcVal(pReal, eSrcType, ii), // re GetSrcVal(pImag, eSrcType, ii) // im }; GDALCopyWords(adfPixVal, GDT_CFloat64, 0, static_cast<GByte *>(pData) + static_cast<GSpacing>(nLineSpace) * iLine + iCol * nPixelSpace, eBufType, nPixelSpace, 1); } } /* ---- Return success ---- */ return CE_None; } // MakeComplexPixelFunc static CPLErr ModulePixelFunc( void **papoSources, int nSources, void *pData, int nXSize, int nYSize, GDALDataType eSrcType, GDALDataType eBufType, int nPixelSpace, int nLineSpace ) { /* ---- Init ---- */ if( nSources != 1 ) return CE_Failure; if( GDALDataTypeIsComplex( eSrcType ) ) { const void *pReal = papoSources[0]; const void *pImag = static_cast<GByte *>(papoSources[0]) + GDALGetDataTypeSizeBytes( eSrcType ) / 2; /* ---- Set pixels ---- */ size_t ii = 0; for( int iLine = 0; iLine < nYSize; ++iLine ) { for( int iCol = 0; iCol < nXSize; ++iCol, ++ii ) { // Source raster pixels may be obtained with GetSrcVal macro. const double dfReal = GetSrcVal(pReal, eSrcType, ii); const double dfImag = GetSrcVal(pImag, eSrcType, ii); const double dfPixVal = sqrt( dfReal * dfReal + dfImag * dfImag ); GDALCopyWords( &dfPixVal, GDT_Float64, 0, static_cast<GByte *>(pData) + static_cast<GSpacing>(nLineSpace) * iLine + iCol * nPixelSpace, eBufType, nPixelSpace, 1 ); } } } else { /* ---- Set pixels ---- */ size_t ii = 0; for( int iLine = 0; iLine < nYSize; ++iLine ) { for( int iCol = 0; iCol < nXSize; ++iCol, ++ii ) { // Source raster pixels may be obtained with GetSrcVal macro. const double dfPixVal = fabs(GetSrcVal(papoSources[0], eSrcType, ii)); GDALCopyWords( &dfPixVal, GDT_Float64, 0, static_cast<GByte *>(pData) + static_cast<GSpacing>(nLineSpace) * iLine + iCol * nPixelSpace, eBufType, nPixelSpace, 1 ); } } } /* ---- Return success ---- */ return CE_None; } // ModulePixelFunc static CPLErr PhasePixelFunc( void **papoSources, int nSources, void *pData, int nXSize, int nYSize, GDALDataType eSrcType, GDALDataType eBufType, int nPixelSpace, int nLineSpace ) { /* ---- Init ---- */ if( nSources != 1 ) return CE_Failure; if( GDALDataTypeIsComplex( eSrcType ) ) { const void * const pReal = papoSources[0]; const void * const pImag = static_cast<GByte *>(papoSources[0]) + GDALGetDataTypeSizeBytes( eSrcType ) / 2; /* ---- Set pixels ---- */ size_t ii = 0; for( int iLine = 0; iLine < nYSize; ++iLine ) { for( int iCol = 0; iCol < nXSize; ++iCol, ++ii ) { // Source raster pixels may be obtained with GetSrcVal macro. const double dfReal = GetSrcVal(pReal, eSrcType, ii); const double dfImag = GetSrcVal(pImag, eSrcType, ii); const double dfPixVal = atan2(dfImag, dfReal); GDALCopyWords( &dfPixVal, GDT_Float64, 0, static_cast<GByte *>(pData) + static_cast<GSpacing>(nLineSpace) * iLine + iCol * nPixelSpace, eBufType, nPixelSpace, 1 ); } } } else if( GDALDataTypeIsInteger( eSrcType ) && !GDALDataTypeIsSigned( eSrcType ) ) { constexpr double dfZero = 0; for( int iLine = 0; iLine < nYSize; ++iLine ) { GDALCopyWords( &dfZero, GDT_Float64, 0, static_cast<GByte *>(pData) + static_cast<GSpacing>(nLineSpace) * iLine, eBufType, nPixelSpace, nXSize ); } } else { /* ---- Set pixels ---- */ size_t ii = 0; for( int iLine = 0; iLine < nYSize; ++iLine ) { for( int iCol = 0; iCol < nXSize; ++iCol, ++ii ) { const void * const pReal = papoSources[0]; // Source raster pixels may be obtained with GetSrcVal macro. const double dfReal = GetSrcVal(pReal, eSrcType, ii); const double dfPixVal = (dfReal < 0) ? M_PI : 0.0; GDALCopyWords( &dfPixVal, GDT_Float64, 0, static_cast<GByte *>(pData) + static_cast<GSpacing>(nLineSpace) * iLine + iCol * nPixelSpace, eBufType, nPixelSpace, 1 ); } } } /* ---- Return success ---- */ return CE_None; } // PhasePixelFunc static CPLErr ConjPixelFunc( void **papoSources, int nSources, void *pData, int nXSize, int nYSize, GDALDataType eSrcType, GDALDataType eBufType, int nPixelSpace, int nLineSpace ) { /* ---- Init ---- */ if( nSources != 1 ) return CE_Failure; if( GDALDataTypeIsComplex( eSrcType ) && GDALDataTypeIsComplex( eBufType ) ) { const int nOffset = GDALGetDataTypeSizeBytes( eSrcType ) / 2; const void * const pReal = papoSources[0]; const void * const pImag = static_cast<GByte *>(papoSources[0]) + nOffset; /* ---- Set pixels ---- */ size_t ii = 0; for( int iLine = 0; iLine < nYSize; ++iLine ) { for( int iCol = 0; iCol < nXSize; ++iCol, ++ii ) { // Source raster pixels may be obtained with GetSrcVal macro. const double adfPixVal[2] = { +GetSrcVal(pReal, eSrcType, ii), // re -GetSrcVal(pImag, eSrcType, ii) // im }; GDALCopyWords( adfPixVal, GDT_CFloat64, 0, static_cast<GByte *>(pData) + static_cast<GSpacing>(nLineSpace) * iLine + iCol * nPixelSpace, eBufType, nPixelSpace, 1 ); } } } else { // No complex data type. return RealPixelFunc(papoSources, nSources, pData, nXSize, nYSize, eSrcType, eBufType, nPixelSpace, nLineSpace); } /* ---- Return success ---- */ return CE_None; } // ConjPixelFunc static CPLErr SumPixelFunc(void **papoSources, int nSources, void *pData, int nXSize, int nYSize, GDALDataType eSrcType, GDALDataType eBufType, int nPixelSpace, int nLineSpace) { /* ---- Init ---- */ if( nSources < 2 ) return CE_Failure; /* ---- Set pixels ---- */ if( GDALDataTypeIsComplex( eSrcType ) ) { const int nOffset = GDALGetDataTypeSizeBytes( eSrcType ) / 2; /* ---- Set pixels ---- */ size_t ii = 0; for( int iLine = 0; iLine < nYSize; ++iLine ) { for( int iCol = 0; iCol < nXSize; ++iCol, ++ii ) { double adfSum[2] = { 0.0, 0.0 }; for( int iSrc = 0; iSrc < nSources; ++iSrc ) { const void * const pReal = papoSources[iSrc]; const void * const pImag = static_cast<const GByte *>(pReal) + nOffset; // Source raster pixels may be obtained with GetSrcVal macro. adfSum[0] += GetSrcVal(pReal, eSrcType, ii); adfSum[1] += GetSrcVal(pImag, eSrcType, ii); } GDALCopyWords( adfSum, GDT_CFloat64, 0, static_cast<GByte *>(pData) + static_cast<GSpacing>(nLineSpace) * iLine + iCol * nPixelSpace, eBufType, nPixelSpace, 1); } } } else { /* ---- Set pixels ---- */ size_t ii = 0; for( int iLine = 0; iLine < nYSize; ++iLine ) { for( int iCol = 0; iCol < nXSize; ++iCol, ++ii ) { double dfSum = 0; // Not complex. for( int iSrc = 0; iSrc < nSources; ++iSrc ) { // Source raster pixels may be obtained with GetSrcVal macro. dfSum += GetSrcVal(papoSources[iSrc], eSrcType, ii); } GDALCopyWords( &dfSum, GDT_Float64, 0, static_cast<GByte *>(pData) + static_cast<GSpacing>(nLineSpace) * iLine + iCol * nPixelSpace, eBufType, nPixelSpace, 1); } } } /* ---- Return success ---- */ return CE_None; } /* SumPixelFunc */ static CPLErr DiffPixelFunc( void **papoSources, int nSources, void *pData, int nXSize, int nYSize, GDALDataType eSrcType, GDALDataType eBufType, int nPixelSpace, int nLineSpace) { /* ---- Init ---- */ if( nSources != 2 ) return CE_Failure; if( GDALDataTypeIsComplex( eSrcType ) ) { const int nOffset = GDALGetDataTypeSizeBytes( eSrcType ) / 2; const void * const pReal0 = papoSources[0]; const void * const pImag0 = static_cast<GByte *>(papoSources[0]) + nOffset; const void * const pReal1 = papoSources[1]; const void * const pImag1 = static_cast<GByte *>(papoSources[1]) + nOffset; /* ---- Set pixels ---- */ size_t ii = 0; for( int iLine = 0; iLine < nYSize; ++iLine ) { for( int iCol = 0; iCol < nXSize; ++iCol, ++ii ) { // Source raster pixels may be obtained with GetSrcVal macro. double adfPixVal[2] = { GetSrcVal(pReal0, eSrcType, ii) - GetSrcVal(pReal1, eSrcType, ii), GetSrcVal(pImag0, eSrcType, ii) - GetSrcVal(pImag1, eSrcType, ii) }; GDALCopyWords( adfPixVal, GDT_CFloat64, 0, static_cast<GByte *>(pData) + static_cast<GSpacing>(nLineSpace) * iLine + iCol * nPixelSpace, eBufType, nPixelSpace, 1 ); } } } else { /* ---- Set pixels ---- */ size_t ii = 0; for( int iLine = 0; iLine < nYSize; ++iLine ) { for( int iCol = 0; iCol < nXSize; ++iCol, ++ii ) { // Source raster pixels may be obtained with GetSrcVal macro. // Not complex. const double dfPixVal = GetSrcVal(papoSources[0], eSrcType, ii) - GetSrcVal(papoSources[1], eSrcType, ii); GDALCopyWords( &dfPixVal, GDT_Float64, 0, static_cast<GByte *>(pData) + static_cast<GSpacing>(nLineSpace) * iLine + iCol * nPixelSpace, eBufType, nPixelSpace, 1); } } } /* ---- Return success ---- */ return CE_None; } // DiffPixelFunc static CPLErr MulPixelFunc( void **papoSources, int nSources, void *pData, int nXSize, int nYSize, GDALDataType eSrcType, GDALDataType eBufType, int nPixelSpace, int nLineSpace ) { /* ---- Init ---- */ if( nSources < 2 ) return CE_Failure; /* ---- Set pixels ---- */ if( GDALDataTypeIsComplex( eSrcType ) ) { const int nOffset = GDALGetDataTypeSizeBytes( eSrcType ) / 2; /* ---- Set pixels ---- */ size_t ii = 0; for( int iLine = 0; iLine < nYSize; ++iLine ) { for( int iCol = 0; iCol < nXSize; ++iCol, ++ii ) { double adfPixVal[2] = { 1.0, 0.0 }; for( int iSrc = 0; iSrc < nSources; ++iSrc ) { const void * const pReal = papoSources[iSrc]; const void * const pImag = static_cast<const GByte *>(pReal) + nOffset; const double dfOldR = adfPixVal[0]; const double dfOldI = adfPixVal[1]; // Source raster pixels may be obtained with GetSrcVal macro. const double dfNewR = GetSrcVal(pReal, eSrcType, ii); const double dfNewI = GetSrcVal(pImag, eSrcType, ii); adfPixVal[0] = dfOldR * dfNewR - dfOldI * dfNewI; adfPixVal[1] = dfOldR * dfNewI + dfOldI * dfNewR; } GDALCopyWords( adfPixVal, GDT_CFloat64, 0, static_cast<GByte *>(pData) + static_cast<GSpacing>(nLineSpace) * iLine + iCol * nPixelSpace, eBufType, nPixelSpace, 1); } } } else { /* ---- Set pixels ---- */ size_t ii = 0; for( int iLine = 0; iLine < nYSize; ++iLine ) { for( int iCol = 0; iCol < nXSize; ++iCol, ++ii ) { double dfPixVal = 1.0; // Not complex. for( int iSrc = 0; iSrc < nSources; ++iSrc ) { // Source raster pixels may be obtained with GetSrcVal macro. dfPixVal *= GetSrcVal(papoSources[iSrc], eSrcType, ii); } GDALCopyWords( &dfPixVal, GDT_Float64, 0, static_cast<GByte *>(pData) + static_cast<GSpacing>(nLineSpace) * iLine + iCol * nPixelSpace, eBufType, nPixelSpace, 1); } } } /* ---- Return success ---- */ return CE_None; } // MulPixelFunc static CPLErr CMulPixelFunc( void **papoSources, int nSources, void *pData, int nXSize, int nYSize, GDALDataType eSrcType, GDALDataType eBufType, int nPixelSpace, int nLineSpace ) { /* ---- Init ---- */ if( nSources != 2 ) return CE_Failure; /* ---- Set pixels ---- */ if( GDALDataTypeIsComplex( eSrcType ) ) { const int nOffset = GDALGetDataTypeSizeBytes( eSrcType ) / 2; const void * const pReal0 = papoSources[0]; const void * const pImag0 = static_cast<GByte *>(papoSources[0]) + nOffset; const void * const pReal1 = papoSources[1]; const void * const pImag1 = static_cast<GByte *>(papoSources[1]) + nOffset; size_t ii = 0; for( int iLine = 0; iLine < nYSize; ++iLine ) { for( int iCol = 0; iCol < nXSize; ++iCol, ++ii ) { // Source raster pixels may be obtained with GetSrcVal macro. const double dfReal0 = GetSrcVal(pReal0, eSrcType, ii); const double dfReal1 = GetSrcVal(pReal1, eSrcType, ii); const double dfImag0 = GetSrcVal(pImag0, eSrcType, ii); const double dfImag1 = GetSrcVal(pImag1, eSrcType, ii); const double adfPixVal[2] = { dfReal0 * dfReal1 + dfImag0 * dfImag1, dfReal1 * dfImag0 - dfReal0 * dfImag1 }; GDALCopyWords( adfPixVal, GDT_CFloat64, 0, static_cast<GByte *>(pData) + static_cast<GSpacing>(nLineSpace) * iLine + iCol * nPixelSpace, eBufType, nPixelSpace, 1 ); } } } else { size_t ii = 0; for( int iLine = 0; iLine < nYSize; ++iLine ) { for( int iCol = 0; iCol < nXSize; ++iCol, ++ii ) { // Source raster pixels may be obtained with GetSrcVal macro. // Not complex. const double adfPixVal[2] = { GetSrcVal(papoSources[0], eSrcType, ii) * GetSrcVal(papoSources[1], eSrcType, ii), 0.0 }; GDALCopyWords( adfPixVal, GDT_CFloat64, 0, static_cast<GByte *>(pData) + static_cast<GSpacing>(nLineSpace) * iLine + iCol * nPixelSpace, eBufType, nPixelSpace, 1 ); } } } /* ---- Return success ---- */ return CE_None; } // CMulPixelFunc static CPLErr InvPixelFunc( void **papoSources, int nSources, void *pData, int nXSize, int nYSize, GDALDataType eSrcType, GDALDataType eBufType, int nPixelSpace, int nLineSpace ) { /* ---- Init ---- */ if( nSources != 1 ) return CE_Failure; /* ---- Set pixels ---- */ if( GDALDataTypeIsComplex( eSrcType ) ) { const int nOffset = GDALGetDataTypeSizeBytes( eSrcType ) / 2; const void * const pReal = papoSources[0]; const void * const pImag = static_cast<GByte *>(papoSources[0]) + nOffset; size_t ii = 0; for( int iLine = 0; iLine < nYSize; ++iLine ) { for( int iCol = 0; iCol < nXSize; ++iCol, ++ii ) { // Source raster pixels may be obtained with GetSrcVal macro. const double dfReal = GetSrcVal(pReal, eSrcType, ii); const double dfImag = GetSrcVal(pImag, eSrcType, ii); const double dfAux = dfReal * dfReal + dfImag * dfImag; const double adfPixVal[2] = { dfAux == 0 ? std::numeric_limits<double>::infinity() : dfReal / dfAux, dfAux == 0 ? std::numeric_limits<double>::infinity() : -dfImag / dfAux }; GDALCopyWords( adfPixVal, GDT_CFloat64, 0, static_cast<GByte *>(pData) + static_cast<GSpacing>(nLineSpace) * iLine + iCol * nPixelSpace, eBufType, nPixelSpace, 1); } } } else { /* ---- Set pixels ---- */ size_t ii = 0; for( int iLine = 0; iLine < nYSize; ++iLine ) { for( int iCol = 0; iCol < nXSize; ++iCol, ++ii ) { // Source raster pixels may be obtained with GetSrcVal macro. // Not complex. const double dfVal = GetSrcVal(papoSources[0], eSrcType, ii); const double dfPixVal = dfVal == 0 ? std::numeric_limits<double>::infinity() : 1.0 / dfVal; GDALCopyWords( &dfPixVal, GDT_Float64, 0, static_cast<GByte *>(pData) + static_cast<GSpacing>(nLineSpace) * iLine + iCol * nPixelSpace, eBufType, nPixelSpace, 1 ); } } } /* ---- Return success ---- */ return CE_None; } // InvPixelFunc static CPLErr IntensityPixelFunc( void **papoSources, int nSources, void *pData, int nXSize, int nYSize, GDALDataType eSrcType, GDALDataType eBufType, int nPixelSpace, int nLineSpace ) { /* ---- Init ---- */ if( nSources != 1 ) return CE_Failure; if( GDALDataTypeIsComplex( eSrcType ) ) { const int nOffset = GDALGetDataTypeSizeBytes( eSrcType ) / 2; const void * const pReal = papoSources[0]; const void * const pImag = static_cast<GByte *>(papoSources[0]) + nOffset; /* ---- Set pixels ---- */ size_t ii = 0; for( int iLine = 0; iLine < nYSize; ++iLine ) { for( int iCol = 0; iCol < nXSize; ++iCol, ++ii ) { // Source raster pixels may be obtained with GetSrcVal macro. const double dfReal = GetSrcVal(pReal, eSrcType, ii); const double dfImag = GetSrcVal(pImag, eSrcType, ii); const double dfPixVal = dfReal * dfReal + dfImag * dfImag; GDALCopyWords( &dfPixVal, GDT_Float64, 0, static_cast<GByte *>(pData) + static_cast<GSpacing>(nLineSpace) * iLine + iCol * nPixelSpace, eBufType, nPixelSpace, 1); } } } else { /* ---- Set pixels ---- */ size_t ii = 0; for( int iLine = 0; iLine < nYSize; ++iLine ) { for( int iCol = 0; iCol < nXSize; ++iCol, ++ii ) { // Source raster pixels may be obtained with GetSrcVal macro. double dfPixVal = GetSrcVal(papoSources[0], eSrcType, ii); dfPixVal *= dfPixVal; GDALCopyWords( &dfPixVal, GDT_Float64, 0, static_cast<GByte *>(pData) + static_cast<GSpacing>(nLineSpace) * iLine + iCol * nPixelSpace, eBufType, nPixelSpace, 1); } } } /* ---- Return success ---- */ return CE_None; } // IntensityPixelFunc static CPLErr SqrtPixelFunc( void **papoSources, int nSources, void *pData, int nXSize, int nYSize, GDALDataType eSrcType, GDALDataType eBufType, int nPixelSpace, int nLineSpace ) { /* ---- Init ---- */ if( nSources != 1 ) return CE_Failure; if( GDALDataTypeIsComplex( eSrcType ) ) return CE_Failure; /* ---- Set pixels ---- */ size_t ii = 0; for( int iLine = 0; iLine < nYSize; ++iLine ) { for( int iCol = 0; iCol < nXSize; ++iCol, ++ii ) { // Source raster pixels may be obtained with GetSrcVal macro. const double dfPixVal = sqrt( GetSrcVal(papoSources[0], eSrcType, ii) ); GDALCopyWords( &dfPixVal, GDT_Float64, 0, static_cast<GByte *>(pData) + static_cast<GSpacing>(nLineSpace) * iLine + iCol * nPixelSpace, eBufType, nPixelSpace, 1); } } /* ---- Return success ---- */ return CE_None; } // SqrtPixelFunc static CPLErr Log10PixelFuncHelper( void **papoSources, int nSources, void *pData, int nXSize, int nYSize, GDALDataType eSrcType, GDALDataType eBufType, int nPixelSpace, int nLineSpace, double fact ) { /* ---- Init ---- */ if( nSources != 1 ) return CE_Failure; if( GDALDataTypeIsComplex( eSrcType ) ) { // Complex input datatype. const int nOffset = GDALGetDataTypeSizeBytes( eSrcType ) / 2; const void * const pReal = papoSources[0]; const void * const pImag = static_cast<GByte *>(papoSources[0]) + nOffset; /* ---- Set pixels ---- */ size_t ii = 0; for( int iLine = 0; iLine < nYSize; ++iLine ) { for( int iCol = 0; iCol < nXSize; ++iCol, ++ii ) { // Source raster pixels may be obtained with GetSrcVal macro. const double dfReal = GetSrcVal(pReal, eSrcType, ii); const double dfImag = GetSrcVal(pImag, eSrcType, ii); const double dfPixVal = fact * log10( sqrt( dfReal * dfReal + dfImag * dfImag ) ); GDALCopyWords( &dfPixVal, GDT_Float64, 0, static_cast<GByte *>(pData) + static_cast<GSpacing>(nLineSpace) * iLine + iCol * nPixelSpace, eBufType, nPixelSpace, 1 ); } } } else { /* ---- Set pixels ---- */ size_t ii = 0; for( int iLine = 0; iLine < nYSize; ++iLine ) { for( int iCol = 0; iCol < nXSize; ++iCol, ++ii ) { // Source raster pixels may be obtained with GetSrcVal macro. const double dfPixVal = fact * log10( fabs( GetSrcVal(papoSources[0], eSrcType, ii) ) ); GDALCopyWords( &dfPixVal, GDT_Float64, 0, static_cast<GByte *>(pData) + static_cast<GSpacing>(nLineSpace) * iLine + iCol * nPixelSpace, eBufType, nPixelSpace, 1 ); } } } /* ---- Return success ---- */ return CE_None; } // Log10PixelFuncHelper static CPLErr Log10PixelFunc( void **papoSources, int nSources, void *pData, int nXSize, int nYSize, GDALDataType eSrcType, GDALDataType eBufType, int nPixelSpace, int nLineSpace ) { return Log10PixelFuncHelper(papoSources, nSources, pData, nXSize, nYSize, eSrcType, eBufType, nPixelSpace, nLineSpace, 1.0); } // Log10PixelFunc static CPLErr DBPixelFunc( void **papoSources, int nSources, void *pData, int nXSize, int nYSize, GDALDataType eSrcType, GDALDataType eBufType, int nPixelSpace, int nLineSpace ) { return Log10PixelFuncHelper(papoSources, nSources, pData, nXSize, nYSize, eSrcType, eBufType, nPixelSpace, nLineSpace, 20.0); } // DBPixelFunc static CPLErr PowPixelFuncHelper( void **papoSources, int nSources, void *pData, int nXSize, int nYSize, GDALDataType eSrcType, GDALDataType eBufType, int nPixelSpace, int nLineSpace, double base, double fact ) { /* ---- Init ---- */ if( nSources != 1 ) return CE_Failure; if( GDALDataTypeIsComplex( eSrcType ) ) return CE_Failure; /* ---- Set pixels ---- */ size_t ii = 0; for( int iLine = 0; iLine < nYSize; ++iLine ) { for( int iCol = 0; iCol < nXSize; ++iCol, ++ii ) { // Source raster pixels may be obtained with GetSrcVal macro. const double dfPixVal = pow(base, GetSrcVal(papoSources[0], eSrcType, ii) / fact); GDALCopyWords( &dfPixVal, GDT_Float64, 0, static_cast<GByte *>(pData) + static_cast<GSpacing>(nLineSpace) * iLine + iCol * nPixelSpace, eBufType, nPixelSpace, 1); } } /* ---- Return success ---- */ return CE_None; } // PowPixelFuncHelper static CPLErr dB2AmpPixelFunc( void **papoSources, int nSources, void *pData, int nXSize, int nYSize, GDALDataType eSrcType, GDALDataType eBufType, int nPixelSpace, int nLineSpace ) { return PowPixelFuncHelper(papoSources, nSources, pData, nXSize, nYSize, eSrcType, eBufType, nPixelSpace, nLineSpace, 10.0, 20.0); } // dB2AmpPixelFunc static CPLErr dB2PowPixelFunc( void **papoSources, int nSources, void *pData, int nXSize, int nYSize, GDALDataType eSrcType, GDALDataType eBufType, int nPixelSpace, int nLineSpace ) { return PowPixelFuncHelper(papoSources, nSources, pData, nXSize, nYSize, eSrcType, eBufType, nPixelSpace, nLineSpace, 10.0, 10.0); } // dB2PowPixelFunc static CPLErr PowPixelFunc( void **papoSources, int nSources, void *pData, int nXSize, int nYSize, GDALDataType eSrcType, GDALDataType eBufType, int nPixelSpace, int nLineSpace, CSLConstList papszArgs ) { /* ---- Init ---- */ if( nSources != 1 ) return CE_Failure; if( GDALDataTypeIsComplex( eSrcType ) ) return CE_Failure; double power; if ( FetchDoubleArg(papszArgs, "power", &power) != CE_None ) return CE_Failure; /* ---- Set pixels ---- */ size_t ii = 0; for( int iLine = 0; iLine < nYSize; ++iLine ) { for( int iCol = 0; iCol < nXSize; ++iCol, ++ii ) { const double dfPixVal = std::pow( GetSrcVal(papoSources[0], eSrcType, ii), power); GDALCopyWords( &dfPixVal, GDT_Float64, 0, static_cast<GByte *>(pData) + static_cast<GSpacing>(nLineSpace) * iLine + iCol * nPixelSpace, eBufType, nPixelSpace, 1); } } /* ---- Return success ---- */ return CE_None; } // Given nt intervals spaced by dt and beginning at t0, return the the index of // the lower bound of the interval that should be used to interpolate/extrapolate // a value for t. static std::size_t intervalLeft(double t0, double dt, std::size_t nt, double t) { if (t < t0) { return 0; } std::size_t n = static_cast<std::size_t>((t - t0) / dt); if (n >= nt - 1) { return nt - 2; } return n; } static double InterpolateLinear(double dfX0, double dfX1, double dfY0, double dfY1, double dfX) { return dfY0 + (dfX - dfX0) * (dfY1 - dfY0) / (dfX1 - dfX0); } static double InterpolateExponential(double dfX0, double dfX1, double dfY0, double dfY1, double dfX) { const double r = std::log(dfY1 / dfY0) / (dfX1 - dfX0); return dfY0*std::exp(r * (dfX - dfX0)); } template<decltype(InterpolateLinear) InterpolationFunction> CPLErr InterpolatePixelFunc( void **papoSources, int nSources, void *pData, int nXSize, int nYSize, GDALDataType eSrcType, GDALDataType eBufType, int nPixelSpace, int nLineSpace, CSLConstList papszArgs ) { /* ---- Init ---- */ if( GDALDataTypeIsComplex( eSrcType ) ) return CE_Failure; double dfT0; if (FetchDoubleArg(papszArgs, "t0", &dfT0) == CE_Failure ) return CE_Failure; double dfT; if (FetchDoubleArg(papszArgs, "t", &dfT) == CE_Failure ) return CE_Failure; double dfDt; if (FetchDoubleArg(papszArgs, "dt", &dfDt) == CE_Failure ) return CE_Failure; if( nSources < 2 ) { CPLError(CE_Failure, CPLE_AppDefined, "At least two sources required for interpolation."); return CE_Failure; } if (dfT == 0 || !std::isfinite(dfT) ) { CPLError(CE_Failure, CPLE_AppDefined, "dt must be finite and non-zero"); return CE_Failure; } const auto i0 = intervalLeft(dfT0, dfDt, nSources, dfT); const auto i1 = i0 + 1; dfT0 = dfT0 + static_cast<double>(i0) * dfDt; double dfX1 = dfT0 + dfDt; /* ---- Set pixels ---- */ size_t ii = 0; for( int iLine = 0; iLine < nYSize; ++iLine ) { for( int iCol = 0; iCol < nXSize; ++iCol, ++ii ) { const double dfY0 = GetSrcVal(papoSources[i0], eSrcType, ii); const double dfY1 = GetSrcVal(papoSources[i1], eSrcType, ii); const double dfPixVal = InterpolationFunction(dfT0, dfX1, dfY0, dfY1, dfT); GDALCopyWords( &dfPixVal, GDT_Float64, 0, static_cast<GByte *>(pData) + static_cast<GSpacing>(nLineSpace) * iLine + iCol * nPixelSpace, eBufType, nPixelSpace, 1); } } /* ---- Return success ---- */ return CE_None; } /************************************************************************/ /* GDALRegisterDefaultPixelFunc() */ /************************************************************************/ /** * This adds a default set of pixel functions to the global list of * available pixel functions for derived bands: * * - "real": extract real part from a single raster band (just a copy if the * input is non-complex) * - "imag": extract imaginary part from a single raster band (0 for * non-complex) * - "complex": make a complex band merging two bands used as real and * imag values * - "mod": extract module from a single raster band (real or complex) * - "phase": extract phase from a single raster band [-PI,PI] (0 or PI for non-complex) * - "conj": computes the complex conjugate of a single raster band (just a * copy if the input is non-complex) * - "sum": sum 2 or more raster bands * - "diff": computes the difference between 2 raster bands (b1 - b2) * - "mul": multiply 2 or more raster bands * - "cmul": multiply the first band for the complex conjugate of the second * - "inv": inverse (1./x). Note: no check is performed on zero division * - "intensity": computes the intensity Re(x*conj(x)) of a single raster band * (real or complex) * - "sqrt": perform the square root of a single raster band (real only) * - "log10": compute the logarithm (base 10) of the abs of a single raster * band (real or complex): log10( abs( x ) ) * - "dB": perform conversion to dB of the abs of a single raster * band (real or complex): 20. * log10( abs( x ) ) * - "dB2amp": perform scale conversion from logarithmic to linear * (amplitude) (i.e. 10 ^ ( x / 20 ) ) of a single raster * band (real only) * - "dB2pow": perform scale conversion from logarithmic to linear * (power) (i.e. 10 ^ ( x / 10 ) ) of a single raster * band (real only) * - "pow": raise a single raster band to a constant power * - "interpolate_linear": interpolate values between two raster bands * using linear interpolation * - "interpolate_exp": interpolate values between two raster bands using * exponential interpolation * * @see GDALAddDerivedBandPixelFunc * * @return CE_None */ CPLErr GDALRegisterDefaultPixelFunc() { GDALAddDerivedBandPixelFunc("real", RealPixelFunc); GDALAddDerivedBandPixelFunc("imag", ImagPixelFunc); GDALAddDerivedBandPixelFunc("complex", ComplexPixelFunc); GDALAddDerivedBandPixelFunc("mod", ModulePixelFunc); GDALAddDerivedBandPixelFunc("phase", PhasePixelFunc); GDALAddDerivedBandPixelFunc("conj", ConjPixelFunc); GDALAddDerivedBandPixelFunc("sum", SumPixelFunc); GDALAddDerivedBandPixelFunc("diff", DiffPixelFunc); GDALAddDerivedBandPixelFunc("mul", MulPixelFunc); GDALAddDerivedBandPixelFunc("cmul", CMulPixelFunc); GDALAddDerivedBandPixelFunc("inv", InvPixelFunc); GDALAddDerivedBandPixelFunc("intensity", IntensityPixelFunc); GDALAddDerivedBandPixelFunc("sqrt", SqrtPixelFunc); GDALAddDerivedBandPixelFunc("log10", Log10PixelFunc); GDALAddDerivedBandPixelFunc("dB", DBPixelFunc); GDALAddDerivedBandPixelFunc("dB2amp", dB2AmpPixelFunc); GDALAddDerivedBandPixelFunc("dB2pow", dB2PowPixelFunc); GDALAddDerivedBandPixelFuncWithArgs("pow", PowPixelFunc, nullptr); GDALAddDerivedBandPixelFuncWithArgs("interpolate_linear", InterpolatePixelFunc<InterpolateLinear>, nullptr); GDALAddDerivedBandPixelFuncWithArgs("interpolate_exp", InterpolatePixelFunc<InterpolateExponential>, nullptr); return CE_None; }
23,710
1,056
<gh_stars>1000+ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.editor.lib2.view; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.InputEvent; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; import java.awt.font.FontRenderContext; import java.awt.font.TextLayout; import java.awt.geom.Rectangle2D; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.lang.ref.Reference; import java.lang.ref.WeakReference; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import java.util.prefs.PreferenceChangeEvent; import java.util.prefs.PreferenceChangeListener; import java.util.prefs.Preferences; import javax.swing.Action; import javax.swing.JLayeredPane; import javax.swing.JScrollBar; import javax.swing.JScrollPane; import javax.swing.JViewport; import javax.swing.KeyStroke; import javax.swing.RepaintManager; import javax.swing.SwingUtilities; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.plaf.ScrollPaneUI; import javax.swing.text.AttributeSet; import javax.swing.text.Document; import javax.swing.text.JTextComponent; import javax.swing.text.Keymap; import javax.swing.text.StyleConstants; import org.netbeans.api.editor.mimelookup.MimeLookup; import org.netbeans.api.editor.settings.FontColorNames; import org.netbeans.api.editor.settings.FontColorSettings; import org.netbeans.api.editor.settings.SimpleValueNames; import org.netbeans.lib.editor.util.swing.DocumentUtilities; import org.netbeans.modules.editor.lib2.EditorPreferencesDefaults; import org.openide.util.Lookup; import org.openide.util.LookupEvent; import org.openide.util.LookupListener; import org.openide.util.WeakListeners; /** * Document View operation management. * * @author <NAME> */ @SuppressWarnings("ClassWithMultipleLoggers") //NOI18N public final class DocumentViewOp implements PropertyChangeListener, ChangeListener { // -J-Dorg.netbeans.modules.editor.lib2.view.DocumentViewOp.level=FINE private static final Logger LOG = Logger.getLogger(DocumentViewOp.class.getName()); // Whether use fractional metrics rendering hint static final Map<Object, Object> extraRenderingHints = new HashMap<Object, Object>(); static final Boolean doubleBuffered; static { String aa = System.getProperty("org.netbeans.editor.aa"); if (aa != null) { extraRenderingHints.put(RenderingHints.KEY_ANTIALIASING, (Boolean.parseBoolean(aa) || "on".equals(aa)) ? RenderingHints.VALUE_ANTIALIAS_ON : ("false".equalsIgnoreCase(aa) || "off".equals(aa)) ? RenderingHints.VALUE_ANTIALIAS_OFF : RenderingHints.VALUE_ANTIALIAS_DEFAULT); } String aaText = System.getProperty("org.netbeans.editor.aa.text"); if (aaText != null) { extraRenderingHints.put(RenderingHints.KEY_TEXT_ANTIALIASING, (Boolean.parseBoolean(aaText) || "on".equals(aaText)) ? RenderingHints.VALUE_TEXT_ANTIALIAS_ON : "gasp".equals(aaText) ? RenderingHints.VALUE_TEXT_ANTIALIAS_GASP : "hbgr".equals(aaText) ? RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HBGR : "hrgb".equals(aaText) ? RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB : "vbgr".equals(aaText) ? RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_VBGR : "vrgb".equals(aaText) ? RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_VRGB : ("false".equalsIgnoreCase(aaText) || "off".equals(aaText)) ? RenderingHints.VALUE_TEXT_ANTIALIAS_OFF : RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT); } String useFractionalMetrics = System.getProperty("org.netbeans.editor.aa.fractional"); if (useFractionalMetrics != null) { extraRenderingHints.put(RenderingHints.KEY_FRACTIONALMETRICS, (Boolean.parseBoolean(useFractionalMetrics) || "on".equals(useFractionalMetrics)) ? RenderingHints.VALUE_FRACTIONALMETRICS_ON : ("false".equalsIgnoreCase(useFractionalMetrics) || "off".equals(useFractionalMetrics)) ? RenderingHints.VALUE_FRACTIONALMETRICS_OFF : RenderingHints.VALUE_FRACTIONALMETRICS_DEFAULT); } String rendering = System.getProperty("org.netbeans.editor.aa.rendering"); if (rendering != null) { extraRenderingHints.put(RenderingHints.KEY_RENDERING, ("quality".equals(rendering)) ? RenderingHints.VALUE_RENDER_QUALITY : ("speed".equals(rendering)) ? RenderingHints.VALUE_RENDER_SPEED : RenderingHints.VALUE_RENDER_DEFAULT); } String strokeControl = System.getProperty("org.netbeans.editor.aa.stroke"); if (strokeControl != null) { extraRenderingHints.put(RenderingHints.KEY_STROKE_CONTROL, "normalize".equals(strokeControl) ? RenderingHints.VALUE_STROKE_NORMALIZE : "pure".equals(strokeControl) ? RenderingHints.VALUE_STROKE_PURE : RenderingHints.VALUE_STROKE_DEFAULT); } String contrast = System.getProperty("org.netbeans.editor.aa.contrast"); // Integer expected if (contrast != null) { try { extraRenderingHints.put(RenderingHints.KEY_TEXT_LCD_CONTRAST, Integer.parseInt(contrast)); } catch (NumberFormatException ex) { // Do not add the key } } String dBuffered = System.getProperty("org.netbeans.editor.double.buffered"); doubleBuffered = (dBuffered != null) ? Boolean.parseBoolean(dBuffered) : null; } static final char PRINTING_SPACE = '\u00B7'; static final char PRINTING_TAB = '\u2192'; static final char PRINTING_TAB_ALTERNATE = '\u00BB'; static final char PRINTING_NEWLINE = '\u00B6'; static final char LINE_CONTINUATION = '\u21A9'; static final char LINE_CONTINUATION_ALTERNATE = '\u2190'; private static final int ALLOCATION_WIDTH_CHANGE = 1; private static final int ALLOCATION_HEIGHT_CHANGE = 2; private static final int WIDTH_CHANGE = 4; private static final int HEIGHT_CHANGE = 8; /** * Whether the "children" is currently reflecting the document state. * <br> * The children may hold a semi-valid view hierarchy which may still be partly used * to resolve queries in some cases. */ private static final int CHILDREN_VALID = 16; /** * Whether there's a pending document modification so the view hierarchy should not be active * until it gets updated by the pending modification. */ private static final int INCOMING_MODIFICATION = 32; /** * Whether view hierarchy currently fires a change so any queries to view hierarchy are prohibited. */ private static final int FIRING_CHANGE = 64; private static final int ACCURATE_SPAN = 128; private static final int AVAILABLE_WIDTH_VALID = 256; private static final int NON_PRINTABLE_CHARACTERS_VISIBLE = 512; private static final int UPDATE_VISIBLE_DIMENSION_PENDING = 1024; private static final String ORIG_MOUSE_WHEEL_LISTENER_PROP = "orig-mouse-wheel-listener"; private final DocumentView docView; private int statusBits; /** * Maintenance of view updates. * If this is a preview-only view e.g. for a collapsed fold preview * when located over collapsed fold's tooltip. */ ViewUpdates viewUpdates; // pkg-private for tests private final TextLayoutCache textLayoutCache; /** * New width assigned by DocumentView.setSize() - it will be processed once a lock is acquired. */ private float newAllocationWidth; private float newAllocationHeight; /** * Visible rectangle of the viewport or a text component if there is no viewport. * Initial size should not be zero since when querying DocView for preferred horizontal span * for a component that was not laid out yet (e.g. a FoldView) * with linewrap set to "anywhere" the views would attempt to fit into zero width. */ private Rectangle visibleRect = new Rectangle(0, 0, Integer.MAX_VALUE, Integer.MAX_VALUE); private float availableWidth; private float renderWrapWidth; private double repaintX0; private double repaintY0; private double repaintX1; private double repaintY1; /** * Cached font render context (in order not to call getContainer().getGraphics() etc. each time). * It appears the FontRenderContext class is not extended (inspected SunGraphics2D) * so it should be safe and work fine. */ private FontRenderContext fontRenderContext; private AttributeSet defaultColoring; /** * Default row height computed as height of the defaultFont. */ private int defaultRowHeightInt; private int defaultAscentInt; private float defaultCharWidth; private Color textLimitLineColor; private int textLimitLineX; private LineWrapType lineWrapType; private TextLayout newlineTextLayout; private TextLayout tabTextLayout; private TextLayout singleCharTabTextLayout; private TextLayout lineContinuationTextLayout; private LookupListener lookupListener; private JViewport activeViewport; private JScrollPane activeScrollPane; private Preferences prefs; private PreferenceChangeListener prefsListener; Map<?, ?> renderingHints; private int lengthyAtomicEdit; // Long atomic edit being performed ViewHierarchyImpl viewHierarchyImpl; // Assigned upon setParent() private Map<Font,FontInfo> fontInfos = new HashMap<Font, FontInfo>(4); private Font defaultFont; private Font defaultHintFont; private boolean fontRenderContextFromPaint; /** * Constant retrieved from preferences settings that allows the user to increase/decrease * paragraph view's height (which may help for problematic fonts that do not report its height * correctly for them to fit the line). * <br> * By default it's 1.0. All the ascents, descent and leadings of all fonts * are multiplied by the constant. */ private float rowHeightCorrection = 1.0f; private int textZoom; /** * Extra height of 1/3 of viewport's window height added to the real views' allocation. */ private float extraVirtualHeight; boolean asTextField; private boolean guideLinesEnable; private boolean inlineHintsEnable; private int indentLevelSize; private int tabSize; private Color guideLinesColor; private int[] guideLinesCache = { -1, -1, -1}; public DocumentViewOp(DocumentView docView) { this.docView = docView; textLayoutCache = new TextLayoutCache(); } public ViewHierarchyImpl viewHierarchyImpl() { return viewHierarchyImpl; } public boolean isChildrenValid() { return isAnyStatusBit(CHILDREN_VALID); } /** * Rebuild views if there are any pending highlight factory changes reported. * Method ensures proper locking of document and view hierarchy. */ public void viewsRebuildOrMarkInvalid() { docView.runReadLockTransaction(new Runnable() { @Override public void run() { if (viewUpdates != null) { viewUpdates.viewsRebuildOrMarkInvalidNeedsLock(); } } }); } void notifyWidthChange() { setStatusBits(WIDTH_CHANGE); if (ViewHierarchyImpl.SPAN_LOG.isLoggable(Level.FINE)) { ViewUtils.log(ViewHierarchyImpl.SPAN_LOG, "DV-WIDTH changed\n"); // NOI18N } } boolean isWidthChange() { return isAnyStatusBit(WIDTH_CHANGE); } private void resetWidthChange() { clearStatusBits(WIDTH_CHANGE); } /** * If width-change was notified then check if real change occurred comparing * current width and width of children. * @return true if real change occurred. */ private boolean checkRealWidthChange() { if (isWidthChange()) { resetWidthChange(); return docView.updatePreferredWidth(); } return false; } void notifyHeightChange() { setStatusBits(HEIGHT_CHANGE); if (ViewHierarchyImpl.SPAN_LOG.isLoggable(Level.FINE)) { ViewUtils.log(ViewHierarchyImpl.SPAN_LOG, "DV-HEIGHT changed\n"); // NOI18N } } boolean isHeightChange() { return isAnyStatusBit(HEIGHT_CHANGE); } private void resetHeightChange() { clearStatusBits(HEIGHT_CHANGE); } /** * If height-change was notified then check if real change occurred comparing * current height and height of children. * @return true if real change occurred. */ private boolean checkRealHeightChange() { if (isHeightChange()) { resetHeightChange(); return docView.updatePreferredHeight(); } return false; } void markAllocationWidthChange(float newWidth) { setStatusBits(ALLOCATION_WIDTH_CHANGE); newAllocationWidth = newWidth; } void markAllocationHeightChange(float newHeight) { setStatusBits(ALLOCATION_HEIGHT_CHANGE); newAllocationHeight = newHeight; } /** * Set given status bits to 1. */ private void setStatusBits(int bits) { statusBits |= bits; } /** * Set given status bits to 0. */ private void clearStatusBits(int bits) { statusBits &= ~bits; } /** * Set all given status bits to the given value. * @param bits status bits to be updated. * @param value true to change all status bits to 1 or false to change them to 0. */ private void updateStatusBits(int bits, boolean value) { if (value) { setStatusBits(bits); } else { clearStatusBits(bits); } } private boolean isAnyStatusBit(int bits) { return (statusBits & bits) != 0; } void lockCheck() { // Check if there's any unprocessed allocation width/height change if (isAnyStatusBit(ALLOCATION_HEIGHT_CHANGE)) { clearStatusBits(ALLOCATION_HEIGHT_CHANGE); docView.setAllocationHeight(newAllocationHeight); } if (isAnyStatusBit(ALLOCATION_WIDTH_CHANGE)) { docView.setAllocationWidth(newAllocationWidth); // Updating of visible dimension can only be performed in EDT (acquires AWT treelock) // and the AWT treelock must precede VH lock. if (!isAnyStatusBit(UPDATE_VISIBLE_DIMENSION_PENDING)) { setStatusBits(UPDATE_VISIBLE_DIMENSION_PENDING); if (ViewHierarchyImpl.SPAN_LOG.isLoggable(Level.FINE)) { ViewUtils.log(ViewHierarchyImpl.SPAN_LOG, "DVOp.logCheck: invokeLater(updateVisibleDimension())\n"); } SwingUtilities.invokeLater(new Runnable() { @Override public void run() { updateVisibleDimension(true); } }); } } } void unlockCheck() { checkRealSpanChange(); // Clears widthChange and heightChange checkRepaint(); // Check if there's any unprocessed width/height change if (isAnyStatusBit(WIDTH_CHANGE | HEIGHT_CHANGE)) { // Do not throw error (only log) since unlock() call may be in another nested 'finally' section // which would lose original stacktrace. LOG.log(Level.INFO, "DocumentView invalid state upon unlock.", new Exception()); // NOI18N } } void checkRealSpanChange() { boolean widthChange = checkRealWidthChange(); boolean heightChange = checkRealHeightChange(); if (widthChange || heightChange) { if (ViewHierarchyImpl.SPAN_LOG.isLoggable(Level.FINE)) { String msg = "TC-preferenceChanged(" + // NOI18N (widthChange ? "W" : "-") + "x" + (heightChange ? "H" : "-") + ")\n"; // NOI18N ViewUtils.log(ViewHierarchyImpl.SPAN_LOG, msg); } // RootView.preferenceChanged() calls textComponent.revalidate (reposts to EDT if not called in it already) docView.superPreferenceChanged(widthChange, heightChange); } } public void notifyRepaint(double x0, double y0, double x1, double y1) { if (repaintX1 == 0d) { repaintX0 = x0; repaintY0 = y0; repaintX1 = x1; repaintY1 = y1; } else { // Merge regions repaintX0 = Math.min(repaintX0, x0); repaintX1 = Math.max(repaintX1, x1); repaintY0 = Math.min(repaintY0, y0); repaintY1 = Math.max(repaintY1, y1); } if (ViewHierarchyImpl.REPAINT_LOG.isLoggable(Level.FINE)) { String msg = "NOTIFY-REPAINT XYWH[" + x0 + ";" + y0 + ";" + (x1-x0) + ";" + (y1-y0) + "] => [" // NOI18N + repaintX0 + ";" + repaintY0 + ";" + (repaintX1-repaintX0) + ";" + (repaintY1-repaintY0) + "]\n"; // NOI18N ViewUtils.log(ViewHierarchyImpl.REPAINT_LOG, msg); } } void notifyRepaint(Rectangle2D repaintRect) { notifyRepaint(repaintRect.getX(), repaintRect.getY(), repaintRect.getMaxX(), repaintRect.getMaxY()); } final void checkRepaint() { if (repaintX1 != 0d) { final int x0 = (int) repaintX0; final int x1 = (int) Math.ceil(repaintX1); final int y0 = (int) repaintY0; final int y1 = (int) Math.ceil(repaintY1); resetRepaintRegion(); // Possibly post repaint into EDT since there was a deadlock in JDK related to this. ViewUtils.runInEDT(new Runnable() { @Override public void run() { JTextComponent textComponent = docView.getTextComponent(); if (textComponent != null) { if (ViewHierarchyImpl.REPAINT_LOG.isLoggable(Level.FINE)) { ViewHierarchyImpl.REPAINT_LOG.finer("REPAINT [x0,y0][x1,y1]: [" + x0 + "," + y0 + "][" + x1 + "," + y1 + "]\n"); // NOI18N } textComponent.repaint(x0, y0, x1 - x0, y1 - y0); } } }); } } private void resetRepaintRegion() { repaintX1 = 0d; // Make repaint region empty } void extendToVisibleWidth(Rectangle2D.Double r) { r.width = getVisibleRect().getMaxX(); } void parentViewSet() { JTextComponent textComponent = docView.getTextComponent(); assert (textComponent != null) : "Null textComponent"; // NOI18N updateStatusBits(ACCURATE_SPAN, Boolean.TRUE.equals(textComponent.getClientProperty(DocumentView.ACCURATE_SPAN_PROPERTY))); updateTextZoom(textComponent); viewUpdates = new ViewUpdates(docView); viewUpdates.initFactories(); asTextField = Boolean.TRUE.equals(textComponent.getClientProperty("AsTextField")); textComponent.addPropertyChangeListener(this); viewHierarchyImpl = ViewHierarchyImpl.get(textComponent); viewHierarchyImpl.setDocumentView(docView); if (doubleBuffered != null) { // Following code has no real effect since parents (all JPanel instances) // will use buffer of parent components (even if all parents are set to false). textComponent.setDoubleBuffered(doubleBuffered); // Turn on/off double-buffering in repaint manager. Since the current implementation // uses a shared RM instance for the whole system this will affect painting // for the whole application. RepaintManager rm = RepaintManager.currentManager(textComponent); boolean doubleBufferingOrig = rm.isDoubleBufferingEnabled(); ViewHierarchyImpl.SETTINGS_LOG.fine("RepaintManager.setDoubleBuffered() from " + // NOI18N doubleBufferingOrig + " to " + doubleBuffered + "\n"); rm.setDoubleBufferingEnabled(doubleBuffered); } if (ViewHierarchyImpl.REPAINT_LOG.isLoggable(Level.FINER)) { DebugRepaintManager.register(textComponent); } } void parentCleared() { JTextComponent textComponent = docView.getTextComponent(); // not null yet viewHierarchyImpl.setDocumentView(null); uninstallFromViewport(); textComponent.removePropertyChangeListener(this); viewUpdates.released(); viewUpdates = null; } void checkViewsInited() { // Must be called under mutex if (!isChildrenValid() && docView.getTextComponent() != null) { checkSettingsInfo(); // checkSettingsInfo() might called component.setFont() which might // lead to BasicTextUI.modelChanged() and new DocumentView creation // so docView.getTextComponent() == null should be checked. if (docView.getTextComponent() != null) { if (checkFontRenderContext()) { updateCharMetrics(); } // Update start and end offsets since e.g. during lengthy-atomic-edit // the view hierarchy is not updated and start/end offsets are obsolete. docView.updateStartEndOffsets(); ((EditorTabExpander) docView.getTabExpander()).updateTabSize(); if (isBuildable()) { LOG.fine("viewUpdates.reinitViews()\n"); // Signal early that the views will be valid - otherwise preferenceChange() // that calls getPreferredSpan() would attempt to reinit the views again // (failing in HighlightsViewFactory on usageCount). setStatusBits(CHILDREN_VALID); boolean success = false; try { viewUpdates.reinitAllViews(); success = true; } finally { // In case of an error in VH code the children would stay null if (!success) { // Prevent VH to look like active markChildrenInvalid(); } } } } } } void initParagraphs(int startIndex, int endIndex) { viewUpdates.initParagraphs(startIndex, endIndex); } private boolean checkFontRenderContext() { // check various things related to rendering if (fontRenderContext == null) { JTextComponent textComponent = docView.getTextComponent(); Graphics graphics = (textComponent != null) ? textComponent.getGraphics() : null; if (graphics instanceof Graphics2D) { updateFontRenderContext((Graphics2D)graphics, false); return (fontRenderContext != null); } } return false; } void updateFontRenderContext(Graphics2D g, boolean paint) { if (g != null) { if (!paint && ViewHierarchyImpl.SETTINGS_LOG.isLoggable(Level.FINE)) { ViewHierarchyImpl.SETTINGS_LOG.fine( "DocumentView.updateFontColorSettings() Antialiasing Rendering Hints:\n Graphics: " + // NOI18N g.getRenderingHints() + "\n Desktop Hints: " + renderingHints + // NOI18N "\n Extra Hints: " + extraRenderingHints + '\n'); // NOI18N } // Use rendering hints (antialiasing etc.) if (renderingHints != null) { g.addRenderingHints(renderingHints); } if (extraRenderingHints.size() > 0) { g.addRenderingHints(extraRenderingHints); } if (paint) { if (!fontRenderContextFromPaint) { fontRenderContextFromPaint = true; fontRenderContext = g.getFontRenderContext(); // Release children since the original non-painting graphics does not have // proper AA set. releaseChildrenNeedsLock(); // Already locked in DV.paint() } } else { fontRenderContext = g.getFontRenderContext(); } } } void releaseChildrenNeedsLock() { // It should be called with acquired mutex // Do not set children == null like in super.releaseChildren() // Instead mark them as invalid but allow to use them in certain limited cases markChildrenInvalid(); } private void markChildrenInvalid() { clearStatusBits(CHILDREN_VALID); } /** * Release all pViews of the document view due to some global change. * The method does not build the new views directly just marks the current ones as obsolete. * * @param updateFonts whether font metrics should be recreated. */ public void releaseChildren(final boolean updateFonts) { // It acquires document readlock and VH mutex first docView.runReadLockTransaction(new Runnable() { @Override public void run() { releaseChildrenNeedsLock(); if (updateFonts) { updateCharMetrics(); } } }); } /** * Whether the view should compute accurate spans (no lazy children views computation). * This is handy e.g. for fold preview computation since the fold preview * pane must be properly measured. * * @return whether accurate span measurements should be performed. */ boolean isAccurateSpan() { return isAnyStatusBit(ACCURATE_SPAN); } void updateVisibleDimension(final boolean clearAllocationWidthChange) { // Must be called without VH mutex since viewport.getViewRect() acquires AWT treelock // and since e.g. paint is called with AWT treelock acquired there would otherwise be a deadlock. // assert SwingUtilities.isEventDispatchThread() : "Must be called in EDT"; // NOI18N JTextComponent textComponent = docView.getTextComponent(); if (textComponent == null) { // No longer active view return; } Component parent = textComponent.getParent(); if(parent instanceof JLayeredPane) { parent = parent.getParent(); } final Rectangle newVisibleRect; if (parent instanceof JViewport) { JViewport viewport = (JViewport) parent; parent = viewport.getParent(); if (parent instanceof JScrollPane) { JScrollPane scrollPane = (JScrollPane) parent; if (activeViewport != viewport) { uninstallFromViewport(); activeViewport = viewport; if (LOG.isLoggable(Level.FINE)) { LOG.log(Level.FINE, "DocumentViewOp.updateVisibleDimension(): viewport change pane={0}, viewport={1}\n", new Object[]{obj2String(activeViewport.getView()), obj2String(activeViewport)}); } if (activeViewport != null) { activeViewport.addChangeListener(this); } } if (activeScrollPane != scrollPane) { uninstallFromScrollPane(); activeScrollPane = scrollPane; MouseWheelDelegator.install(this, activeScrollPane); } } newVisibleRect = viewport.getViewRect(); // acquires AWT treelock } else { // No parent viewport uninstallFromViewport(); Dimension size = textComponent.getSize(); newVisibleRect = new Rectangle(0, 0, size.width, size.height); } final float extraHeight; if (!DocumentView.DISABLE_END_VIRTUAL_SPACE && activeViewport != null && !asTextField) { // Compute same value regardless whether there's a horizontal scrollbar visible or not. // This is important to avoid flickering caused by vertical shrinking of the text component // so that vertical scrollbar appears and then appearing of a horizontal scrollbar // (in case there was a line nearly wide as viewport's width without Vscrollbar)\ // which in turn causes viewport's height to decrease and triggers recomputation again etc. float eHeight = activeViewport.getExtentSize().height; parent = activeViewport.getParent(); if(parent instanceof JLayeredPane) { parent = parent.getParent(); } if (parent instanceof JScrollPane) { JScrollBar hScrollBar = ((JScrollPane)parent).getHorizontalScrollBar(); if (hScrollBar != null && hScrollBar.isVisible()) { eHeight += hScrollBar.getHeight(); } } extraHeight = eHeight / 3; // One third of viewport's extent height } else { extraHeight = 0f; } // No document read lock necessary docView.runTransaction(new Runnable() { @Override public void run() { boolean widthDiffers = (newVisibleRect.width != visibleRect.width); boolean heightDiffers = (newVisibleRect.height != visibleRect.height); if (ViewHierarchyImpl.SPAN_LOG.isLoggable(Level.FINE)) { ViewUtils.log(ViewHierarchyImpl.SPAN_LOG, "DVOp.updateVisibleDimension: widthDiffers=" + widthDiffers + // NOI18N ", newVisibleRect=" + ViewUtils.toString(newVisibleRect) + // NOI18N ", extraHeight=" + extraHeight + "\n"); // NOI18N } if (clearAllocationWidthChange) { clearStatusBits(ALLOCATION_WIDTH_CHANGE | UPDATE_VISIBLE_DIMENSION_PENDING); } extraVirtualHeight = extraHeight; visibleRect = newVisibleRect; if (widthDiffers) { clearStatusBits(AVAILABLE_WIDTH_VALID); docView.markChildrenLayoutInvalid(); } if (asTextField && heightDiffers) { docView.updateBaseY(); } } }); } float getExtraVirtualHeight() { return extraVirtualHeight; } private void uninstallFromViewport() { // assert SwingUtilities.isEventDispatchThread() : "Must be called in EDT"; // NOI18N if (activeViewport != null) { uninstallFromScrollPane(); if (LOG.isLoggable(Level.FINE)) { LOG.log(Level.FINE, "DocumentViewOp.uninstallFromViewport(): pane={0}, viewport={1}\n", new Object[] {obj2String(activeViewport.getView()), obj2String(activeViewport)}); } activeViewport.removeChangeListener(this); activeViewport = null; } } private void uninstallFromScrollPane() { if (activeScrollPane != null) { if (LOG.isLoggable(Level.FINE)) { LOG.log(Level.FINE, "DocumentViewOp.uninstallFromScrollPane(): pane={0}, scrollPane={1}\n", new Object[]{obj2String((activeViewport != null) ? activeViewport.getView() : null), obj2String(activeScrollPane)}); } MouseWheelDelegator.uninstall(activeScrollPane); activeScrollPane = null; } } private static final String obj2String(Object o) { return (o != null) ? (o.getClass().getSimpleName() + "@" + System.identityHashCode(o)) : "null"; } @Override public void stateChanged(ChangeEvent e) { // First lock document and then monitor JTextComponent textComponent = docView.getTextComponent(); if (textComponent != null) { updateVisibleDimension(false); } } private void checkSettingsInfo() { JTextComponent textComponent = docView.getTextComponent(); if (textComponent == null) { return; } if (prefs == null) { String mimeType = DocumentUtilities.getMimeType(textComponent); prefs = MimeLookup.getLookup(mimeType).lookup(Preferences.class); prefsListener = new PreferenceChangeListener() { @Override public void preferenceChange(PreferenceChangeEvent evt) { updatePreferencesSettings(true); } }; prefs.addPreferenceChangeListener(WeakListeners.create(PreferenceChangeListener.class, prefsListener, prefs)); updatePreferencesSettings(false); } if (lookupListener == null) { lookupListener = new LookupListener() { @Override public void resultChanged(LookupEvent ev) { @SuppressWarnings("unchecked") final Lookup.Result<FontColorSettings> result = (Lookup.Result<FontColorSettings>) ev.getSource(); SwingUtilities.invokeLater(new Runnable() { // Must run in AWT to apply fonts/colors to comp. @Override public void run() { docView.runReadLockTransaction(new Runnable() { @Override public void run() { JTextComponent textComponent = docView.getTextComponent(); if (textComponent != null) { // Reset zoom since when changing font in tools->options the existing zoom // would be still applied to the new font textComponent.putClientProperty(DocumentView.TEXT_ZOOM_PROPERTY, null); updateFontColorSettings(result, true); } } }); } }); } }; String mimeType = DocumentUtilities.getMimeType(textComponent); Lookup lookup = MimeLookup.getLookup(mimeType); Lookup.Result<FontColorSettings> result = lookup.lookupResult(FontColorSettings.class); // Called without explicitly acquiring mutex but it's called only when lookup listener is null // so it should be acquired. updateFontColorSettings(result, false); result.addLookupListener(WeakListeners.create(LookupListener.class, lookupListener, result)); } if (lineWrapType == null) { updateLineWrapType(); Document doc = docView.getDocument(); updateTextLimitLine(doc); clearStatusBits(AVAILABLE_WIDTH_VALID); DocumentUtilities.addWeakPropertyChangeListener(doc, this); } } /* private */ void updatePreferencesSettings(boolean nonInitialUpdate) { boolean nonPrintableCharactersVisibleOrig = isAnyStatusBit(NON_PRINTABLE_CHARACTERS_VISIBLE); boolean nonPrintableCharactersVisible = Boolean.TRUE.equals(prefs.getBoolean( SimpleValueNames.NON_PRINTABLE_CHARACTERS_VISIBLE, false)); updateStatusBits(NON_PRINTABLE_CHARACTERS_VISIBLE, nonPrintableCharactersVisible); // Line height correction float lineHeightCorrectionOrig = rowHeightCorrection; rowHeightCorrection = prefs.getFloat(SimpleValueNames.LINE_HEIGHT_CORRECTION, 1.0f); boolean inlineHintsEnableOrig = inlineHintsEnable; inlineHintsEnable = Boolean.TRUE.equals(prefs.getBoolean("enable.inline.hints", false)); // NOI18N boolean updateMetrics = (rowHeightCorrection != lineHeightCorrectionOrig); boolean releaseChildren = nonInitialUpdate && ((nonPrintableCharactersVisible != nonPrintableCharactersVisibleOrig) || (rowHeightCorrection != lineHeightCorrectionOrig) || (inlineHintsEnable != inlineHintsEnableOrig)); indentLevelSize = getIndentSize(); tabSize = prefs.getInt(SimpleValueNames.TAB_SIZE, EditorPreferencesDefaults.defaultTabSize); if (updateMetrics) { updateCharMetrics(); } if (releaseChildren) { releaseChildren(false); } boolean currentGuideLinesEnable = Boolean.TRUE.equals(prefs.getBoolean("enable.guide.lines", true)); // NOI18N if (nonInitialUpdate && guideLinesEnable != currentGuideLinesEnable) { docView.op.notifyRepaint(visibleRect.getMinX(), visibleRect.getMinY(), visibleRect.getMaxX(), visibleRect.getMaxY()); } guideLinesEnable = currentGuideLinesEnable; } /* private */ void updateFontColorSettings(Lookup.Result<FontColorSettings> result, boolean nonInitialUpdate) { JTextComponent textComponent = docView.getTextComponent(); if (textComponent == null) { return; } AttributeSet defaultColoringOrig = defaultColoring; FontColorSettings fcs = result.allInstances().iterator().next(); AttributeSet attribs = fcs.getFontColors(FontColorNames.INDENT_GUIDE_LINES); guideLinesColor = attribs != null ? (Color) attribs.getAttribute(StyleConstants.Foreground) : Color.LIGHT_GRAY; AttributeSet newDefaultColoring = fcs.getFontColors(FontColorNames.DEFAULT_COLORING); // Attempt to always hold non-null content of "defaultColoring" variable once it became non-null if (newDefaultColoring != null) { defaultColoring = newDefaultColoring; // renderingHints = (Map<?, ?>) defaultColoring.getAttribute(EditorStyleConstants.RenderingHints); } // Use desktop hints renderingHints = (Map<?, ?>) Toolkit.getDefaultToolkit().getDesktopProperty("awt.font.desktophints"); //NOI18N // Possibly use fractional metrics if (asTextField) { return; } Color textLimitLineColorOrig = textLimitLineColor; AttributeSet textLimitLineColoring = fcs.getFontColors(FontColorNames.TEXT_LIMIT_LINE_COLORING); textLimitLineColor = (textLimitLineColoring != null) ? (Color) textLimitLineColoring.getAttribute(StyleConstants.Foreground) : null; if (textLimitLineColor == null) { textLimitLineColor = Color.PINK; } final boolean applyDefaultColoring = (defaultColoring != defaultColoringOrig); // Do not do equals() (for renderingHints) final boolean releaseChildren = nonInitialUpdate && applyDefaultColoring; final boolean repaint = nonInitialUpdate && (textLimitLineColor == null || !textLimitLineColor.equals(textLimitLineColorOrig)); if (applyDefaultColoring || releaseChildren || repaint) { ViewUtils.runInEDT(new Runnable() { @Override public void run() { JTextComponent textComponent = docView.getTextComponent(); if (textComponent != null) { if (applyDefaultColoring) { applyDefaultColoring(textComponent); } if (releaseChildren) { releaseChildren(true); } if (repaint) { textComponent.repaint(); } } } }); } } /*private*/ void applyDefaultColoring(JTextComponent textComponent) { // Called in AWT to possibly apply default coloring from settings AttributeSet coloring = defaultColoring; Font font = ViewUtils.getFont(coloring); if (font != null) { textComponent.setFont(font); } Color foreColor = (Color) coloring.getAttribute(StyleConstants.Foreground); if (foreColor != null) { textComponent.setForeground(foreColor); } Color backColor = (Color) coloring.getAttribute(StyleConstants.Background); if (backColor != null) { textComponent.setBackground(backColor); } } private void updateTextLimitLine(Document doc) { // #183797 - most likely seeing a non-nb document during the editor pane creation Integer dllw = (Integer) doc.getProperty(SimpleValueNames.TEXT_LIMIT_WIDTH); int textLimitLineColumn = (dllw != null) ? dllw.intValue() : EditorPreferencesDefaults.defaultTextLimitWidth; Preferences prefsLocal = prefs; if (prefsLocal != null) { boolean drawTextLimitLine = prefsLocal.getBoolean(SimpleValueNames.TEXT_LIMIT_LINE_VISIBLE, true); textLimitLineX = drawTextLimitLine ? (int) (textLimitLineColumn * defaultCharWidth) : -1; } } private void updateLineWrapType() { // Should be able to run without mutex String lwt = null; JTextComponent textComponent = docView.getTextComponent(); if (textComponent != null) { lwt = (String) textComponent.getClientProperty(SimpleValueNames.TEXT_LINE_WRAP); } if (lwt == null) { Document doc = docView.getDocument(); lwt = (String) doc.getProperty(SimpleValueNames.TEXT_LINE_WRAP); } if (lwt != null) { lineWrapType = LineWrapType.fromSettingValue(lwt); } if (asTextField || lineWrapType == null) { lineWrapType = LineWrapType.NONE; } clearStatusBits(AVAILABLE_WIDTH_VALID); } private void updateCharMetrics() { // Update default row height and other params checkFontRenderContext(); // Possibly get FRC created; ignore ret value since now actually updating the metrics FontRenderContext frc = getFontRenderContext(); JTextComponent textComponent = docView.getTextComponent(); Font font; if (frc != null && textComponent != null && ((font = textComponent.getFont()) != null)) { // Reset all the measurements to adhere just to default font. // Possible other fonts in fontInfos get eliminated. fontInfos.clear(); FontInfo defaultFontInfo = new FontInfo(font, textComponent, frc, rowHeightCorrection, textZoom); fontInfos.put(font, defaultFontInfo); fontInfos.put(null, defaultFontInfo); // Alternative way to find default font info updateRowHeight(defaultFontInfo, true); defaultFont = font; defaultHintFont = font.deriveFont((float) (font.getSize2D() * 0.75)); defaultCharWidth = defaultFontInfo.charWidth; tabTextLayout = null; singleCharTabTextLayout = null; newlineTextLayout = null; lineContinuationTextLayout = null; updateTextLimitLine(docView.getDocument()); clearStatusBits(AVAILABLE_WIDTH_VALID); ViewHierarchyImpl.SETTINGS_LOG.fine("updateCharMetrics(): FontRenderContext: AA=" + frc.isAntiAliased() + // NOI18N ", AATransformed=" + frc.isTransformed() + // NOI18N ", AAFractMetrics=" + frc.usesFractionalMetrics() + // NOI18N ", AAHint=" + frc.getAntiAliasingHint() + "\n"); // NOI18N } } private void updateRowHeight(FontInfo fontInfo, boolean force) { if (force || defaultAscentInt < fontInfo.ascentInt) { if (LOG.isLoggable(Level.FINE)) { LOG.fine("DV.updateRowHeight()" + (force ? "-forced" : "") + // NOI18N ": defaultAscentInt from " + defaultAscentInt + " to " + fontInfo.ascentInt + "\n"); // NOI18N } defaultAscentInt = fontInfo.ascentInt; } if (force || defaultRowHeightInt < fontInfo.rowHeightInt) { if (LOG.isLoggable(Level.FINE)) { LOG.fine("DV.updateRowHeight()" + (force ? "-forced" : "") + // NOI18N ": defaultRowHeightInt from " + defaultRowHeightInt + " to " + fontInfo.rowHeightInt + "\n"); // NOI18N } defaultRowHeightInt = fontInfo.rowHeightInt; } } void markIncomingModification() { setStatusBits(INCOMING_MODIFICATION); } void clearIncomingModification() { clearStatusBits(INCOMING_MODIFICATION); } boolean isActive() { if (isAnyStatusBit(FIRING_CHANGE)) { throw new IllegalStateException("View hierarchy must not be queried during change firing"); // NOI18N } else if (isAnyStatusBit(INCOMING_MODIFICATION)) { if (ViewHierarchyImpl.OP_LOG.isLoggable(Level.FINER)) { ViewHierarchyImpl.OP_LOG.log(Level.INFO, "View Hierarchy Query during Incoming Modification\n", // NOI18N new Exception()); } return false; } else { return isUpdatable(); } } boolean isUpdatable() { // Whether the view hierarchy can be updated (by insertUpdate() etc.) JTextComponent textComponent = docView.getTextComponent(); return textComponent != null && isChildrenValid() && (lengthyAtomicEdit <= 0); } boolean isBuildable() { JTextComponent textComponent = docView.getTextComponent(); return textComponent != null && fontRenderContext != null && fontInfos.size() > 0 && (lengthyAtomicEdit <= 0) && !isAnyStatusBit(INCOMING_MODIFICATION); } // from org.netbeans.api.java.source.CodeStyle private int getIndentSize() { Integer indentLevelInteger = (Integer) docView.getDocument().getProperty(SimpleValueNames.INDENT_SHIFT_WIDTH); if (indentLevelInteger != null && indentLevelInteger > 0) { return indentLevelInteger; } int indentLevel = prefs.getInt(SimpleValueNames.INDENT_SHIFT_WIDTH, 0); if (indentLevel > 0) { return indentLevel; } Boolean expandTabsBoolean = (Boolean) docView.getDocument().getProperty(SimpleValueNames.EXPAND_TABS); if (expandTabsBoolean != null) { if (Boolean.TRUE.equals(expandTabsBoolean)) { indentLevelInteger = (Integer) docView.getDocument().getProperty(SimpleValueNames.SPACES_PER_TAB); if (indentLevelInteger == null) { return prefs.getInt(SimpleValueNames.SPACES_PER_TAB, EditorPreferencesDefaults.defaultSpacesPerTab); } } else { indentLevelInteger = (Integer) docView.getDocument().getProperty(SimpleValueNames.TAB_SIZE); if (indentLevelInteger == null) { return prefs.getInt(SimpleValueNames.TAB_SIZE, EditorPreferencesDefaults.defaultTabSize); } } return indentLevelInteger; } boolean expandTabs = prefs.getBoolean(SimpleValueNames.EXPAND_TABS, EditorPreferencesDefaults.defaultExpandTabs); if (expandTabs) { indentLevel = prefs.getInt(SimpleValueNames.SPACES_PER_TAB, EditorPreferencesDefaults.defaultSpacesPerTab); } else { indentLevel = prefs.getInt(SimpleValueNames.TAB_SIZE, EditorPreferencesDefaults.defaultTabSize); } return indentLevel; } public boolean isGuideLinesEnable() { return guideLinesEnable && !asTextField; } public boolean isInlineHintsEnable() { return inlineHintsEnable; } public int getIndentLevelSize() { return indentLevelSize; } public int getTabSize() { return tabSize; } public Color getGuideLinesColor() { return guideLinesColor; } public void setGuideLinesCache(int cacheAtOffset, int foundAtOffset, int length) { guideLinesCache = new int[] {cacheAtOffset, foundAtOffset, length}; } public int[] getGuideLinesCache() { return guideLinesCache; } /** * It should be called with +1 once it's detected that there's a lengthy atomic edit * in progress and with -1 when such edit gets finished. * @param delta +1 or -1 when entering/leaving lengthy atomic edit. */ public void updateLengthyAtomicEdit(int delta) { lengthyAtomicEdit += delta; if (LOG.isLoggable(Level.FINE)) { ViewUtils.log(LOG, "updateLengthyAtomicEdit: delta=" + delta + // NOI18N " lengthyAtomicEdit=" + lengthyAtomicEdit + "\n"); // NOI18N } if (lengthyAtomicEdit == 0) { releaseChildren(false); } } /** * Get displayed portion of the component (either viewport.getViewRect()) * or (if viewport is missing) size of the component. * <br> * Note: The value may be obsolete during paint - clipping bounds may already * incorporate a just performed scroll while visibleRect does not yet. * * @return visible rectangle of the editor either viewport's view or editor component * bounds. */ Rectangle getVisibleRect() { return visibleRect; } /** * Get width available for display of child views. For non-wrap case it's Integer.MAX_VALUE * and for wrapping it's a display width or (if display width would become too narrow) * a width of four chars to not overflow the word wrapping algorithm. * @return */ float getAvailableWidth() { if (!isAnyStatusBit(AVAILABLE_WIDTH_VALID)) { // Mark valid and assign early values to prevent stack overflow in getLineContinuationCharTextLayout() setStatusBits(AVAILABLE_WIDTH_VALID); availableWidth = Integer.MAX_VALUE; renderWrapWidth = availableWidth; if (getLineWrapType() != LineWrapType.NONE) { final TextLayout lineContTextLayout = getLineContinuationCharTextLayout(); final float lineContTextLayoutAdvance = lineContTextLayout == null ? 0f : lineContTextLayout.getAdvance(); availableWidth = Math.max(getVisibleRect().width, 4 * getDefaultCharWidth() + lineContTextLayoutAdvance); renderWrapWidth = availableWidth - lineContTextLayoutAdvance; } } return availableWidth; } /** * Get width available for rendering of real text on a wrapped line. * It's {@link #getAvailableWidth()} minus width of wrap designating character. * @return */ float getRenderWrapWidth() { return renderWrapWidth; } TextLayoutCache getTextLayoutCache() { return textLayoutCache; } FontRenderContext getFontRenderContext() { return fontRenderContext; } public Font getDefaultFont() { return defaultFont; } public Font getDefaultHintFont() { return defaultHintFont; } public float getDefaultRowHeight() { checkSettingsInfo(); return defaultRowHeightInt; } public float getDefaultAscent() { checkSettingsInfo(); return defaultAscentInt; } /** * Return array of default: * <ol> * <li>Underline offset.</li> * <li>Underline thickness.</li> * <li>Strike-through offset.</li> * <li>Strike-through thickness.</li> * </ol> */ public float[] getUnderlineAndStrike(Font font) { checkSettingsInfo(); FontInfo fontInfo = fontInfos.get(font); if (fontInfo == null) { // Should not normally happen fontInfo = fontInfos.get(null); } return fontInfo.underlineAndStrike; } public float getDefaultCharWidth() { checkSettingsInfo(); return defaultCharWidth; } public boolean isNonPrintableCharactersVisible() { checkSettingsInfo(); return isAnyStatusBit(NON_PRINTABLE_CHARACTERS_VISIBLE) && !asTextField; } LineWrapType getLineWrapType() { checkSettingsInfo(); return lineWrapType; } Color getTextLimitLineColor() { checkSettingsInfo(); return textLimitLineColor; } int getTextLimitLineX() { return textLimitLineX; } TextLayout getNewlineCharTextLayout() { if (newlineTextLayout == null) { newlineTextLayout = createTextLayout(String.valueOf(PRINTING_NEWLINE), defaultFont); } return newlineTextLayout; } TextLayout getTabCharTextLayout(double availableWidth) { if (tabTextLayout == null) { char tabChar = defaultFont.canDisplay(PRINTING_TAB) ? PRINTING_TAB : PRINTING_TAB_ALTERNATE; tabTextLayout = createTextLayout(String.valueOf(tabChar), defaultFont); } TextLayout ret = tabTextLayout; if (tabTextLayout != null && availableWidth > 0 && tabTextLayout.getAdvance() > availableWidth) { if (singleCharTabTextLayout == null) { for (int i = defaultFont.getSize() - 1; i >= 0; i--) { Font font = new Font(defaultFont.getName(), defaultFont.getStyle(), i); char tabChar = font.canDisplay(PRINTING_TAB) ? PRINTING_TAB : PRINTING_TAB_ALTERNATE; singleCharTabTextLayout = createTextLayout(String.valueOf(tabChar), font); if (singleCharTabTextLayout != null) { if (singleCharTabTextLayout.getAdvance() <= getDefaultCharWidth()) { LOG.log(Level.FINE, "singleChar font size={0}\n", i); break; } } else { // layout creation failed break; } } } ret = singleCharTabTextLayout; } return ret; } /** * @return will be null if the line continuation character should not be shown */ TextLayout getLineContinuationCharTextLayout() { /* The line continuation character is used to show that a line is automatically being broken into multiple wrap lines via the line wrap feature. This causes a lot of visual clutter, and always takes up an extra character of horizontal space, so don't show it by default. The same information is communicated by the line numbers in the left-hand side of the editor anyway. */ if (!docView.op.isNonPrintableCharactersVisible()) return null; if (lineContinuationTextLayout == null) { char lineContinuationChar = LINE_CONTINUATION; if (!defaultFont.canDisplay(lineContinuationChar)) { lineContinuationChar = LINE_CONTINUATION_ALTERNATE; } lineContinuationTextLayout = createTextLayout(String.valueOf(lineContinuationChar), defaultFont); } return lineContinuationTextLayout; } public FontInfo getFontInfo(Font font) { FontInfo fontInfo = fontInfos.get(font); if (fontInfo == null) { fontInfo = new FontInfo(font, docView.getTextComponent(), getFontRenderContext(), rowHeightCorrection, textZoom); fontInfos.put(font, fontInfo); } return fontInfo; } TextLayout createTextLayout(String text, Font font) { checkSettingsInfo(); if (fontRenderContext != null && font != null) { ViewStats.incrementTextLayoutCreated(text.length()); FontInfo fontInfo = getFontInfo(font); TextLayout textLayout = new TextLayout(text, fontInfo.renderFont, fontRenderContext); if (fontInfo.updateRowHeight(textLayout, rowHeightCorrection)) { updateRowHeight(fontInfo, false); LOG.fine("RowHeight Updated -> release children"); releaseChildren(false); } return textLayout; } return null; } @Override public void propertyChange(PropertyChangeEvent evt) { JTextComponent textComponent = docView.getTextComponent(); if (textComponent == null) { return; } boolean releaseChildren = false; boolean updateFonts = false; Object src = evt.getSource(); String propName = evt.getPropertyName(); if (src instanceof Document) { if (propName == null || SimpleValueNames.TEXT_LINE_WRAP.equals(propName)) { LineWrapType origLineWrapType = lineWrapType; updateLineWrapType(); // can run without mutex if (origLineWrapType != lineWrapType) { LOG.log(Level.FINE, "Changing lineWrapType from {0} to {1}", new Object [] { origLineWrapType, lineWrapType }); //NOI18N releaseChildren = true; } } if (propName == null || SimpleValueNames.TAB_SIZE.equals(propName)) { releaseChildren = true; Integer tabSizeInteger = (Integer) docView.getDocument().getProperty(SimpleValueNames.TAB_SIZE); tabSize = (tabSizeInteger != null) ? tabSizeInteger : tabSize; } if (propName == null || SimpleValueNames.SPACES_PER_TAB.equals(propName) || SimpleValueNames.TAB_SIZE.equals(propName) || SimpleValueNames.INDENT_SHIFT_WIDTH.equals(propName)) { releaseChildren = true; indentLevelSize = getIndentSize(); } if (propName == null || SimpleValueNames.TEXT_LIMIT_WIDTH.equals(propName)) { updateTextLimitLine(docView.getDocument()); releaseChildren = true; } } else if (src instanceof JTextComponent) { // an event from JTextComponent if ("ancestor".equals(propName)) { // NOI18N } else if ("document".equals(propName)) { // NOI18N } else if ("font".equals(propName)) { // NOI18N releaseChildren = true; updateFonts = true; } else if ("foreground".equals(propName)) { //NOI18N releaseChildren = true; // Repaint should possibly suffice too } else if ("background".equals(propName)) { //NOI18N releaseChildren = true; // Repaint should possibly suffice too } else if (SimpleValueNames.TEXT_LINE_WRAP.equals(propName)) { updateLineWrapType(); // can run without mutex releaseChildren = true; } else if (DocumentView.START_POSITION_PROPERTY.equals(propName) || DocumentView.END_POSITION_PROPERTY.equals(propName)) { docView.runReadLockTransaction(new Runnable() { @Override public void run() { docView.updateStartEndOffsets(); releaseChildrenNeedsLock(); // Rebuild view hierarchy } }); } else if (DocumentView.TEXT_ZOOM_PROPERTY.equals(propName)) { updateTextZoom(textComponent); releaseChildren = true; updateFonts = true; } else if ("AsTextField".equals(propName)) { asTextField = Boolean.TRUE.equals(textComponent.getClientProperty("AsTextField")); updateLineWrapType(); docView.updateBaseY(); releaseChildren = true; } } if (releaseChildren) { releaseChildren(updateFonts); } } private void updateTextZoom(JTextComponent textComponent) { Integer textZoomInteger = (Integer) textComponent.getClientProperty(DocumentView.TEXT_ZOOM_PROPERTY); textZoom = (textZoomInteger != null) ? textZoomInteger : 0; } public void mouseWheelMoved(MouseWheelEvent evt, MouseWheelDelegator delegator) { // Since consume() idoes not prevent BasicScrollPaneUI.Handler from operation // the code in DocumentView.setParent() removes BasicScrollPaneUI.Handler and stores it // in origMouseWheelListener and installs "this" as MouseWheelListener instead. // This method only calls origMouseWheelListener if Ctrl is not pressed (zooming in/out). if (evt.getScrollType() != MouseWheelEvent.WHEEL_UNIT_SCROLL) { delegator.delegateToOriginalListener(evt, activeScrollPane); // evt.consume(); // consuming the event has no effect return; } int modifiers = 0; if (evt.isControlDown()) { modifiers |= InputEvent.CTRL_DOWN_MASK; } if (evt.isAltDown()) { modifiers |= InputEvent.ALT_DOWN_MASK; } if (evt.isShiftDown()) { modifiers |= InputEvent.SHIFT_DOWN_MASK; } if (evt.isMetaDown()) { modifiers |= InputEvent.META_DOWN_MASK; } JTextComponent textComponent = docView.getTextComponent(); Keymap keymap = textComponent.getKeymap(); double wheelRotation = evt.getPreciseWheelRotation(); if (wheelRotation < 0) { Action action = keymap.getAction(KeyStroke.getKeyStroke(0x290, modifiers)); //WHEEL_UP constant if (action != null) { action.actionPerformed(new ActionEvent(docView.getTextComponent(),0,"")); textComponent.repaint(); // Consider repaint triggering elsewhere } else { delegator.delegateToOriginalListener(evt, activeScrollPane); } } else if (wheelRotation > 0) { Action action = keymap.getAction(KeyStroke.getKeyStroke(0x291, modifiers)); //WHEEL_DOWN constant if (action != null) { action.actionPerformed(new ActionEvent(docView.getTextComponent(),0,"")); textComponent.repaint(); // Consider repaint triggering elsewhere } else { delegator.delegateToOriginalListener(evt, activeScrollPane); } } // else: wheelRotation == 0 => do nothing } StringBuilder appendInfo(StringBuilder sb) { sb.append(" incomMod=").append(isAnyStatusBit(INCOMING_MODIFICATION)); // NOI18N sb.append(", lengthyAE=").append(lengthyAtomicEdit); // NOI18N sb.append('\n'); sb.append(viewUpdates); sb.append(", ChgFlags:"); // NOI18N int len = sb.length(); if (isWidthChange()) sb.append(" W"); if (isHeightChange()) sb.append(" H"); if (sb.length() == len) { sb.append(" <NONE>"); } sb.append("; visWidth:").append(getVisibleRect().width); // NOI18N sb.append(", rowHeight=").append(getDefaultRowHeight()); // NOI18N sb.append(", ascent=").append(getDefaultAscent()); // NOI18N sb.append(", charWidth=").append(getDefaultCharWidth()); // NOI18N return sb; } @Override public String toString() { return appendInfo(new StringBuilder(200)).toString(); } /** * Listener for changes of UI of a scroll pane. */ private static final class MouseWheelDelegator implements MouseWheelListener, PropertyChangeListener { static void install(DocumentViewOp op, JScrollPane scrollPane) { MouseWheelDelegator mwd = (MouseWheelDelegator) scrollPane.getClientProperty(MouseWheelDelegator.class); if (mwd == null) { mwd = new MouseWheelDelegator(scrollPane); scrollPane.putClientProperty(MouseWheelDelegator.class, mwd); } mwd.setOp(op); } static void uninstall(JScrollPane scrollPane) { MouseWheelDelegator mwd = (MouseWheelDelegator) scrollPane.getClientProperty(MouseWheelDelegator.class); if (mwd != null) { mwd.uninstall(); scrollPane.putClientProperty(MouseWheelDelegator.class, null); } } private Reference<DocumentViewOp> opRef; private final JScrollPane scrollPane; private ScrollPaneUI lastUI; private MouseWheelListener delegateListener; MouseWheelDelegator(JScrollPane scrollPane) { this.scrollPane = scrollPane; scrollPane.addPropertyChangeListener(this); updateListeners(); } DocumentViewOp op() { Reference<DocumentViewOp> lOp = this.opRef; return (lOp != null) ? lOp.get() : null; } void setOp(DocumentViewOp op) { if (op != op()) { this.opRef = new WeakReference<DocumentViewOp>(op); } } private void updateListeners() { ScrollPaneUI ui = scrollPane.getUI(); if (ui != lastUI) { // Update "ui" property listener if (ui != null) { // Check mouse wheel listeners on scroll pane. // Pair first non-MWDelegator listener with // Remove any other delegators than this one. MouseWheelListener[] mwls = scrollPane.getListeners(MouseWheelListener.class); if (LOG.isLoggable(Level.FINE)) { LOG.log(Level.FINE, "MouseWheelDelegator.updateListeners(): scrollPane change scrollPane={0}, MouseWheelListeners:{1}\n", new Object[]{obj2String(scrollPane), Arrays.asList(mwls)}); } delegateListener = null; for (MouseWheelListener listener : mwls) { if (listener instanceof MouseWheelDelegator) { scrollPane.removeMouseWheelListener(listener); if (delegateListener == null) { delegateListener = ((MouseWheelDelegator) listener).delegateListener; scrollPane.addMouseWheelListener(this); } } else { // Regular listener // Current patch only assumes one MW listener attached by the UI impl. if (delegateListener == null) { delegateListener = listener; scrollPane.removeMouseWheelListener(listener); scrollPane.addMouseWheelListener(this); } } } } lastUI = ui; } } private void uninstall() { scrollPane.removePropertyChangeListener(this); } @Override public void propertyChange(PropertyChangeEvent evt) { if ("ui".equals(evt.getPropertyName()) || "UI".equals(evt.getPropertyName())) { updateListeners(); } if (LOG.isLoggable(Level.FINE)) { LOG.log(Level.FINE, "Scrollpane changed with property name: {0}", new Object[]{evt.getPropertyName()}); } } @Override public void mouseWheelMoved(MouseWheelEvent e) { DocumentViewOp op = op(); if (op != null && scrollPane != null ) { op.mouseWheelMoved(e, this); } } void delegateToOriginalListener(MouseWheelEvent e, JScrollPane activeScrollPane) { // Only delegate if the updated scrollpane is still actively used by the DocumentViewOp // and when it still uses the overriden listener (this) if (activeScrollPane == scrollPane) { MouseWheelListener[] mwls = scrollPane.getListeners(MouseWheelListener.class); for (int i = 0; i < mwls.length; i++) { if (mwls[i] == this) { delegateListener.mouseWheelMoved(e); return; } } } } } }
31,613
666
<gh_stars>100-1000 import sys sys.path.append("../../") from appJar import gui with gui() as app: app.addImage("a", "lb3.gif")
54
852
<filename>L1Trigger/L1TMuonOverlapPhase1/src/Omtf/IOMTFEmulationObserver.cc /* * IOMTFEmulationObserver.cc * * Created on: Oct 12, 2017 * Author: kbunkow */ #include "L1Trigger/L1TMuonOverlapPhase1/interface/Omtf/IOMTFEmulationObserver.h" IOMTFEmulationObserver::IOMTFEmulationObserver() {} IOMTFEmulationObserver::~IOMTFEmulationObserver() {}
146
956
/* SPDX-License-Identifier: BSD-3-Clause * Copyright(c) 2016-2020 Intel Corporation */ #ifndef __DLB_REGS_H #define __DLB_REGS_H #include "dlb_osdep_types.h" #define DLB_MSIX_MEM_VECTOR_CTRL(x) \ (0x100000c + (x) * 0x10) #define DLB_MSIX_MEM_VECTOR_CTRL_RST 0x1 union dlb_msix_mem_vector_ctrl { struct { u32 vec_mask : 1; u32 rsvd0 : 31; } field; u32 val; }; #define DLB_SYS_TOTAL_VAS 0x124 #define DLB_SYS_TOTAL_VAS_RST 0x20 union dlb_sys_total_vas { struct { u32 total_vas : 32; } field; u32 val; }; #define DLB_SYS_ALARM_PF_SYND2 0x508 #define DLB_SYS_ALARM_PF_SYND2_RST 0x0 union dlb_sys_alarm_pf_synd2 { struct { u32 lock_id : 16; u32 meas : 1; u32 debug : 7; u32 cq_pop : 1; u32 qe_uhl : 1; u32 qe_orsp : 1; u32 qe_valid : 1; u32 cq_int_rearm : 1; u32 dsi_error : 1; u32 rsvd0 : 2; } field; u32 val; }; #define DLB_SYS_ALARM_PF_SYND1 0x504 #define DLB_SYS_ALARM_PF_SYND1_RST 0x0 union dlb_sys_alarm_pf_synd1 { struct { u32 dsi : 16; u32 qid : 8; u32 qtype : 2; u32 qpri : 3; u32 msg_type : 3; } field; u32 val; }; #define DLB_SYS_ALARM_PF_SYND0 0x500 #define DLB_SYS_ALARM_PF_SYND0_RST 0x0 union dlb_sys_alarm_pf_synd0 { struct { u32 syndrome : 8; u32 rtype : 2; u32 rsvd0 : 2; u32 from_dmv : 1; u32 is_ldb : 1; u32 cls : 2; u32 aid : 6; u32 unit : 4; u32 source : 4; u32 more : 1; u32 valid : 1; } field; u32 val; }; #define DLB_SYS_LDB_VASQID_V(x) \ (0xf60 + (x) * 0x1000) #define DLB_SYS_LDB_VASQID_V_RST 0x0 union dlb_sys_ldb_vasqid_v { struct { u32 vasqid_v : 1; u32 rsvd0 : 31; } field; u32 val; }; #define DLB_SYS_DIR_VASQID_V(x) \ (0xf68 + (x) * 0x1000) #define DLB_SYS_DIR_VASQID_V_RST 0x0 union dlb_sys_dir_vasqid_v { struct { u32 vasqid_v : 1; u32 rsvd0 : 31; } field; u32 val; }; #define DLB_SYS_WBUF_DIR_FLAGS(x) \ (0xf70 + (x) * 0x1000) #define DLB_SYS_WBUF_DIR_FLAGS_RST 0x0 union dlb_sys_wbuf_dir_flags { struct { u32 wb_v : 4; u32 cl : 1; u32 busy : 1; u32 opt : 1; u32 rsvd0 : 25; } field; u32 val; }; #define DLB_SYS_WBUF_LDB_FLAGS(x) \ (0xf78 + (x) * 0x1000) #define DLB_SYS_WBUF_LDB_FLAGS_RST 0x0 union dlb_sys_wbuf_ldb_flags { struct { u32 wb_v : 4; u32 cl : 1; u32 busy : 1; u32 rsvd0 : 26; } field; u32 val; }; #define DLB_SYS_LDB_QID_V(x) \ (0x8000034 + (x) * 0x1000) #define DLB_SYS_LDB_QID_V_RST 0x0 union dlb_sys_ldb_qid_v { struct { u32 qid_v : 1; u32 rsvd0 : 31; } field; u32 val; }; #define DLB_SYS_LDB_QID_CFG_V(x) \ (0x8000030 + (x) * 0x1000) #define DLB_SYS_LDB_QID_CFG_V_RST 0x0 union dlb_sys_ldb_qid_cfg_v { struct { u32 sn_cfg_v : 1; u32 fid_cfg_v : 1; u32 rsvd0 : 30; } field; u32 val; }; #define DLB_SYS_DIR_QID_V(x) \ (0x8000040 + (x) * 0x1000) #define DLB_SYS_DIR_QID_V_RST 0x0 union dlb_sys_dir_qid_v { struct { u32 qid_v : 1; u32 rsvd0 : 31; } field; u32 val; }; #define DLB_SYS_LDB_POOL_ENBLD(x) \ (0x8000070 + (x) * 0x1000) #define DLB_SYS_LDB_POOL_ENBLD_RST 0x0 union dlb_sys_ldb_pool_enbld { struct { u32 pool_enabled : 1; u32 rsvd0 : 31; } field; u32 val; }; #define DLB_SYS_DIR_POOL_ENBLD(x) \ (0x8000080 + (x) * 0x1000) #define DLB_SYS_DIR_POOL_ENBLD_RST 0x0 union dlb_sys_dir_pool_enbld { struct { u32 pool_enabled : 1; u32 rsvd0 : 31; } field; u32 val; }; #define DLB_SYS_LDB_PP2VPP(x) \ (0x8000090 + (x) * 0x1000) #define DLB_SYS_LDB_PP2VPP_RST 0x0 union dlb_sys_ldb_pp2vpp { struct { u32 vpp : 6; u32 rsvd0 : 26; } field; u32 val; }; #define DLB_SYS_DIR_PP2VPP(x) \ (0x8000094 + (x) * 0x1000) #define DLB_SYS_DIR_PP2VPP_RST 0x0 union dlb_sys_dir_pp2vpp { struct { u32 vpp : 7; u32 rsvd0 : 25; } field; u32 val; }; #define DLB_SYS_LDB_PP_V(x) \ (0x8000128 + (x) * 0x1000) #define DLB_SYS_LDB_PP_V_RST 0x0 union dlb_sys_ldb_pp_v { struct { u32 pp_v : 1; u32 rsvd0 : 31; } field; u32 val; }; #define DLB_SYS_LDB_CQ_ISR(x) \ (0x8000124 + (x) * 0x1000) #define DLB_SYS_LDB_CQ_ISR_RST 0x0 /* CQ Interrupt Modes */ #define DLB_CQ_ISR_MODE_DIS 0 #define DLB_CQ_ISR_MODE_MSI 1 #define DLB_CQ_ISR_MODE_MSIX 2 union dlb_sys_ldb_cq_isr { struct { u32 vector : 6; u32 vf : 4; u32 en_code : 2; u32 rsvd0 : 20; } field; u32 val; }; #define DLB_SYS_LDB_CQ2VF_PF(x) \ (0x8000120 + (x) * 0x1000) #define DLB_SYS_LDB_CQ2VF_PF_RST 0x0 union dlb_sys_ldb_cq2vf_pf { struct { u32 vf : 4; u32 is_pf : 1; u32 rsvd0 : 27; } field; u32 val; }; #define DLB_SYS_LDB_PP2VAS(x) \ (0x800011c + (x) * 0x1000) #define DLB_SYS_LDB_PP2VAS_RST 0x0 union dlb_sys_ldb_pp2vas { struct { u32 vas : 5; u32 rsvd0 : 27; } field; u32 val; }; #define DLB_SYS_LDB_PP2LDBPOOL(x) \ (0x8000118 + (x) * 0x1000) #define DLB_SYS_LDB_PP2LDBPOOL_RST 0x0 union dlb_sys_ldb_pp2ldbpool { struct { u32 ldbpool : 6; u32 rsvd0 : 26; } field; u32 val; }; #define DLB_SYS_LDB_PP2DIRPOOL(x) \ (0x8000114 + (x) * 0x1000) #define DLB_SYS_LDB_PP2DIRPOOL_RST 0x0 union dlb_sys_ldb_pp2dirpool { struct { u32 dirpool : 6; u32 rsvd0 : 26; } field; u32 val; }; #define DLB_SYS_LDB_PP2VF_PF(x) \ (0x8000110 + (x) * 0x1000) #define DLB_SYS_LDB_PP2VF_PF_RST 0x0 union dlb_sys_ldb_pp2vf_pf { struct { u32 vf : 4; u32 is_pf : 1; u32 rsvd0 : 27; } field; u32 val; }; #define DLB_SYS_LDB_PP_ADDR_U(x) \ (0x800010c + (x) * 0x1000) #define DLB_SYS_LDB_PP_ADDR_U_RST 0x0 union dlb_sys_ldb_pp_addr_u { struct { u32 addr_u : 32; } field; u32 val; }; #define DLB_SYS_LDB_PP_ADDR_L(x) \ (0x8000108 + (x) * 0x1000) #define DLB_SYS_LDB_PP_ADDR_L_RST 0x0 union dlb_sys_ldb_pp_addr_l { struct { u32 rsvd0 : 7; u32 addr_l : 25; } field; u32 val; }; #define DLB_SYS_LDB_CQ_ADDR_U(x) \ (0x8000104 + (x) * 0x1000) #define DLB_SYS_LDB_CQ_ADDR_U_RST 0x0 union dlb_sys_ldb_cq_addr_u { struct { u32 addr_u : 32; } field; u32 val; }; #define DLB_SYS_LDB_CQ_ADDR_L(x) \ (0x8000100 + (x) * 0x1000) #define DLB_SYS_LDB_CQ_ADDR_L_RST 0x0 union dlb_sys_ldb_cq_addr_l { struct { u32 rsvd0 : 6; u32 addr_l : 26; } field; u32 val; }; #define DLB_SYS_DIR_PP_V(x) \ (0x8000228 + (x) * 0x1000) #define DLB_SYS_DIR_PP_V_RST 0x0 union dlb_sys_dir_pp_v { struct { u32 pp_v : 1; u32 mb_dm : 1; u32 rsvd0 : 30; } field; u32 val; }; #define DLB_SYS_DIR_CQ_ISR(x) \ (0x8000224 + (x) * 0x1000) #define DLB_SYS_DIR_CQ_ISR_RST 0x0 union dlb_sys_dir_cq_isr { struct { u32 vector : 6; u32 vf : 4; u32 en_code : 2; u32 rsvd0 : 20; } field; u32 val; }; #define DLB_SYS_DIR_CQ2VF_PF(x) \ (0x8000220 + (x) * 0x1000) #define DLB_SYS_DIR_CQ2VF_PF_RST 0x0 union dlb_sys_dir_cq2vf_pf { struct { u32 vf : 4; u32 is_pf : 1; u32 rsvd0 : 27; } field; u32 val; }; #define DLB_SYS_DIR_PP2VAS(x) \ (0x800021c + (x) * 0x1000) #define DLB_SYS_DIR_PP2VAS_RST 0x0 union dlb_sys_dir_pp2vas { struct { u32 vas : 5; u32 rsvd0 : 27; } field; u32 val; }; #define DLB_SYS_DIR_PP2LDBPOOL(x) \ (0x8000218 + (x) * 0x1000) #define DLB_SYS_DIR_PP2LDBPOOL_RST 0x0 union dlb_sys_dir_pp2ldbpool { struct { u32 ldbpool : 6; u32 rsvd0 : 26; } field; u32 val; }; #define DLB_SYS_DIR_PP2DIRPOOL(x) \ (0x8000214 + (x) * 0x1000) #define DLB_SYS_DIR_PP2DIRPOOL_RST 0x0 union dlb_sys_dir_pp2dirpool { struct { u32 dirpool : 6; u32 rsvd0 : 26; } field; u32 val; }; #define DLB_SYS_DIR_PP2VF_PF(x) \ (0x8000210 + (x) * 0x1000) #define DLB_SYS_DIR_PP2VF_PF_RST 0x0 union dlb_sys_dir_pp2vf_pf { struct { u32 vf : 4; u32 is_pf : 1; u32 is_hw_dsi : 1; u32 rsvd0 : 26; } field; u32 val; }; #define DLB_SYS_DIR_PP_ADDR_U(x) \ (0x800020c + (x) * 0x1000) #define DLB_SYS_DIR_PP_ADDR_U_RST 0x0 union dlb_sys_dir_pp_addr_u { struct { u32 addr_u : 32; } field; u32 val; }; #define DLB_SYS_DIR_PP_ADDR_L(x) \ (0x8000208 + (x) * 0x1000) #define DLB_SYS_DIR_PP_ADDR_L_RST 0x0 union dlb_sys_dir_pp_addr_l { struct { u32 rsvd0 : 7; u32 addr_l : 25; } field; u32 val; }; #define DLB_SYS_DIR_CQ_ADDR_U(x) \ (0x8000204 + (x) * 0x1000) #define DLB_SYS_DIR_CQ_ADDR_U_RST 0x0 union dlb_sys_dir_cq_addr_u { struct { u32 addr_u : 32; } field; u32 val; }; #define DLB_SYS_DIR_CQ_ADDR_L(x) \ (0x8000200 + (x) * 0x1000) #define DLB_SYS_DIR_CQ_ADDR_L_RST 0x0 union dlb_sys_dir_cq_addr_l { struct { u32 rsvd0 : 6; u32 addr_l : 26; } field; u32 val; }; #define DLB_SYS_INGRESS_ALARM_ENBL 0x300 #define DLB_SYS_INGRESS_ALARM_ENBL_RST 0x0 union dlb_sys_ingress_alarm_enbl { struct { u32 illegal_hcw : 1; u32 illegal_pp : 1; u32 disabled_pp : 1; u32 illegal_qid : 1; u32 disabled_qid : 1; u32 illegal_ldb_qid_cfg : 1; u32 illegal_cqid : 1; u32 rsvd0 : 25; } field; u32 val; }; #define DLB_SYS_CQ_MODE 0x30c #define DLB_SYS_CQ_MODE_RST 0x0 union dlb_sys_cq_mode { struct { u32 ldb_cq64 : 1; u32 dir_cq64 : 1; u32 rsvd0 : 30; } field; u32 val; }; #define DLB_SYS_MSIX_ACK 0x400 #define DLB_SYS_MSIX_ACK_RST 0x0 union dlb_sys_msix_ack { struct { u32 msix_0_ack : 1; u32 msix_1_ack : 1; u32 msix_2_ack : 1; u32 msix_3_ack : 1; u32 msix_4_ack : 1; u32 msix_5_ack : 1; u32 msix_6_ack : 1; u32 msix_7_ack : 1; u32 msix_8_ack : 1; u32 rsvd0 : 23; } field; u32 val; }; #define DLB_SYS_MSIX_PASSTHRU 0x404 #define DLB_SYS_MSIX_PASSTHRU_RST 0x0 union dlb_sys_msix_passthru { struct { u32 msix_0_passthru : 1; u32 msix_1_passthru : 1; u32 msix_2_passthru : 1; u32 msix_3_passthru : 1; u32 msix_4_passthru : 1; u32 msix_5_passthru : 1; u32 msix_6_passthru : 1; u32 msix_7_passthru : 1; u32 msix_8_passthru : 1; u32 rsvd0 : 23; } field; u32 val; }; #define DLB_SYS_MSIX_MODE 0x408 #define DLB_SYS_MSIX_MODE_RST 0x0 /* MSI-X Modes */ #define DLB_MSIX_MODE_PACKED 0 #define DLB_MSIX_MODE_COMPRESSED 1 union dlb_sys_msix_mode { struct { u32 mode : 1; u32 rsvd0 : 31; } field; u32 val; }; #define DLB_SYS_DIR_CQ_31_0_OCC_INT_STS 0x440 #define DLB_SYS_DIR_CQ_31_0_OCC_INT_STS_RST 0x0 union dlb_sys_dir_cq_31_0_occ_int_sts { struct { u32 cq_0_occ_int : 1; u32 cq_1_occ_int : 1; u32 cq_2_occ_int : 1; u32 cq_3_occ_int : 1; u32 cq_4_occ_int : 1; u32 cq_5_occ_int : 1; u32 cq_6_occ_int : 1; u32 cq_7_occ_int : 1; u32 cq_8_occ_int : 1; u32 cq_9_occ_int : 1; u32 cq_10_occ_int : 1; u32 cq_11_occ_int : 1; u32 cq_12_occ_int : 1; u32 cq_13_occ_int : 1; u32 cq_14_occ_int : 1; u32 cq_15_occ_int : 1; u32 cq_16_occ_int : 1; u32 cq_17_occ_int : 1; u32 cq_18_occ_int : 1; u32 cq_19_occ_int : 1; u32 cq_20_occ_int : 1; u32 cq_21_occ_int : 1; u32 cq_22_occ_int : 1; u32 cq_23_occ_int : 1; u32 cq_24_occ_int : 1; u32 cq_25_occ_int : 1; u32 cq_26_occ_int : 1; u32 cq_27_occ_int : 1; u32 cq_28_occ_int : 1; u32 cq_29_occ_int : 1; u32 cq_30_occ_int : 1; u32 cq_31_occ_int : 1; } field; u32 val; }; #define DLB_SYS_DIR_CQ_63_32_OCC_INT_STS 0x444 #define DLB_SYS_DIR_CQ_63_32_OCC_INT_STS_RST 0x0 union dlb_sys_dir_cq_63_32_occ_int_sts { struct { u32 cq_32_occ_int : 1; u32 cq_33_occ_int : 1; u32 cq_34_occ_int : 1; u32 cq_35_occ_int : 1; u32 cq_36_occ_int : 1; u32 cq_37_occ_int : 1; u32 cq_38_occ_int : 1; u32 cq_39_occ_int : 1; u32 cq_40_occ_int : 1; u32 cq_41_occ_int : 1; u32 cq_42_occ_int : 1; u32 cq_43_occ_int : 1; u32 cq_44_occ_int : 1; u32 cq_45_occ_int : 1; u32 cq_46_occ_int : 1; u32 cq_47_occ_int : 1; u32 cq_48_occ_int : 1; u32 cq_49_occ_int : 1; u32 cq_50_occ_int : 1; u32 cq_51_occ_int : 1; u32 cq_52_occ_int : 1; u32 cq_53_occ_int : 1; u32 cq_54_occ_int : 1; u32 cq_55_occ_int : 1; u32 cq_56_occ_int : 1; u32 cq_57_occ_int : 1; u32 cq_58_occ_int : 1; u32 cq_59_occ_int : 1; u32 cq_60_occ_int : 1; u32 cq_61_occ_int : 1; u32 cq_62_occ_int : 1; u32 cq_63_occ_int : 1; } field; u32 val; }; #define DLB_SYS_DIR_CQ_95_64_OCC_INT_STS 0x448 #define DLB_SYS_DIR_CQ_95_64_OCC_INT_STS_RST 0x0 union dlb_sys_dir_cq_95_64_occ_int_sts { struct { u32 cq_64_occ_int : 1; u32 cq_65_occ_int : 1; u32 cq_66_occ_int : 1; u32 cq_67_occ_int : 1; u32 cq_68_occ_int : 1; u32 cq_69_occ_int : 1; u32 cq_70_occ_int : 1; u32 cq_71_occ_int : 1; u32 cq_72_occ_int : 1; u32 cq_73_occ_int : 1; u32 cq_74_occ_int : 1; u32 cq_75_occ_int : 1; u32 cq_76_occ_int : 1; u32 cq_77_occ_int : 1; u32 cq_78_occ_int : 1; u32 cq_79_occ_int : 1; u32 cq_80_occ_int : 1; u32 cq_81_occ_int : 1; u32 cq_82_occ_int : 1; u32 cq_83_occ_int : 1; u32 cq_84_occ_int : 1; u32 cq_85_occ_int : 1; u32 cq_86_occ_int : 1; u32 cq_87_occ_int : 1; u32 cq_88_occ_int : 1; u32 cq_89_occ_int : 1; u32 cq_90_occ_int : 1; u32 cq_91_occ_int : 1; u32 cq_92_occ_int : 1; u32 cq_93_occ_int : 1; u32 cq_94_occ_int : 1; u32 cq_95_occ_int : 1; } field; u32 val; }; #define DLB_SYS_DIR_CQ_127_96_OCC_INT_STS 0x44c #define DLB_SYS_DIR_CQ_127_96_OCC_INT_STS_RST 0x0 union dlb_sys_dir_cq_127_96_occ_int_sts { struct { u32 cq_96_occ_int : 1; u32 cq_97_occ_int : 1; u32 cq_98_occ_int : 1; u32 cq_99_occ_int : 1; u32 cq_100_occ_int : 1; u32 cq_101_occ_int : 1; u32 cq_102_occ_int : 1; u32 cq_103_occ_int : 1; u32 cq_104_occ_int : 1; u32 cq_105_occ_int : 1; u32 cq_106_occ_int : 1; u32 cq_107_occ_int : 1; u32 cq_108_occ_int : 1; u32 cq_109_occ_int : 1; u32 cq_110_occ_int : 1; u32 cq_111_occ_int : 1; u32 cq_112_occ_int : 1; u32 cq_113_occ_int : 1; u32 cq_114_occ_int : 1; u32 cq_115_occ_int : 1; u32 cq_116_occ_int : 1; u32 cq_117_occ_int : 1; u32 cq_118_occ_int : 1; u32 cq_119_occ_int : 1; u32 cq_120_occ_int : 1; u32 cq_121_occ_int : 1; u32 cq_122_occ_int : 1; u32 cq_123_occ_int : 1; u32 cq_124_occ_int : 1; u32 cq_125_occ_int : 1; u32 cq_126_occ_int : 1; u32 cq_127_occ_int : 1; } field; u32 val; }; #define DLB_SYS_LDB_CQ_31_0_OCC_INT_STS 0x460 #define DLB_SYS_LDB_CQ_31_0_OCC_INT_STS_RST 0x0 union dlb_sys_ldb_cq_31_0_occ_int_sts { struct { u32 cq_0_occ_int : 1; u32 cq_1_occ_int : 1; u32 cq_2_occ_int : 1; u32 cq_3_occ_int : 1; u32 cq_4_occ_int : 1; u32 cq_5_occ_int : 1; u32 cq_6_occ_int : 1; u32 cq_7_occ_int : 1; u32 cq_8_occ_int : 1; u32 cq_9_occ_int : 1; u32 cq_10_occ_int : 1; u32 cq_11_occ_int : 1; u32 cq_12_occ_int : 1; u32 cq_13_occ_int : 1; u32 cq_14_occ_int : 1; u32 cq_15_occ_int : 1; u32 cq_16_occ_int : 1; u32 cq_17_occ_int : 1; u32 cq_18_occ_int : 1; u32 cq_19_occ_int : 1; u32 cq_20_occ_int : 1; u32 cq_21_occ_int : 1; u32 cq_22_occ_int : 1; u32 cq_23_occ_int : 1; u32 cq_24_occ_int : 1; u32 cq_25_occ_int : 1; u32 cq_26_occ_int : 1; u32 cq_27_occ_int : 1; u32 cq_28_occ_int : 1; u32 cq_29_occ_int : 1; u32 cq_30_occ_int : 1; u32 cq_31_occ_int : 1; } field; u32 val; }; #define DLB_SYS_LDB_CQ_63_32_OCC_INT_STS 0x464 #define DLB_SYS_LDB_CQ_63_32_OCC_INT_STS_RST 0x0 union dlb_sys_ldb_cq_63_32_occ_int_sts { struct { u32 cq_32_occ_int : 1; u32 cq_33_occ_int : 1; u32 cq_34_occ_int : 1; u32 cq_35_occ_int : 1; u32 cq_36_occ_int : 1; u32 cq_37_occ_int : 1; u32 cq_38_occ_int : 1; u32 cq_39_occ_int : 1; u32 cq_40_occ_int : 1; u32 cq_41_occ_int : 1; u32 cq_42_occ_int : 1; u32 cq_43_occ_int : 1; u32 cq_44_occ_int : 1; u32 cq_45_occ_int : 1; u32 cq_46_occ_int : 1; u32 cq_47_occ_int : 1; u32 cq_48_occ_int : 1; u32 cq_49_occ_int : 1; u32 cq_50_occ_int : 1; u32 cq_51_occ_int : 1; u32 cq_52_occ_int : 1; u32 cq_53_occ_int : 1; u32 cq_54_occ_int : 1; u32 cq_55_occ_int : 1; u32 cq_56_occ_int : 1; u32 cq_57_occ_int : 1; u32 cq_58_occ_int : 1; u32 cq_59_occ_int : 1; u32 cq_60_occ_int : 1; u32 cq_61_occ_int : 1; u32 cq_62_occ_int : 1; u32 cq_63_occ_int : 1; } field; u32 val; }; #define DLB_SYS_ALARM_HW_SYND 0x50c #define DLB_SYS_ALARM_HW_SYND_RST 0x0 union dlb_sys_alarm_hw_synd { struct { u32 syndrome : 8; u32 rtype : 2; u32 rsvd0 : 2; u32 from_dmv : 1; u32 is_ldb : 1; u32 cls : 2; u32 aid : 6; u32 unit : 4; u32 source : 4; u32 more : 1; u32 valid : 1; } field; u32 val; }; #define DLB_SYS_SYS_ALARM_INT_ENABLE 0xc001048 #define DLB_SYS_SYS_ALARM_INT_ENABLE_RST 0x7fffff union dlb_sys_sys_alarm_int_enable { struct { u32 cq_addr_overflow_error : 1; u32 ingress_perr : 1; u32 egress_perr : 1; u32 alarm_perr : 1; u32 vf_to_pf_isr_pend_error : 1; u32 pf_to_vf_isr_pend_error : 1; u32 timeout_error : 1; u32 dmvw_sm_error : 1; u32 pptr_sm_par_error : 1; u32 pptr_sm_len_error : 1; u32 sch_sm_error : 1; u32 wbuf_flag_error : 1; u32 dmvw_cl_error : 1; u32 dmvr_cl_error : 1; u32 cmpl_data_error : 1; u32 cmpl_error : 1; u32 fifo_underflow : 1; u32 fifo_overflow : 1; u32 sb_ep_parity_err : 1; u32 ti_parity_err : 1; u32 ri_parity_err : 1; u32 cfgm_ppw_err : 1; u32 system_csr_perr : 1; u32 rsvd0 : 9; } field; u32 val; }; #define DLB_LSP_CQ_LDB_TOT_SCH_CNT_CTRL(x) \ (0x20000000 + (x) * 0x1000) #define DLB_LSP_CQ_LDB_TOT_SCH_CNT_CTRL_RST 0x0 union dlb_lsp_cq_ldb_tot_sch_cnt_ctrl { struct { u32 count : 32; } field; u32 val; }; #define DLB_LSP_CQ_LDB_DSBL(x) \ (0x20000124 + (x) * 0x1000) #define DLB_LSP_CQ_LDB_DSBL_RST 0x1 union dlb_lsp_cq_ldb_dsbl { struct { u32 disabled : 1; u32 rsvd0 : 31; } field; u32 val; }; #define DLB_LSP_CQ_LDB_TOT_SCH_CNTH(x) \ (0x20000120 + (x) * 0x1000) #define DLB_LSP_CQ_LDB_TOT_SCH_CNTH_RST 0x0 union dlb_lsp_cq_ldb_tot_sch_cnth { struct { u32 count : 32; } field; u32 val; }; #define DLB_LSP_CQ_LDB_TOT_SCH_CNTL(x) \ (0x2000011c + (x) * 0x1000) #define DLB_LSP_CQ_LDB_TOT_SCH_CNTL_RST 0x0 union dlb_lsp_cq_ldb_tot_sch_cntl { struct { u32 count : 32; } field; u32 val; }; #define DLB_LSP_CQ_LDB_TKN_DEPTH_SEL(x) \ (0x20000118 + (x) * 0x1000) #define DLB_LSP_CQ_LDB_TKN_DEPTH_SEL_RST 0x0 union dlb_lsp_cq_ldb_tkn_depth_sel { struct { u32 token_depth_select : 4; u32 ignore_depth : 1; u32 enab_shallow_cq : 1; u32 rsvd0 : 26; } field; u32 val; }; #define DLB_LSP_CQ_LDB_TKN_CNT(x) \ (0x20000114 + (x) * 0x1000) #define DLB_LSP_CQ_LDB_TKN_CNT_RST 0x0 union dlb_lsp_cq_ldb_tkn_cnt { struct { u32 token_count : 11; u32 rsvd0 : 21; } field; u32 val; }; #define DLB_LSP_CQ_LDB_INFL_LIM(x) \ (0x20000110 + (x) * 0x1000) #define DLB_LSP_CQ_LDB_INFL_LIM_RST 0x0 union dlb_lsp_cq_ldb_infl_lim { struct { u32 limit : 13; u32 rsvd0 : 19; } field; u32 val; }; #define DLB_LSP_CQ_LDB_INFL_CNT(x) \ (0x2000010c + (x) * 0x1000) #define DLB_LSP_CQ_LDB_INFL_CNT_RST 0x0 union dlb_lsp_cq_ldb_infl_cnt { struct { u32 count : 13; u32 rsvd0 : 19; } field; u32 val; }; #define DLB_LSP_CQ2QID(x, y) \ (0x20000104 + (x) * 0x1000 + (y) * 0x4) #define DLB_LSP_CQ2QID_RST 0x0 union dlb_lsp_cq2qid { struct { u32 qid_p0 : 7; u32 rsvd3 : 1; u32 qid_p1 : 7; u32 rsvd2 : 1; u32 qid_p2 : 7; u32 rsvd1 : 1; u32 qid_p3 : 7; u32 rsvd0 : 1; } field; u32 val; }; #define DLB_LSP_CQ2PRIOV(x) \ (0x20000100 + (x) * 0x1000) #define DLB_LSP_CQ2PRIOV_RST 0x0 union dlb_lsp_cq2priov { struct { u32 prio : 24; u32 v : 8; } field; u32 val; }; #define DLB_LSP_CQ_DIR_DSBL(x) \ (0x20000310 + (x) * 0x1000) #define DLB_LSP_CQ_DIR_DSBL_RST 0x1 union dlb_lsp_cq_dir_dsbl { struct { u32 disabled : 1; u32 rsvd0 : 31; } field; u32 val; }; #define DLB_LSP_CQ_DIR_TKN_DEPTH_SEL_DSI(x) \ (0x2000030c + (x) * 0x1000) #define DLB_LSP_CQ_DIR_TKN_DEPTH_SEL_DSI_RST 0x0 union dlb_lsp_cq_dir_tkn_depth_sel_dsi { struct { u32 token_depth_select : 4; u32 disable_wb_opt : 1; u32 ignore_depth : 1; u32 rsvd0 : 26; } field; u32 val; }; #define DLB_LSP_CQ_DIR_TOT_SCH_CNTH(x) \ (0x20000308 + (x) * 0x1000) #define DLB_LSP_CQ_DIR_TOT_SCH_CNTH_RST 0x0 union dlb_lsp_cq_dir_tot_sch_cnth { struct { u32 count : 32; } field; u32 val; }; #define DLB_LSP_CQ_DIR_TOT_SCH_CNTL(x) \ (0x20000304 + (x) * 0x1000) #define DLB_LSP_CQ_DIR_TOT_SCH_CNTL_RST 0x0 union dlb_lsp_cq_dir_tot_sch_cntl { struct { u32 count : 32; } field; u32 val; }; #define DLB_LSP_CQ_DIR_TKN_CNT(x) \ (0x20000300 + (x) * 0x1000) #define DLB_LSP_CQ_DIR_TKN_CNT_RST 0x0 union dlb_lsp_cq_dir_tkn_cnt { struct { u32 count : 11; u32 rsvd0 : 21; } field; u32 val; }; #define DLB_LSP_QID_LDB_QID2CQIDX(x, y) \ (0x20000400 + (x) * 0x1000 + (y) * 0x4) #define DLB_LSP_QID_LDB_QID2CQIDX_RST 0x0 union dlb_lsp_qid_ldb_qid2cqidx { struct { u32 cq_p0 : 8; u32 cq_p1 : 8; u32 cq_p2 : 8; u32 cq_p3 : 8; } field; u32 val; }; #define DLB_LSP_QID_LDB_QID2CQIDX2(x, y) \ (0x20000500 + (x) * 0x1000 + (y) * 0x4) #define DLB_LSP_QID_LDB_QID2CQIDX2_RST 0x0 union dlb_lsp_qid_ldb_qid2cqidx2 { struct { u32 cq_p0 : 8; u32 cq_p1 : 8; u32 cq_p2 : 8; u32 cq_p3 : 8; } field; u32 val; }; #define DLB_LSP_QID_ATQ_ENQUEUE_CNT(x) \ (0x2000066c + (x) * 0x1000) #define DLB_LSP_QID_ATQ_ENQUEUE_CNT_RST 0x0 union dlb_lsp_qid_atq_enqueue_cnt { struct { u32 count : 15; u32 rsvd0 : 17; } field; u32 val; }; #define DLB_LSP_QID_LDB_INFL_LIM(x) \ (0x2000064c + (x) * 0x1000) #define DLB_LSP_QID_LDB_INFL_LIM_RST 0x0 union dlb_lsp_qid_ldb_infl_lim { struct { u32 limit : 13; u32 rsvd0 : 19; } field; u32 val; }; #define DLB_LSP_QID_LDB_INFL_CNT(x) \ (0x2000062c + (x) * 0x1000) #define DLB_LSP_QID_LDB_INFL_CNT_RST 0x0 union dlb_lsp_qid_ldb_infl_cnt { struct { u32 count : 13; u32 rsvd0 : 19; } field; u32 val; }; #define DLB_LSP_QID_AQED_ACTIVE_LIM(x) \ (0x20000628 + (x) * 0x1000) #define DLB_LSP_QID_AQED_ACTIVE_LIM_RST 0x0 union dlb_lsp_qid_aqed_active_lim { struct { u32 limit : 12; u32 rsvd0 : 20; } field; u32 val; }; #define DLB_LSP_QID_AQED_ACTIVE_CNT(x) \ (0x20000624 + (x) * 0x1000) #define DLB_LSP_QID_AQED_ACTIVE_CNT_RST 0x0 union dlb_lsp_qid_aqed_active_cnt { struct { u32 count : 12; u32 rsvd0 : 20; } field; u32 val; }; #define DLB_LSP_QID_LDB_ENQUEUE_CNT(x) \ (0x20000604 + (x) * 0x1000) #define DLB_LSP_QID_LDB_ENQUEUE_CNT_RST 0x0 union dlb_lsp_qid_ldb_enqueue_cnt { struct { u32 count : 15; u32 rsvd0 : 17; } field; u32 val; }; #define DLB_LSP_QID_LDB_REPLAY_CNT(x) \ (0x20000600 + (x) * 0x1000) #define DLB_LSP_QID_LDB_REPLAY_CNT_RST 0x0 union dlb_lsp_qid_ldb_replay_cnt { struct { u32 count : 15; u32 rsvd0 : 17; } field; u32 val; }; #define DLB_LSP_QID_DIR_ENQUEUE_CNT(x) \ (0x20000700 + (x) * 0x1000) #define DLB_LSP_QID_DIR_ENQUEUE_CNT_RST 0x0 union dlb_lsp_qid_dir_enqueue_cnt { struct { u32 count : 13; u32 rsvd0 : 19; } field; u32 val; }; #define DLB_LSP_CTRL_CONFIG_0 0x2800002c #define DLB_LSP_CTRL_CONFIG_0_RST 0x12cc union dlb_lsp_ctrl_config_0 { struct { u32 atm_cq_qid_priority_prot : 1; u32 ldb_arb_ignore_empty : 1; u32 ldb_arb_mode : 2; u32 ldb_arb_threshold : 18; u32 cfg_cq_sla_upd_always : 1; u32 cfg_cq_wcn_upd_always : 1; u32 spare : 8; } field; u32 val; }; #define DLB_LSP_CFG_ARB_WEIGHT_ATM_NALB_QID_1 0x28000028 #define DLB_LSP_CFG_ARB_WEIGHT_ATM_NALB_QID_1_RST 0x0 union dlb_lsp_cfg_arb_weight_atm_nalb_qid_1 { struct { u32 slot4_weight : 8; u32 slot5_weight : 8; u32 slot6_weight : 8; u32 slot7_weight : 8; } field; u32 val; }; #define DLB_LSP_CFG_ARB_WEIGHT_ATM_NALB_QID_0 0x28000024 #define DLB_LSP_CFG_ARB_WEIGHT_ATM_NALB_QID_0_RST 0x0 union dlb_lsp_cfg_arb_weight_atm_nalb_qid_0 { struct { u32 slot0_weight : 8; u32 slot1_weight : 8; u32 slot2_weight : 8; u32 slot3_weight : 8; } field; u32 val; }; #define DLB_LSP_CFG_ARB_WEIGHT_LDB_QID_1 0x28000020 #define DLB_LSP_CFG_ARB_WEIGHT_LDB_QID_1_RST 0x0 union dlb_lsp_cfg_arb_weight_ldb_qid_1 { struct { u32 slot4_weight : 8; u32 slot5_weight : 8; u32 slot6_weight : 8; u32 slot7_weight : 8; } field; u32 val; }; #define DLB_LSP_CFG_ARB_WEIGHT_LDB_QID_0 0x2800001c #define DLB_LSP_CFG_ARB_WEIGHT_LDB_QID_0_RST 0x0 union dlb_lsp_cfg_arb_weight_ldb_qid_0 { struct { u32 slot0_weight : 8; u32 slot1_weight : 8; u32 slot2_weight : 8; u32 slot3_weight : 8; } field; u32 val; }; #define DLB_LSP_LDB_SCHED_CTRL 0x28100000 #define DLB_LSP_LDB_SCHED_CTRL_RST 0x0 union dlb_lsp_ldb_sched_ctrl { struct { u32 cq : 8; u32 qidix : 3; u32 value : 1; u32 nalb_haswork_v : 1; u32 rlist_haswork_v : 1; u32 slist_haswork_v : 1; u32 inflight_ok_v : 1; u32 aqed_nfull_v : 1; u32 spare0 : 15; } field; u32 val; }; #define DLB_LSP_DIR_SCH_CNT_H 0x2820000c #define DLB_LSP_DIR_SCH_CNT_H_RST 0x0 union dlb_lsp_dir_sch_cnt_h { struct { u32 count : 32; } field; u32 val; }; #define DLB_LSP_DIR_SCH_CNT_L 0x28200008 #define DLB_LSP_DIR_SCH_CNT_L_RST 0x0 union dlb_lsp_dir_sch_cnt_l { struct { u32 count : 32; } field; u32 val; }; #define DLB_LSP_LDB_SCH_CNT_H 0x28200004 #define DLB_LSP_LDB_SCH_CNT_H_RST 0x0 union dlb_lsp_ldb_sch_cnt_h { struct { u32 count : 32; } field; u32 val; }; #define DLB_LSP_LDB_SCH_CNT_L 0x28200000 #define DLB_LSP_LDB_SCH_CNT_L_RST 0x0 union dlb_lsp_ldb_sch_cnt_l { struct { u32 count : 32; } field; u32 val; }; #define DLB_DP_DIR_CSR_CTRL 0x38000018 #define DLB_DP_DIR_CSR_CTRL_RST 0xc0000000 union dlb_dp_dir_csr_ctrl { struct { u32 cfg_int_dis : 1; u32 cfg_int_dis_sbe : 1; u32 cfg_int_dis_mbe : 1; u32 spare0 : 27; u32 cfg_vasr_dis : 1; u32 cfg_int_dis_synd : 1; } field; u32 val; }; #define DLB_DP_CFG_CTRL_ARB_WEIGHTS_TQPRI_DIR_1 0x38000014 #define DLB_DP_CFG_CTRL_ARB_WEIGHTS_TQPRI_DIR_1_RST 0xfffefdfc union dlb_dp_cfg_ctrl_arb_weights_tqpri_dir_1 { struct { u32 pri4 : 8; u32 pri5 : 8; u32 pri6 : 8; u32 pri7 : 8; } field; u32 val; }; #define DLB_DP_CFG_CTRL_ARB_WEIGHTS_TQPRI_DIR_0 0x38000010 #define DLB_DP_CFG_CTRL_ARB_WEIGHTS_TQPRI_DIR_0_RST 0xfbfaf9f8 union dlb_dp_cfg_ctrl_arb_weights_tqpri_dir_0 { struct { u32 pri0 : 8; u32 pri1 : 8; u32 pri2 : 8; u32 pri3 : 8; } field; u32 val; }; #define DLB_DP_CFG_CTRL_ARB_WEIGHTS_TQPRI_REPLAY_1 0x3800000c #define DLB_DP_CFG_CTRL_ARB_WEIGHTS_TQPRI_REPLAY_1_RST 0xfffefdfc union dlb_dp_cfg_ctrl_arb_weights_tqpri_replay_1 { struct { u32 pri4 : 8; u32 pri5 : 8; u32 pri6 : 8; u32 pri7 : 8; } field; u32 val; }; #define DLB_DP_CFG_CTRL_ARB_WEIGHTS_TQPRI_REPLAY_0 0x38000008 #define DLB_DP_CFG_CTRL_ARB_WEIGHTS_TQPRI_REPLAY_0_RST 0xfbfaf9f8 union dlb_dp_cfg_ctrl_arb_weights_tqpri_replay_0 { struct { u32 pri0 : 8; u32 pri1 : 8; u32 pri2 : 8; u32 pri3 : 8; } field; u32 val; }; #define DLB_NALB_PIPE_CTRL_ARB_WEIGHTS_TQPRI_NALB_1 0x6800001c #define DLB_NALB_PIPE_CTRL_ARB_WEIGHTS_TQPRI_NALB_1_RST 0xfffefdfc union dlb_nalb_pipe_ctrl_arb_weights_tqpri_nalb_1 { struct { u32 pri4 : 8; u32 pri5 : 8; u32 pri6 : 8; u32 pri7 : 8; } field; u32 val; }; #define DLB_NALB_PIPE_CTRL_ARB_WEIGHTS_TQPRI_NALB_0 0x68000018 #define DLB_NALB_PIPE_CTRL_ARB_WEIGHTS_TQPRI_NALB_0_RST 0xfbfaf9f8 union dlb_nalb_pipe_ctrl_arb_weights_tqpri_nalb_0 { struct { u32 pri0 : 8; u32 pri1 : 8; u32 pri2 : 8; u32 pri3 : 8; } field; u32 val; }; #define DLB_NALB_PIPE_CFG_CTRL_ARB_WEIGHTS_TQPRI_ATQ_1 0x68000014 #define DLB_NALB_PIPE_CFG_CTRL_ARB_WEIGHTS_TQPRI_ATQ_1_RST 0xfffefdfc union dlb_nalb_pipe_cfg_ctrl_arb_weights_tqpri_atq_1 { struct { u32 pri4 : 8; u32 pri5 : 8; u32 pri6 : 8; u32 pri7 : 8; } field; u32 val; }; #define DLB_NALB_PIPE_CFG_CTRL_ARB_WEIGHTS_TQPRI_ATQ_0 0x68000010 #define DLB_NALB_PIPE_CFG_CTRL_ARB_WEIGHTS_TQPRI_ATQ_0_RST 0xfbfaf9f8 union dlb_nalb_pipe_cfg_ctrl_arb_weights_tqpri_atq_0 { struct { u32 pri0 : 8; u32 pri1 : 8; u32 pri2 : 8; u32 pri3 : 8; } field; u32 val; }; #define DLB_NALB_PIPE_CFG_CTRL_ARB_WEIGHTS_TQPRI_REPLAY_1 0x6800000c #define DLB_NALB_PIPE_CFG_CTRL_ARB_WEIGHTS_TQPRI_REPLAY_1_RST 0xfffefdfc union dlb_nalb_pipe_cfg_ctrl_arb_weights_tqpri_replay_1 { struct { u32 pri4 : 8; u32 pri5 : 8; u32 pri6 : 8; u32 pri7 : 8; } field; u32 val; }; #define DLB_NALB_PIPE_CFG_CTRL_ARB_WEIGHTS_TQPRI_REPLAY_0 0x68000008 #define DLB_NALB_PIPE_CFG_CTRL_ARB_WEIGHTS_TQPRI_REPLAY_0_RST 0xfbfaf9f8 union dlb_nalb_pipe_cfg_ctrl_arb_weights_tqpri_replay_0 { struct { u32 pri0 : 8; u32 pri1 : 8; u32 pri2 : 8; u32 pri3 : 8; } field; u32 val; }; #define DLB_ATM_PIPE_QID_LDB_QID2CQIDX(x, y) \ (0x70000000 + (x) * 0x1000 + (y) * 0x4) #define DLB_ATM_PIPE_QID_LDB_QID2CQIDX_RST 0x0 union dlb_atm_pipe_qid_ldb_qid2cqidx { struct { u32 cq_p0 : 8; u32 cq_p1 : 8; u32 cq_p2 : 8; u32 cq_p3 : 8; } field; u32 val; }; #define DLB_ATM_PIPE_CFG_CTRL_ARB_WEIGHTS_SCHED_BIN 0x7800000c #define DLB_ATM_PIPE_CFG_CTRL_ARB_WEIGHTS_SCHED_BIN_RST 0xfffefdfc union dlb_atm_pipe_cfg_ctrl_arb_weights_sched_bin { struct { u32 bin0 : 8; u32 bin1 : 8; u32 bin2 : 8; u32 bin3 : 8; } field; u32 val; }; #define DLB_ATM_PIPE_CTRL_ARB_WEIGHTS_RDY_BIN 0x78000008 #define DLB_ATM_PIPE_CTRL_ARB_WEIGHTS_RDY_BIN_RST 0xfffefdfc union dlb_atm_pipe_ctrl_arb_weights_rdy_bin { struct { u32 bin0 : 8; u32 bin1 : 8; u32 bin2 : 8; u32 bin3 : 8; } field; u32 val; }; #define DLB_AQED_PIPE_QID_FID_LIM(x) \ (0x80000014 + (x) * 0x1000) #define DLB_AQED_PIPE_QID_FID_LIM_RST 0x7ff union dlb_aqed_pipe_qid_fid_lim { struct { u32 qid_fid_limit : 13; u32 rsvd0 : 19; } field; u32 val; }; #define DLB_AQED_PIPE_FL_POP_PTR(x) \ (0x80000010 + (x) * 0x1000) #define DLB_AQED_PIPE_FL_POP_PTR_RST 0x0 union dlb_aqed_pipe_fl_pop_ptr { struct { u32 pop_ptr : 11; u32 generation : 1; u32 rsvd0 : 20; } field; u32 val; }; #define DLB_AQED_PIPE_FL_PUSH_PTR(x) \ (0x8000000c + (x) * 0x1000) #define DLB_AQED_PIPE_FL_PUSH_PTR_RST 0x0 union dlb_aqed_pipe_fl_push_ptr { struct { u32 push_ptr : 11; u32 generation : 1; u32 rsvd0 : 20; } field; u32 val; }; #define DLB_AQED_PIPE_FL_BASE(x) \ (0x80000008 + (x) * 0x1000) #define DLB_AQED_PIPE_FL_BASE_RST 0x0 union dlb_aqed_pipe_fl_base { struct { u32 base : 11; u32 rsvd0 : 21; } field; u32 val; }; #define DLB_AQED_PIPE_FL_LIM(x) \ (0x80000004 + (x) * 0x1000) #define DLB_AQED_PIPE_FL_LIM_RST 0x800 union dlb_aqed_pipe_fl_lim { struct { u32 limit : 11; u32 freelist_disable : 1; u32 rsvd0 : 20; } field; u32 val; }; #define DLB_AQED_PIPE_CFG_CTRL_ARB_WEIGHTS_TQPRI_ATM_0 0x88000008 #define DLB_AQED_PIPE_CFG_CTRL_ARB_WEIGHTS_TQPRI_ATM_0_RST 0xfffe union dlb_aqed_pipe_cfg_ctrl_arb_weights_tqpri_atm_0 { struct { u32 pri0 : 8; u32 pri1 : 8; u32 pri2 : 8; u32 pri3 : 8; } field; u32 val; }; #define DLB_RO_PIPE_QID2GRPSLT(x) \ (0x90000000 + (x) * 0x1000) #define DLB_RO_PIPE_QID2GRPSLT_RST 0x0 union dlb_ro_pipe_qid2grpslt { struct { u32 slot : 5; u32 rsvd1 : 3; u32 group : 2; u32 rsvd0 : 22; } field; u32 val; }; #define DLB_RO_PIPE_GRP_SN_MODE 0x98000008 #define DLB_RO_PIPE_GRP_SN_MODE_RST 0x0 union dlb_ro_pipe_grp_sn_mode { struct { u32 sn_mode_0 : 3; u32 reserved0 : 5; u32 sn_mode_1 : 3; u32 reserved1 : 5; u32 sn_mode_2 : 3; u32 reserved2 : 5; u32 sn_mode_3 : 3; u32 reserved3 : 5; } field; u32 val; }; #define DLB_CHP_CFG_DIR_PP_SW_ALARM_EN(x) \ (0xa000003c + (x) * 0x1000) #define DLB_CHP_CFG_DIR_PP_SW_ALARM_EN_RST 0x1 union dlb_chp_cfg_dir_pp_sw_alarm_en { struct { u32 alarm_enable : 1; u32 rsvd0 : 31; } field; u32 val; }; #define DLB_CHP_DIR_CQ_WD_ENB(x) \ (0xa0000038 + (x) * 0x1000) #define DLB_CHP_DIR_CQ_WD_ENB_RST 0x0 union dlb_chp_dir_cq_wd_enb { struct { u32 wd_enable : 1; u32 rsvd0 : 31; } field; u32 val; }; #define DLB_CHP_DIR_LDB_PP2POOL(x) \ (0xa0000034 + (x) * 0x1000) #define DLB_CHP_DIR_LDB_PP2POOL_RST 0x0 union dlb_chp_dir_ldb_pp2pool { struct { u32 pool : 6; u32 rsvd0 : 26; } field; u32 val; }; #define DLB_CHP_DIR_DIR_PP2POOL(x) \ (0xa0000030 + (x) * 0x1000) #define DLB_CHP_DIR_DIR_PP2POOL_RST 0x0 union dlb_chp_dir_dir_pp2pool { struct { u32 pool : 6; u32 rsvd0 : 26; } field; u32 val; }; #define DLB_CHP_DIR_PP_LDB_CRD_CNT(x) \ (0xa000002c + (x) * 0x1000) #define DLB_CHP_DIR_PP_LDB_CRD_CNT_RST 0x0 union dlb_chp_dir_pp_ldb_crd_cnt { struct { u32 count : 16; u32 rsvd0 : 16; } field; u32 val; }; #define DLB_CHP_DIR_PP_DIR_CRD_CNT(x) \ (0xa0000028 + (x) * 0x1000) #define DLB_CHP_DIR_PP_DIR_CRD_CNT_RST 0x0 union dlb_chp_dir_pp_dir_crd_cnt { struct { u32 count : 14; u32 rsvd0 : 18; } field; u32 val; }; #define DLB_CHP_DIR_CQ_TMR_THRESHOLD(x) \ (0xa0000024 + (x) * 0x1000) #define DLB_CHP_DIR_CQ_TMR_THRESHOLD_RST 0x0 union dlb_chp_dir_cq_tmr_threshold { struct { u32 timer_thrsh : 14; u32 rsvd0 : 18; } field; u32 val; }; #define DLB_CHP_DIR_CQ_INT_ENB(x) \ (0xa0000020 + (x) * 0x1000) #define DLB_CHP_DIR_CQ_INT_ENB_RST 0x0 union dlb_chp_dir_cq_int_enb { struct { u32 en_tim : 1; u32 en_depth : 1; u32 rsvd0 : 30; } field; u32 val; }; #define DLB_CHP_DIR_CQ_INT_DEPTH_THRSH(x) \ (0xa000001c + (x) * 0x1000) #define DLB_CHP_DIR_CQ_INT_DEPTH_THRSH_RST 0x0 union dlb_chp_dir_cq_int_depth_thrsh { struct { u32 depth_threshold : 12; u32 rsvd0 : 20; } field; u32 val; }; #define DLB_CHP_DIR_CQ_TKN_DEPTH_SEL(x) \ (0xa0000018 + (x) * 0x1000) #define DLB_CHP_DIR_CQ_TKN_DEPTH_SEL_RST 0x0 union dlb_chp_dir_cq_tkn_depth_sel { struct { u32 token_depth_select : 4; u32 rsvd0 : 28; } field; u32 val; }; #define DLB_CHP_DIR_PP_LDB_MIN_CRD_QNT(x) \ (0xa0000014 + (x) * 0x1000) #define DLB_CHP_DIR_PP_LDB_MIN_CRD_QNT_RST 0x1 union dlb_chp_dir_pp_ldb_min_crd_qnt { struct { u32 quanta : 10; u32 rsvd0 : 22; } field; u32 val; }; #define DLB_CHP_DIR_PP_DIR_MIN_CRD_QNT(x) \ (0xa0000010 + (x) * 0x1000) #define DLB_CHP_DIR_PP_DIR_MIN_CRD_QNT_RST 0x1 union dlb_chp_dir_pp_dir_min_crd_qnt { struct { u32 quanta : 10; u32 rsvd0 : 22; } field; u32 val; }; #define DLB_CHP_DIR_PP_LDB_CRD_LWM(x) \ (0xa000000c + (x) * 0x1000) #define DLB_CHP_DIR_PP_LDB_CRD_LWM_RST 0x0 union dlb_chp_dir_pp_ldb_crd_lwm { struct { u32 lwm : 16; u32 rsvd0 : 16; } field; u32 val; }; #define DLB_CHP_DIR_PP_LDB_CRD_HWM(x) \ (0xa0000008 + (x) * 0x1000) #define DLB_CHP_DIR_PP_LDB_CRD_HWM_RST 0x0 union dlb_chp_dir_pp_ldb_crd_hwm { struct { u32 hwm : 16; u32 rsvd0 : 16; } field; u32 val; }; #define DLB_CHP_DIR_PP_DIR_CRD_LWM(x) \ (0xa0000004 + (x) * 0x1000) #define DLB_CHP_DIR_PP_DIR_CRD_LWM_RST 0x0 union dlb_chp_dir_pp_dir_crd_lwm { struct { u32 lwm : 14; u32 rsvd0 : 18; } field; u32 val; }; #define DLB_CHP_DIR_PP_DIR_CRD_HWM(x) \ (0xa0000000 + (x) * 0x1000) #define DLB_CHP_DIR_PP_DIR_CRD_HWM_RST 0x0 union dlb_chp_dir_pp_dir_crd_hwm { struct { u32 hwm : 14; u32 rsvd0 : 18; } field; u32 val; }; #define DLB_CHP_CFG_LDB_PP_SW_ALARM_EN(x) \ (0xa0000148 + (x) * 0x1000) #define DLB_CHP_CFG_LDB_PP_SW_ALARM_EN_RST 0x1 union dlb_chp_cfg_ldb_pp_sw_alarm_en { struct { u32 alarm_enable : 1; u32 rsvd0 : 31; } field; u32 val; }; #define DLB_CHP_LDB_CQ_WD_ENB(x) \ (0xa0000144 + (x) * 0x1000) #define DLB_CHP_LDB_CQ_WD_ENB_RST 0x0 union dlb_chp_ldb_cq_wd_enb { struct { u32 wd_enable : 1; u32 rsvd0 : 31; } field; u32 val; }; #define DLB_CHP_SN_CHK_ENBL(x) \ (0xa0000140 + (x) * 0x1000) #define DLB_CHP_SN_CHK_ENBL_RST 0x0 union dlb_chp_sn_chk_enbl { struct { u32 en : 1; u32 rsvd0 : 31; } field; u32 val; }; #define DLB_CHP_HIST_LIST_BASE(x) \ (0xa000013c + (x) * 0x1000) #define DLB_CHP_HIST_LIST_BASE_RST 0x0 union dlb_chp_hist_list_base { struct { u32 base : 13; u32 rsvd0 : 19; } field; u32 val; }; #define DLB_CHP_HIST_LIST_LIM(x) \ (0xa0000138 + (x) * 0x1000) #define DLB_CHP_HIST_LIST_LIM_RST 0x0 union dlb_chp_hist_list_lim { struct { u32 limit : 13; u32 rsvd0 : 19; } field; u32 val; }; #define DLB_CHP_LDB_LDB_PP2POOL(x) \ (0xa0000134 + (x) * 0x1000) #define DLB_CHP_LDB_LDB_PP2POOL_RST 0x0 union dlb_chp_ldb_ldb_pp2pool { struct { u32 pool : 6; u32 rsvd0 : 26; } field; u32 val; }; #define DLB_CHP_LDB_DIR_PP2POOL(x) \ (0xa0000130 + (x) * 0x1000) #define DLB_CHP_LDB_DIR_PP2POOL_RST 0x0 union dlb_chp_ldb_dir_pp2pool { struct { u32 pool : 6; u32 rsvd0 : 26; } field; u32 val; }; #define DLB_CHP_LDB_PP_LDB_CRD_CNT(x) \ (0xa000012c + (x) * 0x1000) #define DLB_CHP_LDB_PP_LDB_CRD_CNT_RST 0x0 union dlb_chp_ldb_pp_ldb_crd_cnt { struct { u32 count : 16; u32 rsvd0 : 16; } field; u32 val; }; #define DLB_CHP_LDB_PP_DIR_CRD_CNT(x) \ (0xa0000128 + (x) * 0x1000) #define DLB_CHP_LDB_PP_DIR_CRD_CNT_RST 0x0 union dlb_chp_ldb_pp_dir_crd_cnt { struct { u32 count : 14; u32 rsvd0 : 18; } field; u32 val; }; #define DLB_CHP_LDB_CQ_TMR_THRESHOLD(x) \ (0xa0000124 + (x) * 0x1000) #define DLB_CHP_LDB_CQ_TMR_THRESHOLD_RST 0x0 union dlb_chp_ldb_cq_tmr_threshold { struct { u32 thrsh : 14; u32 rsvd0 : 18; } field; u32 val; }; #define DLB_CHP_LDB_CQ_INT_ENB(x) \ (0xa0000120 + (x) * 0x1000) #define DLB_CHP_LDB_CQ_INT_ENB_RST 0x0 union dlb_chp_ldb_cq_int_enb { struct { u32 en_tim : 1; u32 en_depth : 1; u32 rsvd0 : 30; } field; u32 val; }; #define DLB_CHP_LDB_CQ_INT_DEPTH_THRSH(x) \ (0xa000011c + (x) * 0x1000) #define DLB_CHP_LDB_CQ_INT_DEPTH_THRSH_RST 0x0 union dlb_chp_ldb_cq_int_depth_thrsh { struct { u32 depth_threshold : 12; u32 rsvd0 : 20; } field; u32 val; }; #define DLB_CHP_LDB_CQ_TKN_DEPTH_SEL(x) \ (0xa0000118 + (x) * 0x1000) #define DLB_CHP_LDB_CQ_TKN_DEPTH_SEL_RST 0x0 union dlb_chp_ldb_cq_tkn_depth_sel { struct { u32 token_depth_select : 4; u32 rsvd0 : 28; } field; u32 val; }; #define DLB_CHP_LDB_PP_LDB_MIN_CRD_QNT(x) \ (0xa0000114 + (x) * 0x1000) #define DLB_CHP_LDB_PP_LDB_MIN_CRD_QNT_RST 0x1 union dlb_chp_ldb_pp_ldb_min_crd_qnt { struct { u32 quanta : 10; u32 rsvd0 : 22; } field; u32 val; }; #define DLB_CHP_LDB_PP_DIR_MIN_CRD_QNT(x) \ (0xa0000110 + (x) * 0x1000) #define DLB_CHP_LDB_PP_DIR_MIN_CRD_QNT_RST 0x1 union dlb_chp_ldb_pp_dir_min_crd_qnt { struct { u32 quanta : 10; u32 rsvd0 : 22; } field; u32 val; }; #define DLB_CHP_LDB_PP_LDB_CRD_LWM(x) \ (0xa000010c + (x) * 0x1000) #define DLB_CHP_LDB_PP_LDB_CRD_LWM_RST 0x0 union dlb_chp_ldb_pp_ldb_crd_lwm { struct { u32 lwm : 16; u32 rsvd0 : 16; } field; u32 val; }; #define DLB_CHP_LDB_PP_LDB_CRD_HWM(x) \ (0xa0000108 + (x) * 0x1000) #define DLB_CHP_LDB_PP_LDB_CRD_HWM_RST 0x0 union dlb_chp_ldb_pp_ldb_crd_hwm { struct { u32 hwm : 16; u32 rsvd0 : 16; } field; u32 val; }; #define DLB_CHP_LDB_PP_DIR_CRD_LWM(x) \ (0xa0000104 + (x) * 0x1000) #define DLB_CHP_LDB_PP_DIR_CRD_LWM_RST 0x0 union dlb_chp_ldb_pp_dir_crd_lwm { struct { u32 lwm : 14; u32 rsvd0 : 18; } field; u32 val; }; #define DLB_CHP_LDB_PP_DIR_CRD_HWM(x) \ (0xa0000100 + (x) * 0x1000) #define DLB_CHP_LDB_PP_DIR_CRD_HWM_RST 0x0 union dlb_chp_ldb_pp_dir_crd_hwm { struct { u32 hwm : 14; u32 rsvd0 : 18; } field; u32 val; }; #define DLB_CHP_DIR_CQ_DEPTH(x) \ (0xa0000218 + (x) * 0x1000) #define DLB_CHP_DIR_CQ_DEPTH_RST 0x0 union dlb_chp_dir_cq_depth { struct { u32 cq_depth : 11; u32 rsvd0 : 21; } field; u32 val; }; #define DLB_CHP_DIR_CQ_WPTR(x) \ (0xa0000214 + (x) * 0x1000) #define DLB_CHP_DIR_CQ_WPTR_RST 0x0 union dlb_chp_dir_cq_wptr { struct { u32 write_pointer : 10; u32 rsvd0 : 22; } field; u32 val; }; #define DLB_CHP_DIR_PP_LDB_PUSH_PTR(x) \ (0xa0000210 + (x) * 0x1000) #define DLB_CHP_DIR_PP_LDB_PUSH_PTR_RST 0x0 union dlb_chp_dir_pp_ldb_push_ptr { struct { u32 push_pointer : 16; u32 rsvd0 : 16; } field; u32 val; }; #define DLB_CHP_DIR_PP_DIR_PUSH_PTR(x) \ (0xa000020c + (x) * 0x1000) #define DLB_CHP_DIR_PP_DIR_PUSH_PTR_RST 0x0 union dlb_chp_dir_pp_dir_push_ptr { struct { u32 push_pointer : 16; u32 rsvd0 : 16; } field; u32 val; }; #define DLB_CHP_DIR_PP_STATE_RESET(x) \ (0xa0000204 + (x) * 0x1000) #define DLB_CHP_DIR_PP_STATE_RESET_RST 0x0 union dlb_chp_dir_pp_state_reset { struct { u32 rsvd1 : 7; u32 dir_type : 1; u32 rsvd0 : 23; u32 reset_pp_state : 1; } field; u32 val; }; #define DLB_CHP_DIR_PP_CRD_REQ_STATE(x) \ (0xa0000200 + (x) * 0x1000) #define DLB_CHP_DIR_PP_CRD_REQ_STATE_RST 0x0 union dlb_chp_dir_pp_crd_req_state { struct { u32 dir_crd_req_active_valid : 1; u32 dir_crd_req_active_check : 1; u32 dir_crd_req_active_busy : 1; u32 rsvd1 : 1; u32 ldb_crd_req_active_valid : 1; u32 ldb_crd_req_active_check : 1; u32 ldb_crd_req_active_busy : 1; u32 rsvd0 : 1; u32 no_pp_credit_update : 1; u32 crd_req_state : 23; } field; u32 val; }; #define DLB_CHP_LDB_CQ_DEPTH(x) \ (0xa0000320 + (x) * 0x1000) #define DLB_CHP_LDB_CQ_DEPTH_RST 0x0 union dlb_chp_ldb_cq_depth { struct { u32 depth : 11; u32 reserved : 2; u32 rsvd0 : 19; } field; u32 val; }; #define DLB_CHP_LDB_CQ_WPTR(x) \ (0xa000031c + (x) * 0x1000) #define DLB_CHP_LDB_CQ_WPTR_RST 0x0 union dlb_chp_ldb_cq_wptr { struct { u32 write_pointer : 10; u32 rsvd0 : 22; } field; u32 val; }; #define DLB_CHP_LDB_PP_LDB_PUSH_PTR(x) \ (0xa0000318 + (x) * 0x1000) #define DLB_CHP_LDB_PP_LDB_PUSH_PTR_RST 0x0 union dlb_chp_ldb_pp_ldb_push_ptr { struct { u32 push_pointer : 16; u32 rsvd0 : 16; } field; u32 val; }; #define DLB_CHP_LDB_PP_DIR_PUSH_PTR(x) \ (0xa0000314 + (x) * 0x1000) #define DLB_CHP_LDB_PP_DIR_PUSH_PTR_RST 0x0 union dlb_chp_ldb_pp_dir_push_ptr { struct { u32 push_pointer : 16; u32 rsvd0 : 16; } field; u32 val; }; #define DLB_CHP_HIST_LIST_POP_PTR(x) \ (0xa000030c + (x) * 0x1000) #define DLB_CHP_HIST_LIST_POP_PTR_RST 0x0 union dlb_chp_hist_list_pop_ptr { struct { u32 pop_ptr : 13; u32 generation : 1; u32 rsvd0 : 18; } field; u32 val; }; #define DLB_CHP_HIST_LIST_PUSH_PTR(x) \ (0xa0000308 + (x) * 0x1000) #define DLB_CHP_HIST_LIST_PUSH_PTR_RST 0x0 union dlb_chp_hist_list_push_ptr { struct { u32 push_ptr : 13; u32 generation : 1; u32 rsvd0 : 18; } field; u32 val; }; #define DLB_CHP_LDB_PP_STATE_RESET(x) \ (0xa0000304 + (x) * 0x1000) #define DLB_CHP_LDB_PP_STATE_RESET_RST 0x0 union dlb_chp_ldb_pp_state_reset { struct { u32 rsvd1 : 7; u32 dir_type : 1; u32 rsvd0 : 23; u32 reset_pp_state : 1; } field; u32 val; }; #define DLB_CHP_LDB_PP_CRD_REQ_STATE(x) \ (0xa0000300 + (x) * 0x1000) #define DLB_CHP_LDB_PP_CRD_REQ_STATE_RST 0x0 union dlb_chp_ldb_pp_crd_req_state { struct { u32 dir_crd_req_active_valid : 1; u32 dir_crd_req_active_check : 1; u32 dir_crd_req_active_busy : 1; u32 rsvd1 : 1; u32 ldb_crd_req_active_valid : 1; u32 ldb_crd_req_active_check : 1; u32 ldb_crd_req_active_busy : 1; u32 rsvd0 : 1; u32 no_pp_credit_update : 1; u32 crd_req_state : 23; } field; u32 val; }; #define DLB_CHP_ORD_QID_SN(x) \ (0xa0000408 + (x) * 0x1000) #define DLB_CHP_ORD_QID_SN_RST 0x0 union dlb_chp_ord_qid_sn { struct { u32 sn : 12; u32 rsvd0 : 20; } field; u32 val; }; #define DLB_CHP_ORD_QID_SN_MAP(x) \ (0xa0000404 + (x) * 0x1000) #define DLB_CHP_ORD_QID_SN_MAP_RST 0x0 union dlb_chp_ord_qid_sn_map { struct { u32 mode : 3; u32 slot : 5; u32 grp : 2; u32 rsvd0 : 22; } field; u32 val; }; #define DLB_CHP_LDB_POOL_CRD_CNT(x) \ (0xa000050c + (x) * 0x1000) #define DLB_CHP_LDB_POOL_CRD_CNT_RST 0x0 union dlb_chp_ldb_pool_crd_cnt { struct { u32 count : 16; u32 rsvd0 : 16; } field; u32 val; }; #define DLB_CHP_QED_FL_BASE(x) \ (0xa0000508 + (x) * 0x1000) #define DLB_CHP_QED_FL_BASE_RST 0x0 union dlb_chp_qed_fl_base { struct { u32 base : 14; u32 rsvd0 : 18; } field; u32 val; }; #define DLB_CHP_QED_FL_LIM(x) \ (0xa0000504 + (x) * 0x1000) #define DLB_CHP_QED_FL_LIM_RST 0x8000 union dlb_chp_qed_fl_lim { struct { u32 limit : 14; u32 rsvd1 : 1; u32 freelist_disable : 1; u32 rsvd0 : 16; } field; u32 val; }; #define DLB_CHP_LDB_POOL_CRD_LIM(x) \ (0xa0000500 + (x) * 0x1000) #define DLB_CHP_LDB_POOL_CRD_LIM_RST 0x0 union dlb_chp_ldb_pool_crd_lim { struct { u32 limit : 16; u32 rsvd0 : 16; } field; u32 val; }; #define DLB_CHP_QED_FL_POP_PTR(x) \ (0xa0000604 + (x) * 0x1000) #define DLB_CHP_QED_FL_POP_PTR_RST 0x0 union dlb_chp_qed_fl_pop_ptr { struct { u32 pop_ptr : 14; u32 reserved0 : 1; u32 generation : 1; u32 rsvd0 : 16; } field; u32 val; }; #define DLB_CHP_QED_FL_PUSH_PTR(x) \ (0xa0000600 + (x) * 0x1000) #define DLB_CHP_QED_FL_PUSH_PTR_RST 0x0 union dlb_chp_qed_fl_push_ptr { struct { u32 push_ptr : 14; u32 reserved0 : 1; u32 generation : 1; u32 rsvd0 : 16; } field; u32 val; }; #define DLB_CHP_DIR_POOL_CRD_CNT(x) \ (0xa000070c + (x) * 0x1000) #define DLB_CHP_DIR_POOL_CRD_CNT_RST 0x0 union dlb_chp_dir_pool_crd_cnt { struct { u32 count : 14; u32 rsvd0 : 18; } field; u32 val; }; #define DLB_CHP_DQED_FL_BASE(x) \ (0xa0000708 + (x) * 0x1000) #define DLB_CHP_DQED_FL_BASE_RST 0x0 union dlb_chp_dqed_fl_base { struct { u32 base : 12; u32 rsvd0 : 20; } field; u32 val; }; #define DLB_CHP_DQED_FL_LIM(x) \ (0xa0000704 + (x) * 0x1000) #define DLB_CHP_DQED_FL_LIM_RST 0x2000 union dlb_chp_dqed_fl_lim { struct { u32 limit : 12; u32 rsvd1 : 1; u32 freelist_disable : 1; u32 rsvd0 : 18; } field; u32 val; }; #define DLB_CHP_DIR_POOL_CRD_LIM(x) \ (0xa0000700 + (x) * 0x1000) #define DLB_CHP_DIR_POOL_CRD_LIM_RST 0x0 union dlb_chp_dir_pool_crd_lim { struct { u32 limit : 14; u32 rsvd0 : 18; } field; u32 val; }; #define DLB_CHP_DQED_FL_POP_PTR(x) \ (0xa0000804 + (x) * 0x1000) #define DLB_CHP_DQED_FL_POP_PTR_RST 0x0 union dlb_chp_dqed_fl_pop_ptr { struct { u32 pop_ptr : 12; u32 reserved0 : 1; u32 generation : 1; u32 rsvd0 : 18; } field; u32 val; }; #define DLB_CHP_DQED_FL_PUSH_PTR(x) \ (0xa0000800 + (x) * 0x1000) #define DLB_CHP_DQED_FL_PUSH_PTR_RST 0x0 union dlb_chp_dqed_fl_push_ptr { struct { u32 push_ptr : 12; u32 reserved0 : 1; u32 generation : 1; u32 rsvd0 : 18; } field; u32 val; }; #define DLB_CHP_CTRL_DIAG_02 0xa8000154 #define DLB_CHP_CTRL_DIAG_02_RST 0x0 union dlb_chp_ctrl_diag_02 { struct { u32 control : 32; } field; u32 val; }; #define DLB_CHP_CFG_CHP_CSR_CTRL 0xa8000130 #define DLB_CHP_CFG_CHP_CSR_CTRL_RST 0xc0003fff #define DLB_CHP_CFG_EXCESS_TOKENS_SHIFT 12 union dlb_chp_cfg_chp_csr_ctrl { struct { u32 int_inf_alarm_enable_0 : 1; u32 int_inf_alarm_enable_1 : 1; u32 int_inf_alarm_enable_2 : 1; u32 int_inf_alarm_enable_3 : 1; u32 int_inf_alarm_enable_4 : 1; u32 int_inf_alarm_enable_5 : 1; u32 int_inf_alarm_enable_6 : 1; u32 int_inf_alarm_enable_7 : 1; u32 int_inf_alarm_enable_8 : 1; u32 int_inf_alarm_enable_9 : 1; u32 int_inf_alarm_enable_10 : 1; u32 int_inf_alarm_enable_11 : 1; u32 int_inf_alarm_enable_12 : 1; u32 int_cor_alarm_enable : 1; u32 csr_control_spare : 14; u32 cfg_vasr_dis : 1; u32 counter_clear : 1; u32 blk_cor_report : 1; u32 blk_cor_synd : 1; } field; u32 val; }; #define DLB_CHP_LDB_CQ_INTR_ARMED1 0xa8000068 #define DLB_CHP_LDB_CQ_INTR_ARMED1_RST 0x0 union dlb_chp_ldb_cq_intr_armed1 { struct { u32 armed : 32; } field; u32 val; }; #define DLB_CHP_LDB_CQ_INTR_ARMED0 0xa8000064 #define DLB_CHP_LDB_CQ_INTR_ARMED0_RST 0x0 union dlb_chp_ldb_cq_intr_armed0 { struct { u32 armed : 32; } field; u32 val; }; #define DLB_CHP_DIR_CQ_INTR_ARMED3 0xa8000024 #define DLB_CHP_DIR_CQ_INTR_ARMED3_RST 0x0 union dlb_chp_dir_cq_intr_armed3 { struct { u32 armed : 32; } field; u32 val; }; #define DLB_CHP_DIR_CQ_INTR_ARMED2 0xa8000020 #define DLB_CHP_DIR_CQ_INTR_ARMED2_RST 0x0 union dlb_chp_dir_cq_intr_armed2 { struct { u32 armed : 32; } field; u32 val; }; #define DLB_CHP_DIR_CQ_INTR_ARMED1 0xa800001c #define DLB_CHP_DIR_CQ_INTR_ARMED1_RST 0x0 union dlb_chp_dir_cq_intr_armed1 { struct { u32 armed : 32; } field; u32 val; }; #define DLB_CHP_DIR_CQ_INTR_ARMED0 0xa8000018 #define DLB_CHP_DIR_CQ_INTR_ARMED0_RST 0x0 union dlb_chp_dir_cq_intr_armed0 { struct { u32 armed : 32; } field; u32 val; }; #define DLB_CFG_MSTR_DIAG_RESET_STS 0xb8000004 #define DLB_CFG_MSTR_DIAG_RESET_STS_RST 0x1ff union dlb_cfg_mstr_diag_reset_sts { struct { u32 chp_pf_reset_done : 1; u32 rop_pf_reset_done : 1; u32 lsp_pf_reset_done : 1; u32 nalb_pf_reset_done : 1; u32 ap_pf_reset_done : 1; u32 dp_pf_reset_done : 1; u32 qed_pf_reset_done : 1; u32 dqed_pf_reset_done : 1; u32 aqed_pf_reset_done : 1; u32 rsvd1 : 6; u32 pf_reset_active : 1; u32 chp_vf_reset_done : 1; u32 rop_vf_reset_done : 1; u32 lsp_vf_reset_done : 1; u32 nalb_vf_reset_done : 1; u32 ap_vf_reset_done : 1; u32 dp_vf_reset_done : 1; u32 qed_vf_reset_done : 1; u32 dqed_vf_reset_done : 1; u32 aqed_vf_reset_done : 1; u32 rsvd0 : 6; u32 vf_reset_active : 1; } field; u32 val; }; #define DLB_CFG_MSTR_BCAST_RESET_VF_START 0xc8100000 #define DLB_CFG_MSTR_BCAST_RESET_VF_START_RST 0x0 /* HW Reset Types */ #define VF_RST_TYPE_CQ_LDB 0 #define VF_RST_TYPE_QID_LDB 1 #define VF_RST_TYPE_POOL_LDB 2 #define VF_RST_TYPE_CQ_DIR 8 #define VF_RST_TYPE_QID_DIR 9 #define VF_RST_TYPE_POOL_DIR 10 union dlb_cfg_mstr_bcast_reset_vf_start { struct { u32 vf_reset_start : 1; u32 reserved : 3; u32 vf_reset_type : 4; u32 vf_reset_id : 24; } field; u32 val; }; #endif /* __DLB_REGS_H */
28,119
432
<gh_stars>100-1000 package us.parr.bookish.model; public class InlineImage extends OutputModelObject { public String src; public InlineImage(String src) { this.src = src; } }
64
303
<filename>www/draw/metadata/1/1843.json {"id":1843,"line-1":"Africa","line-2":"West Sahara","attribution":"©2014 Cnes/Spot Image, DigitalGlobe","url":"https://www.google.com/maps/@26.738712,-13.026609,16z/data=!3m1!1e3"}
89
777
<gh_stars>100-1000 // Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef IOS_CHROME_BROWSER_AUTOCOMPLETE_AUTOCOMPLETE_SCHEME_CLASSIFIER_IMPL_H_ #define IOS_CHROME_BROWSER_AUTOCOMPLETE_AUTOCOMPLETE_SCHEME_CLASSIFIER_IMPL_H_ #include "base/macros.h" #include "components/omnibox/browser/autocomplete_scheme_classifier.h" // AutocompleteSchemeClassifierImpl provides iOS-specific implementation of // AutocompleteSchemeClassifier interface. class AutocompleteSchemeClassifierImpl : public AutocompleteSchemeClassifier { public: AutocompleteSchemeClassifierImpl(); ~AutocompleteSchemeClassifierImpl() override; // AutocompleteInputSchemeChecker implementation. metrics::OmniboxInputType::Type GetInputTypeForScheme( const std::string& scheme) const override; private: DISALLOW_COPY_AND_ASSIGN(AutocompleteSchemeClassifierImpl); }; #endif // IOS_CHROME_BROWSER_AUTOCOMPLETE_AUTOCOMPLETE_SCHEME_CLASSIFIER_IMPL_H_
364
522
<reponame>dominico966/Spark package org.jivesoftware.spark.otrplug.util; /** * OTRResources needed to load icons and language files into OTR plugin * * @author <NAME> */ import java.text.MessageFormat; import java.util.PropertyResourceBundle; import java.util.ResourceBundle; import javax.swing.ImageIcon; import org.jivesoftware.spark.util.log.Log; public class OTRResources { private static PropertyResourceBundle prb; static ClassLoader cl = OTRResources.class.getClassLoader(); static { prb = (PropertyResourceBundle) ResourceBundle.getBundle("i18n/otrplugin_i18n"); } /** * Returns a string from the language file * * @param propertyName * @return */ public static final String getString(String propertyName) { try { return prb.getString(propertyName); } catch (Exception e) { Log.error(e); return propertyName; } } /** * Returns an ImageIcon from OTR resources folder * * @param fileName * @return */ public static ImageIcon getIcon(String fileName) { final ClassLoader cl = OTRResources.class.getClassLoader(); ImageIcon icon = new ImageIcon(cl.getResource(fileName)); return icon; } /** * Returns a string with wildcards * * @param propertyName * @param obj */ public static String getString(String propertyName, Object... obj) { String str = prb.getString(propertyName); if (str == null) { return propertyName; } return MessageFormat.format(str, obj); } }
656
2,338
<gh_stars>1000+ // Exercise some template issues. Should not produce errors. // Forward declaration. template<class T> class TemplateClass; // Full declaration. template<class T>class TemplateClass { public: TemplateClass() {} private: T Member; }; // Template alias. template<class T> using TemplateClassAlias = TemplateClass<T>;
95
742
<filename>apps/point_cloud/image_common/camera_calibration_parsers/src/parse_wrapper.cpp /********************************************************************* * Software License Agreement (BSD License) * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Willow Garage 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. *********************************************************************/ #include "camera_calibration_parsers/parse.h" #include "camera_calibration_parsers/parse_wrapper.h" #include <boost/python.hpp> #include <ros/serialization.h> namespace camera_calibration_parsers { /* Write a ROS message into a serialized string. * @from https://github.com/galou/python_bindings_tutorial/blob/master/src/add_two_ints_wrapper.cpp#L27 */ template <typename M> std::string to_python(const M& msg) { size_t serial_size = ros::serialization::serializationLength(msg); boost::shared_array<uint8_t> buffer(new uint8_t[serial_size]); ros::serialization::OStream stream(buffer.get(), serial_size); ros::serialization::serialize(stream, msg); std::string str_msg; str_msg.reserve(serial_size); for (size_t i = 0; i < serial_size; ++i) { str_msg.push_back(buffer[i]); } return str_msg; } // Wrapper for readCalibration() boost::python::tuple readCalibrationWrapper(const std::string& file_name) { std::string camera_name; sensor_msgs::CameraInfo camera_info; bool result = readCalibration(file_name, camera_name, camera_info); std::string cam_info = to_python(camera_info); return boost::python::make_tuple(result, camera_name, cam_info); } BOOST_PYTHON_MODULE(camera_calibration_parsers_wrapper) { boost::python::def("__readCalibrationWrapper", readCalibrationWrapper, boost::python::args("file_name"), ""); } } //namespace camera_calibration_parsers
1,010
1,144
<reponame>legendecas/ShadowNode /* Copyright 2015-present Samsung Electronics Co., Ltd. and other contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "iotjs_def.h" #include "iotjs_module.h" #include "mbedtls/ssl.h" #define NODE_DEFINE_CONSTANT(object, constant) \ do { \ iotjs_jval_set_property_number(object, #constant, constant); \ } while (0) #ifdef MBEDTLS_SSL_MAX_CONTENT_LEN #define TLS_CHUNK_MAX_SIZE MBEDTLS_SSL_MAX_CONTENT_LEN #else #define TLS_CHUNK_MAX_SIZE INT_MAX #endif #define INT32_MAX_VALUE UINT32_MAX void DefineSignalConstants(jerry_value_t target) { #ifdef SIGHUP NODE_DEFINE_CONSTANT(target, SIGHUP); #endif #ifdef SIGINT NODE_DEFINE_CONSTANT(target, SIGINT); #endif #ifdef SIGQUIT NODE_DEFINE_CONSTANT(target, SIGQUIT); #endif #ifdef SIGILL NODE_DEFINE_CONSTANT(target, SIGILL); #endif #ifdef SIGTRAP NODE_DEFINE_CONSTANT(target, SIGTRAP); #endif #ifdef SIGABRT NODE_DEFINE_CONSTANT(target, SIGABRT); #endif #ifdef SIGIOT NODE_DEFINE_CONSTANT(target, SIGIOT); #endif #ifdef SIGBUS NODE_DEFINE_CONSTANT(target, SIGBUS); #endif #ifdef SIGFPE NODE_DEFINE_CONSTANT(target, SIGFPE); #endif #ifdef SIGKILL NODE_DEFINE_CONSTANT(target, SIGKILL); #endif #ifdef SIGUSR1 NODE_DEFINE_CONSTANT(target, SIGUSR1); #endif #ifdef SIGSEGV NODE_DEFINE_CONSTANT(target, SIGSEGV); #endif #ifdef SIGUSR2 NODE_DEFINE_CONSTANT(target, SIGUSR2); #endif #ifdef SIGPIPE NODE_DEFINE_CONSTANT(target, SIGPIPE); #endif #ifdef SIGALRM NODE_DEFINE_CONSTANT(target, SIGALRM); #endif NODE_DEFINE_CONSTANT(target, SIGTERM); #ifdef SIGCHLD NODE_DEFINE_CONSTANT(target, SIGCHLD); #endif #ifdef SIGSTKFLT NODE_DEFINE_CONSTANT(target, SIGSTKFLT); #endif #ifdef SIGCONT NODE_DEFINE_CONSTANT(target, SIGCONT); #endif #ifdef SIGSTOP NODE_DEFINE_CONSTANT(target, SIGSTOP); #endif #ifdef SIGTSTP NODE_DEFINE_CONSTANT(target, SIGTSTP); #endif #ifdef SIGBREAK NODE_DEFINE_CONSTANT(target, SIGBREAK); #endif #ifdef SIGTTIN NODE_DEFINE_CONSTANT(target, SIGTTIN); #endif #ifdef SIGTTOU NODE_DEFINE_CONSTANT(target, SIGTTOU); #endif #ifdef SIGURG NODE_DEFINE_CONSTANT(target, SIGURG); #endif #ifdef SIGXCPU NODE_DEFINE_CONSTANT(target, SIGXCPU); #endif #ifdef SIGXFSZ NODE_DEFINE_CONSTANT(target, SIGXFSZ); #endif #ifdef SIGVTALRM NODE_DEFINE_CONSTANT(target, SIGVTALRM); #endif #ifdef SIGPROF NODE_DEFINE_CONSTANT(target, SIGPROF); #endif #ifdef SIGWINCH NODE_DEFINE_CONSTANT(target, SIGWINCH); #endif #ifdef SIGIO NODE_DEFINE_CONSTANT(target, SIGIO); #endif #ifdef SIGPOLL NODE_DEFINE_CONSTANT(target, SIGPOLL); #endif #ifdef SIGLOST NODE_DEFINE_CONSTANT(target, SIGLOST); #endif #ifdef SIGPWR NODE_DEFINE_CONSTANT(target, SIGPWR); #endif #ifdef SIGINFO NODE_DEFINE_CONSTANT(target, SIGINFO); #endif #ifdef SIGSYS NODE_DEFINE_CONSTANT(target, SIGSYS); #endif #ifdef SIGUNUSED NODE_DEFINE_CONSTANT(target, SIGUNUSED); #endif } void DefinePriorityConstants(jerry_value_t target) { NODE_DEFINE_CONSTANT(target, UV_PRIORITY_LOW); NODE_DEFINE_CONSTANT(target, UV_PRIORITY_HIGHEST); } jerry_value_t InitConstants() { jerry_value_t exports = jerry_create_object(); jerry_value_t os = jerry_create_object(); iotjs_jval_set_property_jval(exports, "os", os); NODE_DEFINE_CONSTANT(exports, O_APPEND); NODE_DEFINE_CONSTANT(exports, O_CREAT); NODE_DEFINE_CONSTANT(exports, O_EXCL); NODE_DEFINE_CONSTANT(exports, O_RDONLY); NODE_DEFINE_CONSTANT(exports, O_RDWR); NODE_DEFINE_CONSTANT(exports, O_SYNC); NODE_DEFINE_CONSTANT(exports, O_TRUNC); NODE_DEFINE_CONSTANT(exports, O_WRONLY); NODE_DEFINE_CONSTANT(exports, S_IFMT); NODE_DEFINE_CONSTANT(exports, S_IFDIR); NODE_DEFINE_CONSTANT(exports, S_IFIFO); NODE_DEFINE_CONSTANT(exports, S_IFREG); NODE_DEFINE_CONSTANT(exports, S_IFLNK); NODE_DEFINE_CONSTANT(exports, S_IFSOCK); NODE_DEFINE_CONSTANT(exports, TLS_CHUNK_MAX_SIZE); NODE_DEFINE_CONSTANT(exports, INT32_MAX_VALUE); // define uv errnos #define V(name, _) NODE_DEFINE_CONSTANT(exports, UV_##name); UV_ERRNO_MAP(V) #undef V // define uv priority constants DefinePriorityConstants(exports); jerry_value_t signals = jerry_create_object(); DefineSignalConstants(signals); iotjs_jval_set_property_jval(os, "signals", signals); jerry_release_value(signals); jerry_release_value(os); return exports; }
2,136
1,190
_base_ = './repvgg-B3_4xb64-autoaug-lbs-mixup-coslr-200e_in1k.py' model = dict(backbone=dict(arch='D2se'))
56
918
<reponame>yogi1324/gobblin<gh_stars>100-1000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.instrumented.writer; import java.io.IOException; import com.google.common.base.Optional; import org.apache.gobblin.configuration.State; import org.apache.gobblin.dataset.Descriptor; import org.apache.gobblin.instrumented.Instrumented; import org.apache.gobblin.metrics.MetricContext; import org.apache.gobblin.records.ControlMessageHandler; import org.apache.gobblin.stream.RecordEnvelope; import org.apache.gobblin.util.Decorator; import org.apache.gobblin.util.DecoratorUtils; import org.apache.gobblin.util.FinalState; import org.apache.gobblin.writer.DataWriter; import org.apache.gobblin.writer.WatermarkAwareWriter; /** * Decorator that automatically instruments {@link org.apache.gobblin.writer.DataWriter}. Handles already instrumented * {@link org.apache.gobblin.instrumented.writer.InstrumentedDataWriter} appropriately to avoid double metric reporting. */ public class InstrumentedDataWriterDecorator<D> extends InstrumentedDataWriterBase<D> implements Decorator, WatermarkAwareWriter<D> { private DataWriter<D> embeddedWriter; private boolean isEmbeddedInstrumented; private Optional<WatermarkAwareWriter> watermarkAwareWriter; public InstrumentedDataWriterDecorator(DataWriter<D> writer, State state) { super(state, Optional.<Class<?>> of(DecoratorUtils.resolveUnderlyingObject(writer).getClass())); this.embeddedWriter = this.closer.register(writer); this.isEmbeddedInstrumented = Instrumented.isLineageInstrumented(writer); Object underlying = DecoratorUtils.resolveUnderlyingObject(embeddedWriter); if (underlying instanceof WatermarkAwareWriter) { this.watermarkAwareWriter = Optional.of((WatermarkAwareWriter) underlying); } else { this.watermarkAwareWriter = Optional.absent(); } } @Override public MetricContext getMetricContext() { return this.isEmbeddedInstrumented ? ((InstrumentedDataWriterBase<D>) this.embeddedWriter).getMetricContext() : super.getMetricContext(); } @Override public final void write(D record) throws IOException { throw new UnsupportedOperationException(); } @Override public void writeEnvelope(RecordEnvelope<D> record) throws IOException { if (this.isEmbeddedInstrumented) { this.embeddedWriter.writeEnvelope(record); } else { if (!isInstrumentationEnabled()) { this.embeddedWriter.writeEnvelope(record); return; } try { long startTimeNanos = System.nanoTime(); beforeWrite(record.getRecord()); this.embeddedWriter.writeEnvelope(record); onSuccessfulWrite(startTimeNanos); } catch (IOException exception) { onException(exception); throw exception; } } } @Override public void writeImpl(D record) throws IOException { this.embeddedWriter.write(record); } @Override public void commit() throws IOException { this.embeddedWriter.commit(); super.commit(); } @Override public void cleanup() throws IOException { this.embeddedWriter.cleanup(); } @Override public long recordsWritten() { return this.embeddedWriter.recordsWritten(); } @Override public long bytesWritten() throws IOException { return this.embeddedWriter.bytesWritten(); } @Override public State getFinalState() { if (this.embeddedWriter instanceof FinalState) { return ((FinalState) this.embeddedWriter).getFinalState(); } return super.getFinalState(); } @Override public Descriptor getDataDescriptor() { return this.embeddedWriter.getDataDescriptor(); } @Override public Object getDecoratedObject() { return this.embeddedWriter; } @Override public boolean isWatermarkCapable() { return watermarkAwareWriter.isPresent() && watermarkAwareWriter.get().isWatermarkCapable(); } @Override public ControlMessageHandler getMessageHandler() { return this.embeddedWriter.getMessageHandler(); } @Override public void flush() throws IOException { this.embeddedWriter.flush(); } }
1,549
323
<filename>springboot-admin-server/src/main/java/cn/huanzi/qch/springbootadminserver/SpringBootAdminServerApplication.java package cn.huanzi.qch.springbootadminserver; import de.codecentric.boot.admin.server.config.EnableAdminServer; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; @EnableAdminServer//开启AdminServer功能 @SpringBootApplication public class SpringBootAdminServerApplication { public static void main(String[] args) { SpringApplication.run(SpringBootAdminServerApplication.class, args); } /** * 启动成功 */ @Bean public ApplicationRunner applicationRunner() { return applicationArguments -> { System.out.println("启动成功!"); }; } }
311
2,690
<reponame>PushyamiKaveti/kalibr<gh_stars>1000+ /****************************************************************************** * Copyright (C) 2013 by <NAME> * * <EMAIL> * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the Lesser GNU General Public License as published by* * the Free Software Foundation; either version 3 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * Lesser GNU General Public License for more details. * * * * You should have received a copy of the Lesser GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************/ #include "aslam/calibration/statistics/NormalDistribution.h" #include "aslam/calibration/statistics/Randomizer.h" #include "aslam/calibration/exceptions/BadArgumentException.h" namespace aslam { namespace calibration { /******************************************************************************/ /* Constructors and Destructor */ /******************************************************************************/ NormalDistribution<1>::NormalDistribution(Mean mean, Variance variance) : mMean(mean) { setVariance(variance); } NormalDistribution<1>::NormalDistribution(const std::tuple<Mean, Variance>& parameters) : mMean(std::get<0>(parameters)) { setVariance(std::get<1>(parameters)); } NormalDistribution<1>::NormalDistribution(const NormalDistribution& other) : mMean(other.mMean), mVariance(other.mVariance), mPrecision(other.mPrecision), mStandardDeviation(other.mStandardDeviation), mNormalizer(other.mNormalizer) { } NormalDistribution<1>& NormalDistribution<1>::operator = (const NormalDistribution& other) { if (this != &other) { mMean = other.mMean; mVariance = other.mVariance; mPrecision = other.mPrecision; mStandardDeviation = other.mStandardDeviation; mNormalizer = other.mNormalizer; } return *this; } NormalDistribution<1>::~NormalDistribution() { } /******************************************************************************/ /* Stream operations */ /******************************************************************************/ void NormalDistribution<1>::read(std::istream& stream) { } void NormalDistribution<1>::write(std::ostream& stream) const { stream << "mean: " << mMean << std::endl << "variance: " << mVariance; } void NormalDistribution<1>::read(std::ifstream& stream) { } void NormalDistribution<1>::write(std::ofstream& stream) const { } /******************************************************************************/ /* Accessors */ /******************************************************************************/ void NormalDistribution<1>::setMean(Mean mean) { mMean = mean; } NormalDistribution<1>::Mean NormalDistribution<1>::getMean() const { return mMean; } void NormalDistribution<1>::setVariance(Variance variance) { if (variance <= 0.0) throw BadArgumentException<Variance>(variance, "NormalDistribution::setVariance(): variance must be strictly bigger " "than 0", __FILE__, __LINE__); mVariance = variance; mPrecision = 1.0 / variance; mStandardDeviation = sqrt(variance); mNormalizer = 0.5 * log(2.0 * M_PI * mVariance); } NormalDistribution<1>::Variance NormalDistribution<1>::getVariance() const { return mVariance; } NormalDistribution<1>::Precision NormalDistribution<1>::getPrecision() const { return mPrecision; } NormalDistribution<1>::Std NormalDistribution<1>::getStandardDeviation() const { return mStandardDeviation; } double NormalDistribution<1>::getNormalizer() const { return mNormalizer; } double NormalDistribution<1>::pdf(const RandomVariable& value) const { return exp(logpdf(value)); } double NormalDistribution<1>::logpdf(const RandomVariable& value) const { return -0.5 * mahalanobisDistance(value) - mNormalizer; } double NormalDistribution<1>::cdf(const RandomVariable& value) const { return 0.5 * (1.0 + erf((value - mMean) / sqrt(2 * mVariance))); } NormalDistribution<1>::RandomVariable NormalDistribution<1>::getSample() const { const static Randomizer<double> randomizer; return randomizer.sampleNormal(mMean, mVariance); } double NormalDistribution<1>::KLDivergence(const NormalDistribution<1>& other) const { return 0.5 * (log(other.mVariance * mPrecision) + other.mPrecision * mVariance - 1.0 + (mMean - other.mMean) * other.mPrecision * (mMean - other.mMean)); } double NormalDistribution<1>::mahalanobisDistance(const RandomVariable& value) const { return (value - mMean) * mPrecision * (value - mMean); } NormalDistribution<1>::Median NormalDistribution<1>::getMedian() const { return mMean; } NormalDistribution<1>::Mode NormalDistribution<1>::getMode() const { return mMean; } } }
2,543
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. * */ // Original file Copyright Crytek GMBH or its affiliates, used under license. #pragma once #include "ResourceSelector.h" namespace Serialization { template<class T> ResourceSelector<T> AudioTrigger(T& s) { return ResourceSelector<T>(s, "AudioTrigger"); } template<class T> ResourceSelector<T> AudioSwitch(T& s) { return ResourceSelector<T>(s, "AudioSwitch"); } template<class T> ResourceSelector<T> AudioSwitchState(T& s) { return ResourceSelector<T>(s, "AudioSwitchState"); } template<class T> ResourceSelector<T> AudioRTPC(T& s) { return ResourceSelector<T>(s, "AudioRTPC"); } template<class T> ResourceSelector<T> AudioEnvironment(T& s) { return ResourceSelector<T>(s, "AudioEnvironment"); } template<class T> ResourceSelector<T> AudioPreloadRequest(T& s) { return ResourceSelector<T>(s, "AudioPreloadRequest"); } };
441
2,151
<filename>content/public/test/android/javatests/src/org/chromium/content/browser/test/util/EqualityCriteria.java // 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. package org.chromium.content.browser.test.util; import java.util.concurrent.Callable; /** * Extension of the Criteria that handles object equality while providing a standard error message. * * @param <T> The type of value whose equality will be tested. */ class EqualityCriteria<T> extends Criteria { private final T mExpectedValue; private final Callable<T> mActualValueCallable; /** * Construct the EqualityCriteria with the given expected value. * @param expectedValue The value that is expected to determine the success of the criteria. */ public EqualityCriteria(T expectedValue, Callable<T> actualValueCallable) { mExpectedValue = expectedValue; mActualValueCallable = actualValueCallable; } @Override public final boolean isSatisfied() { T actualValue = null; try { actualValue = mActualValueCallable.call(); } catch (Exception ex) { updateFailureReason("Exception occurred: " + ex.getMessage()); ex.printStackTrace(); return false; } updateFailureReason( "Values did not match. Expected: " + mExpectedValue + ", actual: " + actualValue); if (mExpectedValue == null) { return actualValue == null; } return mExpectedValue.equals(actualValue); } }
583
679
<reponame>Grosskopf/openoffice /************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #ifndef _TOOLKIT_CONTROLS_STDTABCONTROLLER_HXX_ #define _TOOLKIT_CONTROLS_STDTABCONTROLLER_HXX_ #include <com/sun/star/lang/XServiceInfo.hpp> #include <com/sun/star/awt/XTabController.hpp> #include <com/sun/star/awt/XControl.hpp> #include <com/sun/star/awt/XControlContainer.hpp> #include <com/sun/star/lang/XTypeProvider.hpp> #include <cppuhelper/weakagg.hxx> #include <osl/mutex.hxx> #include <toolkit/helper/macros.hxx> #include <toolkit/helper/servicenames.hxx> class StdTabController : public ::com::sun::star::awt::XTabController, public ::com::sun::star::lang::XServiceInfo, public ::com::sun::star::lang::XTypeProvider, public ::cppu::OWeakAggObject { private: ::osl::Mutex maMutex; ::com::sun::star::uno::Reference< ::com::sun::star::awt::XTabControllerModel > mxModel; ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer > mxControlContainer; protected: ::osl::Mutex& GetMutex() { return maMutex; } sal_Bool ImplCreateComponentSequence( ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl > >& rControls, const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel > >& rModels, ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow > >& rComponents, ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any>* pTabStops, sal_Bool bPeerComponent ) const; // wenn rModels kuerzer als rControls ist, werden nur die rModels entsprechenden Elemente geliefert und die korrespondierenden Elemente aus rControls entfernt void ImplActivateControl( sal_Bool bFirst ) const; public: StdTabController(); ~StdTabController(); static ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl > FindControl( ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl > >& rCtrls, const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel > & rxCtrlModel ); // ::com::sun::star::uno::XInterface ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException) { return OWeakAggObject::queryInterface(rType); } void SAL_CALL acquire() throw() { OWeakAggObject::acquire(); } void SAL_CALL release() throw() { OWeakAggObject::release(); } ::com::sun::star::uno::Any SAL_CALL queryAggregation( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException); // ::com::sun::star::lang::XTypeProvider ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes() throw(::com::sun::star::uno::RuntimeException); ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() throw(::com::sun::star::uno::RuntimeException); // XTabController void SAL_CALL setModel( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XTabControllerModel >& Model ) throw(::com::sun::star::uno::RuntimeException); ::com::sun::star::uno::Reference< ::com::sun::star::awt::XTabControllerModel > SAL_CALL getModel( ) throw(::com::sun::star::uno::RuntimeException); void SAL_CALL setContainer( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer >& Container ) throw(::com::sun::star::uno::RuntimeException); ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer > SAL_CALL getContainer( ) throw(::com::sun::star::uno::RuntimeException); ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl > > SAL_CALL getControls( ) throw(::com::sun::star::uno::RuntimeException); void SAL_CALL autoTabOrder( ) throw(::com::sun::star::uno::RuntimeException); void SAL_CALL activateTabOrder( ) throw(::com::sun::star::uno::RuntimeException); void SAL_CALL activateFirst( ) throw(::com::sun::star::uno::RuntimeException); void SAL_CALL activateLast( ) throw(::com::sun::star::uno::RuntimeException); // XServiceInfo DECLIMPL_SERVICEINFO( StdTabController, szServiceName2_TabController ) }; #endif // _TOOLKIT_AWT_STDTABCONTROLLER_HXX_
1,810
337
<filename>idea/testData/refactoring/rename/renameKotlinPropertyWithGetterJvmNameToDefaultByGetterRef/before/test/JavaClient.java package test; class Test { { new A()./*rename*/getFoo(); new A().setFirst(1); } }
99
1,333
package org.xujin.moss.client.endpoint.dependency.analyzer; import java.io.Serializable; import java.util.List; public class PomInfo implements Serializable { public String groupId; public String artifactId; public String version; public String location; public long size; public List<PomDependency> dependencies; public String getArtifactId() { return artifactId; } public List<PomDependency> getDependencies() { return dependencies; } public String getGroupId() { return groupId; } public String getLocation() { return location; } public long getSize() { return size; } public String getVersion() { return version; } public void setArtifactId(String artifactId) { this.artifactId = artifactId; } public void setDependencies(List<PomDependency> dependencies) { this.dependencies = dependencies; } public void setGroupId(String groupId) { this.groupId = groupId; } public void setLocation(String location) { this.location = location; } public void setSize(long size) { this.size = size; } public void setVersion(String version) { this.version = version; } }
491
3,102
<gh_stars>1000+ #ifndef SETJMP_H #define SETJMP_H typedef struct { int x[42]; } jmp_buf; #endif
51
335
/* Copyright (C) 2018 Quaternion Risk Management Ltd All rights reserved. This file is part of ORE, a free-software/open-source library for transparent pricing and risk analysis - http://opensourcerisk.org ORE is free software: you can redistribute it and/or modify it under the terms of the Modified BSD License. You should have received a copy of the license along with this program. The license is also available online at <http://opensourcerisk.org> This program is distributed on the basis that it will form a useful contribution to risk analytics and model standardisation, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ /*! \file qle/indexes/equityindex.hpp \brief equity index class for holding equity fixing histories and forwarding. \ingroup indexes */ #ifndef quantext_equityindex_hpp #define quantext_equityindex_hpp #include <ql/currency.hpp> #include <ql/handle.hpp> #include <ql/termstructures/yieldtermstructure.hpp> #include <ql/time/calendar.hpp> #include <ql/currency.hpp> #include <qle/indexes/eqfxindexbase.hpp> namespace QuantExt { using namespace QuantLib; //! Equity Index /*! \ingroup indexes */ class EquityIndex : public EqFxIndexBase { public: /*! spot quote is interpreted as of today */ EquityIndex(const std::string& familyName, const Calendar& fixingCalendar, const Currency& currency, const Handle<Quote> spotQuote = Handle<Quote>(), const Handle<YieldTermStructure>& rate = Handle<YieldTermStructure>(), const Handle<YieldTermStructure>& dividend = Handle<YieldTermStructure>()); //! \name Index interface //@{ std::string name() const; void resetName() { name_ = familyName(); } std::string dividendName() const { return name() + "_div"; } Currency currency() const { return currency_; } Calendar fixingCalendar() const; bool isValidFixingDate(const Date& fixingDate) const; // Equity fixing price - can be either fixed hstorical or forecasted. // Forecasted price can include dividend returns by setting incDividend = true Real fixing(const Date& fixingDate, bool forecastTodaysFixing = false) const; Real fixing(const Date& fixingDate, bool forecastTodaysFixing, bool incDividend) const; // Dividend Fixings //! stores the historical dividend fixing at the given date /*! the date passed as arguments must be the actual calendar date of the fixing; no settlement days must be used. */ virtual void addDividend(const Date& fixingDate, Real fixing, bool forceOverwrite = false); virtual const TimeSeries<Real>& dividendFixings() const { return IndexManager::instance().getHistory(dividendName()); } Real dividendsBetweenDates(const Date& startDate, const Date& endDate) const; //@} //! \name Observer interface //@{ void update(); //@} //! \name Inspectors //@{ std::string familyName() const { return familyName_; } const Handle<Quote>& equitySpot() const { return spotQuote_; } const Handle<YieldTermStructure>& equityForecastCurve() const { return rate_; } const Handle<YieldTermStructure>& equityDividendCurve() const { return dividend_; } //@} //! \name Fixing calculations //@{ virtual Real forecastFixing(const Date& fixingDate) const; virtual Real forecastFixing(const Time& fixingTime) const; virtual Real forecastFixing(const Date& fixingDate, bool incDividend) const; virtual Real forecastFixing(const Time& fixingTime, bool incDividend) const; virtual Real pastFixing(const Date& fixingDate) const; // @} //! \name Additional methods //@{ virtual boost::shared_ptr<EquityIndex> clone(const Handle<Quote> spotQuote, const Handle<YieldTermStructure>& rate, const Handle<YieldTermStructure>& dividend) const; // @} protected: std::string familyName_; Currency currency_; const Handle<YieldTermStructure> rate_, dividend_; std::string name_; const Handle<Quote> spotQuote_; private: Calendar fixingCalendar_; }; // inline definitions inline std::string EquityIndex::name() const { return name_; } inline Calendar EquityIndex::fixingCalendar() const { return fixingCalendar_; } inline bool EquityIndex::isValidFixingDate(const Date& d) const { return fixingCalendar().isBusinessDay(d); } inline void EquityIndex::update() { notifyObservers(); } inline Real EquityIndex::pastFixing(const Date& fixingDate) const { QL_REQUIRE(isValidFixingDate(fixingDate), fixingDate << " is not a valid fixing date"); return timeSeries()[fixingDate]; } } // namespace QuantExt #endif
1,530
6,304
/* * Copyright 2020 Google LLC. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "src/gpu/ops/AtlasInstancedHelper.h" #include "src/gpu/BufferWriter.h" #include "src/gpu/KeyBuilder.h" #include "src/gpu/glsl/GrGLSLFragmentShaderBuilder.h" #include "src/gpu/glsl/GrGLSLVarying.h" #include "src/gpu/glsl/GrGLSLVertexGeoBuilder.h" namespace skgpu::v1 { void AtlasInstancedHelper::getKeyBits(KeyBuilder* b) const { b->addBits(kNumShaderFlags, (int)fShaderFlags, "atlasFlags"); } void AtlasInstancedHelper::appendInstanceAttribs( SkTArray<GrGeometryProcessor::Attribute>* instanceAttribs) const { instanceAttribs->emplace_back("locations", kFloat4_GrVertexAttribType, kFloat4_GrSLType); if (fShaderFlags & ShaderFlags::kCheckBounds) { instanceAttribs->emplace_back("sizeInAtlas", kFloat2_GrVertexAttribType, kFloat2_GrSLType); } } void AtlasInstancedHelper::writeInstanceData(VertexWriter* instanceWriter, const Instance* i) const { SkASSERT(i->fLocationInAtlas.x() >= 0); SkASSERT(i->fLocationInAtlas.y() >= 0); *instanceWriter << // A negative x coordinate in the atlas indicates that the path is transposed. // Also add 1 since we can't negate zero. ((float)(i->fTransposedInAtlas ? -i->fLocationInAtlas.x() - 1 : i->fLocationInAtlas.x() + 1)) << (float)i->fLocationInAtlas.y() << (float)i->fPathDevIBounds.left() << (float)i->fPathDevIBounds.top() << VertexWriter::If(fShaderFlags & ShaderFlags::kCheckBounds, SkSize::Make(i->fPathDevIBounds.size())); } void AtlasInstancedHelper::injectShaderCode( const GrGeometryProcessor::ProgramImpl::EmitArgs& args, const GrShaderVar& devCoord, GrGLSLUniformHandler::UniformHandle* atlasAdjustUniformHandle) const { GrGLSLVarying atlasCoord(kFloat2_GrSLType); args.fVaryingHandler->addVarying("atlasCoord", &atlasCoord); const char* atlasAdjustName; *atlasAdjustUniformHandle = args.fUniformHandler->addUniform( nullptr, kVertex_GrShaderFlag, kFloat2_GrSLType, "atlas_adjust", &atlasAdjustName); args.fVertBuilder->codeAppendf(R"( // A negative x coordinate in the atlas indicates that the path is transposed. // We also added 1 since we can't negate zero. float2 atlasTopLeft = float2(abs(locations.x) - 1, locations.y); float2 devTopLeft = locations.zw; bool transposed = locations.x < 0; float2 atlasCoord = %s - devTopLeft; if (transposed) { atlasCoord = atlasCoord.yx; } atlasCoord += atlasTopLeft; %s = atlasCoord * %s;)", devCoord.c_str(), atlasCoord.vsOut(), atlasAdjustName); if (fShaderFlags & ShaderFlags::kCheckBounds) { GrGLSLVarying atlasBounds(kFloat4_GrSLType); args.fVaryingHandler->addVarying("atlasbounds", &atlasBounds, GrGLSLVaryingHandler::Interpolation::kCanBeFlat); args.fVertBuilder->codeAppendf(R"( float4 atlasBounds = atlasTopLeft.xyxy + (transposed ? sizeInAtlas.00yx : sizeInAtlas.00xy); %s = atlasBounds * %s.xyxy;)", atlasBounds.vsOut(), atlasAdjustName); args.fFragBuilder->codeAppendf(R"( half atlasCoverage = 0; float2 atlasCoord = %s; float4 atlasBounds = %s; if (all(greaterThan(atlasCoord, atlasBounds.xy)) && all(lessThan(atlasCoord, atlasBounds.zw))) { atlasCoverage = )", atlasCoord.fsIn(), atlasBounds.fsIn()); args.fFragBuilder->appendTextureLookup(args.fTexSamplers[0], "atlasCoord"); args.fFragBuilder->codeAppendf(R"(.a; })"); } else { args.fFragBuilder->codeAppendf("half atlasCoverage = "); args.fFragBuilder->appendTextureLookup(args.fTexSamplers[0], atlasCoord.fsIn()); args.fFragBuilder->codeAppendf(".a;"); } if (fShaderFlags & ShaderFlags::kInvertCoverage) { args.fFragBuilder->codeAppendf("%s *= (1 - atlasCoverage);", args.fOutputCoverage); } else { args.fFragBuilder->codeAppendf("%s *= atlasCoverage;", args.fOutputCoverage); } } void AtlasInstancedHelper::setUniformData( const GrGLSLProgramDataManager& pdman, const GrGLSLUniformHandler::UniformHandle& atlasAdjustUniformHandle) const { SkASSERT(fAtlasProxy->isInstantiated()); SkISize dimensions = fAtlasProxy->backingStoreDimensions(); pdman.set2f(atlasAdjustUniformHandle, 1.f / dimensions.width(), 1.f / dimensions.height()); } } // namespace skgpu::v1
2,093
2,112
/** * Autogenerated by Thrift * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ #include "gen-py3/includes/metadata.h" namespace a { namespace different { namespace ns { ::apache::thrift::metadata::ThriftMetadata includes_getThriftModuleMetadata() { ::apache::thrift::metadata::ThriftServiceMetadataResponse response; ::apache::thrift::metadata::ThriftMetadata& metadata = *response.metadata_ref(); ::apache::thrift::detail::md::EnumMetadata<AnEnum>::gen(metadata); ::apache::thrift::detail::md::StructMetadata<AStruct>::gen(metadata); ::apache::thrift::detail::md::StructMetadata<AStructB>::gen(metadata); return metadata; } } // namespace a } // namespace different } // namespace ns
233
1,043
package com.oath.micro.server.datadog.metrics; import com.oath.micro.server.Plugin; import cyclops.reactive.collections.mutable.SetX; import java.util.Set; /** * * Collections of Spring configuration classes (Classes annotated with @Configuration) * that configure various useful pieces of functionality - such as property file loading, * datasources, scheduling etc * * @author arunbcodes */ public class DatadogMetricsPlugin implements Plugin { @Override public Set<Class> springClasses() { return SetX.of( DatadogMetricsConfigurer.class); } }
179
1,056
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.mercurial.ui.update; import java.io.File; import java.util.*; import java.util.concurrent.Callable; import org.netbeans.modules.versioning.spi.VCSContext; import org.netbeans.modules.mercurial.Mercurial; import org.netbeans.modules.mercurial.OutputLogger; import org.netbeans.modules.mercurial.FileStatusCache; import org.netbeans.modules.mercurial.FileInformation; import org.netbeans.modules.mercurial.util.HgUtils; import org.netbeans.modules.mercurial.HgProgressSupport; import org.netbeans.modules.mercurial.HgException; import org.netbeans.modules.mercurial.HgModuleConfig; import org.netbeans.modules.mercurial.ui.actions.ContextAction; import org.netbeans.modules.mercurial.ui.repository.ChangesetPickerPanel; import org.openide.util.RequestProcessor; import org.openide.util.NbBundle; import org.netbeans.modules.mercurial.util.HgCommand; import org.openide.nodes.Node; /** * Reverts local changes. * * @author <NAME> */ public class RevertModificationsAction extends ContextAction { private static final String ICON_RESOURCE = "org/netbeans/modules/mercurial/resources/icons/get_clean.png"; //NOI18N public RevertModificationsAction () { super(ICON_RESOURCE); } @Override protected boolean enable(Node[] nodes) { VCSContext context = HgUtils.getCurrentContext(nodes); Set<File> ctxFiles = context != null? context.getRootFiles(): null; if(!HgUtils.isFromHgRepository(context) || ctxFiles == null || ctxFiles.isEmpty()) { return false; } Set<File> roots = context.getRootFiles(); if(roots == null) return false; for (File root : roots) { FileInformation info = Mercurial.getInstance().getFileStatusCache().getCachedStatus(root); if(info != null && info.getStatus() == FileInformation.STATUS_NOTVERSIONED_NEWLOCALLY) { return false; } } return true; } @Override protected String getBaseName(Node[] nodes) { return "CTL_MenuItem_GetClean"; //NOI18N } @Override protected void performContextAction(Node[] nodes) { VCSContext context = HgUtils.getCurrentContext(nodes); revert(context); } @Override protected String iconResource () { return ICON_RESOURCE; } public static void revert(final VCSContext ctx) { final File files[] = HgUtils.getActionRoots(ctx); if (files == null || files.length == 0) return; final File repository = Mercurial.getInstance().getRepositoryRoot(files[0]); final RevertModifications revertModifications = new RevertModifications(repository, Arrays.asList(files).contains(repository) ? null : files); // this is much faster when getting revisions if (!revertModifications.showDialog()) { return; } final String revStr = revertModifications.getSelectionRevision(); final boolean doBackup = revertModifications.isBackupRequested(); final boolean removeNewFiles = revertModifications.isRemoveNewFilesRequested(); HgModuleConfig.getDefault().setRemoveNewFilesOnRevertModifications(removeNewFiles); HgModuleConfig.getDefault().setBackupOnRevertModifications(doBackup); RequestProcessor rp = Mercurial.getInstance().getRequestProcessor(repository); HgProgressSupport support = new HgProgressSupport() { @Override public void perform() { performRevert(repository, revStr, files, doBackup, removeNewFiles, this.getLogger()); } }; support.start(rp, repository, org.openide.util.NbBundle.getMessage(UpdateAction.class, "MSG_Revert_Progress")); // NOI18N } public static void performRevert(File repository, String revStr, File file, boolean doBackup, OutputLogger logger) { List<File> revertFiles = new ArrayList<File>(); revertFiles.add(file); performRevert(repository, revStr, revertFiles, doBackup, false, logger); } public static void performRevert(File repository, String revStr, File[] files, boolean doBackup, boolean removeNewFiles, OutputLogger logger) { List<File> revertFiles = new ArrayList<File>(); revertFiles.addAll(Arrays.asList(files)); performRevert(repository, revStr, revertFiles, doBackup, removeNewFiles, logger); } public static void performRevert(final File repository, final String revStr, final List<File> revertFiles, final boolean doBackup, final boolean removeNewFiles, final OutputLogger logger) { try{ logger.outputInRed( NbBundle.getMessage(RevertModificationsAction.class, "MSG_REVERT_TITLE")); // NOI18N logger.outputInRed( NbBundle.getMessage(RevertModificationsAction.class, "MSG_REVERT_TITLE_SEP")); // NOI18N // revStr == null => no -r REV in hg revert command // No revisions to revert too if (revStr != null && NbBundle.getMessage(ChangesetPickerPanel.class, "MSG_Revision_Default").startsWith(revStr)) { logger.output( NbBundle.getMessage(RevertModificationsAction.class, "MSG_REVERT_NOTHING")); // NOI18N logger.outputInRed( NbBundle.getMessage(RevertModificationsAction.class, "MSG_REVERT_DONE")); // NOI18N logger.outputInRed(""); // NOI18N return; } // revision with no events - e.g. automatic merge if (revertFiles.isEmpty()) { logger.outputInRed( NbBundle.getMessage(RevertModificationsAction.class, "MSG_REVERT_NOFILES")); // NOI18N logger.outputInRed( NbBundle.getMessage(RevertModificationsAction.class, "MSG_REVERT_DONE")); // NOI18N logger.outputInRed(""); // NOI18N return; } logger.output(revStr == null ? NbBundle.getMessage(RevertModificationsAction.class, "MSG_REVERT_REVISION_PARENT") : NbBundle.getMessage(RevertModificationsAction.class, "MSG_REVERT_REVISION_STR", revStr)); // NOI18N for (File file : revertFiles) { logger.output(file.getAbsolutePath()); } logger.output(""); // NOI18N HgUtils.runWithoutIndexing(new Callable<Void>() { @Override public Void call () throws HgException { HgCommand.doRevert(repository, revertFiles, revStr, doBackup, logger); if (removeNewFiles) { // must exclude nonsharable files/folders purge deletes them because they appear new to hg HgCommand.doPurge(repository, revertFiles, HgUtils.getNotSharablePaths(repository, revertFiles), logger); } FileStatusCache cache = Mercurial.getInstance().getFileStatusCache(); File[] conflictFiles = cache.listFiles(revertFiles.toArray(new File[0]), FileInformation.STATUS_VERSIONED_CONFLICT); if (conflictFiles.length != 0) { ConflictResolvedAction.conflictResolved(repository, conflictFiles); } return null; } }, revertFiles); } catch (HgException.HgCommandCanceledException ex) { // canceled by user, do nothing } catch (HgException ex) { HgUtils.notifyException(ex); } Mercurial.getInstance().getFileStatusCache().refreshAllRoots(Collections.singletonMap(repository, (Set<File>)new HashSet<File>(revertFiles))); logger.outputInRed( NbBundle.getMessage(RevertModificationsAction.class, "MSG_REVERT_DONE")); // NOI18N logger.outputInRed(""); // NOI18N } }
3,836
356
<filename>utils/utils.py ################################################################### # File Name: utils.py # Author: <NAME> # mail: <EMAIL> # Created Time: Tue 28 Aug 2018 04:57:29 PM CST ################################################################### from __future__ import print_function from __future__ import division from __future__ import absolute_import import numpy as np from scipy.sparse import coo_matrix import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt def norm(X): for ix,x in enumerate(X): X[ix]/=np.linalg.norm(x) return X def plot_embedding(X,Y): x_min, x_max = np.min(X,0), np.max(X,0) X = (X - x_min) / (x_max - x_min) plt.figure(figsize=(10,10)) for i in xrange(X.shape[0]): plt.text(X[i,0],X[i,1], str(Y[i]), color=plt.cm.Set1(Y[i]/10.), fontdict={'weight':'bold','size':12}) plt.savefig('a.jpg') EPS = np.finfo(float).eps def contingency_matrix(ref_labels, sys_labels): """Return contingency matrix between ``ref_labels`` and ``sys_labels``.""" ref_classes, ref_class_inds = np.unique(ref_labels, return_inverse=True) sys_classes, sys_class_inds = np.unique(sys_labels, return_inverse=True) n_frames = ref_labels.size # Following works because coo_matrix sums duplicate entries. Is roughly # twice as fast as np.histogram2d. cmatrix = coo_matrix( (np.ones(n_frames), (ref_class_inds, sys_class_inds)), shape=(ref_classes.size, sys_classes.size), dtype=np.int) cmatrix = cmatrix.toarray() return cmatrix, ref_classes, sys_classes def bcubed(ref_labels, sys_labels, cm=None): """Return B-cubed precision, recall, and F1. The B-cubed precision of an item is the proportion of items with its system label that share its reference label (Bagga and Baldwin, 1998). Similarly, the B-cubed recall of an item is the proportion of items with its reference label that share its system label. The overall B-cubed precision and recall, then, are the means of the precision and recall for each item. Parameters ---------- ref_labels : ndarray, (n_frames,) Reference labels. sys_labels : ndarray, (n_frames,) System labels. cm : ndarray, (n_ref_classes, n_sys_classes) Contingency matrix between reference and system labelings. If None, will be computed automatically from ``ref_labels`` and ``sys_labels``. Otherwise, the given value will be used and ``ref_labels`` and ``sys_labels`` ignored. (Default: None) Returns ------- precision : float B-cubed precision. recall : float B-cubed recall. f1 : float B-cubed F1. References ---------- <NAME>. and <NAME>. (1998). "Algorithms for scoring coreference chains." Proceedings of LREC 1998. """ if cm is None: cm, _, _ = contingency_matrix(ref_labels, sys_labels) cm = cm.astype('float64') cm_norm = cm / cm.sum() precision = np.sum(cm_norm * (cm / cm.sum(axis=0))) recall = np.sum(cm_norm * (cm / np.expand_dims(cm.sum(axis=1), 1))) f1 = 2*(precision*recall)/(precision + recall) return precision, recall, f1
1,294
682
/**CFile*********************************************************************** FileName [cuddWindow.c] PackageName [cudd] Synopsis [Functions for variable reordering by window permutation.] Description [Internal procedures included in this module: <ul> <li> cuddWindowReorder() </ul> Static procedures included in this module: <ul> <li> ddWindow2() <li> ddWindowConv2() <li> ddPermuteWindow3() <li> ddWindow3() <li> ddWindowConv3() <li> ddPermuteWindow4() <li> ddWindow4() <li> ddWindowConv4() </ul>] Author [<NAME>] Copyright [Copyright (c) 1995-2004, Regents of the University of Colorado All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the University of Colorado 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.] ******************************************************************************/ #include "misc/util/util_hack.h" #include "cuddInt.h" ABC_NAMESPACE_IMPL_START /*---------------------------------------------------------------------------*/ /* Constant declarations */ /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /* Stucture declarations */ /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /* Type declarations */ /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /* Variable declarations */ /*---------------------------------------------------------------------------*/ #ifndef lint static char rcsid[] DD_UNUSED = "$Id: cuddWindow.c,v 1.14 2009/02/20 02:14:58 fabio Exp $"; #endif #ifdef DD_STATS extern int ddTotalNumberSwapping; extern int ddTotalNISwaps; #endif /*---------------------------------------------------------------------------*/ /* Macro declarations */ /*---------------------------------------------------------------------------*/ /**AutomaticStart*************************************************************/ /*---------------------------------------------------------------------------*/ /* Static function prototypes */ /*---------------------------------------------------------------------------*/ static int ddWindow2 (DdManager *table, int low, int high); static int ddWindowConv2 (DdManager *table, int low, int high); static int ddPermuteWindow3 (DdManager *table, int x); static int ddWindow3 (DdManager *table, int low, int high); static int ddWindowConv3 (DdManager *table, int low, int high); static int ddPermuteWindow4 (DdManager *table, int w); static int ddWindow4 (DdManager *table, int low, int high); static int ddWindowConv4 (DdManager *table, int low, int high); /**AutomaticEnd***************************************************************/ /*---------------------------------------------------------------------------*/ /* Definition of exported functions */ /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /* Definition of internal functions */ /*---------------------------------------------------------------------------*/ /**Function******************************************************************** Synopsis [Reorders by applying the method of the sliding window.] Description [Reorders by applying the method of the sliding window. Tries all possible permutations to the variables in a window that slides from low to high. The size of the window is determined by submethod. Assumes that no dead nodes are present. Returns 1 in case of success; 0 otherwise.] SideEffects [None] ******************************************************************************/ int cuddWindowReorder( DdManager * table /* DD table */, int low /* lowest index to reorder */, int high /* highest index to reorder */, Cudd_ReorderingType submethod /* window reordering option */) { int res; #ifdef DD_DEBUG int supposedOpt; #endif switch (submethod) { case CUDD_REORDER_WINDOW2: res = ddWindow2(table,low,high); break; case CUDD_REORDER_WINDOW3: res = ddWindow3(table,low,high); break; case CUDD_REORDER_WINDOW4: res = ddWindow4(table,low,high); break; case CUDD_REORDER_WINDOW2_CONV: res = ddWindowConv2(table,low,high); break; case CUDD_REORDER_WINDOW3_CONV: res = ddWindowConv3(table,low,high); #ifdef DD_DEBUG supposedOpt = table->keys - table->isolated; res = ddWindow3(table,low,high); if (table->keys - table->isolated != (unsigned) supposedOpt) { (void) fprintf(table->err, "Convergence failed! (%d != %d)\n", table->keys - table->isolated, supposedOpt); } #endif break; case CUDD_REORDER_WINDOW4_CONV: res = ddWindowConv4(table,low,high); #ifdef DD_DEBUG supposedOpt = table->keys - table->isolated; res = ddWindow4(table,low,high); if (table->keys - table->isolated != (unsigned) supposedOpt) { (void) fprintf(table->err,"Convergence failed! (%d != %d)\n", table->keys - table->isolated, supposedOpt); } #endif break; default: return(0); } return(res); } /* end of cuddWindowReorder */ /*---------------------------------------------------------------------------*/ /* Definition of static functions */ /*---------------------------------------------------------------------------*/ /**Function******************************************************************** Synopsis [Reorders by applying a sliding window of width 2.] Description [Reorders by applying a sliding window of width 2. Tries both permutations of the variables in a window that slides from low to high. Assumes that no dead nodes are present. Returns 1 in case of success; 0 otherwise.] SideEffects [None] ******************************************************************************/ static int ddWindow2( DdManager * table, int low, int high) { int x; int res; int size; #ifdef DD_DEBUG assert(low >= 0 && high < table->size); #endif if (high-low < 1) return(0); res = table->keys - table->isolated; for (x = low; x < high; x++) { size = res; res = cuddSwapInPlace(table,x,x+1); if (res == 0) return(0); if (res >= size) { /* no improvement: undo permutation */ res = cuddSwapInPlace(table,x,x+1); if (res == 0) return(0); } #ifdef DD_STATS if (res < size) { (void) fprintf(table->out,"-"); } else { (void) fprintf(table->out,"="); } fflush(table->out); #endif } return(1); } /* end of ddWindow2 */ /**Function******************************************************************** Synopsis [Reorders by repeatedly applying a sliding window of width 2.] Description [Reorders by repeatedly applying a sliding window of width 2. Tries both permutations of the variables in a window that slides from low to high. Assumes that no dead nodes are present. Uses an event-driven approach to determine convergence. Returns 1 in case of success; 0 otherwise.] SideEffects [None] ******************************************************************************/ static int ddWindowConv2( DdManager * table, int low, int high) { int x; int res; int nwin; int newevent; int *events; int size; #ifdef DD_DEBUG assert(low >= 0 && high < table->size); #endif if (high-low < 1) return(ddWindowConv2(table,low,high)); nwin = high-low; events = ABC_ALLOC(int,nwin); if (events == NULL) { table->errorCode = CUDD_MEMORY_OUT; return(0); } for (x=0; x<nwin; x++) { events[x] = 1; } res = table->keys - table->isolated; do { newevent = 0; for (x=0; x<nwin; x++) { if (events[x]) { size = res; res = cuddSwapInPlace(table,x+low,x+low+1); if (res == 0) { ABC_FREE(events); return(0); } if (res >= size) { /* no improvement: undo permutation */ res = cuddSwapInPlace(table,x+low,x+low+1); if (res == 0) { ABC_FREE(events); return(0); } } if (res < size) { if (x < nwin-1) events[x+1] = 1; if (x > 0) events[x-1] = 1; newevent = 1; } events[x] = 0; #ifdef DD_STATS if (res < size) { (void) fprintf(table->out,"-"); } else { (void) fprintf(table->out,"="); } fflush(table->out); #endif } } #ifdef DD_STATS if (newevent) { (void) fprintf(table->out,"|"); fflush(table->out); } #endif } while (newevent); ABC_FREE(events); return(1); } /* end of ddWindowConv3 */ /**Function******************************************************************** Synopsis [Tries all the permutations of the three variables between x and x+2 and retains the best.] Description [Tries all the permutations of the three variables between x and x+2 and retains the best. Assumes that no dead nodes are present. Returns the index of the best permutation (1-6) in case of success; 0 otherwise.Assumes that no dead nodes are present. Returns the index of the best permutation (1-6) in case of success; 0 otherwise.] SideEffects [None] ******************************************************************************/ static int ddPermuteWindow3( DdManager * table, int x) { int y,z; int size,sizeNew; int best; #ifdef DD_DEBUG assert(table->dead == 0); assert(x+2 < table->size); #endif size = table->keys - table->isolated; y = x+1; z = y+1; /* The permutation pattern is: ** (x,y)(y,z) ** repeated three times to get all 3! = 6 permutations. */ #define ABC 1 best = ABC; #define BAC 2 sizeNew = cuddSwapInPlace(table,x,y); if (sizeNew < size) { if (sizeNew == 0) return(0); best = BAC; size = sizeNew; } #define BCA 3 sizeNew = cuddSwapInPlace(table,y,z); if (sizeNew < size) { if (sizeNew == 0) return(0); best = BCA; size = sizeNew; } #define CBA 4 sizeNew = cuddSwapInPlace(table,x,y); if (sizeNew < size) { if (sizeNew == 0) return(0); best = CBA; size = sizeNew; } #define CAB 5 sizeNew = cuddSwapInPlace(table,y,z); if (sizeNew < size) { if (sizeNew == 0) return(0); best = CAB; size = sizeNew; } #define ACB 6 sizeNew = cuddSwapInPlace(table,x,y); if (sizeNew < size) { if (sizeNew == 0) return(0); best = ACB; size = sizeNew; } /* Now take the shortest route to the best permuytation. ** The initial permutation is ACB. */ switch(best) { case BCA: if (!cuddSwapInPlace(table,y,z)) return(0); case CBA: if (!cuddSwapInPlace(table,x,y)) return(0); case ABC: if (!cuddSwapInPlace(table,y,z)) return(0); case ACB: break; case BAC: if (!cuddSwapInPlace(table,y,z)) return(0); case CAB: if (!cuddSwapInPlace(table,x,y)) return(0); break; default: return(0); } #ifdef DD_DEBUG assert(table->keys - table->isolated == (unsigned) size); #endif return(best); } /* end of ddPermuteWindow3 */ /**Function******************************************************************** Synopsis [Reorders by applying a sliding window of width 3.] Description [Reorders by applying a sliding window of width 3. Tries all possible permutations to the variables in a window that slides from low to high. Assumes that no dead nodes are present. Returns 1 in case of success; 0 otherwise.] SideEffects [None] ******************************************************************************/ static int ddWindow3( DdManager * table, int low, int high) { int x; int res; #ifdef DD_DEBUG assert(low >= 0 && high < table->size); #endif if (high-low < 2) return(ddWindow2(table,low,high)); for (x = low; x+1 < high; x++) { res = ddPermuteWindow3(table,x); if (res == 0) return(0); #ifdef DD_STATS if (res == ABC) { (void) fprintf(table->out,"="); } else { (void) fprintf(table->out,"-"); } fflush(table->out); #endif } return(1); } /* end of ddWindow3 */ /**Function******************************************************************** Synopsis [Reorders by repeatedly applying a sliding window of width 3.] Description [Reorders by repeatedly applying a sliding window of width 3. Tries all possible permutations to the variables in a window that slides from low to high. Assumes that no dead nodes are present. Uses an event-driven approach to determine convergence. Returns 1 in case of success; 0 otherwise.] SideEffects [None] ******************************************************************************/ static int ddWindowConv3( DdManager * table, int low, int high) { int x; int res; int nwin; int newevent; int *events; #ifdef DD_DEBUG assert(low >= 0 && high < table->size); #endif if (high-low < 2) return(ddWindowConv2(table,low,high)); nwin = high-low-1; events = ABC_ALLOC(int,nwin); if (events == NULL) { table->errorCode = CUDD_MEMORY_OUT; return(0); } for (x=0; x<nwin; x++) { events[x] = 1; } do { newevent = 0; for (x=0; x<nwin; x++) { if (events[x]) { res = ddPermuteWindow3(table,x+low); switch (res) { case ABC: break; case BAC: if (x < nwin-1) events[x+1] = 1; if (x > 1) events[x-2] = 1; newevent = 1; break; case BCA: case CBA: case CAB: if (x < nwin-2) events[x+2] = 1; if (x < nwin-1) events[x+1] = 1; if (x > 0) events[x-1] = 1; if (x > 1) events[x-2] = 1; newevent = 1; break; case ACB: if (x < nwin-2) events[x+2] = 1; if (x > 0) events[x-1] = 1; newevent = 1; break; default: ABC_FREE(events); return(0); } events[x] = 0; #ifdef DD_STATS if (res == ABC) { (void) fprintf(table->out,"="); } else { (void) fprintf(table->out,"-"); } fflush(table->out); #endif } } #ifdef DD_STATS if (newevent) { (void) fprintf(table->out,"|"); fflush(table->out); } #endif } while (newevent); ABC_FREE(events); return(1); } /* end of ddWindowConv3 */ /**Function******************************************************************** Synopsis [Tries all the permutations of the four variables between w and w+3 and retains the best.] Description [Tries all the permutations of the four variables between w and w+3 and retains the best. Assumes that no dead nodes are present. Returns the index of the best permutation (1-24) in case of success; 0 otherwise.] SideEffects [None] ******************************************************************************/ static int ddPermuteWindow4( DdManager * table, int w) { int x,y,z; int size,sizeNew; int best; #ifdef DD_DEBUG assert(table->dead == 0); assert(w+3 < table->size); #endif size = table->keys - table->isolated; x = w+1; y = x+1; z = y+1; /* The permutation pattern is: * (w,x)(y,z)(w,x)(x,y) * (y,z)(w,x)(y,z)(x,y) * repeated three times to get all 4! = 24 permutations. * This gives a hamiltonian circuit of Cayley's graph. * The codes to the permutation are assigned in topological order. * The permutations at lower distance from the final permutation are * assigned lower codes. This way we can choose, between * permutations that give the same size, one that requires the minimum * number of swaps from the final permutation of the hamiltonian circuit. * There is an exception to this rule: ABCD is given Code 1, to * avoid oscillation when convergence is sought. */ #define ABCD 1 best = ABCD; #define BACD 7 sizeNew = cuddSwapInPlace(table,w,x); if (sizeNew < size) { if (sizeNew == 0) return(0); best = BACD; size = sizeNew; } #define BADC 13 sizeNew = cuddSwapInPlace(table,y,z); if (sizeNew < size) { if (sizeNew == 0) return(0); best = BADC; size = sizeNew; } #define ABDC 8 sizeNew = cuddSwapInPlace(table,w,x); if (sizeNew < size || (sizeNew == size && ABDC < best)) { if (sizeNew == 0) return(0); best = ABDC; size = sizeNew; } #define ADBC 14 sizeNew = cuddSwapInPlace(table,x,y); if (sizeNew < size) { if (sizeNew == 0) return(0); best = ADBC; size = sizeNew; } #define ADCB 9 sizeNew = cuddSwapInPlace(table,y,z); if (sizeNew < size || (sizeNew == size && ADCB < best)) { if (sizeNew == 0) return(0); best = ADCB; size = sizeNew; } #define DACB 15 sizeNew = cuddSwapInPlace(table,w,x); if (sizeNew < size) { if (sizeNew == 0) return(0); best = DACB; size = sizeNew; } #define DABC 20 sizeNew = cuddSwapInPlace(table,y,z); if (sizeNew < size) { if (sizeNew == 0) return(0); best = DABC; size = sizeNew; } #define DBAC 23 sizeNew = cuddSwapInPlace(table,x,y); if (sizeNew < size) { if (sizeNew == 0) return(0); best = DBAC; size = sizeNew; } #define BDAC 19 sizeNew = cuddSwapInPlace(table,w,x); if (sizeNew < size || (sizeNew == size && BDAC < best)) { if (sizeNew == 0) return(0); best = BDAC; size = sizeNew; } #define BDCA 21 sizeNew = cuddSwapInPlace(table,y,z); if (sizeNew < size || (sizeNew == size && BDCA < best)) { if (sizeNew == 0) return(0); best = BDCA; size = sizeNew; } #define DBCA 24 sizeNew = cuddSwapInPlace(table,w,x); if (sizeNew < size) { if (sizeNew == 0) return(0); best = DBCA; size = sizeNew; } #define DCBA 22 sizeNew = cuddSwapInPlace(table,x,y); if (sizeNew < size || (sizeNew == size && DCBA < best)) { if (sizeNew == 0) return(0); best = DCBA; size = sizeNew; } #define DCAB 18 sizeNew = cuddSwapInPlace(table,y,z); if (sizeNew < size || (sizeNew == size && DCAB < best)) { if (sizeNew == 0) return(0); best = DCAB; size = sizeNew; } #define CDAB 12 sizeNew = cuddSwapInPlace(table,w,x); if (sizeNew < size || (sizeNew == size && CDAB < best)) { if (sizeNew == 0) return(0); best = CDAB; size = sizeNew; } #define CDBA 17 sizeNew = cuddSwapInPlace(table,y,z); if (sizeNew < size || (sizeNew == size && CDBA < best)) { if (sizeNew == 0) return(0); best = CDBA; size = sizeNew; } #define CBDA 11 sizeNew = cuddSwapInPlace(table,x,y); if (sizeNew < size || (sizeNew == size && CBDA < best)) { if (sizeNew == 0) return(0); best = CBDA; size = sizeNew; } #define BCDA 16 sizeNew = cuddSwapInPlace(table,w,x); if (sizeNew < size || (sizeNew == size && BCDA < best)) { if (sizeNew == 0) return(0); best = BCDA; size = sizeNew; } #define BCAD 10 sizeNew = cuddSwapInPlace(table,y,z); if (sizeNew < size || (sizeNew == size && BCAD < best)) { if (sizeNew == 0) return(0); best = BCAD; size = sizeNew; } #define CBAD 5 sizeNew = cuddSwapInPlace(table,w,x); if (sizeNew < size || (sizeNew == size && CBAD < best)) { if (sizeNew == 0) return(0); best = CBAD; size = sizeNew; } #define CABD 3 sizeNew = cuddSwapInPlace(table,x,y); if (sizeNew < size || (sizeNew == size && CABD < best)) { if (sizeNew == 0) return(0); best = CABD; size = sizeNew; } #define CADB 6 sizeNew = cuddSwapInPlace(table,y,z); if (sizeNew < size || (sizeNew == size && CADB < best)) { if (sizeNew == 0) return(0); best = CADB; size = sizeNew; } #define ACDB 4 sizeNew = cuddSwapInPlace(table,w,x); if (sizeNew < size || (sizeNew == size && ACDB < best)) { if (sizeNew == 0) return(0); best = ACDB; size = sizeNew; } #define ACBD 2 sizeNew = cuddSwapInPlace(table,y,z); if (sizeNew < size || (sizeNew == size && ACBD < best)) { if (sizeNew == 0) return(0); best = ACBD; size = sizeNew; } /* Now take the shortest route to the best permutation. ** The initial permutation is ACBD. */ switch(best) { case DBCA: if (!cuddSwapInPlace(table,y,z)) return(0); case BDCA: if (!cuddSwapInPlace(table,x,y)) return(0); case CDBA: if (!cuddSwapInPlace(table,w,x)) return(0); case ADBC: if (!cuddSwapInPlace(table,y,z)) return(0); case ABDC: if (!cuddSwapInPlace(table,x,y)) return(0); case ACDB: if (!cuddSwapInPlace(table,y,z)) return(0); case ACBD: break; case DCBA: if (!cuddSwapInPlace(table,y,z)) return(0); case BCDA: if (!cuddSwapInPlace(table,x,y)) return(0); case CBDA: if (!cuddSwapInPlace(table,w,x)) return(0); if (!cuddSwapInPlace(table,x,y)) return(0); if (!cuddSwapInPlace(table,y,z)) return(0); break; case DBAC: if (!cuddSwapInPlace(table,x,y)) return(0); case DCAB: if (!cuddSwapInPlace(table,w,x)) return(0); case DACB: if (!cuddSwapInPlace(table,y,z)) return(0); case BACD: if (!cuddSwapInPlace(table,x,y)) return(0); case CABD: if (!cuddSwapInPlace(table,w,x)) return(0); break; case DABC: if (!cuddSwapInPlace(table,y,z)) return(0); case BADC: if (!cuddSwapInPlace(table,x,y)) return(0); case CADB: if (!cuddSwapInPlace(table,w,x)) return(0); if (!cuddSwapInPlace(table,y,z)) return(0); break; case BDAC: if (!cuddSwapInPlace(table,x,y)) return(0); case CDAB: if (!cuddSwapInPlace(table,w,x)) return(0); case ADCB: if (!cuddSwapInPlace(table,y,z)) return(0); case ABCD: if (!cuddSwapInPlace(table,x,y)) return(0); break; case BCAD: if (!cuddSwapInPlace(table,x,y)) return(0); case CBAD: if (!cuddSwapInPlace(table,w,x)) return(0); if (!cuddSwapInPlace(table,x,y)) return(0); break; default: return(0); } #ifdef DD_DEBUG assert(table->keys - table->isolated == (unsigned) size); #endif return(best); } /* end of ddPermuteWindow4 */ /**Function******************************************************************** Synopsis [Reorders by applying a sliding window of width 4.] Description [Reorders by applying a sliding window of width 4. Tries all possible permutations to the variables in a window that slides from low to high. Assumes that no dead nodes are present. Returns 1 in case of success; 0 otherwise.] SideEffects [None] ******************************************************************************/ static int ddWindow4( DdManager * table, int low, int high) { int w; int res; #ifdef DD_DEBUG assert(low >= 0 && high < table->size); #endif if (high-low < 3) return(ddWindow3(table,low,high)); for (w = low; w+2 < high; w++) { res = ddPermuteWindow4(table,w); if (res == 0) return(0); #ifdef DD_STATS if (res == ABCD) { (void) fprintf(table->out,"="); } else { (void) fprintf(table->out,"-"); } fflush(table->out); #endif } return(1); } /* end of ddWindow4 */ /**Function******************************************************************** Synopsis [Reorders by repeatedly applying a sliding window of width 4.] Description [Reorders by repeatedly applying a sliding window of width 4. Tries all possible permutations to the variables in a window that slides from low to high. Assumes that no dead nodes are present. Uses an event-driven approach to determine convergence. Returns 1 in case of success; 0 otherwise.] SideEffects [None] ******************************************************************************/ static int ddWindowConv4( DdManager * table, int low, int high) { int x; int res; int nwin; int newevent; int *events; #ifdef DD_DEBUG assert(low >= 0 && high < table->size); #endif if (high-low < 3) return(ddWindowConv3(table,low,high)); nwin = high-low-2; events = ABC_ALLOC(int,nwin); if (events == NULL) { table->errorCode = CUDD_MEMORY_OUT; return(0); } for (x=0; x<nwin; x++) { events[x] = 1; } do { newevent = 0; for (x=0; x<nwin; x++) { if (events[x]) { res = ddPermuteWindow4(table,x+low); switch (res) { case ABCD: break; case BACD: if (x < nwin-1) events[x+1] = 1; if (x > 2) events[x-3] = 1; newevent = 1; break; case BADC: if (x < nwin-3) events[x+3] = 1; if (x < nwin-1) events[x+1] = 1; if (x > 0) events[x-1] = 1; if (x > 2) events[x-3] = 1; newevent = 1; break; case ABDC: if (x < nwin-3) events[x+3] = 1; if (x > 0) events[x-1] = 1; newevent = 1; break; case ADBC: case ADCB: case ACDB: if (x < nwin-3) events[x+3] = 1; if (x < nwin-2) events[x+2] = 1; if (x > 0) events[x-1] = 1; if (x > 1) events[x-2] = 1; newevent = 1; break; case DACB: case DABC: case DBAC: case BDAC: case BDCA: case DBCA: case DCBA: case DCAB: case CDAB: case CDBA: case CBDA: case BCDA: case CADB: if (x < nwin-3) events[x+3] = 1; if (x < nwin-2) events[x+2] = 1; if (x < nwin-1) events[x+1] = 1; if (x > 0) events[x-1] = 1; if (x > 1) events[x-2] = 1; if (x > 2) events[x-3] = 1; newevent = 1; break; case BCAD: case CBAD: case CABD: if (x < nwin-2) events[x+2] = 1; if (x < nwin-1) events[x+1] = 1; if (x > 1) events[x-2] = 1; if (x > 2) events[x-3] = 1; newevent = 1; break; case ACBD: if (x < nwin-2) events[x+2] = 1; if (x > 1) events[x-2] = 1; newevent = 1; break; default: ABC_FREE(events); return(0); } events[x] = 0; #ifdef DD_STATS if (res == ABCD) { (void) fprintf(table->out,"="); } else { (void) fprintf(table->out,"-"); } fflush(table->out); #endif } } #ifdef DD_STATS if (newevent) { (void) fprintf(table->out,"|"); fflush(table->out); } #endif } while (newevent); ABC_FREE(events); return(1); } /* end of ddWindowConv4 */ ABC_NAMESPACE_IMPL_END
14,052
1,477
<reponame>jaxesn/eks-anywhere<filename>pkg/executables/testdata/kubectl_eksa_cluster.json { "apiVersion": "anywhere.eks.amazonaws.com/v1alpha1", "kind": "Cluster", "metadata": { "annotations": { "anywhere.eks.amazonaws.com/paused": "true", "kubectl.kubernetes.io/last-applied-configuration": "{\"apiVersion\":\"anywhere.eks.amazonaws.com/v1alpha1\",\"kind\":\"Cluster\",\"metadata\":{\"annotations\":{\"anywhere.eks.amazonaws.com/paused\":\"true\"},\"creationTimestamp\":\"2021-07-14T22:40:54Z\",\"generation\":1,\"managedFields\":[{\"apiVersion\":\"anywhere.eks.amazonaws.com/v1alpha1\",\"fieldsType\":\"FieldsV1\",\"fieldsV1\":{\"f:metadata\":{\"f:annotations\":{\".\":{},\"f:kubectl.kubernetes.io/last-applied-configuration\":{}}},\"f:spec\":{\".\":{},\"f:controlPlaneReplicas\":{},\"f:infrastructureRef\":{\".\":{},\"f:apiVersion\":{},\"f:kind\":{},\"f:name\":{}},\"f:kubernetesVersion\":{},\"f:workerNodeReplicas\":{}},\"f:status\":{}},\"manager\":\"kubectl-client-side-apply\",\"operation\":\"Update\",\"time\":\"2021-07-14T22:40:54Z\"}],\"name\":\"sigb\",\"namespace\":\"default\",\"resourceVersion\":\"4373\",\"selfLink\":\"/apis/anywhere.eks.amazonaws.com/v1alpha1/namespaces/default/clusters/sigb\",\"uid\":\"260ba2f7-1307-449a-8a8c-00abcdc946b9\"},\"spec\":{\"controlPlaneReplicas\":3,\"infrastructureRef\":{\"apiVersion\":\"anywhere.eks.amazonaws.com/v1alpha1\",\"kind\":\"VSphereDatacenter\",\"name\":\"sigb\"},\"kubernetesVersion\":\"1.19\",\"workerNodeReplicas\":3},\"status\":{}}\n" }, "creationTimestamp": "2021-07-14T22:40:54Z", "generation": 1, "managedFields": [ { "apiVersion": "anywhere.eks.amazonaws.com/v1alpha1", "fieldsType": "FieldsV1", "fieldsV1": { "f:metadata": { "f:annotations": { ".": {}, "f:anywhere.eks.amazonaws.com/paused": {}, "f:kubectl.kubernetes.io/last-applied-configuration": {} } }, "f:spec": { ".": {}, "f:controlPlaneReplicas": {}, "f:infrastructureRef": { ".": {}, "f:apiVersion": {}, "f:kind": {}, "f:name": {} }, "f:kubernetesVersion": {}, "f:workerNodeReplicas": {} }, "f:status": {} }, "manager": "kubectl-client-side-apply", "operation": "Update", "time": "2021-07-14T22:44:08Z" } ], "name": "test-cluster", "namespace": "default", "resourceVersion": "6333", "selfLink": "/apis/anywhere.eks.amazonaws.com/v1alpha1/namespaces/default/clusters/test-cluster", "uid": "260ba2f7-1307-449a-8a8c-00abcdc946b9" }, "spec": { "controlPlaneConfiguration": { "count": 3 }, "datacenterRef": { "kind": "VSphereDatacenterConfig", "name": "test-cluster" }, "kubernetesVersion": "1.19", "workerNodeGroupConfigurations": [{ "count": 3 }] }, "status": {} }
1,446
324
<filename>src/wchar/_towcase.h #ifndef TOWCASE_H__ #define TOWCASE_H__ #include <wctype.h> #ifdef __cplusplus extern "C" { #endif wchar_t __towcase(wchar_t wc, int lower); #ifdef __cplusplus } #endif #endif // TOWCASE_H_
113
4,640
# 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. import numpy as np import tvm from tvm import relay from tvm.relay import op, create_executor, transform from tvm.relay.analysis import Feature from tvm.relay.analysis import detect_feature def run_opt_pass(expr, opt_pass): mod = tvm.IRModule.from_expr(expr) mod = opt_pass(mod) entry = mod["main"] return entry if isinstance(expr, relay.Function) else entry.body def check_eval(expr, args, expected_result, mod=None, rtol=1e-07): if mod is None: mod = tvm.IRModule() dev = tvm.device("llvm", 0) result = create_executor(mod=mod, device=dev, target="llvm").evaluate(expr)(*args) np.testing.assert_allclose(result.numpy(), expected_result, rtol=rtol) def test_implicit_share(): x = relay.Var("x") y = relay.Var("y") z = relay.Var("z") body = relay.Let(z, op.add(y, y), op.add(z, z)) body = relay.Let(y, op.add(x, x), body) f = relay.Function([], relay.Let(x, relay.const(1), body)) g = run_opt_pass(f, transform.ToGraphNormalForm()) assert Feature.fLet in detect_feature(f) assert not Feature.fLet in detect_feature(g) check_eval(f, [], 8.0) check_eval(g, [], 8.0) def test_round_trip(): x = relay.Var("x") y = relay.Var("y") z = relay.Var("z") body = relay.Let(z, op.add(y, y), op.add(z, z)) body = relay.Let(y, op.add(x, x), body) f = relay.Function([], relay.Let(x, relay.const(1), body)) g = run_opt_pass(f, transform.ToGraphNormalForm()) h = run_opt_pass(g, transform.ToANormalForm()) assert Feature.fLet in detect_feature(f) assert not Feature.fLet in detect_feature(g) check_eval(f, [], 8.0) check_eval(g, [], 8.0) check_eval(h, [], 8.0) if __name__ == "__main__": test_implicit_share() test_round_trip()
935
2,400
<filename>optaplanner-examples/src/main/java/org/optaplanner/examples/batchscheduling/domain/Batch.java package org.optaplanner.examples.batchscheduling.domain; import java.util.List; import org.optaplanner.examples.common.domain.AbstractPersistable; import com.thoughtworks.xstream.annotations.XStreamAlias; @XStreamAlias("PipeBatch") public class Batch extends AbstractPersistable { private List<RoutePath> routePathList; private String name; private Double volume; private Long delayRangeValue; public String getName() { return name; } public void setName(String name) { this.name = name; } public Double getVolume() { return volume; } public void setVolume(Double volume) { this.volume = volume; } public List<RoutePath> getRoutePathList() { return routePathList; } public void setRoutePathList(List<RoutePath> routePathList) { this.routePathList = routePathList; } public Long getDelayRangeValue() { return delayRangeValue; } public void setDelayRangeValue(Long delayRangeValue) { this.delayRangeValue = delayRangeValue; } }
440
2,151
<filename>src/cpp/server/load_reporter/load_reporting_service_server_builder_option.cc /* * * Copyright 2018 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <grpc/support/port_platform.h> #include <grpcpp/ext/server_load_reporting.h> #include "src/cpp/server/load_reporter/load_reporting_service_server_builder_plugin.h" namespace grpc { namespace load_reporter { namespace experimental { void LoadReportingServiceServerBuilderOption::UpdateArguments( ::grpc::ChannelArguments* args) { args->SetInt(GRPC_ARG_ENABLE_LOAD_REPORTING, true); } void LoadReportingServiceServerBuilderOption::UpdatePlugins( std::vector<std::unique_ptr<::grpc::ServerBuilderPlugin>>* plugins) { plugins->emplace_back(new LoadReportingServiceServerBuilderPlugin()); } } // namespace experimental } // namespace load_reporter } // namespace grpc
409
751
/* SPDX-License-Identifier: Apache-2.0 * Copyright(c) 2021 Cisco Systems, Inc. */ #ifndef __DAQ_VPP_H__ #define __DAQ_VPP_H__ #include <stdint.h> #define DAQ_VPP_DEFAULT_SOCKET_FILE "snort.sock" #define DAQ_VPP_DEFAULT_SOCKET_PATH "/run/vpp/" DAQ_VPP_DEFAULT_SOCKET_FILE #define DAQ_VPP_INST_NAME_LEN 32 typedef enum memif_msg_type { DAQ_VPP_MSG_TYPE_NONE = 0, DAQ_VPP_MSG_TYPE_HELLO = 1, DAQ_VPP_MSG_TYPE_CONFIG = 2, DAQ_VPP_MSG_TYPE_BPOOL = 3, DAQ_VPP_MSG_TYPE_QPAIR = 4, } daq_vpp_msg_type_t; typedef struct { char inst_name[DAQ_VPP_INST_NAME_LEN]; } daq_vpp_msg_hello_t; typedef struct { uint32_t shm_size; uint16_t num_bpools; uint16_t num_qpairs; } daq_vpp_msg_config_t; typedef struct { uint32_t size; } daq_vpp_msg_bpool_t; typedef struct { uint8_t log2_queue_size; uint32_t desc_table_offset; uint32_t enq_head_offset; uint32_t deq_head_offset; uint32_t enq_ring_offset; uint32_t deq_ring_offset; } daq_vpp_msg_qpair_t; typedef struct { daq_vpp_msg_type_t type : 8; union { daq_vpp_msg_hello_t hello; daq_vpp_msg_config_t config; daq_vpp_msg_bpool_t bpool; daq_vpp_msg_qpair_t qpair; }; } daq_vpp_msg_t; typedef enum { DAQ_VPP_ACTION_DROP, DAQ_VPP_ACTION_FORWARD, } daq_vpp_action_t; typedef struct { uint32_t offset; uint16_t length; uint16_t address_space_id; uint8_t buffer_pool; daq_vpp_action_t action : 8; } daq_vpp_desc_t; #endif /* __DAQ_VPP_H__ */
747
2,107
/*- * BSD LICENSE * * Copyright (c) Intel Corporation. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Intel Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef __SGL_INTERNAL_H__ #define __SGL_INTERNAL_H__ #include "spdk/stdinc.h" #ifdef __cplusplus extern "C" { #endif struct spdk_iov_sgl { struct iovec *iov; int iovcnt; uint32_t iov_offset; uint32_t total_size; }; /** * Initialize struct spdk_iov_sgl with iov, iovcnt and iov_offset. * * \param s the spdk_iov_sgl to be filled. * \param iov the io vector to fill the s * \param iovcnt the size the iov * \param iov_offset the current filled iov_offset for s. */ static inline void spdk_iov_sgl_init(struct spdk_iov_sgl *s, struct iovec *iov, int iovcnt, uint32_t iov_offset) { s->iov = iov; s->iovcnt = iovcnt; s->iov_offset = iov_offset; s->total_size = 0; } /** * Consume the iovs in spdk_iov_sgl with passed bytes * * \param s the spdk_iov_sgl which contains the iov * \param step the bytes_size consumed. */ static inline void spdk_iov_sgl_advance(struct spdk_iov_sgl *s, uint32_t step) { s->iov_offset += step; while (s->iovcnt > 0) { assert(s->iov != NULL); if (s->iov_offset < s->iov->iov_len) { break; } s->iov_offset -= s->iov->iov_len; s->iov++; s->iovcnt--; } } /** * Append the data to the struct spdk_iov_sgl pointed by s * * \param s the address of the struct spdk_iov_sgl * \param data the data buffer to be appended * \param data_len the length of the data. * * \return true if all the data is appended. */ static inline bool spdk_iov_sgl_append(struct spdk_iov_sgl *s, uint8_t *data, uint32_t data_len) { if (s->iov_offset >= data_len) { s->iov_offset -= data_len; } else { assert(s->iovcnt > 0); s->iov->iov_base = data + s->iov_offset; s->iov->iov_len = data_len - s->iov_offset; s->total_size += data_len - s->iov_offset; s->iov_offset = 0; s->iov++; s->iovcnt--; if (s->iovcnt == 0) { return false; } } return true; } #ifdef __cplusplus } #endif #endif /* __SGL_INTERNAL_H__ */
1,364
312
<filename>3rd_party/occa/tests/src/internal/lang/modes/openmp.cpp #define OCCA_TEST_PARSER_TYPE okl::openmpParser #include <occa/internal/lang/modes/openmp.hpp> #include "../parserUtils.hpp" void testPragma(); void testAtomic(); int main(const int argc, const char **argv) { parser.settings["okl/validate"] = false; parser.settings["serial/include_std"] = false; testPragma(); testAtomic(); return 0; } #define ASSERT_PRAGMA_EXISTS(PRAGMA_SOURCE, COUNT) \ do { \ statementArray pragmaStatements = ( \ parser.root.children \ .flatFilterByStatementType(statementType::pragma) \ ); \ \ ASSERT_EQ(COUNT, \ (int) pragmaStatements.length()); \ \ pragmaStatement &ompPragma = pragmaStatements[0]->to<pragmaStatement>(); \ ASSERT_EQ(PRAGMA_SOURCE, \ ompPragma.value()); \ } while(0) //---[ Pragma ]------------------------- void testPragma() { // @outer -> #pragma omp parseSource( "@kernel void foo() {\n" " for (;;; @outer) {}\n" "}" ); ASSERT_PRAGMA_EXISTS("omp parallel for", 1); } //====================================== //---[ @atomic ]------------------------ void testAtomic() { parseSource( "int i;\n" "@atomic i += 1;\n" ); ASSERT_PRAGMA_EXISTS("omp atomic", 1); parseSource( "@atomic i < 1;\n" ); ASSERT_PRAGMA_EXISTS("omp critical", 1); parseSource( "int i;\n" "@atomic {\n" " i += 1;\n" "}\n" ); ASSERT_PRAGMA_EXISTS("omp atomic", 1); parseSource( "int i;\n" "@atomic {\n" " i += 1;\n" " i += 1;\n" "}\n" ); ASSERT_PRAGMA_EXISTS("omp critical", 1); } //======================================
1,262
1,011
#ifndef __BinaryFileReaderWriter_H__ #define __BinaryFileReaderWriter_H__ #include <iostream> #include <fstream> #include "SPlisHSPlasH/Common.h" #include <Eigen/Sparse> namespace SPH { class BinaryFileWriter { public: std::ofstream m_file; public: bool openFile(const std::string &fileName) { m_file.open(fileName, std::ios::out | std::ios::binary); if (!m_file.is_open()) { std::cout << "Cannot open file.\n"; return false; } return true; } void closeFile() { m_file.close(); } void writeBuffer(const char *buffer, size_t size) { m_file.write(buffer, size); } template<typename T> void write(const T &v) { writeBuffer((char*)&v, sizeof(T)); } void write(const std::string &str) { write((unsigned int) str.size()); writeBuffer(str.c_str(), str.size()); } template<typename T> void writeMatrix(const T &m) { writeBuffer((char*)m.data(), m.size() * sizeof(m.data()[0])); } template<typename T, int Rows, int Cols> void writeMatrixX(const Eigen::Matrix < T, Rows, Cols> & m) { const Eigen::Index rows = m.rows(); const Eigen::Index cols = m.cols(); write(rows); write(cols); writeBuffer((char*)m.data(), rows * cols* sizeof(T)); } template <typename T, int Options, typename StorageIndex> void writeSparseMatrix(Eigen::SparseMatrix<T, Options, StorageIndex>& m) { m.makeCompressed(); const Eigen::Index rows = m.rows(); const Eigen::Index cols = m.cols(); const Eigen::Index nnzs = m.nonZeros(); const Eigen::Index outS = m.outerSize(); const Eigen::Index innS = m.innerSize(); write(rows); write(cols); write(nnzs); write(outS); write(innS); writeBuffer((const char*)(m.valuePtr()), sizeof(T) * nnzs); writeBuffer((const char*)(m.outerIndexPtr()), sizeof(StorageIndex) * outS); writeBuffer((const char*)(m.innerIndexPtr()), sizeof(StorageIndex) * nnzs); } template<typename T> void writeVector(const std::vector<T>& m) { write(m.size()); writeBuffer((char*)m.data(), m.size() * sizeof(T)); } }; class BinaryFileReader { public: std::ifstream m_file; public: bool openFile(const std::string &fileName) { m_file.open(fileName, std::ios::in | std::ios::binary); if (!m_file.is_open()) { std::cout << "Cannot open file.\n"; return false; } return true; } void closeFile() { m_file.close(); } void readBuffer(char *buffer, size_t size) { m_file.read(buffer, size); } template<typename T> void read(T &v) { readBuffer((char*)&v, sizeof(T)); } void read(std::string &str) { unsigned int len; read(len); char* temp = new char[len + 1u]; readBuffer(temp, len); temp[len] = '\0'; str = temp; } template<typename T> void readMatrix(T &m) { readBuffer((char*)m.data(), m.size() * sizeof(m.data()[0])); } template<typename T, int Rows, int Cols> void readMatrixX(Eigen::Matrix < T, Rows, Cols>& m) { Eigen::Index rows, cols; read(rows); read(cols); m.resize(rows, cols); readBuffer((char*)m.data(), rows * cols * sizeof(T)); } template <typename T, int Options, typename StorageIndex> void readSparseMatrix(Eigen::SparseMatrix<T, Options, StorageIndex>& m) { Eigen::Index rows, cols, nnzs, innS, outS; read(rows); read(cols); read(nnzs); read(outS); read(innS); m.resize(rows, cols); m.makeCompressed(); m.resizeNonZeros(nnzs); readBuffer((char*)(m.valuePtr()), sizeof(T) * nnzs); readBuffer((char*)(m.outerIndexPtr()), sizeof(StorageIndex) * outS); readBuffer((char*)(m.innerIndexPtr()), sizeof(StorageIndex) * nnzs); m.finalize(); } template<typename T> void readVector(std::vector<T>& m) { size_t size; read(size); m.resize(size); readBuffer((char*)m.data(), m.size() * sizeof(T)); } }; } #endif
1,742
399
<gh_stars>100-1000 package ioio.tests.torture; import ioio.lib.api.IOIO; import ioio.lib.api.IOIO.VersionType; import ioio.lib.util.BaseIOIOLooper; import ioio.lib.util.IOIOLooper; import ioio.lib.util.android.IOIOActivity; import ioio.tests.torture.ResourceAllocator.Board; import android.content.Context; import android.os.Bundle; import android.os.PowerManager; import android.util.Log; import android.widget.TextView; public class MainActivity extends IOIOActivity { private static final String TAG = "IOIO:TortureTest"; private PowerManager.WakeLock wakeLock_; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); wakeLock_ = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, TAG); } @Override protected IOIOLooper createIOIOLooper() { return new Looper(); } class Looper extends BaseIOIOLooper { private final TestThread[] workers_ = new TestThread[8]; @Override protected void setup() { wakeLock_.acquire(10*60*1000L /*10 minutes*/); ResourceAllocator alloc_ = new ResourceAllocator(Board.valueOf(ioio_ .getImplVersion(IOIO.VersionType.HARDWARE_VER))); TestProvider provider = new TestProvider(MainActivity.this, ioio_, alloc_); showVersions(); for (int i = 0; i < workers_.length; ++i) { workers_[i] = new TestThread(provider, "Test-" + i); workers_[i].start(); } } @Override public void loop() { } @Override public void disconnected() { Log.i(TAG, "IOIO disconnected, killing workers"); for (TestThread testThread : workers_) { if (testThread != null) { testThread.abort(); } } try { for (TestThread testThread : workers_) { if (testThread != null) { testThread.join(); } } Log.i(TAG, "All workers dead"); } catch (InterruptedException e) { Log.w(TAG, "Interrupted. Some workers may linger."); } wakeLock_.release(); } @Override public void incompatible() { Log.e(TAG, "Incompatibility detected"); } private void showVersions() { final String versionText = "hw: " + ioio_.getImplVersion(VersionType.HARDWARE_VER) + "\n" + "bl: " + ioio_.getImplVersion(VersionType.BOOTLOADER_VER) + "\n" + "fw: " + ioio_.getImplVersion(VersionType.APP_FIRMWARE_VER) + "\n" + "lib: " + ioio_.getImplVersion(VersionType.IOIOLIB_VER); runOnUiThread(new Runnable() { @Override public void run() { ((TextView) findViewById(R.id.versions)).setText(versionText); } }); } } }
1,551
5,249
#!/usr/bin/env python3 # # Copyright (c) 2021, NVIDIA CORPORATION. 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. # """ This script loads the TensorRT engine built by `build_and_run.py` and runs inference. """ import numpy as np from polygraphy.backend.common import BytesFromPath from polygraphy.backend.trt import EngineFromBytes, TrtRunner def main(): # Just as we did when building, we can compose multiple loaders together # to achieve the behavior we want. Specifically, we want to load a serialized # engine from a file, then deserialize it into a TensorRT engine. load_engine = EngineFromBytes(BytesFromPath("identity.engine")) # Inference remains virtually exactly the same as before: with TrtRunner(load_engine) as runner: inp_data = np.ones(shape=(1, 1, 2, 2), dtype=np.float32) # NOTE: The runner owns the output buffers and is free to reuse them between `infer()` calls. # Thus, if you want to store results from multiple inferences, you should use `copy.deepcopy()`. outputs = runner.infer(feed_dict={"x": inp_data}) assert np.array_equal(outputs["y"], inp_data) # It's an identity model! print("Inference succeeded!") if __name__ == "__main__": main()
552
1,350
<reponame>Manny27nyc/azure-sdk-for-java // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.synapse.generated; import com.azure.core.util.Context; import com.azure.resourcemanager.synapse.models.RecommendedSensitivityLabelUpdate; import com.azure.resourcemanager.synapse.models.RecommendedSensitivityLabelUpdateKind; import com.azure.resourcemanager.synapse.models.RecommendedSensitivityLabelUpdateList; import java.util.Arrays; /** Samples for SqlPoolRecommendedSensitivityLabels Update. */ public final class SqlPoolRecommendedSensitivityLabelsUpdateSamples { /* * x-ms-original-file: specification/synapse/resource-manager/Microsoft.Synapse/stable/2021-06-01/examples/SensitivityLabelsRecommendedUpdate.json */ /** * Sample code: Update recommended sensitivity labels of a given SQL Pool using an operations batch. * * @param manager Entry point to SynapseManager. */ public static void updateRecommendedSensitivityLabelsOfAGivenSQLPoolUsingAnOperationsBatch( com.azure.resourcemanager.synapse.SynapseManager manager) { manager .sqlPoolRecommendedSensitivityLabels() .updateWithResponse( "myRG", "myWorkspace", "mySqlPool", new RecommendedSensitivityLabelUpdateList() .withOperations( Arrays .asList( new RecommendedSensitivityLabelUpdate() .withOp(RecommendedSensitivityLabelUpdateKind.ENABLE) .withSchema("dbo") .withTable("table1") .withColumn("column1"), new RecommendedSensitivityLabelUpdate() .withOp(RecommendedSensitivityLabelUpdateKind.ENABLE) .withSchema("dbo") .withTable("table2") .withColumn("column2"), new RecommendedSensitivityLabelUpdate() .withOp(RecommendedSensitivityLabelUpdateKind.DISABLE) .withSchema("dbo") .withTable("table1") .withColumn("column3"))), Context.NONE); } }
1,261
3,102
// RUN: %clang_cc1 -std=c++11 %s -verify // expected-no-diagnostics constexpr int operator "" _a(const char *c) { return c[0]; } static_assert(operator "" _a("foo") == 'f', ""); void puts(const char *); static inline void operator "" _puts(const char *c) { puts(c); } void f() { operator "" _puts("foo"); operator "" _puts("bar"); }
133
879
<gh_stars>100-1000 package org.zstack.sdk; import org.zstack.sdk.MdevDeviceType; import org.zstack.sdk.MdevDeviceState; import org.zstack.sdk.MdevDeviceStatus; import org.zstack.sdk.MdevDeviceChooser; public class MdevDeviceInventory { public java.lang.String uuid; public void setUuid(java.lang.String uuid) { this.uuid = uuid; } public java.lang.String getUuid() { return this.uuid; } public java.lang.String name; public void setName(java.lang.String name) { this.name = name; } public java.lang.String getName() { return this.name; } public java.lang.String description; public void setDescription(java.lang.String description) { this.description = description; } public java.lang.String getDescription() { return this.description; } public java.lang.String parentUuid; public void setParentUuid(java.lang.String parentUuid) { this.parentUuid = parentUuid; } public java.lang.String getParentUuid() { return this.parentUuid; } public java.lang.String hostUuid; public void setHostUuid(java.lang.String hostUuid) { this.hostUuid = hostUuid; } public java.lang.String getHostUuid() { return this.hostUuid; } public java.lang.String vmInstanceUuid; public void setVmInstanceUuid(java.lang.String vmInstanceUuid) { this.vmInstanceUuid = vmInstanceUuid; } public java.lang.String getVmInstanceUuid() { return this.vmInstanceUuid; } public java.lang.String mdevSpecUuid; public void setMdevSpecUuid(java.lang.String mdevSpecUuid) { this.mdevSpecUuid = mdevSpecUuid; } public java.lang.String getMdevSpecUuid() { return this.mdevSpecUuid; } public MdevDeviceType type; public void setType(MdevDeviceType type) { this.type = type; } public MdevDeviceType getType() { return this.type; } public MdevDeviceState state; public void setState(MdevDeviceState state) { this.state = state; } public MdevDeviceState getState() { return this.state; } public MdevDeviceStatus status; public void setStatus(MdevDeviceStatus status) { this.status = status; } public MdevDeviceStatus getStatus() { return this.status; } public MdevDeviceChooser chooser; public void setChooser(MdevDeviceChooser chooser) { this.chooser = chooser; } public MdevDeviceChooser getChooser() { return this.chooser; } public java.sql.Timestamp createDate; public void setCreateDate(java.sql.Timestamp createDate) { this.createDate = createDate; } public java.sql.Timestamp getCreateDate() { return this.createDate; } public java.sql.Timestamp lastOpDate; public void setLastOpDate(java.sql.Timestamp lastOpDate) { this.lastOpDate = lastOpDate; } public java.sql.Timestamp getLastOpDate() { return this.lastOpDate; } }
1,246
3,189
<gh_stars>1000+ #include "test_common.h" #include <evpp/event_loop.h> #include <evpp/event_loop_thread.h> #include <evpp/dns_resolver.h> TEST_UNIT(testDNSResolver) { for (int i = 0; i < 6; i++) { bool resolved = false; bool deleted = false; auto fn_resolved = [&resolved](const std::vector <struct in_addr>& addrs) { LOG_INFO << "Entering fn_resolved"; resolved = true; }; evpp::Duration delay(double(3.0)); // 3s std::unique_ptr<evpp::EventLoopThread> t(new evpp::EventLoopThread); t->Start(true); std::shared_ptr<evpp::DNSResolver> dns_resolver( new evpp::DNSResolver(t->loop(), "www.so.com", delay, fn_resolved)); dns_resolver->Start(); while (!resolved) { usleep(1); } auto fn_deleter = [&deleted, dns_resolver]() { LOG_INFO << "Entering fn_deleter"; deleted = true; }; t->loop()->QueueInLoop(fn_deleter); dns_resolver.reset(); while (!deleted) { usleep(1); } t->Stop(true); t.reset(); if (evpp::GetActiveEventCount() != 0) { H_TEST_ASSERT(evpp::GetActiveEventCount() == 0); } } } TEST_UNIT(testDNSResolverTimeout) { for (int i = 0; i < 6; i++) { std::atomic<int> resolved(0); bool deleted = false; auto fn_resolved = [&resolved](const std::vector <struct in_addr>& addrs) { LOG_INFO << "Entering fn_resolved addrs.size=" << addrs.size(); resolved.fetch_add(1); }; // 1us to make it timeout immediately evpp::Duration delay(double(0.000001)); std::unique_ptr<evpp::EventLoopThread> t(new evpp::EventLoopThread); t->Start(true); auto loop = t->loop(); std::shared_ptr<evpp::DNSResolver> dns_resolver( new evpp::DNSResolver(loop, "wwwwwww.en.cppreference.com", delay, fn_resolved)); dns_resolver->Start(); while (!resolved) { usleep(1); } auto fn_deleter = [&deleted, dns_resolver]() { LOG_INFO << "Entering fn_deleter"; deleted = true; }; loop->QueueInLoop(fn_deleter); dns_resolver.reset(); while (!deleted) { usleep(1); } loop->RunAfter(evpp::Duration(0.05), [loop]() { loop->Stop(); }); while (!t->IsStopped()) { usleep(1); } t.reset(); assert(resolved.load() == 1); if (evpp::GetActiveEventCount() != 0) { H_TEST_ASSERT(evpp::GetActiveEventCount() == 0); } } }
1,459
422
<reponame>anama25/LearnJava<filename>Lesson-19/Examples/CashRegisterDrawer/src/cashregisterdrawer/DrawerStatus.java package cashregisterdrawer; public enum DrawerStatus { Open, Closed, Unknown }
69
631
package com.neu.his.cloud.api.pc.dto.sms; import lombok.Getter; import lombok.Setter; import lombok.ToString; import java.io.Serializable; import java.math.BigDecimal; import java.util.List; @Setter @Getter @ToString public class SmsDeptAmountStatisticsResult implements Serializable { List<String> dateOfSevenDays; List<String> amountCat; List<BigDecimal> medicineAmount; List<BigDecimal> herbalAmount; List<BigDecimal> checkAmount; List<BigDecimal> testAmount; List<BigDecimal> dispositionAmount; List<BigDecimal> executedAmount; }
209
1,975
// Copyright 2009 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ======================================================================== #ifndef OMAHA_GOOPDATE_APP_STATE_ERROR_H_ #define OMAHA_GOOPDATE_APP_STATE_ERROR_H_ #include "base/basictypes.h" #include "omaha/goopdate/app_state.h" namespace omaha { namespace fsm { // The error state is idempotent. Further transitions from error state into // itself are allowed but have no effect. Therefore, the first error wins. One // scenario where this occurs is canceling the app. Canceling the app is not // blocking and it moves the app in the error state right away. The Error // method is called a second time, as the actual cancel code executes in the // thread pool. class AppStateError : public AppState { public: AppStateError(); virtual ~AppStateError() {} virtual const PingEvent* CreatePingEvent(App* app, CurrentState previous_state) const; // These calls are legal in this state but do nothing. This can occur when // this app has encountered an error but bundle is still being processed. // For instance, when cancelling a bundle during a download, the applications // transition right away in the error state. The cancel event is handled at // some point in the future. Depending on a race condition, the downloads may // have succeeded or failed due to the cancellation. The race condition is // resolved when the transition call reaches this object and the call is // ignored. virtual void DownloadComplete(App* app); virtual void MarkReadyToInstall(App* app); // These calls are legal in this state but do nothing. This can occur when // this app has encountered an error or has been canceled but bundle is still // being processed. virtual void PreUpdateCheck(App* app, xml::UpdateRequest* update_request); virtual void PostUpdateCheck(App* app, HRESULT result, xml::UpdateResponse* update_response); virtual void QueueDownload(App* app); virtual void QueueDownloadOrInstall(App* app); virtual void Download(App* app, DownloadManagerInterface* download_manager); virtual void QueueInstall(App* app); virtual void Install(App* app, InstallManagerInterface* install_manager); // Canceling while in a terminal state has no effect. virtual void Cancel(App* app); virtual void Error(App* app, const ErrorContext& error_context, const CString& message); private: DISALLOW_COPY_AND_ASSIGN(AppStateError); }; } // namespace fsm } // namespace omaha #endif // OMAHA_GOOPDATE_APP_STATE_ERROR_H_
952
868
# Copyright The OpenTelemetry 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. import sys import threading import unittest from functools import partial from typing import Callable, List, Optional, TypeVar from unittest.mock import Mock ReturnT = TypeVar("ReturnT") class MockFunc: """A thread safe mock function Use this as part of your mock if you want to count calls across multiple threads. """ def __init__(self) -> None: self.lock = threading.Lock() self.call_count = 0 self.mock = Mock() def __call__(self, *args, **kwargs): with self.lock: self.call_count += 1 return self.mock class ConcurrencyTestBase(unittest.TestCase): """Test base class/mixin for tests of concurrent code This test class calls ``sys.setswitchinterval(1e-12)`` to try to create more contention while running tests that use many threads. It also provides ``run_with_many_threads`` to run some test code in many threads concurrently. """ orig_switch_interval = sys.getswitchinterval() @classmethod def setUpClass(cls) -> None: super().setUpClass() # switch threads more often to increase chance of contention sys.setswitchinterval(1e-12) @classmethod def tearDownClass(cls) -> None: super().tearDownClass() sys.setswitchinterval(cls.orig_switch_interval) @staticmethod def run_with_many_threads( func_to_test: Callable[[], ReturnT], num_threads: int = 100, ) -> List[ReturnT]: """Util to run ``func_to_test`` in ``num_threads`` concurrently""" barrier = threading.Barrier(num_threads) results: List[Optional[ReturnT]] = [None] * num_threads def thread_start(idx: int) -> None: nonlocal results # Get all threads here before releasing them to create contention barrier.wait() results[idx] = func_to_test() threads = [ threading.Thread(target=partial(thread_start, i)) for i in range(num_threads) ] for thread in threads: thread.start() for thread in threads: thread.join() return results # type: ignore
1,023
2,151
<reponame>zipated/src # -*- coding: utf-8 -*- # Copyright 2015 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Module containing SDK builders.""" from __future__ import print_function import datetime from chromite.lib import constants from chromite.cbuildbot.builders import simple_builders from chromite.cbuildbot.stages import android_stages from chromite.cbuildbot.stages import artifact_stages from chromite.cbuildbot.stages import build_stages from chromite.cbuildbot.stages import chrome_stages from chromite.cbuildbot.stages import sdk_stages class ChrootSdkBuilder(simple_builders.SimpleBuilder): """Build the SDK chroot.""" def RunStages(self): """Runs through build process.""" # Unlike normal CrOS builds, the SDK has no concept of pinned CrOS manifest # or specific Chrome version. Use a datestamp instead. version = datetime.datetime.now().strftime('%Y.%m.%d.%H%M%S') self._RunStage(build_stages.UprevStage, boards=[]) self._RunStage(build_stages.InitSDKStage) self._RunStage(build_stages.SetupBoardStage, constants.CHROOT_BUILDER_BOARD) self._RunStage(chrome_stages.SyncChromeStage) self._RunStage(android_stages.UprevAndroidStage) self._RunStage(sdk_stages.SDKBuildToolchainsStage) self._RunStage(sdk_stages.SDKPackageStage, version=version) # Note: This produces badly named toolchain tarballs. Before # we re-enable it, make sure we fix that first. For example: # gs://chromiumos-sdk/2015/06/... # .../cros-sdk-overlay-toolchains-aarch64-cros-linux-gnu-$VER.tar.xz #self._RunStage(sdk_stages.SDKPackageToolchainOverlaysStage, # version=version) self._RunStage(sdk_stages.SDKTestStage) # manojgupta: The comment in para below is not valid right now. Need to # test SDK before making artifacts available to users because of # https://crbug.com/798617. # Move it after UploadPrebuilts again once the bug is fixed. # # Upload artifacts before tests. Testing takes several hours, so during # that, goma server will find the new archive and stage it. So that, # goma can be used on bots just after uprev. # TODO(hidehiko): We may want to run upload prebuilts and test in # parallel in future, if it becomes performance bottleneck. self._RunStage(artifact_stages.UploadPrebuiltsStage, constants.CHROOT_BUILDER_BOARD, version=version) self._RunStage(sdk_stages.SDKUprevStage, version=version)
889
72,551
<reponame>gandhi56/swift //===--- ARCRegionState.h ---------------------------------------*- C++ -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #ifndef SWIFT_SILOPTIMIZER_PASSMANAGER_ARC_ARCREGIONSTATE_H #define SWIFT_SILOPTIMIZER_PASSMANAGER_ARC_ARCREGIONSTATE_H #include "GlobalLoopARCSequenceDataflow.h" #include "swift/Basic/NullablePtr.h" namespace swift { class LoopRegion; class LoopRegionFunctionInfo; class AliasAnalysis; class RCIdentityFunctionInfo; /// Per-Region state. class ARCRegionState { public: // TODO: These are relatively expensive, find something else to use here. using TopDownMapTy = SmallBlotMapVector<SILValue, TopDownRefCountState, 4>; using BottomUpMapTy = SmallBlotMapVector<SILValue, BottomUpRefCountState, 4>; private: /// The region that this ARCRegionState summarizes information for. /// /// The only time that the pointer is null is during initialization. Using /// NullablePtr is just a convenient way to make sure that we assert if we /// attempt to use Region during initialization before the pointer is set. NullablePtr<LoopRegion> Region; /// The top-down traversal uses this to record information known about a /// pointer at the bottom of each block. TopDownMapTy PtrToTopDownState; /// The bottom-up traversal uses this to record information known about a /// pointer at the top of each block. BottomUpMapTy PtrToBottomUpState; /// Is this a region from which we can leak ARC values? /// /// If we know that the program has entered a state from which it is /// guaranteed to terminate soon, in our model we allow for all memory to be /// leaked since the operating system will soon reclaim the memory. We take /// advantage of this to ignore control flow. bool AllowsLeaks; /// A list of instructions contained in this region that can either use or /// decrement reference counts. /// /// This is flow insensitive since we just add all of the potential /// users/decrements in subregions without caring if there is only one along a /// path. This is for simplicity in the first iteration. /// /// TODO: This needs a better name. llvm::SmallVector<SILInstruction *, 4> SummarizedInterestingInsts; public: ARCRegionState(LoopRegion *R, bool AllowsLeaks); /// Is this Region from which we can leak memory safely? bool allowsLeaks() const { return AllowsLeaks; } /// Return the region associated with this ARCRegionState. /// /// Even though Region is a NullablePtr, it is only null during /// initialization. This method should not be called then. const LoopRegion *getRegion() const { return Region.get(); } LoopRegion *getRegion() { return Region.get(); } /// Top Down Iterators using topdown_iterator = TopDownMapTy::iterator; using topdown_const_iterator = TopDownMapTy::const_iterator; topdown_iterator topdown_begin() { return PtrToTopDownState.begin(); } topdown_iterator topdown_end() { return PtrToTopDownState.end(); } topdown_const_iterator topdown_begin() const { return PtrToTopDownState.begin(); } topdown_const_iterator topdown_end() const { return PtrToTopDownState.end(); } iterator_range<topdown_iterator> getTopDownStates() { return make_range(topdown_begin(), topdown_end()); } /// Bottom up iteration. using bottomup_iterator = BottomUpMapTy::iterator; using bottomup_const_iterator = BottomUpMapTy::const_iterator; bottomup_iterator bottomup_begin() { return PtrToBottomUpState.begin(); } bottomup_iterator bottomup_end() { return PtrToBottomUpState.end(); } bottomup_const_iterator bottomup_begin() const { return PtrToBottomUpState.begin(); } bottomup_const_iterator bottomup_end() const { return PtrToBottomUpState.end(); } iterator_range<bottomup_iterator> getBottomupStates() { return make_range(bottomup_begin(), bottomup_end()); } /// Attempt to find the PtrState object describing the top down state for /// pointer Arg. Return a new initialized PtrState describing the top down /// state for Arg if we do not find one. TopDownRefCountState &getTopDownRefCountState(SILValue Ptr) { return PtrToTopDownState[Ptr]; } /// Attempt to find the PtrState object describing the bottom up state for /// pointer Arg. Return a new initialized PtrState describing the bottom up /// state for Arg if we do not find one. BottomUpRefCountState &getBottomUpRefCountState(SILValue Ptr) { return PtrToBottomUpState[Ptr]; } /// Blot \p Ptr. void clearBottomUpRefCountState(SILValue Ptr) { PtrToBottomUpState.erase(Ptr); } /// Blot \p Ptr. void clearTopDownRefCountState(SILValue Ptr) { PtrToTopDownState.erase(Ptr); } void clearTopDownState() { PtrToTopDownState.clear(); } void clearBottomUpState() { PtrToBottomUpState.clear(); } /// Clear both the bottom up *AND* top down state. void clear() { clearTopDownState(); clearBottomUpState(); } using const_reverse_summarizedinterestinginsts_iterator = decltype(SummarizedInterestingInsts)::const_reverse_iterator; const_reverse_summarizedinterestinginsts_iterator summarizedinterestinginsts_rbegin() const { return SummarizedInterestingInsts.rbegin(); } const_reverse_summarizedinterestinginsts_iterator summarizedinterestinginsts_rend() const { return SummarizedInterestingInsts.rend(); } using const_summarizedinterestinginsts_iterator = decltype(SummarizedInterestingInsts)::const_iterator; const_summarizedinterestinginsts_iterator summarizedinterestinginsts_begin() const { return SummarizedInterestingInsts.begin(); } const_summarizedinterestinginsts_iterator summarizedinterestinginsts_end() const { return SummarizedInterestingInsts.end(); } iterator_range<const_summarizedinterestinginsts_iterator> getSummarizedInterestingInsts() const { return {summarizedinterestinginsts_begin(), summarizedinterestinginsts_end()}; } /// Merge in the state of the successor basic block. This is currently a stub. void mergeSuccBottomUp(ARCRegionState &SuccRegion); /// Initialize this Region with the state of the successor basic block. This /// is /// called on a basic block's state and then any other successors states are /// merged in. This is currently a stub. void initSuccBottomUp(ARCRegionState &SuccRegion); /// Merge in the state of the predecessor basic block. This is currently a /// stub. void mergePredTopDown(ARCRegionState &PredRegion); /// Initialize the state for this Region with the state of its predecessor /// Region. Used to create an initial state before we merge in other /// predecessors. This is currently a stub. void initPredTopDown(ARCRegionState &PredRegion); /// If this region is a block, process all instructions top down. Otherwise, /// apply the summarized top down information to the merged top down /// state. Returns true if nested retains were detected while visiting /// instructions. Returns false otherwise. bool processTopDown( AliasAnalysis *AA, RCIdentityFunctionInfo *RCIA, LoopRegionFunctionInfo *LRFI, llvm::DenseSet<SILInstruction *> &UnmatchedRefCountInsts, BlotMapVector<SILInstruction *, TopDownRefCountState> &DecToIncStateMap, llvm::DenseMap<const LoopRegion *, ARCRegionState *> &LoopRegionState, ImmutablePointerSetFactory<SILInstruction> &SetFactory); /// If this region is a block, process all instructions bottom up. Otherwise, /// apply the summarized bottom up information to the merged bottom up /// state. Returns true if nested releases were detected while visiting /// instructions. Returns false otherwise. bool processBottomUp( AliasAnalysis *AA, RCIdentityFunctionInfo *RCIA, EpilogueARCFunctionInfo *EAFI, LoopRegionFunctionInfo *LRFI, bool FreezeOwnedArgEpilogueReleases, llvm::DenseSet<SILInstruction *> &UnmatchedRefCountInsts, BlotMapVector<SILInstruction *, BottomUpRefCountState> &IncToDecStateMap, llvm::DenseMap<const LoopRegion *, ARCRegionState *> &RegionStateInfo, ImmutablePointerSetFactory<SILInstruction> &SetFactory); void summarizeBlock(SILBasicBlock *BB); void summarize( LoopRegionFunctionInfo *LRFI, llvm::DenseMap<const LoopRegion *, ARCRegionState *> &RegionStateInfo); /// Add \p I to the interesting instruction list of this region if it is a /// block. We assume that I is an instruction in the block. void addInterestingInst(SILInstruction *I); /// Remove \p I from the interesting instruction list of this region if it is /// a block. We assume that I is an instruction in the block. void removeInterestingInst(SILInstruction *I); private: bool processBlockBottomUp( const LoopRegion *R, AliasAnalysis *AA, RCIdentityFunctionInfo *RCIA, EpilogueARCFunctionInfo *EAFI, LoopRegionFunctionInfo *LRFI, bool FreezeOwnedArgEpilogueReleases, BlotMapVector<SILInstruction *, BottomUpRefCountState> &IncToDecStateMap, ImmutablePointerSetFactory<SILInstruction> &SetFactory); bool processLoopBottomUp( const LoopRegion *R, AliasAnalysis *AA, LoopRegionFunctionInfo *LRFI, RCIdentityFunctionInfo *RCIA, llvm::DenseMap<const LoopRegion *, ARCRegionState *> &RegionStateInfo, llvm::DenseSet<SILInstruction *> &UnmatchedRefCountInsts); bool processBlockTopDown( SILBasicBlock &BB, AliasAnalysis *AA, RCIdentityFunctionInfo *RCIA, BlotMapVector<SILInstruction *, TopDownRefCountState> &DecToIncStateMap, ImmutablePointerSetFactory<SILInstruction> &SetFactory); bool processLoopTopDown( const LoopRegion *R, ARCRegionState *State, AliasAnalysis *AA, LoopRegionFunctionInfo *LRFI, RCIdentityFunctionInfo *RCIA, llvm::DenseSet<SILInstruction *> &UnmatchedRefCountInsts); void summarizeLoop( const LoopRegion *R, LoopRegionFunctionInfo *LRFI, llvm::DenseMap<const LoopRegion *, ARCRegionState *> &RegionStateInfo); }; } // end swift namespace #endif
3,128
877
// Test case for Issue #2082: // https://github.com/typetools/checker-framework/issues/2082 import java.util.concurrent.Callable; public class Issue2082 { Callable foo = () -> 0; }
64