max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
461
/******************************************************************************* * 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.ofbiz.service; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; import javax.wsdl.Definition; import javax.wsdl.Part; import javax.xml.namespace.QName; import org.apache.ofbiz.base.util.Debug; import org.apache.ofbiz.base.util.ObjectType; import org.apache.ofbiz.base.util.UtilProperties; import org.apache.ofbiz.base.util.UtilValidate; import org.apache.ofbiz.base.util.string.FlexibleStringExpander; /** * Generic Service Model Parameter */ @SuppressWarnings("serial") public class ModelParam implements Serializable { private static final String MODULE = ModelParam.class.getName(); /** Parameter name */ private String name; /** The description of this parameter */ private String description; /** Paramater type */ private String type; /** Parameter mode (IN/OUT/INOUT) */ private String mode; /** The form label */ private String formLabel; /** The entity name */ private String entityName; /** The entity field name */ private String fieldName; /** Request attribute to look for if not defined as a parameter */ private String requestAttributeName; /** Session attribute to look for if not defined as a parameter */ private String sessionAttributeName; /** Parameter prefix for creating an attribute Map */ private String stringMapPrefix; /** Parameter suffix for creating an attribute List */ private String stringListSuffix; /** Validation methods */ private List<ModelParamValidator> validators; /** Default value */ private FlexibleStringExpander defaultValue = null; /** Is this Parameter required or optional? Default to false, or required */ private boolean optional = false; private boolean overrideOptional = false; /** Is this parameter to be displayed via the form tool? */ private boolean formDisplay = true; private boolean overrideFormDisplay = false; /** Default value */ private String allowHtml = null; /** Is this Parameter set internally? */ private boolean internal = false; /** Children attributes*/ private ArrayList<ModelParam> children = null; public ModelParam() { } public ModelParam(ModelParam param) { this.name = param.name; this.description = param.description; this.type = param.type; this.mode = param.mode; this.formLabel = param.formLabel; this.entityName = param.entityName; this.fieldName = param.fieldName; this.requestAttributeName = param.requestAttributeName; this.sessionAttributeName = param.sessionAttributeName; this.stringMapPrefix = param.stringMapPrefix; this.stringListSuffix = param.stringListSuffix; this.validators = param.validators; if (param.defaultValue != null) { this.setDefaultValue(param.defaultValue.getOriginal()); } this.optional = param.optional; this.overrideOptional = param.overrideOptional; this.formDisplay = param.formDisplay; this.overrideFormDisplay = param.overrideFormDisplay; this.allowHtml = param.allowHtml; this.internal = param.internal; } /** * Add validator. * @param className the class name * @param methodName the method name * @param failMessage the fail message */ public void addValidator(String className, String methodName, String failMessage) { validators.add(new ModelParamValidator(className, methodName, failMessage, null, null)); } /** * Add validator. * @param className the class name * @param methodName the method name * @param failResource the fail resource * @param failProperty the fail property */ public void addValidator(String className, String methodName, String failResource, String failProperty) { validators.add(new ModelParamValidator(className, methodName, null, failResource, failProperty)); } /** * Gets primary fail message. * @param locale the locale * @return the primary fail message */ public String getPrimaryFailMessage(Locale locale) { if (UtilValidate.isNotEmpty(validators)) { return validators.get(0).getFailMessage(locale); } return null; } /** * Gets short display description. * @return the short display description */ public String getShortDisplayDescription() { return this.name + "[" + this.type + "-" + this.mode + "]" + (optional ? "" : "*"); } /** * Gets name. * @return the name */ public String getName() { return this.name; } /** * Sets mode. * @param mode the mode */ public void setMode(String mode) { this.mode = mode; } /** * Gets validators. * @return the validators */ public List<ModelParamValidator> getValidators() { return validators; } /** * Sets form display. * @param formDisplay the form display */ public void setFormDisplay(boolean formDisplay) { this.formDisplay = formDisplay; } /** * Sets description. * @param description the description */ public void setDescription(String description) { this.description = description; } /** * Sets override optional. * @param overrideOptional the override optional */ public void setOverrideOptional(boolean overrideOptional) { this.overrideOptional = overrideOptional; } /** * Sets override form display. * @param overrideFormDisplay the override form display */ public void setOverrideFormDisplay(boolean overrideFormDisplay) { this.overrideFormDisplay = overrideFormDisplay; } /** * Sets validators. * @param validators the validators */ public void setValidators(List<ModelParamValidator> validators) { this.validators = validators; } /** * Sets internal. * @param internal the internal */ public void setInternal(boolean internal) { this.internal = internal; } /** * Sets request attribute name. * @param requestAttributeName the request attribute name */ public void setRequestAttributeName(String requestAttributeName) { this.requestAttributeName = requestAttributeName; } /** * Sets session attribute name. * @param sessionAttributeName the session attribute name */ public void setSessionAttributeName(String sessionAttributeName) { this.sessionAttributeName = sessionAttributeName; } /** * Sets string map prefix. * @param stringMapPrefix the string map prefix */ public void setStringMapPrefix(String stringMapPrefix) { this.stringMapPrefix = stringMapPrefix; } /** * Sets string list suffix. * @param stringListSuffix the string list suffix */ public void setStringListSuffix(String stringListSuffix) { this.stringListSuffix = stringListSuffix; } /** * Sets name. * @param name the name */ public void setName(String name) { this.name = name; } /** * Sets allow html. * @param allowHtml the allow html */ public void setAllowHtml(String allowHtml) { this.allowHtml = allowHtml; } /** * Gets allow html. * @return the allow html */ public String getAllowHtml() { return allowHtml; } /** * Gets request attribute name. * @return the request attribute name */ public String getRequestAttributeName() { return requestAttributeName; } /** * Gets session attribute name. * @return the session attribute name */ public String getSessionAttributeName() { return sessionAttributeName; } /** * Is override optional boolean. * @return the boolean */ public boolean isOverrideOptional() { return overrideOptional; } /** * Is form display boolean. * @return the boolean */ public boolean isFormDisplay() { return formDisplay; } /** * Is override form display boolean. * @return the boolean */ public boolean isOverrideFormDisplay() { return overrideFormDisplay; } /** * Sets type. * @param type the type */ public void setType(String type) { this.type = type; } /** * Sets form label. * @param formLabel the form label */ public void setFormLabel(String formLabel) { this.formLabel = formLabel; } /** * Sets entity name. * @param entityName the entity name */ public void setEntityName(String entityName) { this.entityName = entityName; } /** * Sets field name. * @param fieldName the field name */ public void setFieldName(String fieldName) { this.fieldName = fieldName; } /** * Is internal boolean. * @return the boolean */ public boolean isInternal() { return internal; } /** * Sets optional. * @param optional the optional */ public void setOptional(boolean optional) { this.optional = optional; } /** * Gets string map prefix. * @return the string map prefix */ public String getStringMapPrefix() { return stringMapPrefix; } /** * Gets string list suffix. * @return the string list suffix */ public String getStringListSuffix() { return stringListSuffix; } /** * Gets form label. * @return the form label */ // Method to retrieve form-label from model parameter object in freemarker public String getFormLabel() { return this.formLabel; } /** * Gets type. * @return the type */ public String getType() { return this.type; } /** * Gets mode. * @return the mode */ public String getMode() { return this.mode; } /** * Gets entity name. * @return the entity name */ public String getEntityName() { return this.entityName; } /** * Gets field name. * @return the field name */ public String getFieldName() { return this.fieldName; } /** * Gets internal. * @return the internal */ public boolean getInternal() { return this.internal; } /** * Is in boolean. * @return the boolean */ public boolean isIn() { return ModelService.IN_PARAM.equals(this.mode) || ModelService.IN_OUT_PARAM.equals(this.mode); } /** * Is out boolean. * @return the boolean */ public boolean isOut() { return ModelService.OUT_PARAM.equals(this.mode) || ModelService.IN_OUT_PARAM.equals(this.mode); } /** * Is optional boolean. * @return the boolean */ public boolean isOptional() { return this.optional; } /** * Gets default value. * @return the default value */ public FlexibleStringExpander getDefaultValue() { return this.defaultValue; } /** * Gets default value. * @param context the context * @return the default value */ public Object getDefaultValue(Map<String, Object> context) { Object defaultValueObj = null; if (this.type != null) { try { defaultValueObj = ObjectType.simpleTypeOrObjectConvert(this.defaultValue.expandString(context), this.type, null, null, false); } catch (Exception e) { Debug.logWarning(e, "Service attribute [" + name + "] default value could not be converted to type [" + type + "]: " + e.toString(), MODULE); } if (defaultValueObj == null) { // uh-oh, conversion failed, set the String and see what happens defaultValueObj = this.defaultValue; } } else { defaultValueObj = this.defaultValue; } return defaultValueObj; } /** * Sets default value. * @param defaultValue the default value */ public void setDefaultValue(String defaultValue) { this.defaultValue = FlexibleStringExpander.getInstance(defaultValue); if (this.defaultValue != null) { this.optional = true; } if (Debug.verboseOn()) { Debug.logVerbose("Default value for attribute [" + this.name + "] set to [" + this.defaultValue + "]", MODULE); } } /** * @return the children of the attribute */ public ArrayList<ModelParam> getChildren() { if (children == null) { children = new ArrayList<>(); } return children; } /** * Copy default value. * @param param the param */ public void copyDefaultValue(ModelParam param) { this.setDefaultValue(param.defaultValue.getOriginal()); } /** * Equals boolean. * @param model the model * @return the boolean */ public boolean equals(ModelParam model) { return model.name.equals(this.name); } @Override public int hashCode() { return Objects.hash(allowHtml, defaultValue, description, entityName, fieldName, entityName, fieldName, formDisplay, formLabel, internal, mode, name, optional, overrideFormDisplay, overrideOptional, requestAttributeName, stringListSuffix, stringMapPrefix, type, validators); } @Override public boolean equals(Object obj) { if (!(obj instanceof ModelParam)) { return false; } return equals((ModelParam) obj); } @Override public String toString() { StringBuilder buf = new StringBuilder(); buf.append(name).append("::"); buf.append(type).append("::"); buf.append(mode).append("::"); buf.append(formLabel).append("::"); buf.append(entityName).append("::"); buf.append(fieldName).append("::"); buf.append(stringMapPrefix).append("::"); buf.append(stringListSuffix).append("::"); buf.append(optional).append("::"); buf.append(overrideOptional).append("::"); buf.append(formDisplay).append("::"); buf.append(overrideFormDisplay).append("::"); buf.append(allowHtml).append("::"); buf.append(defaultValue).append("::"); buf.append(internal); if (validators != null) { buf.append(validators.toString()).append("::"); } return buf.toString(); } /** * Gets wsdl part. * @param def the def * @return the wsdl part */ public Part getWSDLPart(Definition def) { Part part = def.createPart(); part.setName(this.name); part.setTypeName(new QName(ModelService.TNS, this.java2wsdlType())); return part; } /** * Java 2 wsdl type string. * @return the string */ protected String java2wsdlType() { if (ObjectType.instanceOf(java.lang.Character.class, this.type)) { return "std-String"; } else if (ObjectType.instanceOf(java.lang.String.class, this.type)) { return "std-String"; } else if (ObjectType.instanceOf(java.lang.Byte.class, this.type)) { return "std-String"; } else if (ObjectType.instanceOf(java.lang.Boolean.class, this.type)) { return "std-Boolean"; } else if (ObjectType.instanceOf(java.lang.Integer.class, this.type)) { return "std-Integer"; } else if (ObjectType.instanceOf(java.lang.Double.class, this.type)) { return "std-Double"; } else if (ObjectType.instanceOf(java.lang.Float.class, this.type)) { return "std-Float"; } else if (ObjectType.instanceOf(java.lang.Short.class, this.type)) { return "std-Integer"; } else if (ObjectType.instanceOf(java.math.BigDecimal.class, this.type)) { return "std-Long"; } else if (ObjectType.instanceOf(java.math.BigInteger.class, this.type)) { return "std-Integer"; } else if (ObjectType.instanceOf(java.util.Calendar.class, this.type)) { return "sql-Timestamp"; } else if (ObjectType.instanceOf(com.ibm.icu.util.Calendar.class, this.type)) { return "sql-Timestamp"; } else if (ObjectType.instanceOf(java.sql.Date.class, this.type)) { return "sql-Date"; } else if (ObjectType.instanceOf(java.util.Date.class, this.type)) { return "sql-Timestamp"; } else if (ObjectType.instanceOf(java.lang.Long.class, this.type)) { return "std-Long"; } else if (ObjectType.instanceOf(java.sql.Timestamp.class, this.type)) { return "sql-Timestamp"; } else if (ObjectType.instanceOf(org.apache.ofbiz.entity.GenericValue.class, this.type)) { return "eeval-"; } else if (ObjectType.instanceOf(org.apache.ofbiz.entity.GenericPK.class, this.type)) { return "eepk-"; } else if (ObjectType.instanceOf(java.util.Map.class, this.type)) { return "map-Map"; } else if (ObjectType.instanceOf(java.util.List.class, this.type)) { return "col-LinkedList"; } else { return "cus-obj"; } } static class ModelParamValidator implements Serializable { private String className; private String methodName; private String failMessage; private String failResource; private String failProperty; ModelParamValidator(String className, String methodName, String failMessage, String failResource, String failProperty) { this.className = className; this.methodName = methodName; this.failMessage = failMessage; this.failResource = failResource; this.failProperty = failProperty; } public String getClassName() { return className; } public String getMethodName() { return methodName; } public String getFailMessage(Locale locale) { if (failMessage != null) { return this.failMessage; } if (failResource != null && failProperty != null) { return UtilProperties.getMessage(failResource, failProperty, locale); } return null; } @Override public String toString() { return className + "::" + methodName + "::" + failMessage + "::" + failResource + "::" + failProperty; } } }
7,712
575
<gh_stars>100-1000 // 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 <memory> #include "base/run_loop.h" #include "base/task/thread_pool.h" #include "base/test/bind.h" #include "base/test/task_environment.h" #include "build/build_config.h" #include "chrome/updater/persisted_data.h" #include "chrome/updater/prefs.h" #include "chrome/updater/prefs_impl.h" #include "chrome/updater/registration_data.h" #include "components/prefs/testing_pref_service.h" #include "components/update_client/update_client.h" #include "testing/gtest/include/gtest/gtest.h" namespace updater { TEST(PrefsTest, PrefsCommitPendingWrites) { base::test::TaskEnvironment task_environment( base::test::SingleThreadTaskEnvironment::MainThreadType::UI); auto pref = std::make_unique<TestingPrefServiceSimple>(); update_client::RegisterPrefs(pref->registry()); auto metadata = base::MakeRefCounted<PersistedData>(pref.get()); // Writes something to prefs. metadata->SetBrandCode("someappid", "brand"); EXPECT_STREQ(metadata->GetBrandCode("someappid").c_str(), "brand"); // Tests writing to storage completes. PrefsCommitPendingWrites(pref.get()); } TEST(PrefsTest, AcquireGlobalPrefsLock_LockThenTryLockInThreadFail) { base::test::TaskEnvironment task_environment( base::test::SingleThreadTaskEnvironment::MainThreadType::UI); std::unique_ptr<ScopedPrefsLock> lock = AcquireGlobalPrefsLock(base::TimeDelta::FromSeconds(0)); EXPECT_TRUE(lock); base::RunLoop run_loop; base::ThreadPool::PostTaskAndReplyWithResult( FROM_HERE, base::BindOnce([]() { std::unique_ptr<ScopedPrefsLock> lock = AcquireGlobalPrefsLock(base::TimeDelta::FromSeconds(0)); return lock.get() != nullptr; }), base::OnceCallback<void(bool)>( base::BindLambdaForTesting([&run_loop](bool acquired_lock) { EXPECT_FALSE(acquired_lock); run_loop.Quit(); }))); run_loop.Run(); } TEST(PrefsTest, AcquireGlobalPrefsLock_TryLockInThreadSuccess) { base::test::TaskEnvironment task_environment( base::test::SingleThreadTaskEnvironment::MainThreadType::UI); base::RunLoop run_loop; base::ThreadPool::PostTaskAndReplyWithResult( FROM_HERE, base::BindOnce([]() { std::unique_ptr<ScopedPrefsLock> lock = AcquireGlobalPrefsLock(base::TimeDelta::FromSeconds(0)); return lock.get() != nullptr; }), base::OnceCallback<void(bool)>( base::BindLambdaForTesting([&run_loop](bool acquired_lock) { EXPECT_TRUE(acquired_lock); run_loop.Quit(); }))); run_loop.Run(); auto lock = AcquireGlobalPrefsLock(base::TimeDelta::FromSeconds(0)); EXPECT_TRUE(lock); } } // namespace updater
1,101
1,350
<gh_stars>1000+ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.resourcemanager.sql.implementation; import com.azure.resourcemanager.resources.fluentcore.model.implementation.WrapperImpl; import com.azure.resourcemanager.sql.models.SqlDatabaseImportExportResponse; import com.azure.resourcemanager.sql.fluent.models.ImportExportResponseInner; import java.util.UUID; /** Implementation for SqlDatabaseImportExportResponse. */ public class SqlDatabaseImportExportResponseImpl extends WrapperImpl<ImportExportResponseInner> implements SqlDatabaseImportExportResponse { private String key; protected SqlDatabaseImportExportResponseImpl(ImportExportResponseInner innerObject) { super(innerObject); this.key = UUID.randomUUID().toString(); } @Override public String name() { return this.innerModel().name(); } @Override public String id() { return this.innerModel().id(); } @Override public String requestType() { return this.innerModel().requestType(); } @Override public String requestId() { return this.innerModel().requestId().toString(); } @Override public String serverName() { return this.innerModel().serverName(); } @Override public String databaseName() { return this.innerModel().databaseName(); } @Override public String status() { return this.innerModel().status(); } @Override public String lastModifiedTime() { return this.innerModel().lastModifiedTime(); } @Override public String queuedTime() { return this.innerModel().queuedTime(); } @Override public String blobUri() { return this.innerModel().blobUri(); } @Override public String errorMessage() { return this.innerModel().errorMessage(); } @Override public String key() { return this.key; } }
698
1,694
package org.stagemonitor.alerting.annotation; import com.codahale.metrics.annotation.ExceptionMetered; import com.codahale.metrics.annotation.Timed; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.stagemonitor.alerting.AlertingPlugin; import org.stagemonitor.alerting.check.Check; import org.stagemonitor.alerting.check.CheckResult; import org.stagemonitor.alerting.check.MetricValueType; import org.stagemonitor.alerting.check.Threshold; import org.stagemonitor.alerting.incident.Incident; import org.stagemonitor.core.Stagemonitor; import org.stagemonitor.core.metrics.metrics2.MetricName; import org.stagemonitor.tracing.Traced; import java.util.List; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.stagemonitor.core.metrics.metrics2.MetricName.name; public class SlaCheckCreatingClassPathScannerTest { private final AlertingPlugin alertingPlugin = Stagemonitor.getPlugin(AlertingPlugin.class); private Map<String, Check> checks; private static class SlaTestClass { @SLAs({ @SLA(metric = {MetricValueType.P95, MetricValueType.MAX}, threshold = {0, 0}), @SLA(errorRateThreshold = 0) }) @Traced void monitorSla() { throw null; } @SLA(errorRateThreshold = 0) void monitorRequestsAnnotationMissing() { } @Traced @SLA(metric = {MetricValueType.P95, MetricValueType.MAX}, threshold = 0) void tooFewThresholds() { } @Traced(resolveNameAtRuntime = true) @SLA(metric = {MetricValueType.P95, MetricValueType.MAX}, threshold = {0, 0}) void slaMonitorRequestsResolveAtRuntime() { } @Traced(requestName = "monitor requests custom name") @SLA(metric = {MetricValueType.P95, MetricValueType.MAX}, threshold = {0, 0}) void slaMonitorRequestsCustomName() { } @Timed(name = "timed custom name", absolute = true) @SLA(metric = {MetricValueType.P95, MetricValueType.MAX}, threshold = {0, 0}) void slaTimedCustomName() { } @Timed @SLA(metric = {MetricValueType.P95, MetricValueType.MAX}, threshold = {0, 0}) void slaOnTimed() { } @ExceptionMetered @SLA(errorRateThreshold = 0) void slaOnExceptionMetered() { } @Timed @SLA(errorRateThreshold = 0) void slaMissingExceptionMetered() { } static void makeSureClassIsLoaded() { } } @BeforeClass @AfterClass public static void init() throws Exception { Stagemonitor.init(); SlaTestClass.makeSureClassIsLoaded(); ClassLevelMonitorRequestsTestClass.makeSureClassIsLoaded(); } @Before public void setUp() throws Exception { checks = alertingPlugin.getChecks(); assertThat(alertingPlugin.isInitialized()).isTrue(); assertThat(alertingPlugin.getThresholdMonitoringReporter()).isNotNull(); } @Test public void testSlaMonitorRequests() throws Exception { testErrorRateCheck("void org.stagemonitor.alerting.annotation.SlaCheckCreatingClassPathScannerTest$SlaTestClass.monitorSla().errors", name("error_rate").operationName("Monitor Sla").operationType("method_invocation").build()); testResponseTimeCheck("void org.stagemonitor.alerting.annotation.SlaCheckCreatingClassPathScannerTest$SlaTestClass.monitorSla().responseTime", name("response_time").operationName("Monitor Sla").operationType("method_invocation").build()); } private void testErrorRateCheck(String checkId, MetricName checkTarget) { final Check errorRateCheck = checks.get(checkId); assertNotNull(checks.keySet().toString(), errorRateCheck); assertEquals("Alerting-Test", errorRateCheck.getApplication()); assertEquals(checkTarget, errorRateCheck.getTarget()); } private void testResponseTimeCheck(String checkId, MetricName checkTarget) { final Check responseTimeChek = checks.get(checkId); assertNotNull(checks.keySet().toString(), responseTimeChek); assertEquals("Alerting-Test", responseTimeChek.getApplication()); assertEquals(checkTarget, responseTimeChek.getTarget()); final List<Threshold> thresholds = responseTimeChek.getThresholds(CheckResult.Status.ERROR); final Threshold p95 = thresholds.get(0); assertEquals(MetricValueType.P95, p95.getValueType()); assertEquals(Threshold.Operator.LESS, p95.getOperator()); assertEquals(0, p95.getThresholdValue(), 0); final Threshold max = thresholds.get(1); assertEquals(MetricValueType.MAX, max.getValueType()); assertEquals(Threshold.Operator.LESS, max.getOperator()); assertEquals(0, max.getThresholdValue(), 0); } @Test public void testSlaCustomName() throws Exception { testResponseTimeCheck("void org.stagemonitor.alerting.annotation.SlaCheckCreatingClassPathScannerTest$SlaTestClass.slaMonitorRequestsCustomName().responseTime", name("response_time").operationName("monitor requests custom name").operationType("method_invocation").build()); } @Test public void testTimedCustomName() throws Exception { testResponseTimeCheck("void org.stagemonitor.alerting.annotation.SlaCheckCreatingClassPathScannerTest$SlaTestClass.slaTimedCustomName().responseTime", name("timer").tag("signature", "timed custom name").build()); } @Test public void testSlaTimed() throws Exception { testResponseTimeCheck("void org.stagemonitor.alerting.annotation.SlaCheckCreatingClassPathScannerTest$SlaTestClass.slaOnTimed().responseTime", name("timer").tag("signature", "SlaCheckCreatingClassPathScannerTest$SlaTestClass#slaOnTimed").build()); } @Test public void testSlaExceptionMetered() throws Exception { testErrorRateCheck("void org.stagemonitor.alerting.annotation.SlaCheckCreatingClassPathScannerTest$SlaTestClass.slaOnExceptionMetered().errors", name("exception_rate").tag("signature", "SlaCheckCreatingClassPathScannerTest$SlaTestClass#slaOnExceptionMetered").build()); } @Test public void testSlaMissingExceptionMetered() throws Exception { assertNull(checks.get("void org.stagemonitor.alerting.annotation.SlaCheckCreatingClassPathScannerTest$SlaTestClass.slaMissingExceptionMetered().errors")); } @Test public void testSlaMonitorRequestsResolveAtRuntime() throws Exception { assertNull(checks.get("void org.stagemonitor.alerting.annotation.SlaCheckCreatingClassPathScannerTest$SlaTestClass.slaMonitorRequestsResolveAtRuntime().responseTime")); } @Test public void testSlaMonitorRequestsClassLevel() throws Exception { testResponseTimeCheck("public void org.stagemonitor.alerting.annotation.SlaCheckCreatingClassPathScannerTest$ClassLevelMonitorRequestsTestClass.slaMonitorRequestsClassLevel().responseTime", name("response_time").operationName("Sla Monitor Requests Class Level").operationType("method_invocation").build()); } @Traced private static class ClassLevelMonitorRequestsTestClass { static void makeSureClassIsLoaded() { } @SLA(metric = {MetricValueType.P95, MetricValueType.MAX}, threshold = {0, 0}) public void slaMonitorRequestsClassLevel() { } } @Test public void testTriggersResponseTimeIncident() throws Exception { final String checkId = "void org.stagemonitor.alerting.annotation.SlaCheckCreatingClassPathScannerTest$SlaTestClass.monitorSla().responseTime"; assertThat(checks).containsKey(checkId); try { new SlaTestClass().monitorSla(); } catch (Exception e) { // ignore } assertThat(Stagemonitor.getMetric2Registry().getTimers()).containsKey(name("response_time").operationName("Monitor Sla").operationType("method_invocation").build()); alertingPlugin.getThresholdMonitoringReporter().report(); final Incident incident = alertingPlugin.getIncidentRepository() .getIncidentByCheckId(checkId); assertThat(incident).isNotNull(); } @Test public void testTriggersErrorRateIncident() throws Exception { final String checkId = "void org.stagemonitor.alerting.annotation.SlaCheckCreatingClassPathScannerTest$SlaTestClass.monitorSla().errors"; assertThat(checks).containsKey(checkId); try { new SlaTestClass().monitorSla(); } catch (Exception e) { // ignore } assertThat(Stagemonitor.getMetric2Registry().getMeters()).containsKey(name("error_rate").operationName("Monitor Sla").operationType("method_invocation").build()); alertingPlugin.getThresholdMonitoringReporter().report(); final Incident incident = alertingPlugin.getIncidentRepository() .getIncidentByCheckId(checkId); assertThat(incident).isNotNull(); } }
2,816
2,151
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chrome_content_browser_client.h" #include "base/base_switches.h" #include "base/command_line.h" #include "base/macros.h" #include "base/sys_info.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/search/instant_service.h" #include "chrome/browser/search/instant_service_factory.h" #include "chrome/browser/search/search.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/search/instant_test_base.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/common/chrome_features.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/url_constants.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "components/network_session_configurator/common/network_switches.h" #include "content/public/browser/navigation_controller.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/site_isolation_policy.h" #include "content/public/browser/web_contents.h" #include "content/public/common/content_switches.h" #include "content/public/test/browser_test_utils.h" #include "net/dns/mock_host_resolver.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "url/gurl.h" namespace content { // Use a test class with SetUpCommandLine to ensure the flag is sent to the // first renderer process. class ChromeContentBrowserClientBrowserTest : public InProcessBrowserTest { public: ChromeContentBrowserClientBrowserTest() {} void SetUpCommandLine(base::CommandLine* command_line) override { IsolateAllSitesForTesting(command_line); } private: DISALLOW_COPY_AND_ASSIGN(ChromeContentBrowserClientBrowserTest); }; // Test that a basic navigation works in --site-per-process mode. This prevents // regressions when that mode calls out into the ChromeContentBrowserClient, // such as http://crbug.com/164223. IN_PROC_BROWSER_TEST_F(ChromeContentBrowserClientBrowserTest, SitePerProcessNavigation) { ASSERT_TRUE(embedded_test_server()->Start()); const GURL url(embedded_test_server()->GetURL("/title1.html")); ui_test_utils::NavigateToURL(browser(), url); NavigationEntry* entry = browser() ->tab_strip_model() ->GetWebContentsAt(0) ->GetController() .GetLastCommittedEntry(); ASSERT_TRUE(entry != NULL); EXPECT_EQ(url, entry->GetURL()); EXPECT_EQ(url, entry->GetVirtualURL()); } // Helper class to mark "https://ntp.com/" as an isolated origin. class IsolatedOriginNTPBrowserTest : public InProcessBrowserTest, public InstantTestBase { public: IsolatedOriginNTPBrowserTest() {} void SetUpCommandLine(base::CommandLine* command_line) override { ASSERT_TRUE(https_test_server().InitializeAndListen()); // Mark ntp.com (with an appropriate port from the test server) as an // isolated origin. GURL isolated_url(https_test_server().GetURL("ntp.com", "/")); command_line->AppendSwitchASCII(switches::kIsolateOrigins, isolated_url.spec()); command_line->AppendSwitch(switches::kIgnoreCertificateErrors); } void SetUpOnMainThread() override { InProcessBrowserTest::SetUpOnMainThread(); host_resolver()->AddRule("*", "127.0.0.1"); https_test_server().StartAcceptingConnections(); } private: DISALLOW_COPY_AND_ASSIGN(IsolatedOriginNTPBrowserTest); }; // Verifies that when the remote NTP URL has an origin which is also marked as // an isolated origin (i.e., requiring a dedicated process), the NTP URL // still loads successfully, and the resulting process is marked as an Instant // process. See https://crbug.com/755595. IN_PROC_BROWSER_TEST_F(IsolatedOriginNTPBrowserTest, IsolatedOriginDoesNotInterfereWithNTP) { GURL base_url = https_test_server().GetURL("ntp.com", "/instant_extended.html"); GURL ntp_url = https_test_server().GetURL("ntp.com", "/instant_extended_ntp.html"); InstantTestBase::Init(base_url, ntp_url, false); SetupInstant(browser()); // Sanity check that a SiteInstance for a generic ntp.com URL requires a // dedicated process. content::BrowserContext* context = browser()->profile(); GURL isolated_url(https_test_server().GetURL("ntp.com", "/title1.html")); scoped_refptr<SiteInstance> site_instance = SiteInstance::CreateForURL(context, isolated_url); EXPECT_TRUE(site_instance->RequiresDedicatedProcess()); // The site URL for the NTP URL should resolve to a chrome-search:// URL via // GetEffectiveURL(), even if the NTP URL matches an isolated origin. GURL site_url(content::SiteInstance::GetSiteForURL(context, ntp_url)); EXPECT_TRUE(site_url.SchemeIs(chrome::kChromeSearchScheme)); // Navigate to the NTP URL and verify that the resulting process is marked as // an Instant process. ui_test_utils::NavigateToURL(browser(), ntp_url); content::WebContents* contents = browser()->tab_strip_model()->GetActiveWebContents(); InstantService* instant_service = InstantServiceFactory::GetForProfile(browser()->profile()); EXPECT_TRUE(instant_service->IsInstantProcess( contents->GetMainFrame()->GetProcess()->GetID())); // Navigating to a non-NTP URL on ntp.com should not result in an Instant // process. ui_test_utils::NavigateToURL(browser(), isolated_url); EXPECT_FALSE(instant_service->IsInstantProcess( contents->GetMainFrame()->GetProcess()->GetID())); } // Helper class to mark "https://ntp.com/" as an isolated origin. class SitePerProcessMemoryThresholdBrowserTest : public InProcessBrowserTest { public: SitePerProcessMemoryThresholdBrowserTest() = default; void SetUpCommandLine(base::CommandLine* command_line) override { InProcessBrowserTest::SetUpCommandLine(command_line); // This way the test always sees the same amount of physical memory // (kLowMemoryDeviceThresholdMB = 512MB), regardless of how much memory is // available in the testing environment. command_line->AppendSwitch(switches::kEnableLowEndDeviceMode); EXPECT_EQ(512, base::SysInfo::AmountOfPhysicalMemoryMB()); } // Some command-line switches override field trials - the tests need to be // skipped in this case. bool ShouldSkipBecauseOfConflictingCommandLineSwitches() { if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kSitePerProcess)) return true; if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableSiteIsolationTrials)) return true; return false; } private: DISALLOW_COPY_AND_ASSIGN(SitePerProcessMemoryThresholdBrowserTest); }; IN_PROC_BROWSER_TEST_F(SitePerProcessMemoryThresholdBrowserTest, SitePerProcessEnabled_HighThreshold) { if (ShouldSkipBecauseOfConflictingCommandLineSwitches()) return; // 512MB of physical memory that the test simulates is below the 768MB // threshold. base::test::ScopedFeatureList memory_feature; memory_feature.InitAndEnableFeatureWithParameters( features::kSitePerProcessOnlyForHighMemoryClients, {{features::kSitePerProcessOnlyForHighMemoryClientsParamName, "768"}}); base::test::ScopedFeatureList site_per_process; site_per_process.InitAndEnableFeature(features::kSitePerProcess); // Despite enabled site-per-process trial, there should be no isolation // because the device has too little memory. EXPECT_FALSE( content::SiteIsolationPolicy::UseDedicatedProcessesForAllSites()); } IN_PROC_BROWSER_TEST_F(SitePerProcessMemoryThresholdBrowserTest, SitePerProcessEnabled_LowThreshold) { if (ShouldSkipBecauseOfConflictingCommandLineSwitches()) return; // 512MB of physical memory that the test simulates is above the 128MB // threshold. base::test::ScopedFeatureList memory_feature; memory_feature.InitAndEnableFeatureWithParameters( features::kSitePerProcessOnlyForHighMemoryClients, {{features::kSitePerProcessOnlyForHighMemoryClientsParamName, "128"}}); base::test::ScopedFeatureList site_per_process; site_per_process.InitAndEnableFeature(features::kSitePerProcess); // site-per-process trial is enabled, and the memory threshold is above the // memory present on the device. EXPECT_TRUE(content::SiteIsolationPolicy::UseDedicatedProcessesForAllSites()); } IN_PROC_BROWSER_TEST_F(SitePerProcessMemoryThresholdBrowserTest, SitePerProcessEnabled_NoThreshold) { if (ShouldSkipBecauseOfConflictingCommandLineSwitches()) return; base::test::ScopedFeatureList site_per_process; site_per_process.InitAndEnableFeature(features::kSitePerProcess); EXPECT_TRUE(content::SiteIsolationPolicy::UseDedicatedProcessesForAllSites()); } IN_PROC_BROWSER_TEST_F(SitePerProcessMemoryThresholdBrowserTest, SitePerProcessDisabled_HighThreshold) { if (ShouldSkipBecauseOfConflictingCommandLineSwitches()) return; // 512MB of physical memory that the test simulates is below the 768MB // threshold. base::test::ScopedFeatureList memory_feature; memory_feature.InitAndEnableFeatureWithParameters( features::kSitePerProcessOnlyForHighMemoryClients, {{features::kSitePerProcessOnlyForHighMemoryClientsParamName, "768"}}); base::test::ScopedFeatureList site_per_process; site_per_process.InitAndDisableFeature(features::kSitePerProcess); // site-per-process trial is disabled, so isolation should be disabled // (i.e. the memory threshold should be ignored). EXPECT_FALSE( content::SiteIsolationPolicy::UseDedicatedProcessesForAllSites()); } IN_PROC_BROWSER_TEST_F(SitePerProcessMemoryThresholdBrowserTest, SitePerProcessDisabled_LowThreshold) { if (ShouldSkipBecauseOfConflictingCommandLineSwitches()) return; // 512MB of physical memory that the test simulates is above the 128MB // threshold. base::test::ScopedFeatureList memory_feature; memory_feature.InitAndEnableFeatureWithParameters( features::kSitePerProcessOnlyForHighMemoryClients, {{features::kSitePerProcessOnlyForHighMemoryClientsParamName, "128"}}); base::test::ScopedFeatureList site_per_process; site_per_process.InitAndDisableFeature(features::kSitePerProcess); // site-per-process trial is disabled, so isolation should be disabled // (i.e. the memory threshold should be ignored). EXPECT_FALSE( content::SiteIsolationPolicy::UseDedicatedProcessesForAllSites()); } IN_PROC_BROWSER_TEST_F(SitePerProcessMemoryThresholdBrowserTest, SitePerProcessDisabled_NoThreshold) { if (ShouldSkipBecauseOfConflictingCommandLineSwitches()) return; base::test::ScopedFeatureList site_per_process; site_per_process.InitAndDisableFeature(features::kSitePerProcess); // site-per-process trial is disabled, so isolation should be disabled // (i.e. the memory threshold should be ignored). EXPECT_FALSE( content::SiteIsolationPolicy::UseDedicatedProcessesForAllSites()); } } // namespace content
3,886
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.compute.fluent.models; import com.azure.core.annotation.Fluent; import com.azure.core.management.Resource; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.compute.models.EncryptionSetIdentity; import com.azure.resourcemanager.compute.models.KeyVaultAndKeyReference; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; import java.util.Map; /** disk encryption set resource. */ @Fluent public final class DiskEncryptionSetInner extends Resource { @JsonIgnore private final ClientLogger logger = new ClientLogger(DiskEncryptionSetInner.class); /* * The managed identity for the disk encryption set. It should be given * permission on the key vault before it can be used to encrypt disks. */ @JsonProperty(value = "identity") private EncryptionSetIdentity identity; /* * The properties property. */ @JsonProperty(value = "properties") private EncryptionSetProperties innerProperties; /** * Get the identity property: The managed identity for the disk encryption set. It should be given permission on the * key vault before it can be used to encrypt disks. * * @return the identity value. */ public EncryptionSetIdentity identity() { return this.identity; } /** * Set the identity property: The managed identity for the disk encryption set. It should be given permission on the * key vault before it can be used to encrypt disks. * * @param identity the identity value to set. * @return the DiskEncryptionSetInner object itself. */ public DiskEncryptionSetInner withIdentity(EncryptionSetIdentity identity) { this.identity = identity; return this; } /** * Get the innerProperties property: The properties property. * * @return the innerProperties value. */ private EncryptionSetProperties innerProperties() { return this.innerProperties; } /** {@inheritDoc} */ @Override public DiskEncryptionSetInner withLocation(String location) { super.withLocation(location); return this; } /** {@inheritDoc} */ @Override public DiskEncryptionSetInner withTags(Map<String, String> tags) { super.withTags(tags); return this; } /** * Get the activeKey property: The key vault key which is currently used by this disk encryption set. * * @return the activeKey value. */ public KeyVaultAndKeyReference activeKey() { return this.innerProperties() == null ? null : this.innerProperties().activeKey(); } /** * Set the activeKey property: The key vault key which is currently used by this disk encryption set. * * @param activeKey the activeKey value to set. * @return the DiskEncryptionSetInner object itself. */ public DiskEncryptionSetInner withActiveKey(KeyVaultAndKeyReference activeKey) { if (this.innerProperties() == null) { this.innerProperties = new EncryptionSetProperties(); } this.innerProperties().withActiveKey(activeKey); return this; } /** * Get the previousKeys property: A readonly collection of key vault keys previously used by this disk encryption * set while a key rotation is in progress. It will be empty if there is no ongoing key rotation. * * @return the previousKeys value. */ public List<KeyVaultAndKeyReference> previousKeys() { return this.innerProperties() == null ? null : this.innerProperties().previousKeys(); } /** * Get the provisioningState property: The disk encryption set provisioning state. * * @return the provisioningState value. */ public String provisioningState() { return this.innerProperties() == null ? null : this.innerProperties().provisioningState(); } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { if (identity() != null) { identity().validate(); } if (innerProperties() != null) { innerProperties().validate(); } } }
1,544
631
<filename>wallet/transactions/assets/assets_reg_creators.cpp // Copyright 2018 The Beam Team // // 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 "assets_reg_creators.h" #include "aregister_transaction.h" #include "aunregister_transaction.h" #include "aissue_transaction.h" #include "ainfo_transaction.h" #include "wallet/core/base_transaction.h" namespace beam::wallet { void RegisterAllAssetCreators(Wallet& wallet) { auto crReg = std::make_shared<AssetRegisterTransaction::Creator>(); wallet.RegisterTransactionType(TxType::AssetReg, std::static_pointer_cast<BaseTransaction::Creator>(crReg)); auto crUnreg = std::make_shared<AssetUnregisterTransaction::Creator>(); wallet.RegisterTransactionType(TxType::AssetUnreg, std::static_pointer_cast<BaseTransaction::Creator>(crUnreg)); auto crIssue = std::make_shared<AssetIssueTransaction::Creator>(true); wallet.RegisterTransactionType(TxType::AssetIssue, std::static_pointer_cast<BaseTransaction::Creator>(crIssue)); auto crConsume = std::make_shared<AssetIssueTransaction::Creator>(false); wallet.RegisterTransactionType(TxType::AssetConsume, std::static_pointer_cast<BaseTransaction::Creator>(crConsume)); auto crInfo = std::make_shared<AssetInfoTransaction::Creator>(); wallet.RegisterTransactionType(TxType::AssetInfo, std::static_pointer_cast<BaseTransaction::Creator>(crInfo)); } void RegusterDappsAssetCreators(Wallet& wallet) { auto crInfo = std::make_shared<AssetInfoTransaction::Creator>(); wallet.RegisterTransactionType(TxType::AssetInfo, std::static_pointer_cast<BaseTransaction::Creator>(crInfo)); } }
693
8,428
# third party from sqlalchemy import Column from sqlalchemy import Integer from sqlalchemy import String # relative from . import Base # this table holds the list of known nodes usually peer domains class Node(Base): __tablename__ = "node" id = Column(Integer(), primary_key=True, autoincrement=True) node_uid = Column(String(255)) node_name = Column(String(255))
117
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. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_framework.hxx" //_________________________________________________________________________________________________________________ // my own includes //_________________________________________________________________________________________________________________ #include <dispatch/servicehandler.hxx> #include <threadhelp/readguard.hxx> #include <general.h> #include <services.h> //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ #include <com/sun/star/frame/DispatchResultState.hpp> #include <com/sun/star/task/XJobExecutor.hpp> //_________________________________________________________________________________________________________________ // includes of other projects //_________________________________________________________________________________________________________________ #include <vcl/svapp.hxx> //_________________________________________________________________________________________________________________ // namespace //_________________________________________________________________________________________________________________ namespace framework{ //_________________________________________________________________________________________________________________ // non exported const //_________________________________________________________________________________________________________________ #define PROTOCOL_VALUE "service:" #define PROTOCOL_LENGTH 8 //_________________________________________________________________________________________________________________ // non exported definitions //_________________________________________________________________________________________________________________ //_________________________________________________________________________________________________________________ // declarations //_________________________________________________________________________________________________________________ //_________________________________________________________________________________________________________________ // XInterface, XTypeProvider, XServiceInfo DEFINE_XINTERFACE_5(ServiceHandler , OWeakObject , DIRECT_INTERFACE(css::lang::XTypeProvider ), DIRECT_INTERFACE(css::lang::XServiceInfo ), DIRECT_INTERFACE(css::frame::XDispatchProvider ), DIRECT_INTERFACE(css::frame::XNotifyingDispatch), DIRECT_INTERFACE(css::frame::XDispatch )) DEFINE_XTYPEPROVIDER_5(ServiceHandler , css::lang::XTypeProvider , css::lang::XServiceInfo , css::frame::XDispatchProvider , css::frame::XNotifyingDispatch, css::frame::XDispatch ) DEFINE_XSERVICEINFO_MULTISERVICE(ServiceHandler , ::cppu::OWeakObject , SERVICENAME_PROTOCOLHANDLER , IMPLEMENTATIONNAME_SERVICEHANDLER) DEFINE_INIT_SERVICE(ServiceHandler, { /*Attention I think we don't need any mutex or lock here ... because we are called by our own static method impl_createInstance() to create a new instance of this class by our own supported service factory. see macro DEFINE_XSERVICEINFO_MULTISERVICE and "impl_initService()" for further informations! */ } ) //_________________________________________________________________________________________________________________ /** @short standard ctor @descr These initialize a new instance of this class with needed informations for work. @param xFactory reference to uno servicemanager for creation of new services @modified 02.05.2002 08:16, as96863 */ ServiceHandler::ServiceHandler( const css::uno::Reference< css::lang::XMultiServiceFactory >& xFactory ) // Init baseclasses first : ThreadHelpBase( &Application::GetSolarMutex() ) , OWeakObject ( ) // Init member , m_xFactory ( xFactory ) { } //_________________________________________________________________________________________________________________ /** @short standard dtor @descr - @modified 02.05.2002 08:16, as96863 */ ServiceHandler::~ServiceHandler() { m_xFactory = NULL; } //_________________________________________________________________________________________________________________ /** @short decide if this dispatch implementation can be used for requested URL or not @descr A protocol handler is registerd for an URL pattern inside configuration and will be asked by the generic dispatch mechanism inside framework, if he can handle this special URL which match his registration. He can agree by returning of a valid dispatch instance or disagree by returning <NULL/>. We don't create new dispatch instances here really - we return THIS as result to handle it at the same implementation. @modified 02.05.2002 15:25, as96863 */ css::uno::Reference< css::frame::XDispatch > SAL_CALL ServiceHandler::queryDispatch( const css::util::URL& aURL , const ::rtl::OUString& /*sTarget*/ , sal_Int32 /*nFlags*/ ) throw( css::uno::RuntimeException ) { css::uno::Reference< css::frame::XDispatch > xDispatcher; if (aURL.Complete.compareToAscii(PROTOCOL_VALUE,PROTOCOL_LENGTH)==0) xDispatcher = this; return xDispatcher; } //_________________________________________________________________________________________________________________ /** @short do the same like dispatch() but for multiple requests at the same time @descr - @modified 02.05.2002 15:27, as96863 */ css::uno::Sequence< css::uno::Reference< css::frame::XDispatch > > SAL_CALL ServiceHandler::queryDispatches( const css::uno::Sequence< css::frame::DispatchDescriptor >& lDescriptor ) throw( css::uno::RuntimeException ) { sal_Int32 nCount = lDescriptor.getLength(); css::uno::Sequence< css::uno::Reference< css::frame::XDispatch > > lDispatcher( nCount ); for( sal_Int32 i=0; i<nCount; ++i ) { lDispatcher[i] = this->queryDispatch( lDescriptor[i].FeatureURL, lDescriptor[i].FrameName, lDescriptor[i].SearchFlags); } return lDispatcher; } //_________________________________________________________________________________________________________________ /** @short dispatch URL with arguments @descr We use threadsafe internal method to do so. It returns a state value - but we ignore it. Because we doesn't support status listener notifications here. @param aURL uno URL which should be executed @param lArguments list of optional arguments for this request @modified 02.05.2002 08:19, as96863 */ void SAL_CALL ServiceHandler::dispatch( const css::util::URL& aURL , const css::uno::Sequence< css::beans::PropertyValue >& lArguments ) throw( css::uno::RuntimeException ) { // dispatch() is an [oneway] call ... and may our user release his reference to us immediately. // So we should hold us self alive till this call ends. css::uno::Reference< css::frame::XNotifyingDispatch > xSelfHold(static_cast< ::cppu::OWeakObject* >(this), css::uno::UNO_QUERY); implts_dispatch(aURL,lArguments); // No notification for status listener! } //_________________________________________________________________________________________________________________ /** @short dispatch with guaranteed notifications about success @descr We use threadsafe internal method to do so. Return state of this function will be used for notification if an optional listener is given. @param aURL uno URL which should be executed @param lArguments list of optional arguments for this request @param xListener optional listener for state events @modified 30.04.2002 14:49, as96863 */ void SAL_CALL ServiceHandler::dispatchWithNotification( const css::util::URL& aURL , const css::uno::Sequence< css::beans::PropertyValue >& lArguments, const css::uno::Reference< css::frame::XDispatchResultListener >& xListener ) throw( css::uno::RuntimeException ) { // This class was designed to die by reference. And if user release his reference to us immediately after calling this method // we can run into some problems. So we hold us self alive till this method ends. // Another reason: We can use this reference as source of sending event at the end too. css::uno::Reference< css::frame::XNotifyingDispatch > xThis(static_cast< ::cppu::OWeakObject* >(this), css::uno::UNO_QUERY); css::uno::Reference< css::uno::XInterface > xService = implts_dispatch(aURL,lArguments); if (xListener.is()) { css::frame::DispatchResultEvent aEvent; if (xService.is()) aEvent.State = css::frame::DispatchResultState::SUCCESS; else aEvent.State = css::frame::DispatchResultState::FAILURE; aEvent.Result <<= xService; // may NULL for state=FAILED! aEvent.Source = xThis; xListener->dispatchFinished( aEvent ); } } //_________________________________________________________________________________________________________________ /** @short threadsafe helper for dispatch calls @descr We support two interfaces for the same process - dispatch URLs. That the reason for this internal function. It implements the real dispatch operation and returns a state value which inform caller about success. He can notify listener then by using this return value. @param aURL uno URL which should be executed @param lArguments list of optional arguments for this request @return <NULL/> if requested service couldn't be created successullfy; a valid reference otherwise. This return value can be used to indicate, if dispatch was successfully or not. @modified 02.05.2002 10:51, as96863 */ css::uno::Reference< css::uno::XInterface > ServiceHandler::implts_dispatch( const css::util::URL& aURL , const css::uno::Sequence< css::beans::PropertyValue >& /*lArguments*/ ) throw( css::uno::RuntimeException ) { /* SAFE */ ReadGuard aReadLock( m_aLock ); css::uno::Reference< css::lang::XMultiServiceFactory > xFactory = m_xFactory; aReadLock.unlock(); /* SAFE */ if (!xFactory.is()) return css::uno::Reference< css::uno::XInterface >(); // extract service name and may optional given parameters from given URL // and use it to create and start the component ::rtl::OUString sServiceAndArguments = aURL.Complete.copy(PROTOCOL_LENGTH); ::rtl::OUString sServiceName; ::rtl::OUString sArguments ; sal_Int32 nArgStart = sServiceAndArguments.indexOf('?',0); if (nArgStart!=-1) { sServiceName = sServiceAndArguments.copy(0,nArgStart); ++nArgStart; // ignore '?'! sArguments = sServiceAndArguments.copy(nArgStart); } else { sServiceName = sServiceAndArguments; } if (!sServiceName.getLength()) return css::uno::Reference< css::uno::XInterface >(); // If a service doesn't support an optional job executor interface - he can't get // any given parameters! // Because we can't know if we must call createInstanceWithArguments() or XJobExecutor::trigger() ... css::uno::Reference< css::uno::XInterface > xService; try { // => a) a service starts running inside his own ctor and we create it only xService = xFactory->createInstance(sServiceName); // or b) he implements the right interface and starts there (may with optional parameters) css::uno::Reference< css::task::XJobExecutor > xExecuteable(xService, css::uno::UNO_QUERY); if (xExecuteable.is()) xExecuteable->trigger(sArguments); } // ignore all errors - inclusive runtime errors! // E.g. a script based service (written in phyton) could not be executed // because it contains syntax errors, which was detected at runtime ... catch(const css::uno::Exception&) { xService.clear(); } return xService; } //_________________________________________________________________________________________________________________ /** @short add/remove listener for state events @descr We use an internal container to hold such registered listener. This container lives if we live. And if call pas registration as non breakable transaction - we can accept the request without any explicit lock. Because we share our mutex with this container. @param xListener reference to a valid listener for state events @param aURL URL about listener will be informed, if something occurred @modified 30.04.2002 14:49, as96863 */ void SAL_CALL ServiceHandler::addStatusListener( const css::uno::Reference< css::frame::XStatusListener >& /*xListener*/ , const css::util::URL& /*aURL*/ ) throw( css::uno::RuntimeException ) { // not suported yet } //_________________________________________________________________________________________________________________ void SAL_CALL ServiceHandler::removeStatusListener( const css::uno::Reference< css::frame::XStatusListener >& /*xListener*/ , const css::util::URL& /*aURL*/ ) throw( css::uno::RuntimeException ) { // not suported yet } } // namespace framework
5,888
1,338
<filename>headers/posix/stdc-predef.h /* * Copyright 2021 Haiku, Inc. All Rights Reserved. * Distributed under the terms of the MIT License. */ #ifndef _STDC_PREDEF_H #define _STDC_PREDEF_H #if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L # define __STDC_NO_THREADS__ 1 #endif #endif /* _STDC_PREDEF_H */
129
14,668
<filename>mojo/core/ports/message_queue.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 "mojo/core/ports/message_queue.h" #include <algorithm> #include "base/compiler_specific.h" #include "base/logging.h" #include "mojo/core/ports/message_filter.h" namespace mojo { namespace core { namespace ports { // Used by std::{push,pop}_heap functions inline bool operator<(const std::unique_ptr<UserMessageEvent>& a, const std::unique_ptr<UserMessageEvent>& b) { return a->sequence_num() > b->sequence_num(); } MessageQueue::MessageQueue() : MessageQueue(kInitialSequenceNum) {} MessageQueue::MessageQueue(uint64_t next_sequence_num) : next_sequence_num_(next_sequence_num) { // The message queue is blocked waiting for a message with sequence number // equal to |next_sequence_num|. } MessageQueue::~MessageQueue() { #if DCHECK_IS_ON() size_t num_leaked_ports = 0; for (const auto& message : heap_) num_leaked_ports += message->num_ports(); DVLOG_IF(1, num_leaked_ports > 0) << "Leaking " << num_leaked_ports << " ports in unreceived messages"; #endif } bool MessageQueue::HasNextMessage() const { return !heap_.empty() && heap_[0]->sequence_num() == next_sequence_num_; } void MessageQueue::GetNextMessage(std::unique_ptr<UserMessageEvent>* message, MessageFilter* filter) { if (!HasNextMessage() || (filter && !filter->Match(*heap_[0]))) { message->reset(); return; } std::pop_heap(heap_.begin(), heap_.end()); *message = std::move(heap_.back()); total_queued_bytes_ -= (*message)->GetSizeIfSerialized(); heap_.pop_back(); // We keep the capacity of |heap_| in check so that a large batch of incoming // messages doesn't permanently wreck available memory. The choice of interval // here is somewhat arbitrary. constexpr size_t kHeapMinimumShrinkSize = 16; constexpr size_t kHeapShrinkInterval = 512; if (UNLIKELY(heap_.size() > kHeapMinimumShrinkSize && heap_.size() % kHeapShrinkInterval == 0)) { heap_.shrink_to_fit(); } } void MessageQueue::AcceptMessage(std::unique_ptr<UserMessageEvent> message, bool* has_next_message) { // TODO: Handle sequence number roll-over. total_queued_bytes_ += message->GetSizeIfSerialized(); heap_.emplace_back(std::move(message)); std::push_heap(heap_.begin(), heap_.end()); if (!signalable_) { *has_next_message = false; } else { *has_next_message = (heap_[0]->sequence_num() == next_sequence_num_); } } void MessageQueue::TakeAllMessages( std::vector<std::unique_ptr<UserMessageEvent>>* messages) { *messages = std::move(heap_); total_queued_bytes_ = 0; } void MessageQueue::MessageProcessed() { next_sequence_num_++; } } // namespace ports } // namespace core } // namespace mojo
1,086
2,151
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef ASH_WM_LOCK_STATE_CONTROLLER_TEST_API_H_ #define ASH_WM_LOCK_STATE_CONTROLLER_TEST_API_H_ #include "ash/wm/lock_state_controller.h" namespace ash { // Helper class used by tests to access LockStateController's internal state. class LockStateControllerTestApi { public: explicit LockStateControllerTestApi(LockStateController* controller); ~LockStateControllerTestApi(); void set_shutdown_controller(ShutdownController* shutdown_controller) { controller_->shutdown_controller_ = shutdown_controller; } bool lock_fail_timer_is_running() const { return controller_->lock_fail_timer_.IsRunning(); } bool lock_to_shutdown_timer_is_running() const { return controller_->lock_to_shutdown_timer_.IsRunning(); } bool shutdown_timer_is_running() const { return controller_->pre_shutdown_timer_.IsRunning(); } bool real_shutdown_timer_is_running() const { return controller_->real_shutdown_timer_.IsRunning(); } bool is_animating_lock() const { return controller_->animating_lock_; } bool is_lock_cancellable() const { return controller_->CanCancelLockAnimation(); } void trigger_lock_fail_timeout() { controller_->OnLockFailTimeout(); controller_->lock_fail_timer_.Stop(); } void trigger_lock_to_shutdown_timeout() { controller_->OnLockToShutdownTimeout(); controller_->lock_to_shutdown_timer_.Stop(); } void trigger_shutdown_timeout() { controller_->OnPreShutdownAnimationTimeout(); controller_->pre_shutdown_timer_.Stop(); } void trigger_real_shutdown_timeout() { controller_->OnRealPowerTimeout(); controller_->real_shutdown_timer_.Stop(); } private: LockStateController* controller_; // not owned DISALLOW_COPY_AND_ASSIGN(LockStateControllerTestApi); }; } // namespace ash #endif // ASH_WM_LOCK_STATE_CONTROLLER_TEST_API_H_
668
2,564
// // Created by CainHuang on 2019/3/13. // #include "FrameBuffer.h" TextureAttributes FrameBuffer::defaultTextureAttributes = { .minFilter = GL_LINEAR, .magFilter = GL_LINEAR, .wrapS = GL_CLAMP_TO_EDGE, .wrapT = GL_CLAMP_TO_EDGE, .internalFormat = GL_RGBA, .format = GL_RGBA, .type = GL_UNSIGNED_BYTE }; FrameBuffer::FrameBuffer(int width, int height, const TextureAttributes textureAttributes) : texture(-1), framebuffer(-1) { this->width = width; this->height = height; this->textureAttributes = textureAttributes; initialized = false; } FrameBuffer::~FrameBuffer() { destroy(); } void FrameBuffer::init() { createFrameBuffer(); } void FrameBuffer::destroy() { if (texture >= 0) { glDeleteTextures(1, &texture); texture = -1; } if (framebuffer >= 0) { glDeleteFramebuffers(1, &framebuffer); framebuffer = -1; } } void FrameBuffer::bindBuffer() { if (framebuffer >= 0) { glBindFramebuffer(GL_FRAMEBUFFER, framebuffer); } glViewport(0, 0, width, height); } void FrameBuffer::unbindBuffer() { glBindFramebuffer(GL_FRAMEBUFFER, 0); } void FrameBuffer::createTexture() { glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, textureAttributes.minFilter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, textureAttributes.magFilter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, textureAttributes.wrapS); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, textureAttributes.wrapT); } void FrameBuffer::createFrameBuffer() { if (initialized) { return; } glGenFramebuffers(1, &framebuffer); glBindFramebuffer(GL_FRAMEBUFFER, framebuffer); createTexture(); glTexImage2D(GL_TEXTURE_2D, 0, textureAttributes.internalFormat, width, height, 0, textureAttributes.format, textureAttributes.type, 0); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0); glBindTexture(GL_TEXTURE_2D, 0); glBindFramebuffer(GL_FRAMEBUFFER, 0); initialized = true; }
882
537
<reponame>TheVinhLuong102/drf-flex-fields from rest_flex_fields import FlexFieldsModelViewSet from tests.testapp.models import Pet from tests.testapp.serializers import PetSerializer class PetViewSet(FlexFieldsModelViewSet): """ API endpoint for testing purposes. """ serializer_class = PetSerializer queryset = Pet.objects.all() permit_list_expands = ["owner"]
132
682
<reponame>HackerFoo/vtr-verilog-to-routing<filename>abc/src/aig/saig/saigSynch.c /**CFile**************************************************************** FileName [saigSynch.c] SystemName [ABC: Logic synthesis and verification system.] PackageName [Sequential AIG package.] Synopsis [Computation of synchronizing sequence.] Author [<NAME>] Affiliation [UC Berkeley] Date [Ver. 1.0. Started - June 20, 2005.] Revision [$Id: saigSynch.c,v 1.00 2005/06/20 00:00:00 alanmi Exp $] ***********************************************************************/ #include "saig.h" ABC_NAMESPACE_IMPL_START //////////////////////////////////////////////////////////////////////// /// DECLARATIONS /// //////////////////////////////////////////////////////////////////////// // 0 1 x // 00 01 11 // 0 00 00 00 00 // 1 01 00 01 11 // x 11 00 11 11 static inline unsigned Saig_SynchNot( unsigned w ) { return w^((~(w&(w>>1)))&0x55555555); } static inline unsigned Saig_SynchAnd( unsigned u, unsigned w ) { return (u&w)|((((u&(u>>1)&w&~(w>>1))|(w&(w>>1)&u&~(u>>1)))&0x55555555)<<1); } static inline unsigned Saig_SynchRandomBinary() { return Aig_ManRandom(0) & 0x55555555; } static inline unsigned Saig_SynchRandomTernary() { unsigned w = Aig_ManRandom(0); return w^((~w)&(w>>1)&0x55555555); } static inline unsigned Saig_SynchTernary( int v ) { assert( v == 0 || v == 1 || v == 3 ); return v? ((v==1)? 0x55555555 : 0xffffffff) : 0; } //////////////////////////////////////////////////////////////////////// /// FUNCTION DEFINITIONS /// //////////////////////////////////////////////////////////////////////// /**Function************************************************************* Synopsis [Initializes registers to the ternary state.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Saig_SynchSetConstant1( Aig_Man_t * pAig, Vec_Ptr_t * vSimInfo, int nWords ) { Aig_Obj_t * pObj; unsigned * pSim; int w; pObj = Aig_ManConst1( pAig ); pSim = (unsigned *)Vec_PtrEntry( vSimInfo, pObj->Id ); for ( w = 0; w < nWords; w++ ) pSim[w] = 0x55555555; } /**Function************************************************************* Synopsis [Initializes registers to the ternary state.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Saig_SynchInitRegsTernary( Aig_Man_t * pAig, Vec_Ptr_t * vSimInfo, int nWords ) { Aig_Obj_t * pObj; unsigned * pSim; int i, w; Saig_ManForEachLo( pAig, pObj, i ) { pSim = (unsigned *)Vec_PtrEntry( vSimInfo, pObj->Id ); for ( w = 0; w < nWords; w++ ) pSim[w] = 0xffffffff; } } /**Function************************************************************* Synopsis [Initializes registers to the given binary state.] Description [The binary state is stored in pObj->fMarkA.] SideEffects [] SeeAlso [] ***********************************************************************/ void Saig_SynchInitRegsBinary( Aig_Man_t * pAig, Vec_Ptr_t * vSimInfo, int nWords ) { Aig_Obj_t * pObj; unsigned * pSim; int i, w; Saig_ManForEachLo( pAig, pObj, i ) { pSim = (unsigned *)Vec_PtrEntry( vSimInfo, pObj->Id ); for ( w = 0; w < nWords; w++ ) pSim[w] = Saig_SynchTernary( pObj->fMarkA ); } } /**Function************************************************************* Synopsis [Initializes random binary primary inputs.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Saig_SynchInitPisRandom( Aig_Man_t * pAig, Vec_Ptr_t * vSimInfo, int nWords ) { Aig_Obj_t * pObj; unsigned * pSim; int i, w; Saig_ManForEachPi( pAig, pObj, i ) { pSim = (unsigned *)Vec_PtrEntry( vSimInfo, pObj->Id ); for ( w = 0; w < nWords; w++ ) pSim[w] = Saig_SynchRandomBinary(); } } /**Function************************************************************* Synopsis [Initializes random binary primary inputs.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Saig_SynchInitPisGiven( Aig_Man_t * pAig, Vec_Ptr_t * vSimInfo, int nWords, char * pValues ) { Aig_Obj_t * pObj; unsigned * pSim; int i, w; Saig_ManForEachPi( pAig, pObj, i ) { pSim = (unsigned *)Vec_PtrEntry( vSimInfo, pObj->Id ); for ( w = 0; w < nWords; w++ ) pSim[w] = Saig_SynchTernary( pValues[i] ); } } /**Function************************************************************* Synopsis [Performs ternary simulation of the nodes.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Saig_SynchTernarySimulate( Aig_Man_t * pAig, Vec_Ptr_t * vSimInfo, int nWords ) { Aig_Obj_t * pObj; unsigned * pSim0, * pSim1, * pSim; int i, w; // simulate nodes Aig_ManForEachNode( pAig, pObj, i ) { pSim = (unsigned *)Vec_PtrEntry( vSimInfo, pObj->Id ); pSim0 = (unsigned *)Vec_PtrEntry( vSimInfo, Aig_ObjFaninId0(pObj) ); pSim1 = (unsigned *)Vec_PtrEntry( vSimInfo, Aig_ObjFaninId1(pObj) ); if ( Aig_ObjFaninC0(pObj) && Aig_ObjFaninC1(pObj) ) { for ( w = 0; w < nWords; w++ ) pSim[w] = Saig_SynchAnd( Saig_SynchNot(pSim0[w]), Saig_SynchNot(pSim1[w]) ); } else if ( !Aig_ObjFaninC0(pObj) && Aig_ObjFaninC1(pObj) ) { for ( w = 0; w < nWords; w++ ) pSim[w] = Saig_SynchAnd( pSim0[w], Saig_SynchNot(pSim1[w]) ); } else if ( Aig_ObjFaninC0(pObj) && !Aig_ObjFaninC1(pObj) ) { for ( w = 0; w < nWords; w++ ) pSim[w] = Saig_SynchAnd( Saig_SynchNot(pSim0[w]), pSim1[w] ); } else // if ( !Aig_ObjFaninC0(pObj) && !Aig_ObjFaninC1(pObj) ) { for ( w = 0; w < nWords; w++ ) pSim[w] = Saig_SynchAnd( pSim0[w], pSim1[w] ); } } // transfer values to register inputs Saig_ManForEachLi( pAig, pObj, i ) { pSim = (unsigned *)Vec_PtrEntry( vSimInfo, pObj->Id ); pSim0 = (unsigned *)Vec_PtrEntry( vSimInfo, Aig_ObjFaninId0(pObj) ); if ( Aig_ObjFaninC0(pObj) ) { for ( w = 0; w < nWords; w++ ) pSim[w] = Saig_SynchNot( pSim0[w] ); } else { for ( w = 0; w < nWords; w++ ) pSim[w] = pSim0[w]; } } } /**Function************************************************************* Synopsis [Performs ternary simulation of the nodes.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Saig_SynchTernaryTransferState( Aig_Man_t * pAig, Vec_Ptr_t * vSimInfo, int nWords ) { Aig_Obj_t * pObjLi, * pObjLo; unsigned * pSim0, * pSim1; int i, w; Saig_ManForEachLiLo( pAig, pObjLi, pObjLo, i ) { pSim0 = (unsigned *)Vec_PtrEntry( vSimInfo, pObjLi->Id ); pSim1 = (unsigned *)Vec_PtrEntry( vSimInfo, pObjLo->Id ); for ( w = 0; w < nWords; w++ ) pSim1[w] = pSim0[w]; } } /**Function************************************************************* Synopsis [Returns the number of Xs in the smallest ternary pattern.] Description [Returns the number of this pattern.] SideEffects [] SeeAlso [] ***********************************************************************/ int Saig_SynchCountX( Aig_Man_t * pAig, Vec_Ptr_t * vSimInfo, int nWords, int * piPat ) { Aig_Obj_t * pObj; unsigned * pSim; int * pCounters, i, w, b; int iPatBest, iTernMin; // count the number of ternary values in each pattern pCounters = ABC_CALLOC( int, nWords * 16 ); Saig_ManForEachLi( pAig, pObj, i ) { pSim = (unsigned *)Vec_PtrEntry( vSimInfo, pObj->Id ); for ( w = 0; w < nWords; w++ ) for ( b = 0; b < 16; b++ ) if ( ((pSim[w] >> (b << 1)) & 3) == 3 ) pCounters[16 * w + b]++; } // get the best pattern iPatBest = -1; iTernMin = 1 + Saig_ManRegNum(pAig); for ( b = 0; b < 16 * nWords; b++ ) if ( iTernMin > pCounters[b] ) { iTernMin = pCounters[b]; iPatBest = b; if ( iTernMin == 0 ) break; } ABC_FREE( pCounters ); *piPat = iPatBest; return iTernMin; } /**Function************************************************************* Synopsis [Saves the best pattern found and initializes the registers.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int Saig_SynchSavePattern( Aig_Man_t * pAig, Vec_Ptr_t * vSimInfo, int nWords, int iPat, Vec_Str_t * vSequence ) { Aig_Obj_t * pObj, * pObjLi, * pObjLo; unsigned * pSim; int Counter, Value, i, w; assert( iPat < 16 * nWords ); Saig_ManForEachPi( pAig, pObj, i ) { pSim = (unsigned *)Vec_PtrEntry( vSimInfo, pObj->Id ); Value = (pSim[iPat>>4] >> ((iPat&0xf) << 1)) & 3; Vec_StrPush( vSequence, (char)Value ); // printf( "%d ", Value ); } // printf( "\n" ); Counter = 0; Saig_ManForEachLiLo( pAig, pObjLi, pObjLo, i ) { pSim = (unsigned *)Vec_PtrEntry( vSimInfo, pObjLi->Id ); Value = (pSim[iPat>>4] >> ((iPat&0xf) << 1)) & 3; Counter += (Value == 3); // save patern in the same register pSim = (unsigned *)Vec_PtrEntry( vSimInfo, pObjLo->Id ); for ( w = 0; w < nWords; w++ ) pSim[w] = Saig_SynchTernary( Value ); } return Counter; } /**Function************************************************************* Synopsis [Implement synchronizing sequence.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int Saig_SynchSequenceRun( Aig_Man_t * pAig, Vec_Ptr_t * vSimInfo, Vec_Str_t * vSequence, int fTernary ) { unsigned * pSim; Aig_Obj_t * pObj; int Counter, nIters, Value, i; assert( Vec_StrSize(vSequence) % Saig_ManPiNum(pAig) == 0 ); nIters = Vec_StrSize(vSequence) / Saig_ManPiNum(pAig); Saig_SynchSetConstant1( pAig, vSimInfo, 1 ); if ( fTernary ) Saig_SynchInitRegsTernary( pAig, vSimInfo, 1 ); else Saig_SynchInitRegsBinary( pAig, vSimInfo, 1 ); for ( i = 0; i < nIters; i++ ) { Saig_SynchInitPisGiven( pAig, vSimInfo, 1, Vec_StrArray(vSequence) + i * Saig_ManPiNum(pAig) ); Saig_SynchTernarySimulate( pAig, vSimInfo, 1 ); Saig_SynchTernaryTransferState( pAig, vSimInfo, 1 ); } // save the resulting state in the registers Counter = 0; Saig_ManForEachLo( pAig, pObj, i ) { pSim = (unsigned *)Vec_PtrEntry( vSimInfo, pObj->Id ); Value = pSim[0] & 3; assert( Value != 2 ); Counter += (Value == 3); pObj->fMarkA = Value; } return Counter; } /**Function************************************************************* Synopsis [Determines synchronizing sequence using ternary simulation.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ Vec_Str_t * Saig_SynchSequence( Aig_Man_t * pAig, int nWords ) { int nStepsMax = 100; // the maximum number of simulation steps int nTriesMax = 100; // the maximum number of attempts at each step int fVerify = 1; // verify the resulting pattern Vec_Str_t * vSequence; Vec_Ptr_t * vSimInfo; int nTerPrev, nTerCur = 0, nTerCur2; int iPatBest, RetValue, s, t; assert( Saig_ManRegNum(pAig) > 0 ); // reset random numbers Aig_ManRandom( 1 ); // start the sequence vSequence = Vec_StrAlloc( 20 * Saig_ManRegNum(pAig) ); // create sim info and init registers vSimInfo = Vec_PtrAllocSimInfo( Aig_ManObjNumMax(pAig), nWords ); Saig_SynchSetConstant1( pAig, vSimInfo, nWords ); // iterate over the timeframes nTerPrev = Saig_ManRegNum(pAig); Saig_SynchInitRegsTernary( pAig, vSimInfo, nWords ); for ( s = 0; s < nStepsMax && nTerPrev > 0; s++ ) { for ( t = 0; t < nTriesMax; t++ ) { Saig_SynchInitPisRandom( pAig, vSimInfo, nWords ); Saig_SynchTernarySimulate( pAig, vSimInfo, nWords ); nTerCur = Saig_SynchCountX( pAig, vSimInfo, nWords, &iPatBest ); if ( nTerCur < nTerPrev ) break; } if ( t == nTriesMax ) break; nTerCur2 = Saig_SynchSavePattern( pAig, vSimInfo, nWords, iPatBest, vSequence ); assert( nTerCur == nTerCur2 ); nTerPrev = nTerCur; } if ( nTerPrev > 0 ) { printf( "Count not initialize %d registers.\n", nTerPrev ); Vec_PtrFree( vSimInfo ); Vec_StrFree( vSequence ); return NULL; } // verify that the sequence is correct if ( fVerify ) { RetValue = Saig_SynchSequenceRun( pAig, vSimInfo, vSequence, 1 ); assert( RetValue == 0 ); Aig_ManCleanMarkA( pAig ); } Vec_PtrFree( vSimInfo ); return vSequence; } /**Function************************************************************* Synopsis [Duplicates the AIG to have constant-0 initial state.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ Aig_Man_t * Saig_ManDupInitZero( Aig_Man_t * p ) { Aig_Man_t * pNew; Aig_Obj_t * pObj; int i; pNew = Aig_ManStart( Aig_ManObjNumMax(p) ); pNew->pName = Abc_UtilStrsav( p->pName ); Aig_ManConst1(p)->pData = Aig_ManConst1(pNew); Saig_ManForEachPi( p, pObj, i ) pObj->pData = Aig_ObjCreateCi( pNew ); Saig_ManForEachLo( p, pObj, i ) pObj->pData = Aig_NotCond( Aig_ObjCreateCi( pNew ), pObj->fMarkA ); Aig_ManForEachNode( p, pObj, i ) pObj->pData = Aig_And( pNew, Aig_ObjChild0Copy(pObj), Aig_ObjChild1Copy(pObj) ); Saig_ManForEachPo( p, pObj, i ) pObj->pData = Aig_ObjCreateCo( pNew, Aig_ObjChild0Copy(pObj) ); Saig_ManForEachLi( p, pObj, i ) pObj->pData = Aig_ObjCreateCo( pNew, Aig_NotCond( Aig_ObjChild0Copy(pObj), pObj->fMarkA ) ); Aig_ManSetRegNum( pNew, Saig_ManRegNum(p) ); assert( Aig_ManNodeNum(pNew) == Aig_ManNodeNum(p) ); return pNew; } /**Function************************************************************* Synopsis [Determines synchronizing sequence using ternary simulation.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ Aig_Man_t * Saig_SynchSequenceApply( Aig_Man_t * pAig, int nWords, int fVerbose ) { Aig_Man_t * pAigZero; Vec_Str_t * vSequence; Vec_Ptr_t * vSimInfo; int RetValue; abctime clk; clk = Abc_Clock(); // derive synchronization sequence vSequence = Saig_SynchSequence( pAig, nWords ); if ( vSequence == NULL ) printf( "Design 1: Synchronizing sequence is not found. " ); else if ( fVerbose ) printf( "Design 1: Synchronizing sequence of length %4d is found. ", Vec_StrSize(vSequence) / Saig_ManPiNum(pAig) ); if ( fVerbose ) { ABC_PRT( "Time", Abc_Clock() - clk ); } else printf( "\n" ); if ( vSequence == NULL ) { printf( "Quitting synchronization.\n" ); return NULL; } // apply synchronization sequence vSimInfo = Vec_PtrAllocSimInfo( Aig_ManObjNumMax(pAig), 1 ); RetValue = Saig_SynchSequenceRun( pAig, vSimInfo, vSequence, 1 ); assert( RetValue == 0 ); // duplicate pAigZero = Saig_ManDupInitZero( pAig ); // cleanup Vec_PtrFree( vSimInfo ); Vec_StrFree( vSequence ); Aig_ManCleanMarkA( pAig ); return pAigZero; } /**Function************************************************************* Synopsis [Creates SEC miter for two designs without initial state.] Description [The designs (pAig1 and pAig2) are assumed to have ternary initial state. Determines synchronizing sequences using ternary simulation. Simulates the sequences on both designs to come up with equivalent binary initial states. Create seq miter for the designs starting in these states.] SideEffects [] SeeAlso [] ***********************************************************************/ Aig_Man_t * Saig_Synchronize( Aig_Man_t * pAig1, Aig_Man_t * pAig2, int nWords, int fVerbose ) { Aig_Man_t * pAig1z, * pAig2z, * pMiter; Vec_Str_t * vSeq1, * vSeq2; Vec_Ptr_t * vSimInfo; int RetValue; abctime clk; /* { unsigned u = Saig_SynchRandomTernary(); unsigned w = Saig_SynchRandomTernary(); unsigned x = Saig_SynchNot( u ); unsigned y = Saig_SynchNot( w ); unsigned z = Saig_SynchAnd( x, y ); Extra_PrintBinary( stdout, &u, 32 ); printf( "\n" ); Extra_PrintBinary( stdout, &w, 32 ); printf( "\n" ); printf( "\n" ); Extra_PrintBinary( stdout, &x, 32 ); printf( "\n" ); Extra_PrintBinary( stdout, &y, 32 ); printf( "\n" ); printf( "\n" ); Extra_PrintBinary( stdout, &z, 32 ); printf( "\n" ); } */ // report statistics if ( fVerbose ) { printf( "Design 1: " ); Aig_ManPrintStats( pAig1 ); printf( "Design 2: " ); Aig_ManPrintStats( pAig2 ); } // synchronize the first design clk = Abc_Clock(); vSeq1 = Saig_SynchSequence( pAig1, nWords ); if ( vSeq1 == NULL ) printf( "Design 1: Synchronizing sequence is not found. " ); else if ( fVerbose ) printf( "Design 1: Synchronizing sequence of length %4d is found. ", Vec_StrSize(vSeq1) / Saig_ManPiNum(pAig1) ); if ( fVerbose ) { ABC_PRT( "Time", Abc_Clock() - clk ); } else printf( "\n" ); // synchronize the first design clk = Abc_Clock(); vSeq2 = Saig_SynchSequence( pAig2, nWords ); if ( vSeq2 == NULL ) printf( "Design 2: Synchronizing sequence is not found. " ); else if ( fVerbose ) printf( "Design 2: Synchronizing sequence of length %4d is found. ", Vec_StrSize(vSeq2) / Saig_ManPiNum(pAig2) ); if ( fVerbose ) { ABC_PRT( "Time", Abc_Clock() - clk ); } else printf( "\n" ); // quit if one of the designs cannot be synchronized if ( vSeq1 == NULL || vSeq2 == NULL ) { printf( "Quitting synchronization.\n" ); if ( vSeq1 ) Vec_StrFree( vSeq1 ); if ( vSeq2 ) Vec_StrFree( vSeq2 ); return NULL; } clk = Abc_Clock(); vSimInfo = Vec_PtrAllocSimInfo( Abc_MaxInt( Aig_ManObjNumMax(pAig1), Aig_ManObjNumMax(pAig2) ), 1 ); // process Design 1 RetValue = Saig_SynchSequenceRun( pAig1, vSimInfo, vSeq1, 1 ); assert( RetValue == 0 ); RetValue = Saig_SynchSequenceRun( pAig1, vSimInfo, vSeq2, 0 ); assert( RetValue == 0 ); // process Design 2 RetValue = Saig_SynchSequenceRun( pAig2, vSimInfo, vSeq2, 1 ); assert( RetValue == 0 ); // duplicate designs pAig1z = Saig_ManDupInitZero( pAig1 ); pAig2z = Saig_ManDupInitZero( pAig2 ); pMiter = Saig_ManCreateMiter( pAig1z, pAig2z, 0 ); Aig_ManCleanup( pMiter ); Aig_ManStop( pAig1z ); Aig_ManStop( pAig2z ); // cleanup Vec_PtrFree( vSimInfo ); Vec_StrFree( vSeq1 ); Vec_StrFree( vSeq2 ); Aig_ManCleanMarkA( pAig1 ); Aig_ManCleanMarkA( pAig2 ); if ( fVerbose ) { printf( "Miter of the synchronized designs is constructed. " ); ABC_PRT( "Time", Abc_Clock() - clk ); } return pMiter; } //////////////////////////////////////////////////////////////////////// /// END OF FILE /// //////////////////////////////////////////////////////////////////////// ABC_NAMESPACE_IMPL_END
9,026
1,652
<reponame>minluzhou/test1 package com.ctrip.xpipe.redis.core.entity; import com.ctrip.xpipe.endpoint.HostPort; import com.ctrip.xpipe.utils.ObjectUtils; /** * @author wenchao.meng * <p> * Jul 17, 2016 */ public interface Redis { String getId(); String getIp(); String getMaster(); Long getOffset(); Integer getPort(); Redis setId(String id); Redis setIp(String ip); Redis setMaster(String master); Redis setOffset(Long offset); Redis setPort(Integer port); Redis setSurvive(Boolean survive); boolean isSurvive(); default boolean equalsWithIpPort(HostPort hostPort) { if (!ObjectUtils.equals(getIp(), hostPort.getHost())) { return false; } if (!ObjectUtils.equals(getPort(), hostPort.getPort())) { return false; } return true; } default boolean equalsWithIpPort(Redis redis) { if (redis == null) { return false; } if (!ObjectUtils.equals(getIp(), redis.getIp())) { return false; } if (!ObjectUtils.equals(getPort(), redis.getPort())) { return false; } return true; } default String desc() { return String.format("%s(%s:%d)", getClass().getSimpleName(), getIp(), getPort()); } }
606
2,406
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <vector> #include "single_layer_tests/mvn.hpp" #include "common_test_utils/test_constants.hpp" using namespace LayerTestsDefinitions; const std::vector<ngraph::AxisSet> emptyReductionAxes = {{}}; const std::vector<std::vector<size_t>> inputShapes = { {1, 32, 17}, {1, 37, 9}, {1, 16, 5, 8}, {2, 19, 5, 10}, {7, 32, 2, 8}, {5, 8, 3, 5}, {4, 41, 6, 9}, {1, 32, 8, 1, 6}, {1, 9, 1, 15, 9}, {6, 64, 6, 1, 18}, {2, 31, 2, 9, 1}, {10, 16, 5, 10, 6} }; const std::vector<bool> acrossChannels = { true, false }; const std::vector<bool> normalizeVariance = { true, false }; const std::vector<double> epsilon = { 0.000000001 }; const auto MvnCases = ::testing::Combine( ::testing::ValuesIn(inputShapes), ::testing::Values(InferenceEngine::Precision::FP32), ::testing::ValuesIn(emptyReductionAxes), ::testing::ValuesIn(acrossChannels), ::testing::ValuesIn(normalizeVariance), ::testing::ValuesIn(epsilon), ::testing::Values(CommonTestUtils::DEVICE_GPU) ); INSTANTIATE_TEST_SUITE_P(smoke_CLDNN_TestsMVN, Mvn1LayerTest, MvnCases, Mvn1LayerTest::getTestCaseName); std::vector<InferenceEngine::Precision> dataPrecisions = { InferenceEngine::Precision::FP32, InferenceEngine::Precision::FP16 }; std::vector<InferenceEngine::Precision> idxPrecisions = { InferenceEngine::Precision::I32, InferenceEngine::Precision::I64 }; const std::vector<std::string> epsMode = { "inside_sqrt", "outside_sqrt" }; const std::vector<float> epsilonF = { 0.0001 }; INSTANTIATE_TEST_SUITE_P(smoke_MVN_5D, Mvn6LayerTest, ::testing::Combine( ::testing::ValuesIn(std::vector<std::vector<size_t>>{{1, 10, 5, 7, 8}, {1, 3, 8, 9, 49}}), ::testing::ValuesIn(dataPrecisions), ::testing::ValuesIn(idxPrecisions), ::testing::ValuesIn(std::vector<std::vector<int>>{{1, 2, 3, 4}, {2, 3, 4}, {-3, -2, -1}, {-1, -4, -2, -3}}), ::testing::ValuesIn(normalizeVariance), ::testing::ValuesIn(epsilonF), ::testing::ValuesIn(epsMode), ::testing::Values(CommonTestUtils::DEVICE_GPU)), Mvn6LayerTest::getTestCaseName); INSTANTIATE_TEST_SUITE_P(smoke_MVN_4D, Mvn6LayerTest, ::testing::Combine( ::testing::ValuesIn(std::vector<std::vector<size_t>>{{1, 10, 5, 17}, {1, 3, 8, 9}}), ::testing::ValuesIn(dataPrecisions), ::testing::ValuesIn(idxPrecisions), ::testing::ValuesIn(std::vector<std::vector<int>>{{1, 2, 3}, {2, 3}, {-2, -1}, {-2, -1, -3}}), ::testing::ValuesIn(normalizeVariance), ::testing::ValuesIn(epsilonF), ::testing::ValuesIn(epsMode), ::testing::Values(CommonTestUtils::DEVICE_GPU)), Mvn6LayerTest::getTestCaseName); INSTANTIATE_TEST_SUITE_P(smoke_MVN_3D, Mvn6LayerTest, ::testing::Combine( ::testing::ValuesIn(std::vector<std::vector<size_t>>{{1, 32, 17}, {1, 37, 9}}), ::testing::ValuesIn(dataPrecisions), ::testing::ValuesIn(idxPrecisions), ::testing::ValuesIn(std::vector<std::vector<int>>{{1, 2}, {2}, {-1}, {-1, -2}}), ::testing::ValuesIn(normalizeVariance), ::testing::ValuesIn(epsilonF), ::testing::ValuesIn(epsMode), ::testing::Values(CommonTestUtils::DEVICE_GPU)), Mvn6LayerTest::getTestCaseName); INSTANTIATE_TEST_SUITE_P(smoke_MVN_2D, Mvn6LayerTest, ::testing::Combine( ::testing::ValuesIn(std::vector<std::vector<size_t>>{{3, 5}, {2, 55}}), ::testing::ValuesIn(dataPrecisions), ::testing::ValuesIn(idxPrecisions), ::testing::ValuesIn(std::vector<std::vector<int>>{{1}}), ::testing::ValuesIn(normalizeVariance), ::testing::ValuesIn(epsilonF), ::testing::ValuesIn(epsMode), ::testing::Values(CommonTestUtils::DEVICE_GPU)), Mvn6LayerTest::getTestCaseName); INSTANTIATE_TEST_SUITE_P(smoke_Decomposition_1D, Mvn6LayerTest, ::testing::Combine( ::testing::ValuesIn(std::vector<std::vector<size_t>>{{3}, {9}, {55}}), ::testing::ValuesIn(dataPrecisions), ::testing::ValuesIn(idxPrecisions), ::testing::ValuesIn(std::vector<std::vector<int>>{{}}), ::testing::ValuesIn(normalizeVariance), ::testing::ValuesIn(epsilonF), ::testing::ValuesIn(epsMode), ::testing::Values(CommonTestUtils::DEVICE_GPU)), Mvn6LayerTest::getTestCaseName); INSTANTIATE_TEST_SUITE_P(smoke_Decomposition_3D, Mvn6LayerTest, ::testing::Combine( ::testing::ValuesIn(std::vector<std::vector<size_t>>{{1, 32, 17}, {1, 37, 9}}), ::testing::ValuesIn(dataPrecisions), ::testing::ValuesIn(idxPrecisions), ::testing::ValuesIn(std::vector<std::vector<int>>{{0, 1, 2}, {0}, {1}}), ::testing::ValuesIn(normalizeVariance), ::testing::ValuesIn(epsilonF), ::testing::ValuesIn(epsMode), ::testing::Values(CommonTestUtils::DEVICE_GPU)), Mvn6LayerTest::getTestCaseName); INSTANTIATE_TEST_SUITE_P(smoke_Decomposition_4D, Mvn6LayerTest, ::testing::Combine( ::testing::ValuesIn(std::vector<std::vector<size_t>>{{1, 16, 5, 8}, {2, 19, 5, 10}}), ::testing::ValuesIn(dataPrecisions), ::testing::ValuesIn(idxPrecisions), ::testing::ValuesIn(std::vector<std::vector<int>>{{0, 1, 2, 3}, {0, 1, 2}, {0, 3}, {0}, {1}, {2}, {3}}), ::testing::ValuesIn(normalizeVariance), ::testing::ValuesIn(epsilonF), ::testing::ValuesIn(epsMode), ::testing::Values(CommonTestUtils::DEVICE_GPU)), Mvn6LayerTest::getTestCaseName); INSTANTIATE_TEST_SUITE_P(smoke_Decomposition_6D, Mvn6LayerTest, ::testing::Combine( ::testing::ValuesIn(std::vector<std::vector<size_t>>{{1, 3, 5, 4, 2, 6}}), ::testing::ValuesIn(dataPrecisions), ::testing::ValuesIn(idxPrecisions), ::testing::ValuesIn(std::vector<std::vector<int>>{{0, 1, 5}, {0, 1, 2, 3}, {0, 1, 2}, {0, 3}, {0}, {3}}), ::testing::ValuesIn(normalizeVariance), ::testing::ValuesIn(epsilonF), ::testing::ValuesIn(epsMode), ::testing::Values(CommonTestUtils::DEVICE_GPU)), Mvn6LayerTest::getTestCaseName);
4,416
14,668
<gh_stars>1000+ // Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.send_tab_to_self; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.when; import androidx.test.filters.SmallTest; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import org.robolectric.annotation.Config; import org.chromium.base.test.BaseRobolectricTestRunner; import org.chromium.base.test.util.JniMocker; import org.chromium.chrome.browser.share.send_tab_to_self.SendTabToSelfAndroidBridge; import org.chromium.chrome.browser.share.send_tab_to_self.SendTabToSelfAndroidBridgeJni; import org.chromium.chrome.browser.tab.Tab; import org.chromium.content_public.browser.WebContents; /** Tests for SendTabToSelfShareActivity */ @RunWith(BaseRobolectricTestRunner.class) @Config(manifest = Config.NONE) public class SendTabToSelfShareActivityTest { @Rule public JniMocker mocker = new JniMocker(); @Rule public MockitoRule mMockitoRule = MockitoJUnit.rule(); @Mock SendTabToSelfAndroidBridge.Natives mNativeMock; @Mock private Tab mTab; @Mock private WebContents mWebContents; @Before public void setUp() { mocker.mock(SendTabToSelfAndroidBridgeJni.TEST_HOOKS, mNativeMock); } @Test @SmallTest public void testIsFeatureAvailable() { boolean expected = true; when(mTab.getWebContents()).thenReturn(mWebContents); when(mNativeMock.isFeatureAvailable(eq(mWebContents))).thenReturn(expected); boolean actual = SendTabToSelfShareActivity.featureIsAvailable(mTab); Assert.assertEquals(expected, actual); } }
709
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.beans; import java.util.*; import org.openide.nodes.Children; import org.openide.nodes.Node; import org.openide.util.RequestProcessor; /** Implements children for basic source code patterns * * @author <NAME>, <NAME> */ public final class PatternChildren extends Children.Keys<Pattern> { // static final RequestProcessor ANALYZER = new RequestProcessor("Bean patterns analyser", 1); // NOI18N private boolean wri = false; // private Listener elementListener = new Listener(this); private RequestProcessor.Task refreshTask; /** Object for finding patterns in class */ private PatternAnalyser patternAnalyser; // private final JavaClass classElement; public PatternChildren(List<Pattern> patterns /*, PatternFilters filters */ ) { resetKeys( patterns /*, filters */ ); } protected Node[] createNodes (Pattern key) { return new Node[] {createPatternNode(key)}; } private Node createPatternNode(Object key) { if (key instanceof ClassPattern ) { return new PatternNode((ClassPattern)key, wri ); } if (key instanceof IdxPropertyPattern) return new IdxPropertyPatternNode((IdxPropertyPattern) key, wri); if (key instanceof PropertyPattern) return new PropertyPatternNode((PropertyPattern) key, wri); if (key instanceof EventSetPattern) return new EventSetPatternNode((EventSetPattern) key, wri); return null; } void resetKeys( List<Pattern> patterns /*, PattenrMemberFilters filters */) { setKeys( patterns/* filters.filter(descriptions) */ ); } // Constructors ----------------------------------------------------------------------- // /** Create pattern children. The children are initilay unfiltered. // * @param classElement the atteached class. For this class we recognize the patterns // */ // // public PatternChildren (JavaClass classElement) { // this(classElement, true); // } // // public PatternChildren (JavaClass classElement, boolean isWritable ) { // this.classElement = classElement; // patternAnalyser = new PatternAnalyser( classElement ); // PropertyActionSettings.getDefault().addPropertyChangeListener(elementListener); // wri = isWritable; // } // // protected void addNotify() { // super.addNotify(); // refreshAllKeys(); // } // // /** Updates all the keys (elements) according to the current filter & // * ordering. // */ // protected void refreshAllKeys () { // scheduleRefresh(); // } // // private synchronized void scheduleRefresh() { // if (refreshTask == null) { // refreshTask = ANALYZER.create(elementListener); // } // refreshTask.schedule(200); // } // // /** Updates all the keys with given filter. Overriden to provide package access tothis method. // */ // protected void refreshKeys (int filter) { // // // Method is added or removed ve have to re-analyze the pattern abd to // // registrate Children as listener // JMIUtils.beginTrans(false); // try { // try { // elementListener.unregisterAll(); // elementListener.reassignMethodListener(this.classElement); // elementListener.reassignFieldListener(this.classElement); // elementListener.assignFeaturesListener(this.classElement); // patternAnalyser.analyzeAll(); // } finally { // JMIUtils.endTrans(); // } // } catch (JmiException e) { // ErrorManager.getDefault().notify(ErrorManager.EXCEPTION, e); // } // // setKeys(collectAllKeys()); // } // // private Collection collectAllKeys() { // List keys = new LinkedList(); // keys.addAll(getKeysOfType(PatternFilter.PROPERTY)); // keys.addAll(getKeysOfType(PatternFilter.IDXPROPERTY)); // keys.addAll(getKeysOfType(PatternFilter.EVENT_SET)); // return keys; // } // // /** Gets the pattern analyser which manages the patterns */ // PatternAnalyser getPatternAnalyser( ) { // return patternAnalyser; // } // // public void removeAll() { // elementListener.unregisterAll(); // setKeys(Collections.EMPTY_LIST); // } // // Utility methods -------------------------------------------------------------------- // protected Collection getKeysOfType (int elementType) { // // List keys = null; // // if ((elementType & PatternFilter.PROPERTY) != 0) { // keys = new ArrayList(patternAnalyser.getPropertyPatterns()); // Collections.sort( keys, new PatternComparator() ); // } // if ((elementType & PatternFilter.IDXPROPERTY) != 0) { // keys = new ArrayList(patternAnalyser.getIdxPropertyPatterns()); // Collections.sort( keys, new PatternComparator() ); // } // if ((elementType & PatternFilter.EVENT_SET) != 0) { // keys = new ArrayList(patternAnalyser.getEventSetPatterns()); // Collections.sort( keys, new PatternComparator() ); // } // // // if ((filter == null) || filter.isSorted ()) // // Collections.sort (keys, comparator); // return keys; // } // }
2,312
1,738
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ // Original file Copyright Crytek GMBH or its affiliates, used under license. #include "pch.h" #include "Serialization/ClassFactory.h" #include "Serialization/Pointers.h" #include "Serialization/IArchive.h" #include "JointNameSelector.h" #include <IEditor.h> #include <ICryPak.h> #include <QDialogButtonBox> #include <QBoxLayout> #include <QTreeView> #include <QStandardItemModel> #include <QHeaderView> #include <QLabel> #include <QLineEdit> #include <QIcon> #include <QMenu> #include <QEvent> #include <QKeyEvent> #include <QCoreApplication> #include <ICryAnimation.h> #include "IResourceSelectorHost.h" #include "../EditorCommon/DeepFilterProxyModel.h" // --------------------------------------------------------------------------- JointSelectionDialog::JointSelectionDialog(QWidget* parent) : QDialog(parent) { setWindowTitle("Choose Joint..."); setWindowIcon(QIcon("Editor/Icons/animation/bone.png")); setWindowModality(Qt::ApplicationModal); QBoxLayout* layout = new QBoxLayout(QBoxLayout::TopToBottom); setLayout(layout); QBoxLayout* filterBox = new QBoxLayout(QBoxLayout::LeftToRight); layout->addLayout(filterBox); { filterBox->addWidget(new QLabel("Filter:", this), 0); filterBox->addWidget(m_filterEdit = new QLineEdit(this), 1); connect(m_filterEdit, SIGNAL(textChanged(const QString&)), this, SLOT(onFilterChanged(const QString&))); m_filterEdit->installEventFilter(this); } QBoxLayout* infoBox = new QBoxLayout(QBoxLayout::LeftToRight); layout->addLayout(infoBox); { infoBox->addWidget(new QLabel("Skeleton:")); infoBox->addWidget(m_skeletonLabel = new QLabel(""), 1); //QFont font = m_skeletonLabel->font(); //font.setBold(true); //m_skeletonLabel->setFont(font); } m_model = new QStandardItemModel(); #if 0 m_model->setColumnCount(3); #else m_model->setColumnCount(2); #endif m_model->setHeaderData(0, Qt::Horizontal, "Joint Name", Qt::DisplayRole); m_model->setHeaderData(1, Qt::Horizontal, "Id", Qt::DisplayRole); #if 0 m_model->setHeaderData(2, Qt::Horizontal, "CRC32", Qt::DisplayRole); #endif m_filterModel = new DeepFilterProxyModel(this); m_filterModel->setSourceModel(m_model); m_filterModel->setDynamicSortFilter(true); m_tree = new QTreeView(this); //m_tree->setColumnCount(3); m_tree->setModel(m_filterModel); m_tree->header()->setStretchLastSection(false); #if QT_VERSION >= 0x50000 m_tree->header()->setSectionResizeMode(0, QHeaderView::Stretch); m_tree->header()->setSectionResizeMode(1, QHeaderView::Interactive); #if 0 m_tree->header()->setSectionResizeMode(2, QHeaderView::Interactive); #endif #else m_tree->header()->setResizeMode(0, QHeaderView::Stretch); m_tree->header()->setResizeMode(1, QHeaderView::Interactive); #if 0 m_tree->header()->setResizeMode(2, QHeaderView::Interactive); #endif #endif m_tree->header()->resizeSection(1, 40); m_tree->header()->resizeSection(2, 80); connect(m_tree, SIGNAL(activated(const QModelIndex&)), this, SLOT(onActivated(const QModelIndex&))); layout->addWidget(m_tree, 1); QDialogButtonBox* buttons = new QDialogButtonBox(this); buttons->setStandardButtons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); connect(buttons, SIGNAL(accepted()), this, SLOT(accept())); connect(buttons, SIGNAL(rejected()), this, SLOT(reject())); layout->addWidget(buttons, 0); } bool JointSelectionDialog::eventFilter(QObject* obj, QEvent* event) { if (obj == m_filterEdit && event->type() == QEvent::KeyPress) { QKeyEvent* keyEvent = (QKeyEvent*)event; if (keyEvent->key() == Qt::Key_Down || keyEvent->key() == Qt::Key_Up || keyEvent->key() == Qt::Key_PageDown || keyEvent->key() == Qt::Key_PageUp) { QCoreApplication::sendEvent(m_tree, event); return true; } } return QDialog::eventFilter(obj, event); } void JointSelectionDialog::onFilterChanged(const QString& str) { m_filterModel->setFilterString(str); m_filterModel->invalidate(); m_tree->expandAll(); QModelIndex currentSource = m_filterModel->mapToSource(m_tree->selectionModel()->currentIndex()); if (!currentSource.isValid() || !m_filterModel->matchFilter(currentSource.row(), currentSource.parent())) { QModelIndex firstMatchingIndex = m_filterModel->findFirstMatchingIndex(QModelIndex()); if (firstMatchingIndex.isValid()) { m_tree->selectionModel()->setCurrentIndex(firstMatchingIndex, QItemSelectionModel::SelectCurrent); } } } void JointSelectionDialog::onActivated(const QModelIndex& index) { m_tree->setCurrentIndex(index); accept(); } QSize JointSelectionDialog::sizeHint() const { return QSize(600, 900); } bool JointSelectionDialog::chooseJoint(QString &name, IDefaultSkeleton* skeleton) { m_skeletonLabel->setText(skeleton ? skeleton->GetModelFilePath() : "No character loaded"); if (skeleton) { QString selectedName = name; typedef std::vector<QList<QStandardItem*> > JointIDToItem; JointIDToItem jointToItem; QStandardItem* selectedItem = 0; int jointCount = skeleton->GetJointCount(); jointToItem.resize(jointCount); for (int i = 0; i < jointCount; ++i) { QString jointName = QString::fromLocal8Bit(skeleton->GetJointNameByID(i)); QList<QStandardItem*>& items = jointToItem[i]; QStandardItem* item; item = new QStandardItem(jointName); item->setEditable(false); item->setData(jointName); items.append(item); QString idStr; idStr.asprintf("%i", i); item = new QStandardItem(idStr); item->setEditable(false); item->setData(jointName); items.append(item); #if 0 QString crcStr; crcStr.sprintf("%08x", skeleton->GetJointCRC32ByID(i)); item = new QStandardItem(crcStr); item->setEditable(false); item->setData(jointName); items.append(item); #endif if (jointName == selectedName) { selectedItem = items[0]; } } for (int i = 0; i < jointCount; ++i) { int parent = skeleton->GetJointParentIDByID(i); if (size_t(parent) >= jointToItem.size()) { m_model->appendRow(jointToItem[i]); } else { jointToItem[parent][0]->appendRow(jointToItem[i]); } } if (selectedItem) { m_tree->selectionModel()->setCurrentIndex(m_filterModel->mapFromSource(m_model->indexFromItem(selectedItem)), QItemSelectionModel::SelectCurrent); } m_tree->expandAll(); } if (exec() == QDialog::Accepted && m_tree->selectionModel()->currentIndex().isValid()) { QModelIndex currentIndex = m_tree->selectionModel()->currentIndex(); QModelIndex sourceCurrentIndex = m_filterModel->mapToSource(currentIndex); QStandardItem* item = m_model->itemFromIndex(sourceCurrentIndex); if (item) { name = item->data().toString(); return true; } } return false; } // --------------------------------------------------------------------------- QString JointNameSelector(const SResourceSelectorContext& x, const QString& previousValue, IDefaultSkeleton* defaultSkeleton) { QWidget parent(x.parentWidget); parent.setWindowModality(Qt::ApplicationModal); JointSelectionDialog dialog(&parent); QString jointName = previousValue; dialog.chooseJoint(jointName, defaultSkeleton); return jointName; } REGISTER_RESOURCE_SELECTOR("Joint", JointNameSelector, "Editor/Icons/animation/bone.png") #include <CharacterTool/JointNameSelector.moc>
3,423
1,312
#include "lwip/include/lwip/init.h" #include "lwip/include/lwip/timeouts.h" #include "lwip/include/lwip/netif.h" #include "lwip/include/lwip/tcp.h" #include "lwip/include/lwip/udp.h" #include "lwip/include/lwip/ip_addr.h"
114
355
#!/usr/bin/env python3 """ The input expected is a standards-compliant GFF3 file. http://www.sequenceontology.org/gff3.shtml Example of a gene with GO annotation: AAGK01000005 . gene 161052 164192 . + . ID=0ACE4B1023C0E198886936CD6BE3869B;locus_tag=TpMuguga_03g00084 AAGK01000005 . mRNA 161052 164192 . + . ID=99A7DA3C31446D989D46A5B0C8EC5C0E;Parent=0ACE4B1023C0E198886936CD6BE3869B;locus_tag=TpMuguga_03g00084 AAGK01000005 . CDS 161337 162111 . + 0 ID=470AEE91631AFCE9DBFD1CF9BA0E7365;Parent=99A7DA3C31446D989D46A5B0C8EC5C0E AAGK01000005 . CDS 162179 163696 . + 0 ID=470AEE91631AFCE9DBFD1CF9BA0E7365;Parent=99A7DA3C31446D989D46A5B0C8EC5C0E AAGK01000005 . CDS 163868 164178 . + 0 ID=470AEE91631AFCE9DBFD1CF9BA0E7365;Parent=99A7DA3C31446D989D46A5B0C8EC5C0E AAGK01000005 . exon 163868 164192 . + . ID=B1A06E24F7020FC4E92B7F2F1099D059;Parent=99A7DA3C31446D989D46A5B0C8EC5C0E AAGK01000005 . exon 162179 163696 . + . ID=BBBED213F1613EEBE471FA356BC818E4;Parent=99A7DA3C31446D989D46A5B0C8EC5C0E AAGK01000005 . exon 161052 162111 . + . ID=BD61FC870CA44840B1817F831519608A;Parent=99A7DA3C31446D989D46A5B0C8EC5C0E AAGK01000005 . polypeptide 161052 164192 . + . ID=99A7DA3C31446D989D46A5B0C8EC5C0E;Parent=99A7DA3C31446D989D46A5B0C8EC5C0E;gene_symbol=gcs-1;product_name=Glutamate-cysteine ligase;Ontology_term=GO:0004357,GO:0006750;Dbxref=EC:6.3.2.2 Most of the other options correspond to required fields in the GAF spec. Here are those arguments and the columns they correspond to: -db : 1 OUTPUT: GO Gene Association File 2.0 (GAF) format is specified here: http://geneontology.org/page/go-annotation-file-formats This output is also appropriate for use in slimming tools such as map2slim: http://search.cpan.org/~cmungall/go-perl/scripts/map2slim LIMITATIONS: - I do not currently have support for representation of evidence_code / with_from in the GFF3, so it can't be supported here. Instead, the default evidence code column (7) will just be IEA """ import argparse import os import re import sys import time from biocode import gff def main(): parser = argparse.ArgumentParser( description='Converts GFF3 files to GO Gene Association Format (GAF)') ## output file to be written parser.add_argument('-i', '--input_file', type=str, required=True, help='Path to an input file to be read' ) parser.add_argument('-o', '--output_file', type=str, required=True, help='Path to an output file to be created' ) parser.add_argument('-go', '--go_file', type=str, required=True, help='Gene Ontology (GO) file' ) parser.add_argument('-db', '--database', type=str, required=True, help='Database issuing that IDs. Example: UniProtKB' ) parser.add_argument('-dbref', '--db_reference', type=str, required=True, help='DB reference, like PMID:2676709 (column 6)' ) parser.add_argument('-ec', '--evidence_code', type=str, required=False, default='IEA', help='Like IEA (column 7)' ) parser.add_argument('-t', '--taxon_id', type=int, required=True, help='NCBI taxon ID (column 13)' ) parser.add_argument('-ad', '--annotation_date', type=str, required=False, help='Annotation date in YYYYMMDD format. Default = GFF3 file datestamp' ) parser.add_argument('-ab', '--assign_by', type=str, required=False, help='Assign by (column 15) Defaults to --database argument value' ) args = parser.parse_args() print("INFO: Parsing GFF3 objects", file=sys.stderr) (assemblies, features) = gff.get_gff3_features(args.input_file) print("INFO: Parsing GO file", file=sys.stderr) go_lookup = parse_go_file(args.go_file) annot_date = args.annotation_date if annot_date is None: annot_date = time.strftime('%Y%m%d', time.gmtime(os.path.getmtime(args.input_file))) assign_by = args.assign_by if assign_by is None: assign_by = args.database ofh = open(args.output_file, 'wt') ofh.write("!gaf-version: 2.0\n") for assembly_id in assemblies: for gene in assemblies[assembly_id].genes(): for mRNA in gene.mRNAs(): for polypeptide in mRNA.polypeptides(): for go_annot in polypeptide.annotation.go_annotations: go_id = "GO:{0}".format(go_annot.go_id) product = None gene_sym = None if go_id not in go_lookup: raise Exception("ERROR: GO ID {0} not found in provided go.obo file".format(go_id)) if polypeptide.annotation.product_name is not None: product = polypeptide.annotation.product_name if polypeptide.annotation.gene_symbol is not None: gene_sym = polypeptide.annotation.gene_symbol # Aspect is F, P or C, depending on which component/ontology the term comes from ofh.write("{0}\t{1}\t{1}\t\t{2}\t{3}\t{4}\t\t{5}\t{6}" "\t{7}\tprotein\ttaxon:{8}\t{9}\t{10}\t" "\t\n".format(args.database, polypeptide.id, go_id, args.db_reference, args.evidence_code, go_lookup[go_id], product, gene_sym, args.taxon_id, annot_date, assign_by)) print("INFO: Conversion complete.", file=sys.stderr) def parse_go_file(path): lookup = dict() primary_id = None alt_ids = list() namespace = None for line in open(path): line = line.rstrip() # if we found a new term, store the data from the last, then reset if line.startswith('[Term]'): if primary_id is not None: lookup[primary_id] = namespace for alt_id in alt_ids: lookup[alt_id] = namespace primary_id = None alt_ids = list() namespace = None m = re.search('^id: (\S+)', line) if m: primary_id = m.group(1) else: m = re.search('^namespace: (\S+)', line) if m: if m.group(1) == 'biological_process': namespace = 'P' elif m.group(1) == 'molecular_function': namespace = 'F' elif m.group(1) == 'cellular_component': namespace = 'C' else: m = re.search('^alt_id: (\S+)', line) if m: alt_ids.append(m.group(1)) print("INFO: \t{0} terms parsed".format(len(lookup))) return lookup if __name__ == '__main__': main()
3,308
335
{ "word": "Distribution", "definitions": [ "The action of sharing something out among a number of recipients.", "The action or process of supplying goods to retailers.", "The different number of cards of each suit in a player's hand.", "The way in which something is shared out among a group or spread over an area." ], "parts-of-speech": "Noun" }
132
1,655
#ifndef CLIPARSER_HPP_ #define CLIPARSER_HPP_ #include <tinyformat/tinyformat.hpp> #include <unordered_map> #include <iostream> #include <vector> #include <string> namespace Tungsten { class CliParser { struct CliOption { char shortOpt; std::string longOpt; std::string description; bool hasParam; int token; std::string param; bool isPresent; }; std::string _programName, _usage; std::vector<CliOption> _options; std::unordered_map<int, int> _tokenToOption; std::unordered_map<char, int> _shortOpts; std::unordered_map<std::string, int> _longOpts; std::vector<std::string> _operands; void wrapString(int width, int padding, const std::string &src) const; std::vector<std::string> retrieveUtf8Args(int argc, const char *argv[]); public: CliParser(const std::string &programName, const std::string &usage = "[options] [operands]"); template<typename T1, typename... Ts> void fail(const char *fmt, const T1 &v1, const Ts &... ts) { std::cerr << _programName << ": "; tfm::format(std::cerr, fmt, v1, ts...); exit(-1); } void fail(const char *fmt) { std::cerr << _programName << ": " << fmt; exit(-1); } void printHelpText(int maxWidth = 80) const; void addOption(char shortOpt, const std::string &longOpt, const std::string &description, bool hasParam, int token); void parse(int argc, const char *argv[]); bool isPresent(int token) const; const std::string &param(int token) const; const std::vector<std::string> &operands() const { return _operands; } }; } #endif /* CLIPARSER_HPP_ */
722
892
<gh_stars>100-1000 { "schema_version": "1.2.0", "id": "GHSA-43j7-3qrg-cqxx", "modified": "2022-05-05T02:48:51Z", "published": "2022-05-05T02:48:51Z", "aliases": [ "CVE-2013-0355" ], "details": "Unspecified vulnerability in the Enterprise Manager Base Platform component in Oracle Enterprise Manager Grid Control EM Base Platform 10.2.0.5 and 192.168.3.11, and EM DB Control 172.16.17.32, 172.16.58.3, and 172.16.58.3, allows remote attackers to affect integrity via unknown vectors related to Distributed/Cross DB Features.", "severity": [ ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2013-0355" }, { "type": "WEB", "url": "http://www.mandriva.com/security/advisories?name=MDVSA-2013:150" }, { "type": "WEB", "url": "http://www.oracle.com/technetwork/topics/security/cpujan2013-1515902.html" } ], "database_specific": { "cwe_ids": [ ], "severity": "MODERATE", "github_reviewed": false } }
454
348
<gh_stars>100-1000 {"nom":"Crimolois","circ":"3ème circonscription","dpt":"Côte-d'Or","inscrits":582,"abs":347,"votants":235,"blancs":24,"nuls":7,"exp":204,"res":[{"nuance":"REM","nom":"<NAME>","voix":117},{"nuance":"FN","nom":"<NAME>","voix":87}]}
103
3,428
<gh_stars>1000+ {"id":"00118","group":"spam-2","checksum":{"type":"MD5","value":"141d803810acd9d4fc23db103dddfcd9"},"text":"From <EMAIL> Thu Aug 2 01:53:22 2001\nReturn-Path: <<EMAIL>>\nDelivered-To: yyyy<EMAIL>\nReceived: from cps_mail.entelchile.net (postmaster.cps-sa.cl\n [172.16.58.390]) by mail.netnoteinc.com (Postfix) with ESMTP id\n 27C6611410E for <<EMAIL>>; Thu, 2 Aug 2001 00:53:21 +0000\n (Eire)\nReceived: from ecis.com (pm16b.icx.net [216.82.8.17]) by\n cps_mail.entelchile.net with SMTP (Microsoft Exchange Internet Mail\n Service Version 5.5.1960.3) id QCJ6XGJ5; Wed, 1 Aug 2001 20:54:19 -0400\nMessage-Id: <<EMAIL>>\nTo: <<EMAIL>>\nFrom: <EMAIL>\nSubject: Viagra Online Now!! 219\nDate: Wed, 01 Aug 2001 20:45:33 -1600\nMIME-Version: 1.0\nContent-Transfer-Encoding: 7bit\nX-Priority: 3\nX-Msmail-Priority: Normal\n\n\n<HTML><FONT BACK=\"#ffffff\" style=\"BACKGROUND-COLOR: #ffffff\" SIZE=3 PTSIZE=12><B> VIAGRA </FONT><FONT COLOR=\"#000000\" BACK=\"#ffffff\" style=\"BACKGROUND-COLOR: #ffffff\" SIZE=2 PTSIZE=10 FAMILY=\"SANSSERIF\" FACE=\"Arial\" LANG=\"0\"></B><BR>\n<BR>\n the breakthrough medication for impotence<BR>\ndelivered to your mailbox...<BR>\n<BR>\n..without leaving your computer.<BR>\n<BR>\nSimply Click Here:<A HREF=\"http://host.1bulk-email-software.com/ch4/pharm/blue\">http://host.1bulk-email-software.com/ch4/pharm/blue</A><BR>\n<BR>\nIn less than 5 minutes you can complete the on-line consultation and in<BR>\nmany cases have the medication in 24 &nbsp;hours.<BR>\n<BR>\nSimply Click Here:<A HREF=\"http://host.1bulk-email-software.com/ch4/pharm/blue\">http://host.1bulk-email-software.com/ch4/pharm/blue</A><BR>\n&gt;From our website to your mailbox.<BR>\nOn-line consultation for treatment of compromised sexual function.<BR>\n<BR>\nConvenient...affordable....confidential.<BR>\nWe ship VIAGRA worldwide at US prices.<BR>\n<BR>\nTo Order Visit:<A HREF=\"http://host.1bulk-email-software.com/ch4/pharm/blue\">http://host.1bulk-email-software.com/ch4/pharm/blue</A><BR>\n<BR>\nThis is not a SPAM. You are receiving this because<BR>\nyou are on a list of email addresses that I have bought.<BR>\nAnd you have opted to receive information about<BR>\nbusiness opportunities. If you did not opt in to receive<BR>\ninformation on business opportunities then please accept <BR>\nour apology. To be REMOVED from this list simply reply <BR>\nwith REMOVE as the subject. And you will NEVER receive <BR>\nanother email from me.<A HREF=\"mailto:<EMAIL>\">mailto:</A><A HREF=\"mailto:<EMAIL>\"><EMAIL></A><BR>\n<BR>\n<BR>\n<BR>\n<BR>\n</FONT></HTML>\n\n\n\n"}
1,080
190,993
<filename>tensorflow/core/common_runtime/gpu/gpu_virtual_mem_allocator_test.cc<gh_stars>1000+ /* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/common_runtime/gpu/gpu_virtual_mem_allocator.h" #if CUDA_VERSION >= 10020 #include "tensorflow/core/common_runtime/device/device_id_utils.h" #include "tensorflow/core/common_runtime/gpu/gpu_id.h" #include "tensorflow/core/common_runtime/gpu/gpu_init.h" #include "tensorflow/core/platform/test.h" #include "tensorflow/core/platform/test_benchmark.h" namespace tensorflow { namespace { using ::stream_executor::gpu::GpuContext; using ::stream_executor::gpu::GpuDevicePtr; using ::stream_executor::gpu::GpuDriver; // Empirically the min allocation granularity. constexpr size_t k2MiB{2 << 20}; // Creates an allocator with 8 MiB of virtual address space. std::unique_ptr<GpuVirtualMemAllocator> CreateAllocator() { PlatformDeviceId gpu_id(0); auto executor = DeviceIdUtil::ExecutorForPlatformDeviceId(GPUMachineManager(), gpu_id) .ValueOrDie(); GpuContext* gpu_context = reinterpret_cast<GpuContext*>( executor->implementation()->GpuContextHack()); return GpuVirtualMemAllocator::Create( {}, {}, *gpu_context, gpu_id, /*virtual_address_space_size=*/4 * k2MiB, {}) .ValueOrDie(); } TEST(GpuVirtualMemAllocatorTest, SimpleAlloc) { PlatformDeviceId gpu_id(0); auto executor = DeviceIdUtil::ExecutorForPlatformDeviceId(GPUMachineManager(), gpu_id) .ValueOrDie(); GpuContext* gpu_context = reinterpret_cast<GpuContext*>( executor->implementation()->GpuContextHack()); auto allocator = GpuVirtualMemAllocator::Create( {}, {}, *gpu_context, gpu_id, /*virtual_address_space_size=*/4 * k2MiB, {}) .ValueOrDie(); size_t bytes_received; // Ignored in this test. void* gpu_block = allocator->Alloc(/*alignment=*/0, /*num_bytes=*/k2MiB, &bytes_received); ASSERT_NE(gpu_block, nullptr); constexpr size_t kBufSize{256}; void* host_mem[2] = {GpuDriver::HostAllocate(gpu_context, kBufSize), GpuDriver::HostAllocate(gpu_context, kBufSize)}; std::memset(host_mem[0], 'z', kBufSize); std::memset(host_mem[1], 0, kBufSize); GpuDevicePtr gpu_buf = reinterpret_cast<GpuDevicePtr>(gpu_block) + 2048; ASSERT_TRUE(GpuDriver::SynchronousMemcpyH2D(gpu_context, gpu_buf, host_mem[0], kBufSize) .ok()); ASSERT_TRUE(GpuDriver::SynchronousMemcpyD2H(gpu_context, host_mem[1], gpu_buf, kBufSize) .ok()); for (int i = 0; i < kBufSize; ++i) { ASSERT_EQ('z', reinterpret_cast<const char*>(host_mem[1])[i]); } } TEST(GpuVirtualMemAllocatorTest, AllocPaddedUp) { auto allocator = CreateAllocator(); size_t bytes_received; void* gpu_block = allocator->Alloc(/*alignment=*/0, /*num_bytes=*/256, &bytes_received); ASSERT_NE(gpu_block, nullptr); ASSERT_EQ(bytes_received, k2MiB); } TEST(GpuVirtualMemAllocatorTest, AllocsContiguous) { auto allocator = CreateAllocator(); size_t bytes_received; // Ignored in this test. void* first_alloc = allocator->Alloc(/*alignment=*/0, /*num_bytes=*/k2MiB, &bytes_received); ASSERT_NE(first_alloc, nullptr); void* second_alloc = allocator->Alloc( /*alignment=*/0, /*num_bytes=*/2 * k2MiB, &bytes_received); ASSERT_NE(second_alloc, nullptr); ASSERT_EQ(second_alloc, reinterpret_cast<const char*>(first_alloc) + k2MiB); void* third_alloc = allocator->Alloc(/*alignment=*/0, /*num_bytes=*/k2MiB, &bytes_received); ASSERT_NE(third_alloc, nullptr); ASSERT_EQ(third_alloc, reinterpret_cast<const char*>(second_alloc) + 2 * k2MiB); } TEST(GpuVirtualMemAllocator, OverAllocate) { auto allocator = CreateAllocator(); size_t bytes_received; // Ignored in this test. void* first_alloc = allocator->Alloc(/*alignment=*/0, /*num_bytes=*/k2MiB, &bytes_received); ASSERT_NE(first_alloc, nullptr); void* over_alloc = allocator->Alloc(/*alignment=*/0, /*num_bytes=*/4 * k2MiB, &bytes_received); ASSERT_EQ(over_alloc, nullptr); } TEST(GpuVirtualMemAllocatorTest, FreeAtEnd) { auto allocator = CreateAllocator(); size_t bytes_received; // Ignored in this test. void* first_alloc = allocator->Alloc(/*alignment=*/0, /*num_bytes=*/k2MiB, &bytes_received); ASSERT_NE(first_alloc, nullptr); void* second_alloc = allocator->Alloc(/*alignment=*/0, /*num_bytes=*/k2MiB, &bytes_received); ASSERT_NE(second_alloc, nullptr); allocator->Free(second_alloc, k2MiB); void* re_alloc = allocator->Alloc(/*alignment=*/0, /*num_bytes=*/k2MiB, &bytes_received); ASSERT_EQ(re_alloc, second_alloc); } TEST(GpuVirtualMemAllocatorTest, FreeHole) { auto allocator = CreateAllocator(); size_t bytes_received; // Ignored in this test. void* first_alloc = allocator->Alloc(/*alignment=*/0, /*num_bytes=*/k2MiB, &bytes_received); ASSERT_NE(first_alloc, nullptr); void* second_alloc = allocator->Alloc(/*alignment=*/0, /*num_bytes=*/k2MiB, &bytes_received); ASSERT_NE(second_alloc, nullptr); allocator->Free(first_alloc, k2MiB); void* third_alloc = allocator->Alloc(/*alignment=*/0, /*num_bytes=*/k2MiB, &bytes_received); ASSERT_NE(third_alloc, nullptr); // Expect that allocation still happens at the end. ASSERT_EQ(third_alloc, reinterpret_cast<const char*>(second_alloc) + k2MiB); } TEST(GpuVirtualMemAllocatorTest, FreeRange) { auto allocator = CreateAllocator(); size_t bytes_received; // Ignored in this test. void* first_alloc = allocator->Alloc(/*alignment=*/0, /*num_bytes=*/k2MiB, &bytes_received); ASSERT_NE(first_alloc, nullptr); void* second_alloc = allocator->Alloc(/*alignment=*/0, /*num_bytes=*/k2MiB, &bytes_received); ASSERT_NE(second_alloc, nullptr); void* third_alloc = allocator->Alloc(/*alignment=*/0, /*num_bytes=*/k2MiB, &bytes_received); ASSERT_NE(third_alloc, nullptr); allocator->Free(first_alloc, 3 * k2MiB); void* re_alloc = allocator->Alloc(/*alignment=*/0, /*num_bytes=*/k2MiB, &bytes_received); ASSERT_NE(re_alloc, nullptr); ASSERT_EQ(re_alloc, first_alloc); } } // namespace } // namespace tensorflow #endif
2,832
1,564
package org.modelmapper.jackson; import com.fasterxml.jackson.databind.ObjectMapper; import org.modelmapper.ModelMapper; import org.modelmapper.Module; /** * ModelMapper module for Jackson * * @author <NAME> */ public class JacksonModule implements Module { private ObjectMapper objectMapper; public JacksonModule() { this(new ObjectMapper()); } public JacksonModule(ObjectMapper objectMapper) { this.objectMapper = objectMapper; } @Override public void setupModule(ModelMapper modelMapper) { modelMapper.getConfiguration().addValueReader(new JsonNodeValueReader()); modelMapper.getConfiguration().getConverters().add(0, new PrimitiveJsonNodeConverter()); modelMapper.getConfiguration().getConverters().add(0, new ArrayNodeToCollectionConverter()); modelMapper.getConfiguration().getConverters().add(0, new CollectionToArrayNodeConverter(objectMapper)); } }
283
1,433
<reponame>gerald-yang/ubuntu-iotivity-demo /****************************************************************** * * Copyright 2015 Samsung Electronics All Rights Reserved. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************/ package com.tm.sample; import java.util.ArrayList; import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Vector; import org.iotivity.base.OcException; import org.iotivity.base.OcHeaderOption; import org.iotivity.base.OcPlatform; import org.iotivity.base.OcRepresentation; import org.iotivity.base.OcResource; import org.iotivity.base.OcResourceHandle; import org.iotivity.base.ResourceProperty; import org.iotivity.service.tm.OCStackResult; import org.iotivity.service.tm.GroupManager; import org.iotivity.service.tm.ThingsMaintenance; import org.iotivity.service.tm.GroupManager.*; import org.iotivity.service.tm.ThingsConfiguration; import org.iotivity.service.tm.ThingsConfiguration.*; import org.iotivity.service.tm.ThingsMaintenance.*; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; /* * Activity for Handling all Configuration Apis as per user's selection on the UI. * and updating of UI */ public class ConfigurationApiActivity extends Activity { private class ResourceInformation { OcResource resource = null; OcResourceHandle resourceHandle = null; } private final String LOG_TAG = "[TMSample] " + this.getClass() .getSimpleName(); private final String CONFIGURATION_COLLECTION_RESOURCE_URI = "/core/configuration/resourceset"; private final String CONFIGURATION_COLLECTION_RESOURCE_TYPE = "core.configuration.resourceset"; private final String CONFIGURATION_RESOURCE_TYPE = "oic.wk.con"; private final String MAINTENANCE_COLLECTION_RESOURCE_URI = "/core/maintenance/resourceset"; private final String MAINTENANCE_COLLECTION_RESOURCE_TYPE = "core.maintenance.resourceset"; private final String MAINTENANCE_RESOURCE_TYPE = "oic.wk.mnt"; private final String FACTORYSET_COLLECTION_RESOURCE_URI = "/core/factoryset/resourceset"; private final String FACTORYSET_COLLECTION_RESOURCE_TYPE = "core.factoryset.resourceset"; private final String FACTORYSET_RESOURCE_TYPE = "factoryset"; private final String CONFIGURATION_RESOURCE_URI = "/oic/con"; private final String MAINTENANCE_RESOURCE_URI = "/oic/mnt"; private final String FACTORYSET_RESOURCE_URI = "/factoryset"; private ListView list; private ArrayAdapter<String> configurationApis; private ArrayList<String> configurationApisList; private static int messageCount = 0; private static EditText logs; private static String logMessage = ""; private static Handler mHandler; private static Message msg; private GroupManager groupManager = null; private ThingsConfiguration thingsConfiguration = null; private ThingsMaintenance thingsMaintenance = null; private Map<String, ResourceInformation> resourceList = null; private Map<String, ResourceInformation> collectionList = null; public boolean configurationResourceFlag = false; public boolean factorysetResourceFlag = false; public boolean maintenanceResourceFlag = false; public static Context mcontext; public String region = ""; public boolean findGroupPressedFlag = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.configapis); mcontext = this; groupManager = new GroupManager(); thingsConfiguration = ThingsConfiguration.getInstance(); thingsMaintenance = ThingsMaintenance.getInstance(); // set the listeners setResourceListener(); setConfigurationListener(); setMaintenanceListener(); // Create API menu list configurationApisList = new ArrayList<String>(); logs = (EditText) findViewById(R.id.EditText); list = (ListView) findViewById(R.id.configApisList); configurationApisList.add("Find All Groups"); configurationApisList.add("Find All Resources"); configurationApisList.add("Get a Configuration Resource"); configurationApisList.add("Update Attribute (Region)"); configurationApisList.add("Factory Reset"); configurationApisList.add("Reboot"); configurationApisList.add("Get Supported Configuration Units"); configurationApis = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, configurationApisList); list.setAdapter(configurationApis); // setting the Listener for calling the APIs as per User selection list.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // Find All Groups if (position == 0) { Vector<String> resourceTypes = new Vector<String>(); resourceTypes.add(CONFIGURATION_COLLECTION_RESOURCE_TYPE); findCandidateResources(resourceTypes); logMessage = ""; messageCount = 0; messageCount++; resourceTypes.clear(); resourceTypes.add(MAINTENANCE_COLLECTION_RESOURCE_TYPE); findCandidateResources(resourceTypes); messageCount++; resourceTypes.clear(); resourceTypes.add(FACTORYSET_COLLECTION_RESOURCE_TYPE); findCandidateResources(resourceTypes); messageCount++; } else if (position == 1) { // Find All Resources if (false == findGroupPressedFlag) { displayToastMessage("Configuration collection resource does not exist!"); } else { Vector<String> resourceTypes = new Vector<String>(); resourceTypes.add(CONFIGURATION_RESOURCE_TYPE); findCandidateResources(resourceTypes); logMessage = ""; messageCount = 0; messageCount++; resourceTypes.clear(); resourceTypes.add(MAINTENANCE_RESOURCE_TYPE); findCandidateResources(resourceTypes); messageCount++; resourceTypes.clear(); resourceTypes.add(FACTORYSET_RESOURCE_TYPE); findCandidateResources(resourceTypes); messageCount++; } } else if (position == 2) { // Get Configuration getConfiguration(); } else if (position == 3) { // Update Attribute (Region) userInputDialog(); } else if (position == 4) { // Factory Reset factoryReset(); } else if (position == 5) { // Reboot reboot(); } else if (position == 6) { // Get Supported Configuration Units String configurationUnits; configurationUnits = getListOfSupportedConfigurationUnits(); Log.i(LOG_TAG, "Configuration Units:" + configurationUnits); logMessage = configurationUnits; logs.setText(""); logs.setText(logMessage); } } }); resourceList = new HashMap<String, ResourceInformation>(); collectionList = new HashMap<String, ResourceInformation>(); try { createResourceCollection(CONFIGURATION_COLLECTION_RESOURCE_URI, CONFIGURATION_COLLECTION_RESOURCE_TYPE); createResourceCollection(MAINTENANCE_COLLECTION_RESOURCE_URI, MAINTENANCE_COLLECTION_RESOURCE_TYPE); createResourceCollection(FACTORYSET_COLLECTION_RESOURCE_URI, FACTORYSET_COLLECTION_RESOURCE_TYPE); } catch (OcException e) { Log.e(LOG_TAG, "OcException occured! " + e.toString()); } // handler for updating the UI i.e. LogMessage TextBox mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case 0: logs.setText(""); logs.setText(logMessage); Log.i(LOG_TAG, logMessage); } } }; } private void userInputDialog() { ResourceInformation configurationCollection = collectionList .get(CONFIGURATION_COLLECTION_RESOURCE_URI); if (null == configurationCollection || null == configurationCollection.resource) { displayToastMessage("Configuration collection resource does not exist!"); } if (false == configurationResourceFlag) { displayToastMessage("Configuration resource does not exist!"); } else { final Dialog dialog = new Dialog(mcontext); dialog.setContentView(R.layout.userinputforregionvalue); dialog.setTitle("Enter the Region Value"); dialog.setCancelable(false); dialog.show(); Button ok = (Button) dialog.findViewById(R.id.ok); Button cancel = (Button) dialog.findViewById(R.id.cancel); ok.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { EditText regionValue = (EditText) dialog .findViewById(R.id.region); region = regionValue.getText().toString(); if (region.equalsIgnoreCase("")) { String toastmessage = "Please enter the Region Value"; displayToastMessage(toastmessage); } else { dialog.dismiss(); updateConfiguration(region); } } }); cancel.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); } } @Override public void onBackPressed() { super.onBackPressed(); // unregistering resource from the platform deleteResources(); resourceList.clear(); resourceList = null; collectionList.clear(); collectionList = null; } private void setResourceListener() { groupManager .setFindCandidateResourceListener(new IFindCandidateResourceListener() { @Override public void onResourceFoundCallback( Vector<OcResource> resources) { // TODO Auto-generated method stub Log.i(LOG_TAG, "onResourceCallback: enter"); for (int i = 0; i < resources.size(); i++) { OcResource resource = resources.get(i); String uri = resource.getUri(); String host = resource.getHost(); // Display resource information Log.i(LOG_TAG, "Resource URI:" + uri); Log.i(LOG_TAG, "Resource HOST: " + host); Log.i(LOG_TAG, "Resource types: "); logMessage += "Resource URI : " + uri + "\n"; logMessage += "Resource Host : " + host + "\n"; List<String> resourcetypes = resource .getResourceTypes(); for (int j = 0; j < resourcetypes.size(); j++) { Log.i(LOG_TAG, resourcetypes.get(j)); logMessage += "ResourceType " + (j + 1) + " : " + resourcetypes.get(j) + "\n"; } Log.i(LOG_TAG, "Interface types: "); List<String> interfacetypes = resource .getResourceInterfaces(); for (int j = 0; j < interfacetypes.size(); j++) { Log.i(LOG_TAG, interfacetypes.get(j)); logMessage += "interfacetype " + (j + 1) + " : " + interfacetypes.get(j) + "\n"; } try { if (true == uri.contains("/resourceset")) { collectionFound(resource); } else { resourceFound(resource); } } catch (OcException e) { Log.e(LOG_TAG, "OcExcepion occured! " + e.toString()); } } if (messageCount == 3) { msg = Message.obtain(); msg.what = 0; mHandler.sendMessage(msg); } } }); } private void setConfigurationListener() { thingsConfiguration .setConfigurationListener(new IConfigurationListener() { @Override public void onBootStrapCallback( Vector<OcHeaderOption> headerOptions, OcRepresentation rep, int errorValue) { Log.i(LOG_TAG, "onBootStrapCallback: enter"); } @Override public void onUpdateConfigurationsCallback( Vector<OcHeaderOption> headerOptions, OcRepresentation rep, int errorValue) { Log.i(LOG_TAG, "onUpdateConfigurationsCallback: enter"); Log.i(LOG_TAG, "Resource URI: " + rep.getUri()); if (rep.hasAttribute("n")) { logMessage += "Device Name : " + rep.getValueString("n") + "\n"; } if (rep.hasAttribute("loc")) { logMessage += "Location : " + rep.getValueString("loc") + "\n"; } if (rep.hasAttribute("locn")) { logMessage += "Location Name : " + rep.getValueString("locn") + "\n"; } if (rep.hasAttribute("r")) { logMessage += "Region : " + rep.getValueString("r") + "\n"; } if (rep.hasAttribute("c")) { logMessage += "Currency : " + rep.getValueString("c") + "\n"; } } @Override public void onGetConfigurationsCallback( Vector<OcHeaderOption> headerOptions, OcRepresentation rep, int errorValue) { Log.i(LOG_TAG, "onGetConfigurationsCallback: enter"); Log.i(LOG_TAG, "Resource URI: " + rep.getUri()); logMessage += "Resource URI : " + rep.getUri() + "\n"; if (rep.hasAttribute("n")) { logMessage += "Device Name : " + rep.getValueString("n") + "\n"; } if (rep.hasAttribute("loc")) { logMessage += "Location : " + rep.getValueString("loc") + "\n"; } if (rep.hasAttribute("locn")) { logMessage += "Location Name : " + rep.getValueString("locn") + "\n"; } if (rep.hasAttribute("r")) { logMessage += "Region : " + rep.getValueString("r") + "\n"; } if (rep.hasAttribute("c")) { logMessage += "Currency : " + rep.getValueString("c") + "\n"; } msg = Message.obtain(); msg.what = 0; mHandler.sendMessage(msg); } }); } private void setMaintenanceListener() { thingsMaintenance .setThingsMaintenanceListener(new IThingsMaintenanceListener() { @Override public void onRebootCallback( Vector<OcHeaderOption> headerOptions, OcRepresentation rep, int errorValue) { // TODO Auto-generated method stu } @Override public void onFactoryResetCallback( Vector<OcHeaderOption> headerOptions, OcRepresentation rep, int errorValue) { // TODO Auto-generated method stub } }); } /** * This method find the resources available in network. */ private void findCandidateResources(Vector<String> resourceTypes) { OCStackResult result = groupManager.findCandidateResources( resourceTypes, 5); if (OCStackResult.OC_STACK_OK != result) { Log.e(LOG_TAG, "Error while calling findCandidateResources"); String toastmessage = "findCandidateResources API returned error! [" + result + "]"; displayToastMessage(toastmessage); } if (messageCount == 1) logMessage += "API RESULT : " + result.toString() + "\n"; } /** * This method gets the configuration data from con-server. */ private void getConfiguration() { Log.i(LOG_TAG, "There are " + resourceList.size() + " servers present in network"); ResourceInformation configurationCollection = collectionList .get(CONFIGURATION_COLLECTION_RESOURCE_URI); if (null == configurationCollection || null == configurationCollection.resource) { displayToastMessage("Configuration collection resource does not exist!"); return; } if (false == configurationResourceFlag) { displayToastMessage("Configuration resource does not exist!"); return; } String name = "all"; Vector<String> configs = new Vector<String>(); configs.add(name); OCStackResult result = OCStackResult.OC_STACK_ERROR; try { result = thingsConfiguration.getConfigurations( configurationCollection.resource, configs); } catch (OcException e) { e.printStackTrace(); } if (OCStackResult.OC_STACK_OK != result) { Log.e(LOG_TAG, "getConfigurations failed!"); String toastmessage = "getConfigurations API returned error! [" + result + "]"; displayToastMessage(toastmessage); } logMessage = "API RESULT : " + result.toString() + "\n"; msg = Message.obtain(); msg.what = 0; mHandler.sendMessage(msg); } /** * This method update the configuration resource region attribute to given * value. * * @param region */ private void updateConfiguration(String region) { ResourceInformation configurationCollection = collectionList .get(CONFIGURATION_COLLECTION_RESOURCE_URI); String name = "r"; Map<String, String> configurations = new HashMap<String, String>(); try { configurations.put(name, region); } catch (Exception e) { Log.e(LOG_TAG, "Exception occured! " + e.toString()); } OCStackResult result = OCStackResult.OC_STACK_ERROR; try { result = thingsConfiguration.updateConfigurations( configurationCollection.resource, configurations); } catch (OcException e) { e.printStackTrace(); } if (OCStackResult.OC_STACK_OK != result) { Log.e(LOG_TAG, "updateConfigurations failed!"); String toastmessage = "updateConfigurations API returned error! [" + result + "]"; displayToastMessage(toastmessage); } logMessage = "API RESULT : " + result.toString() + "\n"; logMessage += "Updating region to " + region; msg = Message.obtain(); msg.what = 0; mHandler.sendMessage(msg); } /** * This method send request to reset all the configuration attribute values * to default. */ private void factoryReset() { ResourceInformation MaintenanceCollection = collectionList .get(MAINTENANCE_COLLECTION_RESOURCE_URI); if (null == MaintenanceCollection || null == MaintenanceCollection.resource) { displayToastMessage("Maintenance collection does not exist!"); return; } if (false == maintenanceResourceFlag) { displayToastMessage("Maintenance resource does not exist!"); return; } OCStackResult result = OCStackResult.values()[30]; try { result = thingsMaintenance .factoryReset(MaintenanceCollection.resource); } catch (OcException e) { e.printStackTrace(); } if (OCStackResult.OC_STACK_OK != result) { Log.e(LOG_TAG, "factoryReset failed!"); String toastmessage = "factoryReset API returned error! [" + result + "]"; displayToastMessage(toastmessage); } logMessage = "API RESULT : " + result.toString() + "\n"; msg = Message.obtain(); msg.what = 0; mHandler.sendMessage(msg); } /** * This method send request to reboot server. */ private void reboot() { ResourceInformation MaintenanceCollection = collectionList .get(MAINTENANCE_COLLECTION_RESOURCE_URI); if (null == MaintenanceCollection || null == MaintenanceCollection.resource) { displayToastMessage("Maintenance collection does not exist!"); return; } if (false == maintenanceResourceFlag) { displayToastMessage("Maintenance resource does not exist!"); return; } OCStackResult result = OCStackResult.OC_STACK_ERROR; try { result = thingsMaintenance.reboot(MaintenanceCollection.resource); } catch (OcException e) { e.printStackTrace(); } if (OCStackResult.OC_STACK_OK != result) { Log.e(LOG_TAG, "reboot failed!"); String toastmessage = "reboot API returned error! [" + result + "]"; displayToastMessage(toastmessage); } logMessage = "API RESULT : " + result.toString() + "\n"; msg = Message.obtain(); msg.what = 0; mHandler.sendMessage(msg); } /** * This method is for getting list of all supported configuration values. * Response will be in JSON format (key-value pair). */ private String getListOfSupportedConfigurationUnits() { return thingsConfiguration.getListOfSupportedConfigurationUnits(); } private void displayToastMessage(String message) { Toast toast = Toast.makeText(this, message, Toast.LENGTH_SHORT); toast.show(); Log.i(LOG_TAG, message); } private void collectionFound(OcResource resource) { String uri = resource.getUri(); ResourceInformation resourceInfo = collectionList.get(uri); if (null == resourceInfo) { Log.e(LOG_TAG, "Collection is not created!"); return; } if (null != resourceInfo.resource) { Log.e(LOG_TAG, "Collection resource already updated!"); return; } resourceInfo.resource = resource; if (3 == messageCount) { findGroupPressedFlag = true; } } /** * This callback will be invoked when the interested resource discovered in * network. */ private void resourceFound(OcResource resource) throws OcException { String uri = resource.getUri(); String host = resource.getHost(); // Check if the resource already exist in the map table ResourceInformation resourceInfo = resourceList.get(uri + host); if (null != resourceInfo) { Log.e(LOG_TAG, "Resource already exists!"); return; } // Create resource resourceInfo = new ResourceInformation(); resourceInfo.resource = resource; if (uri.equalsIgnoreCase("/oic/con")) { ResourceInformation collectionResource = collectionList .get(CONFIGURATION_COLLECTION_RESOURCE_URI); if (null == collectionResource || null == collectionResource.resourceHandle) { Log.e(LOG_TAG, "Invalid Configuration collection!"); return; } ResourceInformation resourceInfoCollection; resourceInfoCollection = collectionList .get(CONFIGURATION_COLLECTION_RESOURCE_URI); OcResourceHandle handle; handle = resourceInfoCollection.resourceHandle; resourceInfo.resourceHandle = handle; resourceInfo.resourceHandle = groupManager.bindResourceToGroup( resource, handle); resourceList.put(uri + host, resourceInfo); configurationResourceFlag = true; } else if (uri.equalsIgnoreCase("/oic/mnt")) { ResourceInformation maintenanceResource = collectionList .get(MAINTENANCE_COLLECTION_RESOURCE_URI); if (null == maintenanceResource || null == maintenanceResource.resourceHandle) { Log.e(LOG_TAG, "Invalid Configuration collection!"); return; } ResourceInformation resourceInfoCollection; resourceInfoCollection = collectionList .get(MAINTENANCE_COLLECTION_RESOURCE_URI); OcResourceHandle handle; handle = resourceInfoCollection.resourceHandle; resourceInfo.resourceHandle = handle; resourceInfo.resourceHandle = groupManager.bindResourceToGroup( resource, handle); resourceList.put(uri + host, resourceInfo); maintenanceResourceFlag = true; } else if (uri.equalsIgnoreCase("/factoryset")) { ResourceInformation factorysetResource = collectionList .get(FACTORYSET_COLLECTION_RESOURCE_URI); if (null == factorysetResource || null == factorysetResource.resourceHandle) { Log.e(LOG_TAG, "Invalid Configuration collection!"); return; } ResourceInformation resourceInfoCollection; resourceInfoCollection = collectionList .get(FACTORYSET_COLLECTION_RESOURCE_URI); OcResourceHandle handle; handle = resourceInfoCollection.resourceHandle; resourceInfo.resourceHandle = handle; resourceInfo.resourceHandle = groupManager.bindResourceToGroup( resource, handle); resourceList.put(uri + host, resourceInfo); factorysetResourceFlag = true; } else { Log.e(LOG_TAG, "Resource is of different type: " + uri); return; } } private void createResourceCollection(String uri, String typename) throws OcException { Map<String, OcResourceHandle> groupList = new HashMap<String, OcResourceHandle>(); Log.i(LOG_TAG, "createGroup: " + typename); // Check if the resource collection is already created if (null != collectionList.get(uri)) { Log.e(LOG_TAG, "Collection is already exist!"); return; } OcResourceHandle resourceHandle = null; try { resourceHandle = OcPlatform.registerResource(uri, typename, OcPlatform.BATCH_INTERFACE, null, EnumSet.of(ResourceProperty.DISCOVERABLE)); } catch (OcException e) { Log.e(LOG_TAG, "go exception"); Log.e(LOG_TAG, "RegisterResource error. " + e.getMessage()); } try { OcPlatform.bindInterfaceToResource(resourceHandle, OcPlatform.GROUP_INTERFACE); } catch (OcException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { OcPlatform.bindInterfaceToResource(resourceHandle, OcPlatform.DEFAULT_INTERFACE); } catch (OcException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (null == resourceHandle) { Log.e(LOG_TAG, " createResourceCollection : resourceHandle is NULL"); } // Add the collection resource to map table ResourceInformation resourceInfo = new ResourceInformation(); resourceInfo.resourceHandle = resourceHandle; collectionList.put(uri, resourceInfo); Log.i(LOG_TAG, "size of collectionList : " + collectionList.size()); } private void deleteResources() { Log.i(LOG_TAG, "deleteResources: enter"); try { // unregister all resources for (ResourceInformation resource : resourceList.values()) { if (null != resource.resourceHandle) { if (resource.resource.getUri().equalsIgnoreCase( CONFIGURATION_RESOURCE_URI)) { ResourceInformation collectionResource = collectionList .get(CONFIGURATION_COLLECTION_RESOURCE_URI); if (null != collectionResource && null != collectionResource.resourceHandle) { OcPlatform .unregisterResource(resource.resourceHandle); Log.i(LOG_TAG, "unregistered resource" + CONFIGURATION_COLLECTION_RESOURCE_URI); } } else if (resource.resource.getUri().equalsIgnoreCase( MAINTENANCE_RESOURCE_URI)) { ResourceInformation maintenanceResource = collectionList .get(MAINTENANCE_COLLECTION_RESOURCE_URI); if (null != maintenanceResource && null != maintenanceResource.resourceHandle) { OcPlatform .unregisterResource(resource.resourceHandle); Log.i(LOG_TAG, "unregistered resource" + CONFIGURATION_COLLECTION_RESOURCE_URI); } } else if (resource.resource.getUri().equalsIgnoreCase( FACTORYSET_RESOURCE_URI)) { ResourceInformation factorysetResource = collectionList .get(FACTORYSET_COLLECTION_RESOURCE_URI); if (null != factorysetResource && null != factorysetResource.resourceHandle) { OcPlatform .unregisterResource(resource.resourceHandle); Log.i(LOG_TAG, "unregistered resource" + CONFIGURATION_COLLECTION_RESOURCE_URI); } } } } } catch (OcException e) { Log.e(LOG_TAG, "OcException occured! " + e.toString()); } } }
17,636
11,356
<reponame>Bpowers4/turicreate<filename>src/external/boost/boost_1_68_0/libs/geometry/example/with_external_libs/x01_qt_example.cpp // Boost.Geometry (aka GGL, Generic Geometry Library) // // Copyright (c) 2007-2012 <NAME>, Amsterdam, the Netherlands. // Use, modification and distribution is subject to 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) // Qt Example // Qt is a well-known and often used platform independent windows library // To build and run this example: // 1) download (from http://qt.nokia.com), configure and make QT // 2) if necessary, adapt Qt clause in include path (note there is a Qt property sheet) #include <sstream> #include <QtGui> #include <boost/geometry/geometry.hpp> #include <boost/geometry/geometries/register/point.hpp> #include <boost/geometry/geometries/register/ring.hpp> // Adapt a QPointF such that it can be handled by Boost.Geometry BOOST_GEOMETRY_REGISTER_POINT_2D_GET_SET(QPointF, double, cs::cartesian, x, y, setX, setY) // Adapt a QPolygonF as well. // A QPolygonF has no holes (interiors) so it is similar to a Boost.Geometry ring BOOST_GEOMETRY_REGISTER_RING(QPolygonF) int main(int argc, char *argv[]) { // This usage QApplication and QLabel is adapted from // http://en.wikipedia.org/wiki/Qt_(toolkit)#Qt_hello_world QApplication app(argc, argv); // Declare a Qt polygon. The Qt Polygon can be used // in Boost.Geometry, just by its oneline registration above. QPolygonF polygon; // Use Qt to add points to polygon polygon << QPointF(10, 20) << QPointF(20, 30) << QPointF(30, 20) << QPointF(20, 10) << QPointF(10, 20); // Use Boost.Geometry e.g. to calculate area std::ostringstream out; out << "Boost.Geometry area: " << boost::geometry::area(polygon) << std::endl; // Some functionality is defined in both Qt and Boost.Geometry QPointF p(20,20); out << "Qt contains: " << (polygon.containsPoint(p, Qt::WindingFill) ? "yes" : "no") << std::endl << "Boost.Geometry within: " << (boost::geometry::within(p, polygon) ? "yes" : "no") << std::endl; // Detail: if point is ON boundary, Qt says yes, Boost.Geometry says no. // Qt defines an iterator // (which is required for of the Boost.Geometry ring-concept) // such that Boost.Geometry can use the points of this polygon QPolygonF::const_iterator it; for (it = polygon.begin(); it != polygon.end(); ++it) { // Stream Delimiter-Separated, just to show something Boost.Geometry can do out << boost::geometry::dsv(*it) << std::endl; } // Stream the polygon as well out << boost::geometry::dsv(polygon) << std::endl; // Just show what we did in a label QLabel label(out.str().c_str()); label.show(); return app.exec(); }
1,089
722
package org.ahocorasick.trie; /** * Contains the matched keyword and some payload data. * * @author <NAME> * @param <T> The type of the wrapped payload data. */ public class Payload<T> implements Comparable<Payload<T>> { private final String keyword; private final T data; public Payload(final String keyword, final T data) { super(); this.keyword = keyword; this.data = data; } public String getKeyword() { return keyword; } public T getData() { return data; } @Override public int compareTo(Payload<T> other) { return keyword.compareTo(other.getKeyword()); } }
254
17,990
<reponame>Mu-L/ice-1<filename>examples/basic-vite/build.json { "hash": false, "minify": "esbuild", "polyfill": false, "vite": true, "vendor": false, "plugins": [ "build-plugin-jsx-plus" ], "sassLoaderOptions": { "prependData": ".test{color:red}" }, "tsChecker": true, "proxy": { "/api": { "target": "http://jsonplaceholder.typicode.com", "changeOrigin": true, "pathRewrite": { "^/api": "/todos" } } } }
211
5,169
{ "name": "MLFunctionalPackage", "version": "1.0.2", "summary": "A set of map-filter-reduce tools for Objective-C", "description": "# MLFunctionalPackage\n## A set of map-filter-reduce tools for Objective-C\n\nThanks to blocks Objective-C has the potential to support functional programming style. \nThis library provides the basic map-filter-reduce library functions to further expand this opportunity.\n\n## Installation\n \nUse CocoaPods or copy those 2 files directly into the project. \n\n pod 'MLFunctionalPackage'\n\n## How to use it?\n\n #import <MLFunctionalPackage/MLFunctionalPackage.h>\n \n NSLog(@\"%@\", [[[[[NSArray rangeFrom:10 to: 21] mll_filter: ^(NSNumber *n) { \n return n.integerValue % 2 == 0; \n }] mll_map: ^(NSNumber *n) { \n return [NSString stringWithFormat:@\"%d\", n.integerValue]; \n }] mll_reduce: ^(NSString *l, NSString *r) { \n return [NSString stringWithFormat:@\"%@, %@\", l, r];\n }] stringByAppendingString: @\".\"]);", "homepage": "https://github.com/mll/MLFunctionalPackage", "license": "MIT", "authors": { "<NAME>": "<EMAIL>" }, "platforms": { "ios": "5.0" }, "source": { "git": "https://github.com/mll/MLFunctionalPackage.git", "tag": "1.0.2" }, "source_files": "*.{h,m}", "requires_arc": true }
511
649
package net.serenitybdd.screenplay.webtests.ui; import io.github.bonigarcia.wdm.WebDriverManager; import net.serenitybdd.junit.runners.SerenityRunner; import net.serenitybdd.screenplay.Actor; import net.serenitybdd.screenplay.abilities.BrowseTheWeb; import net.serenitybdd.screenplay.actions.Click; import net.serenitybdd.screenplay.actions.Open; import net.serenitybdd.screenplay.ui.Button; import net.thucydides.core.annotations.Managed; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.openqa.selenium.WebDriver; /** * Working with HTML buttons */ @RunWith(SerenityRunner.class) public class ButtonExamples { @Managed(driver = "chrome", options = "--headless") WebDriver driver; Actor sarah = Actor.named("Sarah"); @BeforeClass public static void setupDriver() { WebDriverManager.chromedriver().setup(); } @Before public void openBrowser() { sarah.can(BrowseTheWeb.with(driver)); sarah.attemptsTo( Open.url("classpath:/sample-web-site/screenplay/ui-elements/forms/multi-button-form.html") ); } @Test public void clickingOnAButtonElement() { sarah.attemptsTo( Click.on(Button.called("Cancel")) ); } @Test public void selectingAnInputFieldButtonByValue() { sarah.attemptsTo( Click.on(Button.called("Submit")) ); } @Test public void selectingAnHtmlButtonByName() { sarah.attemptsTo( Click.on(Button.called("submit-button")) ); } @Test public void selectingAnHtmlButtonByTestDataAttribute() { sarah.attemptsTo( Click.on(Button.called("submit-the-button")) ); } }
758
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.form.layoutdesign; import java.awt.Dimension; import java.awt.Point; import java.awt.Rectangle; import java.io.File; import java.io.IOException; import java.util.*; import org.openide.filesystems.FileUtil; public class ALT_BorderPositions07Test extends LayoutTestCase { private Object changeMark; public ALT_BorderPositions07Test(String name) { super(name); try { className = this.getClass().getName(); className = className.substring(className.lastIndexOf('.') + 1, className.length()); startingFormFile = FileUtil.toFileObject(new File(url.getFile() + goldenFilesPath + className + "-StartingForm.form").getCanonicalFile()); } catch (IOException ioe) { fail(ioe.toString()); } } /** * Move jScrolBar1 so it snaps at default distances from top-left corner of * the container. Bug 213124. */ public void doChanges0() { lm.setChangeRecording(true); changeMark = lm.getChangeMark(); ld.externalSizeChangeHappened(); // > UPDATE CURRENT STATE compBounds.put("Form", new Rectangle(0, 0, 504, 395)); contInterior.put("Form", new Rectangle(0, 0, 504, 395)); compBounds.put("jScrollBar1", new Rectangle(0, 29, 17, 341)); baselinePosition.put("jScrollBar1-17-341", new Integer(0)); compBounds.put("jComboBox1", new Rectangle(145, 60, 185, 20)); baselinePosition.put("jComboBox1-185-20", new Integer(14)); compBounds.put("jButton1", new Rectangle(162, 156, 126, 150)); baselinePosition.put("jButton1-126-150", new Integer(79)); compBounds.put("jLabel1", new Rectangle(355, 149, 34, 122)); baselinePosition.put("jLabel1-34-122", new Integer(65)); compBounds.put("jCheckBox1", new Rectangle(326, 273, 178, 23)); baselinePosition.put("jCheckBox1-178-23", new Integer(15)); compMinSize.put("Form", new Dimension(504, 395)); compBounds.put("Form", new Rectangle(0, 0, 504, 395)); compBounds.put("Form", new Rectangle(0, 0, 504, 395)); compBounds.put("Form", new Rectangle(0, 0, 504, 395)); compPrefSize.put("jScrollBar1", new Dimension(17, 48)); compPrefSize.put("jLabel1", new Dimension(34, 14)); compPrefSize.put("jComboBox1", new Dimension(56, 20)); prefPadding.put("jComboBox1-jButton1-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jComboBox1-jLabel1-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jLabel1-jCheckBox1-1-0-0", new Integer(2)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType compPrefSize.put("jCheckBox1", new Dimension(81, 23)); prefPadding.put("jComboBox1-jButton1-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jComboBox1-jLabel1-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType ld.updateCurrentState(); // < UPDATE CURRENT STATE prefPadding.put("jComboBox1-jButton1-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jComboBox1-jLabel1-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType // > START MOVING baselinePosition.put("jScrollBar1-17-341", new Integer(0)); { String[] compIds = new String[]{ "jScrollBar1" }; Rectangle[] bounds = new Rectangle[]{ new Rectangle(0, 29, 17, 341) }; Point hotspot = new Point(8, 127); ld.startMoving(compIds, bounds, hotspot); } // < START MOVING prefPaddingInParent.put("Form-jScrollBar1-1-0", new Integer(11)); // parentId-compId-dimension-compAlignment prefPaddingInParent.put("Form-jScrollBar1-1-1", new Integer(11)); // parentId-compId-dimension-compAlignment prefPaddingInParent.put("Form-jScrollBar1-0-0", new Integer(10)); // parentId-compId-dimension-compAlignment prefPaddingInParent.put("Form-jScrollBar1-0-1", new Integer(10)); // parentId-compId-dimension-compAlignment prefPadding.put("jScrollBar1-jComboBox1-0-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jScrollBar1-jComboBox1-0-0-1", new Integer(10)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jScrollBar1-jComboBox1-0-0-2", new Integer(10)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jScrollBar1-jComboBox1-0-0-3", new Integer(18)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jScrollBar1-jButton1-0-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jScrollBar1-jButton1-0-0-1", new Integer(10)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jScrollBar1-jButton1-0-0-2", new Integer(10)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jScrollBar1-jButton1-0-0-3", new Integer(18)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jScrollBar1-jLabel1-0-0-0", new Integer(4)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jScrollBar1-jLabel1-0-0-1", new Integer(10)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jScrollBar1-jLabel1-0-0-2", new Integer(10)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jScrollBar1-jLabel1-0-0-3", new Integer(18)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jScrollBar1-jCheckBox1-0-0-0", new Integer(2)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jScrollBar1-jCheckBox1-0-0-1", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jScrollBar1-jCheckBox1-0-0-2", new Integer(10)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jScrollBar1-jCheckBox1-0-0-3", new Integer(18)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType // > MOVE { Point p = new Point(16, 116); String containerId = "Form"; boolean autoPositioning = true; boolean lockDimension = false; Rectangle[] bounds = new Rectangle[]{ new Rectangle(10, 11, 17, 341) }; ld.move(p, containerId, autoPositioning, lockDimension, bounds); } // < MOVE prefPaddingInParent.put("Form-jScrollBar1-1-0", new Integer(11)); // parentId-compId-dimension-compAlignment prefPaddingInParent.put("Form-jScrollBar1-1-1", new Integer(11)); // parentId-compId-dimension-compAlignment prefPaddingInParent.put("Form-jScrollBar1-0-0", new Integer(10)); // parentId-compId-dimension-compAlignment prefPaddingInParent.put("Form-jScrollBar1-0-1", new Integer(10)); // parentId-compId-dimension-compAlignment prefPadding.put("jScrollBar1-jComboBox1-0-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jScrollBar1-jComboBox1-0-0-1", new Integer(10)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jScrollBar1-jComboBox1-0-0-2", new Integer(10)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jScrollBar1-jComboBox1-0-0-3", new Integer(18)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jScrollBar1-jButton1-0-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jScrollBar1-jButton1-0-0-1", new Integer(10)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jScrollBar1-jButton1-0-0-2", new Integer(10)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jScrollBar1-jButton1-0-0-3", new Integer(18)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jScrollBar1-jLabel1-0-0-0", new Integer(4)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jScrollBar1-jLabel1-0-0-1", new Integer(10)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jScrollBar1-jLabel1-0-0-2", new Integer(10)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jScrollBar1-jLabel1-0-0-3", new Integer(18)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jScrollBar1-jCheckBox1-0-0-0", new Integer(2)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jScrollBar1-jCheckBox1-0-0-1", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jScrollBar1-jCheckBox1-0-0-2", new Integer(10)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jScrollBar1-jCheckBox1-0-0-3", new Integer(18)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType // > MOVE { Point p = new Point(16, 115); String containerId = "Form"; boolean autoPositioning = true; boolean lockDimension = false; Rectangle[] bounds = new Rectangle[]{ new Rectangle(10, 11, 17, 341) }; ld.move(p, containerId, autoPositioning, lockDimension, bounds); } // < MOVE // > END MOVING prefPadding.put("jScrollBar1-jComboBox1-0-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jScrollBar1-jButton1-0-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType ld.endMoving(true); // < END MOVING ld.externalSizeChangeHappened(); // > UPDATE CURRENT STATE compBounds.put("Form", new Rectangle(0, 0, 504, 395)); contInterior.put("Form", new Rectangle(0, 0, 504, 395)); compBounds.put("jScrollBar1", new Rectangle(10, 11, 17, 341)); baselinePosition.put("jScrollBar1-17-341", new Integer(0)); compBounds.put("jComboBox1", new Rectangle(145, 60, 185, 20)); baselinePosition.put("jComboBox1-185-20", new Integer(14)); compBounds.put("jButton1", new Rectangle(162, 156, 126, 150)); baselinePosition.put("jButton1-126-150", new Integer(79)); compBounds.put("jLabel1", new Rectangle(355, 149, 34, 122)); baselinePosition.put("jLabel1-34-122", new Integer(65)); compBounds.put("jCheckBox1", new Rectangle(326, 273, 178, 23)); baselinePosition.put("jCheckBox1-178-23", new Integer(15)); compMinSize.put("Form", new Dimension(504, 395)); compBounds.put("Form", new Rectangle(0, 0, 504, 395)); prefPaddingInParent.put("Form-jScrollBar1-0-0", new Integer(10)); // parentId-compId-dimension-compAlignment compPrefSize.put("jScrollBar1", new Dimension(17, 48)); compPrefSize.put("jLabel1", new Dimension(34, 14)); compPrefSize.put("jComboBox1", new Dimension(56, 20)); prefPadding.put("jLabel1-jCheckBox1-1-0-0", new Integer(2)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType compPrefSize.put("jCheckBox1", new Dimension(81, 23)); prefPaddingInParent.put("Form-jScrollBar1-1-0", new Integer(11)); // parentId-compId-dimension-compAlignment ld.updateCurrentState(); // < UPDATE CURRENT STATE compBounds.put("Form", new Rectangle(0, 0, 504, 395)); prefPaddingInParent.put("Form-jScrollBar1-1-0", new Integer(11)); // parentId-compId-dimension-compAlignment prefPaddingInParent.put("Form-jScrollBar1-0-0", new Integer(10)); // parentId-compId-dimension-compAlignment } /** * Undo previous change. Resize jScrollBar1 slightly to the right. */ public void doChanges1() { lm.undo(changeMark, lm.getChangeMark()); compBounds.put("Form", new Rectangle(0, 0, 504, 395)); prefPaddingInParent.put("Form-jScrollBar1-1-0", new Integer(11)); // parentId-compId-dimension-compAlignment prefPaddingInParent.put("Form-jScrollBar1-0-0", new Integer(10)); // parentId-compId-dimension-compAlignment // > UPDATE CURRENT STATE compBounds.put("Form", new Rectangle(0, 0, 504, 395)); contInterior.put("Form", new Rectangle(0, 0, 504, 395)); compBounds.put("jScrollBar1", new Rectangle(0, 29, 17, 341)); baselinePosition.put("jScrollBar1-17-341", new Integer(0)); compBounds.put("jComboBox1", new Rectangle(145, 60, 185, 20)); baselinePosition.put("jComboBox1-185-20", new Integer(14)); compBounds.put("jButton1", new Rectangle(162, 156, 126, 150)); baselinePosition.put("jButton1-126-150", new Integer(79)); compBounds.put("jLabel1", new Rectangle(355, 149, 34, 122)); baselinePosition.put("jLabel1-34-122", new Integer(65)); compBounds.put("jCheckBox1", new Rectangle(326, 273, 178, 23)); baselinePosition.put("jCheckBox1-178-23", new Integer(15)); compMinSize.put("Form", new Dimension(504, 395)); compBounds.put("Form", new Rectangle(0, 0, 504, 395)); prefPadding.put("jComboBox1-jButton1-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jComboBox1-jLabel1-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType ld.updateCurrentState(); // < UPDATE CURRENT STATE compBounds.put("Form", new Rectangle(0, 0, 504, 395)); prefPadding.put("jComboBox1-jButton1-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jComboBox1-jLabel1-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType compBounds.put("Form", new Rectangle(0, 0, 504, 395)); // > START RESIZING baselinePosition.put("jScrollBar1-17-341", new Integer(0)); compPrefSize.put("jScrollBar1", new Dimension(17, 48)); { String[] compIds = new String[]{ "jScrollBar1" }; Rectangle[] bounds = new Rectangle[]{ new Rectangle(0, 29, 17, 341) }; Point hotspot = new Point(17, 128); int[] resizeEdges = new int[]{ 1, -1 }; boolean inLayout = true; ld.startResizing(compIds, bounds, hotspot, resizeEdges, inLayout); } // < START RESIZING // > MOVE { Point p = new Point(49, 132); String containerId = "Form"; boolean autoPositioning = true; boolean lockDimension = false; Rectangle[] bounds = new Rectangle[]{ new Rectangle(0, 29, 49, 341) }; ld.move(p, containerId, autoPositioning, lockDimension, bounds); } // < MOVE // > MOVE { Point p = new Point(50, 132); String containerId = "Form"; boolean autoPositioning = true; boolean lockDimension = false; Rectangle[] bounds = new Rectangle[]{ new Rectangle(0, 29, 50, 341) }; ld.move(p, containerId, autoPositioning, lockDimension, bounds); } // < MOVE // > END MOVING prefPadding.put("jScrollBar1-jComboBox1-0-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jScrollBar1-jButton1-0-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType ld.endMoving(true); // < END MOVING ld.externalSizeChangeHappened(); // > UPDATE CURRENT STATE compBounds.put("Form", new Rectangle(0, 0, 504, 395)); contInterior.put("Form", new Rectangle(0, 0, 504, 395)); compBounds.put("jScrollBar1", new Rectangle(0, 29, 50, 341)); baselinePosition.put("jScrollBar1-50-341", new Integer(0)); compBounds.put("jComboBox1", new Rectangle(145, 60, 185, 20)); baselinePosition.put("jComboBox1-185-20", new Integer(14)); compBounds.put("jButton1", new Rectangle(162, 156, 126, 150)); baselinePosition.put("jButton1-126-150", new Integer(79)); compBounds.put("jLabel1", new Rectangle(355, 149, 34, 122)); baselinePosition.put("jLabel1-34-122", new Integer(65)); compBounds.put("jCheckBox1", new Rectangle(326, 273, 178, 23)); baselinePosition.put("jCheckBox1-178-23", new Integer(15)); compMinSize.put("Form", new Dimension(504, 395)); compBounds.put("Form", new Rectangle(0, 0, 504, 395)); compPrefSize.put("jLabel1", new Dimension(34, 14)); compPrefSize.put("jComboBox1", new Dimension(56, 20)); prefPadding.put("jComboBox1-jButton1-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jComboBox1-jLabel1-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jLabel1-jCheckBox1-1-0-0", new Integer(2)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType compPrefSize.put("jCheckBox1", new Dimension(81, 23)); prefPadding.put("jComboBox1-jButton1-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jComboBox1-jLabel1-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType ld.updateCurrentState(); // < UPDATE CURRENT STATE compBounds.put("Form", new Rectangle(0, 0, 504, 395)); compBounds.put("Form", new Rectangle(0, 0, 504, 395)); prefPadding.put("jComboBox1-jButton1-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jComboBox1-jLabel1-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType compBounds.put("Form", new Rectangle(0, 0, 504, 395)); prefPadding.put("jComboBox1-jButton1-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jComboBox1-jLabel1-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType } }
8,041
575
<reponame>Ron423c/chromium<filename>chrome/browser/ui/views/crostini/crostini_force_close_view_browsertest.cc // 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 "chrome/browser/ui/views/crostini/crostini_force_close_view.h" #include "base/bind.h" #include "base/memory/weak_ptr.h" #include "base/run_loop.h" #include "chrome/browser/ui/views/crostini/crostini_dialogue_browser_test_util.h" #include "content/public/test/browser_test.h" #include "ui/views/controls/button/label_button.h" namespace crostini { namespace { class CrostiniForceCloseViewTest : public DialogBrowserTest { public: CrostiniForceCloseViewTest() : weak_ptr_factory_(this) {} void ShowUi(const std::string& name) override { dialog_widget_ = CrostiniForceCloseView::Show( "Test App", nullptr, nullptr, base::BindOnce(&CrostiniForceCloseViewTest::ForceCloseCounter, weak_ptr_factory_.GetWeakPtr())); } protected: // This method is used as the force close callback, allowing us to observe // calls to it. void ForceCloseCounter() { force_close_invocations_++; } views::Widget* dialog_widget_ = nullptr; int force_close_invocations_ = 0; base::WeakPtrFactory<CrostiniForceCloseViewTest> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(CrostiniForceCloseViewTest); }; IN_PROC_BROWSER_TEST_F(CrostiniForceCloseViewTest, FocusesForceQuit) { ShowUi(""); EXPECT_EQ( dialog_widget_->widget_delegate()->AsDialogDelegate()->GetOkButton(), dialog_widget_->GetFocusManager()->GetFocusedView()); } IN_PROC_BROWSER_TEST_F(CrostiniForceCloseViewTest, OkInvokesCallback) { ShowUi(""); EXPECT_EQ(force_close_invocations_, 0); dialog_widget_->widget_delegate()->AsDialogDelegate()->AcceptDialog(); EXPECT_EQ(force_close_invocations_, 1); } IN_PROC_BROWSER_TEST_F(CrostiniForceCloseViewTest, CancelDoesNotInvokeCallback) { ShowUi(""); EXPECT_EQ(force_close_invocations_, 0); dialog_widget_->widget_delegate()->AsDialogDelegate()->CancelDialog(); EXPECT_EQ(force_close_invocations_, 0); } IN_PROC_BROWSER_TEST_F(CrostiniForceCloseViewTest, CloseDoesNotInvokeCallback) { ShowUi(""); EXPECT_EQ(force_close_invocations_, 0); dialog_widget_->Close(); base::RunLoop().RunUntilIdle(); EXPECT_EQ(force_close_invocations_, 0); } IN_PROC_BROWSER_TEST_F(CrostiniForceCloseViewTest, InvokeUi_default) { ShowAndVerifyUi(); } } // namespace } // namespace crostini
976
443
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import torchvision import torchvision.transforms as transforms from collections import OrderedDict # =========== configuration ============== M = 1.0 alpha = 0.01 def getLoader(phase, download=False): if phase=='train': trainset = torchvision.datasets.MNIST(root='.', train=True, transform=transforms.ToTensor(), download=download) loader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True, num_workers=4) else: testset = torchvision.datasets.MNIST(root='.', train=False, transform=transforms.ToTensor(), download=download) loader = torch.utils.data.DataLoader(testset, batch_size=1, shuffle=False, num_workers=1) return loader def create_net(): net, snet = BaseNet(),Screener() return net, snet # =========== Module ==================== class BaseNet(nn.Module): def __init__(self): super(BaseNet, self).__init__() self.conv1 = nn.Conv2d(1, 10, 5) # 28-5+1=24->12 self.pool = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(10, 20, 5) # 12-5+1=8->4 self.dropout = nn.Dropout2d() self.fc1 = nn.Linear(20 * 4 * 4, 50) self.fc2 = nn.Linear(50, 10) def forward(self, x): x = self.pool(F.relu(self.conv1(x))) x = self.dropout(self.conv2(x)) x = self.pool(F.relu(x)) x = x.view(-1, 20 * 4 * 4) x = F.relu(self.fc1(x)) x = self.fc2(x) return x class Screener(nn.Module): def __init__(self): super(Screener, self).__init__() self.model = nn.Sequential(OrderedDict([ ('conv1',nn.Conv2d(1,4,3)),('act1',nn.ELU()), # 28-3+1=26 ('conv2',nn.Conv2d(4,8,3)),('act2',nn.ELU()), # 26-3+1=24 ('conv3',nn.Conv2d(8,16,3)),('act3',nn.ELU()), # 24-3+1=22 ('conv4',nn.Conv2d(16,32,3)),('act4',nn.ELU())])) # 22-3+1=20 self.fc = nn.Linear(20*20*32,1) def forward(self, x): x = self.model(x) x = x.view(-1, 20*20*32) out = F.sigmoid(self.fc(x)) return out
1,050
634
# Generated by Django 2.2.3 on 2019-09-25 19:34 from django.db import migrations def update_enrollment_osquery_release(apps, schema_editor): Enrollment = apps.get_model("osquery", "Enrollment") for enrollment in Enrollment.objects.filter(osquery_release__gt=""): enrollment.osquery_release = enrollment.osquery_release.replace("osquery-", "").replace(".pkg", "") enrollment.save() class Migration(migrations.Migration): dependencies = [ ('osquery', '0005_auto_20190227_1132'), ] operations = [ migrations.RunPython(update_enrollment_osquery_release), ]
225
3,834
<filename>engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/UnresolvedConversion.java package org.enso.interpreter.runtime.callable; import com.oracle.truffle.api.dsl.Cached; import com.oracle.truffle.api.dsl.ImportStatic; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.interop.*; import com.oracle.truffle.api.library.ExportLibrary; import com.oracle.truffle.api.library.ExportMessage; import org.enso.interpreter.Constants; import org.enso.interpreter.node.callable.InteropConversionCallNode; import org.enso.interpreter.node.callable.InteropMethodCallNode; import org.enso.interpreter.runtime.callable.atom.AtomConstructor; import org.enso.interpreter.runtime.callable.function.Function; import org.enso.interpreter.runtime.scope.ModuleScope; import org.enso.interpreter.runtime.state.data.EmptyMap; /** Simple runtime value representing a yet-unresolved by-name symbol. */ @ExportLibrary(InteropLibrary.class) public class UnresolvedConversion implements TruffleObject { private final ModuleScope scope; /** * Creates a new unresolved conversion. * * @param scope the scope in which this conversion was created */ private UnresolvedConversion(ModuleScope scope) { this.scope = scope; } /** @return the scope this symbol was used in. */ public ModuleScope getScope() { return scope; } /** * Resolves the symbol for a given hierarchy of constructors. * * <p>The constructors are checked in the first to last order, and the first match for this symbol * is returned. This is useful for certain subtyping relations, such as "any constructor is a * subtype of Any" or "Nat is a subtype of Int, is a subtype of Number". * * @param constructors the constructors hierarchy for which this symbol should be resolved * @return the resolved function definition, or null if not found */ public Function resolveFor(AtomConstructor into, AtomConstructor... constructors) { for (AtomConstructor constructor : constructors) { Function candidate = scope.lookupConversionDefinition(constructor, into); if (candidate != null) { return candidate; } } return null; } @Override public String toString() { return "UnresolvedConversion"; } @ExportMessage String toDisplayString(boolean allowSideEffects) { return this.toString(); } /** * Creates an instance of this node. * * @param name the name that is unresolved * @param scope the scope in which the lookup will occur * @return a node representing an unresolved symbol {@code name} in {@code scope} */ public static UnresolvedConversion build(ModuleScope scope) { return new UnresolvedConversion(scope); } /** * Marks this object as executable through the interop library. * * @return always true */ @ExportMessage public boolean isExecutable() { return true; } /** Implements the logic of executing {@link UnresolvedConversion} through the interop library. */ @ExportMessage @ImportStatic(Constants.CacheSizes.class) public static class Execute { @Specialization static Object doDispatch( UnresolvedConversion conversion, Object[] arguments, @Cached InteropConversionCallNode interopConversionCallNode) throws ArityException, UnsupportedTypeException, UnsupportedMessageException { return interopConversionCallNode.execute(conversion, EmptyMap.create(), arguments); } } }
1,102
575
<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. #include "components/dom_distiller/core/page_features.h" #include <stddef.h> #include <memory> #include <string> #include "base/json/json_reader.h" #include "third_party/re2/src/re2/re2.h" #include "url/gurl.h" namespace dom_distiller { /* This code needs to derive features in the same way and order in which they * are derived when training the model. Parts of that code are reproduced in the * comments below. */ namespace { std::string GetLastSegment(const std::string& path) { // return re.search('[^/]*\/?$', path).group(0) if (path.size() == 0) return ""; if (path.size() == 1) { DCHECK(path[0] == '/'); return path; } size_t start = path.rfind("/", path.size() - 2); return start == std::string::npos ? "" : path.substr(start + 1); } int CountMatches(const std::string& s, const std::string& p) { // return len(re.findall(p, s)) re2::StringPiece sp(s); re2::RE2 regexp(p); int count = 0; while (re2::RE2::FindAndConsume(&sp, regexp)) count++; return count; } int GetWordCount(const std::string& s) { return CountMatches(s, "\\w+"); } bool Contains(const std::string& n, const std::string& h) { return h.find(n) != std::string::npos; } bool EndsWith(const std::string& t, const std::string& s) { return s.size() >= t.size() && s.compare(s.size() - t.size(), std::string::npos, t) == 0; } } // namespace int kDerivedFeaturesCount = 29; std::vector<double> CalculateDerivedFeatures(bool isOGArticle, const GURL& url, double numElements, double numAnchors, double numForms, const std::string& innerText, const std::string& textContent, const std::string& innerHTML) { // In the training pipeline, the strings are explicitly encoded in utf-8 (as // they are here). const std::string& path = url.path(); int innerTextWords = GetWordCount(innerText); int textContentWords = GetWordCount(textContent); int innerHTMLWords = GetWordCount(innerHTML); std::vector<double> features; // 'opengraph', opengraph, features.push_back(isOGArticle); // 'forum', 'forum' in path, features.push_back(Contains("forum", path)); // 'index', 'index' in path, features.push_back(Contains("index", path)); // 'view', 'view' in path, features.push_back(Contains("view", path)); // 'asp', '.asp' in path, features.push_back(Contains(".asp", path)); // 'phpbb', 'phpbb' in path, features.push_back(Contains("phpbb", path)); // 'php', path.endswith('.php'), features.push_back(EndsWith(".php", path)); // 'pathlength', len(path), features.push_back(path.size()); // 'domain', len(path) < 2, features.push_back(path.size() < 2); // 'pathcomponents', CountMatches(path, r'\/.'), features.push_back(CountMatches(path, "\\/.")); // 'slugdetector', CountMatches(path, r'[^\w/]'), features.push_back(CountMatches(path, "[^\\w/]")); // 'pathnumbers', CountMatches(path, r'\d+'), features.push_back(CountMatches(path, "\\d+")); // 'lastSegmentLength', len(GetLastSegment(path)), features.push_back(GetLastSegment(path).size()); // 'formcount', numForms, features.push_back(numForms); // 'anchorcount', numAnchors, features.push_back(numAnchors); // 'elementcount', numElements, features.push_back(numElements); // 'anchorratio', float(numAnchors) / max(1, numElements), features.push_back(double(numAnchors) / std::max<double>(1, numElements)); // 'innertextlength', len(innerText), features.push_back(innerText.size()); // 'textcontentlength', len(textContent), features.push_back(textContent.size()); // 'innerhtmllength', len(innerHTML), features.push_back(innerHTML.size()); // 'innertextlengthratio', float(len(innerText)) / max(1, len(innerHTML)), features.push_back(double(innerText.size()) / std::max<double>(1.0, innerHTML.size())); // 'textcontentlengthratio', float(len(textContent)) / max(1, len(innerHTML)), features.push_back(double(textContent.size()) / std::max<double>(1.0, innerHTML.size())); // 'innertexttextcontentlengthratio', // float(len(innerText)) / max(1, len(textContent)), features.push_back(double(innerText.size()) / std::max<double>(1.0, textContent.size())); // 'innertextwordcount', innerTextWords, features.push_back(innerTextWords); // 'textcontentwordcount', textContentWords, features.push_back(textContentWords); // 'innerhtmlwordcount', innerHTMLWords, features.push_back(innerHTMLWords); // 'innertextwordcountratio', float(innerTextWords) / max(1, innerHTMLWords), features.push_back(double(innerTextWords) / std::max<int>(1.0, innerHTMLWords)); // 'textcontentwordcountratio', // float(textContentWords) / max(1, innerHTMLWords), features.push_back(double(textContentWords) / std::max<int>(1.0, innerHTMLWords)); // 'innertexttextcontentwordcountratio', // float(innerTextWords) / max(1, textContentWords), features.push_back(double(innerTextWords) / std::max<int>(1.0, textContentWords)); return features; } std::vector<double> CalculateDerivedFeaturesFromJSON( const base::Value* stringified_json) { std::string stringified; if (!stringified_json->GetAsString(&stringified)) { return std::vector<double>(); } std::unique_ptr<base::Value> json = base::JSONReader::ReadDeprecated(stringified); if (!json) { return std::vector<double>(); } const base::DictionaryValue* dict; if (!json->GetAsDictionary(&dict)) { return std::vector<double>(); } bool isOGArticle = false; std::string url, innerText, textContent, innerHTML; double numElements = 0.0, numAnchors = 0.0, numForms = 0.0; if (!(dict->GetBoolean("opengraph", &isOGArticle) && dict->GetString("url", &url) && dict->GetDouble("numElements", &numElements) && dict->GetDouble("numAnchors", &numAnchors) && dict->GetDouble("numForms", &numForms) && dict->GetString("innerText", &innerText) && dict->GetString("textContent", &textContent) && dict->GetString("innerHTML", &innerHTML))) { return std::vector<double>(); } GURL parsed_url(url); if (!parsed_url.is_valid()) { return std::vector<double>(); } return CalculateDerivedFeatures(isOGArticle, parsed_url, numElements, numAnchors, numForms, innerText, textContent, innerHTML); } std::vector<double> CalculateDerivedFeatures(bool openGraph, const GURL& url, unsigned elementCount, unsigned anchorCount, unsigned formCount, double mozScore, double mozScoreAllSqrt, double mozScoreAllLinear) { const std::string& path = url.path(); std::vector<double> features; // 'opengraph', opengraph, features.push_back(openGraph); // 'forum', 'forum' in path, features.push_back(Contains("forum", path)); // 'index', 'index' in path, features.push_back(Contains("index", path)); // 'search', 'search' in path, features.push_back(Contains("search", path)); // 'view', 'view' in path, features.push_back(Contains("view", path)); // 'archive', 'archive' in path, features.push_back(Contains("archive", path)); // 'asp', '.asp' in path, features.push_back(Contains(".asp", path)); // 'phpbb', 'phpbb' in path, features.push_back(Contains("phpbb", path)); // 'php', path.endswith('.php'), features.push_back(EndsWith(".php", path)); // 'pathLength', len(path), features.push_back(path.size()); // 'domain', len(path) < 2, features.push_back(path.size() < 2); // 'pathComponents', CountMatches(path, r'\/.'), features.push_back(CountMatches(path, "\\/.")); // 'slugDetector', CountMatches(path, r'[^\w/]'), features.push_back(CountMatches(path, "[^\\w/]")); // 'pathNumbers', CountMatches(path, r'\d+'), features.push_back(CountMatches(path, "\\d+")); // 'lastSegmentLength', len(GetLastSegment(path)), features.push_back(GetLastSegment(path).size()); // 'formCount', numForms, features.push_back(formCount); // 'anchorCount', numAnchors, features.push_back(anchorCount); // 'elementCount', numElements, features.push_back(elementCount); // 'anchorRatio', float(numAnchors) / max(1, numElements), features.push_back(double(anchorCount) / std::max<double>(1, elementCount)); // 'mozScore' features.push_back(mozScore); // 'mozScoreAllSqrt' features.push_back(mozScoreAllSqrt); // 'mozScoreAllLinear' features.push_back(mozScoreAllLinear); return features; } } // namespace dom_distiller
3,861
5,169
{ "name": "SessionSodium", "version": "0.9.1", "swift_versions": "5.0", "license": { "type": "ISC", "file": "LICENSE" }, "summary": "Swift-Sodium provides a safe and easy to use interface to perform common cryptographic operations on iOS and OSX.", "homepage": "https://github.com/loki-project/session-ios-swift-sodium", "social_media_url": "https://twitter.com/jedisct1", "authors": { "<NAME>": "" }, "source": { "git": "https://github.com/loki-project/session-ios-swift-sodium.git", "tag": "0.9.1" }, "platforms": { "ios": "9.0", "osx": "10.11", "watchos": "5.0" }, "source_files": "Sodium/**/*.{swift,h}", "private_header_files": "Sodium/libsodium/*.h", "pod_target_xcconfig": { "SWIFT_INCLUDE_PATHS": "$(inherited) \"${PODS_XCFRAMEWORKS_BUILD_DIR}/Clibsodium\"" }, "user_target_xcconfig": { "SWIFT_INCLUDE_PATHS": "$(inherited) \"${PODS_XCFRAMEWORKS_BUILD_DIR}/Clibsodium\"" }, "requires_arc": true, "vendored_frameworks": "Clibsodium.xcframework", "swift_version": "5.0" }
483
848
<gh_stars>100-1000 /* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef TENSORFLOW_CORE_PLATFORM_PLATFORM_STRINGS_H_ #define TENSORFLOW_CORE_PLATFORM_PLATFORM_STRINGS_H_ // This header defines the macro TF_PLATFORM_STRINGS() which should be used // once in each dynamically loadable TensorFlow module. It embeds static // strings into the compilation unit that allow TensorFlow to determine what // compilation options were in effect when the compilation unit was built. All // compilation units within the same dynamically loadable library should be // built with the same options (or at least, the strings should be embedded in // the compilation unit built with the most restrictive options). // The platform strings embedded into a binary may be retrieved with the // GetPlatformStrings function. // Rationale: // We wish to load only those libraries that this CPU can execute. For // example, we should not load a library compiled with avx256 instructions on a // CPU that cannot execute them. // // One might think that one could dlopen() the library, and call a routine that // would return which cpu type it was compiled for. Alas, this does not work, // because at dlopen() time, a library containing C++ will execute constructors // of class variables with static storage class. Even code that looks // innocuous may use optional platform-specific instructions. For example, // the fastest way to zero a region of memory might use optional instructions. // // One might think one could run a tool such as "objdump" to read flags from // the libraries' headers, or perhaps disassemble each library to look for // particular instructions. Unfortunately, the desired flags are not present // in the headers, and disassembly can be prohibitively slow ("objdump -d" is // very slow, for example). Moreover, a tool to examine the library may not // be present on the system unless the user has installed special packages (for // example, on Windows). // // Instead, we adopt a crude but straightforward solution: We require // developers to use the macro TF_PLATFORM_STRINGS() in their library, to // embed the compilation options as constant strings. The compiler's // predefined macros pick which strings are included. We then search for the // strings in the files, and then dlopen() only those libraries that have or // lack strings as needed. // // We adopt the approach of placing in the binary a fairly raw copy of the // predefined macros, rather than trying to interpret them in complex ways at // compile time. This allows the loading binary to alter its interpretation of // the strings without library developers having to recompile. #include <stdio.h> #include <string> #include <vector> // Aside from the header guard, the internal macros defined here have the form: // TF_PLAT_STR_* // If a macro is removed from the list of tested macros, the major version in // the following version number should be incremented, and the minor version // set to zero. Otherwise, if a macro is added to the list of tested macros, // the minor number should be incremented. #define TF_PLAT_STR_VERSION_ "1.0" // Prefix of each option string indicator in the binary. // After the prefix, such strings have the form: // [A-Za-z_0-9]=<value> // followed by a terminating nul. To simplify searching, this prefix is all // ASCII, starts with a nul, and contains no character twice. #define TF_PLAT_STR_MAGIC_PREFIX_ "\0S\\s\":^p*L}" // A helper macro for TF_PLAT_STR_AS_STR_(). #define TF_PLAT_STR_STR_1_(x) #x // Yield a constant string corresponding to x, after macro expansion. #define TF_PLAT_STR_AS_STR_(x) TF_PLAT_STR_STR_1_(x) // An empty definition to make lists more uniform. #define TF_PLAT_STR_TERMINATOR_ // TF_PLAT_STR_(x) introduces a constant string indicating whether a // particular compilation option has been turned on. // // In gcc and clang, we might imagine using something like // #define TF_PLAT_STR_(x) \ // (sizeof (#x) != sizeof (TF_PLAT_STR_AS_STR_ (x))? \ // TF_PLAT_STR_MAGIC_PREFIX_ #x "=" TF_PLAT_STR_AS_STR_ (x) : \ // TF_PLAT_STR_MAGIC_PREFIX_ #x "=0"), // but some compilers (notably MSVC) place both "foo" and "bar" in the binary // when presented with // (true? "foo" : "bar") // so we must use #if to select the strings we need, which is rather verbose. #define TF_PLAT_STR_(x) TF_PLAT_STR_MAGIC_PREFIX_ #x "=" TF_PLAT_STR_AS_STR_(x) // Include the #if machinery that sets the macros used below. // platform_strings_computed.h can be generated by filtering this header file // through: // awk ' // header == "" { print; } // /\*\// && header == "" { // print "// Generated from platform_strings.h."; // print ""; // print "#ifndef TENSORFLOW_CORE_PLATFORM_PLATFORM_STRINGS_COMPUTED_H_"; // print "#define TENSORFLOW_CORE_PLATFORM_PLATFORM_STRINGS_COMPUTED_H_"; // print ""; // header = 1; // } // /^#define TF_PLAT_STR_LIST_[a-zA-Z0-9_]*\(\) *\\$/ { active = 1; } // /TF_PLAT_STR_TERMINATOR_/ { active = 0; } // /^ *TF_PLAT_STR_[A-Za-z0-9_]* *\\$/ && active { // x = $0; // sub(/^ *TF_PLAT_STR_/, "", x); // sub(/ *\\$/, "", x); // printf ("#if defined(%s)\n", x); // printf ("#define TF_PLAT_STR_%s TF_PLAT_STR_(%s)\n", x, x); // printf ("#else\n"); // printf ("#define TF_PLAT_STR_%s\n", x); // printf ("#endif\n"); // } // END { // print ""; // print "#endif // TENSORFLOW_CORE_PLATFORM_PLATFORM_STRINGS_COMPUTED_H_"; // }' #include "tensorflow/core/platform/platform_strings_computed.h" // clang-format butchers the following lines. // clang-format off // x86_64 and x86_32 optional features. #define TF_PLAT_STR_LIST___x86_64__() \ TF_PLAT_STR__M_IX86_FP \ TF_PLAT_STR__NO_PREFETCHW \ TF_PLAT_STR___3dNOW_A__ \ TF_PLAT_STR___3dNOW__ \ TF_PLAT_STR___ABM__ \ TF_PLAT_STR___ADX__ \ TF_PLAT_STR___AES__ \ TF_PLAT_STR___AVX2__ \ TF_PLAT_STR___AVX512BW__ \ TF_PLAT_STR___AVX512CD__ \ TF_PLAT_STR___AVX512DQ__ \ TF_PLAT_STR___AVX512ER__ \ TF_PLAT_STR___AVX512F__ \ TF_PLAT_STR___AVX512IFMA__ \ TF_PLAT_STR___AVX512PF__ \ TF_PLAT_STR___AVX512VBMI__ \ TF_PLAT_STR___AVX512VL__ \ TF_PLAT_STR___AVX__ \ TF_PLAT_STR___BMI2__ \ TF_PLAT_STR___BMI__ \ TF_PLAT_STR___CLFLUSHOPT__ \ TF_PLAT_STR___CLZERO__ \ TF_PLAT_STR___F16C__ \ TF_PLAT_STR___FMA4__ \ TF_PLAT_STR___FMA__ \ TF_PLAT_STR___FP_FAST_FMA \ TF_PLAT_STR___FP_FAST_FMAF \ TF_PLAT_STR___FSGSBASE__ \ TF_PLAT_STR___FXSR__ \ TF_PLAT_STR___LWP__ \ TF_PLAT_STR___LZCNT__ \ TF_PLAT_STR___MMX__ \ TF_PLAT_STR___MWAITX__ \ TF_PLAT_STR___PCLMUL__ \ TF_PLAT_STR___PKU__ \ TF_PLAT_STR___POPCNT__ \ TF_PLAT_STR___PRFCHW__ \ TF_PLAT_STR___RDRND__ \ TF_PLAT_STR___RDSEED__ \ TF_PLAT_STR___RTM__ \ TF_PLAT_STR___SHA__ \ TF_PLAT_STR___SSE2_MATH__ \ TF_PLAT_STR___SSE2__ \ TF_PLAT_STR___SSE_MATH__ \ TF_PLAT_STR___SSE__ \ TF_PLAT_STR___SSE3__ \ TF_PLAT_STR___SSE4A__ \ TF_PLAT_STR___SSE4_1__ \ TF_PLAT_STR___SSE4_2__ \ TF_PLAT_STR___SSSE3__ \ TF_PLAT_STR___TBM__ \ TF_PLAT_STR___XOP__ \ TF_PLAT_STR___XSAVEC__ \ TF_PLAT_STR___XSAVEOPT__ \ TF_PLAT_STR___XSAVES__ \ TF_PLAT_STR___XSAVE__ \ TF_PLAT_STR_TERMINATOR_ // PowerPC (64- and 32-bit) optional features. #define TF_PLAT_STR_LIST___powerpc64__() \ TF_PLAT_STR__SOFT_DOUBLE \ TF_PLAT_STR__SOFT_FLOAT \ TF_PLAT_STR___ALTIVEC__ \ TF_PLAT_STR___APPLE_ALTIVEC__ \ TF_PLAT_STR___CRYPTO__ \ TF_PLAT_STR___FLOAT128_HARDWARE__ \ TF_PLAT_STR___FLOAT128_TYPE__ \ TF_PLAT_STR___FP_FAST_FMA \ TF_PLAT_STR___FP_FAST_FMAF \ TF_PLAT_STR___HTM__ \ TF_PLAT_STR___NO_FPRS__ \ TF_PLAT_STR___NO_LWSYNC__ \ TF_PLAT_STR___POWER8_VECTOR__ \ TF_PLAT_STR___POWER9_VECTOR__ \ TF_PLAT_STR___PPC405__ \ TF_PLAT_STR___QUAD_MEMORY_ATOMIC__ \ TF_PLAT_STR___RECIPF__ \ TF_PLAT_STR___RECIP_PRECISION__ \ TF_PLAT_STR___RECIP__ \ TF_PLAT_STR___RSQRTEF__ \ TF_PLAT_STR___RSQRTE__ \ TF_PLAT_STR___TM_FENCE__ \ TF_PLAT_STR___UPPER_REGS_DF__ \ TF_PLAT_STR___UPPER_REGS_SF__ \ TF_PLAT_STR___VEC__ \ TF_PLAT_STR___VSX__ \ TF_PLAT_STR_TERMINATOR_ // aarch64 and 32-bit arm optional features #define TF_PLAT_STR_LIST___aarch64__() \ TF_PLAT_STR___ARM_ARCH \ TF_PLAT_STR___ARM_FEATURE_CLZ \ TF_PLAT_STR___ARM_FEATURE_CRC32 \ TF_PLAT_STR___ARM_FEATURE_CRC32 \ TF_PLAT_STR___ARM_FEATURE_CRYPTO \ TF_PLAT_STR___ARM_FEATURE_DIRECTED_ROUNDING \ TF_PLAT_STR___ARM_FEATURE_DSP \ TF_PLAT_STR___ARM_FEATURE_FMA \ TF_PLAT_STR___ARM_FEATURE_IDIV \ TF_PLAT_STR___ARM_FEATURE_LDREX \ TF_PLAT_STR___ARM_FEATURE_NUMERIC_MAXMIN \ TF_PLAT_STR___ARM_FEATURE_QBIT \ TF_PLAT_STR___ARM_FEATURE_QRDMX \ TF_PLAT_STR___ARM_FEATURE_SAT \ TF_PLAT_STR___ARM_FEATURE_SIMD32 \ TF_PLAT_STR___ARM_FEATURE_UNALIGNED \ TF_PLAT_STR___ARM_FP \ TF_PLAT_STR___ARM_NEON_FP \ TF_PLAT_STR___ARM_NEON__ \ TF_PLAT_STR___ARM_WMMX \ TF_PLAT_STR___IWMMXT2__ \ TF_PLAT_STR___IWMMXT__ \ TF_PLAT_STR___VFP_FP__ \ TF_PLAT_STR_TERMINATOR_ // Generic features, including indication of architecture and OS. // The _M_* macros are defined by Visual Studio. // It doesn't define __LITTLE_ENDIAN__ or __BYTE_ORDER__; // Windows is assumed to be little endian. #define TF_PLAT_STR_LIST___generic__() \ TF_PLAT_STR_TARGET_IPHONE_SIMULATOR \ TF_PLAT_STR_TARGET_OS_IOS \ TF_PLAT_STR_TARGET_OS_IPHONE \ TF_PLAT_STR__MSC_VER \ TF_PLAT_STR__M_ARM \ TF_PLAT_STR__M_ARM64 \ TF_PLAT_STR__M_ARM_ARMV7VE \ TF_PLAT_STR__M_ARM_FP \ TF_PLAT_STR__M_IX86 \ TF_PLAT_STR__M_X64 \ TF_PLAT_STR__WIN32 \ TF_PLAT_STR__WIN64 \ TF_PLAT_STR___ANDROID__ \ TF_PLAT_STR___APPLE__ \ TF_PLAT_STR___BYTE_ORDER__ \ TF_PLAT_STR___CYGWIN__ \ TF_PLAT_STR___FreeBSD__ \ TF_PLAT_STR___LITTLE_ENDIAN__ \ TF_PLAT_STR___NetBSD__ \ TF_PLAT_STR___OpenBSD__ \ TF_PLAT_STR_____MSYS__ \ TF_PLAT_STR___aarch64__ \ TF_PLAT_STR___alpha__ \ TF_PLAT_STR___arm__ \ TF_PLAT_STR___i386__ \ TF_PLAT_STR___i686__ \ TF_PLAT_STR___ia64__ \ TF_PLAT_STR___linux__ \ TF_PLAT_STR___mips32__ \ TF_PLAT_STR___mips64__ \ TF_PLAT_STR___powerpc64__ \ TF_PLAT_STR___powerpc__ \ TF_PLAT_STR___riscv___ \ TF_PLAT_STR___s390x__ \ TF_PLAT_STR___sparc64__ \ TF_PLAT_STR___sparc__ \ TF_PLAT_STR___x86_64__ \ TF_PLAT_STR_TERMINATOR_ #if !defined(__x86_64__) && !defined(_M_X64) && \ !defined(__i386__) && !defined(_M_IX86) #undef TF_PLAT_STR_LIST___x86_64__ #define TF_PLAT_STR_LIST___x86_64__() #endif #if !defined(__powerpc64__) && !defined(__powerpc__) #undef TF_PLAT_STR_LIST___powerpc64__ #define TF_PLAT_STR_LIST___powerpc64__() #endif #if !defined(__aarch64__) && !defined(_M_ARM64) && \ !defined(__arm__) && !defined(_M_ARM) #undef TF_PLAT_STR_LIST___aarch64__ #define TF_PLAT_STR_LIST___aarch64__() #endif // Macro to be used in each dynamically loadable library. // // The BSS global variable tf_cpu_option_global and the class // instance tf_cpu_option_avoid_omit_class are needed to prevent // compilers/linkers such as clang from omitting the static variable // tf_cpu_option[], which would otherwise appear to be unused. We cannot make // tf_cpu_option[] global, because we then might get multiply-defined symbols // if TF_PLAT_STR() is used twice in the same library. // (tf_cpu_option_global doesn't see such errors because it is // defined in BSS, so multiple definitions are combined by the linker.) gcc's // __attribute__((used)) is insufficient because it seems to be ignored by // linkers. #define TF_PLATFORM_STRINGS() \ static const char tf_cpu_option[] = \ TF_PLAT_STR_MAGIC_PREFIX_ "TF_PLAT_STR_VERSION=" TF_PLAT_STR_VERSION_ \ TF_PLAT_STR_LIST___x86_64__() \ TF_PLAT_STR_LIST___powerpc64__() \ TF_PLAT_STR_LIST___aarch64__() \ TF_PLAT_STR_LIST___generic__() \ ; \ const char *tf_cpu_option_global; \ namespace { \ class TFCPUOptionHelper { \ public: \ TFCPUOptionHelper() { \ /* Compilers/linkers remove unused variables aggressively. The */ \ /* following gyrations subvert most such optimizations. */ \ tf_cpu_option_global = tf_cpu_option; \ /* Nothing is printed because the string starts with a nul. */ \ printf("%s", tf_cpu_option); \ } \ } tf_cpu_option_avoid_omit_class; \ } /* anonymous namespace */ // clang-format on namespace tensorflow { class Status; // Retrieves the platform strings from the file at the given path and appends // them to the given vector. If the returned int is non-zero, an error occurred // reading the file and vector may or may not be modified. The returned error // code is suitable for use with strerror(). int GetPlatformStrings(const std::string& path, std::vector<std::string>* found); } // namespace tensorflow #endif // TENSORFLOW_CORE_PLATFORM_PLATFORM_STRINGS_H_
13,103
1,561
/* * Copyright (c) 2015 Cossack Labs Limited * * 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 secure_session.h * @brief Secure session is a lightweight mechanism to secure any network communications (both * private and public networks including Internet) */ #ifndef THEMIS_SECURE_SESSION_H #define THEMIS_SECURE_SESSION_H /* * ssize_t is POSIX-specific (as is <sys/types.h>). * Explicitly define ssize_t as signed counterpart of size_t on Windows. */ #if _WIN32 #include <stddef.h> #include <stdint.h> #ifdef _WIN64 typedef signed __int64 ssize_t; #else typedef signed int ssize_t; #endif #else #include <sys/types.h> #endif #include <soter/soter.h> #include <themis/themis_api.h> #include <themis/themis_error.h> #ifdef __cplusplus extern "C" { #endif /** * @addtogroup THEMIS * @{ * @defgroup THEMIS_SECURE_SESSION secure session * @brief Secure session is a lightweight mechanism to secure any network communications (both * private and public networks including Internet) * @{ */ /** @brief idle state define */ #define STATE_IDLE 0 /** @brief negotiating state define */ #define STATE_NEGOTIATING 1 /** @brief established state define */ #define STATE_ESTABLISHED 2 /** @brief send data callbeck tyoedef*/ typedef ssize_t (*send_protocol_data_callback)(const uint8_t* data, size_t data_length, void* user_data); /** @brief receive data callbeck tyoedef*/ typedef ssize_t (*receive_protocol_data_callback)(uint8_t* data, size_t data_length, void* user_data); /** @brief state change callbeck tyoedef*/ typedef void (*protocol_state_changed_callback)(int event, void* user_data); /** @brief get public key by id callbeck tyoedef*/ typedef int (*get_public_key_for_id_callback)( const void* id, size_t id_length, void* key_buffer, size_t key_buffer_length, void* user_data); struct secure_session_user_callbacks_type { send_protocol_data_callback send_data; receive_protocol_data_callback receive_data; protocol_state_changed_callback state_changed; get_public_key_for_id_callback get_public_key_for_id; void* user_data; }; typedef struct secure_session_user_callbacks_type secure_session_user_callbacks_t; typedef struct secure_session_type secure_session_t; THEMIS_API secure_session_t* secure_session_create(const void* id, size_t id_length, const void* sign_key, size_t sign_key_length, const secure_session_user_callbacks_t* user_callbacks); THEMIS_API themis_status_t secure_session_destroy(secure_session_t* session_ctx); THEMIS_API themis_status_t secure_session_connect(secure_session_t* session_ctx); THEMIS_API themis_status_t secure_session_generate_connect_request(secure_session_t* session_ctx, void* output, size_t* output_length); THEMIS_API themis_status_t secure_session_wrap(secure_session_t* session_ctx, const void* message, size_t message_length, void* wrapped_message, size_t* wrapped_message_length); THEMIS_API themis_status_t secure_session_unwrap(secure_session_t* session_ctx, const void* wrapped_message, size_t wrapped_message_length, void* message, size_t* message_length); /* Trying to mimic socket functions */ THEMIS_API ssize_t secure_session_send(secure_session_t* session_ctx, const void* message, size_t message_length); THEMIS_API ssize_t secure_session_receive(secure_session_t* session_ctx, void* message, size_t message_length); THEMIS_API themis_status_t secure_session_save(const secure_session_t* session_ctx, void* out, size_t* out_length); THEMIS_API themis_status_t secure_session_load(secure_session_t* session_ctx, const void* in, size_t in_length, const secure_session_user_callbacks_t* user_callbacks); THEMIS_API bool secure_session_is_established(const secure_session_t* session_ctx); THEMIS_API themis_status_t secure_session_get_remote_id(const secure_session_t* session_ctx, uint8_t* id, size_t* id_length); /** @} */ /** @} */ #ifdef __cplusplus } #endif #endif /* THEMIS_SECURE_SESSION_H */
2,253
345
<filename>kemon/trace.c /*++ Copyright (c) Didi Research America. All rights reserved. Module Name: trace.c Author: <NAME>, 08-Feb-2017 Revision History: --*/ #include <libkern/libkern.h> #include <sys/systm.h> #include "trace.h" extern void hex_printf( void *buffer, unsigned long length, unsigned long flag ) { int timer_chan; struct timespec timer; unsigned char hex_buffer[0x80]; unsigned char *tmp_buffer = buffer; unsigned long hex_length = sizeof(hex_buffer); unsigned long line, index, character; if (!buffer || !length || ((flag & HEX_PRINTF_W) && (length % sizeof(uint16_t))) || ((flag & HEX_PRINTF_D) && (length % sizeof(uint32_t))) || ((flag & HEX_PRINTF_Q) && (length % sizeof(uint64_t)))) return; timer_chan = 0; timer.tv_sec = 0; timer.tv_nsec = 800000; if (flag & HEX_PRINTF_B) { printf(" -*> MEMORY DUMP <*- \n"); printf("+---------------------+--------------------------------------------------+-------------------+\n"); printf("| ADDRESS | 0 1 2 3 4 5 6 7 8 9 A B C D E F | 0123456789ABCDEF |\n"); printf("| --------------------+--------------------------------------------------+------------------ |\n"); for (index = 0; index < length; index += 0x10) { memset(hex_buffer, 0, hex_length); line = length - index > 0x10 ? 0x10 : length - index; snprintf((char *) hex_buffer, hex_length, "| %16p | ", tmp_buffer + index); for (character = 0; character < line; character++) { if (sizeof(char) * 7 == character) snprintf(((char *) hex_buffer + strlen((char *) hex_buffer)), hex_length - strlen((char *) hex_buffer), "%02x ", tmp_buffer[index + character]); else snprintf(((char *) hex_buffer + strlen((char *) hex_buffer)), hex_length - strlen((char *) hex_buffer), "%02x ", tmp_buffer[index + character]); } for (; character < 0x10; character++) { if (sizeof(char) * 7 == character) snprintf(((char *) hex_buffer + strlen((char *) hex_buffer)), hex_length - strlen((char *) hex_buffer), "%s", " "); else snprintf(((char *) hex_buffer + strlen((char *) hex_buffer)), hex_length - strlen((char *) hex_buffer), "%s", " "); } snprintf(((char *) hex_buffer + strlen((char *) hex_buffer)), hex_length - strlen((char *) hex_buffer), "%s", "| "); for (character = 0; character < line; character++) { if (tmp_buffer[index + character] < 0x20 || tmp_buffer[index + character] > 0x7E) snprintf(((char *) hex_buffer + strlen((char *) hex_buffer)), hex_length - strlen((char *) hex_buffer), "%c", '.'); else snprintf(((char *) hex_buffer + strlen((char *) hex_buffer)), hex_length - strlen((char *) hex_buffer), "%c", tmp_buffer[index + character]); } for (; character < 0x10; character++) { snprintf(((char *) hex_buffer + strlen((char *) hex_buffer)), hex_length - strlen((char *) hex_buffer), "%c", ' '); } snprintf(((char *) hex_buffer + strlen((char *) hex_buffer)), hex_length - strlen((char *) hex_buffer), "%s", " |\n"); printf("%s", hex_buffer); } printf("+---------------------+--------------------------------------------------+-------------------+\n"); msleep(&timer_chan, NULL, PUSER, "hex_printf_b", &timer); } else if (flag & HEX_PRINTF_W) { printf(" -*> MEMORY DUMP <*- \n"); printf("+---------------------+------------------------------------------+-------------------+\n"); printf("| ADDRESS | 1 0 3 2 5 4 7 6 9 8 B A D C F E | 0123456789ABCDEF |\n"); printf("| --------------------+------------------------------------------+------------------ |\n"); for (index = 0; index < length; index += 0x10) { memset(hex_buffer, 0, hex_length); line = length - index > 0x10 ? 0x10 : length - index; snprintf((char *) hex_buffer, hex_length, "| %16p | ", tmp_buffer + index); for (character = 0; character < line; character += sizeof(uint16_t)) { if (sizeof(uint16_t) * 3 == character) snprintf(((char *) hex_buffer + strlen((char *) hex_buffer)), hex_length - strlen((char *) hex_buffer), "%04x ", *(unsigned short *) (tmp_buffer + index + character)); else snprintf(((char *) hex_buffer + strlen((char *) hex_buffer)), hex_length - strlen((char *) hex_buffer), "%04x ", *(unsigned short *) (tmp_buffer + index + character)); } for (; character < 0x10; character += sizeof(uint16_t)) { if (sizeof(uint16_t) * 3 == character) snprintf(((char *) hex_buffer + strlen((char *) hex_buffer)), hex_length - strlen((char *) hex_buffer), "%s", " "); else snprintf(((char *) hex_buffer + strlen((char *) hex_buffer)), hex_length - strlen((char *) hex_buffer), "%s", " "); } snprintf(((char *) hex_buffer + strlen((char *) hex_buffer)), hex_length - strlen((char *) hex_buffer), "%s", "| "); for (character = 0; character < line; character++) { if (tmp_buffer[index + character] < 0x20 || tmp_buffer[index + character] > 0x7E) snprintf(((char *) hex_buffer + strlen((char *) hex_buffer)), hex_length - strlen((char *) hex_buffer), "%c", '.'); else snprintf(((char *) hex_buffer + strlen((char *) hex_buffer)), hex_length - strlen((char *) hex_buffer), "%c", tmp_buffer[index + character]); } for (; character < 0x10; character++) { snprintf(((char *) hex_buffer + strlen((char *) hex_buffer)), hex_length - strlen((char *) hex_buffer), "%c", ' '); } snprintf(((char *) hex_buffer + strlen((char *) hex_buffer)), hex_length - strlen((char *) hex_buffer), "%s", " |\n"); printf("%s", hex_buffer); } printf("+---------------------+------------------------------------------+-------------------+\n"); msleep(&timer_chan, NULL, PUSER, "hex_printf_w", &timer); } else if (flag & HEX_PRINTF_D) { printf(" -*> MEMORY DUMP <*- \n"); printf("+---------------------+--------------------------------------+-------------------+\n"); printf("| ADDRESS | 3 2 1 0 7 6 5 4 B A 9 8 F E D C | 0123456789ABCDEF |\n"); printf("| --------------------+--------------------------------------+------------------ |\n"); for (index = 0; index < length; index += 0x10) { memset(hex_buffer, 0, hex_length); line = length - index > 0x10 ? 0x10 : length - index; snprintf((char *) hex_buffer, hex_length, "| %16p | ", tmp_buffer + index); for (character = 0; character < line; character += sizeof(uint32_t)) { if (sizeof(uint32_t) == character) snprintf(((char *) hex_buffer + strlen((char *) hex_buffer)), hex_length - strlen((char *) hex_buffer), "%08x ", *(unsigned int *) (tmp_buffer + index + character)); else snprintf(((char *) hex_buffer + strlen((char *) hex_buffer)), hex_length - strlen((char *) hex_buffer), "%08x ", *(unsigned int *) (tmp_buffer + index + character)); } for (; character < 0x10; character += sizeof(uint32_t)) { if (sizeof(uint32_t) == character) snprintf(((char *) hex_buffer + strlen((char *) hex_buffer)), hex_length - strlen((char *) hex_buffer), "%s", " "); else snprintf(((char *) hex_buffer + strlen((char *) hex_buffer)), hex_length - strlen((char *) hex_buffer), "%s", " "); } snprintf(((char *) hex_buffer + strlen((char *) hex_buffer)), hex_length - strlen((char *) hex_buffer), "%s", "| "); for (character = 0; character < line; character++) { if (tmp_buffer[index + character] < 0x20 || tmp_buffer[index + character] > 0x7E) snprintf(((char *) hex_buffer + strlen((char *) hex_buffer)), hex_length - strlen((char *) hex_buffer), "%c", '.'); else snprintf(((char *) hex_buffer + strlen((char *) hex_buffer)), hex_length - strlen((char *) hex_buffer), "%c", tmp_buffer[index + character]); } for (; character < 0x10; character++) { snprintf(((char *) hex_buffer + strlen((char *) hex_buffer)), hex_length - strlen((char *) hex_buffer), "%c", ' '); } snprintf(((char *) hex_buffer + strlen((char *) hex_buffer)), hex_length - strlen((char *) hex_buffer), "%s", " |\n"); printf("%s", hex_buffer); } printf("+---------------------+--------------------------------------+-------------------+\n"); msleep(&timer_chan, NULL, PUSER, "hex_printf_d", &timer); } else if (flag & HEX_PRINTF_Q) { printf(" -*> MEMORY DUMP <*- \n"); printf("+---------------------+--------------------------------------+-------------------+\n"); printf("| ADDRESS | 7 6 5 4 3 2 1 0 F E D C B A 9 8 | 0123456789ABCDEF |\n"); printf("| --------------------+--------------------------------------+------------------ |\n"); for (index = 0; index < length; index += 0x10) { memset(hex_buffer, 0, hex_length); line = length - index > 0x10 ? 0x10 : length - index; snprintf((char *) hex_buffer, hex_length, "| %16p | ", tmp_buffer + index); for (character = 0; character < line; character += sizeof(uint64_t)) { if (!character) snprintf(((char *) hex_buffer + strlen((char *) hex_buffer)), hex_length - strlen((char *) hex_buffer), "%08x`%08x ", *(unsigned int *) (tmp_buffer + index + character + sizeof(uint32_t) * 1), *(unsigned int *) (tmp_buffer + index + character + sizeof(uint32_t) * 0)); else snprintf(((char *) hex_buffer + strlen((char *) hex_buffer)), hex_length - strlen((char *) hex_buffer), "%08x`%08x ", *(unsigned int *) (tmp_buffer + index + character + sizeof(uint32_t) * 1), *(unsigned int *) (tmp_buffer + index + character + sizeof(uint32_t) * 0)); } for (; character < 0x10; character += sizeof(uint64_t)) { snprintf(((char *) hex_buffer + strlen((char *) hex_buffer)), hex_length - strlen((char *) hex_buffer), "%s", " "); } snprintf(((char *) hex_buffer + strlen((char *) hex_buffer)), hex_length - strlen((char *) hex_buffer), "%s", "| "); for (character = 0; character < line; character++) { if (tmp_buffer[index + character] < 0x20 || tmp_buffer[index + character] > 0x7E) snprintf(((char *) hex_buffer + strlen((char *) hex_buffer)), hex_length - strlen((char *) hex_buffer), "%c", '.'); else snprintf(((char *) hex_buffer + strlen((char *) hex_buffer)), hex_length - strlen((char *) hex_buffer), "%c", tmp_buffer[index + character]); } for (; character < 0x10; character++) { snprintf(((char *) hex_buffer + strlen((char *) hex_buffer)), hex_length - strlen((char *) hex_buffer), "%c", ' '); } snprintf(((char *) hex_buffer + strlen((char *) hex_buffer)), hex_length - strlen((char *) hex_buffer), "%s", " |\n"); printf("%s", hex_buffer); } printf("+---------------------+--------------------------------------+-------------------+\n"); msleep(&timer_chan, NULL, PUSER, "hex_printf_q", &timer); } }
7,429
460
<filename>trunk/win/Source/Includes/QtIncludes/src/gui/widgets/qcheckbox.h<gh_stars>100-1000 /**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (<EMAIL>) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QCHECKBOX_H #define QCHECKBOX_H #include <QtGui/qabstractbutton.h> QT_BEGIN_HEADER QT_BEGIN_NAMESPACE QT_MODULE(Gui) class QCheckBoxPrivate; class QStyleOptionButton; class Q_GUI_EXPORT QCheckBox : public QAbstractButton { Q_OBJECT Q_PROPERTY(bool tristate READ isTristate WRITE setTristate) public: explicit QCheckBox(QWidget *parent=0); explicit QCheckBox(const QString &text, QWidget *parent=0); QSize sizeHint() const; void setTristate(bool y = true); bool isTristate() const; Qt::CheckState checkState() const; void setCheckState(Qt::CheckState state); Q_SIGNALS: void stateChanged(int); protected: bool event(QEvent *e); bool hitButton(const QPoint &pos) const; void checkStateSet(); void nextCheckState(); void paintEvent(QPaintEvent *); void mouseMoveEvent(QMouseEvent *); void initStyleOption(QStyleOptionButton *option) const; #ifdef QT3_SUPPORT public: enum ToggleState { Off = Qt::Unchecked, NoChange = Qt::PartiallyChecked, On = Qt::Checked }; inline QT3_SUPPORT ToggleState state() const { return static_cast<QCheckBox::ToggleState>(static_cast<int>(checkState())); } inline QT3_SUPPORT void setState(ToggleState state) { setCheckState(static_cast<Qt::CheckState>(static_cast<int>(state))); } inline QT3_SUPPORT void setNoChange() { setCheckState(Qt::PartiallyChecked); } QT3_SUPPORT_CONSTRUCTOR QCheckBox(QWidget *parent, const char* name); QT3_SUPPORT_CONSTRUCTOR QCheckBox(const QString &text, QWidget *parent, const char* name); #endif private: Q_DECLARE_PRIVATE(QCheckBox) Q_DISABLE_COPY(QCheckBox) }; QT_END_NAMESPACE QT_END_HEADER #endif // QCHECKBOX_H
1,291
1,020
<reponame>icse18-refactorings/RoboBinding package org.robobinding.util; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; /** * * @since 1.0 * @version $Revision: 1.0 $ * @author <NAME> */ public class BitmapDrawableData { public final int resourceId; public final Bitmap bitmap; public final BitmapDrawable drawable; public BitmapDrawableData(int resourceId, Bitmap bitmap, BitmapDrawable drawable) { this.resourceId = resourceId; this.bitmap = bitmap; this.drawable = drawable; } }
212
498
<filename>01_wallet_rpc/rpc-common/src/main/java/com/bizzan/bc/wallet/entity/Coin.java package com.bizzan.bc.wallet.entity; import lombok.Data; import java.math.BigDecimal; import java.math.BigInteger; @Data public class Coin { private String name; private String unit; private String rpc; private String keystorePath; private BigDecimal defaultMinerFee; private String withdrawAddress; private String withdrawWallet; private String withdrawWalletPassword; private BigDecimal minCollectAmount; private BigInteger gasLimit; private BigDecimal gasSpeedUp = BigDecimal.ONE; private BigDecimal rechargeMinerFee; private String ignoreFromAddress; private String masterAddress; }
241
1,320
<gh_stars>1000+ /* * Copyright 2019 Flipkart Internet Pvt. Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.flipkart.android.proteus.support.design.widget; import android.content.Context; import android.content.res.ColorStateList; import android.view.ViewGroup; import com.flipkart.android.proteus.ProteusContext; import com.flipkart.android.proteus.ProteusView; import com.flipkart.android.proteus.ViewTypeParser; import com.flipkart.android.proteus.processor.BooleanAttributeProcessor; import com.flipkart.android.proteus.processor.ColorResourceProcessor; import com.flipkart.android.proteus.processor.DimensionAttributeProcessor; import com.flipkart.android.proteus.processor.NumberAttributeProcessor; import com.flipkart.android.proteus.value.Layout; import com.flipkart.android.proteus.value.ObjectValue; import com.flipkart.android.proteus.value.Primitive; import com.flipkart.android.proteus.value.Value; import com.google.android.material.floatingactionbutton.FloatingActionButton; import androidx.annotation.NonNull; import androidx.annotation.Nullable; /** * FloatingActionButtonParser * * @author adityasharat */ public class FloatingActionButtonParser<V extends FloatingActionButton> extends ViewTypeParser<V> { @NonNull @Override public String getType() { return "FloatingActionButton"; } @Nullable @Override public String getParentType() { return "ImageButton"; } @NonNull @Override public ProteusView createView(@NonNull ProteusContext context, @NonNull Layout layout, @NonNull ObjectValue data, @Nullable ViewGroup parent, int dataIndex) { return new ProteusFloatingActionButton(context); } @Override protected void addAttributeProcessors() { addAttributeProcessor("elevation", new DimensionAttributeProcessor<V>() { @Override public void setDimension(V view, float dimension) { view.setCompatElevation(dimension); } }); addAttributeProcessor("fabSize", new NumberAttributeProcessor<V>() { private final Primitive AUTO = new Primitive(FloatingActionButton.SIZE_AUTO); private final Primitive MINI = new Primitive(FloatingActionButton.SIZE_MINI); private final Primitive NORMAL = new Primitive(FloatingActionButton.SIZE_NORMAL); @Override public void setNumber(V view, @NonNull Number value) { //noinspection WrongConstant view.setSize(value.intValue()); } @Override public Value compile(@Nullable Value value, Context context) { if (value != null) { String string = value.getAsString(); switch (string) { case "auto": return AUTO; case "mini": return MINI; case "normal": return NORMAL; default: return AUTO; } } else { return AUTO; } } }); addAttributeProcessor("rippleColor", new ColorResourceProcessor<V>() { @Override public void setColor(V view, int color) { view.setRippleColor(color); } @Override public void setColor(V view, ColorStateList colors) { throw new IllegalArgumentException("rippleColor must be a color int"); } }); addAttributeProcessor("useCompatPadding", new BooleanAttributeProcessor<V>() { @Override public void setBoolean(V view, boolean value) { view.setUseCompatPadding(value); } }); } }
1,424
578
<filename>app/server/credential/src/main/java/io/syndesis/server/credential/generic/OAuth2CredentialProviderFactory.java /* * Copyright (C) 2016 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.syndesis.server.credential.generic; import io.syndesis.server.credential.CredentialProvider; import io.syndesis.server.credential.CredentialProviderFactory; import io.syndesis.server.credential.OAuth2Applicator; import io.syndesis.server.credential.OAuth2ConnectorProperties; import io.syndesis.server.credential.OAuth2CredentialProvider; import io.syndesis.server.credential.SocialProperties; import io.syndesis.server.credential.UnconfiguredProperties; import org.springframework.social.connect.support.OAuth2ConnectionFactory; import org.springframework.social.oauth2.GenericOAuth2ServiceProvider; import org.springframework.social.oauth2.OAuth2ServiceProvider; import org.springframework.social.oauth2.TokenStrategy; import org.springframework.web.client.RestOperations; public class OAuth2CredentialProviderFactory implements CredentialProviderFactory { @Override public CredentialProvider create(final SocialProperties properties) { if (properties instanceof UnconfiguredProperties) { return new OAuth2CredentialProvider<>("oauth2"); } if (!(properties instanceof OAuth2ConnectorProperties)) { throw new IllegalArgumentException(String.format("Unsupported social properties instance - " + "expected properties of type %s, but found %s", OAuth2ConnectorProperties.class, properties.getClass())); } final OAuth2ConnectorProperties oauth2Properties = (OAuth2ConnectorProperties) properties; final String appId = oauth2Properties.getAppId(); final String appSecret = oauth2Properties.getAppSecret(); final String authorizationUrl = oauth2Properties.getAuthorizationUrl(); final String authenticationUrl = oauth2Properties.getAuthenticationUrl(); final String accessTokenUrl = oauth2Properties.getAccessTokenUrl(); final boolean useParametersForClientCredentials = oauth2Properties.isUseParametersForClientCredentials(); final TokenStrategy tokenStrategy = oauth2Properties.getTokenStrategy(); final String scope = oauth2Properties.getScope(); final OAuth2ServiceProvider<RestOperations> serviceProvider = new GenericOAuth2ServiceProvider(appId, appSecret, authorizationUrl, authenticationUrl, accessTokenUrl, useParametersForClientCredentials, tokenStrategy); final OAuth2ConnectionFactory<RestOperations> connectionFactory = new OAuth2ConnectionFactory<>("oauth2", serviceProvider, null); connectionFactory.setScope(scope); final OAuth2Applicator applicator = new OAuth2Applicator(properties); applicator.setAccessTokenProperty("accessToken"); applicator.setAccessTokenExpiresAtProperty("accessTokenExpiresAt"); applicator.setRefreshTokenProperty("refreshToken"); applicator.setClientIdProperty("clientId"); applicator.setClientSecretProperty("clientSecret"); return new OAuth2CredentialProvider<>("oauth2", connectionFactory, applicator, oauth2Properties.getAdditionalQueryParameters()); } @Override public String id() { return "oauth2"; } }
1,226
396
<filename>indicatorbox-library/src/main/java/com/wusp/indicatorbox_library/Particle/ParticleField.java package com.wusp.indicatorbox_library.Particle; import android.content.Context; import android.graphics.Canvas; import android.util.AttributeSet; import android.widget.FrameLayout; import java.util.ArrayList; /** * Created by wusp on 16/4/1. */ public class ParticleField extends FrameLayout { private int flagType = -1; /**At least we need these variants to form a particle motion, and the variants cannot be a default value.*/ private ArrayList<Particle> mParticles; public ParticleField(Context context) { super(context); } public ParticleField(Context context, AttributeSet attrs) { super(context, attrs); } public ParticleField(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } private ParticleField(ViewGenerator viewGenerator){ this(viewGenerator.getContext(), viewGenerator.getAttributeSet()); //Init particle mParticles = new ArrayList<>(); if (viewGenerator.getParticleInitializers() != null && viewGenerator.getParticleInitializers().size() > 0) { for (int i = 0; i < viewGenerator.getParticleInitializers().size(); i++) { mParticles.add(new Particle(viewGenerator.getParticleInitializers().get(i))); } }else{ //No custom bitmap, just draw a default circle. for (int i = 0; i < viewGenerator.particleNumbers; i++){ mParticles.add(new Particle()); } } } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); synchronized (mParticles){ for (Particle p : mParticles){ p.draw(canvas); } } } public void onUpdate(float interpolatorValue){ if (interpolatorValue >= 0 && interpolatorValue <= 1.0f){ for (Particle particle : mParticles){ particle.update(interpolatorValue); } postInvalidate(); } } public ArrayList<Particle> getmParticles() { return mParticles; } /**This is used to generator a particle field(View) can be add to a custom view and cooperate with that directly.*/ public static class ViewGenerator{ //To indicate which type is. private int type; //Context private Context context; //Attributes private AttributeSet attributeSet; //ParticleInitializer is used to create fundamental particles. private ArrayList<ParticleInitializer> particleInitializers; private int particleNumbers; public ViewGenerator() { } public ParticleField generate(){ return new ParticleField(this); } public Context getContext() { return context; } public ViewGenerator setContext(Context context) { this.context = context; return this; } public AttributeSet getAttributeSet() { return attributeSet; } public ViewGenerator setAttributeSet(AttributeSet attributeSet) { this.attributeSet = attributeSet; return this; } public int getType() { return type; } public ViewGenerator setType(int type) { this.type = type; return this; } public ArrayList<ParticleInitializer> getParticleInitializers() { return particleInitializers; } public ViewGenerator setParticleInitializers(ArrayList<ParticleInitializer> particleInitializers) { this.particleInitializers = particleInitializers; return this; } public ViewGenerator setParticleNumbers(int numbers){ particleNumbers = numbers; return this; } } }
1,642
417
<gh_stars>100-1000 /*************************************************************************** file : grtexture.h created : Wed Jun 1 14:56:31 CET 2005 copyright : (C) 2005 by <NAME> version : $Id: grtexture.h,v 1.2.2.1 2008/08/16 14:12:08 berniw Exp $ ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ /* This classes/methods are used to handle texture compression and textures which are shared among multiple objects. In the long term they should obsolete parts of grutil.cpp. */ #ifndef _GRTEXTURE_H_ #define _GRTEXTURE_H_ #include <stdio.h> #include <plib/ssg.h> #include <glfeatures.h> #include "grloadsgi.h" bool doMipMap(const char *tfname, int mipmap); // This state does currently not manage anything! // TODO: manage shared textures, obsolete grutil.cpp parts. class grManagedState : public ssgSimpleState { public: virtual void setTexture(ssgTexture *tex) { ssgSimpleState::setTexture(tex); } virtual void setTexture(const char *fname, int _wrapu = TRUE, int _wrapv = TRUE, int _mipmap = TRUE) { _mipmap = doMipMap(fname, _mipmap); ssgSimpleState::setTexture(fname, _wrapu, _wrapv, _mipmap); } virtual void setTexture(GLuint tex) { printf("Obsolete call: setTexture(GLuint tex)\n"); ssgSimpleState::setTexture(tex); } }; // Managed state factory. inline grManagedState* grStateFactory(void) { return new grManagedState(); } // Prototype for mipmap generation. bool grMakeMipMaps(GLubyte *image, int xsize, int ysize, int zsize, bool mipmap); // Prototype for SGI texture loading function. bool grLoadSGI(const char *fname, ssgTextureInfo* info); // Register customized loader in plib. void grRegisterCustomSGILoader(void); // SGI loader class to call customized ssgMakeMipMaps. This is necessary because // of plib architecture which does not allow to customize the mipmap // generation. class grSGIHeader : public ssgSGIHeader { public: grSGIHeader(const char *fname, ssgTextureInfo* info); }; #endif // _GRTEXTURE_H_
995
429
/******************************************************************************************* * * raylib [shaders] example - Apply a shader to a 3d model * * NOTE: This example requires raylib OpenGL 3.3 or ES2 versions for shaders support, * OpenGL 1.1 does not support shaders, recompile raylib to OpenGL 3.3 version. * * NOTE: Shaders used in this example are #version 330 (OpenGL 3.3), to test this example * on OpenGL ES 2.0 platforms (Android, Raspberry Pi, HTML5), use #version 100 shaders * raylib comes with shaders ready for both versions, check raylib/shaders install folder * * This example has been created using raylib 1.3 (www.raylib.com) * raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) * * Copyright (c) 2014 <NAME> (@raysan5) * ********************************************************************************************/ use raylib::prelude::*; #[cfg(not(target_arch = "wasm32"))] const GLSL_VERSION 330 #[cfg(target_arch = "wasm32")] const GLSL_VERSION 100 pub fn run(rl: &mut RaylibHandle, thread: &RaylibThread) -> crate::SampleOut { // Initialization //-------------------------------------------------------------------------------------- let screen_width = 800; let screen_height = 450; SetConfigFlags(FLAG_MSAA_4X_HINT); // Enable Multi Sampling Anti Aliasing 4x (if available) rl.set_window_size(screen_width, screen_height); rl.set_window_title(thread, "raylib [shaders] example - model shader"); // Define the camera to look into our 3d world let mut camera = Camera3D::perspective( rvec3(4.0, 4.0, 4.0), rvec3(0.0, 1.0, 1.0), rvec3(0.0, 1.0, 0.0), 45.0, ); let model = rl.load_model(&thread, "original/models/resources/models/watermill.obj"); // Load OBJ model let texture = rl.load_texture(thread, "original/shaders/resources/models/watermill_diffuse.png"); // Load model texture // Load shader for model // NOTE: Defining 0 (NULL) for vertex shader forces usage of internal default vertex shader let shader = rl.load_shader(thread,0, &format!("original/shaders/resources/shaders/glsl{}/grayscale.fs", GLSL_VERSION)); model.materials_mut()[0].shader = shader; // Set shader effect to 3d model model.materials_mut()[0].maps_mut()[raylib::consts::MaterialMapType::MAP_ALBEDO as usize].texture = *texture.as_ref(); // Bind texture to model let position = Vector3::zero(); // Set model position rl.set_camera_mode(&camera, raylib::consts::CameraMode::CAMERA_FREE); // Set an orbital camera mode rl.set_target_fps(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop return Box::new(move |rl: &mut RaylibHandle, thread: &RaylibThread| -> () // Detect window close button or ESC key { // Update //---------------------------------------------------------------------------------- rl.update_camera(&mut camera); // Update camera //---------------------------------------------------------------------------------- // Draw //---------------------------------------------------------------------------------- let mut d = rl.begin_drawing(thread); d.clear_background(Color::RAYWHITE); let mut d = d.begin_mode3D(&camera); d.draw_model(model, position, 0.2, Color::WHITE); // Draw 3d model with texture d.draw_grid(10, 1.0); // Draw a grid EndMode3D(); d.draw_text("(c) Watermill 3D model by <NAME>", screen_width - 210, screen_height - 20, 10, Color::GRAY); d.draw_fps(10, 10); EndDrawing(); //---------------------------------------------------------------------------------- } // De-Initialization //-------------------------------------------------------------------------------------- UnloadShader(shader); // Unload shader UnloadTexture(texture); // Unload texture UnloadModel(model); // Unload model CloseWindow(); // Close window and OpenGL context //-------------------------------------------------------------------------------------- return 0; }
1,376
4,538
<filename>components/ota/hal/ota_hal_vfs_plat.c #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <string.h> #include <stdlib.h> #include <stdint.h> #include "ota_log.h" #include "ota_hal.h" #include <aos/vfs.h> #include <sys/types.h> #include <sys/ioctl.h> #include "ota_import.h" #include "ota_hal_os.h" #include "aos/kernel.h" #include "aos/hal/flash.h" #include <vfsdev/flash_dev.h> #include "aos/mtdpart.h" #include "aos/mtd.h" unsigned char *ota_cache = NULL; unsigned int ota_cache_len = 0; unsigned int ota_fw_size = 0; unsigned int ota_receive_total_len = 0; static int boot_part = MTD_PART_ID_KERNEL2; static ota_crc16_ctx ctx = {0}; static int ota_fd = -1; OTA_WEAK int ota_get_running_index(void) { return 0; } OTA_WEAK int ota_hal_init(ota_boot_param_t *param) { int ret = OTA_INIT_FAIL; unsigned int len = 0; unsigned int off = 0; unsigned int block_size = 0; char dev_str[16] = {0}; struct mtd_erase_info erase_info = {0}; int partition_id =boot_part; mtd_partition_t *tmp_part_info; if (param == NULL) { goto OTA_HAL_INIT_EXIT; } if(ota_get_running_index()==0) partition_id = MTD_PART_ID_KERNEL2; else partition_id = MTD_PART_ID_KERNEL; OTA_LOG_I("update partition %d\r\n", partition_id); snprintf(dev_str, 15, "/dev/mtdblock%d", partition_id); ota_fd = open(dev_str, 0); if (ota_fd < 0) { ota_fd = -1; OTA_LOG_E("open ota temp partition failed"); goto OTA_HAL_INIT_EXIT; } tmp_part_info = &mtd_partitions[partition_id]; if ((param->len == 0) || (param->len > tmp_part_info->partition_length)) { ret = OTA_INIT_FAIL; OTA_LOG_E("bin file size err!"); goto OTA_HAL_INIT_EXIT; } ota_receive_total_len = 0; ota_fw_size = param->len; ota_cache = ota_malloc(OTA_FLASH_WRITE_CACHE_SIZE); if (NULL == ota_cache) { ret = OTA_INIT_FAIL; goto OTA_HAL_INIT_EXIT; } len = param->len; while (len > 0) { block_size = (len > OTA_FLASH_BLOCK_SIZE) ? OTA_FLASH_BLOCK_SIZE : len; ret = lseek(ota_fd, (off_t)off, SEEK_SET); if (ret < 0) { ret = OTA_INIT_FAIL; OTA_LOG_E("lseek fail! "); goto OTA_HAL_INIT_EXIT; } erase_info.offset = off; erase_info.length = block_size; ret = ioctl(ota_fd, IOC_MTD_ERASE, &erase_info); if (ret < 0) { ret = OTA_INIT_FAIL; OTA_LOG_E("erase fail! "); goto OTA_HAL_INIT_EXIT; } off += block_size; len -= block_size; ota_msleep(10); } ota_crc16_init(&ctx); OTA_LOG_I("ota init part:%d len:%d\n", boot_part, param->len); OTA_HAL_INIT_EXIT: if (ret != 0) { if (NULL != ota_cache) { ota_free(ota_cache); ota_cache = NULL; } if (ota_fd >= 0) { close(ota_fd); ota_fd = -1; } OTA_LOG_E("ota init fail!"); } return ret; } OTA_WEAK int ota_hal_final(void) { return 0; } OTA_WEAK int ota_hal_write(unsigned int *off, char *in_buf, unsigned int in_buf_len) { int ret = 0; int tocopy = 0; if (off == NULL || in_buf_len > OTA_FLASH_WRITE_CACHE_SIZE) { return OTA_UPGRADE_WRITE_FAIL; } if (in_buf_len <= OTA_FLASH_WRITE_CACHE_SIZE - ota_cache_len) { tocopy = in_buf_len; } else { tocopy = OTA_FLASH_WRITE_CACHE_SIZE - ota_cache_len; } /*Start from last byte of remaing data*/ memcpy(ota_cache + ota_cache_len, in_buf, tocopy); ota_cache_len += tocopy; if (ota_cache_len == OTA_FLASH_WRITE_CACHE_SIZE) { ret = lseek(ota_fd, (off_t)*off, SEEK_SET); if (ret < 0) { goto EXIT; } ret = write(ota_fd, ota_cache, OTA_FLASH_WRITE_CACHE_SIZE); if (ret < 0) { goto EXIT; } *off += OTA_FLASH_WRITE_CACHE_SIZE; ota_cache_len = 0; ota_crc16_update(&ctx, ota_cache, OTA_FLASH_WRITE_CACHE_SIZE); } /*keep remaining data*/ if (in_buf_len - tocopy > 0) { /*Now ota_cache only contains remaing data*/ memcpy(ota_cache, in_buf + tocopy, in_buf_len - tocopy); ota_cache_len = in_buf_len - tocopy; } ota_receive_total_len += in_buf_len; if (ota_receive_total_len == ota_fw_size) { if (ota_cache_len != 0) { ret = lseek(ota_fd, (off_t)*off, SEEK_SET); if (ret < 0) { goto EXIT; } ret = write(ota_fd, ota_cache, ota_cache_len); if (ret < 0) { goto EXIT; } *off += ota_cache_len; ota_crc16_update(&ctx, ota_cache, ota_cache_len); } if (ota_cache != NULL) { ota_free(ota_cache); ota_cache = NULL; } if (ota_fd >= 0) { close(ota_fd); ota_fd = -1; } } EXIT: if (ret < 0) { if (ota_cache != NULL) { ota_free(ota_cache); ota_cache = NULL; } if (ota_fd >= 0) { close(ota_fd); ota_fd = -1; } OTA_LOG_E("ota_write err:%d", ret); } return ret; } OTA_WEAK int ota_hal_rollback_platform_hook(void) { return 0; } OTA_WEAK int ota_hal_rollback(void) { int ret = 0; int temp_fd = -1; char dev_str[16]; ota_boot_param_t param; memset(&param, 0, sizeof(ota_boot_param_t)); snprintf(dev_str, 15, "/dev/mtdblock%d", MTD_PART_ID_ENV); temp_fd = open(dev_str, 0); if (temp_fd < 0) { OTA_LOG_E("open ota temp partition failed"); goto OTA_ROLLBACK; } ret = read(temp_fd, (void *)&param, sizeof(ota_boot_param_t)); if (ret < 0) { OTA_LOG_E("rollback err1:%d", ret); goto OTA_ROLLBACK; } if ((param.boot_count != 0) && (param.boot_count != 0xff)) { param.upg_flag = 0; param.boot_count = 0; /*Clear bootcount to avoid rollback*/ ret = ota_update_parameter(&param); if (ret < 0) { OTA_LOG_E("rollback err2:%d", ret); goto OTA_ROLLBACK; } ret = ota_hal_rollback_platform_hook(); if (ret < 0) { OTA_LOG_E("ota_hal_rollback_platform_hook fail!"); goto OTA_ROLLBACK; } } OTA_ROLLBACK: if (temp_fd >= 0) { close(temp_fd); temp_fd = -1; } if (ret != 0) { OTA_LOG_E("rollback err3:%d", ret); } return ret; } OTA_WEAK int ota_hal_reboot_bank(void) { return 0; } OTA_WEAK void ota_hal_image_crc16(unsigned short *outResult) { ota_crc16_final(&ctx, outResult); } OTA_WEAK int ota_hal_platform_boot_type(void) { return 0; } OTA_WEAK int ota_hal_boot_type() { int ret = -1; ret = ota_hal_platform_boot_type(); if (ret < 0) { OTA_LOG_E("get boot type failed!"); } return ret; } OTA_WEAK int ota_hal_boot(ota_boot_param_t *param) { int ret = OTA_UPGRADE_WRITE_FAIL; int dst_partition, src_partition;/*on boot stage do copying from src_partition to dst_partition*/ mtd_partition_t *tmp_part_info; if(ota_get_running_index()==0) { src_partition = MTD_PART_ID_KERNEL2; dst_partition = MTD_PART_ID_KERNEL; }else { src_partition = MTD_PART_ID_KERNEL; dst_partition = MTD_PART_ID_KERNEL2; } tmp_part_info = &mtd_partitions[src_partition]; param->src_adr = tmp_part_info->partition_start_addr; tmp_part_info = &mtd_partitions[dst_partition]; param->dst_adr = tmp_part_info->partition_start_addr; param->old_size = tmp_part_info->partition_length; if (param->crc == 0 || param->crc == 0xffff) { OTA_LOG_I("calculate image crc"); ota_hal_image_crc16(&param->crc); } if (param->upg_flag == OTA_UPGRADE_ALL) { int tmp_type = ota_hal_boot_type(); if (tmp_type < 0) { OTA_LOG_E("get platform boot type err!"); goto OTA_HAL_BOOT_OVER; } param->boot_type = (unsigned char)tmp_type; } else { param->boot_type = 0; } ret = ota_update_parameter(param); if (ret < 0) { OTA_LOG_E("update param err!"); goto OTA_HAL_BOOT_OVER; } if (param->upg_flag == OTA_UPGRADE_ALL) { ret = ota_hal_final(); if (ret < 0) { OTA_LOG_E("clear user boot count fail!"); goto OTA_HAL_BOOT_OVER; } } OTA_LOG_I("OTA after finish dst:0x%08x src:0x%08x len:0x%08x, crc:0x%04x param crc:0x%04x upg_flag:0x%04x \r\n", param->dst_adr, param->src_adr, param->len, param->crc, param->param_crc, param->upg_flag); OTA_HAL_BOOT_OVER: if (ret < 0) { OTA_LOG_E("set boot info failed!"); } return ret; } OTA_WEAK int ota_hal_read(unsigned int *off, char *out_buf, unsigned int out_buf_len) { int ret = -1; int temp_fd = -1; char dev_str[16] = {0}; int partition_id; if(ota_get_running_index()==0) partition_id = MTD_PART_ID_KERNEL2; else partition_id = MTD_PART_ID_KERNEL; boot_part = partition_id; snprintf(dev_str, 15, "/dev/mtdblock%d", partition_id); temp_fd = open(dev_str, 0); if (temp_fd < 0) { OTA_LOG_E("open ota temp partition failed"); goto OTA_HAL_READ; } ret = lseek(temp_fd, (off_t)*off, SEEK_SET); if (ret < 0) { OTA_LOG_E("read lseek failed:%d", ret); goto OTA_HAL_READ; } ret = read(temp_fd, (void *)out_buf, out_buf_len); if (ret < 0) { OTA_LOG_E("read failed:%d", ret); goto OTA_HAL_READ; } OTA_HAL_READ: if (temp_fd >= 0) { close(temp_fd); temp_fd = -1; } return ret; }
5,267
14,668
<gh_stars>1000+ // Copyright 2020 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/accessibility/live_caption_speech_recognition_host.h" #include <memory> #include <utility> #include "chrome/browser/accessibility/caption_bubble_context_browser.h" #include "chrome/browser/accessibility/live_caption_controller_factory.h" #include "chrome/browser/profiles/profile.h" #include "components/live_caption/live_caption_controller.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/web_contents.h" #include "mojo/public/cpp/bindings/self_owned_receiver.h" namespace captions { // static void LiveCaptionSpeechRecognitionHost::Create( content::RenderFrameHost* frame_host, mojo::PendingReceiver<media::mojom::SpeechRecognitionRecognizerClient> receiver) { // The object is bound to the lifetime of |host| and the mojo // connection. See DocumentService for details. new LiveCaptionSpeechRecognitionHost(frame_host, std::move(receiver)); } LiveCaptionSpeechRecognitionHost::LiveCaptionSpeechRecognitionHost( content::RenderFrameHost* frame_host, mojo::PendingReceiver<media::mojom::SpeechRecognitionRecognizerClient> receiver) : DocumentService<media::mojom::SpeechRecognitionRecognizerClient>( frame_host, std::move(receiver)) { content::WebContents* web_contents = GetWebContents(); if (!web_contents) return; Observe(web_contents); context_ = CaptionBubbleContextBrowser::Create(web_contents); } LiveCaptionSpeechRecognitionHost::~LiveCaptionSpeechRecognitionHost() { LiveCaptionController* live_caption_controller = GetLiveCaptionController(); if (live_caption_controller) live_caption_controller->OnAudioStreamEnd(context_.get()); } void LiveCaptionSpeechRecognitionHost::OnSpeechRecognitionRecognitionEvent( const media::SpeechRecognitionResult& result, OnSpeechRecognitionRecognitionEventCallback reply) { LiveCaptionController* live_caption_controller = GetLiveCaptionController(); if (!live_caption_controller) { std::move(reply).Run(false); return; } std::move(reply).Run( live_caption_controller->DispatchTranscription(context_.get(), result)); } void LiveCaptionSpeechRecognitionHost::OnLanguageIdentificationEvent( media::mojom::LanguageIdentificationEventPtr event) { LiveCaptionController* live_caption_controller = GetLiveCaptionController(); if (!live_caption_controller) return; live_caption_controller->OnLanguageIdentificationEvent(std::move(event)); } void LiveCaptionSpeechRecognitionHost::OnSpeechRecognitionError() { LiveCaptionController* live_caption_controller = GetLiveCaptionController(); if (live_caption_controller) live_caption_controller->OnError(context_.get()); } #if defined(OS_MAC) || defined(OS_CHROMEOS) void LiveCaptionSpeechRecognitionHost::MediaEffectivelyFullscreenChanged( bool is_fullscreen) { LiveCaptionController* live_caption_controller = GetLiveCaptionController(); if (live_caption_controller) live_caption_controller->OnToggleFullscreen(context_.get()); } #endif content::WebContents* LiveCaptionSpeechRecognitionHost::GetWebContents() { return content::WebContents::FromRenderFrameHost(render_frame_host()); } LiveCaptionController* LiveCaptionSpeechRecognitionHost::GetLiveCaptionController() { content::WebContents* web_contents = GetWebContents(); if (!web_contents) return nullptr; Profile* profile = Profile::FromBrowserContext(web_contents->GetBrowserContext()); if (!profile) return nullptr; return LiveCaptionControllerFactory::GetForProfile(profile); } } // namespace captions
1,223
348
{"nom":"Eragny-sur-Epte","circ":"2ème circonscription","dpt":"Oise","inscrits":451,"abs":265,"votants":186,"blancs":13,"nuls":2,"exp":171,"res":[{"nuance":"REM","nom":"<NAME>","voix":98},{"nuance":"FN","nom":"<NAME>","voix":73}]}
94
370
// Copyright (c) 2018 <NAME>. All rights reserved. // #pragma once #include <bitset> #include <iostream> #include <smf/rpc_generated.h> namespace std { inline ostream & operator<<(ostream &o, const ::smf::rpc::header &h) { o << "rpc::header={compression:" << ::smf::rpc::EnumNamecompression_flags(h.compression()) << ", header_bit_flags:" << std::bitset<8>(static_cast<uint8_t>(h.bitflags())) << ", session:" << h.session() << ", size:" << h.size() << ", checksum:" << h.checksum() << ", meta:" << h.meta() << "}"; return o; } } // namespace std
225
765
<filename>src/systemc/tests/systemc/datatypes/misc/concat/test03/test03.cpp /***************************************************************************** Licensed to Accellera Systems Initiative Inc. (Accellera) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Accellera licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *****************************************************************************/ /***************************************************************************** test03.cpp -- Original Author: <NAME>, Forte Design Systems, 7 Apr 2005 *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation, Date: Description of Modification: *****************************************************************************/ // test of l-value concatenation #include "systemc.h" int sc_main( int, char*[] ) { sc_uint<2> uint2a; sc_int<2> int2a; const sc_uint<2> uint2c( "10" ); const sc_uint<2> uint2d( "01" ); sc_biguint<4> biguint4a; sc_bigint<4> bigint4a( "1111" ); cout << "( uint2a, int2a ) = \"0110\"" << endl; ( uint2a, int2a ) = "0110"; cout << "uint2a = " << uint2a << endl; cout << "int2a = " << int2a << endl; cout << "biguint4a = ( uint2a, int2a )" << endl; biguint4a = ( uint2a, int2a ); cout << "biguint4a = " << biguint4a << endl; cout << "biguint4a = ( uint2c, uint2d )" << endl; biguint4a = ( uint2c, uint2d ); cout << "biguint4a = " << biguint4a << endl; cout << "( biguint4a.range( 2, 1 ), uint2a ) = \"0110\"" << endl; ( biguint4a.range( 2, 1 ), uint2a ) = "0110"; cout << "biguint4a = " << biguint4a << endl; cout << "uint2a = " << uint2a << endl; #if 0 cout << "( uint2a, biguint4a.range( 1, 2 ) ) = \"0101\"" << endl; ( uint2a, biguint4a.range( 1, 2 ) ) = "0101"; cout << "biguint4a = " << biguint4a << endl; cout << "uint2a = " << uint2a << endl; #endif // 0 cout << "( biguint4a.range( 2, 1 ), bigint4a.range( 2, 1 ) ) = \"1100\"" << endl; ( biguint4a.range( 2, 1 ), bigint4a.range( 2, 1 ) ) = "1100"; cout << "biguint4a = " << biguint4a << endl; cout << "bigint4a = " << bigint4a << endl; cout << "( ( uint2a, int2a ), biguint4a ) = \"00110011\"" << endl; ( ( uint2a, int2a ), biguint4a ) = "00110011"; cout << "uint2a = " << uint2a << endl; cout << "int2a = " << int2a << endl; cout << "biguint4a = " << biguint4a << endl; cout << "( biguint4a, ( uint2a, int2a ) ) = \"11001100\"" << endl; ( biguint4a, ( uint2a, int2a ) ) = "11001100"; cout << "biguint4a = " << biguint4a << endl; cout << "uint2a = " << uint2a << endl; cout << "int2a = " << int2a << endl; cout << "( ( uint2a, int2a ), ( biguint4a, bigint4a ) ) = \"011000001111\"" << endl; ( ( uint2a, int2a ), ( biguint4a, bigint4a ) ) = "011000001111"; cout << "uint2a = " << uint2a << endl; cout << "int2a = " << int2a << endl; cout << "biguint4a = " << biguint4a << endl; cout << "bigint4a = " << bigint4a << endl; cout << "( ( uint2a, int2a ), biguint4a.range( 2, 1 ) ) = \"001111\"" << endl; ( ( uint2a, int2a ), biguint4a.range( 2, 1 ) ) = "001111"; cout << "uint2a = " << uint2a << endl; cout << "int2a = " << int2a << endl; cout << "biguint4a = " << biguint4a << endl; cout << "( biguint4a.range( 2, 1 ), ( uint2a, int2a ) ) = \"001100\"" << endl; ( biguint4a.range( 2, 1 ), ( uint2a, int2a ) ) = "001100"; cout << "biguint4a = " << biguint4a << endl; cout << "uint2a = " << uint2a << endl; cout << "int2a = " << int2a << endl; return 0; }
1,665
1,401
package com.github.jvmgo.instructions.control; import com.github.jvmgo.instructions.base.BranchInstruction; import com.github.jvmgo.instructions.base.BytecodeReader; import com.github.jvmgo.rtda.Frame; public class goto_ extends BranchInstruction { @Override public int getOpCode() { return 0xa7; } @Override public void fetchOperands(BytecodeReader reader) throws Exception { this.offset = reader.read16(); } @Override public void execute(Frame frame) throws Exception { branch(frame, offset); } }
206
434
<filename>openwrt-18.06/package/utils/fritz-tools/src/fritz_cal_extract.c /* * A tool for reading the zlib compressed calibration data * found in AVM Fritz!Box based devices). * * Copyright (c) 2017 <NAME> <<EMAIL>> * * Based on zpipe, which is an example of proper use of zlib's inflate(). * that is Not copyrighted -- provided to the public domain * Version 1.4 11 December 2005 <NAME> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <stdio.h> #include <string.h> #include <assert.h> #include <unistd.h> #include <stdint.h> #include <stdlib.h> #include <endian.h> #include <errno.h> #include "zlib.h" #define CHUNK 1024 static inline size_t special_min(size_t a, size_t b) { return a == 0 ? b : (a < b ? a : b); } /* Decompress from file source to file dest until stream ends or EOF. inf() returns Z_OK on success, Z_MEM_ERROR if memory could not be allocated for processing, Z_DATA_ERROR if the deflate data is invalid or incomplete, Z_VERSION_ERROR if the version of zlib.h and the version of the library linked do not match, or Z_ERRNO if there is an error reading or writing the files. */ static int inf(FILE *source, FILE *dest, size_t limit, size_t skip) { int ret; size_t have; z_stream strm; unsigned char in[CHUNK]; unsigned char out[CHUNK]; /* allocate inflate state */ strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.opaque = Z_NULL; strm.avail_in = 0; strm.next_in = Z_NULL; ret = inflateInit(&strm); if (ret != Z_OK) return ret; /* decompress until deflate stream ends or end of file */ do { strm.avail_in = fread(in, 1, CHUNK, source); if (ferror(source)) { (void)inflateEnd(&strm); return Z_ERRNO; } if (strm.avail_in == 0) break; strm.next_in = in; /* run inflate() on input until output buffer not full */ do { strm.avail_out = CHUNK; strm.next_out = out; ret = inflate(&strm, Z_NO_FLUSH); assert(ret != Z_STREAM_ERROR); /* state not clobbered */ switch (ret) { case Z_NEED_DICT: ret = Z_DATA_ERROR; /* and fall through */ case Z_DATA_ERROR: case Z_MEM_ERROR: (void)inflateEnd(&strm); return ret; } have = special_min(limit, CHUNK - strm.avail_out) - skip; if (fwrite(&out[skip], have, 1, dest) != 1 || ferror(dest)) { (void)inflateEnd(&strm); return Z_ERRNO; } skip = 0; limit -= have; } while (strm.avail_out == 0 && limit > 0); /* done when inflate() says it's done */ } while (ret != Z_STREAM_END && limit > 0); /* clean up and return */ (void)inflateEnd(&strm); return (limit == 0 ? Z_OK : (ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR)); } /* report a zlib or i/o error */ static void zerr(int ret) { switch (ret) { case Z_ERRNO: if (ferror(stdin)) fputs("error reading stdin\n", stderr); if (ferror(stdout)) fputs("error writing stdout\n", stderr); break; case Z_STREAM_ERROR: fputs("invalid compression level\n", stderr); break; case Z_DATA_ERROR: fputs("invalid or incomplete deflate data\n", stderr); break; case Z_MEM_ERROR: fputs("out of memory\n", stderr); break; case Z_VERSION_ERROR: fputs("zlib version mismatch!\n", stderr); } } static unsigned int get_num(char *str) { if (!strncmp("0x", str, 2)) return strtoul(str+2, NULL, 16); else return strtoul(str, NULL, 10); } static void usage(void) { fprintf(stderr, "Usage: fritz_cal_extract [-s seek offset] [-i skip] [-o output file] [-l limit] [infile] -e entry_id\n" "Finds and extracts zlib compressed calibration data in the EVA loader\n"); exit(EXIT_FAILURE); } struct cal_entry { uint16_t id; uint16_t len; } __attribute__((packed)); /* compress or decompress from stdin to stdout */ int main(int argc, char **argv) { struct cal_entry cal = { .len = 0 }; FILE *in = stdin; FILE *out = stdout; size_t limit = 0, skip = 0; int initial_offset = 0; int entry = -1; int ret; int opt; while ((opt = getopt(argc, argv, "s:e:o:l:i:")) != -1) { switch (opt) { case 's': initial_offset = (int)get_num(optarg); if (errno) { perror("Failed to parse seek offset"); goto out_bad; } break; case 'e': entry = (int) htobe16(get_num(optarg)); if (errno) { perror("Failed to entry id"); goto out_bad; } break; case 'o': out = fopen(optarg, "w"); if (!out) { perror("Failed to create output file"); goto out_bad; } break; case 'l': limit = (size_t)get_num(optarg); if (errno) { perror("Failed to parse limit"); goto out_bad; } break; case 'i': skip = (size_t)get_num(optarg); if (errno) { perror("Failed to parse skip"); goto out_bad; } break; default: /* '?' */ usage(); } } if (entry == -1) usage(); if (argc > 1 && optind <= argc) { in = fopen(argv[optind], "r"); if (!in) { perror("Failed to create output file"); goto out_bad; } } if (initial_offset) { ret = fseek(in, initial_offset, SEEK_CUR); if (ret) { perror("Failed to seek to calibration table"); goto out_bad; } } do { ret = fseek(in, be16toh(cal.len), SEEK_CUR); if (feof(in)) { fprintf(stderr, "Reached end of file, but didn't find the matching entry\n"); goto out_bad; } else if (ferror(in)) { perror("Failure during seek"); goto out_bad; } ret = fread(&cal, 1, sizeof cal, in); if (ret != sizeof cal) goto out_bad; } while (entry != cal.id || cal.id == 0xffff); if (cal.id == 0xffff) { fprintf(stderr, "Reached end of filesystem, but didn't find the matching entry\n"); goto out_bad; } ret = inf(in, out, limit, skip); if (ret == Z_OK) goto out; zerr(ret); out_bad: ret = EXIT_FAILURE; out: fclose(in); fclose(out); return ret; }
2,977
374
package me.hao0.diablo.common.convert; import com.google.common.base.Converter; /** * Author: haolin * Email: <EMAIL> */ public class BooleanConverter extends Converter<String, Boolean> { public static final BooleanConverter INSTANCE = new BooleanConverter(); private BooleanConverter(){} @Override protected Boolean doForward(String s) { return Boolean.parseBoolean(s); } @Override protected String doBackward(Boolean b) { return String.valueOf(b); } }
182
435
<reponame>amaajemyfren/data<filename>pycon-israel-2018/videos/advanced-celery-tricks-itamar-hartstein-pycon-israel-2018.json { "copyright_text": null, "description": "Advanced Celery Tricks - How we adapted and extended Celery to fit our data pipeline\n\nIn Singular, we have a data pipeline which consists of hundreds of thousands of daily tasks, in varying length (from less than a second to hours per task), and with complex dependencies between them. In addition, we integrate with hundreds of third-party providers, which means that tasks are not necessarily reliable / predictable, so we need to be robust to failures and delays and be able to monitor them easily. We found Celery to be highly suitable to our needs as a task infrastructure, especially due to its distributed nature, its support for various workflows and its modular design. In particular, the fact that it is compatible with multiple technologies for conveying messages (\"brokers\") and storing results (\"backends\") greatly appealed to us.\n\nIt wasn't an immediate fit however. We needed to extend Celery so it will fit our use cases: (1) We implemented a custom backend and a custom serialization method. (2) We tweaked the behavior of Celery's workflows (chains, groups and chords). (3) We needed to be able to update code easily without restarting workers. (4) and more..\n\nIn this session we will discuss how we adapted Celery to our needs, as well as tools we developed for working with it better, and various advanced tips & tricks.", "duration": 1444, "language": "eng", "recorded": "2018-06-05", "related_urls": [ { "label": "Conference schedule", "url": "https://il.pycon.org/2018/schedule/" }, { "label": "Talk slides", "url": "https://s3-eu-west-1.amazonaws.com/pyconil-data-amit/presentations/Itamar_Hartstein_Celery+-+PyCon+Presentation.pdf" } ], "speakers": [ "<NAME>" ], "tags": [ "celery" ], "thumbnail_url": "https://i.ytimg.com/vi/Bo6UtRhedjE/maxresdefault.jpg", "title": "Advanced Celery Tricks", "videos": [ { "type": "youtube", "url": "https://www.youtube.com/watch?v=Bo6UtRhedjE" } ] }
675
2,195
<reponame>liupeng68/mynews /* * Copyright (c) 2015 [<EMAIL> | <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.youku.service.download; import java.io.File; import java.io.FileInputStream; import java.util.ArrayList; import java.util.HashMap; import android.content.Context; import com.baseproject.utils.Logger; import com.youku.player.YoukuPlayerApplication; import com.youku.player.util.PlayerUtil; import com.youku.service.download.SDCardManager.SDCardInfo; /** * BaseDownload.下载管理抽象类 * * @author 刘仲男 <EMAIL> * @version v3.5 * @created time 2012-10-15 下午1:16:02 */ public abstract class BaseDownload implements IDownload { public Context context; /** SD卡列表 */ public ArrayList<SDCardInfo> sdCard_list; @Override public final boolean existsDownloadInfo(String videoId) { return getDownloadInfo(videoId) == null ? false : true; } @Override public final boolean isDownloadFinished(String vid) { DownloadInfo info = getDownloadInfo(vid); if (info != null && info.getState() == DownloadInfo.STATE_FINISH) return true; return false; } @Override public final DownloadInfo getDownloadInfo(String videoId) { if (sdCard_list == null && (sdCard_list = SDCardManager.getExternalStorageDirectory()) == null) { return null; } for (int i = 0; i < sdCard_list.size(); i++) { DownloadInfo info = getDownloadInfoBySavePath(sdCard_list.get(i).path + YoukuPlayerApplication.getDownloadPath() + videoId + "/"); if (info != null) { return info; } } return null; } /** * 根据存储路径获得DownloadInfo */ public final DownloadInfo getDownloadInfoBySavePath(String savePath) { try { File f = new File(savePath + FILE_NAME); if (f.exists() && f.isFile()) { String s = PlayerUtil.convertStreamToString(new FileInputStream( f)); DownloadInfo i = DownloadInfo.jsonToDownloadInfo(s); if (i != null && i.getState() != DownloadInfo.STATE_CANCEL) { i.savePath = savePath; return i; } } } catch (Exception e) { Logger.e("Download_BaseDownload", "getDownloadInfoBySavePath()#savePath:" + savePath, e); } return null; } /** * 重新获取正在下载的数据 * * @return */ protected HashMap<String, DownloadInfo> getNewDownloadingData() { HashMap<String, DownloadInfo> downloadingData = new HashMap<String, DownloadInfo>(); if (sdCard_list == null && (sdCard_list = SDCardManager.getExternalStorageDirectory()) == null) { return downloadingData; } for (int j = 0; j < sdCard_list.size(); j++) { File dir = new File(sdCard_list.get(j).path + YoukuPlayerApplication.getDownloadPath()); if (!dir.exists()) continue; String[] dirs = dir.list(); for (int i = dirs.length - 1; i >= 0; i--) { String vid = dirs[i]; DownloadInfo info = getDownloadInfoBySavePath(sdCard_list .get(j).path + YoukuPlayerApplication.getDownloadPath() + vid + "/"); if (info != null && info.getState() != DownloadInfo.STATE_FINISH && info.getState() != DownloadInfo.STATE_CANCEL) { info.downloadListener = new DownloadListenerImpl(context, info); downloadingData.put(info.taskId, info); } } } return downloadingData; } }
1,399
711
#include "vk_default_loader.h" #include "vulkan/vulkan.h" #if defined(_WIN32) #include <windows.h> typedef void* (*vkGetInstanceProcAddrFn)(void* lib, const char* procname); static vkGetInstanceProcAddrFn symLoader; static void* loaderWrap(VkInstance instance, const char* vkproc) { return (*symLoader)(instance, vkproc); } #elif defined(unix) || defined(__unix__) || defined(__unix) #include <dlfcn.h> static void* (*symLoader)(void* lib, const char* procname); static void* loaderWrap(VkInstance instance, const char* vkproc) { return (*symLoader)(instance, vkproc); } #elif defined(__APPLE__) && defined(__MACH__) // #include <GLFW/glfw3.h> // static void* loaderWrap(VkInstance instance, const char* vkproc) { // return glfwGetInstanceProcAddress(instance, vkproc); // } #endif void* getDefaultProcAddr() { #if defined(_WIN32) HMODULE libvulkan = LoadLibrary(TEXT("vulkan-1.dll")); if (libvulkan == NULL) { return NULL; } symLoader = (vkGetInstanceProcAddrFn)GetProcAddress(libvulkan, "vkGetInstanceProcAddr"); if (symLoader == NULL) { return NULL; } return &loaderWrap; #elif defined(__APPLE__) && defined(__MACH__) // return &loaderWrap; return NULL; #elif defined(unix) || defined(__unix__) || defined(__unix) void* libvulkan = dlopen("libvulkan.so", RTLD_NOW | RTLD_LOCAL); if (libvulkan == NULL) { return NULL; } symLoader = dlsym(libvulkan, "vkGetInstanceProcAddr"); if (symLoader == NULL) { return NULL; } return &loaderWrap; #else // Unknown operating system return NULL; #endif }
801
956
<filename>src/dpdk/drivers/net/nfp/nfpcore/nfp6000/nfp6000.h<gh_stars>100-1000 /* SPDX-License-Identifier: BSD-3-Clause * Copyright(c) 2018 Netronome Systems, Inc. * All rights reserved. */ #ifndef __NFP_NFP6000_H__ #define __NFP_NFP6000_H__ /* CPP Target IDs */ #define NFP_CPP_TARGET_INVALID 0 #define NFP_CPP_TARGET_NBI 1 #define NFP_CPP_TARGET_QDR 2 #define NFP_CPP_TARGET_ILA 6 #define NFP_CPP_TARGET_MU 7 #define NFP_CPP_TARGET_PCIE 9 #define NFP_CPP_TARGET_ARM 10 #define NFP_CPP_TARGET_CRYPTO 12 #define NFP_CPP_TARGET_ISLAND_XPB 14 /* Shared with CAP */ #define NFP_CPP_TARGET_ISLAND_CAP 14 /* Shared with XPB */ #define NFP_CPP_TARGET_CT_XPB 14 #define NFP_CPP_TARGET_LOCAL_SCRATCH 15 #define NFP_CPP_TARGET_CLS NFP_CPP_TARGET_LOCAL_SCRATCH #define NFP_ISL_EMEM0 24 #define NFP_MU_ADDR_ACCESS_TYPE_MASK 3ULL #define NFP_MU_ADDR_ACCESS_TYPE_DIRECT 2ULL static inline int nfp_cppat_mu_locality_lsb(int mode, int addr40) { switch (mode) { case 0 ... 3: return addr40 ? 38 : 30; default: return -EINVAL; } } #endif /* NFP_NFP6000_H */
643
478
<reponame>aerys/minko /* Copyright (c) 2014 Aerys 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 "minko/file/GeometryParser.hpp" #include "minko/render/IndexBuffer.hpp" #include "minko/render/VertexBuffer.hpp" #include "minko/geometry/Geometry.hpp" #include "minko/file/AssetLibrary.hpp" #include "minko/deserialize/TypeDeserializer.hpp" #include "minko/deserialize/Unpacker.hpp" #include "minko/file/Options.hpp" using namespace minko; using namespace minko::file; using namespace minko::deserialize; std::unordered_map<uint, std::function<std::shared_ptr<render::IndexBuffer>(std::string&, std::shared_ptr<render::AbstractContext>)>> GeometryParser::indexBufferParserFunctions; std::unordered_map<uint, std::function<std::shared_ptr<render::VertexBuffer>(std::string&, std::shared_ptr<render::AbstractContext>)>> GeometryParser::vertexBufferParserFunctions; void GeometryParser::initialize() { // Default 16-bit index. registerIndexBufferParserFunction( [](std::string& serializedindexBuffer, std::shared_ptr<render::AbstractContext> context) { return deserializeIndexBuffer<unsigned short>(serializedindexBuffer, context); }, 0 ); // 8-bit index. registerIndexBufferParserFunction( std::bind(&GeometryParser::deserializeIndexBufferChar, std::placeholders::_1, std::placeholders::_2), 1 ); // 32-bit index. registerIndexBufferParserFunction( [](std::string& serializedindexBuffer, std::shared_ptr<render::AbstractContext> context) { return deserializeIndexBuffer<unsigned int>(serializedindexBuffer, context); }, 2 ); registerVertexBufferParserFunction( std::bind(&GeometryParser::deserializeVertexBuffer, std::placeholders::_1, std::placeholders::_2), 0 ); } std::shared_ptr<render::VertexBuffer> GeometryParser::deserializeVertexBuffer(std::string& serializedVertexBuffer, std::shared_ptr<render::AbstractContext> context) { msgpack::type::tuple<std::string, std::vector<SerializeAttribute>> deserializedVertex; unpack(deserializedVertex, serializedVertexBuffer.data(), serializedVertexBuffer.size()); std::vector<float> vector = deserialize::TypeDeserializer::deserializeVector<float>(deserializedVertex.get<0>()); VertexBufferPtr vertexBuffer = render::VertexBuffer::create(context, vector); uint numAttributes = deserializedVertex.get<1>().size(); for (unsigned int attributesIndex = 0; attributesIndex < numAttributes; ++attributesIndex) vertexBuffer->addAttribute( deserializedVertex.get<1>()[attributesIndex].get<0>(), deserializedVertex.get<1>()[attributesIndex].get<1>(), deserializedVertex.get<1>()[attributesIndex].get<2>()); return vertexBuffer; } GeometryParser::IndexBufferPtr GeometryParser::deserializeIndexBufferChar(std::string& serializedIndexBuffer, std::shared_ptr<render::AbstractContext> context) { std::vector<unsigned short> vector = deserialize::TypeDeserializer::deserializeVector<unsigned short, unsigned char>(serializedIndexBuffer); return render::IndexBuffer::create(context, vector); } void GeometryParser::parse(const std::string& filename, const std::string& resolvedFilename, std::shared_ptr<Options> options, const std::vector<unsigned char>& data, std::shared_ptr<AssetLibrary> assetLibrary) { if (!readHeader(filename, data, 0x47)) return; std::string folderPathName = extractFolderPath(resolvedFilename); geometry::Geometry::Ptr geom = geometry::Geometry::Ptr(); SerializedGeometry serializedGeometry; extractDependencies(assetLibrary, data, _headerSize, _dependencySize, options, folderPathName); unpack(serializedGeometry, data, _sceneDataSize, _headerSize + _dependencySize); static auto nameId = 0; auto uniqueName = serializedGeometry.get<1>(); while (assetLibrary->geometry(uniqueName) != nullptr) uniqueName = "geometry" + std::to_string(nameId++); geom = geometry::Geometry::create(uniqueName); assetLibrary->geometry(uniqueName, geom); _lastParsedAssetName = uniqueName; uint indexBufferFunction = 0; uint vertexBufferFunction = 0; computeMetaData(serializedGeometry.get<0>(), indexBufferFunction, vertexBufferFunction); geom->indices(indexBufferParserFunctions[indexBufferFunction](serializedGeometry.get<2>(), options->context())); for (std::string serializedVertexBuffer : serializedGeometry.get<3>()) { geom->addVertexBuffer(vertexBufferParserFunctions[vertexBufferFunction](serializedVertexBuffer, options->context())); } geom = options->geometryFunction()(geom->name(), geom); if (options->disposeIndexBufferAfterLoading()) { geom->disposeIndexBufferData(); } if (options->disposeVertexBufferAfterLoading()) { geom->disposeVertexBufferData(); } complete()->execute(shared_from_this()); } void GeometryParser::computeMetaData(unsigned short metaData, uint& indexBufferFunctionId, uint& vertexBufferFunctionId) { indexBufferFunctionId = 0x00000000 + ((metaData >> 4) & 0x0F); vertexBufferFunctionId = 0x00000000 + (metaData & 0x0F); }
2,394
348
<filename>docs/data/leg-t2/051/05101439.json<gh_stars>100-1000 {"nom":"Pomacle","circ":"1ère circonscription","dpt":"Marne","inscrits":332,"abs":167,"votants":165,"blancs":9,"nuls":1,"exp":155,"res":[{"nuance":"LR","nom":"<NAME>","voix":101},{"nuance":"DIV","nom":"<NAME>","voix":54}]}
116
334
<reponame>SpongePowered/Common /* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.common.mixin.core.world.level.block; import org.spongepowered.api.world.server.ServerLocation; import org.spongepowered.api.world.server.ServerWorld; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import org.spongepowered.asm.mixin.injection.callback.LocalCapture; import org.spongepowered.common.bridge.world.level.block.entity.CampfireBlockEntityBridge; import org.spongepowered.common.bridge.world.damagesource.DamageSourceBridge; import org.spongepowered.common.mixin.core.block.BlockMixin; import org.spongepowered.common.util.MinecraftBlockDamageSource; import java.util.Optional; import net.minecraft.core.BlockPos; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.damagesource.DamageSource; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.CampfireCookingRecipe; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.CampfireBlock; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.CampfireBlockEntity; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.BlockHitResult; @Mixin(CampfireBlock.class) public abstract class CampfireBlockMixin extends BlockMixin { @Redirect(method = "entityInside", at = @At( value = "INVOKE", target = "Lnet/minecraft/world/entity/Entity;hurt(Lnet/minecraft/world/damagesource/DamageSource;F)Z" ) ) private boolean impl$spongeRedirectForFireDamage(final Entity self, final DamageSource source, final float damage, final BlockState blockState, final Level world, final BlockPos blockPos, final Entity entity) { if (self.level.isClientSide) { // Short Circuit return self.hurt(source, damage); } try { final ServerLocation location = ServerLocation.of((ServerWorld) world, blockPos.getX(), blockPos.getY(), blockPos.getZ()); final DamageSource fire = MinecraftBlockDamageSource.ofFire("inFire", location, true); ((DamageSourceBridge) fire).bridge$setFireSource(); return self.hurt(DamageSource.IN_FIRE, damage); } finally { // Since "source" is already the DamageSource.IN_FIRE object, we can re-use it to re-assign. ((DamageSourceBridge) source).bridge$setFireSource(); } } @Inject(method = "use", locals = LocalCapture.CAPTURE_FAILEXCEPTION, at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/block/entity/CampfireBlockEntity;placeFood(Lnet/minecraft/world/item/ItemStack;I)Z")) public void impl$placeFood(BlockState p_225533_1_, Level p_225533_2_, BlockPos p_225533_3_, Player p_225533_4_, InteractionHand p_225533_5_, BlockHitResult p_225533_6_, CallbackInfoReturnable<InteractionResult> cir, BlockEntity tileEntity, CampfireBlockEntity campfire, ItemStack itemStack, Optional<CampfireCookingRecipe> optional) { ((CampfireBlockEntityBridge) campfire).bridge$placeRecipe(optional.get()); } }
1,564
4,772
<filename>jpa/deferred/src/main/java/example/repo/Customer228Repository.java<gh_stars>1000+ package example.repo; import example.model.Customer228; import java.util.List; import org.springframework.data.repository.CrudRepository; public interface Customer228Repository extends CrudRepository<Customer228, Long> { List<Customer228> findByLastName(String lastName); }
117
3,194
/** * Copyright (c) 2011-2021, <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.jfinal.proxy; import java.util.Map; import java.util.Objects; import java.util.concurrent.atomic.AtomicLong; import com.jfinal.kit.SyncWriteMap; /** * ProxyMethodCache */ public class ProxyMethodCache { private static final AtomicLong atomicLong = new AtomicLong(); private static final Map<Long, ProxyMethod> cache = new SyncWriteMap<>(2048, 0.25F); public static Long generateKey() { return atomicLong.incrementAndGet(); } public static void put(ProxyMethod proxyMethod) { Objects.requireNonNull(proxyMethod, "proxyMethod can not be null"); Objects.requireNonNull(proxyMethod.getKey(), "the key of proxyMethod can not be null"); if (cache.containsKey(proxyMethod.getKey())) { throw new RuntimeException("the key of proxyMethod already exists"); } cache.putIfAbsent(proxyMethod.getKey(), proxyMethod); } public static ProxyMethod get(Long key) { return cache.get(key); } }
538
2,151
// © 2016 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html /* ******************************************************************************* * * Copyright (C) 2005-2012, International Business Machines * Corporation and others. All Rights Reserved. * ******************************************************************************* * file name: writesrc.h * encoding: UTF-8 * tab size: 8 (not used) * indentation:4 * * created on: 2005apr23 * created by: <NAME> * * Helper functions for writing source code for data. */ #ifndef __WRITESRC_H__ #define __WRITESRC_H__ #include <stdio.h> #include "unicode/utypes.h" #include "utrie2.h" /** * Creates a source text file and writes a header comment with the ICU copyright. * Writes a C/Java-style comment with the generator name. */ U_CAPI FILE * U_EXPORT2 usrc_create(const char *path, const char *filename, const char *generator); /** * Creates a source text file and writes a header comment with the ICU copyright. * Writes the comment with # lines, as used in scripts and text data. */ U_CAPI FILE * U_EXPORT2 usrc_createTextData(const char *path, const char *filename, const char *generator); /** * Writes the contents of an array of 8/16/32-bit words. * The prefix and postfix are optional (can be NULL) and are written first/last. * The prefix may contain a %ld or similar field for the array length. * The {} and declaration etc. need to be included in prefix/postfix or * printed before and after the array contents. */ U_CAPI void U_EXPORT2 usrc_writeArray(FILE *f, const char *prefix, const void *p, int32_t width, int32_t length, const char *postfix); /** * Calls usrc_writeArray() for the index and data arrays of a frozen UTrie2. * Only the index array is written for a 16-bit UTrie2. In this case, dataPrefix * is ignored and can be NULL. */ U_CAPI void U_EXPORT2 usrc_writeUTrie2Arrays(FILE *f, const char *indexPrefix, const char *dataPrefix, const UTrie2 *pTrie, const char *postfix); /** * Writes the UTrie2 struct values. * The {} and declaration etc. need to be included in prefix/postfix or * printed before and after the array contents. */ U_CAPI void U_EXPORT2 usrc_writeUTrie2Struct(FILE *f, const char *prefix, const UTrie2 *pTrie, const char *indexName, const char *dataName, const char *postfix); /** * Writes the contents of an array of mostly invariant characters. * Characters 0..0x1f are printed as numbers, * others as characters with single quotes: '%c'. * * The prefix and postfix are optional (can be NULL) and are written first/last. * The prefix may contain a %ld or similar field for the array length. * The {} and declaration etc. need to be included in prefix/postfix or * printed before and after the array contents. */ U_CAPI void U_EXPORT2 usrc_writeArrayOfMostlyInvChars(FILE *f, const char *prefix, const char *p, int32_t length, const char *postfix); #endif
1,204
469
<reponame>born2snipe/mini2Dx /******************************************************************************* * Copyright 2019 See AUTHORS file * * 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.badlogic.gdx.graphics; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.graphics.g2d.TextureRegion; public class LibgdxTextureRegionWrapper extends TextureRegion { /** Constructs a region with no texture and no coordinates defined. */ public LibgdxTextureRegionWrapper () { } /** Constructs a region the size of the specified texture. */ public LibgdxTextureRegionWrapper (Texture texture) { super(texture); flip(false, true); } /** @param width The width of the texture region. May be negative to flip the sprite when drawn. * @param height The height of the texture region. May be negative to flip the sprite when drawn. */ public LibgdxTextureRegionWrapper (Texture texture, int width, int height) { super(texture, width, height); flip(false, true); } /** @param width The width of the texture region. May be negative to flip the sprite when drawn. * @param height The height of the texture region. May be negative to flip the sprite when drawn. */ public LibgdxTextureRegionWrapper (Texture texture, int x, int y, int width, int height) { super(texture, x, y, width, height); flip(false, true); } public LibgdxTextureRegionWrapper (Texture texture, float u, float v, float u2, float v2) { super(texture, u, v, u2, v2); flip(false, true); } /** Constructs a region with the same texture and coordinates of the specified region. */ public LibgdxTextureRegionWrapper (TextureRegion region) { if (region.getTexture() != null){ super.setRegion(region); } } /** Constructs a region with the same texture as the specified region and sets the coordinates relative to the specified region. * @param width The width of the texture region. May be negative to flip the sprite when drawn. * @param height The height of the texture region. May be negative to flip the sprite when drawn. */ public LibgdxTextureRegionWrapper (TextureRegion region, int x, int y, int width, int height) { super(region, x, y, width, height); flip(false, true); } /** * Constructs a region from an {@link TextureAtlas.AtlasRegion} * @param atlasRegion */ public LibgdxTextureRegionWrapper(TextureAtlas.AtlasRegion atlasRegion) { super(atlasRegion); flip(false, true); } @Override public boolean isFlipY() { return !super.isFlipY(); } @Override public int getRegionY() { setFlipY(!isFlipY()); int result = super.getRegionY(); setFlipY(!isFlipY()); return result; } /** * Sets if the {@link TextureRegion} is flipped * @param flipX True if the region is flipped horizontally * @param flipY True if the region is flipped vertically */ public void setFlip(boolean flipX, boolean flipY) { setFlipX(flipX); setFlipY(flipY); } /** * Sets if the {@link TextureRegion} is flipped horizontally * @param flipX True if the region is flipped horizontally */ public void setFlipX(boolean flipX) { if(flipX == isFlipX()) { return; } flip(true, false); } /** * Sets if the {@link TextureRegion} is flipped vertically * @param flipY True if the region is flipped vertically */ public void setFlipY(boolean flipY) { if(flipY == isFlipY()) { return; } flip(false, true); } public void setRegionHeight (int height) { if (!isFlipY()) { setV(getV2() + height / (float)getTexture().getHeight()); } else { setV2(getV() + height / (float)getTexture().getHeight()); } } }
1,299
2,151
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef IOS_CHROME_BROWSER_PAYMENTS_IOS_PAYMENT_INSTRUMENT_H_ #define IOS_CHROME_BROWSER_PAYMENTS_IOS_PAYMENT_INSTRUMENT_H_ #import <UIKit/UIKit.h> #include <map> #include <string> #include "base/macros.h" #include "base/strings/string16.h" #include "components/payments/core/payment_instrument.h" #include "ios/chrome/browser/payments/payment_request.h" #include "url/gurl.h" @class PaymentRequestUIDelegate; namespace payments { // A map is maintained to enumerate scheme names corresponding with iOS // payment apps. These scheme names are needed as a form of installation // check. If canOpenURL of UIApplication succeeds on the scheme name then // that's a guarantee that the app is installed on the user's device. // These scheme names MUST be enumerated in LSApplicationQueriesSchemes // in the plist file. const std::map<std::string, std::string>& GetMethodNameToSchemeName(); // Represents an iOS Native App as a form of payment in Payment Request. class IOSPaymentInstrument : public PaymentInstrument { public: // Initializes an IOSPaymentInstrument. |method_name| is the url payment // method identifier for this instrument. |universal_link| is the unique // link that is used to open the app from Chrome. |app_name| is the name // the iOS native payment app. The IOSPaymentInstrument takes ownership // of |icon_image| which is an icon that represents the app. // |payment_request_ui_delegate| is the UI class that manages opening // the native payment app from Chrome. IOSPaymentInstrument( const std::string& method_name, const GURL& universal_link, const std::string& app_name, UIImage* icon_image, id<PaymentRequestUIDelegate> payment_request_ui_delegate); ~IOSPaymentInstrument() override; // PaymentInstrument: void InvokePaymentApp(PaymentInstrument::Delegate* delegate) override; bool IsCompleteForPayment() const override; bool IsExactlyMatchingMerchantRequest() const override; base::string16 GetMissingInfoLabel() const override; bool IsValidForCanMakePayment() const override; void RecordUse() override; base::string16 GetLabel() const override; base::string16 GetSublabel() const override; bool IsValidForModifier(const std::vector<std::string>& methods, bool supported_networks_specified, const std::set<std::string>& supported_networks, bool supported_types_specified, const std::set<autofill::CreditCard::CardType>& supported_types) const override; // Given that the icon for the iOS payment instrument can only be determined // at run-time, the icon is obtained using this UIImage object rather than // using a resource ID and Chrome's resource bundle. UIImage* icon_image() const { return icon_image_; } private: std::string method_name_; GURL universal_link_; std::string app_name_; UIImage* icon_image_; id<PaymentRequestUIDelegate> payment_request_ui_delegate_; DISALLOW_COPY_AND_ASSIGN(IOSPaymentInstrument); }; } // namespace payments #endif // IOS_CHROME_BROWSER_PAYMENTS_IOS_PAYMENT_INSTRUMENT_H_
1,118
713
<reponame>franz1981/infinispan<gh_stars>100-1000 package org.infinispan.commands.write; import org.infinispan.commands.DataCommand; import org.infinispan.metadata.impl.PrivateMetadata; /** * Mixes features from DataCommand and WriteCommand * * @author <NAME> * @since 4.0 */ public interface DataWriteCommand extends WriteCommand, DataCommand { PrivateMetadata getInternalMetadata(); void setInternalMetadata(PrivateMetadata internalMetadata); @Override default PrivateMetadata getInternalMetadata(Object key) { return key.equals(getKey()) ? getInternalMetadata() : null; } @Override default void setInternalMetadata(Object key, PrivateMetadata internalMetadata) { if (key.equals(getKey())) { setInternalMetadata(internalMetadata); } } }
262
2,151
<reponame>X018/CCTOOL //===- llvm/Analysis/ScalarEvolution.h - Scalar Evolution -------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // The ScalarEvolution class is an LLVM pass which can be used to analyze and // categorize scalar expressions in loops. It specializes in recognizing // general induction variables, representing them with the abstract and opaque // SCEV class. Given this analysis, trip counts of loops and other important // properties can be obtained. // // This analysis is primarily useful for induction variable substitution and // strength reduction. // //===----------------------------------------------------------------------===// #ifndef LLVM_ANALYSIS_SCALAREVOLUTION_H #define LLVM_ANALYSIS_SCALAREVOLUTION_H #include "llvm/ADT/DenseSet.h" #include "llvm/ADT/FoldingSet.h" #include "llvm/ADT/SetVector.h" #include "llvm/Analysis/LoopInfo.h" #include "llvm/IR/ConstantRange.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/Operator.h" #include "llvm/IR/PassManager.h" #include "llvm/IR/ValueHandle.h" #include "llvm/IR/ValueMap.h" #include "llvm/Pass.h" #include "llvm/Support/Allocator.h" #include "llvm/Support/DataTypes.h" namespace llvm { class APInt; class AssumptionCache; class Constant; class ConstantInt; class DominatorTree; class Type; class ScalarEvolution; class DataLayout; class TargetLibraryInfo; class LLVMContext; class Operator; class SCEV; class SCEVAddRecExpr; class SCEVConstant; class SCEVExpander; class SCEVPredicate; class SCEVUnknown; class Function; template <> struct FoldingSetTrait<SCEV>; template <> struct FoldingSetTrait<SCEVPredicate>; /// This class represents an analyzed expression in the program. These are /// opaque objects that the client is not allowed to do much with directly. /// class SCEV : public FoldingSetNode { friend struct FoldingSetTrait<SCEV>; /// A reference to an Interned FoldingSetNodeID for this node. The /// ScalarEvolution's BumpPtrAllocator holds the data. FoldingSetNodeIDRef FastID; // The SCEV baseclass this node corresponds to const unsigned short SCEVType; protected: /// This field is initialized to zero and may be used in subclasses to store /// miscellaneous information. unsigned short SubclassData; private: SCEV(const SCEV &) = delete; void operator=(const SCEV &) = delete; public: /// NoWrapFlags are bitfield indices into SubclassData. /// /// Add and Mul expressions may have no-unsigned-wrap <NUW> or /// no-signed-wrap <NSW> properties, which are derived from the IR /// operator. NSW is a misnomer that we use to mean no signed overflow or /// underflow. /// /// AddRec expressions may have a no-self-wraparound <NW> property if, in /// the integer domain, abs(step) * max-iteration(loop) <= /// unsigned-max(bitwidth). This means that the recurrence will never reach /// its start value if the step is non-zero. Computing the same value on /// each iteration is not considered wrapping, and recurrences with step = 0 /// are trivially <NW>. <NW> is independent of the sign of step and the /// value the add recurrence starts with. /// /// Note that NUW and NSW are also valid properties of a recurrence, and /// either implies NW. For convenience, NW will be set for a recurrence /// whenever either NUW or NSW are set. enum NoWrapFlags { FlagAnyWrap = 0, // No guarantee. FlagNW = (1 << 0), // No self-wrap. FlagNUW = (1 << 1), // No unsigned wrap. FlagNSW = (1 << 2), // No signed wrap. NoWrapMask = (1 << 3) - 1 }; explicit SCEV(const FoldingSetNodeIDRef ID, unsigned SCEVTy) : FastID(ID), SCEVType(SCEVTy), SubclassData(0) {} unsigned getSCEVType() const { return SCEVType; } /// Return the LLVM type of this SCEV expression. /// Type *getType() const; /// Return true if the expression is a constant zero. /// bool isZero() const; /// Return true if the expression is a constant one. /// bool isOne() const; /// Return true if the expression is a constant all-ones value. /// bool isAllOnesValue() const; /// Return true if the specified scev is negated, but not a constant. bool isNonConstantNegative() const; /// Print out the internal representation of this scalar to the specified /// stream. This should really only be used for debugging purposes. void print(raw_ostream &OS) const; /// This method is used for debugging. /// void dump() const; }; // Specialize FoldingSetTrait for SCEV to avoid needing to compute // temporary FoldingSetNodeID values. template <> struct FoldingSetTrait<SCEV> : DefaultFoldingSetTrait<SCEV> { static void Profile(const SCEV &X, FoldingSetNodeID &ID) { ID = X.FastID; } static bool Equals(const SCEV &X, const FoldingSetNodeID &ID, unsigned IDHash, FoldingSetNodeID &TempID) { return ID == X.FastID; } static unsigned ComputeHash(const SCEV &X, FoldingSetNodeID &TempID) { return X.FastID.ComputeHash(); } }; inline raw_ostream &operator<<(raw_ostream &OS, const SCEV &S) { S.print(OS); return OS; } /// An object of this class is returned by queries that could not be answered. /// For example, if you ask for the number of iterations of a linked-list /// traversal loop, you will get one of these. None of the standard SCEV /// operations are valid on this class, it is just a marker. struct SCEVCouldNotCompute : public SCEV { SCEVCouldNotCompute(); /// Methods for support type inquiry through isa, cast, and dyn_cast: static bool classof(const SCEV *S); }; /// This class represents an assumption made using SCEV expressions which can /// be checked at run-time. class SCEVPredicate : public FoldingSetNode { friend struct FoldingSetTrait<SCEVPredicate>; /// A reference to an Interned FoldingSetNodeID for this node. The /// ScalarEvolution's BumpPtrAllocator holds the data. FoldingSetNodeIDRef FastID; public: enum SCEVPredicateKind { P_Union, P_Equal, P_Wrap }; protected: SCEVPredicateKind Kind; ~SCEVPredicate() = default; SCEVPredicate(const SCEVPredicate &) = default; SCEVPredicate &operator=(const SCEVPredicate &) = default; public: SCEVPredicate(const FoldingSetNodeIDRef ID, SCEVPredicateKind Kind); SCEVPredicateKind getKind() const { return Kind; } /// Returns the estimated complexity of this predicate. This is roughly /// measured in the number of run-time checks required. virtual unsigned getComplexity() const { return 1; } /// Returns true if the predicate is always true. This means that no /// assumptions were made and nothing needs to be checked at run-time. virtual bool isAlwaysTrue() const = 0; /// Returns true if this predicate implies \p N. virtual bool implies(const SCEVPredicate *N) const = 0; /// Prints a textual representation of this predicate with an indentation of /// \p Depth. virtual void print(raw_ostream &OS, unsigned Depth = 0) const = 0; /// Returns the SCEV to which this predicate applies, or nullptr if this is /// a SCEVUnionPredicate. virtual const SCEV *getExpr() const = 0; }; inline raw_ostream &operator<<(raw_ostream &OS, const SCEVPredicate &P) { P.print(OS); return OS; } // Specialize FoldingSetTrait for SCEVPredicate to avoid needing to compute // temporary FoldingSetNodeID values. template <> struct FoldingSetTrait<SCEVPredicate> : DefaultFoldingSetTrait<SCEVPredicate> { static void Profile(const SCEVPredicate &X, FoldingSetNodeID &ID) { ID = X.FastID; } static bool Equals(const SCEVPredicate &X, const FoldingSetNodeID &ID, unsigned IDHash, FoldingSetNodeID &TempID) { return ID == X.FastID; } static unsigned ComputeHash(const SCEVPredicate &X, FoldingSetNodeID &TempID) { return X.FastID.ComputeHash(); } }; /// This class represents an assumption that two SCEV expressions are equal, /// and this can be checked at run-time. We assume that the left hand side is /// a SCEVUnknown and the right hand side a constant. class SCEVEqualPredicate final : public SCEVPredicate { /// We assume that LHS == RHS, where LHS is a SCEVUnknown and RHS a /// constant. const SCEVUnknown *LHS; const SCEVConstant *RHS; public: SCEVEqualPredicate(const FoldingSetNodeIDRef ID, const SCEVUnknown *LHS, const SCEVConstant *RHS); /// Implementation of the SCEVPredicate interface bool implies(const SCEVPredicate *N) const override; void print(raw_ostream &OS, unsigned Depth = 0) const override; bool isAlwaysTrue() const override; const SCEV *getExpr() const override; /// Returns the left hand side of the equality. const SCEVUnknown *getLHS() const { return LHS; } /// Returns the right hand side of the equality. const SCEVConstant *getRHS() const { return RHS; } /// Methods for support type inquiry through isa, cast, and dyn_cast: static inline bool classof(const SCEVPredicate *P) { return P->getKind() == P_Equal; } }; /// This class represents an assumption made on an AddRec expression. Given an /// affine AddRec expression {a,+,b}, we assume that it has the nssw or nusw /// flags (defined below) in the first X iterations of the loop, where X is a /// SCEV expression returned by getPredicatedBackedgeTakenCount). /// /// Note that this does not imply that X is equal to the backedge taken /// count. This means that if we have a nusw predicate for i32 {0,+,1} with a /// predicated backedge taken count of X, we only guarantee that {0,+,1} has /// nusw in the first X iterations. {0,+,1} may still wrap in the loop if we /// have more than X iterations. class SCEVWrapPredicate final : public SCEVPredicate { public: /// Similar to SCEV::NoWrapFlags, but with slightly different semantics /// for FlagNUSW. The increment is considered to be signed, and a + b /// (where b is the increment) is considered to wrap if: /// zext(a + b) != zext(a) + sext(b) /// /// If Signed is a function that takes an n-bit tuple and maps to the /// integer domain as the tuples value interpreted as twos complement, /// and Unsigned a function that takes an n-bit tuple and maps to the /// integer domain as as the base two value of input tuple, then a + b /// has IncrementNUSW iff: /// /// 0 <= Unsigned(a) + Signed(b) < 2^n /// /// The IncrementNSSW flag has identical semantics with SCEV::FlagNSW. /// /// Note that the IncrementNUSW flag is not commutative: if base + inc /// has IncrementNUSW, then inc + base doesn't neccessarily have this /// property. The reason for this is that this is used for sign/zero /// extending affine AddRec SCEV expressions when a SCEVWrapPredicate is /// assumed. A {base,+,inc} expression is already non-commutative with /// regards to base and inc, since it is interpreted as: /// (((base + inc) + inc) + inc) ... enum IncrementWrapFlags { IncrementAnyWrap = 0, // No guarantee. IncrementNUSW = (1 << 0), // No unsigned with signed increment wrap. IncrementNSSW = (1 << 1), // No signed with signed increment wrap // (equivalent with SCEV::NSW) IncrementNoWrapMask = (1 << 2) - 1 }; /// Convenient IncrementWrapFlags manipulation methods. LLVM_NODISCARD static SCEVWrapPredicate::IncrementWrapFlags clearFlags(SCEVWrapPredicate::IncrementWrapFlags Flags, SCEVWrapPredicate::IncrementWrapFlags OffFlags) { assert((Flags & IncrementNoWrapMask) == Flags && "Invalid flags value!"); assert((OffFlags & IncrementNoWrapMask) == OffFlags && "Invalid flags value!"); return (SCEVWrapPredicate::IncrementWrapFlags)(Flags & ~OffFlags); } LLVM_NODISCARD static SCEVWrapPredicate::IncrementWrapFlags maskFlags(SCEVWrapPredicate::IncrementWrapFlags Flags, int Mask) { assert((Flags & IncrementNoWrapMask) == Flags && "Invalid flags value!"); assert((Mask & IncrementNoWrapMask) == Mask && "Invalid mask value!"); return (SCEVWrapPredicate::IncrementWrapFlags)(Flags & Mask); } LLVM_NODISCARD static SCEVWrapPredicate::IncrementWrapFlags setFlags(SCEVWrapPredicate::IncrementWrapFlags Flags, SCEVWrapPredicate::IncrementWrapFlags OnFlags) { assert((Flags & IncrementNoWrapMask) == Flags && "Invalid flags value!"); assert((OnFlags & IncrementNoWrapMask) == OnFlags && "Invalid flags value!"); return (SCEVWrapPredicate::IncrementWrapFlags)(Flags | OnFlags); } /// Returns the set of SCEVWrapPredicate no wrap flags implied by a /// SCEVAddRecExpr. LLVM_NODISCARD static SCEVWrapPredicate::IncrementWrapFlags getImpliedFlags(const SCEVAddRecExpr *AR, ScalarEvolution &SE); private: const SCEVAddRecExpr *AR; IncrementWrapFlags Flags; public: explicit SCEVWrapPredicate(const FoldingSetNodeIDRef ID, const SCEVAddRecExpr *AR, IncrementWrapFlags Flags); /// Returns the set assumed no overflow flags. IncrementWrapFlags getFlags() const { return Flags; } /// Implementation of the SCEVPredicate interface const SCEV *getExpr() const override; bool implies(const SCEVPredicate *N) const override; void print(raw_ostream &OS, unsigned Depth = 0) const override; bool isAlwaysTrue() const override; /// Methods for support type inquiry through isa, cast, and dyn_cast: static inline bool classof(const SCEVPredicate *P) { return P->getKind() == P_Wrap; } }; /// This class represents a composition of other SCEV predicates, and is the /// class that most clients will interact with. This is equivalent to a /// logical "AND" of all the predicates in the union. /// /// NB! Unlike other SCEVPredicate sub-classes this class does not live in the /// ScalarEvolution::Preds folding set. This is why the \c add function is sound. class SCEVUnionPredicate final : public SCEVPredicate { private: typedef DenseMap<const SCEV *, SmallVector<const SCEVPredicate *, 4>> PredicateMap; /// Vector with references to all predicates in this union. SmallVector<const SCEVPredicate *, 16> Preds; /// Maps SCEVs to predicates for quick look-ups. PredicateMap SCEVToPreds; public: SCEVUnionPredicate(); const SmallVectorImpl<const SCEVPredicate *> &getPredicates() const { return Preds; } /// Adds a predicate to this union. void add(const SCEVPredicate *N); /// Returns a reference to a vector containing all predicates which apply to /// \p Expr. ArrayRef<const SCEVPredicate *> getPredicatesForExpr(const SCEV *Expr); /// Implementation of the SCEVPredicate interface bool isAlwaysTrue() const override; bool implies(const SCEVPredicate *N) const override; void print(raw_ostream &OS, unsigned Depth) const override; const SCEV *getExpr() const override; /// We estimate the complexity of a union predicate as the size number of /// predicates in the union. unsigned getComplexity() const override { return Preds.size(); } /// Methods for support type inquiry through isa, cast, and dyn_cast: static inline bool classof(const SCEVPredicate *P) { return P->getKind() == P_Union; } }; /// The main scalar evolution driver. Because client code (intentionally) /// can't do much with the SCEV objects directly, they must ask this class /// for services. class ScalarEvolution { public: /// An enum describing the relationship between a SCEV and a loop. enum LoopDisposition { LoopVariant, ///< The SCEV is loop-variant (unknown). LoopInvariant, ///< The SCEV is loop-invariant. LoopComputable ///< The SCEV varies predictably with the loop. }; /// An enum describing the relationship between a SCEV and a basic block. enum BlockDisposition { DoesNotDominateBlock, ///< The SCEV does not dominate the block. DominatesBlock, ///< The SCEV dominates the block. ProperlyDominatesBlock ///< The SCEV properly dominates the block. }; /// Convenient NoWrapFlags manipulation that hides enum casts and is /// visible in the ScalarEvolution name space. LLVM_NODISCARD static SCEV::NoWrapFlags maskFlags(SCEV::NoWrapFlags Flags, int Mask) { return (SCEV::NoWrapFlags)(Flags & Mask); } LLVM_NODISCARD static SCEV::NoWrapFlags setFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags OnFlags) { return (SCEV::NoWrapFlags)(Flags | OnFlags); } LLVM_NODISCARD static SCEV::NoWrapFlags clearFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags OffFlags) { return (SCEV::NoWrapFlags)(Flags & ~OffFlags); } private: /// A CallbackVH to arrange for ScalarEvolution to be notified whenever a /// Value is deleted. class SCEVCallbackVH final : public CallbackVH { ScalarEvolution *SE; void deleted() override; void allUsesReplacedWith(Value *New) override; public: SCEVCallbackVH(Value *V, ScalarEvolution *SE = nullptr); }; friend class SCEVCallbackVH; friend class SCEVExpander; friend class SCEVUnknown; /// The function we are analyzing. /// Function &F; /// Does the module have any calls to the llvm.experimental.guard intrinsic /// at all? If this is false, we avoid doing work that will only help if /// thare are guards present in the IR. /// bool HasGuards; /// The target library information for the target we are targeting. /// TargetLibraryInfo &TLI; /// The tracker for @llvm.assume intrinsics in this function. AssumptionCache &AC; /// The dominator tree. /// DominatorTree &DT; /// The loop information for the function we are currently analyzing. /// LoopInfo &LI; /// This SCEV is used to represent unknown trip counts and things. std::unique_ptr<SCEVCouldNotCompute> CouldNotCompute; /// The typedef for HasRecMap. /// typedef DenseMap<const SCEV *, bool> HasRecMapType; /// This is a cache to record whether a SCEV contains any scAddRecExpr. HasRecMapType HasRecMap; /// The typedef for ExprValueMap. /// typedef std::pair<Value *, ConstantInt *> ValueOffsetPair; typedef DenseMap<const SCEV *, SetVector<ValueOffsetPair>> ExprValueMapType; /// ExprValueMap -- This map records the original values from which /// the SCEV expr is generated from. /// /// We want to represent the mapping as SCEV -> ValueOffsetPair instead /// of SCEV -> Value: /// Suppose we know S1 expands to V1, and /// S1 = S2 + C_a /// S3 = S2 + C_b /// where C_a and C_b are different SCEVConstants. Then we'd like to /// expand S3 as V1 - C_a + C_b instead of expanding S2 literally. /// It is helpful when S2 is a complex SCEV expr. /// /// In order to do that, we represent ExprValueMap as a mapping from /// SCEV to ValueOffsetPair. We will save both S1->{V1, 0} and /// S2->{V1, C_a} into the map when we create SCEV for V1. When S3 /// is expanded, it will first expand S2 to V1 - C_a because of /// S2->{V1, C_a} in the map, then expand S3 to V1 - C_a + C_b. /// /// Note: S->{V, Offset} in the ExprValueMap means S can be expanded /// to V - Offset. ExprValueMapType ExprValueMap; /// The typedef for ValueExprMap. /// typedef DenseMap<SCEVCallbackVH, const SCEV *, DenseMapInfo<Value *>> ValueExprMapType; /// This is a cache of the values we have analyzed so far. /// ValueExprMapType ValueExprMap; /// Mark predicate values currently being processed by isImpliedCond. SmallPtrSet<Value *, 6> PendingLoopPredicates; /// Set to true by isLoopBackedgeGuardedByCond when we're walking the set of /// conditions dominating the backedge of a loop. bool WalkingBEDominatingConds; /// Set to true by isKnownPredicateViaSplitting when we're trying to prove a /// predicate by splitting it into a set of independent predicates. bool ProvingSplitPredicate; /// Memoized values for the GetMinTrailingZeros DenseMap<const SCEV *, uint32_t> MinTrailingZerosCache; /// Private helper method for the GetMinTrailingZeros method uint32_t GetMinTrailingZerosImpl(const SCEV *S); /// Information about the number of loop iterations for which a loop exit's /// branch condition evaluates to the not-taken path. This is a temporary /// pair of exact and max expressions that are eventually summarized in /// ExitNotTakenInfo and BackedgeTakenInfo. struct ExitLimit { const SCEV *ExactNotTaken; // The exit is not taken exactly this many times const SCEV *MaxNotTaken; // The exit is not taken at most this many times bool MaxOrZero; // Not taken either exactly MaxNotTaken or zero times /// A set of predicate guards for this ExitLimit. The result is only valid /// if all of the predicates in \c Predicates evaluate to 'true' at /// run-time. SmallPtrSet<const SCEVPredicate *, 4> Predicates; void addPredicate(const SCEVPredicate *P) { assert(!isa<SCEVUnionPredicate>(P) && "Only add leaf predicates here!"); Predicates.insert(P); } /*implicit*/ ExitLimit(const SCEV *E) : ExactNotTaken(E), MaxNotTaken(E), MaxOrZero(false) {} ExitLimit( const SCEV *E, const SCEV *M, bool MaxOrZero, ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || !isa<SCEVCouldNotCompute>(MaxNotTaken)) && "Exact is not allowed to be less precise than Max"); for (auto *PredSet : PredSetList) for (auto *P : *PredSet) addPredicate(P); } ExitLimit(const SCEV *E, const SCEV *M, bool MaxOrZero, const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) : ExitLimit(E, M, MaxOrZero, {&PredSet}) {} ExitLimit(const SCEV *E, const SCEV *M, bool MaxOrZero) : ExitLimit(E, M, MaxOrZero, None) {} /// Test whether this ExitLimit contains any computed information, or /// whether it's all SCEVCouldNotCompute values. bool hasAnyInfo() const { return !isa<SCEVCouldNotCompute>(ExactNotTaken) || !isa<SCEVCouldNotCompute>(MaxNotTaken); } /// Test whether this ExitLimit contains all information. bool hasFullInfo() const { return !isa<SCEVCouldNotCompute>(ExactNotTaken); } }; /// Information about the number of times a particular loop exit may be /// reached before exiting the loop. struct ExitNotTakenInfo { PoisoningVH<BasicBlock> ExitingBlock; const SCEV *ExactNotTaken; std::unique_ptr<SCEVUnionPredicate> Predicate; bool hasAlwaysTruePredicate() const { return !Predicate || Predicate->isAlwaysTrue(); } explicit ExitNotTakenInfo(PoisoningVH<BasicBlock> ExitingBlock, const SCEV *ExactNotTaken, std::unique_ptr<SCEVUnionPredicate> Predicate) : ExitingBlock(ExitingBlock), ExactNotTaken(ExactNotTaken), Predicate(std::move(Predicate)) {} }; /// Information about the backedge-taken count of a loop. This currently /// includes an exact count and a maximum count. /// class BackedgeTakenInfo { /// A list of computable exits and their not-taken counts. Loops almost /// never have more than one computable exit. SmallVector<ExitNotTakenInfo, 1> ExitNotTaken; /// The pointer part of \c MaxAndComplete is an expression indicating the /// least maximum backedge-taken count of the loop that is known, or a /// SCEVCouldNotCompute. This expression is only valid if the predicates /// associated with all loop exits are true. /// /// The integer part of \c MaxAndComplete is a boolean indicating if \c /// ExitNotTaken has an element for every exiting block in the loop. PointerIntPair<const SCEV *, 1> MaxAndComplete; /// True iff the backedge is taken either exactly Max or zero times. bool MaxOrZero; /// \name Helper projection functions on \c MaxAndComplete. /// @{ bool isComplete() const { return MaxAndComplete.getInt(); } const SCEV *getMax() const { return MaxAndComplete.getPointer(); } /// @} public: BackedgeTakenInfo() : MaxAndComplete(nullptr, 0) {} BackedgeTakenInfo(BackedgeTakenInfo &&) = default; BackedgeTakenInfo &operator=(BackedgeTakenInfo &&) = default; typedef std::pair<BasicBlock *, ExitLimit> EdgeExitInfo; /// Initialize BackedgeTakenInfo from a list of exact exit counts. BackedgeTakenInfo(SmallVectorImpl<EdgeExitInfo> &&ExitCounts, bool Complete, const SCEV *MaxCount, bool MaxOrZero); /// Test whether this BackedgeTakenInfo contains any computed information, /// or whether it's all SCEVCouldNotCompute values. bool hasAnyInfo() const { return !ExitNotTaken.empty() || !isa<SCEVCouldNotCompute>(getMax()); } /// Test whether this BackedgeTakenInfo contains complete information. bool hasFullInfo() const { return isComplete(); } /// Return an expression indicating the exact backedge-taken count of the /// loop if it is known or SCEVCouldNotCompute otherwise. This is the /// number of times the loop header can be guaranteed to execute, minus /// one. /// /// If the SCEV predicate associated with the answer can be different /// from AlwaysTrue, we must add a (non null) Predicates argument. /// The SCEV predicate associated with the answer will be added to /// Predicates. A run-time check needs to be emitted for the SCEV /// predicate in order for the answer to be valid. /// /// Note that we should always know if we need to pass a predicate /// argument or not from the way the ExitCounts vector was computed. /// If we allowed SCEV predicates to be generated when populating this /// vector, this information can contain them and therefore a /// SCEVPredicate argument should be added to getExact. const SCEV *getExact(ScalarEvolution *SE, SCEVUnionPredicate *Predicates = nullptr) const; /// Return the number of times this loop exit may fall through to the back /// edge, or SCEVCouldNotCompute. The loop is guaranteed not to exit via /// this block before this number of iterations, but may exit via another /// block. const SCEV *getExact(BasicBlock *ExitingBlock, ScalarEvolution *SE) const; /// Get the max backedge taken count for the loop. const SCEV *getMax(ScalarEvolution *SE) const; /// Return true if the number of times this backedge is taken is either the /// value returned by getMax or zero. bool isMaxOrZero(ScalarEvolution *SE) const; /// Return true if any backedge taken count expressions refer to the given /// subexpression. bool hasOperand(const SCEV *S, ScalarEvolution *SE) const; /// Invalidate this result and free associated memory. void clear(); }; /// Cache the backedge-taken count of the loops for this function as they /// are computed. DenseMap<const Loop *, BackedgeTakenInfo> BackedgeTakenCounts; /// Cache the predicated backedge-taken count of the loops for this /// function as they are computed. DenseMap<const Loop *, BackedgeTakenInfo> PredicatedBackedgeTakenCounts; /// This map contains entries for all of the PHI instructions that we /// attempt to compute constant evolutions for. This allows us to avoid /// potentially expensive recomputation of these properties. An instruction /// maps to null if we are unable to compute its exit value. DenseMap<PHINode *, Constant *> ConstantEvolutionLoopExitValue; /// This map contains entries for all the expressions that we attempt to /// compute getSCEVAtScope information for, which can be expensive in /// extreme cases. DenseMap<const SCEV *, SmallVector<std::pair<const Loop *, const SCEV *>, 2>> ValuesAtScopes; /// Memoized computeLoopDisposition results. DenseMap<const SCEV *, SmallVector<PointerIntPair<const Loop *, 2, LoopDisposition>, 2>> LoopDispositions; struct LoopProperties { /// Set to true if the loop contains no instruction that can have side /// effects (i.e. via throwing an exception, volatile or atomic access). bool HasNoAbnormalExits; /// Set to true if the loop contains no instruction that can abnormally exit /// the loop (i.e. via throwing an exception, by terminating the thread /// cleanly or by infinite looping in a called function). Strictly /// speaking, the last one is not leaving the loop, but is identical to /// leaving the loop for reasoning about undefined behavior. bool HasNoSideEffects; }; /// Cache for \c getLoopProperties. DenseMap<const Loop *, LoopProperties> LoopPropertiesCache; /// Return a \c LoopProperties instance for \p L, creating one if necessary. LoopProperties getLoopProperties(const Loop *L); bool loopHasNoSideEffects(const Loop *L) { return getLoopProperties(L).HasNoSideEffects; } bool loopHasNoAbnormalExits(const Loop *L) { return getLoopProperties(L).HasNoAbnormalExits; } /// Compute a LoopDisposition value. LoopDisposition computeLoopDisposition(const SCEV *S, const Loop *L); /// Memoized computeBlockDisposition results. DenseMap< const SCEV *, SmallVector<PointerIntPair<const BasicBlock *, 2, BlockDisposition>, 2>> BlockDispositions; /// Compute a BlockDisposition value. BlockDisposition computeBlockDisposition(const SCEV *S, const BasicBlock *BB); /// Memoized results from getRange DenseMap<const SCEV *, ConstantRange> UnsignedRanges; /// Memoized results from getRange DenseMap<const SCEV *, ConstantRange> SignedRanges; /// Used to parameterize getRange enum RangeSignHint { HINT_RANGE_UNSIGNED, HINT_RANGE_SIGNED }; /// Set the memoized range for the given SCEV. const ConstantRange &setRange(const SCEV *S, RangeSignHint Hint, const ConstantRange &CR) { DenseMap<const SCEV *, ConstantRange> &Cache = Hint == HINT_RANGE_UNSIGNED ? UnsignedRanges : SignedRanges; auto Pair = Cache.insert({S, CR}); if (!Pair.second) Pair.first->second = CR; return Pair.first->second; } /// Determine the range for a particular SCEV. ConstantRange getRange(const SCEV *S, RangeSignHint Hint); /// Determines the range for the affine SCEVAddRecExpr {\p Start,+,\p Stop}. /// Helper for \c getRange. ConstantRange getRangeForAffineAR(const SCEV *Start, const SCEV *Stop, const SCEV *MaxBECount, unsigned BitWidth); /// Try to compute a range for the affine SCEVAddRecExpr {\p Start,+,\p /// Stop} by "factoring out" a ternary expression from the add recurrence. /// Helper called by \c getRange. ConstantRange getRangeViaFactoring(const SCEV *Start, const SCEV *Stop, const SCEV *MaxBECount, unsigned BitWidth); /// We know that there is no SCEV for the specified value. Analyze the /// expression. const SCEV *createSCEV(Value *V); /// Provide the special handling we need to analyze PHI SCEVs. const SCEV *createNodeForPHI(PHINode *PN); /// Helper function called from createNodeForPHI. const SCEV *createAddRecFromPHI(PHINode *PN); /// Helper function called from createNodeForPHI. const SCEV *createNodeFromSelectLikePHI(PHINode *PN); /// Provide special handling for a select-like instruction (currently this /// is either a select instruction or a phi node). \p I is the instruction /// being processed, and it is assumed equivalent to "Cond ? TrueVal : /// FalseVal". const SCEV *createNodeForSelectOrPHI(Instruction *I, Value *Cond, Value *TrueVal, Value *FalseVal); /// Provide the special handling we need to analyze GEP SCEVs. const SCEV *createNodeForGEP(GEPOperator *GEP); /// Implementation code for getSCEVAtScope; called at most once for each /// SCEV+Loop pair. /// const SCEV *computeSCEVAtScope(const SCEV *S, const Loop *L); /// This looks up computed SCEV values for all instructions that depend on /// the given instruction and removes them from the ValueExprMap map if they /// reference SymName. This is used during PHI resolution. void forgetSymbolicName(Instruction *I, const SCEV *SymName); /// Return the BackedgeTakenInfo for the given loop, lazily computing new /// values if the loop hasn't been analyzed yet. The returned result is /// guaranteed not to be predicated. const BackedgeTakenInfo &getBackedgeTakenInfo(const Loop *L); /// Similar to getBackedgeTakenInfo, but will add predicates as required /// with the purpose of returning complete information. const BackedgeTakenInfo &getPredicatedBackedgeTakenInfo(const Loop *L); /// Compute the number of times the specified loop will iterate. /// If AllowPredicates is set, we will create new SCEV predicates as /// necessary in order to return an exact answer. BackedgeTakenInfo computeBackedgeTakenCount(const Loop *L, bool AllowPredicates = false); /// Compute the number of times the backedge of the specified loop will /// execute if it exits via the specified block. If AllowPredicates is set, /// this call will try to use a minimal set of SCEV predicates in order to /// return an exact answer. ExitLimit computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, bool AllowPredicates = false); /// Compute the number of times the backedge of the specified loop will /// execute if its exit condition were a conditional branch of ExitCond, /// TBB, and FBB. /// /// \p ControlsExit is true if ExitCond directly controls the exit /// branch. In this case, we can assume that the loop exits only if the /// condition is true and can infer that failing to meet the condition prior /// to integer wraparound results in undefined behavior. /// /// If \p AllowPredicates is set, this call will try to use a minimal set of /// SCEV predicates in order to return an exact answer. ExitLimit computeExitLimitFromCond(const Loop *L, Value *ExitCond, BasicBlock *TBB, BasicBlock *FBB, bool ControlsExit, bool AllowPredicates = false); /// Compute the number of times the backedge of the specified loop will /// execute if its exit condition were a conditional branch of the ICmpInst /// ExitCond, TBB, and FBB. If AllowPredicates is set, this call will try /// to use a minimal set of SCEV predicates in order to return an exact /// answer. ExitLimit computeExitLimitFromICmp(const Loop *L, ICmpInst *ExitCond, BasicBlock *TBB, BasicBlock *FBB, bool IsSubExpr, bool AllowPredicates = false); /// Compute the number of times the backedge of the specified loop will /// execute if its exit condition were a switch with a single exiting case /// to ExitingBB. ExitLimit computeExitLimitFromSingleExitSwitch(const Loop *L, SwitchInst *Switch, BasicBlock *ExitingBB, bool IsSubExpr); /// Given an exit condition of 'icmp op load X, cst', try to see if we can /// compute the backedge-taken count. ExitLimit computeLoadConstantCompareExitLimit(LoadInst *LI, Constant *RHS, const Loop *L, ICmpInst::Predicate p); /// Compute the exit limit of a loop that is controlled by a /// "(IV >> 1) != 0" type comparison. We cannot compute the exact trip /// count in these cases (since SCEV has no way of expressing them), but we /// can still sometimes compute an upper bound. /// /// Return an ExitLimit for a loop whose backedge is guarded by `LHS Pred /// RHS`. ExitLimit computeShiftCompareExitLimit(Value *LHS, Value *RHS, const Loop *L, ICmpInst::Predicate Pred); /// If the loop is known to execute a constant number of times (the /// condition evolves only from constants), try to evaluate a few iterations /// of the loop until we get the exit condition gets a value of ExitWhen /// (true or false). If we cannot evaluate the exit count of the loop, /// return CouldNotCompute. const SCEV *computeExitCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen); /// Return the number of times an exit condition comparing the specified /// value to zero will execute. If not computable, return CouldNotCompute. /// If AllowPredicates is set, this call will try to use a minimal set of /// SCEV predicates in order to return an exact answer. ExitLimit howFarToZero(const SCEV *V, const Loop *L, bool IsSubExpr, bool AllowPredicates = false); /// Return the number of times an exit condition checking the specified /// value for nonzero will execute. If not computable, return /// CouldNotCompute. ExitLimit howFarToNonZero(const SCEV *V, const Loop *L); /// Return the number of times an exit condition containing the specified /// less-than comparison will execute. If not computable, return /// CouldNotCompute. /// /// \p isSigned specifies whether the less-than is signed. /// /// \p ControlsExit is true when the LHS < RHS condition directly controls /// the branch (loops exits only if condition is true). In this case, we can /// use NoWrapFlags to skip overflow checks. /// /// If \p AllowPredicates is set, this call will try to use a minimal set of /// SCEV predicates in order to return an exact answer. ExitLimit howManyLessThans(const SCEV *LHS, const SCEV *RHS, const Loop *L, bool isSigned, bool ControlsExit, bool AllowPredicates = false); ExitLimit howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, const Loop *L, bool isSigned, bool IsSubExpr, bool AllowPredicates = false); /// Return a predecessor of BB (which may not be an immediate predecessor) /// which has exactly one successor from which BB is reachable, or null if /// no such block is found. std::pair<BasicBlock *, BasicBlock *> getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB); /// Test whether the condition described by Pred, LHS, and RHS is true /// whenever the given FoundCondValue value evaluates to true. bool isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, Value *FoundCondValue, bool Inverse); /// Test whether the condition described by Pred, LHS, and RHS is true /// whenever the condition described by FoundPred, FoundLHS, FoundRHS is /// true. bool isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, ICmpInst::Predicate FoundPred, const SCEV *FoundLHS, const SCEV *FoundRHS); /// Test whether the condition described by Pred, LHS, and RHS is true /// whenever the condition described by Pred, FoundLHS, and FoundRHS is /// true. bool isImpliedCondOperands(ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const SCEV *FoundLHS, const SCEV *FoundRHS); /// Test whether the condition described by Pred, LHS, and RHS is true /// whenever the condition described by Pred, FoundLHS, and FoundRHS is /// true. Here LHS is an operation that includes FoundLHS as one of its /// arguments. bool isImpliedViaOperations(ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const SCEV *FoundLHS, const SCEV *FoundRHS, unsigned Depth = 0); /// Test whether the condition described by Pred, LHS, and RHS is true. /// Use only simple non-recursive types of checks, such as range analysis etc. bool isKnownViaSimpleReasoning(ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS); /// Test whether the condition described by Pred, LHS, and RHS is true /// whenever the condition described by Pred, FoundLHS, and FoundRHS is /// true. bool isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const SCEV *FoundLHS, const SCEV *FoundRHS); /// Test whether the condition described by Pred, LHS, and RHS is true /// whenever the condition described by Pred, FoundLHS, and FoundRHS is /// true. Utility function used by isImpliedCondOperands. Tries to get /// cases like "X `sgt` 0 => X - 1 `sgt` -1". bool isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const SCEV *FoundLHS, const SCEV *FoundRHS); /// Return true if the condition denoted by \p LHS \p Pred \p RHS is implied /// by a call to \c @llvm.experimental.guard in \p BB. bool isImpliedViaGuard(BasicBlock *BB, ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS); /// Test whether the condition described by Pred, LHS, and RHS is true /// whenever the condition described by Pred, FoundLHS, and FoundRHS is /// true. /// /// This routine tries to rule out certain kinds of integer overflow, and /// then tries to reason about arithmetic properties of the predicates. bool isImpliedCondOperandsViaNoOverflow(ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const SCEV *FoundLHS, const SCEV *FoundRHS); /// If we know that the specified Phi is in the header of its containing /// loop, we know the loop executes a constant number of times, and the PHI /// node is just a recurrence involving constants, fold it. Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt &BEs, const Loop *L); /// Test if the given expression is known to satisfy the condition described /// by Pred and the known constant ranges of LHS and RHS. /// bool isKnownPredicateViaConstantRanges(ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS); /// Try to prove the condition described by "LHS Pred RHS" by ruling out /// integer overflow. /// /// For instance, this will return true for "A s< (A + C)<nsw>" if C is /// positive. bool isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS); /// Try to split Pred LHS RHS into logical conjunctions (and's) and try to /// prove them individually. bool isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS); /// Try to match the Expr as "(L + R)<Flags>". bool splitBinaryAdd(const SCEV *Expr, const SCEV *&L, const SCEV *&R, SCEV::NoWrapFlags &Flags); /// Compute \p LHS - \p RHS and returns the result as an APInt if it is a /// constant, and None if it isn't. /// /// This is intended to be a cheaper version of getMinusSCEV. We can be /// frugal here since we just bail out of actually constructing and /// canonicalizing an expression in the cases where the result isn't going /// to be a constant. Optional<APInt> computeConstantDifference(const SCEV *LHS, const SCEV *RHS); /// Drop memoized information computed for S. void forgetMemoizedResults(const SCEV *S); /// Return an existing SCEV for V if there is one, otherwise return nullptr. const SCEV *getExistingSCEV(Value *V); /// Return false iff given SCEV contains a SCEVUnknown with NULL value- /// pointer. bool checkValidity(const SCEV *S) const; /// Return true if `ExtendOpTy`({`Start`,+,`Step`}) can be proved to be /// equal to {`ExtendOpTy`(`Start`),+,`ExtendOpTy`(`Step`)}. This is /// equivalent to proving no signed (resp. unsigned) wrap in /// {`Start`,+,`Step`} if `ExtendOpTy` is `SCEVSignExtendExpr` /// (resp. `SCEVZeroExtendExpr`). /// template <typename ExtendOpTy> bool proveNoWrapByVaryingStart(const SCEV *Start, const SCEV *Step, const Loop *L); /// Try to prove NSW or NUW on \p AR relying on ConstantRange manipulation. SCEV::NoWrapFlags proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR); bool isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS, ICmpInst::Predicate Pred, bool &Increasing); /// Return SCEV no-wrap flags that can be proven based on reasoning about /// how poison produced from no-wrap flags on this value (e.g. a nuw add) /// would trigger undefined behavior on overflow. SCEV::NoWrapFlags getNoWrapFlagsFromUB(const Value *V); /// Return true if the SCEV corresponding to \p I is never poison. Proving /// this is more complex than proving that just \p I is never poison, since /// SCEV commons expressions across control flow, and you can have cases /// like: /// /// idx0 = a + b; /// ptr[idx0] = 100; /// if (<condition>) { /// idx1 = a +nsw b; /// ptr[idx1] = 200; /// } /// /// where the SCEV expression (+ a b) is guaranteed to not be poison (and /// hence not sign-overflow) only if "<condition>" is true. Since both /// `idx0` and `idx1` will be mapped to the same SCEV expression, (+ a b), /// it is not okay to annotate (+ a b) with <nsw> in the above example. bool isSCEVExprNeverPoison(const Instruction *I); /// This is like \c isSCEVExprNeverPoison but it specifically works for /// instructions that will get mapped to SCEV add recurrences. Return true /// if \p I will never generate poison under the assumption that \p I is an /// add recurrence on the loop \p L. bool isAddRecNeverPoison(const Instruction *I, const Loop *L); public: ScalarEvolution(Function &F, TargetLibraryInfo &TLI, AssumptionCache &AC, DominatorTree &DT, LoopInfo &LI); ~ScalarEvolution(); ScalarEvolution(ScalarEvolution &&Arg); LLVMContext &getContext() const { return F.getContext(); } /// Test if values of the given type are analyzable within the SCEV /// framework. This primarily includes integer types, and it can optionally /// include pointer types if the ScalarEvolution class has access to /// target-specific information. bool isSCEVable(Type *Ty) const; /// Return the size in bits of the specified type, for which isSCEVable must /// return true. uint64_t getTypeSizeInBits(Type *Ty) const; /// Return a type with the same bitwidth as the given type and which /// represents how SCEV will treat the given type, for which isSCEVable must /// return true. For pointer types, this is the pointer-sized integer type. Type *getEffectiveSCEVType(Type *Ty) const; // Returns a wider type among {Ty1, Ty2}. Type *getWiderType(Type *Ty1, Type *Ty2) const; /// Return true if the SCEV is a scAddRecExpr or it contains /// scAddRecExpr. The result will be cached in HasRecMap. /// bool containsAddRecurrence(const SCEV *S); /// Return the Value set from which the SCEV expr is generated. SetVector<ValueOffsetPair> *getSCEVValues(const SCEV *S); /// Erase Value from ValueExprMap and ExprValueMap. void eraseValueFromMap(Value *V); /// Return a SCEV expression for the full generality of the specified /// expression. const SCEV *getSCEV(Value *V); const SCEV *getConstant(ConstantInt *V); const SCEV *getConstant(const APInt &Val); const SCEV *getConstant(Type *Ty, uint64_t V, bool isSigned = false); const SCEV *getTruncateExpr(const SCEV *Op, Type *Ty); const SCEV *getZeroExtendExpr(const SCEV *Op, Type *Ty); const SCEV *getSignExtendExpr(const SCEV *Op, Type *Ty); const SCEV *getAnyExtendExpr(const SCEV *Op, Type *Ty); const SCEV *getAddExpr(SmallVectorImpl<const SCEV *> &Ops, SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap, unsigned Depth = 0); const SCEV *getAddExpr(const SCEV *LHS, const SCEV *RHS, SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) { SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; return getAddExpr(Ops, Flags); } const SCEV *getAddExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2, SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) { SmallVector<const SCEV *, 3> Ops = {Op0, Op1, Op2}; return getAddExpr(Ops, Flags); } const SCEV *getMulExpr(SmallVectorImpl<const SCEV *> &Ops, SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap); const SCEV *getMulExpr(const SCEV *LHS, const SCEV *RHS, SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) { SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; return getMulExpr(Ops, Flags); } const SCEV *getMulExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2, SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) { SmallVector<const SCEV *, 3> Ops = {Op0, Op1, Op2}; return getMulExpr(Ops, Flags); } const SCEV *getUDivExpr(const SCEV *LHS, const SCEV *RHS); const SCEV *getUDivExactExpr(const SCEV *LHS, const SCEV *RHS); const SCEV *getAddRecExpr(const SCEV *Start, const SCEV *Step, const Loop *L, SCEV::NoWrapFlags Flags); const SCEV *getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, const Loop *L, SCEV::NoWrapFlags Flags); const SCEV *getAddRecExpr(const SmallVectorImpl<const SCEV *> &Operands, const Loop *L, SCEV::NoWrapFlags Flags) { SmallVector<const SCEV *, 4> NewOp(Operands.begin(), Operands.end()); return getAddRecExpr(NewOp, L, Flags); } /// Returns an expression for a GEP /// /// \p GEP The GEP. The indices contained in the GEP itself are ignored, /// instead we use IndexExprs. /// \p IndexExprs The expressions for the indices. const SCEV *getGEPExpr(GEPOperator *GEP, const SmallVectorImpl<const SCEV *> &IndexExprs); const SCEV *getSMaxExpr(const SCEV *LHS, const SCEV *RHS); const SCEV *getSMaxExpr(SmallVectorImpl<const SCEV *> &Operands); const SCEV *getUMaxExpr(const SCEV *LHS, const SCEV *RHS); const SCEV *getUMaxExpr(SmallVectorImpl<const SCEV *> &Operands); const SCEV *getSMinExpr(const SCEV *LHS, const SCEV *RHS); const SCEV *getUMinExpr(const SCEV *LHS, const SCEV *RHS); const SCEV *getUnknown(Value *V); const SCEV *getCouldNotCompute(); /// Return a SCEV for the constant 0 of a specific type. const SCEV *getZero(Type *Ty) { return getConstant(Ty, 0); } /// Return a SCEV for the constant 1 of a specific type. const SCEV *getOne(Type *Ty) { return getConstant(Ty, 1); } /// Return an expression for sizeof AllocTy that is type IntTy /// const SCEV *getSizeOfExpr(Type *IntTy, Type *AllocTy); /// Return an expression for offsetof on the given field with type IntTy /// const SCEV *getOffsetOfExpr(Type *IntTy, StructType *STy, unsigned FieldNo); /// Return the SCEV object corresponding to -V. /// const SCEV *getNegativeSCEV(const SCEV *V, SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap); /// Return the SCEV object corresponding to ~V. /// const SCEV *getNotSCEV(const SCEV *V); /// Return LHS-RHS. Minus is represented in SCEV as A+B*-1. const SCEV *getMinusSCEV(const SCEV *LHS, const SCEV *RHS, SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap); /// Return a SCEV corresponding to a conversion of the input value to the /// specified type. If the type must be extended, it is zero extended. const SCEV *getTruncateOrZeroExtend(const SCEV *V, Type *Ty); /// Return a SCEV corresponding to a conversion of the input value to the /// specified type. If the type must be extended, it is sign extended. const SCEV *getTruncateOrSignExtend(const SCEV *V, Type *Ty); /// Return a SCEV corresponding to a conversion of the input value to the /// specified type. If the type must be extended, it is zero extended. The /// conversion must not be narrowing. const SCEV *getNoopOrZeroExtend(const SCEV *V, Type *Ty); /// Return a SCEV corresponding to a conversion of the input value to the /// specified type. If the type must be extended, it is sign extended. The /// conversion must not be narrowing. const SCEV *getNoopOrSignExtend(const SCEV *V, Type *Ty); /// Return a SCEV corresponding to a conversion of the input value to the /// specified type. If the type must be extended, it is extended with /// unspecified bits. The conversion must not be narrowing. const SCEV *getNoopOrAnyExtend(const SCEV *V, Type *Ty); /// Return a SCEV corresponding to a conversion of the input value to the /// specified type. The conversion must not be widening. const SCEV *getTruncateOrNoop(const SCEV *V, Type *Ty); /// Promote the operands to the wider of the types using zero-extension, and /// then perform a umax operation with them. const SCEV *getUMaxFromMismatchedTypes(const SCEV *LHS, const SCEV *RHS); /// Promote the operands to the wider of the types using zero-extension, and /// then perform a umin operation with them. const SCEV *getUMinFromMismatchedTypes(const SCEV *LHS, const SCEV *RHS); /// Transitively follow the chain of pointer-type operands until reaching a /// SCEV that does not have a single pointer operand. This returns a /// SCEVUnknown pointer for well-formed pointer-type expressions, but corner /// cases do exist. const SCEV *getPointerBase(const SCEV *V); /// Return a SCEV expression for the specified value at the specified scope /// in the program. The L value specifies a loop nest to evaluate the /// expression at, where null is the top-level or a specified loop is /// immediately inside of the loop. /// /// This method can be used to compute the exit value for a variable defined /// in a loop by querying what the value will hold in the parent loop. /// /// In the case that a relevant loop exit value cannot be computed, the /// original value V is returned. const SCEV *getSCEVAtScope(const SCEV *S, const Loop *L); /// This is a convenience function which does getSCEVAtScope(getSCEV(V), L). const SCEV *getSCEVAtScope(Value *V, const Loop *L); /// Test whether entry to the loop is protected by a conditional between LHS /// and RHS. This is used to help avoid max expressions in loop trip /// counts, and to eliminate casts. bool isLoopEntryGuardedByCond(const Loop *L, ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS); /// Test whether the backedge of the loop is protected by a conditional /// between LHS and RHS. This is used to to eliminate casts. bool isLoopBackedgeGuardedByCond(const Loop *L, ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS); /// Returns the maximum trip count of the loop if it is a single-exit /// loop and we can compute a small maximum for that loop. /// /// Implemented in terms of the \c getSmallConstantTripCount overload with /// the single exiting block passed to it. See that routine for details. unsigned getSmallConstantTripCount(const Loop *L); /// Returns the maximum trip count of this loop as a normal unsigned /// value. Returns 0 if the trip count is unknown or not constant. This /// "trip count" assumes that control exits via ExitingBlock. More /// precisely, it is the number of times that control may reach ExitingBlock /// before taking the branch. For loops with multiple exits, it may not be /// the number times that the loop header executes if the loop exits /// prematurely via another branch. unsigned getSmallConstantTripCount(const Loop *L, BasicBlock *ExitingBlock); /// Returns the upper bound of the loop trip count as a normal unsigned /// value. /// Returns 0 if the trip count is unknown or not constant. unsigned getSmallConstantMaxTripCount(const Loop *L); /// Returns the largest constant divisor of the trip count of the /// loop if it is a single-exit loop and we can compute a small maximum for /// that loop. /// /// Implemented in terms of the \c getSmallConstantTripMultiple overload with /// the single exiting block passed to it. See that routine for details. unsigned getSmallConstantTripMultiple(const Loop *L); /// Returns the largest constant divisor of the trip count of this loop as a /// normal unsigned value, if possible. This means that the actual trip /// count is always a multiple of the returned value (don't forget the trip /// count could very well be zero as well!). As explained in the comments /// for getSmallConstantTripCount, this assumes that control exits the loop /// via ExitingBlock. unsigned getSmallConstantTripMultiple(const Loop *L, BasicBlock *ExitingBlock); /// Get the expression for the number of loop iterations for which this loop /// is guaranteed not to exit via ExitingBlock. Otherwise return /// SCEVCouldNotCompute. const SCEV *getExitCount(const Loop *L, BasicBlock *ExitingBlock); /// If the specified loop has a predictable backedge-taken count, return it, /// otherwise return a SCEVCouldNotCompute object. The backedge-taken count /// is the number of times the loop header will be branched to from within /// the loop. This is one less than the trip count of the loop, since it /// doesn't count the first iteration, when the header is branched to from /// outside the loop. /// /// Note that it is not valid to call this method on a loop without a /// loop-invariant backedge-taken count (see /// hasLoopInvariantBackedgeTakenCount). /// const SCEV *getBackedgeTakenCount(const Loop *L); /// Similar to getBackedgeTakenCount, except it will add a set of /// SCEV predicates to Predicates that are required to be true in order for /// the answer to be correct. Predicates can be checked with run-time /// checks and can be used to perform loop versioning. const SCEV *getPredicatedBackedgeTakenCount(const Loop *L, SCEVUnionPredicate &Predicates); /// Similar to getBackedgeTakenCount, except return the least SCEV value /// that is known never to be less than the actual backedge taken count. const SCEV *getMaxBackedgeTakenCount(const Loop *L); /// Return true if the backedge taken count is either the value returned by /// getMaxBackedgeTakenCount or zero. bool isBackedgeTakenCountMaxOrZero(const Loop *L); /// Return true if the specified loop has an analyzable loop-invariant /// backedge-taken count. bool hasLoopInvariantBackedgeTakenCount(const Loop *L); /// This method should be called by the client when it has changed a loop in /// a way that may effect ScalarEvolution's ability to compute a trip count, /// or if the loop is deleted. This call is potentially expensive for large /// loop bodies. void forgetLoop(const Loop *L); /// This method should be called by the client when it has changed a value /// in a way that may effect its value, or which may disconnect it from a /// def-use chain linking it to a loop. void forgetValue(Value *V); /// Called when the client has changed the disposition of values in /// this loop. /// /// We don't have a way to invalidate per-loop dispositions. Clear and /// recompute is simpler. void forgetLoopDispositions(const Loop *L) { LoopDispositions.clear(); } /// Determine the minimum number of zero bits that S is guaranteed to end in /// (at every loop iteration). It is, at the same time, the minimum number /// of times S is divisible by 2. For example, given {4,+,8} it returns 2. /// If S is guaranteed to be 0, it returns the bitwidth of S. uint32_t GetMinTrailingZeros(const SCEV *S); /// Determine the unsigned range for a particular SCEV. /// ConstantRange getUnsignedRange(const SCEV *S) { return getRange(S, HINT_RANGE_UNSIGNED); } /// Determine the signed range for a particular SCEV. /// ConstantRange getSignedRange(const SCEV *S) { return getRange(S, HINT_RANGE_SIGNED); } /// Test if the given expression is known to be negative. /// bool isKnownNegative(const SCEV *S); /// Test if the given expression is known to be positive. /// bool isKnownPositive(const SCEV *S); /// Test if the given expression is known to be non-negative. /// bool isKnownNonNegative(const SCEV *S); /// Test if the given expression is known to be non-positive. /// bool isKnownNonPositive(const SCEV *S); /// Test if the given expression is known to be non-zero. /// bool isKnownNonZero(const SCEV *S); /// Test if the given expression is known to satisfy the condition described /// by Pred, LHS, and RHS. /// bool isKnownPredicate(ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS); /// Return true if, for all loop invariant X, the predicate "LHS `Pred` X" /// is monotonically increasing or decreasing. In the former case set /// `Increasing` to true and in the latter case set `Increasing` to false. /// /// A predicate is said to be monotonically increasing if may go from being /// false to being true as the loop iterates, but never the other way /// around. A predicate is said to be monotonically decreasing if may go /// from being true to being false as the loop iterates, but never the other /// way around. bool isMonotonicPredicate(const SCEVAddRecExpr *LHS, ICmpInst::Predicate Pred, bool &Increasing); /// Return true if the result of the predicate LHS `Pred` RHS is loop /// invariant with respect to L. Set InvariantPred, InvariantLHS and /// InvariantLHS so that InvariantLHS `InvariantPred` InvariantRHS is the /// loop invariant form of LHS `Pred` RHS. bool isLoopInvariantPredicate(ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, const SCEV *&InvariantRHS); /// Simplify LHS and RHS in a comparison with predicate Pred. Return true /// iff any changes were made. If the operands are provably equal or /// unequal, LHS and RHS are set to the same value and Pred is set to either /// ICMP_EQ or ICMP_NE. /// bool SimplifyICmpOperands(ICmpInst::Predicate &Pred, const SCEV *&LHS, const SCEV *&RHS, unsigned Depth = 0); /// Return the "disposition" of the given SCEV with respect to the given /// loop. LoopDisposition getLoopDisposition(const SCEV *S, const Loop *L); /// Return true if the value of the given SCEV is unchanging in the /// specified loop. bool isLoopInvariant(const SCEV *S, const Loop *L); /// Return true if the given SCEV changes value in a known way in the /// specified loop. This property being true implies that the value is /// variant in the loop AND that we can emit an expression to compute the /// value of the expression at any particular loop iteration. bool hasComputableLoopEvolution(const SCEV *S, const Loop *L); /// Return the "disposition" of the given SCEV with respect to the given /// block. BlockDisposition getBlockDisposition(const SCEV *S, const BasicBlock *BB); /// Return true if elements that makes up the given SCEV dominate the /// specified basic block. bool dominates(const SCEV *S, const BasicBlock *BB); /// Return true if elements that makes up the given SCEV properly dominate /// the specified basic block. bool properlyDominates(const SCEV *S, const BasicBlock *BB); /// Test whether the given SCEV has Op as a direct or indirect operand. bool hasOperand(const SCEV *S, const SCEV *Op) const; /// Return the size of an element read or written by Inst. const SCEV *getElementSize(Instruction *Inst); /// Compute the array dimensions Sizes from the set of Terms extracted from /// the memory access function of this SCEVAddRecExpr (second step of /// delinearization). void findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, SmallVectorImpl<const SCEV *> &Sizes, const SCEV *ElementSize) const; void print(raw_ostream &OS) const; void verify() const; bool invalidate(Function &F, const PreservedAnalyses &PA, FunctionAnalysisManager::Invalidator &Inv); /// Collect parametric terms occurring in step expressions (first step of /// delinearization). void collectParametricTerms(const SCEV *Expr, SmallVectorImpl<const SCEV *> &Terms); /// Return in Subscripts the access functions for each dimension in Sizes /// (third step of delinearization). void computeAccessFunctions(const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, SmallVectorImpl<const SCEV *> &Sizes); /// Split this SCEVAddRecExpr into two vectors of SCEVs representing the /// subscripts and sizes of an array access. /// /// The delinearization is a 3 step process: the first two steps compute the /// sizes of each subscript and the third step computes the access functions /// for the delinearized array: /// /// 1. Find the terms in the step functions /// 2. Compute the array size /// 3. Compute the access function: divide the SCEV by the array size /// starting with the innermost dimensions found in step 2. The Quotient /// is the SCEV to be divided in the next step of the recursion. The /// Remainder is the subscript of the innermost dimension. Loop over all /// array dimensions computed in step 2. /// /// To compute a uniform array size for several memory accesses to the same /// object, one can collect in step 1 all the step terms for all the memory /// accesses, and compute in step 2 a unique array shape. This guarantees /// that the array shape will be the same across all memory accesses. /// /// FIXME: We could derive the result of steps 1 and 2 from a description of /// the array shape given in metadata. /// /// Example: /// /// A[][n][m] /// /// for i /// for j /// for k /// A[j+k][2i][5i] = /// /// The initial SCEV: /// /// A[{{{0,+,2*m+5}_i, +, n*m}_j, +, n*m}_k] /// /// 1. Find the different terms in the step functions: /// -> [2*m, 5, n*m, n*m] /// /// 2. Compute the array size: sort and unique them /// -> [n*m, 2*m, 5] /// find the GCD of all the terms = 1 /// divide by the GCD and erase constant terms /// -> [n*m, 2*m] /// GCD = m /// divide by GCD -> [n, 2] /// remove constant terms /// -> [n] /// size of the array is A[unknown][n][m] /// /// 3. Compute the access function /// a. Divide {{{0,+,2*m+5}_i, +, n*m}_j, +, n*m}_k by the innermost size m /// Quotient: {{{0,+,2}_i, +, n}_j, +, n}_k /// Remainder: {{{0,+,5}_i, +, 0}_j, +, 0}_k /// The remainder is the subscript of the innermost array dimension: [5i]. /// /// b. Divide Quotient: {{{0,+,2}_i, +, n}_j, +, n}_k by next outer size n /// Quotient: {{{0,+,0}_i, +, 1}_j, +, 1}_k /// Remainder: {{{0,+,2}_i, +, 0}_j, +, 0}_k /// The Remainder is the subscript of the next array dimension: [2i]. /// /// The subscript of the outermost dimension is the Quotient: [j+k]. /// /// Overall, we have: A[][n][m], and the access function: A[j+k][2i][5i]. void delinearize(const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, SmallVectorImpl<const SCEV *> &Sizes, const SCEV *ElementSize); /// Return the DataLayout associated with the module this SCEV instance is /// operating on. const DataLayout &getDataLayout() const { return F.getParent()->getDataLayout(); } const SCEVPredicate *getEqualPredicate(const SCEVUnknown *LHS, const SCEVConstant *RHS); const SCEVPredicate * getWrapPredicate(const SCEVAddRecExpr *AR, SCEVWrapPredicate::IncrementWrapFlags AddedFlags); /// Re-writes the SCEV according to the Predicates in \p A. const SCEV *rewriteUsingPredicate(const SCEV *S, const Loop *L, SCEVUnionPredicate &A); /// Tries to convert the \p S expression to an AddRec expression, /// adding additional predicates to \p Preds as required. const SCEVAddRecExpr *convertSCEVToAddRecWithPredicates( const SCEV *S, const Loop *L, SmallPtrSetImpl<const SCEVPredicate *> &Preds); private: /// Compute the backedge taken count knowing the interval difference, the /// stride and presence of the equality in the comparison. const SCEV *computeBECount(const SCEV *Delta, const SCEV *Stride, bool Equality); /// Verify if an linear IV with positive stride can overflow when in a /// less-than comparison, knowing the invariant term of the comparison, /// the stride and the knowledge of NSW/NUW flags on the recurrence. bool doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, bool IsSigned, bool NoWrap); /// Verify if an linear IV with negative stride can overflow when in a /// greater-than comparison, knowing the invariant term of the comparison, /// the stride and the knowledge of NSW/NUW flags on the recurrence. bool doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, bool IsSigned, bool NoWrap); /// Get add expr already created or create a new one const SCEV *getOrCreateAddExpr(SmallVectorImpl<const SCEV *> &Ops, SCEV::NoWrapFlags Flags); private: FoldingSet<SCEV> UniqueSCEVs; FoldingSet<SCEVPredicate> UniquePreds; BumpPtrAllocator SCEVAllocator; /// The head of a linked list of all SCEVUnknown values that have been /// allocated. This is used by releaseMemory to locate them all and call /// their destructors. SCEVUnknown *FirstUnknown; }; /// Analysis pass that exposes the \c ScalarEvolution for a function. class ScalarEvolutionAnalysis : public AnalysisInfoMixin<ScalarEvolutionAnalysis> { friend AnalysisInfoMixin<ScalarEvolutionAnalysis>; static AnalysisKey Key; public: typedef ScalarEvolution Result; ScalarEvolution run(Function &F, FunctionAnalysisManager &AM); }; /// Printer pass for the \c ScalarEvolutionAnalysis results. class ScalarEvolutionPrinterPass : public PassInfoMixin<ScalarEvolutionPrinterPass> { raw_ostream &OS; public: explicit ScalarEvolutionPrinterPass(raw_ostream &OS) : OS(OS) {} PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM); }; class ScalarEvolutionWrapperPass : public FunctionPass { std::unique_ptr<ScalarEvolution> SE; public: static char ID; ScalarEvolutionWrapperPass(); ScalarEvolution &getSE() { return *SE; } const ScalarEvolution &getSE() const { return *SE; } bool runOnFunction(Function &F) override; void releaseMemory() override; void getAnalysisUsage(AnalysisUsage &AU) const override; void print(raw_ostream &OS, const Module * = nullptr) const override; void verifyAnalysis() const override; }; /// An interface layer with SCEV used to manage how we see SCEV expressions /// for values in the context of existing predicates. We can add new /// predicates, but we cannot remove them. /// /// This layer has multiple purposes: /// - provides a simple interface for SCEV versioning. /// - guarantees that the order of transformations applied on a SCEV /// expression for a single Value is consistent across two different /// getSCEV calls. This means that, for example, once we've obtained /// an AddRec expression for a certain value through expression /// rewriting, we will continue to get an AddRec expression for that /// Value. /// - lowers the number of expression rewrites. class PredicatedScalarEvolution { public: PredicatedScalarEvolution(ScalarEvolution &SE, Loop &L); const SCEVUnionPredicate &getUnionPredicate() const; /// Returns the SCEV expression of V, in the context of the current SCEV /// predicate. The order of transformations applied on the expression of V /// returned by ScalarEvolution is guaranteed to be preserved, even when /// adding new predicates. const SCEV *getSCEV(Value *V); /// Get the (predicated) backedge count for the analyzed loop. const SCEV *getBackedgeTakenCount(); /// Adds a new predicate. void addPredicate(const SCEVPredicate &Pred); /// Attempts to produce an AddRecExpr for V by adding additional SCEV /// predicates. If we can't transform the expression into an AddRecExpr we /// return nullptr and not add additional SCEV predicates to the current /// context. const SCEVAddRecExpr *getAsAddRec(Value *V); /// Proves that V doesn't overflow by adding SCEV predicate. void setNoOverflow(Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags); /// Returns true if we've proved that V doesn't wrap by means of a SCEV /// predicate. bool hasNoOverflow(Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags); /// Returns the ScalarEvolution analysis used. ScalarEvolution *getSE() const { return &SE; } /// We need to explicitly define the copy constructor because of FlagsMap. PredicatedScalarEvolution(const PredicatedScalarEvolution &); /// Print the SCEV mappings done by the Predicated Scalar Evolution. /// The printed text is indented by \p Depth. void print(raw_ostream &OS, unsigned Depth) const; private: /// Increments the version number of the predicate. This needs to be called /// every time the SCEV predicate changes. void updateGeneration(); /// Holds a SCEV and the version number of the SCEV predicate used to /// perform the rewrite of the expression. typedef std::pair<unsigned, const SCEV *> RewriteEntry; /// Maps a SCEV to the rewrite result of that SCEV at a certain version /// number. If this number doesn't match the current Generation, we will /// need to do a rewrite. To preserve the transformation order of previous /// rewrites, we will rewrite the previous result instead of the original /// SCEV. DenseMap<const SCEV *, RewriteEntry> RewriteMap; /// Records what NoWrap flags we've added to a Value *. ValueMap<Value *, SCEVWrapPredicate::IncrementWrapFlags> FlagsMap; /// The ScalarEvolution analysis. ScalarEvolution &SE; /// The analyzed Loop. const Loop &L; /// The SCEVPredicate that forms our context. We will rewrite all /// expressions assuming that this predicate true. SCEVUnionPredicate Preds; /// Marks the version of the SCEV predicate used. When rewriting a SCEV /// expression we mark it with the version of the predicate. We use this to /// figure out if the predicate has changed from the last rewrite of the /// SCEV. If so, we need to perform a new rewrite. unsigned Generation; /// The backedge taken count. const SCEV *BackedgeCount; }; } #endif
26,023
3,227
#include <CGAL/Cartesian.h> #include <CGAL/Segment_2.h> #include <CGAL/Iso_rectangle_2.h> #include <CGAL/Largest_empty_iso_rectangle_2.h> #include <fstream> #include <cassert> #include <sstream> #define MIN_X 0 #define MIN_Y 0 #define MAX_X 10 #define MAX_Y 10 typedef double Number_Type; typedef CGAL::Cartesian<Number_Type> K; typedef K::Point_2 Point; typedef K::Vector_2 Vector; typedef K::Segment_2 Segment; typedef K::Iso_rectangle_2 Iso_rectangle_2; typedef CGAL::Largest_empty_iso_rectangle_2<K> Largest_empty_rect; int test(std::ifstream& is_ptr, const std::string&); int main(int argc,char *argv[]) { if(argc < 3) { std::cerr << "Syntax : test [input_file_name expected_output_file]*"; return(1); } for(int i = 1, j = 2; j < argc; i += 2, j += 2) { std::cout << "Using " << argv[i] << " and comparing against" << argv[j] << std::endl; std::ifstream is(argv[i]); std::ifstream ifs(argv[j]); if(is.fail() || ifs.fail()) { std::cerr << "Bad input or output file : " << argv[i] << " " << argv[j] << std::endl; return(1); } std::string expected((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>())); if(!test(is, expected)) { std::cerr << "ERROR: " << argv[i] << " produced output different from " << argv[j] << std::endl; } } } int test(std::ifstream& is_ptr, const std::string& expected) { std::stringstream output; const CGAL::Set_ieee_double_precision pfr; double x,y; std::list<Point> points_list; Iso_rectangle_2 ler; // determine bounding box Number_Type x1,y1,x2,y2; Number_Type tmp; is_ptr >> x1 >> y1 >> x2 >> y2; if(x1 > x2) { tmp = x1; x1 = x2; x2 = tmp; } if(y1 > y2) { tmp = y1; y1 = y2; y2 = tmp; } Iso_rectangle_2 b(Point(x1, y1), Point(x2, y2)); Largest_empty_rect empty_rectangle1(b); assert(b == empty_rectangle1.get_largest_empty_iso_rectangle()); // get points from an input file int number_of_points = 0; is_ptr >> number_of_points; for(int i = 0;i < number_of_points;++i) { is_ptr >> x; is_ptr >> y; Point tmp2(x,y); empty_rectangle1.insert(tmp2); points_list.push_back(tmp2); } // print points inserted so far output << "test points\n"; for(Largest_empty_rect::const_iterator it = empty_rectangle1.begin(); it != empty_rectangle1.end(); ++it){ const Point& p = *it; output << " " << p << std::endl; } // output ler = empty_rectangle1.get_largest_empty_iso_rectangle(); output << "test first set (" << (ler.min)().x() << "," << (ler.min)().y() << "),(" << (ler.max)().x() << "," << (ler.max)().y() << ")\n"; // test another ctor Largest_empty_rect empty_rectangle2(Point(x1, y1), Point(x2, y2)); // test operator = empty_rectangle2 = empty_rectangle1; // output ler = empty_rectangle2.get_largest_empty_iso_rectangle(); output << "test operator = (" << (ler.min)().x() << "," << (ler.min)().y() << "),(" << (ler.max)().x() << "," << (ler.max)().y() << ")\n"; // test cctor Largest_empty_rect empty_rectangle3(empty_rectangle1); // output ler = empty_rectangle3.get_largest_empty_iso_rectangle(); output << "test cctor (" << (ler.min)().x() << "," << (ler.min)().y() << "),(" << (ler.max)().x() << "," << (ler.max)().y() << ")\n"; // test list insertion Largest_empty_rect empty_rectangle4(Point(x1, y1), Point(x2, y2)); int n = empty_rectangle4.insert(points_list.begin(), points_list.end()); // output output << "test list insertion:\n"; output << " number of successfully inserted points is " << n << std::endl; ler = empty_rectangle4.get_largest_empty_iso_rectangle(); output << " LER is (" << (ler.min)().x() << "," << (ler.min)().y() << "),(" << (ler.max)().x() << "," << (ler.max)().y() << ")\n"; // test default bbox Largest_empty_rect empty_rectangle5; Point p1(0.5,0.5),p2(2,2); empty_rectangle5.insert(p1); empty_rectangle5.insert(p2); // output ler = empty_rectangle5.get_largest_empty_iso_rectangle(); output << "test default ctor (" << (ler.min)().x() << "," << (ler.min)().y() << "),(" << (ler.max)().x() << "," << (ler.max)().y() << ")\n"; // test removals Point p(x,y); empty_rectangle1.remove(p); // output ler = empty_rectangle1.get_largest_empty_iso_rectangle(); output << "test after removal (" << (ler.min)().x() << "," << (ler.min)().y() << "),(" << (ler.max)().x() << "," << (ler.max)().y() << ")\n"; // test clear empty_rectangle1.clear(); assert(empty_rectangle1.begin() == empty_rectangle1.end()); bool bo = empty_rectangle1.insert(p); output << "test successful insertion " << bo << std::endl; // output ler = empty_rectangle1.get_largest_empty_iso_rectangle(); output << "test after clear (" << (ler.min)().x() << "," << (ler.min)().y() << "),(" << (ler.max)().x() << "," << (ler.max)().y() << ")\n"; bo = empty_rectangle1.insert(p); output << "test unsuccessful insertion " << bo << std::endl; // test bbox Iso_rectangle_2 bb = empty_rectangle1.get_bounding_box(); output << "test bounding box (" << (bb.min)().x() << "," << (bb.min)().y() << "),(" << (bb.max)().x() << "," << (bb.max)().y() << ")\n"; // test quadruple CGAL::Quadruple<Largest_empty_rect::Point_2, Largest_empty_rect::Point_2, Largest_empty_rect::Point_2, Largest_empty_rect::Point_2> q = empty_rectangle1.get_left_bottom_right_top(); output << "test left_bottom_right_top is " << q.first << ", " << q.second << ", " << q.third << ", " << q.fourth << std::endl; // comapre output with expected std::string outputstring = output.str(); std::cout << outputstring << std::endl; std::cout << expected << std::endl; return outputstring == expected; }
2,864
429
package io.airlift.http.client.jetty; import io.airlift.http.client.HttpClientConfig; public class TestJettyHttpClientSocksProxyHttp2 extends TestJettyHttpClientSocksProxy { @Override protected HttpClientConfig createClientConfig() { return super.createClientConfig() .setHttp2Enabled(true); } }
133
1,760
/* * Copyright (C)2009 - SSHJ 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. */ package net.schmizz.sshj.userauth.password; /** * Callback that can be implemented to allow an application to provide an updated password for the 'auth-password' * authentication method. */ public interface PasswordUpdateProvider { /** * Called with the prompt received from the SSH server. This should return the updated password for the user that is * currently authenticating. * * @param resource The resource for which the updated password is being requested. * @param prompt The password update prompt received from the SSH Server. * @return The new password for the resource. */ char[] provideNewPassword(Resource<?> resource, String prompt); /** * If password turns out to be incorrect, indicates whether another call to {@link #provideNewPassword(Resource, String)} should be * made. * <p/> * This method is geared at interactive implementations, and stub implementations may simply return {@code false}. * * @param resource the resource for which the updated password is being requested * * @return whether to retry requesting the updated password for a particular resource */ boolean shouldRetry(Resource<?> resource); }
495
2,137
<gh_stars>1000+ package com.publiccms.common.view; import java.util.Map; import javax.servlet.http.HttpServletRequest; import com.publiccms.common.base.AbstractFreemarkerView; import com.publiccms.common.tools.ControllerUtils; /** * * WebFreeMarkerView 视图类 * */ public class WebFreeMarkerView extends AbstractFreemarkerView { @Override protected void exposeHelpers(Map<String, Object> model, HttpServletRequest request) throws Exception { if (!model.containsKey(CONTEXT_USER)) { model.put(CONTEXT_USER, ControllerUtils.getUserFromSession(request.getSession())); } super.exposeHelpers(model, request); } }
266
319
<filename>Examples/B04283_04_code/main.cpp #include <iostream> #include <string> #include <sstream> #include <cmath> using namespace std; // OpenCV includes #include "opencv2/core/utility.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/highgui.hpp" using namespace cv; Mat img; // OpenCV command line parser functions // Keys accecpted by command line parser const char* keys = { "{help h usage ? | | print this message}" "{@image | | Image to process}" }; void showHistoCallback(int state, void* userData) { // Separate image in BRG vector<Mat> bgr; split( img, bgr ); // Create the histogram for 256 bins // The number of possibles values int numbins= 256; /// Set the ranges ( for B,G,R) ) float range[] = { 0, 256 } ; const float* histRange = { range }; Mat b_hist, g_hist, r_hist; calcHist( &bgr[0], 1, 0, Mat(), b_hist, 1, &numbins, &histRange ); calcHist( &bgr[1], 1, 0, Mat(), g_hist, 1, &numbins, &histRange ); calcHist( &bgr[2], 1, 0, Mat(), r_hist, 1, &numbins, &histRange ); // Draw the histogram // We go to draw lines for each channel int width= 512; int height= 300; // Create image with gray base Mat histImage( height, width, CV_8UC3, Scalar(20,20,20) ); // Normalize the histograms to height of image normalize(b_hist, b_hist, 0, height, NORM_MINMAX ); normalize(g_hist, g_hist, 0, height, NORM_MINMAX ); normalize(r_hist, r_hist, 0, height, NORM_MINMAX ); int binStep= cvRound((float)width/(float)numbins); for( int i=1; i< numbins; i++) { line( histImage, Point( binStep*(i-1), height-cvRound(b_hist.at<float>(i-1) ) ), Point( binStep*(i), height-cvRound(b_hist.at<float>(i) ) ), Scalar(255,0,0) ); line( histImage, Point( binStep*(i-1), height-cvRound(g_hist.at<float>(i-1) ) ), Point( binStep*(i), height-cvRound(g_hist.at<float>(i) ) ), Scalar(0,255,0) ); line( histImage, Point( binStep*(i-1), height-cvRound(r_hist.at<float>(i-1) ) ), Point( binStep*(i), height-cvRound(r_hist.at<float>(i) ) ), Scalar(0,0,255) ); } imshow("Histogram", histImage); } void equalizeCallback(int state, void* userData) { Mat result; // Convert BGR image to YCbCr Mat ycrcb; cvtColor( img, ycrcb, COLOR_BGR2YCrCb); // Split image into channels vector<Mat> channels; split( ycrcb, channels ); // Equalize the Y channel only equalizeHist( channels[0], channels[0] ); // Merge the result channels merge( channels, ycrcb ); // Convert color ycrcb to BGR cvtColor( ycrcb, result, COLOR_YCrCb2BGR ); // Show image imshow("Equalized", result); } void lomoCallback(int state, void* userData) { Mat result; const double E = std::exp(1.0); // Create Lookup table for color curve effect Mat lut(1, 256, CV_8UC1); for (int i=0; i<256; i++) { float x= (float)i/256.0; lut.at<uchar>(i)= cvRound( 256 * (1/(1 + pow(E, -((x-0.5)/0.1)) )) ); } // Split the image channels and apply curve transform only to red channel vector<Mat> bgr; split(img, bgr); LUT(bgr[2], lut, bgr[2]); // merge result merge(bgr, result); // Create image for halo dark Mat halo( img.rows, img.cols, CV_32FC3, Scalar(0.3,0.3,0.3) ); // Create circle circle(halo, Point(img.cols/2, img.rows/2), img.cols/3, Scalar(1,1,1), -1); blur(halo, halo, Size(img.cols/3, img.cols/3)); // Convert the result to float to allow multiply by 1 factor Mat resultf; result.convertTo(resultf, CV_32FC3); // Multiply our result with halo multiply(resultf, halo, resultf); // convert to 8 bits resultf.convertTo(result, CV_8UC3); // show result imshow("Lomograpy", result); // Release mat memory halo.release(); resultf.release(); lut.release(); bgr[0].release(); bgr[1].release(); bgr[2].release(); } void cartoonCallback(int state, void* userData) { /** EDGES **/ // Apply median filter to remove possible noise Mat imgMedian; medianBlur(img, imgMedian, 7); // Detect edges with canny Mat imgCanny; Canny(imgMedian, imgCanny, 50, 150); // Dilate the edges Mat kernel= getStructuringElement(MORPH_RECT, Size(2,2)); dilate(imgCanny, imgCanny, kernel); // Scale edges values to 1 and invert values imgCanny= imgCanny/255; imgCanny= 1-imgCanny; // Use float values to allow multiply between 0 and 1 Mat imgCannyf; imgCanny.convertTo(imgCannyf, CV_32FC3); // Blur the edgest to do smooth effect blur(imgCannyf, imgCannyf, Size(5,5)); /** COLOR **/ // Apply bilateral filter to homogenizes color Mat imgBF; bilateralFilter(img, imgBF, 9, 150.0, 150.0); // truncate colors Mat result= imgBF/25; result= result*25; /** MERGES COLOR + EDGES **/ // Create a 3 channles for edges Mat imgCanny3c; Mat cannyChannels[]={ imgCannyf, imgCannyf, imgCannyf}; merge(cannyChannels, 3, imgCanny3c); // Convert color result to float Mat resultf; result.convertTo(resultf, CV_32FC3); // Multiply color and edges matrices multiply(resultf, imgCanny3c, resultf); // convert to 8 bits color resultf.convertTo(result, CV_8UC3); // Show image imshow("Result", result); } int main( int argc, const char** argv ) { CommandLineParser parser(argc, argv, keys); parser.about("Chapter 4. PhotoTool v1.0.0"); //If requires help show if (parser.has("help")) { parser.printMessage(); return 0; } String imgFile= parser.get<String>(0); // Check if params are correctly parsed in his variables if (!parser.check()) { parser.printErrors(); return 0; } // Load image to process img= imread(imgFile); // Create window namedWindow("Input"); // Create UI buttons createButton("Show histogram", showHistoCallback, NULL, QT_PUSH_BUTTON, 0); createButton("Equalize histogram", equalizeCallback, NULL, QT_PUSH_BUTTON, 0); createButton("Lomography effect", lomoCallback, NULL, QT_PUSH_BUTTON, 0); createButton("Cartonize effect", cartoonCallback, NULL, QT_PUSH_BUTTON, 0); // Show image imshow("Input", img); waitKey(0); return 0; }
2,803
1,408
<reponame>sohumango/arm-trusted-firmware<gh_stars>1000+ /* * Copyright (c) 2019-2020, The Linux Foundation. All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ #ifndef QTI_SECURE_IO_CFG_H #define QTI_SECURE_IO_CFG_H #include <stdint.h> /* * List of peripheral/IO memory areas that are protected from * non-secure world but not required to be secure. */ #define APPS_SMMU_TBU_PWR_STATUS 0x15002204 #define APPS_SMMU_CUSTOM_CFG 0x15002300 #define APPS_SMMU_STATS_SYNC_INV_TBU_ACK 0x150025DC #define APPS_SMMU_SAFE_SEC_CFG 0x15002648 #define APPS_SMMU_MMU2QSS_AND_SAFE_WAIT_CNTR 0x15002670 static const uintptr_t qti_secure_io_allowed_regs[] = { APPS_SMMU_TBU_PWR_STATUS, APPS_SMMU_CUSTOM_CFG, APPS_SMMU_STATS_SYNC_INV_TBU_ACK, APPS_SMMU_SAFE_SEC_CFG, APPS_SMMU_MMU2QSS_AND_SAFE_WAIT_CNTR, }; #endif /* QTI_SECURE_IO_CFG_H */
417
1,285
package net.minestom.server.registry; import net.kyori.adventure.key.Key; import net.kyori.adventure.key.Keyed; import net.minestom.server.utils.NamespaceID; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; public interface ProtocolObject extends Keyed { @Contract(pure = true) @NotNull NamespaceID namespace(); @Override @Contract(pure = true) default @NotNull Key key() { return namespace(); } @Contract(pure = true) default @NotNull String name() { return namespace().asString(); } @Contract(pure = true) int id(); }
226
1,273
<gh_stars>1000+ package org.broadinstitute.hellbender.tools.copynumber.formats.collections; import org.broadinstitute.hellbender.tools.copynumber.formats.metadata.SampleLocatableMetadata; import org.broadinstitute.hellbender.tools.copynumber.formats.records.CopyRatioSegment; import org.broadinstitute.hellbender.utils.SimpleInterval; import org.broadinstitute.hellbender.utils.tsv.DataLine; import org.broadinstitute.hellbender.utils.tsv.TableColumnCollection; import java.io.File; import java.util.List; import java.util.function.BiConsumer; import java.util.function.Function; /** * @author <NAME> &lt;<EMAIL>&gt; */ public final class CopyRatioSegmentCollection extends AbstractSampleLocatableCollection<CopyRatioSegment> { //note to developers: repeat the column headers in Javadoc so that they are viewable when linked /** * CONTIG, START, END, NUM_POINTS_COPY_RATIO, MEAN_LOG2_COPY_RATIO */ enum CopyRatioSegmentTableColumn { CONTIG, START, END, NUM_POINTS_COPY_RATIO, MEAN_LOG2_COPY_RATIO; static final TableColumnCollection COLUMNS = new TableColumnCollection((Object[]) values()); } private static final Function<DataLine, CopyRatioSegment> COPY_RATIO_SEGMENT_RECORD_FROM_DATA_LINE_DECODER = dataLine -> { final String contig = dataLine.get(CopyRatioSegmentTableColumn.CONTIG); final int start = dataLine.getInt(CopyRatioSegmentTableColumn.START); final int end = dataLine.getInt(CopyRatioSegmentTableColumn.END); final int numPoints = dataLine.getInt(CopyRatioSegmentTableColumn.NUM_POINTS_COPY_RATIO); final double meanLog2CopyRatio = dataLine.getDouble(CopyRatioSegmentTableColumn.MEAN_LOG2_COPY_RATIO); final SimpleInterval interval = new SimpleInterval(contig, start, end); return new CopyRatioSegment(interval, numPoints, meanLog2CopyRatio); }; private static final BiConsumer<CopyRatioSegment, DataLine> COPY_RATIO_SEGMENT_RECORD_TO_DATA_LINE_ENCODER = (copyRatioSegment, dataLine) -> dataLine.append(copyRatioSegment.getInterval().getContig()) .append(copyRatioSegment.getInterval().getStart()) .append(copyRatioSegment.getInterval().getEnd()) .append(copyRatioSegment.getNumPoints()) .append(formatDouble(copyRatioSegment.getMeanLog2CopyRatio())); public CopyRatioSegmentCollection(final File inputFile) { super(inputFile, CopyRatioSegmentTableColumn.COLUMNS, COPY_RATIO_SEGMENT_RECORD_FROM_DATA_LINE_DECODER, COPY_RATIO_SEGMENT_RECORD_TO_DATA_LINE_ENCODER); } public CopyRatioSegmentCollection(final SampleLocatableMetadata metadata, final List<CopyRatioSegment> copyRatioSegments) { super(metadata, copyRatioSegments, CopyRatioSegmentTableColumn.COLUMNS, COPY_RATIO_SEGMENT_RECORD_FROM_DATA_LINE_DECODER, COPY_RATIO_SEGMENT_RECORD_TO_DATA_LINE_ENCODER); } }
1,193
11,775
<reponame>rainyShine/jib /* * Copyright 2020 Google LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.cloud.tools.jib.api.buildplan; import java.util.Objects; import javax.annotation.concurrent.Immutable; /** Represents an image platform (for example, "amd64/linux"). */ @Immutable public class Platform { private final String architecture; private final String os; public Platform(String architecture, String os) { this.architecture = architecture; this.os = os; } public String getArchitecture() { return architecture; } public String getOs() { return os; } @Override public boolean equals(Object other) { if (this == other) { return true; } if (!(other instanceof Platform)) { return false; } Platform otherPlatform = (Platform) other; return architecture.equals(otherPlatform.getArchitecture()) && os.equals(otherPlatform.getOs()); } @Override public int hashCode() { return Objects.hash(architecture, os); } }
472
3,834
package org.enso.interpreter.node.expression.builtin.error; import com.oracle.truffle.api.nodes.Node; import org.enso.interpreter.dsl.BuiltinMethod; import org.enso.interpreter.runtime.error.DataflowError; @BuiltinMethod( type = "Error", name = "throw", description = "Returns a new value error with given payload.") public class ThrowErrorNode extends Node { public Object execute(Object _this, Object payload) { return DataflowError.withoutTrace(payload, this); } }
163
429
<reponame>fedepad/daos /* * (C) Copyright 2018-2021 Intel Corporation. * * SPDX-License-Identifier: BSD-2-Clause-Patent */ package io.daos.fs.hadoop; import io.daos.BufferAllocator; import io.daos.dfs.DaosFile; import io.netty.buffer.ByteBuf; import org.apache.hadoop.fs.FileSystem; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; public abstract class DaosFileSource { protected final DaosFile daosFile; protected final long fileLen; protected final ByteBuf buffer; private final boolean selfManagedBuf; protected final int bufCapacity; protected int readSize; protected final FileSystem.Statistics stats; private long lastReadPos; // file offset from which file data is read to buffer private long nextReadPos; // next read position private long nextWritePos; private static final Logger LOG = LoggerFactory.getLogger(DaosFileSource.class); protected DaosFileSource(DaosFile daosFile, int bufCapacity, long fileLen, FileSystem.Statistics stats) { this.daosFile = daosFile; this.buffer = BufferAllocator.directNettyBuf(bufCapacity); selfManagedBuf = true; this.bufCapacity = buffer.capacity(); this.fileLen = fileLen; this.stats = stats; } protected DaosFileSource(DaosFile daosFile, ByteBuf buffer, long fileLen, FileSystem.Statistics stats) { this.daosFile = daosFile; this.buffer = buffer; selfManagedBuf = false; this.bufCapacity = buffer.capacity(); this.fileLen = fileLen; this.stats = stats; } public void setReadSize(int readSize) { this.readSize = readSize; } public void close() { this.daosFile.release(); if (selfManagedBuf) { buffer.release(); } closeMore(); } protected void closeMore() {} public void write(int b) throws IOException { buffer.writeByte(b); if (buffer.writableBytes() == 0) { daosWrite(); } } public void write(byte[] buf, int off, int len) throws IOException { if (buffer.writableBytes() >= len) { buffer.writeBytes(buf, off, len); if (buffer.writableBytes() == 0) { daosWrite(); } return; } while (len > 0) { int length = Math.min(len, buffer.writableBytes()); buffer.writeBytes(buf, off, length); if (buffer.writableBytes() == 0) { daosWrite(); } len -= length; off += length; } } /** * write data in cache buffer to DAOS. */ private void daosWrite() throws IOException { if (LOG.isDebugEnabled()) { LOG.debug("daosWrite : Write into this.path == " + this.daosFile.getPath()); } long currentTime = 0; if (LOG.isDebugEnabled()) { currentTime = System.currentTimeMillis(); } long writeSize = doWrite(nextWritePos); stats.incrementWriteOps(1); if (LOG.isDebugEnabled()) { LOG.debug("daosWrite : writing by daos_api spend time is : " + (System.currentTimeMillis() - currentTime) + " ; writing data size : " + writeSize + "."); } this.nextWritePos += writeSize; this.buffer.clear(); } protected abstract int doWrite(long nextWritePos) throws IOException; public void flush() throws IOException { if (buffer.readableBytes() > 0) { daosWrite(); } } public long nextReadPos() { return nextReadPos; } public void setNextReadPos(long targetPos) { this.nextReadPos = targetPos; } public int read(byte[] buf, int off, int len) throws IOException { int actualLen = 0; // check buffer overlay long start = lastReadPos; long end = lastReadPos + buffer.writerIndex(); // Copy requested data from internal buffer to result array if possible if (nextReadPos >= start && nextReadPos < end) { buffer.readerIndex((int) (nextReadPos - start)); int remaining = (int) (end - nextReadPos); // Want to read len bytes, and there is remaining bytes left in buffer, pick the smaller one actualLen = Math.min(remaining, len); buffer.readBytes(buf, off, actualLen); nextReadPos += actualLen; off += actualLen; len -= actualLen; } // Read data from DAOS to result array actualLen += readFromDaos(buf, off, len); // -1 : reach EOF return actualLen == 0 ? -1 : actualLen; } private int readFromDaos(byte[] buf, int off, int len) throws IOException { int numBytes = 0; while (len > 0 && (nextReadPos < fileLen)) { int actualLen = readFromDaos(len); if (actualLen == 0) { break; } // If we read 3 bytes but need 1, put 1; if we read 1 byte but need 3, put 1 int lengthToPutInBuffer = Math.min(len, actualLen); buffer.readBytes(buf, off, lengthToPutInBuffer); numBytes += lengthToPutInBuffer; nextReadPos += lengthToPutInBuffer; off += lengthToPutInBuffer; len -= lengthToPutInBuffer; } return numBytes; } /** * Read data from DAOS and put into cache buffer. */ private int readFromDaos(int length) throws IOException { if (LOG.isDebugEnabled()) { LOG.debug("readFromDaos : read from daos ,filePos = {}", this.nextReadPos); } buffer.clear(); length = Math.min(length, bufCapacity); length = Math.max(length, readSize); long currentTime = 0; if (LOG.isDebugEnabled()) { currentTime = System.currentTimeMillis(); } int actualLen = doRead(this.nextReadPos, length); buffer.writerIndex(actualLen); lastReadPos = nextReadPos; stats.incrementReadOps(1); this.stats.incrementBytesRead(actualLen); if (LOG.isDebugEnabled()) { LOG.debug("readFromDaos :reading from daos_api spend time is : " + (System.currentTimeMillis() - currentTime) + " ;" + " requested data size: " + length + " actual data size : " + actualLen); } return actualLen; } protected abstract int doRead(long nextReadPos, int length) throws IOException; public int writerIndex() { return buffer.writerIndex(); } public int readerIndex() { return buffer.readerIndex(); } }
2,291
5,411
/* * This file is part of the CitizenFX project - http://citizen.re/ * * See LICENSE and MENTIONS in the root of the source tree for information * regarding licensing. */ #pragma once enum ConsoleModifiers { ConsoleModifierNone = 0, ConsoleModifierAlt = 1, ConsoleModifierShift = 2, ConsoleModifierControl = 4 }; // THANKS MICROSOFT DEFINE_ENUM_FLAG_OPERATORS(ConsoleModifiers); void ConHost_Run(); void ConHost_KeyEnter(uint32_t vKey, wchar_t character, ConsoleModifiers modifiers); // private void ConHost_AddInternalCalls(); void ConHost_WaitForKey(uint32_t& vKey, wchar_t& character, ConsoleModifiers& modifiers); void ConHost_GetCursorPos(int& x, int& y); void ConHost_NewBuffer(int width, int height); void* ConHost_GetBuffer();
283
700
<reponame>liboz/kuromoji /** * Copyright © 2010-2018 Atilika Inc. and contributors (see CONTRIBUTORS.md) * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. A copy of the * License is distributed with this work in the LICENSE.md file. You may * also obtain a copy of the License from * * 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.atilika.kuromoji.compile; import com.atilika.kuromoji.buffer.BufferEntry; import com.atilika.kuromoji.io.ByteBufferIO; import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; import java.util.List; public class TokenInfoBufferCompiler implements Compiler { private static final int INTEGER_BYTES = Integer.SIZE / Byte.SIZE; private static final int SHORT_BYTES = Short.SIZE / Byte.SIZE; private ByteBuffer buffer; private OutputStream output; public TokenInfoBufferCompiler(OutputStream output, List<BufferEntry> entries) { this.output = output; putEntries(entries); } public void putEntries(List<BufferEntry> entries) { int size = calculateEntriesSize(entries) * 2; this.buffer = ByteBuffer.allocate(size + INTEGER_BYTES * 4); buffer.putInt(size); buffer.putInt(entries.size()); BufferEntry firstEntry = entries.get(0); buffer.putInt(firstEntry.tokenInfo.size()); buffer.putInt(firstEntry.posInfo.size()); buffer.putInt(firstEntry.features.size()); for (BufferEntry entry : entries) { for (Short s : entry.tokenInfo) { buffer.putShort(s); } for (Byte b : entry.posInfo) { buffer.put(b); } for (Integer feature : entry.features) { buffer.putInt(feature); } } } private int calculateEntriesSize(List<BufferEntry> entries) { if (entries.isEmpty()) { return 0; } else { int size = 0; BufferEntry entry = entries.get(0); size += entry.tokenInfo.size() * SHORT_BYTES + SHORT_BYTES; size += entry.posInfo.size(); size += entry.features.size() * INTEGER_BYTES; size *= entries.size(); return size; } } @Override public void compile() throws IOException { ByteBufferIO.write(output, buffer); output.close(); } }
1,111
534
<gh_stars>100-1000 #pragma once #include <limits.h> #define NAT_INT_MIN LLONG_MIN #define NAT_INT_MAX LLONG_MAX namespace Natalie { using nat_int_t = long long; }
70
3,589
package picocli.examples.casesensitivity; import picocli.CommandLine; import picocli.CommandLine.Command; import picocli.CommandLine.Option; import java.util.Arrays; @Command(name = "POSIX Option Resemble Demo", description = "Demonstrates multiple POSIX options resembling a long option.") public class POSIXOptionResembleDemo implements Runnable { @Option(names = "-a") boolean a; @Option(names = "-b") boolean b; @Option(names = "-c") boolean c; @Option(names = "-ABC") boolean abc; @Override public void run() { System.out.printf("-a is %s%n" + "-b is %s%n" + "-c is %s%n" + "-ABC is %s%n", a, b, c, abc); } public static void main(String... args) { if (args.length == 0) { args = new String[]{"-abc"}; } System.out.println("Original args: " + Arrays.toString(args)); System.out.println(); System.out.println("Parsing in default mode..."); new CommandLine(new POSIXOptionResembleDemo()) .execute(args); System.out.println(); System.out.println("Parsing in case insensitive mode..."); new CommandLine(new POSIXOptionResembleDemo()) .setOptionsCaseInsensitive(true) .execute(args); } }
586
343
<reponame>gerasim13/Tonic // // ControlPulse.cpp // Tonic // // Created by <NAME> on 3/10/13. // #include "ControlPulse.h" namespace Tonic { namespace Tonic_{ ControlPulse_::ControlPulse_() : lastOnTime_(0) {} } // Namespace Tonic_ } // Namespace Tonic
116
1,093
<filename>spring-integration-core/src/test/java/org/springframework/integration/router/config/HeaderValueRouterParserTests.java /* * Copyright 2002-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.router.config; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.integration.support.MessageBuilder; import org.springframework.messaging.Message; import org.springframework.messaging.PollableChannel; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * @author <NAME> * @author <NAME> */ @ContextConfiguration @RunWith(SpringJUnit4ClassRunner.class) public class HeaderValueRouterParserTests { @Autowired private ConfigurableApplicationContext context; @Autowired private TestServiceA testServiceA; @Autowired private TestServiceB testServiceB; @Test public void testHeaderValuesAsChannels() { context.start(); MessageBuilder<?> channel1MessageBuilder = MessageBuilder.withPayload(""); channel1MessageBuilder.setHeader("testHeader", "channel1"); Message<?> message1 = channel1MessageBuilder.build(); MessageBuilder<?> channel2MessageBuilder = MessageBuilder.withPayload(""); channel2MessageBuilder.setHeader("testHeader", "channel2"); Message<?> message2 = channel2MessageBuilder.build(); testServiceA.foo(message1); testServiceA.foo(message2); PollableChannel channel1 = (PollableChannel) context.getBean("channel1"); PollableChannel channel2 = (PollableChannel) context.getBean("channel2"); message1 = channel1.receive(); assertThat(message1.getHeaders().get("testHeader")).isEqualTo("channel1"); message2 = channel2.receive(); assertThat(message2.getHeaders().get("testHeader")).isEqualTo("channel2"); } @Test public void testHeaderValuesWithMapResolver() { context.start(); MessageBuilder<?> channel1MessageBuilder = MessageBuilder.withPayload(""); channel1MessageBuilder.setHeader("testHeader", "1"); Message<?> message1 = channel1MessageBuilder.build(); MessageBuilder<?> channel2MessageBuilder = MessageBuilder.withPayload(""); channel2MessageBuilder.setHeader("testHeader", "2"); Message<?> message2 = channel2MessageBuilder.build(); testServiceB.foo(message1); testServiceB.foo(message2); PollableChannel channel1 = (PollableChannel) context.getBean("channel1"); PollableChannel channel2 = (PollableChannel) context.getBean("channel2"); message1 = channel1.receive(); assertThat(message1.getHeaders().get("testHeader")).isEqualTo("1"); message2 = channel2.receive(); assertThat(message2.getHeaders().get("testHeader")).isEqualTo("2"); } public interface TestServiceA { void foo(Message<?> message); } public interface TestServiceB { void foo(Message<?> message); } }
1,072
1,546
#include <cstdlib> #include <cstring> #include <iostream> #include "apu.hpp" #include "cartridge.hpp" #include "joypad.hpp" #include "ppu.hpp" #include "cpu.hpp" namespace CPU { /* CPU state */ u8 ram[0x800]; u8 A, X, Y, S; u16 PC; Flags P; bool nmi, irq; // Remaining clocks to end frame: const int TOTAL_CYCLES = 29781; int remainingCycles; inline int elapsed() { return TOTAL_CYCLES - remainingCycles; } /* Cycle emulation */ #define T tick() inline void tick() { PPU::step(); PPU::step(); PPU::step(); remainingCycles--; } /* Flags updating */ inline void upd_cv(u8 x, u8 y, s16 r) { P[C] = (r>0xFF); P[V] = ~(x^y) & (x^r) & 0x80; } inline void upd_nz(u8 x) { P[N] = x & 0x80; P[Z] = (x == 0); } // Does adding I to A cross a page? inline bool cross(u16 a, u8 i) { return ((a+i) & 0xFF00) != ((a & 0xFF00)); } /* Memory access */ void dma_oam(u8 bank); template<bool wr> inline u8 access(u16 addr, u8 v = 0) { u8* r; switch (addr) { case 0x0000 ... 0x1FFF: r = &ram[addr % 0x800]; if (wr) *r = v; return *r; // RAM. case 0x2000 ... 0x3FFF: return PPU::access<wr>(addr % 8, v); // PPU. // APU: case 0x4000 ... 0x4013: case 0x4015: return APU::access<wr>(elapsed(), addr, v); case 0x4017: if (wr) return APU::access<wr>(elapsed(), addr, v); else return Joypad::read_state(1); // Joypad 1. case 0x4014: if (wr) dma_oam(v); break; // OAM DMA. case 0x4016: if (wr) { Joypad::write_strobe(v & 1); break; } // Joypad strobe. else return Joypad::read_state(0); // Joypad 0. case 0x4018 ... 0xFFFF: return Cartridge::access<wr>(addr, v); // Cartridge. } return 0; } inline u8 wr(u16 a, u8 v) { T; return access<1>(a, v); } inline u8 rd(u16 a) { T; return access<0>(a); } inline u16 rd16_d(u16 a, u16 b) { return rd(a) | (rd(b) << 8); } // Read from A and B and merge. inline u16 rd16(u16 a) { return rd16_d(a, a+1); } inline u8 push(u8 v) { return wr(0x100 + (S--), v); } inline u8 pop() { return rd(0x100 + (++S)); } void dma_oam(u8 bank) { for (int i = 0; i < 256; i++) wr(0x2014, rd(bank*0x100 + i)); } /* Addressing modes */ inline u16 imm() { return PC++; } inline u16 imm16() { PC += 2; return PC - 2; } inline u16 abs() { return rd16(imm16()); } inline u16 _abx() { T; return abs() + X; } // Exception. inline u16 abx() { u16 a = abs(); if (cross(a, X)) T; return a + X; } inline u16 aby() { u16 a = abs(); if (cross(a, Y)) T; return a + Y; } inline u16 zp() { return rd(imm()); } inline u16 zpx() { T; return (zp() + X) % 0x100; } inline u16 zpy() { T; return (zp() + Y) % 0x100; } inline u16 izx() { u8 i = zpx(); return rd16_d(i, (i+1) % 0x100); } inline u16 _izy() { u8 i = zp(); return rd16_d(i, (i+1) % 0x100) + Y; } // Exception. inline u16 izy() { u16 a = _izy(); if (cross(a-Y, Y)) T; return a; } /* STx */ template<u8& r, Mode m> void st() { wr( m() , r); } template<> void st<A,izy>() { T; wr(_izy() , A); } // Exceptions. template<> void st<A,abx>() { T; wr( abs() + X, A); } // ... template<> void st<A,aby>() { T; wr( abs() + Y, A); } // ... #define G u16 a = m(); u8 p = rd(a) /* Fetch parameter */ template<u8& r, Mode m> void ld() { G; upd_nz(r = p); } // LDx template<u8& r, Mode m> void cmp() { G; upd_nz(r - p); P[C] = (r >= p); } // CMP, CPx /* Arithmetic and bitwise */ template<Mode m> void ADC() { G ; s16 r = A + p + P[C]; upd_cv(A, p, r); upd_nz(A = r); } template<Mode m> void SBC() { G ^ 0xFF; s16 r = A + p + P[C]; upd_cv(A, p, r); upd_nz(A = r); } template<Mode m> void BIT() { G; P[Z] = !(A & p); P[N] = p & 0x80; P[V] = p & 0x40; } template<Mode m> void AND() { G; upd_nz(A &= p); } template<Mode m> void EOR() { G; upd_nz(A ^= p); } template<Mode m> void ORA() { G; upd_nz(A |= p); } /* Read-Modify-Write */ template<Mode m> void ASL() { G; P[C] = p & 0x80; T; upd_nz(wr(a, p << 1)); } template<Mode m> void LSR() { G; P[C] = p & 0x01; T; upd_nz(wr(a, p >> 1)); } template<Mode m> void ROL() { G; u8 c = P[C] ; P[C] = p & 0x80; T; upd_nz(wr(a, (p << 1) | c) ); } template<Mode m> void ROR() { G; u8 c = P[C] << 7; P[C] = p & 0x01; T; upd_nz(wr(a, c | (p >> 1)) ); } template<Mode m> void DEC() { G; T; upd_nz(wr(a, --p)); } template<Mode m> void INC() { G; T; upd_nz(wr(a, ++p)); } #undef G /* DEx, INx */ template<u8& r> void dec() { upd_nz(--r); T; } template<u8& r> void inc() { upd_nz(++r); T; } /* Bit shifting on the accumulator */ void ASL_A() { P[C] = A & 0x80; upd_nz(A <<= 1); T; } void LSR_A() { P[C] = A & 0x01; upd_nz(A >>= 1); T; } void ROL_A() { u8 c = P[C] ; P[C] = A & 0x80; upd_nz(A = ((A << 1) | c) ); T; } void ROR_A() { u8 c = P[C] << 7; P[C] = A & 0x01; upd_nz(A = (c | (A >> 1)) ); T; } /* Txx (move values between registers) */ template<u8& s, u8& d> void tr() { upd_nz(d = s); T; } template<> void tr<X,S>() { S = X; T; } // TSX, exception. /* Stack operations */ void PLP() { T; T; P.set(pop()); } void PHP() { T; push(P.get() | (1 << 4)); } // B flag set. void PLA() { T; T; A = pop(); upd_nz(A); } void PHA() { T; push(A); } /* Flow control (branches, jumps) */ template<Flag f, bool v> void br() { s8 j = rd(imm()); if (P[f] == v) { if (cross(PC, j)) T; T; PC += j; } } void JMP_IND() { u16 i = rd16(imm16()); PC = rd16_d(i, (i&0xFF00) | ((i+1) % 0x100)); } void JMP() { PC = rd16(imm16()); } void JSR() { u16 t = PC+1; T; push(t >> 8); push(t); PC = rd16(imm16()); } /* Return instructions */ void RTS() { T; T; PC = (pop() | (pop() << 8)) + 1; T; } void RTI() { PLP(); PC = pop() | (pop() << 8); } template<Flag f, bool v> void flag() { P[f] = v; T; } // Clear and set flags. template<IntType t> void INT() { T; if (t != BRK) T; // BRK already performed the fetch. if (t != RESET) // Writes on stack are inhibited on RESET. { push(PC >> 8); push(PC & 0xFF); push(P.get() | ((t == BRK) << 4)); // Set B if BRK. } else { S -= 3; T; T; T; } P[I] = true; /* NMI Reset IRQ BRK */ constexpr u16 vect[] = { 0xFFFA, 0xFFFC, 0xFFFE, 0xFFFE }; PC = rd16(vect[t]); if (t == NMI) nmi = false; } void NOP() { T; } /* Execute a CPU instruction */ void exec() { switch (rd(PC++)) // Fetch the opcode. { // Select the right function to emulate the instruction: case 0x00: return INT<BRK>() ; case 0x01: return ORA<izx>() ; case 0x05: return ORA<zp>() ; case 0x06: return ASL<zp>() ; case 0x08: return PHP() ; case 0x09: return ORA<imm>() ; case 0x0A: return ASL_A() ; case 0x0D: return ORA<abs>() ; case 0x0E: return ASL<abs>() ; case 0x10: return br<N,0>() ; case 0x11: return ORA<izy>() ; case 0x15: return ORA<zpx>() ; case 0x16: return ASL<zpx>() ; case 0x18: return flag<C,0>() ; case 0x19: return ORA<aby>() ; case 0x1D: return ORA<abx>() ; case 0x1E: return ASL<_abx>() ; case 0x20: return JSR() ; case 0x21: return AND<izx>() ; case 0x24: return BIT<zp>() ; case 0x25: return AND<zp>() ; case 0x26: return ROL<zp>() ; case 0x28: return PLP() ; case 0x29: return AND<imm>() ; case 0x2A: return ROL_A() ; case 0x2C: return BIT<abs>() ; case 0x2D: return AND<abs>() ; case 0x2E: return ROL<abs>() ; case 0x30: return br<N,1>() ; case 0x31: return AND<izy>() ; case 0x35: return AND<zpx>() ; case 0x36: return ROL<zpx>() ; case 0x38: return flag<C,1>() ; case 0x39: return AND<aby>() ; case 0x3D: return AND<abx>() ; case 0x3E: return ROL<_abx>() ; case 0x40: return RTI() ; case 0x41: return EOR<izx>() ; case 0x45: return EOR<zp>() ; case 0x46: return LSR<zp>() ; case 0x48: return PHA() ; case 0x49: return EOR<imm>() ; case 0x4A: return LSR_A() ; case 0x4C: return JMP() ; case 0x4D: return EOR<abs>() ; case 0x4E: return LSR<abs>() ; case 0x50: return br<V,0>() ; case 0x51: return EOR<izy>() ; case 0x55: return EOR<zpx>() ; case 0x56: return LSR<zpx>() ; case 0x58: return flag<I,0>() ; case 0x59: return EOR<aby>() ; case 0x5D: return EOR<abx>() ; case 0x5E: return LSR<_abx>() ; case 0x60: return RTS() ; case 0x61: return ADC<izx>() ; case 0x65: return ADC<zp>() ; case 0x66: return ROR<zp>() ; case 0x68: return PLA() ; case 0x69: return ADC<imm>() ; case 0x6A: return ROR_A() ; case 0x6C: return JMP_IND() ; case 0x6D: return ADC<abs>() ; case 0x6E: return ROR<abs>() ; case 0x70: return br<V,1>() ; case 0x71: return ADC<izy>() ; case 0x75: return ADC<zpx>() ; case 0x76: return ROR<zpx>() ; case 0x78: return flag<I,1>() ; case 0x79: return ADC<aby>() ; case 0x7D: return ADC<abx>() ; case 0x7E: return ROR<_abx>() ; case 0x81: return st<A,izx>() ; case 0x84: return st<Y,zp>() ; case 0x85: return st<A,zp>() ; case 0x86: return st<X,zp>() ; case 0x88: return dec<Y>() ; case 0x8A: return tr<X,A>() ; case 0x8C: return st<Y,abs>() ; case 0x8D: return st<A,abs>() ; case 0x8E: return st<X,abs>() ; case 0x90: return br<C,0>() ; case 0x91: return st<A,izy>() ; case 0x94: return st<Y,zpx>() ; case 0x95: return st<A,zpx>() ; case 0x96: return st<X,zpy>() ; case 0x98: return tr<Y,A>() ; case 0x99: return st<A,aby>() ; case 0x9A: return tr<X,S>() ; case 0x9D: return st<A,abx>() ; case 0xA0: return ld<Y,imm>() ; case 0xA1: return ld<A,izx>() ; case 0xA2: return ld<X,imm>() ; case 0xA4: return ld<Y,zp>() ; case 0xA5: return ld<A,zp>() ; case 0xA6: return ld<X,zp>() ; case 0xA8: return tr<A,Y>() ; case 0xA9: return ld<A,imm>() ; case 0xAA: return tr<A,X>() ; case 0xAC: return ld<Y,abs>() ; case 0xAD: return ld<A,abs>() ; case 0xAE: return ld<X,abs>() ; case 0xB0: return br<C,1>() ; case 0xB1: return ld<A,izy>() ; case 0xB4: return ld<Y,zpx>() ; case 0xB5: return ld<A,zpx>() ; case 0xB6: return ld<X,zpy>() ; case 0xB8: return flag<V,0>() ; case 0xB9: return ld<A,aby>() ; case 0xBA: return tr<S,X>() ; case 0xBC: return ld<Y,abx>() ; case 0xBD: return ld<A,abx>() ; case 0xBE: return ld<X,aby>() ; case 0xC0: return cmp<Y,imm>(); case 0xC1: return cmp<A,izx>(); case 0xC4: return cmp<Y,zp>() ; case 0xC5: return cmp<A,zp>() ; case 0xC6: return DEC<zp>() ; case 0xC8: return inc<Y>() ; case 0xC9: return cmp<A,imm>(); case 0xCA: return dec<X>() ; case 0xCC: return cmp<Y,abs>(); case 0xCD: return cmp<A,abs>(); case 0xCE: return DEC<abs>() ; case 0xD0: return br<Z,0>() ; case 0xD1: return cmp<A,izy>(); case 0xD5: return cmp<A,zpx>(); case 0xD6: return DEC<zpx>() ; case 0xD8: return flag<D,0>() ; case 0xD9: return cmp<A,aby>(); case 0xDD: return cmp<A,abx>(); case 0xDE: return DEC<_abx>() ; case 0xE0: return cmp<X,imm>(); case 0xE1: return SBC<izx>() ; case 0xE4: return cmp<X,zp>() ; case 0xE5: return SBC<zp>() ; case 0xE6: return INC<zp>() ; case 0xE8: return inc<X>() ; case 0xE9: return SBC<imm>() ; case 0xEA: return NOP() ; case 0xEC: return cmp<X,abs>(); case 0xED: return SBC<abs>() ; case 0xEE: return INC<abs>() ; case 0xF0: return br<Z,1>() ; case 0xF1: return SBC<izy>() ; case 0xF5: return SBC<zpx>() ; case 0xF6: return INC<zpx>() ; case 0xF8: return flag<D,1>() ; case 0xF9: return SBC<aby>() ; case 0xFD: return SBC<abx>() ; case 0xFE: return INC<_abx>() ; default: std::cout << "Invalid Opcode! PC: " << PC << " Opcode: 0x" << std::hex << (int)(rd(PC - 1)) << "\n"; return NOP(); } } void set_nmi(bool v) { nmi = v; } void set_irq(bool v) { irq = v; } int dmc_read(void*, cpu_addr_t addr) { return access<0>(addr); } /* Turn on the CPU */ void power() { remainingCycles = 0; P.set(0x04); A = X = Y = S = 0x00; memset(ram, 0xFF, sizeof(ram)); nmi = irq = false; INT<RESET>(); } /* Run the CPU for roughly a frame */ void run_frame() { remainingCycles += TOTAL_CYCLES; while (remainingCycles > 0) { if (nmi) INT<NMI>(); else if (irq and !P[I]) INT<IRQ>(); exec(); } APU::run_frame(elapsed()); } }
6,983
337
<reponame>qussarah/declare import org.jetbrains.annotations.NotNull; class B<T>{ final T t; public <U> U foo(U u, @NotNull String s) { return null; } }
80
401
<reponame>roman-murashov/hedgewars /* * Hedgewars for Android. An Android port of Hedgewars, a free turn based strategy game * Copyright (c) 2011-2012 <NAME> <<EMAIL>> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.hedgewars.hedgeroid.Downloader; import org.hedgewars.hedgeroid.R; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.Messenger; import android.os.RemoteException; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; public class DownloadFragment extends Fragment{ public static final String EXTRA_TASK = "task"; public static final int MSG_START = 0; public static final int MSG_UPDATE = 1; public static final int MSG_DONE = 2; public static final int MSG_FAILED = 3; private boolean boundToService = false; private TextView progress_sub; private ProgressBar progress; private Button /*positive,*/ negative; private DownloadPackage pack; private Handler messageHandler; private Messenger messenger, messengerService; public static DownloadFragment getInstance(DownloadPackage task){ DownloadFragment df = new DownloadFragment(); Bundle args = new Bundle(); args.putParcelable(DownloadFragment.EXTRA_TASK, task); df.setArguments(args); return df; } public void onActivityCreated(Bundle savedInstanceState){ super.onActivityCreated(savedInstanceState); messageHandler = new Handler(messageCallback); messenger = new Messenger(messageHandler); Intent i = new Intent(getActivity().getApplicationContext(), DownloadService.class); getActivity().startService(i); getActivity().bindService(new Intent(getActivity().getApplicationContext(), DownloadService.class), connection, Context.BIND_AUTO_CREATE); } public View onCreateView(LayoutInflater inflater, ViewGroup viewgroup, Bundle savedInstanceState){ View v = inflater.inflate(R.layout.download_progress, viewgroup, false); progress_sub = (TextView)v.findViewById(R.id.progressbar_sub); progress = (ProgressBar)v.findViewById(R.id.progressbar); //positive = (Button) v.findViewById(R.id.background); negative = (Button) v.findViewById(R.id.cancelDownload); //positive.setOnClickListener(backgroundClicker); negative.setOnClickListener(cancelClicker); pack = getArguments().getParcelable(DownloadFragment.EXTRA_TASK); return v; } private OnClickListener backgroundClicker = new OnClickListener(){ public void onClick(View v){ getActivity().finish(); } }; private OnClickListener cancelClicker = new OnClickListener(){ public void onClick(View v){ if(messengerService != null){ Message message = Message.obtain(messageHandler, DownloadService.MSG_CANCEL, pack); try { messengerService.send(message); } catch (RemoteException e) {} } //getActivity().finish(); } }; private OnClickListener doneClicker = new OnClickListener(){ public void onClick(View v){ getActivity().finish(); } }; private OnClickListener tryAgainClicker = new OnClickListener(){ public void onClick(View v){ if(messengerService != null){ Message message = Message.obtain(messageHandler, DownloadService.MSG_ADDTASK, pack); message.replyTo = messenger; try { messengerService.send(message); } catch (RemoteException e) { e.printStackTrace(); } } } }; public void onDestroy(){ unBindFromService(); super.onDestroy(); } private ServiceConnection connection = new ServiceConnection(){ public void onServiceConnected(ComponentName name, IBinder service) { messengerService = new Messenger(service); try{ //give the service a task if(messengerService != null){ Message message = Message.obtain(messageHandler, DownloadService.MSG_ADDTASK, pack); message.replyTo = messenger; messengerService.send(message); } }catch (RemoteException e){} } public void onServiceDisconnected(ComponentName name) { messengerService = null; } }; public void unBindFromService(){ if(messengerService != null){ try { Message message = Message.obtain(messageHandler, DownloadService.MSG_UNREGISTER_CLIENT, pack); message.replyTo = messenger; messengerService.send(message); } catch (RemoteException e) { e.printStackTrace(); } } getActivity().unbindService(connection); } private Handler.Callback messageCallback = new Handler.Callback() { public boolean handleMessage(Message msg) { switch(msg.what){ case MSG_START: progress.setMax(msg.arg1); progress_sub.setText(String.format("%dkb/%dkb\n%s", 0, msg.arg1, "")); //positive.setText(R.string.download_background); //positive.setOnClickListener(backgroundClicker); negative.setText(R.string.download_cancel); negative.setOnClickListener(cancelClicker); break; case MSG_UPDATE: progress_sub.setText(String.format("%d%% - %dkb/%dkb\n%s",(msg.arg1*100)/msg.arg2, msg.arg1, msg.arg2, msg.obj)); progress.setProgress(msg.arg1); break; case MSG_DONE: progress.setProgress(progress.getMax()); progress_sub.setText(R.string.download_done); // positive.setText(R.string.download_back); // positive.setOnClickListener(doneClicker); negative.setVisibility(View.INVISIBLE); break; case MSG_FAILED: progress.setProgress(progress.getMax()); String errorMsg = getString(R.string.download_failed); switch(msg.arg1){ case DownloadAsyncTask.EXIT_CONNERROR: progress_sub.setText(errorMsg + " " + "Connection error"); break; case DownloadAsyncTask.EXIT_FNF: progress_sub.setText(errorMsg + " " + "File not found"); break; case DownloadAsyncTask.EXIT_MD5: progress_sub.setText(errorMsg + " " + "MD5 check failed"); break; case DownloadAsyncTask.EXIT_URLFAIL: progress_sub.setText(errorMsg + " " + "Invalid url"); break; } negative.setText(R.string.download_tryagain); negative.setOnClickListener(tryAgainClicker); break; } return false; } }; }
3,296
494
/******************************************************************************* * Copyright 2011 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax.model; import java.nio.ByteBuffer; import java.util.Date; import java.util.UUID; import com.netflix.astyanax.Serializer; public abstract class AbstractColumnList<C> implements ColumnList<C> { @Override public String getStringValue(C columnName, String defaultValue) { Column<C> column = getColumnByName(columnName); if (column == null || !column.hasValue()) return defaultValue; return column.getStringValue(); } @Override public Integer getIntegerValue(C columnName, Integer defaultValue) { Column<C> column = getColumnByName(columnName); if (column == null || !column.hasValue()) return defaultValue; return column.getIntegerValue(); } @Override public Double getDoubleValue(C columnName, Double defaultValue) { Column<C> column = getColumnByName(columnName); if (column == null || !column.hasValue()) return defaultValue; return column.getDoubleValue(); } @Override public Long getLongValue(C columnName, Long defaultValue) { Column<C> column = getColumnByName(columnName); if (column == null || !column.hasValue()) return defaultValue; return column.getLongValue(); } @Override public byte[] getByteArrayValue(C columnName, byte[] defaultValue) { Column<C> column = getColumnByName(columnName); if (column == null || !column.hasValue()) return defaultValue; return column.getByteArrayValue(); } @Override public Boolean getBooleanValue(C columnName, Boolean defaultValue) { Column<C> column = getColumnByName(columnName); if (column == null || !column.hasValue()) return defaultValue; return column.getBooleanValue(); } @Override public ByteBuffer getByteBufferValue(C columnName, ByteBuffer defaultValue) { Column<C> column = getColumnByName(columnName); if (column == null || !column.hasValue()) return defaultValue; return column.getByteBufferValue(); } @Override public Date getDateValue(C columnName, Date defaultValue) { Column<C> column = getColumnByName(columnName); if (column == null || !column.hasValue()) return defaultValue; return column.getDateValue(); } @Override public UUID getUUIDValue(C columnName, UUID defaultValue) { Column<C> column = getColumnByName(columnName); if (column == null || !column.hasValue()) return defaultValue; return column.getUUIDValue(); } @Override public <T> T getValue(C columnName, Serializer<T> serializer, T defaultValue) { Column<C> column = getColumnByName(columnName); if (column == null || !column.hasValue()) return defaultValue; return column.getValue(serializer); } @Override public String getCompressedStringValue(C columnName, String defaultValue) { Column<C> column = getColumnByName(columnName); if (column == null || !column.hasValue()) return defaultValue; return column.getCompressedStringValue(); } }
1,398
5,169
{ "name": "YouTubePlayer", "version": "0.1", "summary": "Swift library for embedding and controlling YouTube videos in your iOS applications", "homepage": "https://github.com/gilesvangruisen/Swift-YouTube-Player", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "<NAME>": "<EMAIL>" }, "social_media_url": "http://twitter.com/gilesvangruisen", "platforms": { "ios": "8.0" }, "source": { "git": "https://github.com/gilesvangruisen/Swift-YouTube-Player.git", "tag": "v0.1" }, "source_files": "YouTubePlayer/**/*.{swift,h,m}", "exclude_files": "Classes/Exclude" }
257
348
<reponame>chamberone/Leaflet.PixiOverlay<filename>docs/data/t2/050/50621.json<gh_stars>100-1000 {"nom":"Vaudreville","dpt":"Manche","inscrits":66,"abs":17,"votants":49,"blancs":0,"nuls":49,"exp":0,"res":[]}
91
1,837
//======================================================================== //Copyright 2007-2010 <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 io.protostuff; import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; /** * An optimized json output which is efficient in writing numeric keys and pre-encoded utf8 strings (in byte array * form). * <p> * This is the appropriate output sink to use when writing from binary (protostuff,protobuf,etc) pipes. * * @author <NAME> * @created Jul 2, 2010 */ public final class JsonXOutput extends WriteSession implements Output, StatefulOutput { private static final byte START_OBJECT = (byte) '{', END_OBJECT = (byte) '}', START_ARRAY = (byte) '[', END_ARRAY = (byte) ']', COMMA = (byte) ',', QUOTE = (byte) '"'; private static final byte[] TRUE = new byte[] { (byte) 't', (byte) 'r', (byte) 'u', (byte) 'e' }; private static final byte[] FALSE = new byte[] { (byte) 'f', (byte) 'a', (byte) 'l', (byte) 's', (byte) 'e' }; private static final byte[] KEY_SUFFIX_ARRAY = new byte[] { (byte) '"', (byte) ':', (byte) '[' }; private static final byte[] KEY_SUFFIX_ARRAY_OBJECT = new byte[] { (byte) '"', (byte) ':', (byte) '[', (byte) '{' }; private static final byte[] KEY_SUFFIX_ARRAY_STRING = new byte[] { (byte) '"', (byte) ':', (byte) '[', (byte) '"' }; private static final byte[] KEY_SUFFIX_OBJECT = new byte[] { (byte) '"', (byte) ':', (byte) '{' }; private static final byte[] KEY_SUFFIX_STRING = new byte[] { (byte) '"', (byte) ':', (byte) '"' }; private static final byte[] KEY_SUFFIX = new byte[] { (byte) '"', (byte) ':', }; private static final byte[] COMMA_AND_QUOTE = new byte[] { (byte) ',', (byte) '"', }; private static final byte[] COMMA_AND_START_OBJECT = new byte[] { (byte) ',', (byte) '{', }; private static final byte[] END_ARRAY_AND_END_OBJECT = new byte[] { (byte) ']', (byte) '}' }; private static final byte[] END_ARRAY__COMMA__QUOTE = new byte[] { (byte) ']', (byte) ',', (byte) '"' }; private Schema<?> schema; private final boolean numeric; private boolean lastRepeated; private int lastNumber; public JsonXOutput(LinkedBuffer head, boolean numeric, Schema<?> schema) { super(head); this.numeric = numeric; this.schema = schema; } public JsonXOutput(LinkedBuffer head, OutputStream out, FlushHandler flushHandler, int nextBufferSize, boolean numeric, Schema<?> schema) { super(head, out, flushHandler, nextBufferSize); this.numeric = numeric; this.schema = schema; } public JsonXOutput(LinkedBuffer head, OutputStream out, boolean numeric, Schema<?> schema) { super(head, out); this.numeric = numeric; this.schema = schema; } /** * Resets this output for re-use. */ @Override public void reset() { lastRepeated = false; lastNumber = 0; } @Override public JsonXOutput clear() { super.clear(); return this; } /** * Before serializing a message/object tied to a schema, this should be called. */ public JsonXOutput use(Schema<?> schema) { this.schema = schema; return this; } /** * Returns whether the incoming messages' field names are numeric. */ public boolean isNumeric() { return numeric; } /** * Gets the last field number written. */ public int getLastNumber() { return lastNumber; } /** * Returns true if the last written field was a repeated field. */ public boolean isLastRepeated() { return lastRepeated; } @Override public void updateLast(Schema<?> schema, Schema<?> lastSchema) { if (lastSchema != null && lastSchema == this.schema) { this.schema = schema; } } JsonXOutput writeCommaAndStartObject() throws IOException { tail = sink.writeByteArray(COMMA_AND_START_OBJECT, this, tail); return this; } JsonXOutput writeStartObject() throws IOException { tail = sink.writeByte(START_OBJECT, this, tail); return this; } JsonXOutput writeEndObject() throws IOException { tail = sink.writeByte(END_OBJECT, this, tail); return this; } JsonXOutput writeStartArray() throws IOException { tail = sink.writeByte(START_ARRAY, this, tail); return this; } JsonXOutput writeEndArray() throws IOException { tail = sink.writeByte(END_ARRAY, this, tail); return this; } private LinkedBuffer writeKey(final int fieldNumber, final WriteSink sink, final byte[] keySuffix) throws IOException { if (numeric) { if (lastRepeated) { return sink.writeByteArray( keySuffix, this, sink.writeStrFromInt( fieldNumber, this, sink.writeByteArray( END_ARRAY__COMMA__QUOTE, this, tail))); } if (lastNumber == 0) { return sink.writeByteArray( keySuffix, this, sink.writeStrFromInt( fieldNumber, this, sink.writeByte( QUOTE, this, tail))); } return sink.writeByteArray( keySuffix, this, sink.writeStrFromInt( fieldNumber, this, sink.writeByteArray( COMMA_AND_QUOTE, this, tail))); } if (lastRepeated) { return sink.writeByteArray( keySuffix, this, sink.writeStrAscii( schema.getFieldName(fieldNumber), this, sink.writeByteArray( END_ARRAY__COMMA__QUOTE, this, tail))); } if (lastNumber == 0) { return sink.writeByteArray( keySuffix, this, sink.writeStrAscii( schema.getFieldName(fieldNumber), this, sink.writeByte( QUOTE, this, tail))); } return sink.writeByteArray( keySuffix, this, sink.writeStrAscii( schema.getFieldName(fieldNumber), this, sink.writeByteArray( COMMA_AND_QUOTE, this, tail))); } @Override public void writeBool(int fieldNumber, boolean value, boolean repeated) throws IOException { final WriteSink sink = this.sink; if (lastNumber == fieldNumber) { // repeated field tail = sink.writeByteArray( value ? TRUE : FALSE, this, sink.writeByte( COMMA, this, tail)); return; } tail = sink.writeByteArray( value ? TRUE : FALSE, this, writeKey( fieldNumber, sink, repeated ? KEY_SUFFIX_ARRAY : KEY_SUFFIX)); lastNumber = fieldNumber; lastRepeated = repeated; } @Override public void writeByteArray(int fieldNumber, byte[] value, boolean repeated) throws IOException { final WriteSink sink = this.sink; if (lastNumber == fieldNumber) { // repeated field tail = sink.writeByte( QUOTE, this, sink.writeByteArrayB64( value, 0, value.length, this, sink.writeByteArray( COMMA_AND_QUOTE, this, tail))); return; } tail = sink.writeByte( QUOTE, this, sink.writeByteArrayB64( value, 0, value.length, this, writeKey( fieldNumber, sink, repeated ? KEY_SUFFIX_ARRAY_STRING : KEY_SUFFIX_STRING))); lastNumber = fieldNumber; lastRepeated = repeated; } @Override public void writeByteRange(boolean utf8String, int fieldNumber, byte[] value, int offset, int length, boolean repeated) throws IOException { final WriteSink sink = this.sink; if (utf8String) { if (lastNumber == fieldNumber) { // repeated field tail = sink.writeByte( QUOTE, this, writeUTF8Escaped( value, offset, length, sink, this, sink.writeByteArray( COMMA_AND_QUOTE, this, tail))); return; } tail = sink.writeByte( QUOTE, this, writeUTF8Escaped( value, offset, length, sink, this, writeKey( fieldNumber, sink, repeated ? KEY_SUFFIX_ARRAY_STRING : KEY_SUFFIX_STRING))); lastNumber = fieldNumber; lastRepeated = repeated; return; } if (lastNumber == fieldNumber) { // repeated field tail = sink.writeByte( QUOTE, this, sink.writeByteArrayB64( value, offset, length, this, sink.writeByteArray( COMMA_AND_QUOTE, this, tail))); return; } tail = sink.writeByte( QUOTE, this, sink.writeByteArrayB64( value, offset, length, this, writeKey( fieldNumber, sink, repeated ? KEY_SUFFIX_ARRAY_STRING : KEY_SUFFIX_STRING))); lastNumber = fieldNumber; lastRepeated = repeated; } @Override public void writeBytes(int fieldNumber, ByteString value, boolean repeated) throws IOException { writeByteArray(fieldNumber, value.getBytes(), repeated); } @Override public void writeDouble(int fieldNumber, double value, boolean repeated) throws IOException { final WriteSink sink = this.sink; if (lastNumber == fieldNumber) { // repeated field tail = sink.writeStrFromDouble( value, this, sink.writeByte( COMMA, this, tail)); return; } tail = sink.writeStrFromDouble( value, this, writeKey( fieldNumber, sink, repeated ? KEY_SUFFIX_ARRAY : KEY_SUFFIX)); lastNumber = fieldNumber; lastRepeated = repeated; } @Override public void writeEnum(int fieldNumber, int value, boolean repeated) throws IOException { writeInt32(fieldNumber, value, repeated); } @Override public void writeFixed32(int fieldNumber, int value, boolean repeated) throws IOException { writeInt32(fieldNumber, value, repeated); } @Override public void writeFixed64(int fieldNumber, long value, boolean repeated) throws IOException { writeInt64(fieldNumber, value, repeated); } @Override public void writeFloat(int fieldNumber, float value, boolean repeated) throws IOException { final WriteSink sink = this.sink; if (lastNumber == fieldNumber) { // repeated field tail = sink.writeStrFromFloat( value, this, sink.writeByte( COMMA, this, tail)); return; } tail = sink.writeStrFromFloat( value, this, writeKey( fieldNumber, sink, repeated ? KEY_SUFFIX_ARRAY : KEY_SUFFIX)); lastNumber = fieldNumber; lastRepeated = repeated; } @Override public void writeInt32(int fieldNumber, int value, boolean repeated) throws IOException { final WriteSink sink = this.sink; if (lastNumber == fieldNumber) { // repeated field tail = sink.writeStrFromInt( value, this, sink.writeByte( COMMA, this, tail)); return; } tail = sink.writeStrFromInt( value, this, writeKey( fieldNumber, sink, repeated ? KEY_SUFFIX_ARRAY : KEY_SUFFIX)); lastNumber = fieldNumber; lastRepeated = repeated; } @Override public void writeInt64(int fieldNumber, long value, boolean repeated) throws IOException { final WriteSink sink = this.sink; if (lastNumber == fieldNumber) { // repeated field tail = sink.writeStrFromLong( value, this, sink.writeByte( COMMA, this, tail)); return; } tail = sink.writeStrFromLong( value, this, writeKey( fieldNumber, sink, repeated ? KEY_SUFFIX_ARRAY : KEY_SUFFIX)); lastNumber = fieldNumber; lastRepeated = repeated; } @Override public void writeSFixed32(int fieldNumber, int value, boolean repeated) throws IOException { writeInt32(fieldNumber, value, repeated); } @Override public void writeSFixed64(int fieldNumber, long value, boolean repeated) throws IOException { writeInt64(fieldNumber, value, repeated); } @Override public void writeSInt32(int fieldNumber, int value, boolean repeated) throws IOException { writeInt32(fieldNumber, value, repeated); } @Override public void writeSInt64(int fieldNumber, long value, boolean repeated) throws IOException { writeInt64(fieldNumber, value, repeated); } @Override public void writeString(int fieldNumber, CharSequence value, boolean repeated) throws IOException { final WriteSink sink = this.sink; if (lastNumber == fieldNumber) { // repeated field tail = sink.writeByte( QUOTE, this, writeUTF8Escaped( value, sink, this, sink.writeByteArray( COMMA_AND_QUOTE, this, tail))); return; } tail = sink.writeByte( QUOTE, this, writeUTF8Escaped( value, sink, this, writeKey( fieldNumber, sink, repeated ? KEY_SUFFIX_ARRAY_STRING : KEY_SUFFIX_STRING))); lastNumber = fieldNumber; lastRepeated = repeated; } @Override public void writeUInt32(int fieldNumber, int value, boolean repeated) throws IOException { writeInt32(fieldNumber, value, repeated); } @Override public void writeUInt64(int fieldNumber, long value, boolean repeated) throws IOException { writeInt64(fieldNumber, value, repeated); } @Override public <T> void writeObject(final int fieldNumber, final T value, final Schema<T> schema, final boolean repeated) throws IOException { final WriteSink sink = this.sink; final Schema<?> lastSchema = this.schema; if (lastNumber == fieldNumber) { tail = sink.writeByteArray( COMMA_AND_START_OBJECT, this, tail); } else { tail = writeKey( fieldNumber, sink, repeated ? KEY_SUFFIX_ARRAY_OBJECT : KEY_SUFFIX_OBJECT); } // reset this.schema = schema; lastNumber = 0; lastRepeated = false; // recursive write schema.writeTo(this, value); tail = lastRepeated ? sink.writeByteArray(END_ARRAY_AND_END_OBJECT, this, tail) : sink.writeByte(END_OBJECT, this, tail); // restore state lastNumber = fieldNumber; lastRepeated = repeated; this.schema = lastSchema; } private static LinkedBuffer writeUTF8Escaped(final byte[] input, int inStart, int inLen, final WriteSink sink, final WriteSession session, LinkedBuffer lb) throws IOException { int lastStart = inStart; for (int i = 0; i < inLen; i++) { final byte b = input[inStart++]; if (b > 0x7f) continue; // ascii final int escape = sOutputEscapes[b]; if (escape == 0) { // nothing to escape continue; } if (escape < 0) { // hex escape // dump the bytes before this offset. final int dumpLen = inStart - lastStart - 1; if (dumpLen != 0) lb = sink.writeByteArray(input, lastStart, dumpLen, session, lb); // update lastStart = inStart; if (lb.offset + 6 > lb.buffer.length) lb = sink.drain(session, lb); final int value = -(escape + 1); lb.buffer[lb.offset++] = (byte) '\\'; lb.buffer[lb.offset++] = (byte) 'u'; lb.buffer[lb.offset++] = (byte) '0'; lb.buffer[lb.offset++] = (byte) '0'; lb.buffer[lb.offset++] = HEX_BYTES[value >> 4]; lb.buffer[lb.offset++] = HEX_BYTES[value & 0x0F]; session.size += 6; } else { // dump the bytes before this offset. final int dumpLen = inStart - lastStart - 1; if (dumpLen != 0) lb = sink.writeByteArray(input, lastStart, dumpLen, session, lb); // update lastStart = inStart; if (lb.offset + 2 > lb.buffer.length) lb = sink.drain(session, lb); lb.buffer[lb.offset++] = (byte) '\\'; lb.buffer[lb.offset++] = (byte) escape; session.size += 2; } } final int remaining = inStart - lastStart; return remaining == 0 ? lb : sink.writeByteArray(input, lastStart, remaining, session, lb); } private static LinkedBuffer writeUTF8Escaped(final CharSequence str, final WriteSink sink, final WriteSession session, LinkedBuffer lb) throws IOException { final int len = str.length(); if (len == 0) return lb; byte[] buffer = lb.buffer; int limit = buffer.length, offset = lb.offset, size = len; for (int i = 0; i < len; i++) { final char c = str.charAt(i); if (c < 0x0080) { final int escape = sOutputEscapes[c]; // System.out.print(c + "|" + escape + " "); if (escape == 0) { // nothing to escape if (offset == limit) { lb.offset = offset; lb = sink.drain(session, lb); offset = lb.offset; buffer = lb.buffer; limit = buffer.length; } // ascii buffer[offset++] = (byte) c; } else if (escape < 0) { // hex escape if (offset + 6 > limit) { lb.offset = offset; lb = sink.drain(session, lb); offset = lb.offset; buffer = lb.buffer; limit = buffer.length; } final int value = -(escape + 1); buffer[offset++] = (byte) '\\'; buffer[offset++] = (byte) 'u'; buffer[offset++] = (byte) '0'; buffer[offset++] = (byte) '0'; buffer[offset++] = HEX_BYTES[value >> 4]; buffer[offset++] = HEX_BYTES[value & 0x0F]; size += 5; } else { if (offset + 2 > limit) { lb.offset = offset; lb = sink.drain(session, lb); offset = lb.offset; buffer = lb.buffer; limit = buffer.length; } buffer[offset++] = (byte) '\\'; buffer[offset++] = (byte) escape; size++; } } else if (c < 0x0800) { if (offset + 2 > limit) { lb.offset = offset; lb = sink.drain(session, lb); offset = lb.offset; buffer = lb.buffer; limit = buffer.length; } buffer[offset++] = (byte) (0xC0 | ((c >> 6) & 0x1F)); buffer[offset++] = (byte) (0x80 | ((c >> 0) & 0x3F)); size++; } else { if (offset + 3 > limit) { lb.offset = offset; lb = sink.drain(session, lb); offset = lb.offset; buffer = lb.buffer; limit = buffer.length; } buffer[offset++] = (byte) (0xE0 | ((c >> 12) & 0x0F)); buffer[offset++] = (byte) (0x80 | ((c >> 6) & 0x3F)); buffer[offset++] = (byte) (0x80 | ((c >> 0) & 0x3F)); size += 2; } } session.size += size; lb.offset = offset; return lb; } static final byte[] HEX_BYTES = new byte[] { (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F' }; // jackson output escaping compabtility static final int[] sOutputEscapes; static { int[] table = new int[128]; // Control chars need generic escape sequence for (int i = 0; i < 32; ++i) { table[i] = -(i + 1); } /* * Others (and some within that range too) have explicit shorter sequences */ table['"'] = '"'; table['\\'] = '\\'; // Escaping of slash is optional, so let's not add it table[0x08] = 'b'; table[0x09] = 't'; table[0x0C] = 'f'; table[0x0A] = 'n'; table[0x0D] = 'r'; sOutputEscapes = table; } /** * Writes a ByteBuffer field. */ @Override public void writeBytes(int fieldNumber, ByteBuffer value, boolean repeated) throws IOException { writeByteRange(false, fieldNumber, value.array(), value.arrayOffset() + value.position(), value.remaining(), repeated); } }
16,455
324
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jclouds.aws.ec2.features; import static org.testng.Assert.assertEquals; import java.util.Set; import org.jclouds.aws.ec2.internal.BaseAWSEC2ApiMockTest; import org.jclouds.aws.ec2.options.CreateSecurityGroupOptions; import org.jclouds.ec2.domain.SecurityGroup; import org.jclouds.net.domain.IpPermission; import org.jclouds.net.domain.IpProtocol; import org.testng.annotations.Test; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.squareup.okhttp.mockwebserver.MockResponse; @Test(groups = "unit", testName = "AWSSecurityGroupApiMockTest", singleThreaded = true) public class AWSSecurityGroupApiMockTest extends BaseAWSEC2ApiMockTest { private final String describeSecurityGroupsResponse = Joiner.on("\n").join( "<DescribeSecurityGroupsResponse xmlns=\"http://ec2.amazonaws.com/doc/2016-11-15/\">", " <requestId>59dbff89-35bd-4eac-99ed-be587EXAMPLE</requestId>", " <securityGroupInfo>", " <item>", " <ownerId>123456789012</ownerId>", " <groupId>sg-1a2b3c4d</groupId>", " <groupName>WebServers</groupName>", " <groupDescription>Web Servers</groupDescription>", " <vpcId>vpc-614cc409</vpcId>", " <ipPermissions>", " <item>", " <ipProtocol>-1</ipProtocol>", " <groups>", " <item>", " <userId>123456789012</userId>", " <groupId>sg-af8661c0</groupId>", " </item>", " </groups>", " <ipRanges/>", " <prefixListIds/>", " </item>", " <item>", " <ipProtocol>tcp</ipProtocol>", " <fromPort>22</fromPort>", " <toPort>22</toPort>", " <groups/>", " <ipRanges>", " <item>", " <cidrIp>192.168.127.12/32</cidrIp>", " </item>", " </ipRanges>", " <prefixListIds/>", " </item>", " </ipPermissions>", " <ipPermissionsEgress>", " <item>", " <ipProtocol>-1</ipProtocol>", " <groups/>", " <ipRanges>", " <item>", " <cidrIp>0.0.0.0/0</cidrIp>", " </item>", " </ipRanges>", " <prefixListIds/>", " </item>", " </ipPermissionsEgress>", " </item>", " </securityGroupInfo>", "</DescribeSecurityGroupsResponse>"); private final String createSecurityGroupResponse = Joiner.on("\n").join( "<CreateSecurityGroupResponse xmlns=\"http://ec2.amazonaws.com/doc/2016-11-15/\">", " <requestId>59dbff89-35bd-4eac-99ed-be587EXAMPLE</requestId>", " <return>true</return>", " <groupId>sg-0a42d66a</groupId>", "</CreateSecurityGroupResponse>"); private final String authorizeSecurityGroupIngressResponse = Joiner.on("\n").join( "<AuthorizeSecurityGroupIngressResponse xmlns=\"http://ec2.amazonaws.com/doc/2016-11-15/\">", " <requestId>59dbff89-35bd-4eac-99ed-be587EXAMPLE</requestId>", " <return>true</return>", "</AuthorizeSecurityGroupIngressResponse>"); private final String revokeSecurityGroupIngressResponse = Joiner.on("\n").join( "<RevokeSecurityGroupIngressResponse xmlns=\"http://ec2.amazonaws.com/doc/2016-11-15/\">", " <requestId>59dbff89-35bd-4eac-99ed-be587EXAMPLE</requestId>", " <return>true</return>", "</RevokeSecurityGroupIngressResponse>"); private final String deleteSecurityGroupResponse = Joiner.on("\n").join( "<DeleteSecurityGroupResponse xmlns=\"http://ec2.amazonaws.com/doc/2016-11-15/\">", " <requestId>59dbff89-35bd-4eac-99ed-be587EXAMPLE</requestId>", " <return>true</return>", "</DeleteSecurityGroupResponse>"); @SuppressWarnings("deprecation") public void describeSecurityGroups() throws Exception { enqueueRegions(DEFAULT_REGION); enqueue(DEFAULT_REGION, new MockResponse().setBody(describeSecurityGroupsResponse)); Set<SecurityGroup> results = securityGroupApi().describeSecurityGroupsInRegion(DEFAULT_REGION); SecurityGroup result = Iterables.getOnlyElement(results); assertEquals(result.getId(), "sg-1a2b3c4d"); assertEquals(result.getRegion(), "us-east-1"); assertEquals(result.getName(), "WebServers"); assertEquals(result.getOwnerId(), "123456789012"); assertEquals(result.getDescription(), "Web Servers"); assertPosted(DEFAULT_REGION, "Action=DescribeRegions"); assertPosted(DEFAULT_REGION, "Action=DescribeSecurityGroups"); } public void describeSecurityGroupsGiving404() throws Exception { enqueueRegions(DEFAULT_REGION); enqueue(DEFAULT_REGION, new MockResponse().setResponseCode(404)); Set<SecurityGroup> results = securityGroupApi().describeSecurityGroupsInRegion(DEFAULT_REGION); assertEquals(results, ImmutableSet.of()); assertPosted(DEFAULT_REGION, "Action=DescribeRegions"); assertPosted(DEFAULT_REGION, "Action=DescribeSecurityGroups"); } public void describeSecurityGroupsById() throws Exception { enqueueRegions(DEFAULT_REGION); enqueue(DEFAULT_REGION, new MockResponse().setBody(describeSecurityGroupsResponse)); Set<SecurityGroup> results = securityGroupApi().describeSecurityGroupsInRegionById(DEFAULT_REGION, "sg-1a2b3c4d"); SecurityGroup result = Iterables.getOnlyElement(results); assertEquals(result.getId(), "sg-1a2b3c4d"); assertPosted(DEFAULT_REGION, "Action=DescribeRegions"); assertPosted(DEFAULT_REGION, "Action=DescribeSecurityGroups&GroupId.1=sg-1a2b3c4d"); } public void describeSecurityGroupsByName() throws Exception { enqueueRegions(DEFAULT_REGION); enqueue(DEFAULT_REGION, new MockResponse().setBody(describeSecurityGroupsResponse)); Set<SecurityGroup> results = securityGroupApi().describeSecurityGroupsInRegion(DEFAULT_REGION, "WebServers"); SecurityGroup result = Iterables.getOnlyElement(results); assertEquals(result.getId(), "sg-1a2b3c4d"); assertPosted(DEFAULT_REGION, "Action=DescribeRegions"); assertPosted(DEFAULT_REGION, "Action=DescribeSecurityGroups&GroupName.1=WebServers"); } public void describeSecurityGroupsFiltered() throws Exception { enqueueRegions(DEFAULT_REGION); enqueue(DEFAULT_REGION, new MockResponse().setBody(describeSecurityGroupsResponse)); Set<SecurityGroup> results = securityGroupApi().describeSecurityGroupsInRegionWithFilter(DEFAULT_REGION, ImmutableMultimap.of("group-name", "WebServers", "vpc-id", "vpc-614cc409")); SecurityGroup result = Iterables.getOnlyElement(results); assertEquals(result.getId(), "sg-1a2b3c4d"); assertPosted(DEFAULT_REGION, "Action=DescribeRegions"); assertPosted(DEFAULT_REGION, "Action=DescribeSecurityGroups&Filter.1.Name=group-name&Filter.1.Value.1=WebServers&Filter.2.Name=vpc-id&Filter.2.Value.1=vpc-614cc409"); } public void describeSecurityGroupsDifferentRegion() throws Exception { String region = "us-west-2"; enqueueRegions(DEFAULT_REGION, region); enqueue(region, new MockResponse().setBody(describeSecurityGroupsResponse)); Set<SecurityGroup> results = securityGroupApi().describeSecurityGroupsInRegion(region); SecurityGroup result = Iterables.getOnlyElement(results); assertEquals(result.getId(), "sg-1a2b3c4d"); assertPosted(DEFAULT_REGION, "Action=DescribeRegions"); assertPosted(region, "Action=DescribeSecurityGroups"); } public void createSecurityGroupsInRegionAndReturnId() throws Exception { enqueueRegions(DEFAULT_REGION); enqueue(DEFAULT_REGION, new MockResponse().setBody(createSecurityGroupResponse)); String result = securityGroupApi().createSecurityGroupInRegionAndReturnId(DEFAULT_REGION, "WebServers", "Web Servers", CreateSecurityGroupOptions.Builder.vpcId("vpc-614cc409")); assertEquals(result, "sg-0a42d66a"); assertPosted(DEFAULT_REGION, "Action=DescribeRegions"); assertPosted(DEFAULT_REGION, "Action=CreateSecurityGroup&GroupName=WebServers&GroupDescription=Web%20Servers&VpcId=vpc-614cc409"); } public void authorizeSecurityGroupIngress() throws Exception { enqueueRegions(DEFAULT_REGION); enqueue(DEFAULT_REGION, new MockResponse().setBody(authorizeSecurityGroupIngressResponse)); IpPermission perm = IpPermission.builder().ipProtocol(IpProtocol.TCP).cidrBlock("0.0.0.0/0") .fromPort(8080).toPort(8080).build(); securityGroupApi().authorizeSecurityGroupIngressInRegion(DEFAULT_REGION, "sg-1a2b3c4d", perm); assertPosted(DEFAULT_REGION, "Action=DescribeRegions"); assertPosted(DEFAULT_REGION, "Action=AuthorizeSecurityGroupIngress&GroupId=sg-1a2b3c4d&IpPermissions.0.IpProtocol=tcp&IpPermissions.0.FromPort=8080&IpPermissions.0.ToPort=8080&IpPermissions.0.IpRanges.0.CidrIp=0.0.0.0/0"); } public void authorizeSecurityGroupIngressList() throws Exception { enqueueRegions(DEFAULT_REGION); enqueue(DEFAULT_REGION, new MockResponse().setBody(authorizeSecurityGroupIngressResponse)); IpPermission perm = IpPermission.builder().ipProtocol(IpProtocol.TCP).cidrBlock("0.0.0.0/0") .fromPort(8080).toPort(8080).build(); IpPermission perm2 = IpPermission.builder().ipProtocol(IpProtocol.TCP).cidrBlock("0.0.0.0/0") .fromPort(8443).toPort(8443).build(); securityGroupApi().authorizeSecurityGroupIngressInRegion(DEFAULT_REGION, "sg-1a2b3c4d", ImmutableList.of(perm, perm2)); assertPosted(DEFAULT_REGION, "Action=DescribeRegions"); assertPosted(DEFAULT_REGION, "Action=AuthorizeSecurityGroupIngress&GroupId=sg-1a2b3c4d&IpPermissions.0.IpProtocol=tcp&IpPermissions.0.FromPort=8080&IpPermissions.0.ToPort=8080&IpPermissions.0.IpRanges.0.CidrIp=0.0.0.0/0&IpPermissions.1.IpProtocol=tcp&IpPermissions.1.FromPort=8443&IpPermissions.1.ToPort=8443&IpPermissions.1.IpRanges.0.CidrIp=0.0.0.0/0"); } public void revokeSecurityGroupIngress() throws Exception { enqueueRegions(DEFAULT_REGION); enqueue(DEFAULT_REGION, new MockResponse().setBody(revokeSecurityGroupIngressResponse)); IpPermission perm = IpPermission.builder().ipProtocol(IpProtocol.TCP).cidrBlock("0.0.0.0/0") .fromPort(8080).toPort(8080).build(); securityGroupApi().revokeSecurityGroupIngressInRegion(DEFAULT_REGION, "sg-1a2b3c4d", perm); assertPosted(DEFAULT_REGION, "Action=DescribeRegions"); assertPosted(DEFAULT_REGION, "Action=RevokeSecurityGroupIngress&GroupId=sg-1a2b3c4d&IpPermissions.0.IpProtocol=tcp&IpPermissions.0.FromPort=8080&IpPermissions.0.ToPort=8080&IpPermissions.0.IpRanges.0.CidrIp=0.0.0.0/0"); } public void revokeSecurityGroupIngressList() throws Exception { enqueueRegions(DEFAULT_REGION); enqueue(DEFAULT_REGION, new MockResponse().setBody(revokeSecurityGroupIngressResponse)); IpPermission perm = IpPermission.builder().ipProtocol(IpProtocol.TCP).cidrBlock("0.0.0.0/0") .fromPort(8080).toPort(8080).build(); IpPermission perm2 = IpPermission.builder().ipProtocol(IpProtocol.TCP).cidrBlock("0.0.0.0/0") .fromPort(8443).toPort(8443).build(); securityGroupApi().revokeSecurityGroupIngressInRegion(DEFAULT_REGION, "sg-1a2b3c4d", ImmutableList.of(perm, perm2)); assertPosted(DEFAULT_REGION, "Action=DescribeRegions"); assertPosted(DEFAULT_REGION, "Action=RevokeSecurityGroupIngress&GroupId=sg-1a2b3c4d&IpPermissions.0.IpProtocol=tcp&IpPermissions.0.FromPort=8080&IpPermissions.0.ToPort=8080&IpPermissions.0.IpRanges.0.CidrIp=0.0.0.0/0&IpPermissions.1.IpProtocol=tcp&IpPermissions.1.FromPort=8443&IpPermissions.1.ToPort=8443&IpPermissions.1.IpRanges.0.CidrIp=0.0.0.0/0"); } public void deleteSecurityGroups() throws Exception { enqueueRegions(DEFAULT_REGION); enqueue(DEFAULT_REGION, new MockResponse().setBody(deleteSecurityGroupResponse)); securityGroupApi().deleteSecurityGroupInRegionById(DEFAULT_REGION, "sg-1a2b3c4d"); assertPosted(DEFAULT_REGION, "Action=DescribeRegions"); assertPosted(DEFAULT_REGION, "Action=DeleteSecurityGroup&GroupId=sg-1a2b3c4d"); } private AWSSecurityGroupApi securityGroupApi() { return api().getSecurityGroupApi().get(); } }
5,714