max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
1,830 | <reponame>thirteen13Floor/zeebe<filename>engine/src/main/java/io/camunda/zeebe/engine/processing/streamprocessor/StreamProcessorListener.java
/*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH under
* one or more contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright ownership.
* Licensed under the Zeebe Community License 1.1. You may not use this file
* except in compliance with the Zeebe Community License 1.1.
*/
package io.camunda.zeebe.engine.processing.streamprocessor;
import io.camunda.zeebe.logstreams.log.LoggedEvent;
/**
* A listener for the {@link StreamProcessor}. Allows retrieving insides of the processing and
* replay of records. It can be especially useful for testing purposes. Note that the listener is
* invoked inside the context of the stream processor and should not block its execution.
*/
public interface StreamProcessorListener {
/**
* Is called when a command is processed.
*
* @param processedCommand the command that is processed
*/
void onProcessed(TypedRecord<?> processedCommand);
/**
* Is called when a record is skipped and not processed.
*
* @param skippedRecord the record that is skipped
*/
default void onSkipped(final LoggedEvent skippedRecord) {}
/**
* Is called when one or more events are replayed. Even if the state changes are not applied.
*
* @param lastReplayedEventPosition the position of the event that is replayed last
* @param lastReadRecordPosition the position of the record that is read last
*/
default void onReplayed(
final long lastReplayedEventPosition, final long lastReadRecordPosition) {}
}
| 460 |
867 | """
Copyright 2016 Deepgram
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from collections import OrderedDict
###############################################################################
def flatten(x):
""" Returns an iterator over flattened entries of a list-like data
structure.
"""
for item in x:
try:
iter(item)
if isinstance(item, (str, bytes, dict, OrderedDict)):
yield item
else:
yield from flatten(item)
except TypeError:
yield item
###############################################################################
def concatenate(args):
""" Returns an iterator which steps through top-level elements in the
iterable.
"""
for sublist in args:
yield from iter(sublist)
### EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF
| 389 |
342 | <reponame>dayoajayi/dayoajayi.github.io
{
"responseStatus": 200,
"responseDetails": null,
"responseData": {
"feed": {
"feedUrl": "https://www.contentful.com/blog/feed.xml",
"title": "Contentful - Blog",
"link": "https://www.contentful.com",
"description": "Contentful gives you an API-first, cloud-based platform to power your sites and apps, allowing you to create first-class user experiences. Stop burying your content in a CMS, empower it with a content infrastructure.",
"author": "",
"entries": [
{
"title": "Why I’m going to the Ada Lovelace Festival (and you should, too!) ",
"link": "https://www.contentful.com/blog/2019/09/25/you-should-go-to-ada-lovelace/",
"content": "Ada Lovelace was a badass. She wrote one of the first computer programs when almost no women worked in tech — in 1842, to be precise. On Oct. 24–25, the Ada Lovelace Festival will celebrate her contributions and those of women leading tech today with talks, workshops and social activities.\n\nThis year’s event focuses on the topic of ownership. Speakers from leading enterprises — such as Volkswagen, Accenture and SAP — will engage with artists, activists and government officials to discuss who gets to own the future of the digital world, and how more people can be involved.\n\nI’m thrilled to attend this year. Here are a few reasons why.\n",
"contentSnippet": "Ada Lovelace was a badass. She wrote one of the first computer programs when almost no women worked in tech — in 1842, t",
"publishedDate": "2019-09-25T14:00:00.000Z",
"categories": [],
"author": ""
},
{
"title": "Keeping it cool: How one engineer uses Contentful to control a fridge in Argentina",
"link": "https://www.contentful.com/blog/2019/09/19/contentful-controls-fridge-argentina/",
"content": "We often talk about how Contentful can do anything and everything. It’s flexibility enables you to design your own content models and deliver content to any channel. But what are some of the very edge cases of how to use Contentful? In this post, I’ll describe one unexpected way I used Contentful to solve a very real problem for my father.\n",
"contentSnippet": "We often talk about how Contentful can do anything and everything. It’s flexibility enables you to design your own conte",
"publishedDate": "2019-09-19T10:00:00.000Z",
"categories": [],
"author": ""
},
{
"title": "Experimentation is now baked into Contentful with new Optimizely app",
"link": "https://www.contentful.com/blog/2019/09/12/experimentation-in-contentful-new-optimizely-app/",
"content": "If you’re a marketer, or you build things for marketers, you know that experimentation is everything. It can help you deliver faster, and can base your decisions on what’s actually bringing you results. Now you can run these experiments on structured content: From today, Optimizely is an officially supported third-party app on Contentful. ",
"contentSnippet": "If you’re a marketer, or you build things for marketers, you know that experimentation is everything. It can help you de",
"publishedDate": "2019-09-12T13:00:00.000Z",
"categories": [],
"author": ""
},
{
"title": "Turn your sidebar into a sensitive language check, a preview tool, and more with sidebar extensions ",
"link": "https://www.contentful.com/blog/2019/09/11/sidebar-extensions-release-post/",
"content": "The best way to adapt Contentful to your business or content processes is to use our UI extensions. It’s how you can customize your editing experience in the Contentful web app. One of these is sidebar extensions, which allows you to customize your sidebar to create a workspace with the controls you need. ",
"contentSnippet": "The best way to adapt Contentful to your business or content processes is to use our UI extensions. It’s how you can cus",
"publishedDate": "2019-09-11T12:00:00.000Z",
"categories": [],
"author": ""
}
]
}
}
} | 1,840 |
587 | /*
* Copyright 2016-2020 Crown Copyright
*
* 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 uk.gov.gchq.gaffer.data.element.function;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import uk.gov.gchq.gaffer.commonutil.ToStringBuilder;
import uk.gov.gchq.gaffer.data.element.Element;
import uk.gov.gchq.gaffer.data.element.Properties;
import uk.gov.gchq.koryphe.tuple.binaryoperator.TupleAdaptedBinaryOperator;
import uk.gov.gchq.koryphe.tuple.binaryoperator.TupleAdaptedBinaryOperatorComposite;
import java.util.Collections;
import java.util.List;
import java.util.function.BinaryOperator;
/**
* An {@link ElementAggregator} is a {@link BinaryOperator} which aggregates two
* {@link Element} objects into a single element.
*/
public class ElementAggregator extends TupleAdaptedBinaryOperatorComposite<String> {
private final PropertiesTuple stateTuple = new PropertiesTuple();
private final PropertiesTuple propertiesTuple = new PropertiesTuple();
private boolean readOnly;
/**
* Aggregates the element. Note - only the element properties are aggregated.
* Aggregation requires elements to have the same identifiers and group.
*
* @param state the other element to aggregate. This is normally the 'state' where the aggregated results will be set.
* @param element the element to aggregated
* @return Element - the aggregated element
*/
public Element apply(final Element state, final Element element) {
if (null == state) {
return element;
}
apply(state.getProperties(), element.getProperties());
return state;
}
public Properties apply(final Properties state, final Properties properties) {
if (null == state) {
return properties;
}
propertiesTuple.setProperties(properties);
stateTuple.setProperties(state);
apply(stateTuple, propertiesTuple);
return state;
}
@Override
public List<TupleAdaptedBinaryOperator<String, ?>> getComponents() {
if (readOnly) {
return Collections.unmodifiableList(super.getComponents());
}
return super.getComponents();
}
/**
* Prevent any further changes being carried out.
*/
public void lock() {
readOnly = true;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (null == obj || getClass() != obj.getClass()) {
return false;
}
final ElementAggregator that = (ElementAggregator) obj;
return new EqualsBuilder()
.appendSuper(super.equals(obj))
.append(stateTuple, that.stateTuple)
.append(propertiesTuple, that.propertiesTuple)
.isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder(59, 13)
.appendSuper(super.hashCode())
.append(stateTuple)
.append(propertiesTuple)
.toHashCode();
}
@Override
public String toString() {
return new ToStringBuilder(this)
.append("stateTuple", stateTuple)
.append("propertiesTuple", propertiesTuple)
.toString();
}
public static class Builder {
private final ElementAggregator aggregator;
public Builder() {
this(new ElementAggregator());
}
private Builder(final ElementAggregator aggregator) {
this.aggregator = aggregator;
}
public SelectedBuilder select(final String... selection) {
final TupleAdaptedBinaryOperator<String, Object> current = new TupleAdaptedBinaryOperator<>();
current.setSelection(selection);
return new SelectedBuilder(aggregator, current);
}
public ElementAggregator build() {
return aggregator;
}
}
public static final class SelectedBuilder {
private final ElementAggregator aggregator;
private final TupleAdaptedBinaryOperator<String, Object> current;
private SelectedBuilder(final ElementAggregator aggregator, final TupleAdaptedBinaryOperator<String, Object> current) {
this.aggregator = aggregator;
this.current = current;
}
public Builder execute(final BinaryOperator function) {
current.setBinaryOperator(function);
aggregator.getComponents().add(current);
return new Builder(aggregator);
}
}
}
| 1,977 |
419 | <reponame>molspace/FastMVS_experiments
from torch import nn
def init_bn(module):
if module.weight is not None:
nn.init.ones_(module.weight)
if module.bias is not None:
nn.init.zeros_(module.bias)
return
def set_bn(model, momentum):
for m in model.modules():
if isinstance(m, (nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d)):
m.momentum = momentum
def init_uniform(module):
if module.weight is not None:
# nn.init.kaiming_uniform_(module.weight)
nn.init.xavier_uniform_(module.weight)
if module.bias is not None:
nn.init.zeros_(module.bias)
return
def set_eps(model, eps):
for m in model.modules():
if isinstance(m, (nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d)):
m.eps = eps
| 375 |
14,668 | <reponame>zealoussnow/chromium
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "media/learning/impl/distribution_reporter.h"
#include "base/bind.h"
#include "base/cxx17_backports.h"
#include "base/metrics/histogram_functions.h"
#include "services/metrics/public/cpp/ukm_builders.h"
#include "services/metrics/public/cpp/ukm_recorder.h"
namespace media {
namespace learning {
// UMA histogram base names.
static const char* kAggregateBase = "Media.Learning.BinaryThreshold.Aggregate.";
static const char* kByTrainingWeightBase =
"Media.Learning.BinaryThreshold.ByTrainingWeight.";
static const char* kByFeatureBase = "Media.Learning.BinaryThreshold.ByFeature.";
enum /* not class */ Bits {
// These are meant to be bitwise-or'd together, so both false cases just mean
// "don't set any bits".
PredictedFalse = 0x00,
ObservedFalse = 0x00,
ObservedTrue = 0x01,
PredictedTrue = 0x02,
// Special value to mean that no prediction was made.
PredictedNothing = 0x04,
};
// Low order bit is "observed", second bit is "predicted", third bit is
// "could not make a prediction".
enum class ConfusionMatrix {
TrueNegative = Bits::PredictedFalse | Bits::ObservedFalse,
FalseNegative = Bits::PredictedFalse | Bits::ObservedTrue,
FalsePositive = Bits::PredictedTrue | Bits::ObservedFalse,
TruePositive = Bits::PredictedTrue | Bits::ObservedTrue,
SkippedNegative = Bits::PredictedNothing | Bits::ObservedFalse,
SkippedPositive = Bits::PredictedNothing | Bits::ObservedTrue,
kMaxValue = SkippedPositive
};
// TODO(liberato): Currently, this implementation is a hack to collect some
// sanity-checking data for local learning with MediaCapabilities. We assume
// that the prediction is the "percentage of dropped frames".
class UmaRegressionReporter : public DistributionReporter {
public:
UmaRegressionReporter(const LearningTask& task)
: DistributionReporter(task) {}
void OnPrediction(const PredictionInfo& info,
TargetHistogram predicted) override {
DCHECK_EQ(task().target_description.ordering,
LearningTask::Ordering::kNumeric);
// As a complete hack, record accuracy with a fixed threshold. The average
// is the observed / predicted percentage of dropped frames.
bool observed_smooth = info.observed.value() <= task().smoothness_threshold;
// See if we made a prediction.
int prediction_bit_mask = Bits::PredictedNothing;
if (predicted.total_counts() != 0) {
bool predicted_smooth =
predicted.Average() <= task().smoothness_threshold;
DVLOG(2) << "Learning: " << task().name
<< ": predicted: " << predicted_smooth << " ("
<< predicted.Average() << ") observed: " << observed_smooth
<< " (" << info.observed.value() << ")";
prediction_bit_mask =
predicted_smooth ? Bits::PredictedTrue : Bits::PredictedFalse;
} else {
DVLOG(2) << "Learning: " << task().name
<< ": predicted: N/A observed: " << observed_smooth << " ("
<< info.observed.value() << ")";
}
// Figure out the ConfusionMatrix enum value.
ConfusionMatrix confusion_matrix_value = static_cast<ConfusionMatrix>(
(observed_smooth ? Bits::ObservedTrue : Bits::ObservedFalse) |
prediction_bit_mask);
// |uma_bucket_number| is the bucket number that we'll fill in with this
// count. It ranges from 0 to |max_buckets-1|, inclusive. Each bucket is
// is separated from the start of the previous bucket by |uma_bucket_size|.
int uma_bucket_number = 0;
constexpr int matrix_size =
static_cast<int>(ConfusionMatrix::kMaxValue) + 1;
// The enum.xml entries separate the buckets by 10, to make it easy to see
// by inspection what bucket number we're in (e.g., x-axis position 23 is
// bucket 2 * 10 + PredictedTrue|ObservedTrue). The label in enum.xml for
// MegaConfusionMatrix also provides the bucket number for easy reading.
constexpr int uma_bucket_size = 10;
DCHECK_LE(matrix_size, uma_bucket_size);
// Maximum number of buckets defined in enums.xml, numbered from 0.
constexpr int max_buckets = 16;
// Sparse histograms can technically go past 100 exactly-stored elements,
// but we limit it anyway. Note that we don't care about |uma_bucket_size|,
// since it's a sparse histogram. Only |matrix_size| elements are used in
// each bucket.
DCHECK_LE(max_buckets * matrix_size, 100);
// If we're splitting by feature, then record it and stop. The others
// aren't meaningful to record if we're using random feature subsets.
if (task().uma_hacky_by_feature_subset_confusion_matrix &&
feature_indices() && feature_indices()->size() == 1) {
// The bucket number is just the feature number that was selected.
uma_bucket_number =
std::min(*feature_indices()->begin(), max_buckets - 1);
std::string base(kByFeatureBase);
base::UmaHistogramSparse(base + task().name,
static_cast<int>(confusion_matrix_value) +
uma_bucket_number * uma_bucket_size);
// Early return since no other measurements are meaningful when we're
// using feature subsets.
return;
}
// If we're selecting a feature subset that's bigger than one but smaller
// than all of them, then we don't know how to report that.
if (feature_indices() &&
feature_indices()->size() != task().feature_descriptions.size()) {
return;
}
// Do normal reporting.
// Record the aggregate confusion matrix.
if (task().uma_hacky_aggregate_confusion_matrix) {
std::string base(kAggregateBase);
base::UmaHistogramEnumeration(base + task().name, confusion_matrix_value);
}
if (task().uma_hacky_by_training_weight_confusion_matrix) {
// Adjust |uma_bucket_offset| by the training weight, and store the
// results in that bucket in the ByTrainingWeight histogram.
//
// This will bucket from 0 in even steps, with the last bucket holding
// |max_reporting_weight+1| and everything above it.
const int n_buckets = task().num_reporting_weight_buckets;
DCHECK_LE(n_buckets, max_buckets);
// If the max reporting weight is zero, then default to splitting the
// buckets evenly, with the last bucket being "completely full set".
const int max_reporting_weight = task().max_reporting_weight
? task().max_reporting_weight
: task().max_data_set_size - 1;
// We use one fewer buckets, to save one for the overflow. Buckets are
// numbered from 0 to |n_buckets-1|, inclusive. In other words, when the
// training weight is equal to |max_reporting_weight|, we still want to
// be in bucket |n_buckets - 2|. That's why we add one to the max before
// we divide; only things over the max go into the last bucket.
uma_bucket_number =
std::min<int>((n_buckets - 1) * info.total_training_weight /
(max_reporting_weight + 1),
n_buckets - 1);
std::string base(kByTrainingWeightBase);
base::UmaHistogramSparse(base + task().name,
static_cast<int>(confusion_matrix_value) +
uma_bucket_number * uma_bucket_size);
}
}
};
// Ukm-based reporter.
class UkmRegressionReporter : public DistributionReporter {
public:
UkmRegressionReporter(const LearningTask& task)
: DistributionReporter(task) {}
void OnPrediction(const PredictionInfo& info,
TargetHistogram predicted) override {
DCHECK_EQ(task().target_description.ordering,
LearningTask::Ordering::kNumeric);
DCHECK_NE(info.source_id, ukm::kInvalidSourceId);
ukm::UkmRecorder* ukm_recorder = ukm::UkmRecorder::Get();
if (!ukm_recorder)
return;
ukm::builders::Media_Learning_PredictionRecord builder(info.source_id);
builder.SetLearningTask(task().GetId());
builder.SetObservedValue(Bucketize(info.observed.value()));
builder.SetPredictedValue(Bucketize(predicted.Average()));
builder.SetTrainingDataTotalWeight(info.total_training_weight);
builder.SetTrainingDataSize(info.total_training_examples);
// TODO(liberato): we'd add feature subsets here.
builder.Record(ukm_recorder);
}
// Scale and translate |value| from the range specified in the task to 0-100.
// We scale it so that the buckets have an equal amount of the input range in
// each of them.
int Bucketize(double value) {
const int output_min = 0;
const int output_max = 100;
// Scale it so that input_min -> output_min and input_max -> output_max.
// Note that the input width is |input_max - input_min|, but there are
// |output_max - output_min + 1| output buckets. That's why we don't
// add one to the denominator, but we do add one to the numerator.
double scaled_value =
((output_max - output_min + 1) * (value - task().ukm_min_input_value)) /
(task().ukm_max_input_value - task().ukm_min_input_value) +
output_min;
// Clip to [0, 100] and truncate to an integer.
return base::clamp(static_cast<int>(scaled_value), output_min, output_max);
}
};
std::unique_ptr<DistributionReporter> DistributionReporter::Create(
const LearningTask& task) {
// We only know how to report regression tasks right now.
if (task.target_description.ordering != LearningTask::Ordering::kNumeric)
return nullptr;
// We can report hacky UMA or non-hacky UKM. We could report both if we had
// a DistributionReporter that forwarded predictions to each, but we don't.
if (task.uma_hacky_aggregate_confusion_matrix ||
task.uma_hacky_by_training_weight_confusion_matrix ||
task.uma_hacky_by_feature_subset_confusion_matrix) {
return std::make_unique<UmaRegressionReporter>(task);
} else if (task.report_via_ukm) {
return std::make_unique<UkmRegressionReporter>(task);
}
return nullptr;
}
DistributionReporter::DistributionReporter(const LearningTask& task)
: task_(task) {}
DistributionReporter::~DistributionReporter() = default;
Model::PredictionCB DistributionReporter::GetPredictionCallback(
const PredictionInfo& info) {
return base::BindOnce(&DistributionReporter::OnPrediction,
weak_factory_.GetWeakPtr(), info);
}
void DistributionReporter::SetFeatureSubset(
const std::set<int>& feature_indices) {
feature_indices_ = feature_indices;
}
} // namespace learning
} // namespace media
| 3,919 |
1,763 | import copy
import logging
from lxml import etree
from zeep import exceptions
from zeep.exceptions import UnexpectedElementError
from zeep.utils import qname_attr
from zeep.xsd.const import Nil, NotSet, xsi_ns
from zeep.xsd.context import XmlParserContext
from zeep.xsd.elements.base import Base
from zeep.xsd.utils import create_prefixed_name, max_occurs_iter
from zeep.xsd.valueobjects import CompoundValue
logger = logging.getLogger(__name__)
__all__ = ["Element"]
class Element(Base):
def __init__(
self,
name,
type_=None,
min_occurs=1,
max_occurs=1,
nillable=False,
default=None,
is_global=False,
attr_name=None,
):
if name is None:
raise ValueError("name cannot be None", self.__class__)
if not isinstance(name, etree.QName):
name = etree.QName(name)
self.name = name.localname if name else None
self.qname = name
self.type = type_
self.min_occurs = min_occurs
self.max_occurs = max_occurs
self.nillable = nillable
self.is_global = is_global
self.default = default
self.attr_name = attr_name or self.name
# assert type_
def __str__(self):
if self.type:
if self.type.is_global:
return "%s(%s)" % (self.name, self.type.qname)
else:
return "%s(%s)" % (self.name, self.type.signature())
return "%s()" % self.name
def __call__(self, *args, **kwargs):
instance = self.type(*args, **kwargs)
if isinstance(instance, CompoundValue):
instance._xsd_elm = self
return instance
def __repr__(self):
return "<%s(name=%r, type=%r)>" % (
self.__class__.__name__,
self.name,
self.type,
)
def __eq__(self, other):
return (
other is not None
and self.__class__ == other.__class__
and self.__dict__ == other.__dict__
)
def get_prefixed_name(self, schema):
return create_prefixed_name(self.qname, schema)
@property
def default_value(self):
if self.accepts_multiple:
return []
if self.is_optional:
return None
return self.default
def clone(self, name=None, min_occurs=1, max_occurs=1):
new = copy.copy(self)
if name:
if not isinstance(name, etree.QName):
name = etree.QName(name)
new.name = name.localname
new.qname = name
new.attr_name = new.name
new.min_occurs = min_occurs
new.max_occurs = max_occurs
return new
def parse(self, xmlelement, schema, allow_none=False, context=None):
"""Process the given xmlelement. If it has an xsi:type attribute then
use that for further processing. This should only be done for subtypes
of the defined type but for now we just accept everything.
This is the entrypoint for parsing an xml document.
:param xmlelement: The XML element to parse
:type xmlelements: lxml.etree._Element
:param schema: The parent XML schema
:type schema: zeep.xsd.Schema
:param allow_none: Allow none
:type allow_none: bool
:param context: Optional parsing context (for inline schemas)
:type context: zeep.xsd.context.XmlParserContext
:return: dict or None
"""
context = context or XmlParserContext()
instance_type = qname_attr(xmlelement, xsi_ns("type"))
xsd_type = None
if instance_type:
xsd_type = schema.get_type(instance_type, fail_silently=True)
xsd_type = xsd_type or self.type
return xsd_type.parse_xmlelement(
xmlelement,
schema,
allow_none=allow_none,
context=context,
schema_type=self.type,
)
def parse_kwargs(self, kwargs, name, available_kwargs):
return self.type.parse_kwargs(kwargs, name or self.attr_name, available_kwargs)
def parse_xmlelements(self, xmlelements, schema, name=None, context=None):
"""Consume matching xmlelements and call parse() on each of them
:param xmlelements: Dequeue of XML element objects
:type xmlelements: collections.deque of lxml.etree._Element
:param schema: The parent XML schema
:type schema: zeep.xsd.Schema
:param name: The name of the parent element
:type name: str
:param context: Optional parsing context (for inline schemas)
:type context: zeep.xsd.context.XmlParserContext
:return: dict or None
"""
result = []
num_matches = 0
for _unused in max_occurs_iter(self.max_occurs):
if not xmlelements:
break
# Workaround for SOAP servers which incorrectly use unqualified
# or qualified elements in the responses (#170, #176). To make the
# best of it we compare the full uri's if both elements have a
# namespace. If only one has a namespace then only compare the
# localname.
# If both elements have a namespace and they don't match then skip
element_tag = etree.QName(xmlelements[0].tag)
if (
element_tag.namespace
and self.qname.namespace
and element_tag.namespace != self.qname.namespace
and schema.settings.strict
):
break
# Only compare the localname
if element_tag.localname == self.qname.localname:
xmlelement = xmlelements.popleft()
num_matches += 1
item = self.parse(xmlelement, schema, allow_none=True, context=context)
result.append(item)
elif (
schema is not None
and schema.settings.xsd_ignore_sequence_order
and list(
filter(
lambda elem: etree.QName(elem.tag).localname
== self.qname.localname,
xmlelements,
)
)
):
# Search for the field in remaining elements, not only the leftmost
xmlelement = list(
filter(
lambda elem: etree.QName(elem.tag).localname
== self.qname.localname,
xmlelements,
)
)[0]
xmlelements.remove(xmlelement)
num_matches += 1
item = self.parse(xmlelement, schema, allow_none=True, context=context)
result.append(item)
else:
# If the element passed doesn't match and the current one is
# not optional then throw an error
if num_matches == 0 and not self.is_optional:
raise UnexpectedElementError(
"Unexpected element %r, expected %r"
% (element_tag.text, self.qname.text)
)
break
if not self.accepts_multiple:
result = result[0] if result else None
return result
def render(self, parent, value, render_path=None):
"""Render the value(s) on the parent lxml.Element.
This actually just calls _render_value_item for each value.
"""
if not render_path:
render_path = [self.qname.localname]
assert parent is not None
self.validate(value, render_path)
if self.accepts_multiple and isinstance(value, list):
for val in value:
self._render_value_item(parent, val, render_path)
else:
self._render_value_item(parent, value, render_path)
def _render_value_item(self, parent, value, render_path):
"""Render the value on the parent lxml.Element"""
if value is Nil:
elm = etree.SubElement(parent, self.qname)
elm.set(xsi_ns("nil"), "true")
return
if value is None or value is NotSet:
if self.is_optional:
return
elm = etree.SubElement(parent, self.qname)
if self.nillable:
elm.set(xsi_ns("nil"), "true")
return
node = etree.SubElement(parent, self.qname)
xsd_type = getattr(value, "_xsd_type", self.type)
if xsd_type != self.type:
return value._xsd_type.render(node, value, xsd_type, render_path)
return self.type.render(node, value, None, render_path)
def validate(self, value, render_path=None):
"""Validate that the value is valid"""
if self.accepts_multiple and isinstance(value, list):
# Validate bounds
if len(value) < self.min_occurs:
raise exceptions.ValidationError(
"Expected at least %d items (minOccurs check) %d items found."
% (self.min_occurs, len(value)),
path=render_path,
)
elif (
self.max_occurs != "unbounded"
and isinstance(self.max_occurs, int)
and len(value) > self.max_occurs
):
raise exceptions.ValidationError(
"Expected at most %d items (maxOccurs check) %d items found."
% (self.max_occurs, len(value)),
path=render_path,
)
for val in value:
self._validate_item(val, render_path)
else:
if not self.is_optional and not self.nillable and value in (None, NotSet):
raise exceptions.ValidationError(
"Missing element %s" % (self.name), path=render_path
)
self._validate_item(value, render_path)
def _validate_item(self, value, render_path):
if self.nillable and value in (None, NotSet):
return
try:
self.type.validate(value, required=True)
except exceptions.ValidationError as exc:
raise exceptions.ValidationError(
"The element %s is not valid: %s" % (self.qname, exc.message),
path=render_path,
)
def resolve_type(self):
self.type = self.type.resolve()
def resolve(self):
self.resolve_type()
return self
def signature(self, schema=None, standalone=True):
from zeep.xsd import ComplexType
if self.type.is_global or (not standalone and self.is_global):
value = self.type.get_prefixed_name(schema)
else:
value = self.type.signature(schema, standalone=False)
if not standalone and isinstance(self.type, ComplexType):
value = "{%s}" % value
if standalone:
value = "%s(%s)" % (self.get_prefixed_name(schema), value)
if self.accepts_multiple:
return "%s[]" % value
return value
| 5,447 |
411 | //
// RAFNMainViewController.h
// Reactive AFNetworking Example
//
// Created by <NAME> on 3/28/13.
// Copyright (c) 2013 CodaFi. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface RAFNMainViewController : UIViewController
@end
| 87 |
13,846 | <filename>src/Security/Authentication/test/OpenIdConnect/wellknownkeys.json
{
"keys": [
{
"kty": "RSA",
"use": "sig",
"kid": "<KEY>",
"x5t": "<KEY>",
"n": "<KEY>",
"e": "AQAB",
"x5c": [ "<KEY>SV<KEY>" ]
},
{
"kty": "RSA",
"use": "sig",
"kid": "FSimuFrFNoC0sJXGmv13nNZceDc",
"x5t": "FSimuFrFNoC0sJXGmv13nNZceDc",
"n": "<KEY>",
"e": "AQAB",
"x5c": [ "<KEY>" ]
},
{
"kty": "RSA",
"use": "sig",
"kid": "2S4SCVGs8Sg9LS6AqLIq6DpW-g8",
"x5t": "2S4SCVGs8Sg9LS6AqLIq6DpW-g8",
"n": "<KEY>",
"e": "AQAB",
"x5c": [ "<KEY> ]
}
]
} | 444 |
312 | <gh_stars>100-1000
package org.elasticsearch.bootstrap;
import java.net.URL;
import java.util.Collections;
import java.util.Set;
import java.util.function.Consumer;
/**
* test of elasticsearch pass. Thus as a workaround we deactivate this test. see
* https://stackoverflow.com/questions/38712251/java-jar-hell-runtime-exception
*/
public class JarHell {
private JarHell() {
}
public static void checkJarHell() throws Exception {
}
public static void checkJarHell(URL urls[]) throws Exception {
}
public static void checkVersionFormat(String targetVersion) {
}
public static void checkJavaVersion(String resource, String targetVersion) {
}
public static Set<URL> parseClassPath() {
return Collections.emptySet();
}
public static void checkJarHell(Consumer o) {
}
}
| 238 |
778 | //
// Project Name: KratosConstitutiveModelsApplication $
// Created by: $Author: JMCarbonell $
// Last modified by: $Co-Author: $
// Date: $Date: April 2017 $
// Revision: $Revision: 0.0 $
//
//
// System includes
// External includes
// Project includes
#include "custom_models/elasticity_models/linear_elastic_model.hpp"
namespace Kratos
{
//******************************CONSTRUCTOR*******************************************
//************************************************************************************
LinearElasticModel::LinearElasticModel()
: ConstitutiveModel()
{
}
//******************************COPY CONSTRUCTOR**************************************
//************************************************************************************
LinearElasticModel::LinearElasticModel(const LinearElasticModel& rOther)
: ConstitutiveModel(rOther)
{
}
//********************************CLONE***********************************************
//************************************************************************************
ConstitutiveModel::Pointer LinearElasticModel::Clone() const
{
return Kratos::make_shared<LinearElasticModel>(*this);
}
//********************************ASSIGNMENT******************************************
//************************************************************************************
LinearElasticModel& LinearElasticModel::operator=(LinearElasticModel const& rOther)
{
ConstitutiveModel::operator=(rOther);
return *this;
}
//*******************************DESTRUCTOR*******************************************
//************************************************************************************
LinearElasticModel::~LinearElasticModel()
{
}
//***********************PUBLIC OPERATIONS FROM BASE CLASS****************************
//************************************************************************************
void LinearElasticModel::InitializeModel(ModelDataType& rValues)
{
KRATOS_TRY
KRATOS_CATCH(" ")
}
//************************************************************************************
//************************************************************************************
void LinearElasticModel::FinalizeModel(ModelDataType& rValues)
{
KRATOS_TRY
KRATOS_CATCH(" ")
}
//************************************************************************************
//************************************************************************************
void LinearElasticModel::InitializeElasticData(ModelDataType& rValues, ElasticDataType& rVariables)
{
KRATOS_TRY
//set model data pointer
rVariables.SetModelData(rValues);
rVariables.SetState(rValues.State);
//add initial strain
if(this->mOptions.Is(ConstitutiveModel::ADD_HISTORY_VECTOR) && this->mOptions.Is(ConstitutiveModel::HISTORY_STRAIN_MEASURE) ){
VectorType StrainVector;
ConstitutiveModelUtilities::StrainTensorToVector(rValues.StrainMatrix, StrainVector);
for(unsigned int i=0; i<StrainVector.size(); i++)
{
StrainVector[i] += this->mHistoryVector[i];
}
rValues.StrainMatrix = ConstitutiveModelUtilities::StrainVectorToTensor(StrainVector, rValues.StrainMatrix);
}
rValues.SetStrainMeasure( ConstitutiveModelData::StrainMeasureType::CauchyGreen_None);
rValues.MaterialParameters.LameMuBar = rValues.MaterialParameters.LameMu;
KRATOS_CATCH(" ")
}
//************************************************************************************
//************************************************************************************
void LinearElasticModel::CalculateStrainEnergy(ModelDataType& rValues, double& rDensityFunction)
{
KRATOS_TRY
KRATOS_ERROR << "calling the base class function in LinearElasticModel ... illegal operation" << std::endl;
KRATOS_CATCH(" ")
}
//************************************************************************************
//************************************************************************************
void LinearElasticModel::CalculateStressTensor(ModelDataType& rValues, MatrixType& rStressMatrix)
{
KRATOS_TRY
ElasticDataType Variables;
this->InitializeElasticData(rValues,Variables);
VectorType StrainVector;
ConstitutiveModelUtilities::StrainTensorToVector(rValues.StrainMatrix, StrainVector);
this->CalculateAndAddConstitutiveTensor(Variables);
VectorType StressVector;
this->CalculateAndAddStressTensor(Variables,StrainVector,StressVector);
rStressMatrix = ConstitutiveModelUtilities::VectorToSymmetricTensor(StressVector,rStressMatrix);
KRATOS_CATCH(" ")
}
//************************************************************************************
//************************************************************************************
void LinearElasticModel::CalculateAndAddStressTensor(ElasticDataType& rVariables, VectorType& rStrainVector, VectorType& rStressVector)
{
KRATOS_TRY
noalias(rStressVector) = prod(rVariables.ConstitutiveTensor,rStrainVector);
rVariables.State().Set(ConstitutiveModelData::STRESS_COMPUTED);
KRATOS_CATCH(" ")
}
//************************************************************************************
//************************************************************************************
void LinearElasticModel::CalculateIsochoricStressTensor(ModelDataType& rValues, MatrixType& rStressMatrix)
{
KRATOS_TRY
ElasticDataType Variables;
this->InitializeElasticData(rValues,Variables);
VectorType StrainVector;
ConstitutiveModelUtilities::StrainTensorToVector(rValues.StrainMatrix, StrainVector);
this->CalculateAndAddConstitutiveTensor(Variables);
VectorType StressVector;
this->CalculateAndAddIsochoricStressTensor(Variables,StrainVector,StressVector);
rStressMatrix = ConstitutiveModelUtilities::VectorToSymmetricTensor(StressVector,rStressMatrix);
KRATOS_CATCH(" ")
}
//************************************************************************************
//************************************************************************************
void LinearElasticModel::CalculateAndAddIsochoricStressTensor(ElasticDataType& rVariables, VectorType& rStrainVector, VectorType& rStressVector)
{
KRATOS_TRY
//total stress
noalias(rStressVector) = prod(rVariables.ConstitutiveTensor,rStrainVector);
//deviatoric stress
double MeanStress = (1.0/3.0) * (rStressVector[0]+rStressVector[1]+rStressVector[2]);
rStressVector[0] -= MeanStress;
rStressVector[1] -= MeanStress;
rStressVector[2] -= MeanStress;
rVariables.State().Set(ConstitutiveModelData::STRESS_COMPUTED);
KRATOS_CATCH(" ")
}
//************************************************************************************
//************************************************************************************
void LinearElasticModel::CalculateVolumetricStressTensor(ModelDataType& rValues, MatrixType& rStressMatrix)
{
KRATOS_TRY
this->CalculateStressTensor( rValues, rStressMatrix);
double MeanPressure = 0;
for (unsigned int i = 0; i < 3; i++)
MeanPressure += rStressMatrix(i,i)/3.0;
rStressMatrix = IdentityMatrix(3);
rStressMatrix *= MeanPressure;
KRATOS_CATCH(" ")
}
//************************************************************************************
//************************************************************************************
void LinearElasticModel::CalculateAndAddVolumetricStressTensor(ElasticDataType& rVariables, VectorType& rStrainVector, VectorType& rStressVector)
{
KRATOS_TRY
KRATOS_ERROR << "calling the base class function in LinearElasticModel ... illegal operation" << std::endl;
KRATOS_CATCH(" ")
}
//************************************************************************************
//************************************************************************************
void LinearElasticModel::CalculateConstitutiveTensor(ModelDataType& rValues, Matrix& rConstitutiveMatrix)
{
KRATOS_TRY
ElasticDataType Variables;
this->InitializeElasticData(rValues,Variables);
//Set constitutive matrix to zero before adding
rConstitutiveMatrix.clear();
this->CalculateAndAddConstitutiveTensor(Variables,rConstitutiveMatrix);
KRATOS_CATCH(" ")
}
//************************************************************************************
//************************************************************************************
void LinearElasticModel::CalculateAndAddConstitutiveTensor(ElasticDataType& rVariables, Matrix& rConstitutiveMatrix)
{
KRATOS_TRY
this->CalculateAndAddConstitutiveTensor(rVariables);
rConstitutiveMatrix = ConstitutiveModelUtilities::ConstitutiveTensorToMatrix(rVariables.ConstitutiveTensor,rConstitutiveMatrix);
KRATOS_CATCH(" ")
}
//************************************************************************************
//************************************************************************************
void LinearElasticModel::CalculateAndAddConstitutiveTensor(ElasticDataType& rVariables)
{
KRATOS_TRY
//Calculate Elastic ConstitutiveMatrix
const ModelDataType& rModelData = rVariables.GetModelData();
const MaterialDataType& rMaterial = rModelData.GetMaterialParameters();
rVariables.ConstitutiveTensor.clear();
// Lame constants
const double& rYoungModulus = rMaterial.GetYoungModulus();
const double& rPoissonCoefficient = rMaterial.GetPoissonCoefficient();
// 3D linear elastic constitutive matrix
rVariables.ConstitutiveTensor ( 0 , 0 ) = (rYoungModulus*(1.0-rPoissonCoefficient)/((1.0+rPoissonCoefficient)*(1.0-2.0*rPoissonCoefficient)));
rVariables.ConstitutiveTensor ( 1 , 1 ) = rVariables.ConstitutiveTensor ( 0 , 0 );
rVariables.ConstitutiveTensor ( 2 , 2 ) = rVariables.ConstitutiveTensor ( 0 , 0 );
rVariables.ConstitutiveTensor ( 3 , 3 ) = rVariables.ConstitutiveTensor ( 0 , 0 )*(1.0-2.0*rPoissonCoefficient)/(2.0*(1.0-rPoissonCoefficient));
rVariables.ConstitutiveTensor ( 4 , 4 ) = rVariables.ConstitutiveTensor ( 3 , 3 );
rVariables.ConstitutiveTensor ( 5 , 5 ) = rVariables.ConstitutiveTensor ( 3 , 3 );
rVariables.ConstitutiveTensor ( 0 , 1 ) = rVariables.ConstitutiveTensor ( 0 , 0 )*rPoissonCoefficient/(1.0-rPoissonCoefficient);
rVariables.ConstitutiveTensor ( 1 , 0 ) = rVariables.ConstitutiveTensor ( 0 , 1 );
rVariables.ConstitutiveTensor ( 0 , 2 ) = rVariables.ConstitutiveTensor ( 0 , 1 );
rVariables.ConstitutiveTensor ( 2 , 0 ) = rVariables.ConstitutiveTensor ( 0 , 1 );
rVariables.ConstitutiveTensor ( 1 , 2 ) = rVariables.ConstitutiveTensor ( 0 , 1 );
rVariables.ConstitutiveTensor ( 2 , 1 ) = rVariables.ConstitutiveTensor ( 0 , 1 );
rVariables.State().Set(ConstitutiveModelData::CONSTITUTIVE_MATRIX_COMPUTED);
KRATOS_CATCH(" ")
}
//************************************************************************************
//************************************************************************************
void LinearElasticModel::CalculateStressAndConstitutiveTensors(ModelDataType& rValues, MatrixType& rStressMatrix, Matrix& rConstitutiveMatrix)
{
KRATOS_TRY
ElasticDataType Variables;
this->InitializeElasticData(rValues,Variables);
VectorType StrainVector;
ConstitutiveModelUtilities::StrainTensorToVector(rValues.StrainMatrix, StrainVector);
//Set constitutive matrix to zero before adding
rConstitutiveMatrix.clear();
this->CalculateAndAddConstitutiveTensor(Variables, rConstitutiveMatrix);
VectorType StressVector;
this->CalculateAndAddStressTensor(Variables,StrainVector,StressVector);
rStressMatrix = ConstitutiveModelUtilities::VectorToSymmetricTensor(StressVector,rStressMatrix);
KRATOS_CATCH(" ")
}
//************************************************************************************
//************************************************************************************
void LinearElasticModel::CalculateIsochoricStressAndConstitutiveTensors(ModelDataType& rValues, MatrixType& rStressMatrix, Matrix& rConstitutiveMatrix)
{
KRATOS_TRY
KRATOS_ERROR << "calling the base class function in LinearElasticModel ... illegal operation" << std::endl;
KRATOS_CATCH(" ")
}
//************************************************************************************
//************************************************************************************
void LinearElasticModel::CalculateVolumetricStressAndConstitutiveTensors(ModelDataType& rValues, MatrixType& rStressMatrix, Matrix& rConstitutiveMatrix)
{
KRATOS_TRY
KRATOS_ERROR << "calling the base class function in LinearElasticModel ... illegal operation" << std::endl;
KRATOS_CATCH(" ")
}
//************************************************************************************
//************************************************************************************
void LinearElasticModel::CalculateIsochoricConstitutiveTensor(ModelDataType& rValues, Matrix& rConstitutiveMatrix)
{
KRATOS_TRY
ElasticDataType Variables;
this->InitializeElasticData(rValues,Variables);
this->CalculateAndAddIsochoricConstitutiveTensor(Variables,rConstitutiveMatrix);
KRATOS_CATCH(" ")
}
//************************************************************************************
//************************************************************************************
void LinearElasticModel::CalculateAndAddIsochoricConstitutiveTensor(ElasticDataType& rVariables, Matrix& rConstitutiveMatrix)
{
KRATOS_TRY
this->CalculateAndAddIsochoricConstitutiveTensor(rVariables);
rConstitutiveMatrix = ConstitutiveModelUtilities::ConstitutiveTensorToMatrix(rVariables.ConstitutiveTensor, rConstitutiveMatrix);
KRATOS_CATCH(" ")
}
//************************************************************************************
//************************************************************************************
void LinearElasticModel::CalculateAndAddIsochoricConstitutiveTensor(ElasticDataType& rVariables)
{
KRATOS_TRY
KRATOS_ERROR << "calling the base class function in LinearElasticModel ... illegal operation" << std::endl;
KRATOS_CATCH(" ")
}
//************************************************************************************
//************************************************************************************
void LinearElasticModel::CalculateVolumetricConstitutiveTensor(ModelDataType& rValues, Matrix& rConstitutiveMatrix)
{
KRATOS_TRY
ElasticDataType Variables;
this->InitializeElasticData(rValues,Variables);
this->CalculateAndAddVolumetricConstitutiveTensor(Variables,rConstitutiveMatrix);
KRATOS_CATCH(" ")
}
//************************************************************************************
//************************************************************************************
void LinearElasticModel::CalculateAndAddVolumetricConstitutiveTensor(ElasticDataType& rVariables, Matrix& rConstitutiveMatrix)
{
KRATOS_TRY
this->CalculateAndAddVolumetricConstitutiveTensor(rVariables);
rConstitutiveMatrix = ConstitutiveModelUtilities::ConstitutiveTensorToMatrix(rVariables.ConstitutiveTensor, rConstitutiveMatrix);
KRATOS_CATCH(" ")
}
//************************************************************************************
//************************************************************************************
void LinearElasticModel::CalculateAndAddVolumetricConstitutiveTensor(ElasticDataType& rVariables)
{
KRATOS_TRY
KRATOS_ERROR << "calling the base class function in LinearElasticModel ... illegal operation" << std::endl;
KRATOS_CATCH(" ")
}
//************************************************************************************
//************************************************************************************
int LinearElasticModel::Check(const Properties& rProperties, const ProcessInfo& rCurrentProcessInfo)
{
KRATOS_TRY
if(YOUNG_MODULUS.Key() == 0 || rProperties[YOUNG_MODULUS] <= 0.00)
KRATOS_ERROR << "YOUNG_MODULUS has Key zero or invalid value" << std::endl;
if(POISSON_RATIO.Key() == 0){
KRATOS_ERROR << "POISSON_RATIO has Key zero invalid value" << std::endl;
}
else{
const double& nu = rProperties[POISSON_RATIO];
if( (nu > 0.499 && nu < 0.501) || (nu < -0.999 && nu > -1.01) )
KRATOS_ERROR << "POISSON_RATIO has an invalid value" << std::endl;
}
return 0;
KRATOS_CATCH(" ")
}
} // Namespace Kratos
| 4,929 |
1,540 | <filename>testng-core/src/test/java/org/testng/internal/MethodMultiplyingInterceptor.java
package org.testng.internal;
import java.util.List;
import org.testng.IMethodInstance;
import org.testng.IMethodInterceptor;
import org.testng.ITestContext;
import org.testng.TestListenerAdapter;
import org.testng.collections.Lists;
public class MethodMultiplyingInterceptor extends TestListenerAdapter
implements IMethodInterceptor {
private int originalMethodCount;
private int multiplyCount = 0;
@Override
public List<IMethodInstance> intercept(List<IMethodInstance> methods, ITestContext context) {
originalMethodCount = methods.size();
List<IMethodInstance> newMethods = Lists.newArrayList();
for (IMethodInstance method : methods) {
newMethods.add(method);
TestClassSample.Occurs occurs =
method
.getMethod()
.getConstructorOrMethod()
.getMethod()
.getAnnotation(TestClassSample.Occurs.class);
if (occurs == null) {
continue;
}
multiplyCount += occurs.times();
for (int i = 1; i <= occurs.times(); i++) {
newMethods.add(method);
}
}
return newMethods;
}
public int getOriginalMethodCount() {
return originalMethodCount;
}
public int getMultiplyCount() {
return multiplyCount;
}
}
| 501 |
547 | <gh_stars>100-1000
{
"name": "menu-jsx",
"version": "1.0.0",
"description": "",
"main": "script.js",
"scripts": {
"build": "./node_modules/.bin/babel script.jsx -o script.js -w",
"copy-react": "./node_modules/.bin/copyfiles -f ./node_modules/react/dist/react.js ./",
"copy-react-dom": "./node_modules/.bin/copyfiles -f ./node_modules/react-dom/dist/react-dom.js ./",
"copy": "npm run copy-react && npm run copy-react-dom",
"start": "npm run copy && ./node_modules/.bin/static"
},
"author": "<NAME>",
"license": "MIT",
"babel": {
"presets": [
"react"
]
},
"devDependencies": {
"babel-cli": "6.9.0",
"babel-preset-react": "6.5.0",
"copyfiles": "^1.2.0",
"node-static": "^0.7.10"
},
"dependencies": {
"react": "^15.5.4",
"react-dom": "^15.5.4"
}
}
| 386 |
1,256 | {
"plugin.description.short": "Envoyez des emails",
"plugin.description.long": "Envoyez des emails"
}
| 36 |
406 | <gh_stars>100-1000
/*
* The MIT License (MIT)
*
* Copyright (c) 2007-2015 Broad Institute
*
* 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.
*/
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.broad.igv.session;
import org.broad.igv.renderer.*;
/**
* Maps between renderer type name and renderer class. Used for saving and restoring sessions.
*
* @author eflakes
*/
public class RendererFactory {
static public enum RendererType {
BAR_CHART,
BASIC_FEATURE,
FEATURE_DENSITY,
GENE_TRACK,
GISTIC_TRACK,
HEATMAP,
MUTATION,
SCATTER_PLOT,
LINE_PLOT
}
static Class defaultRendererClass = BarChartRenderer.class;
static public Class getRendererClass(String rendererTypeName) {
String typeName = rendererTypeName.toUpperCase();
// Try know type names
if (typeName.equals(RendererType.BAR_CHART.name()) || typeName.equals("BAR")) {
return BarChartRenderer.class;
} else if (typeName.equals(RendererType.BASIC_FEATURE.name())) {
return IGVFeatureRenderer.class;
} else if (typeName.equals(RendererType.FEATURE_DENSITY.name())) {
return FeatureDensityRenderer.class;
} else if (typeName.equals(RendererType.GENE_TRACK.name())) {
return GeneTrackRenderer.class;
} else if (typeName.equals(RendererType.GISTIC_TRACK.name())) {
return GisticTrackRenderer.class;
} else if (typeName.equals(RendererType.HEATMAP.name())) {
return HeatmapRenderer.class;
} else if (typeName.equals(RendererType.MUTATION.name())) {
return MutationRenderer.class;
} else if (typeName.equals(RendererType.SCATTER_PLOT.name()) ||
typeName.toUpperCase().equals("POINTS")) {
return PointsRenderer.class;
} else if (typeName.equals(RendererType.LINE_PLOT.name()) ||
typeName.toUpperCase().equals("LINE")) {
return LineplotRenderer.class;
}
return null;
}
static public RendererType getRenderType(Renderer renderer) {
Class rendererClass = renderer.getClass();
RendererType rendererType = null;
if (rendererClass.equals(BarChartRenderer.class)) {
rendererType = RendererType.BAR_CHART;
} else if (rendererClass.equals(IGVFeatureRenderer.class)) {
rendererType = RendererType.BASIC_FEATURE;
} else if (rendererClass.equals(FeatureDensityRenderer.class)) {
rendererType = RendererType.FEATURE_DENSITY;
} else if (rendererClass.equals(GeneTrackRenderer.class)) {
rendererType = RendererType.GENE_TRACK;
} else if (rendererClass.equals(GisticTrackRenderer.class)) {
rendererType = RendererType.GISTIC_TRACK;
} else if (rendererClass.equals(HeatmapRenderer.class)) {
rendererType = RendererType.HEATMAP;
} else if (rendererClass.equals(MutationRenderer.class)) {
rendererType = RendererType.MUTATION;
} else if (rendererClass.equals(PointsRenderer.class)) {
rendererType = RendererType.SCATTER_PLOT;
} else if (rendererClass.equals(LineplotRenderer.class)) {
rendererType = RendererType.LINE_PLOT;
}
return rendererType;
}
}
| 1,765 |
571 | <reponame>arunvinodqmco/cinder<filename>cinder/tests/unit/volume/drivers/netapp/dataontap/client/test_client_cmode.py
# Copyright (c) 2014 <NAME>. All rights reserved.
# Copyright (c) 2015 <NAME>. All rights reserved.
# Copyright (c) 2015 <NAME>. All rights reserved.
# Copyright (c) 2016 <NAME>. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import copy
import time
from unittest import mock
import uuid
import ddt
from lxml import etree
from oslo_utils import units
import paramiko
import six
from cinder import exception
from cinder import ssh_utils
from cinder.tests.unit import test
from cinder.tests.unit.volume.drivers.netapp.dataontap.client import (
fakes as fake_client)
from cinder.tests.unit.volume.drivers.netapp.dataontap import fakes as fake
from cinder.volume.drivers.netapp.dataontap.client import api as netapp_api
from cinder.volume.drivers.netapp.dataontap.client import client_base
from cinder.volume.drivers.netapp.dataontap.client import client_cmode
from cinder.volume.drivers.netapp import utils as netapp_utils
CONNECTION_INFO = {'hostname': 'hostname',
'transport_type': 'https',
'port': 443,
'username': 'admin',
'password': '<PASSWORD>',
'vserver': 'fake_vserver',
'api_trace_pattern': 'fake_regex'}
@ddt.ddt
class NetAppCmodeClientTestCase(test.TestCase):
def setUp(self):
super(NetAppCmodeClientTestCase, self).setUp()
self.mock_object(client_cmode.Client, '_init_ssh_client')
# store the original reference so we can call it later in
# test__get_cluster_nodes_info
self.original_get_cluster_nodes_info = (
client_cmode.Client._get_cluster_nodes_info)
self.mock_object(client_cmode.Client, '_get_cluster_nodes_info',
return_value=fake.HYBRID_SYSTEM_NODES_INFO)
self.mock_object(client_cmode.Client, 'get_ontap_version',
return_value='9.6')
with mock.patch.object(client_cmode.Client,
'get_ontapi_version',
return_value=(1, 20)):
self.client = client_cmode.Client(**CONNECTION_INFO)
self.client.ssh_client = mock.MagicMock()
self.client.connection = mock.MagicMock()
self.connection = self.client.connection
self.vserver = CONNECTION_INFO['vserver']
self.fake_volume = six.text_type(uuid.uuid4())
self.fake_lun = six.text_type(uuid.uuid4())
self.mock_send_request = self.mock_object(
self.client.connection, 'send_request')
def _mock_api_error(self, code='fake'):
return mock.Mock(side_effect=netapp_api.NaApiError(code=code))
def test_has_records(self):
result = self.client._has_records(netapp_api.NaElement(
fake_client.QOS_POLICY_GROUP_GET_ITER_RESPONSE))
self.assertTrue(result)
def test_has_records_not_found(self):
result = self.client._has_records(
netapp_api.NaElement(fake_client.NO_RECORDS_RESPONSE))
self.assertFalse(result)
@ddt.data((fake_client.AGGR_GET_ITER_RESPONSE, 2),
(fake_client.NO_RECORDS_RESPONSE, 0))
@ddt.unpack
def test_get_record_count(self, response, expected):
api_response = netapp_api.NaElement(response)
result = self.client._get_record_count(api_response)
self.assertEqual(expected, result)
def test_get_records_count_invalid(self):
api_response = netapp_api.NaElement(
fake_client.INVALID_GET_ITER_RESPONSE_NO_RECORDS)
self.assertRaises(netapp_utils.NetAppDriverException,
self.client._get_record_count,
api_response)
@ddt.data(True, False)
def test_send_iter_request(self, enable_tunneling):
api_responses = [
netapp_api.NaElement(
fake_client.STORAGE_DISK_GET_ITER_RESPONSE_PAGE_1),
netapp_api.NaElement(
fake_client.STORAGE_DISK_GET_ITER_RESPONSE_PAGE_2),
netapp_api.NaElement(
fake_client.STORAGE_DISK_GET_ITER_RESPONSE_PAGE_3),
]
mock_send_request = self.mock_object(
self.client.connection, 'send_request',
side_effect=copy.deepcopy(api_responses))
storage_disk_get_iter_args = {
'desired-attributes': {
'storage-disk-info': {
'disk-name': None,
}
}
}
result = self.client.send_iter_request(
'storage-disk-get-iter', api_args=storage_disk_get_iter_args,
enable_tunneling=enable_tunneling, max_page_length=10)
num_records = result.get_child_content('num-records')
self.assertEqual('28', num_records)
next_tag = result.get_child_content('next-tag')
self.assertEqual('', next_tag)
args1 = copy.deepcopy(storage_disk_get_iter_args)
args1['max-records'] = 10
args2 = copy.deepcopy(storage_disk_get_iter_args)
args2['max-records'] = 10
args2['tag'] = 'next_tag_1'
args3 = copy.deepcopy(storage_disk_get_iter_args)
args3['max-records'] = 10
args3['tag'] = 'next_tag_2'
mock_send_request.assert_has_calls([
mock.call('storage-disk-get-iter', args1,
enable_tunneling=enable_tunneling),
mock.call('storage-disk-get-iter', args2,
enable_tunneling=enable_tunneling),
mock.call('storage-disk-get-iter', args3,
enable_tunneling=enable_tunneling),
])
def test_send_iter_request_single_page(self):
api_response = netapp_api.NaElement(
fake_client.STORAGE_DISK_GET_ITER_RESPONSE)
mock_send_request = self.mock_object(self.client.connection,
'send_request',
return_value=api_response)
storage_disk_get_iter_args = {
'desired-attributes': {
'storage-disk-info': {
'disk-name': None,
}
}
}
result = self.client.send_iter_request(
'storage-disk-get-iter', api_args=storage_disk_get_iter_args,
max_page_length=10)
num_records = result.get_child_content('num-records')
self.assertEqual('4', num_records)
args = copy.deepcopy(storage_disk_get_iter_args)
args['max-records'] = 10
mock_send_request.assert_has_calls([
mock.call('storage-disk-get-iter', args, enable_tunneling=True),
])
def test_send_iter_request_not_found(self):
api_response = netapp_api.NaElement(fake_client.NO_RECORDS_RESPONSE)
mock_send_request = self.mock_object(self.client.connection,
'send_request',
return_value=api_response)
result = self.client.send_iter_request('storage-disk-get-iter')
num_records = result.get_child_content('num-records')
self.assertEqual('0', num_records)
args = {'max-records': client_cmode.DEFAULT_MAX_PAGE_LENGTH}
mock_send_request.assert_has_calls([
mock.call('storage-disk-get-iter', args, enable_tunneling=True),
])
@ddt.data(fake_client.INVALID_GET_ITER_RESPONSE_NO_ATTRIBUTES,
fake_client.INVALID_GET_ITER_RESPONSE_NO_RECORDS)
def test_send_iter_request_invalid(self, fake_response):
api_response = netapp_api.NaElement(fake_response)
self.mock_object(self.client.connection,
'send_request',
return_value=api_response)
self.assertRaises(netapp_utils.NetAppDriverException,
self.client.send_iter_request,
'storage-disk-get-iter')
@ddt.data((fake.AFF_SYSTEM_NODE_GET_ITER_RESPONSE,
fake.AFF_SYSTEM_NODES_INFO),
(fake.FAS_SYSTEM_NODE_GET_ITER_RESPONSE,
fake.FAS_SYSTEM_NODES_INFO),
(fake_client.NO_RECORDS_RESPONSE, []),
(fake.HYBRID_SYSTEM_NODE_GET_ITER_RESPONSE,
fake.HYBRID_SYSTEM_NODES_INFO))
@ddt.unpack
def test__get_cluster_nodes_info(self, response, expected):
client_cmode.Client._get_cluster_nodes_info = (
self.original_get_cluster_nodes_info)
nodes_response = netapp_api.NaElement(response)
self.mock_object(client_cmode.Client, 'send_iter_request',
return_value=nodes_response)
result = self.client._get_cluster_nodes_info()
self.assertEqual(expected, result)
def test_list_vservers(self):
api_response = netapp_api.NaElement(
fake_client.VSERVER_DATA_LIST_RESPONSE)
self.mock_object(self.client,
'send_iter_request',
return_value=api_response)
result = self.client.list_vservers()
vserver_get_iter_args = {
'query': {
'vserver-info': {
'vserver-type': 'data'
}
},
'desired-attributes': {
'vserver-info': {
'vserver-name': None
}
}
}
self.client.send_iter_request.assert_has_calls([
mock.call('vserver-get-iter', vserver_get_iter_args,
enable_tunneling=False)])
self.assertListEqual([fake_client.VSERVER_NAME], result)
def test_list_vservers_node_type(self):
api_response = netapp_api.NaElement(
fake_client.VSERVER_DATA_LIST_RESPONSE)
self.mock_object(self.client,
'send_iter_request',
return_value=api_response)
result = self.client.list_vservers(vserver_type='node')
vserver_get_iter_args = {
'query': {
'vserver-info': {
'vserver-type': 'node'
}
},
'desired-attributes': {
'vserver-info': {
'vserver-name': None
}
}
}
self.client.send_iter_request.assert_has_calls([
mock.call('vserver-get-iter', vserver_get_iter_args,
enable_tunneling=False)])
self.assertListEqual([fake_client.VSERVER_NAME], result)
def test_list_vservers_not_found(self):
api_response = netapp_api.NaElement(
fake_client.NO_RECORDS_RESPONSE)
self.mock_object(self.client.connection,
'send_request',
return_value=api_response)
result = self.client.list_vservers(vserver_type='data')
self.assertListEqual([], result)
@ddt.data((1, 21), (1, 100), (2, 0))
def test_get_ems_log_destination_vserver(self, ontapi_version):
self.mock_object(self.client,
'get_ontapi_version',
return_value=ontapi_version)
mock_list_vservers = self.mock_object(
self.client,
'list_vservers',
return_value=[fake_client.ADMIN_VSERVER_NAME])
result = self.client._get_ems_log_destination_vserver()
mock_list_vservers.assert_called_once_with(vserver_type='admin')
self.assertEqual(fake_client.ADMIN_VSERVER_NAME, result)
def test_get_ems_log_destination_vserver_legacy(self):
self.mock_object(self.client,
'get_ontapi_version',
return_value=(1, 15))
mock_list_vservers = self.mock_object(
self.client,
'list_vservers',
return_value=[fake_client.NODE_VSERVER_NAME])
result = self.client._get_ems_log_destination_vserver()
mock_list_vservers.assert_called_once_with(vserver_type='node')
self.assertEqual(fake_client.NODE_VSERVER_NAME, result)
def test_get_ems_log_destination_no_cluster_creds(self):
self.mock_object(self.client,
'get_ontapi_version',
return_value=(1, 21))
mock_list_vservers = self.mock_object(
self.client,
'list_vservers',
side_effect=[[], [fake_client.VSERVER_NAME]])
result = self.client._get_ems_log_destination_vserver()
mock_list_vservers.assert_has_calls([
mock.call(vserver_type='admin'),
mock.call(vserver_type='data')])
self.assertEqual(fake_client.VSERVER_NAME, result)
def test_get_ems_log_destination_vserver_not_found(self):
self.mock_object(self.client,
'get_ontapi_version',
return_value=(1, 21))
mock_list_vservers = self.mock_object(
self.client,
'list_vservers',
return_value=[])
self.assertRaises(exception.NotFound,
self.client._get_ems_log_destination_vserver)
mock_list_vservers.assert_has_calls([
mock.call(vserver_type='admin'),
mock.call(vserver_type='data'),
mock.call(vserver_type='node')])
def test_get_iscsi_target_details_no_targets(self):
response = netapp_api.NaElement(
etree.XML("""<results status="passed">
<num-records>1</num-records>
<attributes-list></attributes-list>
</results>"""))
self.connection.invoke_successfully.return_value = response
target_list = self.client.get_iscsi_target_details()
self.assertEqual([], target_list)
def test_get_iscsi_target_details(self):
expected_target = {
"address": "127.0.0.1",
"port": "1337",
"interface-enabled": "true",
"tpgroup-tag": "7777",
}
response = netapp_api.NaElement(
etree.XML("""<results status="passed">
<num-records>1</num-records>
<attributes-list>
<iscsi-interface-list-entry-info>
<ip-address>%(address)s</ip-address>
<ip-port>%(port)s</ip-port>
<is-interface-enabled>%(interface-enabled)s</is-interface-enabled>
<tpgroup-tag>%(tpgroup-tag)s</tpgroup-tag>
</iscsi-interface-list-entry-info>
</attributes-list>
</results>""" % expected_target))
self.connection.invoke_successfully.return_value = response
target_list = self.client.get_iscsi_target_details()
self.assertEqual([expected_target], target_list)
def test_get_iscsi_service_details_with_no_iscsi_service(self):
response = netapp_api.NaElement(
etree.XML("""<results status="passed">
<num-records>0</num-records>
</results>"""))
self.connection.invoke_successfully.return_value = response
iqn = self.client.get_iscsi_service_details()
self.assertIsNone(iqn)
def test_get_iscsi_service_details(self):
expected_iqn = 'iqn.1998-01.org.openstack.iscsi:name1'
response = netapp_api.NaElement(
etree.XML("""<results status="passed">
<num-records>1</num-records>
<attributes-list>
<iscsi-service-info>
<node-name>%s</node-name>
</iscsi-service-info>
</attributes-list>
</results>""" % expected_iqn))
self.connection.invoke_successfully.return_value = response
iqn = self.client.get_iscsi_service_details()
self.assertEqual(expected_iqn, iqn)
def test_get_lun_list(self):
response = netapp_api.NaElement(
etree.XML("""<results status="passed">
<num-records>2</num-records>
<attributes-list>
<lun-info>
</lun-info>
<lun-info>
</lun-info>
</attributes-list>
</results>"""))
self.connection.invoke_successfully.return_value = response
luns = self.client.get_lun_list()
self.assertEqual(2, len(luns))
def test_get_lun_list_with_multiple_pages(self):
response = netapp_api.NaElement(
etree.XML("""<results status="passed">
<num-records>2</num-records>
<attributes-list>
<lun-info> </lun-info>
<lun-info> </lun-info>
</attributes-list>
<next-tag>fake-next</next-tag>
</results>"""))
response_2 = netapp_api.NaElement(
etree.XML("""<results status="passed">
<num-records>2</num-records>
<attributes-list>
<lun-info> </lun-info>
<lun-info> </lun-info>
</attributes-list>
</results>"""))
self.connection.invoke_successfully.side_effect = [response,
response_2]
luns = self.client.get_lun_list()
self.assertEqual(4, len(luns))
def test_get_lun_map_no_luns_mapped(self):
path = '/vol/%s/%s' % (self.fake_volume, self.fake_lun)
response = netapp_api.NaElement(
etree.XML("""<results status="passed">
<num-records>0</num-records>
<attributes-list></attributes-list>
</results>"""))
self.connection.invoke_successfully.return_value = response
lun_map = self.client.get_lun_map(path)
self.assertEqual([], lun_map)
def test_get_lun_map(self):
path = '/vol/%s/%s' % (self.fake_volume, self.fake_lun)
expected_lun_map = {
"initiator-group": "igroup",
"lun-id": "1337",
"vserver": "vserver",
}
response = netapp_api.NaElement(
etree.XML("""<results status="passed">
<num-records>1</num-records>
<attributes-list>
<lun-map-info>
<lun-id>%(lun-id)s</lun-id>
<initiator-group>%(initiator-group)s</initiator-group>
<vserver>%(vserver)s</vserver>
</lun-map-info>
</attributes-list>
</results>""" % expected_lun_map))
self.connection.invoke_successfully.return_value = response
lun_map = self.client.get_lun_map(path)
self.assertEqual([expected_lun_map], lun_map)
def test_get_lun_map_multiple_pages(self):
path = '/vol/%s/%s' % (self.fake_volume, self.fake_lun)
expected_lun_map = {
"initiator-group": "igroup",
"lun-id": "1337",
"vserver": "vserver",
}
response = netapp_api.NaElement(
etree.XML("""<results status="passed">
<num-records>1</num-records>
<attributes-list>
<lun-map-info>
<lun-id>%(lun-id)s</lun-id>
<initiator-group>%(initiator-group)s</initiator-group>
<vserver>%(vserver)s</vserver>
</lun-map-info>
</attributes-list>
<next-tag>blah</next-tag>
</results>""" % expected_lun_map))
response_2 = netapp_api.NaElement(
etree.XML("""<results status="passed">
<num-records>1</num-records>
<attributes-list>
<lun-map-info>
<lun-id>%(lun-id)s</lun-id>
<initiator-group>%(initiator-group)s</initiator-group>
<vserver>%(vserver)s</vserver>
</lun-map-info>
</attributes-list>
</results>""" % expected_lun_map))
self.connection.invoke_successfully.side_effect = [response,
response_2]
lun_map = self.client.get_lun_map(path)
self.assertEqual([expected_lun_map, expected_lun_map], lun_map)
def test_get_igroup_by_initiator_none_found(self):
initiator = 'initiator'
response = netapp_api.NaElement(
etree.XML("""<results status="passed">
<num-records>0</num-records>
<attributes-list></attributes-list>
</results>"""))
self.connection.invoke_successfully.return_value = response
igroup = self.client.get_igroup_by_initiators([initiator])
self.assertEqual([], igroup)
def test_get_igroup_by_initiators(self):
initiators = ['11:22:33:44:55:66:77:88']
expected_igroup = {
'initiator-group-os-type': 'default',
'initiator-group-type': 'fcp',
'initiator-group-name': 'openstack-igroup1',
}
response = netapp_api.NaElement(
etree.XML("""<results status="passed">
<attributes-list>
<initiator-group-info>
<initiator-group-alua-enabled>true</initiator-group-alua-enabled>
<initiator-group-name>%(initiator-group-name)s</initiator-group-name>
<initiator-group-os-type>default</initiator-group-os-type>
<initiator-group-throttle-borrow>false</initiator-group-throttle-borrow>
<initiator-group-throttle-reserve>0</initiator-group-throttle-reserve>
<initiator-group-type>%(initiator-group-type)s</initiator-group-type>
<initiator-group-use-partner>true</initiator-group-use-partner>
<initiator-group-uuid>f8aa707a-57fa-11e4-ad08-123478563412
</initiator-group-uuid>
<initiator-group-vsa-enabled>false</initiator-group-vsa-enabled>
<initiators>
<initiator-info>
<initiator-name>11:22:33:44:55:66:77:88</initiator-name>
</initiator-info>
</initiators>
<vserver>cinder-iscsi</vserver>
</initiator-group-info>
</attributes-list>
<num-records>1</num-records>
</results>""" % expected_igroup))
self.connection.invoke_successfully.return_value = response
igroups = self.client.get_igroup_by_initiators(initiators)
# make these lists of dicts comparable using hashable dictionaries
igroups = set(
[netapp_utils.hashabledict(igroup) for igroup in igroups])
expected = set([netapp_utils.hashabledict(expected_igroup)])
self.assertSetEqual(igroups, expected)
def test_get_igroup_by_initiators_multiple(self):
initiators = ['fc00:db20:35b:7399::5', 'fc00:e968:6179::de52:7100']
expected_igroup = {
'initiator-group-os-type': 'default',
'initiator-group-type': 'fcp',
'initiator-group-name': 'openstack-igroup1',
}
response = netapp_api.NaElement(
etree.XML("""<results status="passed">
<attributes-list>
<initiator-group-info>
<initiator-group-alua-enabled>true</initiator-group-alua-enabled>
<initiator-group-name>%(initiator-group-name)s</initiator-group-name>
<initiator-group-os-type>default</initiator-group-os-type>
<initiator-group-throttle-borrow>false</initiator-group-throttle-borrow>
<initiator-group-throttle-reserve>0</initiator-group-throttle-reserve>
<initiator-group-type>%(initiator-group-type)s</initiator-group-type>
<initiator-group-use-partner>true</initiator-group-use-partner>
<initiator-group-uuid>f8aa707a-57fa-11e4-ad08-123478563412
</initiator-group-uuid>
<initiator-group-vsa-enabled>false</initiator-group-vsa-enabled>
<initiators>
<initiator-info>
<initiator-name>fc00:db20:35b:7399::5</initiator-name>
</initiator-info>
<initiator-info>
<initiator-name>fc00:e968:6179::de52:7100</initiator-name>
</initiator-info>
</initiators>
<vserver>cinder-iscsi</vserver>
</initiator-group-info>
</attributes-list>
<num-records>1</num-records>
</results>""" % expected_igroup))
self.connection.invoke_successfully.return_value = response
igroups = self.client.get_igroup_by_initiators(initiators)
# make these lists of dicts comparable using hashable dictionaries
igroups = set(
[netapp_utils.hashabledict(igroup) for igroup in igroups])
expected = set([netapp_utils.hashabledict(expected_igroup)])
self.assertSetEqual(igroups, expected)
def test_get_igroup_by_initiators_multiple_pages(self):
initiator = 'fc00:db20:35b:7399::5'
expected_igroup1 = {
'initiator-group-os-type': 'default',
'initiator-group-type': 'fcp',
'initiator-group-name': 'openstack-igroup1',
}
expected_igroup2 = {
'initiator-group-os-type': 'default',
'initiator-group-type': 'fcp',
'initiator-group-name': 'openstack-igroup2',
}
response_1 = netapp_api.NaElement(
etree.XML("""<results status="passed">
<attributes-list>
<initiator-group-info>
<initiator-group-alua-enabled>true</initiator-group-alua-enabled>
<initiator-group-name>%(initiator-group-name)s</initiator-group-name>
<initiator-group-os-type>default</initiator-group-os-type>
<initiator-group-throttle-borrow>false</initiator-group-throttle-borrow>
<initiator-group-throttle-reserve>0</initiator-group-throttle-reserve>
<initiator-group-type>%(initiator-group-type)s</initiator-group-type>
<initiator-group-use-partner>true</initiator-group-use-partner>
<initiator-group-uuid>f8aa707a-57fa-11e4-ad08-123478563412
</initiator-group-uuid>
<initiator-group-vsa-enabled>false</initiator-group-vsa-enabled>
<initiators>
<initiator-info>
<initiator-name>fc00:db20:35b:7399::5</initiator-name>
</initiator-info>
</initiators>
<vserver>cinder-iscsi</vserver>
</initiator-group-info>
</attributes-list>
<next-tag>12345</next-tag>
<num-records>1</num-records>
</results>""" % expected_igroup1))
response_2 = netapp_api.NaElement(
etree.XML("""<results status="passed">
<attributes-list>
<initiator-group-info>
<initiator-group-alua-enabled>true</initiator-group-alua-enabled>
<initiator-group-name>%(initiator-group-name)s</initiator-group-name>
<initiator-group-os-type>default</initiator-group-os-type>
<initiator-group-throttle-borrow>false</initiator-group-throttle-borrow>
<initiator-group-throttle-reserve>0</initiator-group-throttle-reserve>
<initiator-group-type>%(initiator-group-type)s</initiator-group-type>
<initiator-group-use-partner>true</initiator-group-use-partner>
<initiator-group-uuid>f8aa707a-57fa-11e4-ad08-123478563412
</initiator-group-uuid>
<initiator-group-vsa-enabled>false</initiator-group-vsa-enabled>
<initiators>
<initiator-info>
<initiator-name>fc00:db20:35b:7399::5</initiator-name>
</initiator-info>
</initiators>
<vserver>cinder-iscsi</vserver>
</initiator-group-info>
</attributes-list>
<num-records>1</num-records>
</results>""" % expected_igroup2))
self.connection.invoke_successfully.side_effect = [response_1,
response_2]
igroups = self.client.get_igroup_by_initiators([initiator])
# make these lists of dicts comparable using hashable dictionaries
igroups = set(
[netapp_utils.hashabledict(igroup) for igroup in igroups])
expected = set([netapp_utils.hashabledict(expected_igroup1),
netapp_utils.hashabledict(expected_igroup2)])
self.assertSetEqual(igroups, expected)
@ddt.data(True, False)
def test__validate_qos_policy_group_none_adaptive(self, is_adaptive):
self.client.features.add_feature('ADAPTIVE_QOS', supported=True)
self.client._validate_qos_policy_group(
is_adaptive=is_adaptive, spec=None)
def test__validate_qos_policy_group_none_adaptive_no_support(self):
self.client.features.add_feature('ADAPTIVE_QOS', supported=False)
self.assertRaises(
netapp_utils.NetAppDriverException,
self.client._validate_qos_policy_group,
is_adaptive=True,
spec=None)
@ddt.data(True, False)
def test__validate_qos_policy_group_no_qos_min_support(self, is_adaptive):
spec = {'min_throughput': '10'}
self.assertRaises(
netapp_utils.NetAppDriverException,
self.client._validate_qos_policy_group,
is_adaptive=is_adaptive,
spec=spec,
qos_min_support=False)
def test__validate_qos_policy_group_no_block_size_support(self):
self.client.features.add_feature(
'ADAPTIVE_QOS_BLOCK_SIZE', supported=False)
spec = {'block_size': '4K'}
self.assertRaises(
netapp_utils.NetAppDriverException,
self.client._validate_qos_policy_group,
is_adaptive=True,
spec=spec)
def test__validate_qos_policy_group_no_expected_iops_allocation_support(
self):
self.client.features.add_feature(
'ADAPTIVE_QOS_EXPECTED_IOPS_ALLOCATION', supported=False)
spec = {'expected_iops_allocation': 'used-space'}
self.assertRaises(
netapp_utils.NetAppDriverException,
self.client._validate_qos_policy_group,
is_adaptive=True,
spec=spec)
def test__validate_qos_policy_group_adaptive_qos_spec(self):
self.client.features.add_feature('ADAPTIVE_QOS', supported=True)
self.client.features.add_feature(
'ADAPTIVE_QOS_BLOCK_SIZE', supported=True)
self.client.features.add_feature(
'ADAPTIVE_QOS_EXPECTED_IOPS_ALLOCATION', supported=True)
spec = {
'expected_iops': '128IOPS/GB',
'peak_iops': '512IOPS/GB',
'expected_iops_allocation': 'used-space',
'peak_iops_allocation': 'used-space',
'absolute_min_iops': '64IOPS',
'block_size': '4K',
}
self.client._validate_qos_policy_group(is_adaptive=True, spec=spec)
def test_clone_lun(self):
self.client.clone_lun(
'volume', 'fakeLUN', 'newFakeLUN',
qos_policy_group_name=fake.QOS_POLICY_GROUP_NAME)
self.assertEqual(1, self.connection.invoke_successfully.call_count)
@ddt.data({'supports_is_backup': True, 'is_snapshot': True},
{'supports_is_backup': True, 'is_snapshot': False},
{'supports_is_backup': False, 'is_snapshot': True},
{'supports_is_backup': False, 'is_snapshot': False})
@ddt.unpack
def test_clone_lun_is_snapshot(self, supports_is_backup, is_snapshot):
self.client.features.add_feature('BACKUP_CLONE_PARAM',
supported=supports_is_backup)
self.client.clone_lun(
'volume', 'fakeLUN', 'newFakeLUN', is_snapshot=is_snapshot)
clone_create_args = {
'volume': 'volume',
'source-path': 'fakeLUN',
'destination-path': 'newFakeLUN',
'space-reserve': 'true',
}
if is_snapshot and supports_is_backup:
clone_create_args['is-backup'] = 'true'
self.connection.invoke_successfully.assert_called_once_with(
netapp_api.NaElement.create_node_with_children(
'clone-create', **clone_create_args), True)
@ddt.data(0, 1)
def test_clone_lun_is_sub_clone(self, block_count):
self.client.clone_lun(
'volume', 'fakeLUN', 'newFakeLUN', block_count=block_count)
clone_create_args = {
'volume': 'volume',
'source-path': 'fakeLUN',
'destination-path': 'newFakeLUN',
}
is_sub_clone = block_count > 0
if not is_sub_clone:
clone_create_args['space-reserve'] = 'true'
# build the expected request
expected_clone_create_request = \
netapp_api.NaElement.create_node_with_children(
'clone-create', **clone_create_args)
# add expected fields in the request if it's a sub-clone
if is_sub_clone:
block_ranges = netapp_api.NaElement("block-ranges")
block_range = \
netapp_api.NaElement.create_node_with_children(
'block-range',
**{'source-block-number': '0',
'destination-block-number': '0',
'block-count': '1'})
block_ranges.add_child_elem(block_range)
expected_clone_create_request.add_child_elem(block_ranges)
self.connection.invoke_successfully.assert_called_once_with(
expected_clone_create_request, True)
def test_clone_lun_multiple_zapi_calls(self):
"""Test for when lun clone requires more than one zapi call."""
# Max clone size per call = 2^18 blocks * 512 bytes/block = 128 MB
# Force 2 calls
bc = 2 ** 18 * 2
self.client.clone_lun('volume', 'fakeLUN', 'newFakeLUN',
block_count=bc)
self.assertEqual(2, self.connection.invoke_successfully.call_count)
def test_get_lun_by_args(self):
response = netapp_api.NaElement(
etree.XML("""<results status="passed">
<num-records>2</num-records>
<attributes-list>
<lun-info>
</lun-info>
</attributes-list>
</results>"""))
self.connection.invoke_successfully.return_value = response
lun = self.client.get_lun_by_args()
self.assertEqual(1, len(lun))
def test_get_lun_by_args_no_lun_found(self):
response = netapp_api.NaElement(
etree.XML("""<results status="passed">
<num-records>2</num-records>
<attributes-list>
</attributes-list>
</results>"""))
self.connection.invoke_successfully.return_value = response
lun = self.client.get_lun_by_args()
self.assertEqual(0, len(lun))
def test_get_lun_by_args_with_args_specified(self):
path = '/vol/%s/%s' % (self.fake_volume, self.fake_lun)
response = netapp_api.NaElement(
etree.XML("""<results status="passed">
<num-records>2</num-records>
<attributes-list>
<lun-info>
</lun-info>
</attributes-list>
</results>"""))
self.connection.invoke_successfully.return_value = response
lun = self.client.get_lun_by_args(path=path)
__, _args, __ = self.connection.invoke_successfully.mock_calls[0]
actual_request = _args[0]
query = actual_request.get_child_by_name('query')
lun_info_args = query.get_child_by_name('lun-info').get_children()
# Assert request is made with correct arguments
self.assertEqual('path', lun_info_args[0].get_name())
self.assertEqual(path, lun_info_args[0].get_content())
self.assertEqual(1, len(lun))
def test_file_assign_qos(self):
api_args = {
'volume': fake.FLEXVOL,
'qos-policy-group-name': fake.QOS_POLICY_GROUP_NAME,
'file': fake.NFS_FILE_PATH,
'vserver': self.vserver
}
self.client.file_assign_qos(fake.FLEXVOL, fake.QOS_POLICY_GROUP_NAME,
False, fake.NFS_FILE_PATH)
self.mock_send_request.assert_has_calls([
mock.call('file-assign-qos', api_args, False)])
def test_set_lun_qos_policy_group(self):
api_args = {
'path': fake.LUN_PATH,
'qos-policy-group': fake.QOS_POLICY_GROUP_NAME,
}
self.client.set_lun_qos_policy_group(
fake.LUN_PATH, fake.QOS_POLICY_GROUP_NAME)
self.mock_send_request.assert_has_calls([
mock.call('lun-set-qos-policy-group', api_args)])
def test_provision_qos_policy_group_no_qos_policy_group_info(self):
mock_qos_policy_group_create = self.mock_object(
self.client, 'qos_policy_group_create')
self.client.provision_qos_policy_group(qos_policy_group_info=None,
qos_min_support=True)
mock_qos_policy_group_create.assert_not_called()
def test_provision_qos_policy_group_no_legacy_no_spec(self):
mock_qos_policy_group_exists = self.mock_object(
self.client, 'qos_policy_group_exists')
mock_qos_policy_group_create = self.mock_object(
self.client, 'qos_policy_group_create')
mock_qos_policy_group_modify = self.mock_object(
self.client, 'qos_policy_group_modify')
self.client.provision_qos_policy_group(qos_policy_group_info={},
qos_min_support=False)
mock_qos_policy_group_exists.assert_not_called()
mock_qos_policy_group_create.assert_not_called()
mock_qos_policy_group_modify.assert_not_called()
def test_provision_qos_policy_group_legacy_qos_policy_group_info(self):
mock_qos_policy_group_create = self.mock_object(
self.client, 'qos_policy_group_create')
self.client.provision_qos_policy_group(
qos_policy_group_info=fake.QOS_POLICY_GROUP_INFO_LEGACY,
qos_min_support=True)
mock_qos_policy_group_create.assert_not_called()
def test_provision_qos_policy_group_with_qos_spec_create_with_min(self):
self.mock_object(self.client,
'qos_policy_group_exists',
return_value=False)
mock_qos_policy_group_create = self.mock_object(
self.client, 'qos_policy_group_create')
mock_qos_policy_group_modify = self.mock_object(
self.client, 'qos_policy_group_modify')
self.client.provision_qos_policy_group(fake.QOS_POLICY_GROUP_INFO,
True)
mock_qos_policy_group_create.assert_called_once_with({
'policy_name': fake.QOS_POLICY_GROUP_NAME,
'min_throughput': fake.MIN_IOPS,
'max_throughput': fake.MAX_IOPS,
})
mock_qos_policy_group_modify.assert_not_called()
def test_provision_qos_policy_group_with_qos_spec_create_with_aqos(self):
self.client.features.add_feature('ADAPTIVE_QOS', supported=True)
self.client.features.add_feature(
'ADAPTIVE_QOS_BLOCK_SIZE', supported=True)
self.client.features.add_feature(
'ADAPTIVE_QOS_EXPECTED_IOPS_ALLOCATION', supported=True)
self.mock_object(self.client,
'qos_policy_group_exists',
return_value=False)
mock_qos_policy_group_create = self.mock_object(
self.client, 'qos_policy_group_create')
mock_qos_policy_group_modify = self.mock_object(
self.client, 'qos_policy_group_modify')
mock_qos_adaptive_policy_group_create = self.mock_object(
self.client, 'qos_adaptive_policy_group_create')
mock_qos_adaptive_policy_group_modify = self.mock_object(
self.client, 'qos_adaptive_policy_group_modify')
self.client.provision_qos_policy_group(
fake.ADAPTIVE_QOS_POLICY_GROUP_INFO, False)
mock_qos_adaptive_policy_group_create.assert_called_once_with(
fake.ADAPTIVE_QOS_SPEC)
mock_qos_adaptive_policy_group_modify.assert_not_called()
mock_qos_policy_group_create.assert_not_called()
mock_qos_policy_group_modify.assert_not_called()
def test_provision_qos_policy_group_with_qos_spec_create_unsupported(self):
mock_qos_policy_group_exists = self.mock_object(
self.client, 'qos_policy_group_exists')
mock_qos_policy_group_create = self.mock_object(
self.client, 'qos_policy_group_create')
mock_qos_policy_group_modify = self.mock_object(
self.client, 'qos_policy_group_modify')
self.assertRaises(
netapp_utils.NetAppDriverException,
self.client.provision_qos_policy_group,
fake.QOS_POLICY_GROUP_INFO,
False)
mock_qos_policy_group_exists.assert_not_called()
mock_qos_policy_group_create.assert_not_called()
mock_qos_policy_group_modify.assert_not_called()
def test_provision_qos_policy_group_with_invalid_qos_spec(self):
self.mock_object(self.client, '_validate_qos_policy_group',
side_effect=netapp_utils.NetAppDriverException)
mock_policy_group_spec_is_adaptive = self.mock_object(
netapp_utils, 'is_qos_policy_group_spec_adaptive')
mock_qos_policy_group_exists = self.mock_object(
self.client, 'qos_policy_group_exists')
mock_qos_policy_group_create = self.mock_object(
self.client, 'qos_policy_group_create')
mock_qos_policy_group_modify = self.mock_object(
self.client, 'qos_policy_group_modify')
self.assertRaises(
netapp_utils.NetAppDriverException,
self.client.provision_qos_policy_group,
fake.QOS_POLICY_GROUP_INFO,
False)
mock_policy_group_spec_is_adaptive.assert_called_once_with(
fake.QOS_POLICY_GROUP_INFO)
mock_qos_policy_group_exists.assert_not_called()
mock_qos_policy_group_create.assert_not_called()
mock_qos_policy_group_modify.assert_not_called()
def test_provision_qos_policy_group_with_qos_spec_create(self):
self.mock_object(self.client,
'qos_policy_group_exists',
return_value=False)
mock_qos_policy_group_create = self.mock_object(
self.client, 'qos_policy_group_create')
mock_qos_policy_group_modify = self.mock_object(
self.client, 'qos_policy_group_modify')
self.client.provision_qos_policy_group(fake.QOS_POLICY_GROUP_INFO_MAX,
True)
mock_qos_policy_group_create.assert_has_calls([
mock.call({
'policy_name': fake.QOS_POLICY_GROUP_NAME,
'max_throughput': fake.MAX_THROUGHPUT,
})])
mock_qos_policy_group_modify.assert_not_called()
def test_provision_qos_policy_group_with_qos_spec_modify_with_min(self):
self.mock_object(self.client,
'qos_policy_group_exists',
return_value=True)
mock_qos_policy_group_create = self.mock_object(
self.client, 'qos_policy_group_create')
mock_qos_policy_group_modify = self.mock_object(
self.client, 'qos_policy_group_modify')
self.client.provision_qos_policy_group(fake.QOS_POLICY_GROUP_INFO,
True)
mock_qos_policy_group_create.assert_not_called()
mock_qos_policy_group_modify.assert_has_calls([
mock.call({
'policy_name': fake.QOS_POLICY_GROUP_NAME,
'min_throughput': fake.MIN_IOPS,
'max_throughput': fake.MAX_IOPS,
})])
def test_provision_qos_policy_group_with_qos_spec_modify(self):
self.mock_object(self.client,
'qos_policy_group_exists',
return_value=True)
mock_qos_policy_group_create = self.mock_object(
self.client, 'qos_policy_group_create')
mock_qos_policy_group_modify = self.mock_object(
self.client, 'qos_policy_group_modify')
self.client.provision_qos_policy_group(fake.QOS_POLICY_GROUP_INFO_MAX,
True)
mock_qos_policy_group_create.assert_not_called()
mock_qos_policy_group_modify.assert_has_calls([
mock.call({
'policy_name': fake.QOS_POLICY_GROUP_NAME,
'max_throughput': fake.MAX_THROUGHPUT,
})])
def test_provision_qos_policy_group_with_qos_spec_modify_with_aqos(self):
self.client.features.add_feature('ADAPTIVE_QOS', supported=True)
self.client.features.add_feature(
'ADAPTIVE_QOS_BLOCK_SIZE', supported=True)
self.client.features.add_feature(
'ADAPTIVE_QOS_EXPECTED_IOPS_ALLOCATION', supported=True)
self.mock_object(self.client,
'qos_policy_group_exists',
return_value=True)
mock_qos_policy_group_create = self.mock_object(
self.client, 'qos_policy_group_create')
mock_qos_policy_group_modify = self.mock_object(
self.client, 'qos_policy_group_modify')
mock_qos_adaptive_policy_group_create = self.mock_object(
self.client, 'qos_adaptive_policy_group_create')
mock_qos_adaptive_policy_group_modify = self.mock_object(
self.client, 'qos_adaptive_policy_group_modify')
self.client.provision_qos_policy_group(
fake.ADAPTIVE_QOS_POLICY_GROUP_INFO, False)
mock_qos_adaptive_policy_group_modify.assert_called_once_with(
fake.ADAPTIVE_QOS_SPEC)
mock_qos_adaptive_policy_group_create.assert_not_called()
mock_qos_policy_group_create.assert_not_called()
mock_qos_policy_group_modify.assert_not_called()
def test_qos_policy_group_exists(self):
self.mock_send_request.return_value = netapp_api.NaElement(
fake_client.QOS_POLICY_GROUP_GET_ITER_RESPONSE)
result = self.client.qos_policy_group_exists(
fake.QOS_POLICY_GROUP_NAME)
api_args = {
'query': {
'qos-policy-group-info': {
'policy-group': fake.QOS_POLICY_GROUP_NAME,
},
},
'desired-attributes': {
'qos-policy-group-info': {
'policy-group': None,
},
},
}
self.mock_send_request.assert_has_calls([
mock.call('qos-policy-group-get-iter', api_args, False)])
self.assertTrue(result)
def test_qos_policy_group_exists_not_found(self):
self.mock_send_request.return_value = netapp_api.NaElement(
fake_client.NO_RECORDS_RESPONSE)
result = self.client.qos_policy_group_exists(
fake.QOS_POLICY_GROUP_NAME)
self.assertFalse(result)
def test_qos_policy_group_create(self):
api_args = {
'policy-group': fake.QOS_POLICY_GROUP_NAME,
'min-throughput': '0',
'max-throughput': fake.MAX_THROUGHPUT,
'vserver': self.vserver,
}
self.client.qos_policy_group_create({
'policy_name': fake.QOS_POLICY_GROUP_NAME,
'min_throughput': '0',
'max_throughput': fake.MAX_THROUGHPUT,
})
self.mock_send_request.assert_has_calls([
mock.call('qos-policy-group-create', api_args, False)])
def test_qos_adaptive_policy_group_create(self):
api_args = {
'policy-group': fake.QOS_POLICY_GROUP_NAME,
'expected-iops': '%sIOPS/GB' % fake.EXPECTED_IOPS_PER_GB,
'peak-iops': '%sIOPS/GB' % fake.PEAK_IOPS_PER_GB,
'expected-iops-allocation': fake.EXPECTED_IOPS_ALLOCATION,
'peak-iops-allocation': fake.PEAK_IOPS_ALLOCATION,
'block-size': fake.BLOCK_SIZE,
'vserver': self.vserver,
}
self.client.qos_adaptive_policy_group_create({
'policy_name': fake.QOS_POLICY_GROUP_NAME,
'expected_iops': '%sIOPS/GB' % fake.EXPECTED_IOPS_PER_GB,
'peak_iops': '%sIOPS/GB' % fake.PEAK_IOPS_PER_GB,
'expected_iops_allocation': fake.EXPECTED_IOPS_ALLOCATION,
'peak_iops_allocation': fake.PEAK_IOPS_ALLOCATION,
'block_size': fake.BLOCK_SIZE,
})
self.mock_send_request.assert_has_calls([
mock.call('qos-adaptive-policy-group-create', api_args, False)])
def test_qos_policy_group_modify(self):
api_args = {
'policy-group': fake.QOS_POLICY_GROUP_NAME,
'min-throughput': '0',
'max-throughput': fake.MAX_THROUGHPUT,
}
self.client.qos_policy_group_modify({
'policy_name': fake.QOS_POLICY_GROUP_NAME,
'min_throughput': '0',
'max_throughput': fake.MAX_THROUGHPUT,
})
self.mock_send_request.assert_has_calls([
mock.call('qos-policy-group-modify', api_args, False)])
def test_qos_adaptive_policy_group_modify(self):
api_args = {
'policy-group': fake.QOS_POLICY_GROUP_NAME,
'expected-iops': '%sIOPS/GB' % fake.EXPECTED_IOPS_PER_GB,
'peak-iops': '%sIOPS/GB' % fake.PEAK_IOPS_PER_GB,
'expected-iops-allocation': fake.EXPECTED_IOPS_ALLOCATION,
'peak-iops-allocation': fake.PEAK_IOPS_ALLOCATION,
'block-size': fake.BLOCK_SIZE,
}
self.client.qos_adaptive_policy_group_modify({
'policy_name': fake.QOS_POLICY_GROUP_NAME,
'expected_iops': '%sIOPS/GB' % fake.EXPECTED_IOPS_PER_GB,
'peak_iops': '%sIOPS/GB' % fake.PEAK_IOPS_PER_GB,
'expected_iops_allocation': fake.EXPECTED_IOPS_ALLOCATION,
'peak_iops_allocation': fake.PEAK_IOPS_ALLOCATION,
'block_size': fake.BLOCK_SIZE,
})
self.mock_send_request.assert_has_calls([
mock.call('qos-adaptive-policy-group-modify', api_args, False)])
def test_qos_policy_group_rename(self):
new_name = 'new-' + fake.QOS_POLICY_GROUP_NAME
api_args = {
'policy-group-name': fake.QOS_POLICY_GROUP_NAME,
'new-name': new_name,
}
self.client.qos_policy_group_rename(
fake.QOS_POLICY_GROUP_NAME, new_name)
self.mock_send_request.assert_has_calls([
mock.call('qos-policy-group-rename', api_args, False)])
def test_mark_qos_policy_group_for_deletion_no_qos_policy_group_info(self):
mock_rename = self.mock_object(self.client, 'qos_policy_group_rename')
mock_remove = self.mock_object(self.client,
'remove_unused_qos_policy_groups')
self.client.mark_qos_policy_group_for_deletion(
qos_policy_group_info=None)
self.assertEqual(0, mock_rename.call_count)
self.assertEqual(0, mock_remove.call_count)
def test_mark_qos_policy_group_for_deletion_legacy_qos_policy(self):
mock_rename = self.mock_object(self.client, 'qos_policy_group_rename')
mock_remove = self.mock_object(self.client,
'remove_unused_qos_policy_groups')
self.client.mark_qos_policy_group_for_deletion(
qos_policy_group_info=fake.QOS_POLICY_GROUP_INFO_LEGACY)
self.assertEqual(0, mock_rename.call_count)
self.assertEqual(1, mock_remove.call_count)
@ddt.data(True, False)
def test_mark_qos_policy_group_for_deletion_w_qos_spec(self,
is_adaptive):
mock_rename = self.mock_object(self.client, 'qos_policy_group_rename')
mock_remove = self.mock_object(self.client,
'remove_unused_qos_policy_groups')
mock_log = self.mock_object(client_cmode.LOG, 'warning')
new_name = 'deleted_cinder_%s' % fake.QOS_POLICY_GROUP_NAME
self.client.mark_qos_policy_group_for_deletion(
qos_policy_group_info=fake.QOS_POLICY_GROUP_INFO_MAX,
is_adaptive=is_adaptive)
mock_rename.assert_has_calls([
mock.call(fake.QOS_POLICY_GROUP_NAME, new_name, is_adaptive)])
self.assertEqual(0, mock_log.call_count)
self.assertEqual(1, mock_remove.call_count)
@ddt.data(True, False)
def test_mark_qos_policy_group_for_deletion_exception_path(self,
is_adaptive):
mock_rename = self.mock_object(self.client, 'qos_policy_group_rename')
mock_rename.side_effect = netapp_api.NaApiError
mock_remove = self.mock_object(self.client,
'remove_unused_qos_policy_groups')
mock_log = self.mock_object(client_cmode.LOG, 'warning')
new_name = 'deleted_cinder_%s' % fake.QOS_POLICY_GROUP_NAME
self.client.mark_qos_policy_group_for_deletion(
qos_policy_group_info=fake.QOS_POLICY_GROUP_INFO_MAX,
is_adaptive=is_adaptive)
mock_rename.assert_has_calls([
mock.call(fake.QOS_POLICY_GROUP_NAME, new_name, is_adaptive)])
self.assertEqual(1, mock_log.call_count)
self.assertEqual(1, mock_remove.call_count)
def test_remove_unused_qos_policy_groups(self):
mock_log = self.mock_object(client_cmode.LOG, 'debug')
api_args = {
'query': {
'qos-policy-group-info': {
'policy-group': 'deleted_cinder_*',
'vserver': self.vserver,
}
},
'max-records': 3500,
'continue-on-failure': 'true',
'return-success-list': 'false',
'return-failure-list': 'false',
}
self.client.remove_unused_qos_policy_groups()
self.mock_send_request.assert_has_calls([
mock.call('qos-policy-group-delete-iter', api_args, False)])
self.assertEqual(0, mock_log.call_count)
def test_remove_unused_qos_policy_groups_api_error(self):
self.client.features.add_feature('ADAPTIVE_QOS', supported=True)
mock_log = self.mock_object(client_cmode.LOG, 'debug')
qos_query = {
'qos-policy-group-info': {
'policy-group': 'deleted_cinder_*',
'vserver': self.vserver,
}
}
adaptive_qos_query = {
'qos-adaptive-policy-group-info': {
'policy-group': 'deleted_cinder_*',
'vserver': self.vserver,
}
}
qos_api_args = {
'query': qos_query,
'max-records': 3500,
'continue-on-failure': 'true',
'return-success-list': 'false',
'return-failure-list': 'false',
}
adaptive_qos_api_args = {
'query': adaptive_qos_query,
'max-records': 3500,
'continue-on-failure': 'true',
'return-success-list': 'false',
'return-failure-list': 'false',
}
self.mock_send_request.side_effect = netapp_api.NaApiError
self.client.remove_unused_qos_policy_groups()
self.mock_send_request.assert_has_calls([
mock.call('qos-policy-group-delete-iter',
qos_api_args, False),
mock.call('qos-adaptive-policy-group-delete-iter',
adaptive_qos_api_args, False),
])
self.assertEqual(2, mock_log.call_count)
@mock.patch('cinder.volume.volume_utils.resolve_hostname',
return_value='192.168.1.101')
def test_get_if_info_by_ip_not_found(self, mock_resolve_hostname):
fake_ip = '192.168.1.101'
response = netapp_api.NaElement(
etree.XML("""<results status="passed">
<num-records>0</num-records>
<attributes-list>
</attributes-list>
</results>"""))
self.connection.invoke_successfully.return_value = response
self.assertRaises(exception.NotFound, self.client.get_if_info_by_ip,
fake_ip)
@mock.patch('cinder.volume.volume_utils.resolve_hostname',
return_value='192.168.1.101')
def test_get_if_info_by_ip(self, mock_resolve_hostname):
fake_ip = '192.168.1.101'
response = netapp_api.NaElement(
etree.XML("""<results status="passed">
<num-records>1</num-records>
<attributes-list>
<net-interface-info>
</net-interface-info>
</attributes-list>
</results>"""))
self.connection.invoke_successfully.return_value = response
results = self.client.get_if_info_by_ip(fake_ip)
self.assertEqual(1, len(results))
def test_get_vol_by_junc_vserver_not_found(self):
fake_vserver = 'fake_vserver'
fake_junc = 'fake_junction_path'
response = netapp_api.NaElement(
etree.XML("""<results status="passed">
<num-records>0</num-records>
<attributes-list>
</attributes-list>
</results>"""))
self.connection.invoke_successfully.return_value = response
self.assertRaises(exception.NotFound,
self.client.get_vol_by_junc_vserver,
fake_vserver, fake_junc)
def test_get_vol_by_junc_vserver(self):
fake_vserver = 'fake_vserver'
fake_junc = 'fake_junction_path'
expected_flex_vol = 'fake_flex_vol'
volume_attr_str = ("""
<volume-attributes>
<volume-id-attributes>
<name>%(flex_vol)s</name>
</volume-id-attributes>
</volume-attributes>
""" % {'flex_vol': expected_flex_vol})
volume_attr = netapp_api.NaElement(etree.XML(volume_attr_str))
response = netapp_api.NaElement(
etree.XML("""<results status="passed">
<num-records>1</num-records>
<attributes-list>%(vol)s</attributes-list>
</results>""" % {'vol': volume_attr_str}))
self.connection.invoke_successfully.return_value = response
mock_get_unique_vol = self.mock_object(
self.client, 'get_unique_volume', return_value=volume_attr)
actual_flex_vol = self.client.get_vol_by_junc_vserver(fake_vserver,
fake_junc)
self.assertEqual(expected_flex_vol, actual_flex_vol)
mock_get_unique_vol.assert_called_once_with(response)
def test_clone_file(self):
expected_flex_vol = "fake_flex_vol"
expected_src_path = "fake_src_path"
expected_dest_path = "fake_dest_path"
self.connection.get_api_version.return_value = (1, 20)
self.client.clone_file(expected_flex_vol, expected_src_path,
expected_dest_path, self.vserver,
source_snapshot=fake.CG_SNAPSHOT_ID)
__, _args, __ = self.connection.invoke_successfully.mock_calls[0]
actual_request = _args[0]
actual_flex_vol = actual_request.get_child_by_name('volume') \
.get_content()
actual_src_path = actual_request \
.get_child_by_name('source-path').get_content()
actual_dest_path = actual_request.get_child_by_name(
'destination-path').get_content()
self.assertEqual(expected_flex_vol, actual_flex_vol)
self.assertEqual(expected_src_path, actual_src_path)
self.assertEqual(expected_dest_path, actual_dest_path)
req_snapshot_child = actual_request.get_child_by_name('snapshot-name')
self.assertEqual(fake.CG_SNAPSHOT_ID, req_snapshot_child.get_content())
self.assertIsNone(actual_request.get_child_by_name(
'destination-exists'))
def test_clone_file_when_destination_exists(self):
expected_flex_vol = "fake_flex_vol"
expected_src_path = "fake_src_path"
expected_dest_path = "fake_dest_path"
self.connection.get_api_version.return_value = (1, 20)
self.client.clone_file(expected_flex_vol, expected_src_path,
expected_dest_path, self.vserver,
dest_exists=True)
__, _args, __ = self.connection.invoke_successfully.mock_calls[0]
actual_request = _args[0]
actual_flex_vol = actual_request.get_child_by_name('volume') \
.get_content()
actual_src_path = actual_request \
.get_child_by_name('source-path').get_content()
actual_dest_path = actual_request.get_child_by_name(
'destination-path').get_content()
self.assertEqual(expected_flex_vol, actual_flex_vol)
self.assertEqual(expected_src_path, actual_src_path)
self.assertEqual(expected_dest_path, actual_dest_path)
self.assertEqual('true',
actual_request.get_child_by_name(
'destination-exists').get_content())
def test_clone_file_when_destination_exists_and_version_less_than_1_20(
self):
expected_flex_vol = "fake_flex_vol"
expected_src_path = "fake_src_path"
expected_dest_path = "fake_dest_path"
self.connection.get_api_version.return_value = (1, 19)
self.client.clone_file(expected_flex_vol, expected_src_path,
expected_dest_path, self.vserver,
dest_exists=True)
__, _args, __ = self.connection.invoke_successfully.mock_calls[0]
actual_request = _args[0]
actual_flex_vol = actual_request.get_child_by_name('volume') \
.get_content()
actual_src_path = actual_request \
.get_child_by_name('source-path').get_content()
actual_dest_path = actual_request.get_child_by_name(
'destination-path').get_content()
self.assertEqual(expected_flex_vol, actual_flex_vol)
self.assertEqual(expected_src_path, actual_src_path)
self.assertEqual(expected_dest_path, actual_dest_path)
self.assertIsNone(actual_request.get_child_by_name(
'destination-exists'))
@ddt.data({'supports_is_backup': True, 'is_snapshot': True},
{'supports_is_backup': True, 'is_snapshot': False},
{'supports_is_backup': False, 'is_snapshot': True},
{'supports_is_backup': False, 'is_snapshot': False})
@ddt.unpack
def test_clone_file_is_snapshot(self, supports_is_backup, is_snapshot):
self.connection.get_api_version.return_value = (1, 20)
self.client.features.add_feature('BACKUP_CLONE_PARAM',
supported=supports_is_backup)
self.client.clone_file(
'volume', 'fake_source', 'fake_destination', 'fake_vserver',
is_snapshot=is_snapshot)
clone_create_args = {
'volume': 'volume',
'source-path': 'fake_source',
'destination-path': 'fake_destination',
}
if is_snapshot and supports_is_backup:
clone_create_args['is-backup'] = 'true'
self.connection.invoke_successfully.assert_called_once_with(
netapp_api.NaElement.create_node_with_children(
'clone-create', **clone_create_args), True)
def test_get_file_usage(self):
expected_bytes = "2048"
fake_vserver = 'fake_vserver'
fake_path = 'fake_path'
response = netapp_api.NaElement(
etree.XML("""<results status="passed">
<unique-bytes>%(unique-bytes)s</unique-bytes>
</results>""" % {'unique-bytes': expected_bytes}))
self.connection.invoke_successfully.return_value = response
actual_bytes = self.client.get_file_usage(fake_vserver, fake_path)
self.assertEqual(expected_bytes, actual_bytes)
def test_check_cluster_api(self):
self.client.features.USER_CAPABILITY_LIST = True
mock_check_cluster_api_legacy = self.mock_object(
self.client, '_check_cluster_api_legacy')
mock_check_cluster_api = self.mock_object(
self.client, '_check_cluster_api', return_value=True)
result = self.client.check_cluster_api('object', 'operation', 'api')
self.assertTrue(result)
self.assertFalse(mock_check_cluster_api_legacy.called)
mock_check_cluster_api.assert_called_once_with(
'object', 'operation', 'api')
def test_check_cluster_api_legacy(self):
self.client.features.USER_CAPABILITY_LIST = False
mock_check_cluster_api_legacy = self.mock_object(
self.client, '_check_cluster_api_legacy', return_value=True)
mock_check_cluster_api = self.mock_object(
self.client, '_check_cluster_api')
result = self.client.check_cluster_api('object', 'operation', 'api')
self.assertTrue(result)
self.assertFalse(mock_check_cluster_api.called)
mock_check_cluster_api_legacy.assert_called_once_with('api')
def test__check_cluster_api(self):
api_response = netapp_api.NaElement(
fake_client.SYSTEM_USER_CAPABILITY_GET_ITER_RESPONSE)
self.mock_send_request.return_value = api_response
result = self.client._check_cluster_api('object', 'operation', 'api')
system_user_capability_get_iter_args = {
'query': {
'capability-info': {
'object-name': 'object',
'operation-list': {
'operation-info': {
'name': 'operation',
},
},
},
},
'desired-attributes': {
'capability-info': {
'operation-list': {
'operation-info': {
'api-name': None,
},
},
},
},
}
self.mock_send_request.assert_called_once_with(
'system-user-capability-get-iter',
system_user_capability_get_iter_args,
False)
self.assertTrue(result)
@ddt.data(fake_client.SYSTEM_USER_CAPABILITY_GET_ITER_RESPONSE,
fake_client.NO_RECORDS_RESPONSE)
def test__check_cluster_api_not_found(self, response):
api_response = netapp_api.NaElement(response)
self.mock_send_request.return_value = api_response
result = self.client._check_cluster_api('object', 'operation', 'api4')
self.assertFalse(result)
@ddt.data('volume-get-iter', 'volume-get', 'aggr-options-list-info')
def test__check_cluster_api_legacy(self, api):
api_response = netapp_api.NaElement(fake_client.NO_RECORDS_RESPONSE)
self.mock_send_request.return_value = api_response
result = self.client._check_cluster_api_legacy(api)
self.assertTrue(result)
self.mock_send_request.assert_called_once_with(api,
enable_tunneling=False)
@ddt.data(netapp_api.EAPIPRIVILEGE, netapp_api.EAPINOTFOUND)
def test__check_cluster_api_legacy_insufficient_privileges(self, code):
self.mock_send_request.side_effect = netapp_api.NaApiError(code=code)
result = self.client._check_cluster_api_legacy('volume-get-iter')
self.assertFalse(result)
self.mock_send_request.assert_called_once_with('volume-get-iter',
enable_tunneling=False)
def test__check_cluster_api_legacy_api_error(self):
self.mock_send_request.side_effect = netapp_api.NaApiError()
result = self.client._check_cluster_api_legacy('volume-get-iter')
self.assertTrue(result)
self.mock_send_request.assert_called_once_with('volume-get-iter',
enable_tunneling=False)
def test__check_cluster_api_legacy_invalid_api(self):
self.assertRaises(ValueError,
self.client._check_cluster_api_legacy,
'fake_api')
def test_get_operational_lif_addresses(self):
expected_result = ['1.2.3.4', '9172.16.58.3']
api_response = netapp_api.NaElement(
fake_client.GET_OPERATIONAL_LIF_ADDRESSES_RESPONSE)
self.mock_object(self.client,
'send_iter_request',
return_value=api_response)
address_list = self.client.get_operational_lif_addresses()
net_interface_get_iter_args = {
'query': {
'net-interface-info': {
'operational-status': 'up'
}
},
'desired-attributes': {
'net-interface-info': {
'address': None,
}
}
}
self.client.send_iter_request.assert_called_once_with(
'net-interface-get-iter', net_interface_get_iter_args)
self.assertEqual(expected_result, address_list)
@ddt.data({'junction_path': '/fake/vol'},
{'name': 'fake_volume'},
{'junction_path': '/fake/vol', 'name': 'fake_volume'})
def test_get_volume_state(self, kwargs):
api_response = netapp_api.NaElement(
fake_client.VOLUME_GET_ITER_STATE_RESPONSE)
mock_send_iter_request = self.mock_object(
self.client, 'send_iter_request', return_value=api_response)
volume_response = netapp_api.NaElement(
fake_client.VOLUME_GET_ITER_STATE_ATTR)
mock_get_unique_vol = self.mock_object(
self.client, 'get_unique_volume', return_value=volume_response)
state = self.client.get_volume_state(**kwargs)
volume_id_attributes = {}
if 'junction_path' in kwargs:
volume_id_attributes['junction-path'] = kwargs['junction_path']
if 'name' in kwargs:
volume_id_attributes['name'] = kwargs['name']
volume_get_iter_args = {
'query': {
'volume-attributes': {
'volume-id-attributes': volume_id_attributes,
}
},
'desired-attributes': {
'volume-attributes': {
'volume-id-attributes': {
'style-extended': None,
},
'volume-state-attributes': {
'state': None
}
}
},
}
mock_send_iter_request.assert_called_once_with(
'volume-get-iter', volume_get_iter_args)
mock_get_unique_vol.assert_called_once_with(api_response)
self.assertEqual(fake_client.VOLUME_STATE_ONLINE, state)
@ddt.data({'flexvol_path': '/fake/vol'},
{'flexvol_name': 'fake_volume'},
{'flexvol_path': '/fake/vol', 'flexvol_name': 'fake_volume'})
def test_get_flexvol_capacity(self, kwargs):
api_response = netapp_api.NaElement(
fake_client.VOLUME_GET_ITER_CAPACITY_RESPONSE)
mock_send_iter_request = self.mock_object(
self.client, 'send_iter_request', return_value=api_response)
volume_response = netapp_api.NaElement(
fake_client.VOLUME_GET_ITER_CAPACITY_ATTR)
mock_get_unique_vol = self.mock_object(
self.client, 'get_unique_volume', return_value=volume_response)
capacity = self.client.get_flexvol_capacity(**kwargs)
volume_id_attributes = {}
if 'flexvol_path' in kwargs:
volume_id_attributes['junction-path'] = kwargs['flexvol_path']
if 'flexvol_name' in kwargs:
volume_id_attributes['name'] = kwargs['flexvol_name']
volume_get_iter_args = {
'query': {
'volume-attributes': {
'volume-id-attributes': volume_id_attributes,
}
},
'desired-attributes': {
'volume-attributes': {
'volume-id-attributes': {
'style-extended': None,
},
'volume-space-attributes': {
'size-available': None,
'size-total': None,
}
}
},
}
mock_send_iter_request.assert_called_once_with(
'volume-get-iter', volume_get_iter_args)
mock_get_unique_vol.assert_called_once_with(api_response)
self.assertEqual(fake_client.VOLUME_SIZE_TOTAL, capacity['size-total'])
self.assertEqual(fake_client.VOLUME_SIZE_AVAILABLE,
capacity['size-available'])
def test_get_flexvol_capacity_not_found(self):
self.mock_send_request.return_value = netapp_api.NaElement(
fake_client.NO_RECORDS_RESPONSE)
self.assertRaises(netapp_utils.NetAppDriverException,
self.client.get_flexvol_capacity,
flexvol_path='fake_path')
def test_list_flexvols(self):
api_response = netapp_api.NaElement(
fake_client.VOLUME_GET_ITER_LIST_RESPONSE)
self.mock_object(self.client,
'send_iter_request',
return_value=api_response)
result = self.client.list_flexvols()
volume_get_iter_args = {
'query': {
'volume-attributes': {
'volume-id-attributes': {
'type': 'rw',
'style': 'flex',
},
'volume-state-attributes': {
'is-vserver-root': 'false',
'is-inconsistent': 'false',
'is-invalid': 'false',
'state': 'online',
},
},
},
'desired-attributes': {
'volume-attributes': {
'volume-id-attributes': {
'name': None,
},
},
},
}
self.client.send_iter_request.assert_called_once_with(
'volume-get-iter', volume_get_iter_args)
self.assertEqual(list(fake_client.VOLUME_NAMES), result)
def test_list_flexvols_not_found(self):
api_response = netapp_api.NaElement(
fake_client.NO_RECORDS_RESPONSE)
self.mock_object(self.client,
'send_iter_request',
return_value=api_response)
result = self.client.list_flexvols()
self.assertEqual([], result)
@ddt.data(False, True)
def test_get_flexvol(self, is_flexgroup):
if is_flexgroup:
api_response = netapp_api.NaElement(
fake_client.VOLUME_GET_ITER_SSC_RESPONSE_FLEXGROUP)
volume_response = netapp_api.NaElement(
fake_client.VOLUME_GET_ITER_SSC_RESPONSE_ATTR_FLEXGROUP)
else:
api_response = netapp_api.NaElement(
fake_client.VOLUME_GET_ITER_SSC_RESPONSE)
volume_response = netapp_api.NaElement(
fake_client.VOLUME_GET_ITER_SSC_RESPONSE_ATTR)
self.mock_object(self.client,
'send_iter_request',
return_value=api_response)
mock_get_unique_vol = self.mock_object(
self.client, 'get_unique_volume', return_value=volume_response)
result = self.client.get_flexvol(
flexvol_name=fake_client.VOLUME_NAMES[0],
flexvol_path='/%s' % fake_client.VOLUME_NAMES[0])
volume_get_iter_args = {
'query': {
'volume-attributes': {
'volume-id-attributes': {
'name': fake_client.VOLUME_NAMES[0],
'junction-path': '/' + fake_client.VOLUME_NAMES[0],
'type': 'rw',
'style': 'flex',
},
'volume-state-attributes': {
'is-vserver-root': 'false',
'is-inconsistent': 'false',
'is-invalid': 'false',
'state': 'online',
},
},
},
'desired-attributes': {
'volume-attributes': {
'volume-id-attributes': {
'name': None,
'owning-vserver-name': None,
'junction-path': None,
'type': None,
'aggr-list': {
'aggr-name': None,
},
'containing-aggregate-name': None,
'style-extended': None,
},
'volume-mirror-attributes': {
'is-data-protection-mirror': None,
'is-replica-volume': None,
},
'volume-space-attributes': {
'is-space-guarantee-enabled': None,
'space-guarantee': None,
'percentage-snapshot-reserve': None,
'size': None,
},
'volume-qos-attributes': {
'policy-group-name': None,
},
'volume-snapshot-attributes': {
'snapshot-policy': None,
},
'volume-language-attributes': {
'language-code': None,
}
},
},
}
self.client.send_iter_request.assert_called_once_with(
'volume-get-iter', volume_get_iter_args)
mock_get_unique_vol.assert_called_once_with(api_response)
if is_flexgroup:
self.assertEqual(fake_client.VOLUME_INFO_SSC_FLEXGROUP, result)
else:
self.assertEqual(fake_client.VOLUME_INFO_SSC, result)
def test_create_flexvol(self):
self.mock_object(self.client.connection, 'send_request')
self.client.create_flexvol(
fake_client.VOLUME_NAME, fake_client.VOLUME_AGGREGATE_NAME, 100)
volume_create_args = {
'containing-aggr-name': fake_client.VOLUME_AGGREGATE_NAME,
'size': '100g',
'volume': fake_client.VOLUME_NAME,
'volume-type': 'rw',
'junction-path': '/%s' % fake_client.VOLUME_NAME,
}
self.client.connection.send_request.assert_called_once_with(
'volume-create', volume_create_args)
@ddt.data('dp', 'rw', None)
def test_create_volume_with_extra_specs(self, volume_type):
self.mock_object(self.client, 'enable_flexvol_dedupe')
self.mock_object(self.client, 'enable_flexvol_compression')
self.mock_object(self.client.connection, 'send_request')
self.client.create_flexvol(
fake_client.VOLUME_NAME, fake_client.VOLUME_AGGREGATE_NAME, 100,
space_guarantee_type='volume', language='en-US',
snapshot_policy='default', dedupe_enabled=True,
compression_enabled=True, snapshot_reserve=15,
volume_type=volume_type)
volume_create_args = {
'containing-aggr-name': fake_client.VOLUME_AGGREGATE_NAME,
'size': '100g',
'volume': fake_client.VOLUME_NAME,
'space-reserve': 'volume',
'language-code': 'en-US',
'volume-type': volume_type,
'percentage-snapshot-reserve': '15',
}
if volume_type != 'dp':
volume_create_args['snapshot-policy'] = 'default'
volume_create_args['junction-path'] = ('/%s' %
fake_client.VOLUME_NAME)
self.client.connection.send_request.assert_called_with(
'volume-create', volume_create_args)
self.client.enable_flexvol_dedupe.assert_called_once_with(
fake_client.VOLUME_NAME)
self.client.enable_flexvol_compression.assert_called_once_with(
fake_client.VOLUME_NAME)
def test_create_volume_async(self):
self.mock_object(self.client.connection, 'send_request')
self.client.create_volume_async(
fake_client.VOLUME_NAME, [fake_client.VOLUME_AGGREGATE_NAME], 100,
volume_type='dp')
volume_create_args = {
'aggr-list': [{'aggr-name': fake_client.VOLUME_AGGREGATE_NAME}],
'size': 100 * units.Gi,
'volume-name': fake_client.VOLUME_NAME,
'volume-type': 'dp'
}
self.client.connection.send_request.assert_called_once_with(
'volume-create-async', volume_create_args)
@ddt.data('dp', 'rw', None)
def test_create_volume_async_with_extra_specs(self, volume_type):
self.mock_object(self.client.connection, 'send_request')
self.client.create_volume_async(
fake_client.VOLUME_NAME, [fake_client.VOLUME_AGGREGATE_NAME], 100,
space_guarantee_type='volume', language='en-US',
snapshot_policy='default', snapshot_reserve=15,
volume_type=volume_type)
volume_create_args = {
'aggr-list': [{'aggr-name': fake_client.VOLUME_AGGREGATE_NAME}],
'size': 100 * units.Gi,
'volume-name': fake_client.VOLUME_NAME,
'space-reserve': 'volume',
'language-code': 'en-US',
'volume-type': volume_type,
'percentage-snapshot-reserve': '15',
}
if volume_type != 'dp':
volume_create_args['snapshot-policy'] = 'default'
volume_create_args['junction-path'] = ('/%s' %
fake_client.VOLUME_NAME)
self.client.connection.send_request.assert_called_with(
'volume-create-async', volume_create_args)
def test_flexvol_exists(self):
api_response = netapp_api.NaElement(
fake_client.VOLUME_GET_NAME_RESPONSE)
self.mock_object(self.client,
'send_iter_request',
return_value=api_response)
result = self.client.flexvol_exists(fake_client.VOLUME_NAME)
volume_get_iter_args = {
'query': {
'volume-attributes': {
'volume-id-attributes': {
'name': fake_client.VOLUME_NAME
}
}
},
'desired-attributes': {
'volume-attributes': {
'volume-id-attributes': {
'name': None
}
}
}
}
self.client.send_iter_request.assert_has_calls([
mock.call('volume-get-iter', volume_get_iter_args)])
self.assertTrue(result)
def test_flexvol_exists_not_found(self):
api_response = netapp_api.NaElement(fake_client.NO_RECORDS_RESPONSE)
self.mock_object(self.client.connection,
'send_request',
return_value=api_response)
self.assertFalse(self.client.flexvol_exists(fake_client.VOLUME_NAME))
def test_rename_flexvol(self):
self.mock_object(self.client.connection, 'send_request')
self.client.rename_flexvol(fake_client.VOLUME_NAME, 'new_name')
volume_rename_api_args = {
'volume': fake_client.VOLUME_NAME,
'new-volume-name': 'new_name',
}
self.client.connection.send_request.assert_called_once_with(
'volume-rename', volume_rename_api_args)
def test_mount_flexvol_default_junction_path(self):
self.mock_object(self.client.connection, 'send_request')
self.client.mount_flexvol(fake_client.VOLUME_NAME)
volume_mount_args = {
'volume-name': fake_client.VOLUME_NAME,
'junction-path': '/%s' % fake_client.VOLUME_NAME,
}
self.client.connection.send_request.assert_has_calls([
mock.call('volume-mount', volume_mount_args)])
def test_mount_flexvol(self):
self.mock_object(self.client.connection, 'send_request')
fake_path = '/fake_path'
self.client.mount_flexvol(fake_client.VOLUME_NAME,
junction_path=fake_path)
volume_mount_args = {
'volume-name': fake_client.VOLUME_NAME,
'junction-path': fake_path,
}
self.client.connection.send_request.assert_has_calls([
mock.call('volume-mount', volume_mount_args)])
def test_enable_volume_dedupe_async(self):
self.mock_object(self.client.connection, 'send_request')
self.client.enable_volume_dedupe_async(fake_client.VOLUME_NAME)
sis_enable_args = {'volume-name': fake_client.VOLUME_NAME}
self.client.connection.send_request.assert_called_once_with(
'sis-enable-async', sis_enable_args)
def test_disable_volume_dedupe_async(self):
self.mock_object(self.client.connection, 'send_request')
self.client.disable_volume_dedupe_async(fake_client.VOLUME_NAME)
sis_enable_args = {'volume-name': fake_client.VOLUME_NAME}
self.client.connection.send_request.assert_called_once_with(
'sis-disable-async', sis_enable_args)
def test_enable_volume_compression_async(self):
self.mock_object(self.client.connection, 'send_request')
self.client.enable_volume_compression_async(fake_client.VOLUME_NAME)
sis_set_config_args = {
'volume-name': fake_client.VOLUME_NAME,
'enable-compression': 'true'
}
self.client.connection.send_request.assert_called_once_with(
'sis-set-config-async', sis_set_config_args)
def test_disable_volume_compression_async(self):
self.mock_object(self.client.connection, 'send_request')
self.client.disable_volume_compression_async(fake_client.VOLUME_NAME)
sis_set_config_args = {
'volume-name': fake_client.VOLUME_NAME,
'enable-compression': 'false'
}
self.client.connection.send_request.assert_called_once_with(
'sis-set-config-async', sis_set_config_args)
def test_enable_flexvol_dedupe(self):
self.mock_object(self.client.connection, 'send_request')
self.client.enable_flexvol_dedupe(fake_client.VOLUME_NAME)
sis_enable_args = {'path': '/vol/%s' % fake_client.VOLUME_NAME}
self.client.connection.send_request.assert_called_once_with(
'sis-enable', sis_enable_args)
def test_disable_flexvol_dedupe(self):
self.mock_object(self.client.connection, 'send_request')
self.client.disable_flexvol_dedupe(fake_client.VOLUME_NAME)
sis_disable_args = {'path': '/vol/%s' % fake_client.VOLUME_NAME}
self.client.connection.send_request.assert_called_once_with(
'sis-disable', sis_disable_args)
def test_enable_flexvol_compression(self):
self.mock_object(self.client.connection, 'send_request')
self.client.enable_flexvol_compression(fake_client.VOLUME_NAME)
sis_set_config_args = {
'path': '/vol/%s' % fake_client.VOLUME_NAME,
'enable-compression': 'true'
}
self.client.connection.send_request.assert_called_once_with(
'sis-set-config', sis_set_config_args)
def test_disable_flexvol_compression(self):
self.mock_object(self.client.connection, 'send_request')
self.client.disable_flexvol_compression(fake_client.VOLUME_NAME)
sis_set_config_args = {
'path': '/vol/%s' % fake_client.VOLUME_NAME,
'enable-compression': 'false'
}
self.client.connection.send_request.assert_called_once_with(
'sis-set-config', sis_set_config_args)
def test_get_flexvol_dedupe_info(self):
api_response = netapp_api.NaElement(
fake_client.SIS_GET_ITER_SSC_RESPONSE)
self.mock_object(self.client,
'send_iter_request',
return_value=api_response)
result = self.client.get_flexvol_dedupe_info(
fake_client.VOLUME_NAMES[0])
sis_get_iter_args = {
'query': {
'sis-status-info': {
'path': '/vol/%s' % fake_client.VOLUME_NAMES[0],
},
},
'desired-attributes': {
'sis-status-info': {
'state': None,
'is-compression-enabled': None,
'logical-data-size': None,
'logical-data-limit': None,
},
},
}
self.client.send_iter_request.assert_called_once_with(
'sis-get-iter', sis_get_iter_args)
self.assertEqual(fake_client.VOLUME_DEDUPE_INFO_SSC, result)
def test_get_flexvol_dedupe_info_no_logical_data_values(self):
api_response = netapp_api.NaElement(
fake_client.SIS_GET_ITER_SSC_NO_LOGICAL_DATA_RESPONSE)
self.mock_object(self.client,
'send_iter_request',
return_value=api_response)
result = self.client.get_flexvol_dedupe_info(
fake_client.VOLUME_NAMES[0])
self.assertEqual(fake_client.VOLUME_DEDUPE_INFO_SSC_NO_LOGICAL_DATA,
result)
def test_get_flexvol_dedupe_info_not_found(self):
api_response = netapp_api.NaElement(
fake_client.NO_RECORDS_RESPONSE)
self.mock_object(self.client,
'send_iter_request',
return_value=api_response)
result = self.client.get_flexvol_dedupe_info(
fake_client.VOLUME_NAMES[0])
self.assertEqual(fake_client.VOLUME_DEDUPE_INFO_SSC_NO_LOGICAL_DATA,
result)
def test_get_flexvol_dedupe_info_api_error(self):
self.mock_object(self.client,
'send_iter_request',
side_effect=self._mock_api_error())
result = self.client.get_flexvol_dedupe_info(
fake_client.VOLUME_NAMES[0])
self.assertEqual(fake_client.VOLUME_DEDUPE_INFO_SSC_NO_LOGICAL_DATA,
result)
def test_get_flexvol_dedupe_info_api_insufficient_privileges(self):
api_error = netapp_api.NaApiError(code=netapp_api.EAPIPRIVILEGE)
self.mock_object(self.client,
'send_iter_request',
side_effect=api_error)
result = self.client.get_flexvol_dedupe_info(
fake_client.VOLUME_NAMES[0])
self.assertEqual(fake_client.VOLUME_DEDUPE_INFO_SSC_NO_LOGICAL_DATA,
result)
def test_get_flexvol_dedupe_used_percent(self):
self.client.features.add_feature('CLONE_SPLIT_STATUS')
mock_get_flexvol_dedupe_info = self.mock_object(
self.client, 'get_flexvol_dedupe_info',
return_value=fake_client.VOLUME_DEDUPE_INFO_SSC)
mock_get_clone_split_info = self.mock_object(
self.client, 'get_clone_split_info',
return_value=fake_client.VOLUME_CLONE_SPLIT_STATUS)
result = self.client.get_flexvol_dedupe_used_percent(
fake_client.VOLUME_NAMES[0])
self.assertEqual(75.0, result)
mock_get_flexvol_dedupe_info.assert_called_once_with(
fake_client.VOLUME_NAMES[0])
mock_get_clone_split_info.assert_called_once_with(
fake_client.VOLUME_NAMES[0])
def test_get_flexvol_dedupe_used_percent_not_supported(self):
self.client.features.add_feature('CLONE_SPLIT_STATUS', supported=False)
mock_get_flexvol_dedupe_info = self.mock_object(
self.client, 'get_flexvol_dedupe_info',
return_value=fake_client.VOLUME_DEDUPE_INFO_SSC)
mock_get_clone_split_info = self.mock_object(
self.client, 'get_clone_split_info',
return_value=fake_client.VOLUME_CLONE_SPLIT_STATUS)
result = self.client.get_flexvol_dedupe_used_percent(
fake_client.VOLUME_NAMES[0])
self.assertEqual(0.0, result)
self.assertFalse(mock_get_flexvol_dedupe_info.called)
self.assertFalse(mock_get_clone_split_info.called)
def test_get_clone_split_info(self):
api_response = netapp_api.NaElement(
fake_client.CLONE_SPLIT_STATUS_RESPONSE)
self.mock_object(self.client.connection,
'send_request',
return_value=api_response)
result = self.client.get_clone_split_info(fake_client.VOLUME_NAMES[0])
self.assertEqual(fake_client.VOLUME_CLONE_SPLIT_STATUS, result)
self.client.connection.send_request.assert_called_once_with(
'clone-split-status', {'volume-name': fake_client.VOLUME_NAMES[0]})
def test_get_clone_split_info_api_error(self):
self.mock_object(self.client.connection,
'send_request',
side_effect=self._mock_api_error())
result = self.client.get_clone_split_info(fake_client.VOLUME_NAMES[0])
expected = {'unsplit-size': 0, 'unsplit-clone-count': 0}
self.assertEqual(expected, result)
def test_get_clone_split_info_no_data(self):
api_response = netapp_api.NaElement(
fake_client.CLONE_SPLIT_STATUS_NO_DATA_RESPONSE)
self.mock_object(self.client.connection,
'send_request',
return_value=api_response)
result = self.client.get_clone_split_info(fake_client.VOLUME_NAMES[0])
expected = {'unsplit-size': 0, 'unsplit-clone-count': 0}
self.assertEqual(expected, result)
def test_is_flexvol_mirrored(self):
api_response = netapp_api.NaElement(
fake_client.SNAPMIRROR_GET_ITER_RESPONSE)
self.mock_object(self.client,
'send_iter_request',
return_value=api_response)
result = self.client.is_flexvol_mirrored(
fake_client.VOLUME_NAMES[0], fake_client.VOLUME_VSERVER_NAME)
snapmirror_get_iter_args = {
'query': {
'snapmirror-info': {
'source-vserver': fake_client.VOLUME_VSERVER_NAME,
'source-volume': fake_client.VOLUME_NAMES[0],
'mirror-state': 'snapmirrored',
'relationship-type': 'data_protection',
},
},
'desired-attributes': {
'snapmirror-info': None,
},
}
self.client.send_iter_request.assert_called_once_with(
'snapmirror-get-iter', snapmirror_get_iter_args)
self.assertTrue(result)
def test_is_flexvol_mirrored_not_mirrored(self):
api_response = netapp_api.NaElement(
fake_client.NO_RECORDS_RESPONSE)
self.mock_object(self.client.connection,
'send_request',
return_value=api_response)
result = self.client.is_flexvol_mirrored(
fake_client.VOLUME_NAMES[0], fake_client.VOLUME_VSERVER_NAME)
self.assertFalse(result)
def test_is_flexvol_mirrored_api_error(self):
self.mock_object(self.client.connection,
'send_request',
side_effect=self._mock_api_error())
result = self.client.is_flexvol_mirrored(
fake_client.VOLUME_NAMES[0], fake_client.VOLUME_VSERVER_NAME)
self.assertFalse(result)
def test_is_flexvol_encrypted(self):
api_response = netapp_api.NaElement(
fake_client.VOLUME_GET_ITER_ENCRYPTION_SSC_RESPONSE)
self.client.features.add_feature('FLEXVOL_ENCRYPTION')
self.mock_object(self.client,
'send_iter_request',
return_value=api_response)
result = self.client.is_flexvol_encrypted(
fake_client.VOLUME_NAMES[0], fake_client.VOLUME_VSERVER_NAME)
volume_get_iter_args = {
'query': {
'volume-attributes': {
'encrypt': 'true',
'volume-id-attributes': {
'name': fake_client.VOLUME_NAME,
'owning-vserver-name': fake_client.VOLUME_VSERVER_NAME,
}
}
},
'desired-attributes': {
'volume-attributes': {
'encrypt': None,
}
}
}
self.client.send_iter_request.assert_called_once_with(
'volume-get-iter', volume_get_iter_args)
self.assertTrue(result)
def test_is_flexvol_encrypted_unsupported_version(self):
self.client.features.add_feature('FLEXVOL_ENCRYPTION', supported=False)
result = self.client.is_flexvol_encrypted(
fake_client.VOLUME_NAMES[0], fake_client.VOLUME_VSERVER_NAME)
self.assertFalse(result)
def test_is_flexvol_encrypted_no_records_found(self):
api_response = netapp_api.NaElement(
fake_client.NO_RECORDS_RESPONSE)
self.mock_object(self.client.connection,
'send_request',
return_value=api_response)
result = self.client.is_flexvol_encrypted(
fake_client.VOLUME_NAMES[0], fake_client.VOLUME_VSERVER_NAME)
self.assertFalse(result)
def test_is_flexvol_encrypted_api_error(self):
self.mock_object(self.client.connection,
'send_request',
side_effect=self._mock_api_error())
result = self.client.is_flexvol_encrypted(
fake_client.VOLUME_NAMES[0], fake_client.VOLUME_VSERVER_NAME)
self.assertFalse(result)
def test_get_aggregates(self):
api_response = netapp_api.NaElement(
fake_client.AGGR_GET_ITER_RESPONSE)
self.mock_object(self.client.connection,
'send_request',
return_value=api_response)
result = self.client._get_aggregates()
self.client.connection.send_request.assert_has_calls([
mock.call('aggr-get-iter', {}, enable_tunneling=False)])
self.assertListEqual(
[aggr.to_string() for aggr in api_response.get_child_by_name(
'attributes-list').get_children()],
[aggr.to_string() for aggr in result])
def test_get_aggregates_with_filters(self):
api_response = netapp_api.NaElement(
fake_client.AGGR_GET_SPACE_RESPONSE)
self.mock_object(self.client.connection,
'send_request',
return_value=api_response)
desired_attributes = {
'aggr-attributes': {
'aggregate-name': None,
'aggr-space-attributes': {
'size-total': None,
'size-available': None,
}
}
}
result = self.client._get_aggregates(
aggregate_names=fake_client.VOLUME_AGGREGATE_NAMES,
desired_attributes=desired_attributes)
aggr_get_iter_args = {
'query': {
'aggr-attributes': {
'aggregate-name': '|'.join(
fake_client.VOLUME_AGGREGATE_NAMES),
}
},
'desired-attributes': desired_attributes
}
self.client.connection.send_request.assert_has_calls([
mock.call('aggr-get-iter', aggr_get_iter_args,
enable_tunneling=False)])
self.assertListEqual(
[aggr.to_string() for aggr in api_response.get_child_by_name(
'attributes-list').get_children()],
[aggr.to_string() for aggr in result])
def test_get_aggregates_not_found(self):
api_response = netapp_api.NaElement(fake_client.NO_RECORDS_RESPONSE)
self.mock_object(self.client.connection,
'send_request',
return_value=api_response)
result = self.client._get_aggregates()
self.client.connection.send_request.assert_has_calls([
mock.call('aggr-get-iter', {}, enable_tunneling=False)])
self.assertListEqual([], result)
def test_get_node_for_aggregate(self):
api_response = netapp_api.NaElement(
fake_client.AGGR_GET_NODE_RESPONSE).get_child_by_name(
'attributes-list').get_children()
self.mock_object(self.client,
'_get_aggregates',
return_value=api_response)
result = self.client.get_node_for_aggregate(
fake_client.VOLUME_AGGREGATE_NAME)
desired_attributes = {
'aggr-attributes': {
'aggregate-name': None,
'aggr-ownership-attributes': {
'home-name': None,
},
},
}
self.client._get_aggregates.assert_has_calls([
mock.call(
aggregate_names=[fake_client.VOLUME_AGGREGATE_NAME],
desired_attributes=desired_attributes)])
self.assertEqual(fake_client.NODE_NAME, result)
def test_get_node_for_aggregate_none_requested(self):
result = self.client.get_node_for_aggregate(None)
self.assertIsNone(result)
def test_get_node_for_aggregate_api_not_found(self):
api_error = self._mock_api_error(netapp_api.EAPINOTFOUND)
self.mock_object(self.client.connection,
'send_request',
side_effect=api_error)
result = self.client.get_node_for_aggregate(
fake_client.VOLUME_AGGREGATE_NAME)
self.assertIsNone(result)
def test_get_node_for_aggregate_api_error(self):
self.mock_object(self.client.connection,
'send_request',
self._mock_api_error())
self.assertRaises(netapp_api.NaApiError,
self.client.get_node_for_aggregate,
fake_client.VOLUME_AGGREGATE_NAME)
def test_get_node_for_aggregate_not_found(self):
api_response = netapp_api.NaElement(fake_client.NO_RECORDS_RESPONSE)
self.mock_object(self.client.connection,
'send_request',
return_value=api_response)
result = self.client.get_node_for_aggregate(
fake_client.VOLUME_AGGREGATE_NAME)
self.assertIsNone(result)
def test_get_aggregate_none_specified(self):
result = self.client.get_aggregate('')
self.assertEqual({}, result)
def test_get_aggregate(self):
api_response = netapp_api.NaElement(
fake_client.AGGR_GET_ITER_SSC_RESPONSE).get_child_by_name(
'attributes-list').get_children()
self.mock_object(self.client,
'_get_aggregates',
return_value=api_response)
result = self.client.get_aggregate(fake_client.VOLUME_AGGREGATE_NAME)
desired_attributes = {
'aggr-attributes': {
'aggregate-name': None,
'aggr-raid-attributes': {
'raid-type': None,
'is-hybrid': None,
},
'aggr-ownership-attributes': {
'home-name': None,
},
},
}
self.client._get_aggregates.assert_has_calls([
mock.call(
aggregate_names=[fake_client.VOLUME_AGGREGATE_NAME],
desired_attributes=desired_attributes)])
expected = {
'name': fake_client.VOLUME_AGGREGATE_NAME,
'raid-type': 'raid_dp',
'is-hybrid': True,
'node-name': fake_client.NODE_NAME,
}
self.assertEqual(expected, result)
def test_get_aggregate_not_found(self):
api_response = netapp_api.NaElement(fake_client.NO_RECORDS_RESPONSE)
self.mock_object(self.client.connection,
'send_request',
return_value=api_response)
result = self.client.get_aggregate(fake_client.VOLUME_AGGREGATE_NAME)
self.assertEqual({}, result)
def test_get_aggregate_api_error(self):
self.mock_object(self.client.connection,
'send_request',
side_effect=self._mock_api_error())
result = self.client.get_aggregate(fake_client.VOLUME_AGGREGATE_NAME)
self.assertEqual({}, result)
def test_get_aggregate_api_not_found(self):
api_error = netapp_api.NaApiError(code=netapp_api.EAPINOTFOUND)
self.mock_object(self.client.connection,
'send_iter_request',
side_effect=api_error)
result = self.client.get_aggregate(fake_client.VOLUME_AGGREGATE_NAME)
self.assertEqual({}, result)
@ddt.data({'types': {'FCAL'}, 'expected': ['FCAL']},
{'types': {'SATA', 'SSD'}, 'expected': ['SATA', 'SSD']},)
@ddt.unpack
def test_get_aggregate_disk_types(self, types, expected):
mock_get_aggregate_disk_types = self.mock_object(
self.client, '_get_aggregate_disk_types', return_value=types)
result = self.client.get_aggregate_disk_types(
fake_client.VOLUME_AGGREGATE_NAME)
self.assertCountEqual(expected, result)
mock_get_aggregate_disk_types.assert_called_once_with(
fake_client.VOLUME_AGGREGATE_NAME)
def test_get_aggregate_disk_types_not_found(self):
mock_get_aggregate_disk_types = self.mock_object(
self.client, '_get_aggregate_disk_types', return_value=set())
result = self.client.get_aggregate_disk_types(
fake_client.VOLUME_AGGREGATE_NAME)
self.assertIsNone(result)
mock_get_aggregate_disk_types.assert_called_once_with(
fake_client.VOLUME_AGGREGATE_NAME)
def test_get_aggregate_disk_types_api_not_found(self):
api_error = netapp_api.NaApiError(code=netapp_api.EAPINOTFOUND)
self.mock_object(self.client,
'send_iter_request',
side_effect=api_error)
result = self.client.get_aggregate_disk_types(
fake_client.VOLUME_AGGREGATE_NAME)
self.assertIsNone(result)
def test_get_aggregate_disk_types_shared(self):
self.client.features.add_feature('ADVANCED_DISK_PARTITIONING')
mock_get_aggregate_disk_types = self.mock_object(
self.client, '_get_aggregate_disk_types',
side_effect=[set(['SSD']), set(['SATA'])])
result = self.client.get_aggregate_disk_types(
fake_client.VOLUME_AGGREGATE_NAME)
self.assertIsInstance(result, list)
self.assertCountEqual(['SATA', 'SSD'], result)
mock_get_aggregate_disk_types.assert_has_calls([
mock.call(fake_client.VOLUME_AGGREGATE_NAME),
mock.call(fake_client.VOLUME_AGGREGATE_NAME, shared=True),
])
def test__get_aggregate_disk_types(self):
api_response = netapp_api.NaElement(
fake_client.STORAGE_DISK_GET_ITER_RESPONSE)
self.mock_object(self.client,
'send_iter_request',
return_value=api_response)
result = self.client._get_aggregate_disk_types(
fake_client.VOLUME_AGGREGATE_NAME)
storage_disk_get_iter_args = {
'query': {
'storage-disk-info': {
'disk-raid-info': {
'disk-aggregate-info': {
'aggregate-name':
fake_client.VOLUME_AGGREGATE_NAME,
},
},
},
},
'desired-attributes': {
'storage-disk-info': {
'disk-raid-info': {
'effective-disk-type': None,
},
},
},
}
self.client.send_iter_request.assert_called_once_with(
'storage-disk-get-iter', storage_disk_get_iter_args,
enable_tunneling=False)
expected = set(fake_client.AGGREGATE_DISK_TYPES)
self.assertEqual(expected, result)
def test__get_aggregate_disk_types_shared(self):
api_response = netapp_api.NaElement(
fake_client.STORAGE_DISK_GET_ITER_RESPONSE)
self.mock_object(self.client,
'send_iter_request',
return_value=api_response)
result = self.client._get_aggregate_disk_types(
fake_client.VOLUME_AGGREGATE_NAME, shared=True)
storage_disk_get_iter_args = {
'query': {
'storage-disk-info': {
'disk-raid-info': {
'disk-shared-info': {
'aggregate-list': {
'shared-aggregate-info': {
'aggregate-name':
fake_client.VOLUME_AGGREGATE_NAME,
},
},
},
},
},
},
'desired-attributes': {
'storage-disk-info': {
'disk-raid-info': {
'effective-disk-type': None,
},
},
},
}
self.client.send_iter_request.assert_called_once_with(
'storage-disk-get-iter', storage_disk_get_iter_args,
enable_tunneling=False)
expected = set(fake_client.AGGREGATE_DISK_TYPES)
self.assertEqual(expected, result)
def test__get_aggregate_disk_types_not_found(self):
api_response = netapp_api.NaElement(fake_client.NO_RECORDS_RESPONSE)
self.mock_object(self.client,
'send_iter_request',
return_value=api_response)
result = self.client._get_aggregate_disk_types(
fake_client.VOLUME_AGGREGATE_NAME)
self.assertEqual(set(), result)
def test__get_aggregate_disk_types_api_error(self):
self.mock_object(self.client,
'send_iter_request',
side_effect=self._mock_api_error())
result = self.client._get_aggregate_disk_types(
fake_client.VOLUME_AGGREGATE_NAME)
self.assertEqual(set([]), result)
def test_get_aggregate_capacities(self):
aggr1_capacities = {
'percent-used': 50,
'size-available': 100.0,
'size-total': 200.0,
}
aggr2_capacities = {
'percent-used': 75,
'size-available': 125.0,
'size-total': 500.0,
}
mock_get_aggregate_capacity = self.mock_object(
self.client, 'get_aggregate_capacity',
side_effect=[aggr1_capacities, aggr2_capacities])
result = self.client.get_aggregate_capacities(['aggr1', 'aggr2'])
expected = {
'aggr1': aggr1_capacities,
'aggr2': aggr2_capacities,
}
self.assertEqual(expected, result)
mock_get_aggregate_capacity.assert_has_calls([
mock.call('aggr1'),
mock.call('aggr2'),
])
def test_get_aggregate_capacities_not_found(self):
mock_get_aggregate_capacity = self.mock_object(
self.client, 'get_aggregate_capacity', side_effect=[{}, {}])
result = self.client.get_aggregate_capacities(['aggr1', 'aggr2'])
expected = {
'aggr1': {},
'aggr2': {},
}
self.assertEqual(expected, result)
mock_get_aggregate_capacity.assert_has_calls([
mock.call('aggr1'),
mock.call('aggr2'),
])
def test_get_aggregate_capacities_not_list(self):
result = self.client.get_aggregate_capacities('aggr1')
self.assertEqual({}, result)
def test_get_aggregate_capacity(self):
api_response = netapp_api.NaElement(
fake_client.AGGR_GET_ITER_CAPACITY_RESPONSE).get_child_by_name(
'attributes-list').get_children()
self.mock_object(self.client,
'_get_aggregates',
return_value=api_response)
result = self.client.get_aggregate_capacity(
fake_client.VOLUME_AGGREGATE_NAME)
desired_attributes = {
'aggr-attributes': {
'aggr-space-attributes': {
'percent-used-capacity': None,
'size-available': None,
'size-total': None,
},
},
}
self.client._get_aggregates.assert_has_calls([
mock.call(
aggregate_names=[fake_client.VOLUME_AGGREGATE_NAME],
desired_attributes=desired_attributes)])
expected = {
'percent-used': float(fake_client.AGGR_USED_PERCENT),
'size-available': float(fake_client.AGGR_SIZE_AVAILABLE),
'size-total': float(fake_client.AGGR_SIZE_TOTAL),
}
self.assertEqual(expected, result)
def test_get_aggregate_capacity_not_found(self):
api_response = netapp_api.NaElement(fake_client.NO_RECORDS_RESPONSE)
self.mock_object(self.client.connection,
'send_request',
return_value=api_response)
result = self.client.get_aggregate_capacity(
fake_client.VOLUME_AGGREGATE_NAME)
self.assertEqual({}, result)
def test_get_aggregate_capacity_api_error(self):
self.mock_object(self.client.connection,
'send_request',
side_effect=self._mock_api_error())
result = self.client.get_aggregate_capacity(
fake_client.VOLUME_AGGREGATE_NAME)
self.assertEqual({}, result)
def test_get_aggregate_capacity_api_not_found(self):
api_error = netapp_api.NaApiError(code=netapp_api.EAPINOTFOUND)
self.mock_object(
self.client.connection, 'send_request', side_effect=api_error)
result = self.client.get_aggregate_capacity(
fake_client.VOLUME_AGGREGATE_NAME)
self.assertEqual({}, result)
def test_get_performance_instance_uuids(self):
self.mock_send_request.return_value = netapp_api.NaElement(
fake_client.PERF_OBJECT_INSTANCE_LIST_INFO_ITER_RESPONSE)
result = self.client.get_performance_instance_uuids(
'system', fake_client.NODE_NAME)
expected = [fake_client.NODE_NAME + ':kernel:system']
self.assertEqual(expected, result)
perf_object_instance_list_info_iter_args = {
'objectname': 'system',
'query': {
'instance-info': {
'uuid': fake_client.NODE_NAME + ':*',
}
}
}
self.mock_send_request.assert_called_once_with(
'perf-object-instance-list-info-iter',
perf_object_instance_list_info_iter_args, enable_tunneling=False)
def test_get_performance_counters(self):
self.mock_send_request.return_value = netapp_api.NaElement(
fake_client.PERF_OBJECT_GET_INSTANCES_SYSTEM_RESPONSE_CMODE)
instance_uuids = [
fake_client.NODE_NAMES[0] + ':kernel:system',
fake_client.NODE_NAMES[1] + ':kernel:system',
]
counter_names = ['avg_processor_busy']
result = self.client.get_performance_counters('system',
instance_uuids,
counter_names)
expected = [
{
'avg_processor_busy': '5674745133134',
'instance-name': 'system',
'instance-uuid': instance_uuids[0],
'node-name': fake_client.NODE_NAMES[0],
'timestamp': '1453412013',
}, {
'avg_processor_busy': '4077649009234',
'instance-name': 'system',
'instance-uuid': instance_uuids[1],
'node-name': fake_client.NODE_NAMES[1],
'timestamp': '1453412013'
},
]
self.assertEqual(expected, result)
perf_object_get_instances_args = {
'objectname': 'system',
'instance-uuids': [
{'instance-uuid': instance_uuid}
for instance_uuid in instance_uuids
],
'counters': [
{'counter': counter} for counter in counter_names
],
}
self.mock_send_request.assert_called_once_with(
'perf-object-get-instances', perf_object_get_instances_args,
enable_tunneling=False)
def test_check_iscsi_initiator_exists_when_no_initiator_exists(self):
self.connection.invoke_successfully = mock.Mock(
side_effect=netapp_api.NaApiError)
initiator = fake_client.INITIATOR_IQN
initiator_exists = self.client.check_iscsi_initiator_exists(initiator)
self.assertFalse(initiator_exists)
def test_check_iscsi_initiator_exists_when_initiator_exists(self):
self.connection.invoke_successfully = mock.Mock()
initiator = fake_client.INITIATOR_IQN
initiator_exists = self.client.check_iscsi_initiator_exists(initiator)
self.assertTrue(initiator_exists)
def test_set_iscsi_chap_authentication_no_previous_initiator(self):
self.connection.invoke_successfully = mock.Mock()
self.mock_object(self.client, 'check_iscsi_initiator_exists',
return_value=False)
ssh = mock.Mock(paramiko.SSHClient)
sshpool = mock.Mock(ssh_utils.SSHPool)
self.client.ssh_client.ssh_pool = sshpool
self.mock_object(self.client.ssh_client, 'execute_command_with_prompt')
sshpool.item().__enter__ = mock.Mock(return_value=ssh)
sshpool.item().__exit__ = mock.Mock(return_value=False)
self.client.set_iscsi_chap_authentication(fake_client.INITIATOR_IQN,
fake_client.USER_NAME,
fake_client.PASSWORD)
command = ('iscsi security create -vserver fake_vserver '
'-initiator-name iqn.2015-06.com.netapp:fake_iqn '
'-auth-type CHAP -user-name fake_user')
self.client.ssh_client.execute_command_with_prompt.assert_has_calls(
[mock.call(ssh, command, 'Password:', fake_client.PASSWORD)]
)
def test_set_iscsi_chap_authentication_with_preexisting_initiator(self):
self.connection.invoke_successfully = mock.Mock()
self.mock_object(self.client, 'check_iscsi_initiator_exists',
return_value=True)
ssh = mock.Mock(paramiko.SSHClient)
sshpool = mock.Mock(ssh_utils.SSHPool)
self.client.ssh_client.ssh_pool = sshpool
self.mock_object(self.client.ssh_client, 'execute_command_with_prompt')
sshpool.item().__enter__ = mock.Mock(return_value=ssh)
sshpool.item().__exit__ = mock.Mock(return_value=False)
self.client.set_iscsi_chap_authentication(fake_client.INITIATOR_IQN,
fake_client.USER_NAME,
fake_client.PASSWORD)
command = ('iscsi security modify -vserver fake_vserver '
'-initiator-name iqn.2015-06.com.netapp:fake_iqn '
'-auth-type CHAP -user-name fake_user')
self.client.ssh_client.execute_command_with_prompt.assert_has_calls(
[mock.call(ssh, command, 'Password:', fake_client.PASSWORD)]
)
def test_set_iscsi_chap_authentication_with_ssh_exception(self):
self.connection.invoke_successfully = mock.Mock()
self.mock_object(self.client, 'check_iscsi_initiator_exists',
return_value=True)
ssh = mock.Mock(paramiko.SSHClient)
sshpool = mock.Mock(ssh_utils.SSHPool)
self.client.ssh_client.ssh_pool = sshpool
sshpool.item().__enter__ = mock.Mock(return_value=ssh)
sshpool.item().__enter__.side_effect = paramiko.SSHException(
'Connection Failure')
sshpool.item().__exit__ = mock.Mock(return_value=False)
self.assertRaises(exception.VolumeBackendAPIException,
self.client.set_iscsi_chap_authentication,
fake_client.INITIATOR_IQN,
fake_client.USER_NAME,
fake_client.PASSWORD)
def test_get_snapshot_if_snapshot_present_not_busy(self):
expected_vol_name = fake.SNAPSHOT['volume_id']
expected_snapshot_name = fake.SNAPSHOT['name']
response = netapp_api.NaElement(
fake_client.SNAPSHOT_INFO_FOR_PRESENT_NOT_BUSY_SNAPSHOT_CMODE)
self.mock_send_request.return_value = response
snapshot = self.client.get_snapshot(expected_vol_name,
expected_snapshot_name)
self.assertEqual(expected_vol_name, snapshot['volume'])
self.assertEqual(expected_snapshot_name, snapshot['name'])
self.assertEqual(set([]), snapshot['owners'])
self.assertFalse(snapshot['busy'])
def test_get_snapshot_if_snapshot_present_busy(self):
expected_vol_name = fake.SNAPSHOT['volume_id']
expected_snapshot_name = fake.SNAPSHOT['name']
response = netapp_api.NaElement(
fake_client.SNAPSHOT_INFO_FOR_PRESENT_BUSY_SNAPSHOT_CMODE)
self.mock_send_request.return_value = response
snapshot = self.client.get_snapshot(expected_vol_name,
expected_snapshot_name)
self.assertEqual(expected_vol_name, snapshot['volume'])
self.assertEqual(expected_snapshot_name, snapshot['name'])
self.assertEqual(set([]), snapshot['owners'])
self.assertTrue(snapshot['busy'])
def test_get_snapshot_if_snapshot_not_present(self):
expected_vol_name = fake.SNAPSHOT['volume_id']
expected_snapshot_name = fake.SNAPSHOT['name']
response = netapp_api.NaElement(fake_client.NO_RECORDS_RESPONSE)
self.mock_send_request.return_value = response
self.assertRaises(exception.SnapshotNotFound, self.client.get_snapshot,
expected_vol_name, expected_snapshot_name)
def test_create_cluster_peer(self):
self.mock_object(self.client.connection, 'send_request')
self.client.create_cluster_peer(['fake_address_1', 'fake_address_2'],
'fake_user', 'fake_password',
'fake_passphrase')
cluster_peer_create_args = {
'peer-addresses': [
{'remote-inet-address': 'fake_address_1'},
{'remote-inet-address': 'fake_address_2'},
],
'user-name': 'fake_user',
'password': '<PASSWORD>',
'passphrase': '<PASSWORD>',
}
self.client.connection.send_request.assert_has_calls([
mock.call('cluster-peer-create', cluster_peer_create_args)])
def test_get_cluster_peers(self):
api_response = netapp_api.NaElement(
fake_client.CLUSTER_PEER_GET_ITER_RESPONSE)
self.mock_object(self.client,
'send_iter_request',
return_value=api_response)
result = self.client.get_cluster_peers()
cluster_peer_get_iter_args = {}
self.client.send_iter_request.assert_has_calls([
mock.call('cluster-peer-get-iter', cluster_peer_get_iter_args)])
expected = [{
'active-addresses': [
fake_client.CLUSTER_ADDRESS_1,
fake_client.CLUSTER_ADDRESS_2
],
'availability': 'available',
'cluster-name': fake_client.CLUSTER_NAME,
'cluster-uuid': 'fake_uuid',
'peer-addresses': [fake_client.CLUSTER_ADDRESS_1],
'remote-cluster-name': fake_client.REMOTE_CLUSTER_NAME,
'serial-number': 'fake_serial_number',
'timeout': '60',
}]
self.assertEqual(expected, result)
def test_get_cluster_peers_single(self):
api_response = netapp_api.NaElement(
fake_client.CLUSTER_PEER_GET_ITER_RESPONSE)
self.mock_object(self.client,
'send_iter_request',
return_value=api_response)
self.client.get_cluster_peers(
remote_cluster_name=fake_client.CLUSTER_NAME)
cluster_peer_get_iter_args = {
'query': {
'cluster-peer-info': {
'remote-cluster-name': fake_client.CLUSTER_NAME,
}
},
}
self.client.send_iter_request.assert_has_calls([
mock.call('cluster-peer-get-iter', cluster_peer_get_iter_args)])
def test_get_cluster_peers_not_found(self):
api_response = netapp_api.NaElement(fake_client.NO_RECORDS_RESPONSE)
self.mock_object(self.client,
'send_iter_request',
return_value=api_response)
result = self.client.get_cluster_peers(
remote_cluster_name=fake_client.CLUSTER_NAME)
self.assertEqual([], result)
self.assertTrue(self.client.send_iter_request.called)
def test_delete_cluster_peer(self):
self.mock_object(self.client.connection, 'send_request')
self.client.delete_cluster_peer(fake_client.CLUSTER_NAME)
cluster_peer_delete_args = {'cluster-name': fake_client.CLUSTER_NAME}
self.client.connection.send_request.assert_has_calls([
mock.call('cluster-peer-delete', cluster_peer_delete_args)])
def test_get_cluster_peer_policy(self):
self.client.features.add_feature('CLUSTER_PEER_POLICY')
api_response = netapp_api.NaElement(
fake_client.CLUSTER_PEER_POLICY_GET_RESPONSE)
self.mock_object(self.client.connection,
'send_request',
return_value=api_response)
result = self.client.get_cluster_peer_policy()
expected = {
'is-unauthenticated-access-permitted': False,
'passphrase-minimum-length': 8,
}
self.assertEqual(expected, result)
self.assertTrue(self.client.connection.send_request.called)
def test_get_cluster_peer_policy_not_supported(self):
result = self.client.get_cluster_peer_policy()
self.assertEqual({}, result)
def test_set_cluster_peer_policy_not_supported(self):
self.mock_object(self.client.connection, 'send_request')
self.client.set_cluster_peer_policy()
self.assertFalse(self.client.connection.send_request.called)
def test_set_cluster_peer_policy_no_arguments(self):
self.client.features.add_feature('CLUSTER_PEER_POLICY')
self.mock_object(self.client.connection, 'send_request')
self.client.set_cluster_peer_policy()
self.assertFalse(self.client.connection.send_request.called)
def test_set_cluster_peer_policy(self):
self.client.features.add_feature('CLUSTER_PEER_POLICY')
self.mock_object(self.client.connection, 'send_request')
self.client.set_cluster_peer_policy(
is_unauthenticated_access_permitted=True,
passphrase_minimum_length=12)
cluster_peer_policy_modify_args = {
'is-unauthenticated-access-permitted': 'true',
'passphrase-minlength': '12',
}
self.client.connection.send_request.assert_has_calls([
mock.call('cluster-peer-policy-modify',
cluster_peer_policy_modify_args)])
def test_create_vserver_peer(self):
self.mock_object(self.client.connection, 'send_request')
self.client.create_vserver_peer('fake_vserver', 'fake_vserver_peer')
vserver_peer_create_args = {
'vserver': 'fake_vserver',
'peer-vserver': 'fake_vserver_peer',
'applications': [
{'vserver-peer-application': 'snapmirror'},
],
}
self.client.connection.send_request.assert_has_calls([
mock.call('vserver-peer-create', vserver_peer_create_args,
enable_tunneling=False)])
def test_delete_vserver_peer(self):
self.mock_object(self.client.connection, 'send_request')
self.client.delete_vserver_peer('fake_vserver', 'fake_vserver_peer')
vserver_peer_delete_args = {
'vserver': 'fake_vserver',
'peer-vserver': 'fake_vserver_peer',
}
self.client.connection.send_request.assert_has_calls([
mock.call('vserver-peer-delete', vserver_peer_delete_args)])
def test_accept_vserver_peer(self):
self.mock_object(self.client.connection, 'send_request')
self.client.accept_vserver_peer('fake_vserver', 'fake_vserver_peer')
vserver_peer_accept_args = {
'vserver': 'fake_vserver',
'peer-vserver': 'fake_vserver_peer',
}
self.client.connection.send_request.assert_has_calls([
mock.call('vserver-peer-accept', vserver_peer_accept_args)])
def test_get_file_sizes_by_dir(self):
api_response = netapp_api.NaElement(
fake_client.FILE_SIZES_BY_DIR_GET_ITER_RESPONSE)
self.mock_object(self.client,
'send_iter_request',
return_value=api_response)
result = self.client.get_file_sizes_by_dir(fake.NETAPP_VOLUME)
get_get_file_sizes_by_dir_get_iter_args = {
'path': '/vol/%s' % fake.NETAPP_VOLUME,
'query': {
'file-info': {
'file-type': 'file',
}
},
'desired-attributes': {
'file-info': {
'name': None,
'file-size': None
}
},
}
self.client.send_iter_request.assert_has_calls([
mock.call('file-list-directory-iter',
get_get_file_sizes_by_dir_get_iter_args,
max_page_length=100)])
expected = [{
'name': fake.VOLUME_NAME,
'file-size': float(1024)
}]
self.assertEqual(expected, result)
def test_get_file_sizes_by_dir_not_found(self):
api_response = netapp_api.NaElement(fake_client.NO_RECORDS_RESPONSE)
self.mock_object(self.client,
'send_iter_request',
return_value=api_response)
result = self.client.get_file_sizes_by_dir(fake.NETAPP_VOLUME)
self.assertEqual([], result)
self.assertTrue(self.client.send_iter_request.called)
def test_get_lun_sizes_by_volume(self):
api_response = netapp_api.NaElement(
fake_client.LUN_SIZES_BY_VOLUME_GET_ITER_RESPONSE)
self.mock_object(self.client,
'send_iter_request',
return_value=api_response)
result = self.client.get_lun_sizes_by_volume(fake.NETAPP_VOLUME)
get_lun_sizes_by_volume_get_iter_args = {
'query': {
'lun-info': {
'volume': fake.NETAPP_VOLUME,
}
},
'desired-attributes': {
'lun-info': {
'path': None,
'size': None
}
},
}
self.client.send_iter_request.assert_has_calls([
mock.call('lun-get-iter', get_lun_sizes_by_volume_get_iter_args,
max_page_length=100)])
expected = [{
'path': fake.VOLUME_PATH,
'size': float(1024)
}]
self.assertEqual(expected, result)
def test_get_lun_sizes_by_volume_not_found(self):
api_response = netapp_api.NaElement(fake_client.NO_RECORDS_RESPONSE)
self.mock_object(self.client,
'send_iter_request',
return_value=api_response)
result = self.client.get_lun_sizes_by_volume(fake.NETAPP_VOLUME)
self.assertEqual([], result)
self.assertTrue(self.client.send_iter_request.called)
def test_get_vserver_peers(self):
api_response = netapp_api.NaElement(
fake_client.VSERVER_PEER_GET_ITER_RESPONSE)
self.mock_object(self.client,
'send_iter_request',
return_value=api_response)
result = self.client.get_vserver_peers(
vserver_name=fake_client.VSERVER_NAME,
peer_vserver_name=fake_client.VSERVER_NAME_2)
vserver_peer_get_iter_args = {
'query': {
'vserver-peer-info': {
'vserver': fake_client.VSERVER_NAME,
'peer-vserver': fake_client.VSERVER_NAME_2,
}
}
}
self.client.send_iter_request.assert_has_calls([
mock.call('vserver-peer-get-iter', vserver_peer_get_iter_args,
enable_tunneling=False)])
expected = [{
'vserver': 'fake_vserver',
'peer-vserver': 'fake_vserver_2',
'peer-state': 'peered',
'peer-cluster': 'fake_cluster',
'applications': ['snapmirror'],
}]
self.assertEqual(expected, result)
def test_get_vserver_peers_not_found(self):
api_response = netapp_api.NaElement(fake_client.NO_RECORDS_RESPONSE)
self.mock_object(self.client,
'send_iter_request',
return_value=api_response)
result = self.client.get_vserver_peers(
vserver_name=fake_client.VSERVER_NAME,
peer_vserver_name=fake_client.VSERVER_NAME_2)
self.assertEqual([], result)
self.assertTrue(self.client.send_iter_request.called)
def test_ensure_snapmirror_v2(self):
self.assertIsNone(self.client._ensure_snapmirror_v2())
def test_ensure_snapmirror_v2_not_supported(self):
self.client.features.add_feature('SNAPMIRROR_V2', supported=False)
self.assertRaises(netapp_utils.NetAppDriverException,
self.client._ensure_snapmirror_v2)
@ddt.data({'schedule': 'fake_schedule', 'policy': 'fake_policy'},
{'schedule': None, 'policy': None})
@ddt.unpack
def test_create_snapmirror(self, schedule, policy):
self.mock_object(self.client.connection, 'send_request')
self.client.create_snapmirror(
fake_client.SM_SOURCE_VSERVER, fake_client.SM_SOURCE_VOLUME,
fake_client.SM_DEST_VSERVER, fake_client.SM_DEST_VOLUME,
schedule=schedule, policy=policy)
snapmirror_create_args = {
'source-vserver': fake_client.SM_SOURCE_VSERVER,
'source-volume': fake_client.SM_SOURCE_VOLUME,
'destination-vserver': fake_client.SM_DEST_VSERVER,
'destination-volume': fake_client.SM_DEST_VOLUME,
'relationship-type': 'data_protection',
}
if schedule:
snapmirror_create_args['schedule'] = schedule
if policy:
snapmirror_create_args['policy'] = policy
self.client.connection.send_request.assert_has_calls([
mock.call('snapmirror-create', snapmirror_create_args)])
def test_create_snapmirror_already_exists(self):
api_error = netapp_api.NaApiError(code=netapp_api.ERELATION_EXISTS)
self.mock_object(
self.client.connection, 'send_request', side_effect=api_error)
self.client.create_snapmirror(
fake_client.SM_SOURCE_VSERVER, fake_client.SM_SOURCE_VOLUME,
fake_client.SM_DEST_VSERVER, fake_client.SM_DEST_VOLUME)
snapmirror_create_args = {
'source-vserver': fake_client.SM_SOURCE_VSERVER,
'source-volume': fake_client.SM_SOURCE_VOLUME,
'destination-vserver': fake_client.SM_DEST_VSERVER,
'destination-volume': fake_client.SM_DEST_VOLUME,
'relationship-type': 'data_protection',
}
self.client.connection.send_request.assert_has_calls([
mock.call('snapmirror-create', snapmirror_create_args)])
def test_create_snapmirror_error(self):
api_error = netapp_api.NaApiError(code=0)
self.mock_object(
self.client.connection, 'send_request', side_effect=api_error)
self.assertRaises(netapp_api.NaApiError,
self.client.create_snapmirror,
fake_client.SM_SOURCE_VSERVER,
fake_client.SM_SOURCE_VOLUME,
fake_client.SM_DEST_VSERVER,
fake_client.SM_DEST_VOLUME)
self.assertTrue(self.client.connection.send_request.called)
@ddt.data(
{
'source_snapshot': 'fake_snapshot',
'transfer_priority': 'fake_priority'
},
{
'source_snapshot': None,
'transfer_priority': None
}
)
@ddt.unpack
def test_initialize_snapmirror(self, source_snapshot, transfer_priority):
api_response = netapp_api.NaElement(
fake_client.SNAPMIRROR_INITIALIZE_RESULT)
self.mock_object(self.client.connection,
'send_request',
return_value=api_response)
result = self.client.initialize_snapmirror(
fake_client.SM_SOURCE_VSERVER, fake_client.SM_SOURCE_VOLUME,
fake_client.SM_DEST_VSERVER, fake_client.SM_DEST_VOLUME,
source_snapshot=source_snapshot,
transfer_priority=transfer_priority)
snapmirror_initialize_args = {
'source-vserver': fake_client.SM_SOURCE_VSERVER,
'source-volume': fake_client.SM_SOURCE_VOLUME,
'destination-vserver': fake_client.SM_DEST_VSERVER,
'destination-volume': fake_client.SM_DEST_VOLUME,
}
if source_snapshot:
snapmirror_initialize_args['source-snapshot'] = source_snapshot
if transfer_priority:
snapmirror_initialize_args['transfer-priority'] = transfer_priority
self.client.connection.send_request.assert_has_calls([
mock.call('snapmirror-initialize', snapmirror_initialize_args)])
expected = {
'operation-id': None,
'status': 'succeeded',
'jobid': None,
'error-code': None,
'error-message': None
}
self.assertEqual(expected, result)
@ddt.data(True, False)
def test_release_snapmirror(self, relationship_info_only):
self.mock_object(self.client.connection, 'send_request')
self.client.release_snapmirror(
fake_client.SM_SOURCE_VSERVER, fake_client.SM_SOURCE_VOLUME,
fake_client.SM_DEST_VSERVER, fake_client.SM_DEST_VOLUME,
relationship_info_only=relationship_info_only)
snapmirror_release_args = {
'query': {
'snapmirror-destination-info': {
'source-vserver': fake_client.SM_SOURCE_VSERVER,
'source-volume': fake_client.SM_SOURCE_VOLUME,
'destination-vserver': fake_client.SM_DEST_VSERVER,
'destination-volume': fake_client.SM_DEST_VOLUME,
'relationship-info-only': ('true' if relationship_info_only
else 'false'),
}
}
}
self.client.connection.send_request.assert_has_calls([
mock.call('snapmirror-release-iter', snapmirror_release_args)])
def test_quiesce_snapmirror(self):
self.mock_object(self.client.connection, 'send_request')
self.client.quiesce_snapmirror(
fake_client.SM_SOURCE_VSERVER, fake_client.SM_SOURCE_VOLUME,
fake_client.SM_DEST_VSERVER, fake_client.SM_DEST_VOLUME)
snapmirror_quiesce_args = {
'source-vserver': fake_client.SM_SOURCE_VSERVER,
'source-volume': fake_client.SM_SOURCE_VOLUME,
'destination-vserver': fake_client.SM_DEST_VSERVER,
'destination-volume': fake_client.SM_DEST_VOLUME,
}
self.client.connection.send_request.assert_has_calls([
mock.call('snapmirror-quiesce', snapmirror_quiesce_args)])
@ddt.data(True, False)
def test_abort_snapmirror(self, clear_checkpoint):
self.mock_object(self.client.connection, 'send_request')
self.client.abort_snapmirror(
fake_client.SM_SOURCE_VSERVER, fake_client.SM_SOURCE_VOLUME,
fake_client.SM_DEST_VSERVER, fake_client.SM_DEST_VOLUME,
clear_checkpoint=clear_checkpoint)
snapmirror_abort_args = {
'source-vserver': fake_client.SM_SOURCE_VSERVER,
'source-volume': fake_client.SM_SOURCE_VOLUME,
'destination-vserver': fake_client.SM_DEST_VSERVER,
'destination-volume': fake_client.SM_DEST_VOLUME,
'clear-checkpoint': 'true' if clear_checkpoint else 'false',
}
self.client.connection.send_request.assert_has_calls([
mock.call('snapmirror-abort', snapmirror_abort_args)])
def test_abort_snapmirror_no_transfer_in_progress(self):
api_error = netapp_api.NaApiError(
code=netapp_api.ENOTRANSFER_IN_PROGRESS)
self.mock_object(
self.client.connection, 'send_request', side_effect=api_error)
self.client.abort_snapmirror(
fake_client.SM_SOURCE_VSERVER, fake_client.SM_SOURCE_VOLUME,
fake_client.SM_DEST_VSERVER, fake_client.SM_DEST_VOLUME)
snapmirror_abort_args = {
'source-vserver': fake_client.SM_SOURCE_VSERVER,
'source-volume': fake_client.SM_SOURCE_VOLUME,
'destination-vserver': fake_client.SM_DEST_VSERVER,
'destination-volume': fake_client.SM_DEST_VOLUME,
'clear-checkpoint': 'false',
}
self.client.connection.send_request.assert_has_calls([
mock.call('snapmirror-abort', snapmirror_abort_args)])
def test_abort_snapmirror_error(self):
api_error = netapp_api.NaApiError(code=0)
self.mock_object(
self.client.connection, 'send_request', side_effect=api_error)
self.assertRaises(netapp_api.NaApiError,
self.client.abort_snapmirror,
fake_client.SM_SOURCE_VSERVER,
fake_client.SM_SOURCE_VOLUME,
fake_client.SM_DEST_VSERVER,
fake_client.SM_DEST_VOLUME)
def test_break_snapmirror(self):
self.mock_object(self.client.connection, 'send_request')
self.client.break_snapmirror(
fake_client.SM_SOURCE_VSERVER, fake_client.SM_SOURCE_VOLUME,
fake_client.SM_DEST_VSERVER, fake_client.SM_DEST_VOLUME)
snapmirror_break_args = {
'source-vserver': fake_client.SM_SOURCE_VSERVER,
'source-volume': fake_client.SM_SOURCE_VOLUME,
'destination-vserver': fake_client.SM_DEST_VSERVER,
'destination-volume': fake_client.SM_DEST_VOLUME,
}
self.client.connection.send_request.assert_has_calls([
mock.call('snapmirror-break', snapmirror_break_args)])
@ddt.data(
{
'schedule': 'fake_schedule',
'policy': 'fake_policy',
'tries': 5,
'max_transfer_rate': 1024,
},
{
'schedule': None,
'policy': None,
'tries': None,
'max_transfer_rate': None,
}
)
@ddt.unpack
def test_modify_snapmirror(self, schedule, policy, tries,
max_transfer_rate):
self.mock_object(self.client.connection, 'send_request')
self.client.modify_snapmirror(
fake_client.SM_SOURCE_VSERVER, fake_client.SM_SOURCE_VOLUME,
fake_client.SM_DEST_VSERVER, fake_client.SM_DEST_VOLUME,
schedule=schedule, policy=policy, tries=tries,
max_transfer_rate=max_transfer_rate)
snapmirror_modify_args = {
'source-vserver': fake_client.SM_SOURCE_VSERVER,
'source-volume': fake_client.SM_SOURCE_VOLUME,
'destination-vserver': fake_client.SM_DEST_VSERVER,
'destination-volume': fake_client.SM_DEST_VOLUME,
}
if schedule:
snapmirror_modify_args['schedule'] = schedule
if policy:
snapmirror_modify_args['policy'] = policy
if tries:
snapmirror_modify_args['tries'] = tries
if max_transfer_rate:
snapmirror_modify_args['max-transfer-rate'] = max_transfer_rate
self.client.connection.send_request.assert_has_calls([
mock.call('snapmirror-modify', snapmirror_modify_args)])
def test_delete_snapmirror(self):
self.mock_object(self.client.connection, 'send_request')
self.client.delete_snapmirror(
fake_client.SM_SOURCE_VSERVER, fake_client.SM_SOURCE_VOLUME,
fake_client.SM_DEST_VSERVER, fake_client.SM_DEST_VOLUME)
snapmirror_delete_args = {
'query': {
'snapmirror-info': {
'source-vserver': fake_client.SM_SOURCE_VSERVER,
'source-volume': fake_client.SM_SOURCE_VOLUME,
'destination-vserver': fake_client.SM_DEST_VSERVER,
'destination-volume': fake_client.SM_DEST_VOLUME,
}
}
}
self.client.connection.send_request.assert_has_calls([
mock.call('snapmirror-destroy-iter', snapmirror_delete_args)])
def test_update_snapmirror(self):
self.mock_object(self.client.connection, 'send_request')
self.client.update_snapmirror(
fake_client.SM_SOURCE_VSERVER, fake_client.SM_SOURCE_VOLUME,
fake_client.SM_DEST_VSERVER, fake_client.SM_DEST_VOLUME)
snapmirror_update_args = {
'source-vserver': fake_client.SM_SOURCE_VSERVER,
'source-volume': fake_client.SM_SOURCE_VOLUME,
'destination-vserver': fake_client.SM_DEST_VSERVER,
'destination-volume': fake_client.SM_DEST_VOLUME,
}
self.client.connection.send_request.assert_has_calls([
mock.call('snapmirror-update', snapmirror_update_args)])
def test_update_snapmirror_already_transferring(self):
api_error = netapp_api.NaApiError(
code=netapp_api.ETRANSFER_IN_PROGRESS)
self.mock_object(
self.client.connection, 'send_request', side_effect=api_error)
self.client.update_snapmirror(
fake_client.SM_SOURCE_VSERVER, fake_client.SM_SOURCE_VOLUME,
fake_client.SM_DEST_VSERVER, fake_client.SM_DEST_VOLUME)
snapmirror_update_args = {
'source-vserver': fake_client.SM_SOURCE_VSERVER,
'source-volume': fake_client.SM_SOURCE_VOLUME,
'destination-vserver': fake_client.SM_DEST_VSERVER,
'destination-volume': fake_client.SM_DEST_VOLUME,
}
self.client.connection.send_request.assert_has_calls([
mock.call('snapmirror-update', snapmirror_update_args)])
def test_update_snapmirror_already_transferring_two(self):
api_error = netapp_api.NaApiError(code=netapp_api.EANOTHER_OP_ACTIVE)
self.mock_object(
self.client.connection, 'send_request', side_effect=api_error)
self.client.update_snapmirror(
fake_client.SM_SOURCE_VSERVER, fake_client.SM_SOURCE_VOLUME,
fake_client.SM_DEST_VSERVER, fake_client.SM_DEST_VOLUME)
snapmirror_update_args = {
'source-vserver': fake_client.SM_SOURCE_VSERVER,
'source-volume': fake_client.SM_SOURCE_VOLUME,
'destination-vserver': fake_client.SM_DEST_VSERVER,
'destination-volume': fake_client.SM_DEST_VOLUME,
}
self.client.connection.send_request.assert_has_calls([
mock.call('snapmirror-update', snapmirror_update_args)])
def test_update_snapmirror_error(self):
api_error = netapp_api.NaApiError(code=0)
self.mock_object(
self.client.connection, 'send_request', side_effect=api_error)
self.assertRaises(netapp_api.NaApiError,
self.client.update_snapmirror,
fake_client.SM_SOURCE_VSERVER,
fake_client.SM_SOURCE_VOLUME,
fake_client.SM_DEST_VSERVER,
fake_client.SM_DEST_VOLUME)
def test_resume_snapmirror(self):
self.mock_object(self.client.connection, 'send_request')
self.client.resume_snapmirror(
fake_client.SM_SOURCE_VSERVER, fake_client.SM_SOURCE_VOLUME,
fake_client.SM_DEST_VSERVER, fake_client.SM_DEST_VOLUME)
snapmirror_resume_args = {
'source-vserver': fake_client.SM_SOURCE_VSERVER,
'source-volume': fake_client.SM_SOURCE_VOLUME,
'destination-vserver': fake_client.SM_DEST_VSERVER,
'destination-volume': fake_client.SM_DEST_VOLUME,
}
self.client.connection.send_request.assert_has_calls([
mock.call('snapmirror-resume', snapmirror_resume_args)])
def test_resume_snapmirror_not_quiesed(self):
api_error = netapp_api.NaApiError(
code=netapp_api.ERELATION_NOT_QUIESCED)
self.mock_object(
self.client.connection, 'send_request', side_effect=api_error)
self.client.resume_snapmirror(
fake_client.SM_SOURCE_VSERVER, fake_client.SM_SOURCE_VOLUME,
fake_client.SM_DEST_VSERVER, fake_client.SM_DEST_VOLUME)
snapmirror_resume_args = {
'source-vserver': fake_client.SM_SOURCE_VSERVER,
'source-volume': fake_client.SM_SOURCE_VOLUME,
'destination-vserver': fake_client.SM_DEST_VSERVER,
'destination-volume': fake_client.SM_DEST_VOLUME,
}
self.client.connection.send_request.assert_has_calls([
mock.call('snapmirror-resume', snapmirror_resume_args)])
def test_resume_snapmirror_error(self):
api_error = netapp_api.NaApiError(code=0)
self.mock_object(
self.client.connection, 'send_request', side_effect=api_error)
self.assertRaises(netapp_api.NaApiError,
self.client.resume_snapmirror,
fake_client.SM_SOURCE_VSERVER,
fake_client.SM_SOURCE_VOLUME,
fake_client.SM_DEST_VSERVER,
fake_client.SM_DEST_VOLUME)
def test_resync_snapmirror(self):
self.mock_object(self.client.connection, 'send_request')
self.client.resync_snapmirror(
fake_client.SM_SOURCE_VSERVER, fake_client.SM_SOURCE_VOLUME,
fake_client.SM_DEST_VSERVER, fake_client.SM_DEST_VOLUME)
snapmirror_resync_args = {
'source-vserver': fake_client.SM_SOURCE_VSERVER,
'source-volume': fake_client.SM_SOURCE_VOLUME,
'destination-vserver': fake_client.SM_DEST_VSERVER,
'destination-volume': fake_client.SM_DEST_VOLUME,
}
self.client.connection.send_request.assert_has_calls([
mock.call('snapmirror-resync', snapmirror_resync_args)])
def test__get_snapmirrors(self):
api_response = netapp_api.NaElement(
fake_client.SNAPMIRROR_GET_ITER_RESPONSE)
self.mock_object(self.client,
'send_iter_request',
return_value=api_response)
desired_attributes = {
'snapmirror-info': {
'source-vserver': None,
'source-volume': None,
'destination-vserver': None,
'destination-volume': None,
'is-healthy': None,
}
}
result = self.client._get_snapmirrors(
fake_client.SM_SOURCE_VSERVER, fake_client.SM_SOURCE_VOLUME,
fake_client.SM_DEST_VSERVER, fake_client.SM_DEST_VOLUME,
desired_attributes=desired_attributes)
snapmirror_get_iter_args = {
'query': {
'snapmirror-info': {
'source-vserver': fake_client.SM_SOURCE_VSERVER,
'source-volume': fake_client.SM_SOURCE_VOLUME,
'destination-vserver': fake_client.SM_DEST_VSERVER,
'destination-volume': fake_client.SM_DEST_VOLUME,
},
},
'desired-attributes': {
'snapmirror-info': {
'source-vserver': None,
'source-volume': None,
'destination-vserver': None,
'destination-volume': None,
'is-healthy': None,
},
},
}
self.client.send_iter_request.assert_has_calls([
mock.call('snapmirror-get-iter', snapmirror_get_iter_args)])
self.assertEqual(1, len(result))
def test__get_snapmirrors_not_found(self):
api_response = netapp_api.NaElement(fake_client.NO_RECORDS_RESPONSE)
self.mock_object(self.client,
'send_iter_request',
return_value=api_response)
result = self.client._get_snapmirrors()
self.client.send_iter_request.assert_has_calls([
mock.call('snapmirror-get-iter', {})])
self.assertEqual([], result)
def test_get_snapmirrors(self):
api_response = netapp_api.NaElement(
fake_client.SNAPMIRROR_GET_ITER_FILTERED_RESPONSE)
self.mock_object(self.client,
'send_iter_request',
return_value=api_response)
desired_attributes = ['source-vserver', 'source-volume',
'destination-vserver', 'destination-volume',
'is-healthy', 'mirror-state', 'schedule']
result = self.client.get_snapmirrors(
fake_client.SM_SOURCE_VSERVER, fake_client.SM_SOURCE_VOLUME,
fake_client.SM_DEST_VSERVER, fake_client.SM_DEST_VOLUME,
desired_attributes=desired_attributes)
snapmirror_get_iter_args = {
'query': {
'snapmirror-info': {
'source-vserver': fake_client.SM_SOURCE_VSERVER,
'source-volume': fake_client.SM_SOURCE_VOLUME,
'destination-vserver': fake_client.SM_DEST_VSERVER,
'destination-volume': fake_client.SM_DEST_VOLUME,
},
},
'desired-attributes': {
'snapmirror-info': {
'source-vserver': None,
'source-volume': None,
'destination-vserver': None,
'destination-volume': None,
'is-healthy': None,
'mirror-state': None,
'schedule': None,
},
},
}
expected = [{
'source-vserver': fake_client.SM_SOURCE_VSERVER,
'source-volume': fake_client.SM_SOURCE_VOLUME,
'destination-vserver': fake_client.SM_DEST_VSERVER,
'destination-volume': fake_client.SM_DEST_VOLUME,
'is-healthy': 'true',
'mirror-state': 'snapmirrored',
'schedule': 'daily',
}]
self.client.send_iter_request.assert_has_calls([
mock.call('snapmirror-get-iter', snapmirror_get_iter_args)])
self.assertEqual(expected, result)
def test_get_provisioning_options_from_flexvol(self):
self.mock_object(self.client, 'get_flexvol',
return_value=fake_client.VOLUME_INFO_SSC)
self.mock_object(self.client, 'get_flexvol_dedupe_info',
return_value=fake_client.VOLUME_DEDUPE_INFO_SSC)
expected_prov_opts = {
'aggregate': 'fake_aggr1',
'compression_enabled': False,
'dedupe_enabled': True,
'language': 'en_US',
'size': 1,
'snapshot_policy': 'default',
'snapshot_reserve': '5',
'space_guarantee_type': 'none',
'volume_type': 'rw',
'is_flexgroup': False,
}
actual_prov_opts = self.client.get_provisioning_options_from_flexvol(
fake_client.VOLUME_NAME)
self.assertEqual(expected_prov_opts, actual_prov_opts)
def test_wait_for_busy_snapshot(self):
# Need to mock sleep as it is called by @utils.retry
self.mock_object(time, 'sleep')
mock_get_snapshot = self.mock_object(
self.client, 'get_snapshot',
return_value=fake.SNAPSHOT
)
self.client.wait_for_busy_snapshot(fake.FLEXVOL, fake.SNAPSHOT_NAME)
mock_get_snapshot.assert_called_once_with(fake.FLEXVOL,
fake.SNAPSHOT_NAME)
def test_wait_for_busy_snapshot_raise_exception(self):
# Need to mock sleep as it is called by @utils.retry
self.mock_object(time, 'sleep')
BUSY_SNAPSHOT = dict(fake.SNAPSHOT)
BUSY_SNAPSHOT['busy'] = True
mock_get_snapshot = self.mock_object(
self.client, 'get_snapshot',
return_value=BUSY_SNAPSHOT
)
self.assertRaises(exception.SnapshotIsBusy,
self.client.wait_for_busy_snapshot,
fake.FLEXVOL, fake.SNAPSHOT_NAME)
calls = [
mock.call(fake.FLEXVOL, fake.SNAPSHOT_NAME),
mock.call(fake.FLEXVOL, fake.SNAPSHOT_NAME),
mock.call(fake.FLEXVOL, fake.SNAPSHOT_NAME),
]
mock_get_snapshot.assert_has_calls(calls)
@ddt.data({
'mock_return':
fake_client.SNAPSHOT_INFO_FOR_PRESENT_NOT_BUSY_SNAPSHOT_CMODE,
'expected': [{
'name': fake.SNAPSHOT_NAME,
'instance_id': 'abcd-ef01-2345-6789',
'volume_name': fake.SNAPSHOT['volume_id'],
}]
}, {
'mock_return': fake_client.NO_RECORDS_RESPONSE,
'expected': [],
})
@ddt.unpack
def test_get_snapshots_marked_for_deletion(self, mock_return, expected):
api_response = netapp_api.NaElement(mock_return)
self.mock_object(self.client.connection,
'send_request',
return_value=api_response)
result = self.client.get_snapshots_marked_for_deletion()
api_args = {
'query': {
'snapshot-info': {
'name': client_base.DELETED_PREFIX + '*',
'vserver': self.vserver,
'busy': 'false'
},
},
'desired-attributes': {
'snapshot-info': {
'name': None,
'volume': None,
'snapshot-instance-uuid': None,
}
},
}
self.client.connection.send_request.assert_called_once_with(
'snapshot-get-iter', api_args)
self.assertListEqual(expected, result)
@ddt.data(True, False)
def test_is_qos_min_supported(self, supported):
self.client.features.add_feature('test', supported=supported)
mock_name = self.mock_object(netapp_utils,
'qos_min_feature_name',
return_value='test')
result = self.client.is_qos_min_supported(True, 'node')
mock_name.assert_called_once_with(True, 'node')
self.assertEqual(result, supported)
def test_is_qos_min_supported_invalid_node(self):
mock_name = self.mock_object(netapp_utils,
'qos_min_feature_name',
return_value='invalid_feature')
result = self.client.is_qos_min_supported(True, 'node')
mock_name.assert_called_once_with(True, 'node')
self.assertFalse(result)
def test_get_unique_volume(self):
api_response = netapp_api.NaElement(
fake_client.VOLUME_GET_ITER_STYLE_RESPONSE)
volume_elem = netapp_api.NaElement(fake_client.VOLUME_FLEXGROUP_STYLE)
volume_id_attr = self.client.get_unique_volume(api_response)
xml_exp = str(volume_elem).replace(" ", "").replace("\n", "")
xml_res = str(volume_id_attr).replace(" ", "").replace("\n", "")
self.assertEqual(xml_exp, xml_res)
def test_get_unique_volume_raise_exception(self):
api_response = netapp_api.NaElement(
fake_client.VOLUME_GET_ITER_SAME_STYLE_RESPONSE)
self.assertRaises(exception.VolumeBackendAPIException,
self.client.get_unique_volume,
api_response)
def test_get_cluster_name(self):
api_response = netapp_api.NaElement(
fake_client.GET_CLUSTER_NAME_RESPONSE)
mock_send_request = self.mock_object(
self.client.connection, 'send_request', return_value=api_response)
api_args = {
'desired-attributes': {
'cluster-identity-info': {
'cluster-name': None,
}
}
}
result = self.client.get_cluster_name()
mock_send_request.assert_called_once_with('cluster-identity-get',
api_args,
enable_tunneling=False)
self.assertEqual(fake_client.CLUSTER_NAME, result)
@ddt.data((fake_client.LUN_NAME, fake_client.DEST_VOLUME_NAME, None,
fake_client.VOLUME_NAME),
(fake_client.LUN_NAME, None, fake_client.DEST_LUN_NAME,
fake_client.DEST_VOLUME_NAME))
@ddt.unpack
def test_start_lun_move(self, src_lun_name, src_ontap_vol, dest_lun_name,
dest_ontap_vol):
api_response = netapp_api.NaElement(
fake_client.START_LUN_MOVE_RESPONSE)
mock_send_request = self.mock_object(
self.client.connection, 'send_request', return_value=api_response)
result = self.client.start_lun_move(src_lun_name,
dest_ontap_vol,
src_ontap_volume=src_ontap_vol,
dest_lun_name=dest_lun_name)
api_args = {
'paths': [{
'lun-path-pair': {
'destination-path': '/vol/%s/%s' % (dest_ontap_vol,
src_lun_name if
dest_lun_name is None
else dest_lun_name),
'source-path': '/vol/%s/%s' % (dest_ontap_vol
if src_ontap_vol is None
else src_ontap_vol,
src_lun_name)
}
}]
}
mock_send_request.assert_called_once_with('lun-move-start', api_args)
self.assertEqual(fake.JOB_UUID, result)
def test_get_lun_move_status(self):
api_response = netapp_api.NaElement(
fake_client.GET_LUN_MOVE_STATUS_RESPONSE)
mock_send_request = self.mock_object(
self.client.connection, 'send_request', return_value=api_response)
result = self.client.get_lun_move_status(fake.JOB_UUID)
api_args = {
'query': {
'lun-move-info': {
'job-uuid': fake.JOB_UUID
}
}
}
mock_send_request.assert_called_once_with('lun-move-get-iter',
api_args)
expected = {
'job-status': 'complete',
'last-failure-reason': None
}
self.assertEqual(expected, result)
@ddt.data((fake_client.LUN_NAME, None, fake_client.VSERVER_NAME,
fake_client.DEST_LUN_NAME, fake_client.DEST_VOLUME_NAME,
fake_client.DEST_VSERVER_NAME),
(fake_client.LUN_NAME, fake_client.VOLUME_NAME, None,
fake_client.DEST_LUN_NAME, fake_client.DEST_VOLUME_NAME,
fake_client.DEST_VSERVER_NAME),
(fake_client.LUN_NAME, fake_client.VOLUME_NAME,
fake_client.VSERVER_NAME, None, fake_client.DEST_VOLUME_NAME,
fake_client.DEST_VSERVER_NAME))
@ddt.unpack
def test_start_lun_copy(self, src_lun_name, src_ontap_vol, src_vserver,
dest_lun_name, dest_ontap_vol, dest_vserver):
api_response = netapp_api.NaElement(
fake_client.START_LUN_COPY_RESPONSE)
mock_send_request = self.mock_object(
self.client.connection, 'send_request', return_value=api_response)
result = self.client.start_lun_copy(src_lun_name,
dest_ontap_vol,
dest_vserver,
src_ontap_volume=src_ontap_vol,
src_vserver=src_vserver,
dest_lun_name=dest_lun_name)
api_args = {
'source-vserver': (dest_vserver if not src_vserver
else src_vserver),
'destination-vserver': dest_vserver,
'paths': [{
'lun-path-pair': {
'destination-path': '/vol/%s/%s' % (dest_ontap_vol,
src_lun_name if
dest_lun_name is None
else dest_lun_name),
'source-path': '/vol/%s/%s' % (dest_ontap_vol
if src_ontap_vol is None
else src_ontap_vol,
src_lun_name)
}
}]
}
mock_send_request.assert_called_once_with('lun-copy-start', api_args,
enable_tunneling=False)
self.assertEqual(fake.JOB_UUID, result)
def test_get_lun_copy_status(self):
api_response = netapp_api.NaElement(
fake_client.GET_LUN_COPY_STATUS_RESPONSE)
mock_send_request = self.mock_object(
self.client.connection, 'send_request', return_value=api_response)
result = self.client.get_lun_copy_status(fake.JOB_UUID)
api_args = {
'query': {
'lun-copy-info': {
'job-uuid': fake.JOB_UUID
}
}
}
mock_send_request.assert_called_once_with('lun-copy-get-iter',
api_args,
enable_tunneling=False)
expected = {
'job-status': 'complete',
'last-failure-reason': None
}
self.assertEqual(expected, result)
@ddt.data((fake_client.FILE_NAME, None, fake_client.DEST_VOLUME_NAME,
fake_client.DEST_VOLUME_NAME),
(fake_client.FILE_NAME, fake_client.VOLUME_NAME, None,
fake_client.DEST_VOLUME_NAME))
@ddt.unpack
def test_start_file_copy(self, src_file_name, src_ontap_vol,
dest_file_name, dest_ontap_vol):
api_response = netapp_api.NaElement(
fake_client.START_FILE_COPY_RESPONSE)
mock_send_request = self.mock_object(
self.client.connection, 'send_request', return_value=api_response)
result = self.client.start_file_copy(src_file_name,
dest_ontap_vol,
src_ontap_volume=src_ontap_vol,
dest_file_name=dest_file_name)
api_args = {
'source-paths': [{
'sfod-operation-path': '%s/%s' % (dest_ontap_vol if
src_ontap_vol is None else
src_ontap_vol,
src_file_name)
}],
'destination-paths': [{
'sfod-operation-path': '%s/%s' % (dest_ontap_vol,
src_file_name if
dest_file_name is None else
dest_file_name)
}],
}
mock_send_request.assert_called_once_with('file-copy-start', api_args,
enable_tunneling=False)
self.assertEqual(fake.JOB_UUID, result)
def test_get_file_copy_status(self):
api_response = netapp_api.NaElement(
fake_client.GET_FILE_COPY_STATUS_RESPONSE)
mock_send_request = self.mock_object(
self.client.connection, 'send_request', return_value=api_response)
result = self.client.get_file_copy_status(fake.JOB_UUID)
api_args = {
'query': {
'file-copy-info': {
'job-uuid': fake.JOB_UUID
}
}
}
mock_send_request.assert_called_once_with('file-copy-get-iter',
api_args,
enable_tunneling=False)
expected = {
'job-status': 'complete',
'last-failure-reason': None
}
self.assertEqual(expected, result)
def test_destroy_file_copy(self):
api_response = netapp_api.NaElement(
fake_client.DESTROY_FILE_COPY_RESPONSE)
mock_send_request = self.mock_object(
self.client.connection, 'send_request', return_value=api_response)
result = self.client.destroy_file_copy(fake.JOB_UUID)
api_args = {
'job-uuid': fake.JOB_UUID,
'file-index': 0
}
mock_send_request.assert_called_once_with('file-copy-destroy',
api_args,
enable_tunneling=False)
self.assertIsNone(result)
def test_destroy_file_copy_error(self):
mock_send_request = self.mock_object(self.client.connection,
'send_request',
side_effect=netapp_api.NaApiError)
self.assertRaises(netapp_utils.NetAppDriverException,
self.client.destroy_file_copy,
fake.JOB_UUID)
api_args = {
'job-uuid': fake.JOB_UUID,
'file-index': 0
}
mock_send_request.assert_called_once_with('file-copy-destroy',
api_args,
enable_tunneling=False)
def test_cancel_lun_copy(self):
api_response = netapp_api.NaElement(
fake_client.CANCEL_LUN_COPY_RESPONSE)
mock_send_request = self.mock_object(
self.client.connection, 'send_request', return_value=api_response)
result = self.client.cancel_lun_copy(fake.JOB_UUID)
api_args = {
'job-uuid': fake.JOB_UUID
}
mock_send_request.assert_called_once_with('lun-copy-cancel',
api_args,
enable_tunneling=False)
self.assertIsNone(result)
def test_cancel_lun_copy_error(self):
mock_send_request = self.mock_object(self.client.connection,
'send_request',
side_effect=netapp_api.NaApiError)
self.assertRaises(netapp_utils.NetAppDriverException,
self.client.cancel_lun_copy,
fake.JOB_UUID)
api_args = {
'job-uuid': fake.JOB_UUID
}
mock_send_request.assert_called_once_with('lun-copy-cancel',
api_args,
enable_tunneling=False)
def test_rename_file(self):
self.mock_object(self.client.connection, 'send_request')
orig_file_name = '/vol/fake_vol/volume-%s' % self.fake_volume
new_file_name = '/vol/fake_vol/new-volume-%s' % self.fake_volume
self.client.rename_file(orig_file_name, new_file_name)
api_args = {
'from-path': orig_file_name,
'to-path': new_file_name,
}
self.client.connection.send_request.assert_called_once_with(
'file-rename-file', api_args)
| 93,052 |
1,279 | {
"errorMessage": "Invalid Serverless Application Specification document. Number of errors found: 1. Structure of the SAM template is invalid. Could not find x-amazon-apigateway-any-method in /{domain} within DefinitionBody."
} | 56 |
679 | <gh_stars>100-1000
/**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#include <com/sun/star/embed/NoVisualAreaSizeException.hpp>
#include <wrtsh.hxx>
#include <doc.hxx>
#include <swtypes.hxx>
#include <view.hxx>
#include <edtwin.hxx>
#include <swcli.hxx>
#include <cmdid.h>
#include <cfgitems.hxx>
#include <toolkit/helper/vclunohelper.hxx>
using namespace com::sun::star;
SwOleClient::SwOleClient( SwView *pView, SwEditWin *pWin, const svt::EmbeddedObjectRef& xObj ) :
SfxInPlaceClient( pView, pWin, xObj.GetViewAspect() ), bInDoVerb( sal_False ),
bOldCheckForOLEInCaption( pView->GetWrtShell().IsCheckForOLEInCaption() )
{
SetObject( xObj.GetObject() );
}
void SwOleClient::RequestNewObjectArea( Rectangle& aLogRect )
{
//Der Server moechte die Clientgrosse verandern.
//Wir stecken die Wunschgroesse in die Core. Die Attribute des Rahmens
//werden auf den Wunschwert eingestellt. Dieser Wert wird also auch an
//den InPlaceClient weitergegeben.
//Die Core aktzeptiert bzw. formatiert die eingestellten Werte nicht
//zwangslaeufig. Wenn der Ole-Frm formatiert wurde wird das CalcAndSetScale()
//der WrtShell gerufen. Dort wird ggf. die Scalierung des SwOleClient
//eingestellt.
SwWrtShell &rSh = ((SwView*)GetViewShell())->GetWrtShell();
rSh.StartAllAction();
// the aLogRect will get the preliminary size now
aLogRect.SetSize( rSh.RequestObjectResize( SwRect( aLogRect ), GetObject() ) );
// the EndAllAction() call will trigger CalcAndSetScale() call,
// so the embedded object must get the correct size before
if ( aLogRect.GetSize() != GetScaledObjArea().GetSize() )
{
// size has changed, so first change visual area of the object before we resize its view
// without this the object always would be scaled - now it has the choice
// TODO/LEAN: getMapUnit can switch object to running state
MapMode aObjectMap( VCLUnoHelper::UnoEmbed2VCLMapUnit( GetObject()->getMapUnit( GetAspect() ) ) );
MapMode aClientMap( GetEditWin()->GetMapMode().GetMapUnit() );
Size aNewObjSize( Fraction( aLogRect.GetWidth() ) / GetScaleWidth(),
Fraction( aLogRect.GetHeight() ) / GetScaleHeight() );
// convert to logical coordinates of the embedded object
Size aNewSize = GetEditWin()->LogicToLogic( aNewObjSize, &aClientMap, &aObjectMap );
GetObject()->setVisualAreaSize( GetAspect(), awt::Size( aNewSize.Width(), aNewSize.Height() ) );
}
rSh.EndAllAction();
SwRect aFrm( rSh.GetAnyCurRect( RECT_FLY_EMBEDDED, 0, GetObject() )),
aPrt( rSh.GetAnyCurRect( RECT_FLY_PRT_EMBEDDED, 0, GetObject() ));
aLogRect.SetPos( aPrt.Pos() + aFrm.Pos() );
aLogRect.SetSize( aPrt.SSize() );
}
void SwOleClient::ObjectAreaChanged()
{
SwWrtShell &rSh = ((SwView*)GetViewShell())->GetWrtShell();
SwRect aFrm( rSh.GetAnyCurRect( RECT_FLY_EMBEDDED, 0, GetObject() )),
aPrt( rSh.GetAnyCurRect( RECT_FLY_PRT_EMBEDDED, 0, GetObject() ));
if ( !aFrm.IsOver( rSh.VisArea() ) )
rSh.MakeVisible( aFrm );
}
void SwOleClient::ViewChanged()
{
if ( bInDoVerb )
return;
if ( GetAspect() == embed::Aspects::MSOLE_ICON )
{
// the iconified object seems not to need such a scaling handling
// since the replacement image and the size a completely controlled by the container
// TODO/LATER: when the icon exchange is implemented the scaling handling might be required again here
return;
}
SwWrtShell &rSh = ((SwView*)GetViewShell())->GetWrtShell();
//Einstellen der Groesse des Objektes in der Core. Die Scalierung muss
//beruecksichtigt werden. Rueckwirkung auf das Objekt werden von
//CalcAndSetScale() der WrtShell beruecksichtig, wenn die Groesse/Pos des
//Rahmens in der Core sich veraendert.
// TODO/LEAN: getMapUnit can switch object to running state
awt::Size aSz;
try
{
aSz = GetObject()->getVisualAreaSize( GetAspect() );
}
catch( embed::NoVisualAreaSizeException& )
{
// Nothing will be done
}
catch( uno::Exception& )
{
// this is an error
OSL_ENSURE( sal_False, "Something goes wrong on requesting object size!\n" );
}
Size aVisSize( aSz.Width, aSz.Height );
// Bug 24833: solange keine vernuenftige Size vom Object kommt,
// kann nichts skaliert werden
if( !aVisSize.Width() || !aVisSize.Height() )
return;
// first convert to TWIPS before scaling, because scaling factors are calculated for
// the TWIPS mapping and so they will produce the best results if applied to TWIPS based
// coordinates
const MapMode aMyMap ( MAP_TWIP );
const MapMode aObjMap( VCLUnoHelper::UnoEmbed2VCLMapUnit( GetObject()->getMapUnit( GetAspect() ) ) );
aVisSize = OutputDevice::LogicToLogic( aVisSize, aObjMap, aMyMap );
aVisSize.Width() = Fraction( aVisSize.Width() ) * GetScaleWidth();
aVisSize.Height()= Fraction( aVisSize.Height() ) * GetScaleHeight();
SwRect aRect( Point( LONG_MIN, LONG_MIN ), aVisSize );
rSh.LockView( sal_True ); //Scrollen im EndAction verhindern
rSh.StartAllAction();
rSh.RequestObjectResize( aRect, GetObject() );
rSh.EndAllAction();
rSh.LockView( sal_False );
}
void SwOleClient::MakeVisible()
{
const SwWrtShell &rSh = ((SwView*)GetViewShell())->GetWrtShell();
rSh.MakeObjVisible( GetObject() );
}
// --> #i972#
void SwOleClient::FormatChanged()
{
const uno::Reference < embed::XEmbeddedObject >& xObj( GetObject() );
SwView * pView = dynamic_cast< SwView * >( GetViewShell() );
if ( pView && xObj.is() && SotExchange::IsMath( xObj->getClassID() ) )
{
SwWrtShell & rWrtSh = pView->GetWrtShell();
if (rWrtSh.GetDoc()->get( IDocumentSettingAccess::MATH_BASELINE_ALIGNMENT ))
rWrtSh.AlignFormulaToBaseline( xObj );
}
}
// <--
| 2,421 |
2,542 | <reponame>AnthonyM/service-fabric
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pwd.h>
#include <thread>
#include <atomic>
#include <string>
#include <nt.h>
#include <sal.h>
#include "FabricHeader.h"
| 186 |
774 | package com.example;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
public class Main extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.nextButton).setOnClickListener(new handleButton());
}
class handleButton implements OnClickListener {
public void onClick(View v) {
Intent intent = new Intent(Main.this, Screen2.class);
startActivity(intent);
}
}
} | 243 |
5,169 | <gh_stars>1000+
{
"name": "DeltaCalculator",
"version": "1.0.3",
"summary": "DeltaCalculator is a Swift Library focused on replacing reloadData() calls with animated insert, delete and move operations.",
"description": "DeltaCalculator is a Swift Library focused on replacing reloadData()\ncalls with animated insert, delete and move operations.\nDeltaCalculator tries to optimize the number of iterations to calculate all the changes,\nmaking sure the UI thread doesn't block.\nThis framework is based on BKDeltaCalculator Objective-C library.",
"homepage": "https://github.com/ivanbruel/DeltaCalculator",
"license": "MIT",
"authors": {
"<NAME>": "<EMAIL>"
},
"source": {
"git": "https://github.com/ivanbruel/DeltaCalculator.git",
"tag": "1.0.3"
},
"social_media_url": "https://twitter.com/ivanbruel",
"platforms": {
"ios": "8.0"
},
"requires_arc": true,
"source_files": "Pod/Classes/**/*",
"frameworks": "UIKit"
}
| 323 |
725 | <gh_stars>100-1000
/* Part of SWI-Prolog
Author: <NAME>
E-mail: <EMAIL>
WWW: http://www.swi-prolog.org
Copyright (c) 1985-2019, University of Amsterdam
VU University Amsterdam
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "pl-incl.h"
#ifndef _PL_ATOM_H
#define _PL_ATOM_H
/*******************************
* FUNCTION DECLARATIONS *
*******************************/
#define checkAtoms() checkAtoms_src(__FILE__, __LINE__)
word lookupAtom(const char *s, size_t len);
word lookupBlob(const char *s, size_t len,
PL_blob_t *type, int *new);
word pl_atom_hashstat(term_t i, term_t n);
void do_init_atoms(void);
int resetListAtoms(void);
void cleanupAtoms(void);
void markAtom(atom_t a);
foreign_t pl_garbage_collect_atoms(void);
void resetAtoms(void);
int checkAtoms_src(const char *file, int line);
int is_volatile_atom(atom_t a);
size_t atom_space(void);
#ifdef O_DEBUG_ATOMGC
word pl_track_atom(term_t which, term_t stream);
#endif
#endif /*_PL_ATOM_H*/ | 889 |
349 | import sys
import os
import subprocess
import colorama
colorama.init()
import refactoring # Note: refactoring.py need to be in the current working directory
paths = [
"C:/Users/petst55.AD/Documents/Inviwo/inviwo"
]
excludespatterns = ["*/ext/*", "*/templates/*", "*/tools/codegen/*" , "*moc_*", "*cmake*"];
files = refactoring.find_files(paths, ['*.h', '*.hpp', '*.cpp'], excludes=excludespatterns)
for file in files:
print("check " + file)
with subprocess.Popen(["clang-format.exe", "-i", file],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
universal_newlines=True) as proc:
for line in proc.stdout:
print(line, end='', flush=True) | 254 |
1,269 | <filename>venv/Lib/site-packages/langdetect/lang_detect_exception.py<gh_stars>1000+
_error_codes = {
'NoTextError': 0,
'FormatError': 1,
'FileLoadError': 2,
'DuplicateLangError': 3,
'NeedLoadProfileError': 4,
'CantDetectError': 5,
'CantOpenTrainData': 6,
'TrainDataFormatError': 7,
'InitParamError': 8,
}
ErrorCode = type('ErrorCode', (), _error_codes)
class LangDetectException(Exception):
def __init__(self, code, message):
super(LangDetectException, self).__init__(message)
self.code = code
def get_code(self):
return self.code
| 247 |
373 | package com.dianrong.platform.open.cfg;
import java.nio.charset.Charset;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
public class CfgGroup extends CfgBaseGroup {
private static final long serialVersionUID = 1L;
private static Logger logger = LoggerFactory.getLogger(CfgGroup.class);
public CfgGroup() {}
/**
* 构造方法.
*/
public CfgGroup(String connectString, String rootNode, boolean keepAlive) {
super.connectString = connectString;
super.cfgRootNodeName = rootNode;
super.needKeepAlive = keepAlive;
super.init();
}
private CfgGroup internalCfgGroup;
@Override
public String get(Object key) {
String value;
if (internalCfgGroup != null) {
value = internalCfgGroup.get(key);
if (!StringUtils.isEmpty(value)) {
if (NULL_VALUE_IN_ZK.equals(value)) {
return null;
} else {
return value;
}
}
}
value = super.get(key);
if (NULL_VALUE_IN_ZK.equals(value)) {
return null;
} else {
return value;
}
}
/**
* 更新.
*/
public void updateCfg(String fullPath, Object obj) {
checkStatus(fullPath, obj);
checkExist(fullPath);
String value = String.valueOf(obj);
try {
client.setData().forPath(fullPath, value.getBytes(Charset.forName("utf-8")));
super.put(formatFullPathToKey(fullPath), value);
} catch (Exception e) {
// should never happen
logger.error("CfgGroup UpdateCfg Exception, exception = {}", e);
}
}
/**
* 添加配置.
*/
public void addCfg(String fullPath, Object obj) {
checkStatus(fullPath, obj);
Stat stat = null;
try {
stat = client.checkExists().forPath(fullPath);
} catch (Exception e) {
// should never happen
logger.error("CfgGroup AddCfg Exception, exception = {}", e);
}
if (stat != null) {
throw new RuntimeException(fullPath + " Already Exists.");
}
String value = String.valueOf(obj);
try {
client.create().forPath(fullPath, value.getBytes(Charset.forName("utf-8")));
super.put(formatFullPathToKey(fullPath), value);
} catch (Exception e) {
// should never happen
logger.error("CfgGroup AddCfg Exception, exception = {}", e);
}
}
/**
* 删除配置.
*/
public void deleteCfg(String fullPath) {
checkStatus(fullPath, new Object());
checkExist(fullPath);
try {
client.delete().forPath(fullPath);
super.remove(formatFullPathToKey(fullPath));
} catch (Exception e) {
// should never happen
logger.error("CfgGroup DeleteCfg Exception, exception = {}", e);
}
}
private void checkExist(String fullPath) {
Stat stat = null;
try {
stat = client.checkExists().forPath(fullPath);
} catch (Exception e) {
// should never happen
logger.error("CfgGroup CheckExist Exception, exception = {}", e);
}
if (stat == null) {
throw new RuntimeException(fullPath + " Does Not Exist.");
}
}
private void checkStatus(String fullPath, Object value) {
if (value == null) {
throw new RuntimeException("Value To Set Can Not Be Null.");
}
if (StringUtils.isEmpty(cfgRootNodeName) || !fullPath.startsWith(cfgRootNodeName)) {
throw new RuntimeException(
"Permission Deny, " + fullPath + " Does Not Belong To This Group.");
}
if (client == null) {
throw new RuntimeException("CfgGroup Disconnect From Zookeeper.");
}
}
public boolean addCfgEventListener(CfgEventListener listener) {
return listeners.add(listener);
}
public boolean removeCfgEventListener(CfgEventListener listener) {
return listeners.remove(listener);
}
public void setInternalCfgGroup(CfgGroup internalCfgGroup) {
this.internalCfgGroup = internalCfgGroup;
}
}
| 1,516 |
1,363 | /*
* Copyright 2019 liaochong
*
* 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.github.liaochong.myexcel.core;
/**
* excel单元格
*
* @author liaochong
* @version 1.0
*/
public class Cell {
private final int rowNum;
private final int colNum;
public Cell(int rowNum, int colNum) {
this.rowNum = rowNum;
this.colNum = colNum;
}
public int getRowNum() {
return rowNum;
}
public int getColNum() {
return colNum;
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
} else if (!(o instanceof Cell)) {
return false;
} else {
Cell other = (Cell) o;
if (!other.canEqual(this)) {
return false;
} else if (this.getRowNum() != other.getRowNum()) {
return false;
} else {
return this.getColNum() == other.getColNum();
}
}
}
private boolean canEqual(Object other) {
return other instanceof Cell;
}
@Override
public int hashCode() {
int result = 59 + this.getRowNum();
result = result * 59 + this.getColNum();
return result;
}
}
| 709 |
545 | #include <iostream>
struct LongDouble {
LongDouble(double = 0.0);
operator double() {
std::cout << "LongDouble::operator double()" << std::endl;
return 0;
}
operator float() {
std::cout << "LongDouble::operator float()" << std::endl;
return 0;
}
};
void calc(int) {
std::cout << "void calc(int)" << std::endl;
}
void calc(LongDouble) {
std::cout << "void calc(LongDouble)" << std::endl;
}
int main() {
double dval = 0;
calc(dval);
// will call `void calc(int)`, since only standard conversion is used
return 0;
}
| 209 |
866 | from commitizen.cz import exceptions
def required_validator(ans, msg=None):
if not ans:
raise exceptions.AnswerRequiredError(msg)
return ans
def multiple_line_breaker(ans, sep="|"):
return "\n".join(line.strip() for line in ans.split(sep) if line)
| 96 |
3,269 | <filename>C++/time-needed-to-buy-tickets.cpp
// Time: O(n)
// Space: O(1)
class Solution {
public:
int timeRequiredToBuy(vector<int>& tickets, int k) {
int result = 0;
for (int i = 0; i < size(tickets); ++i) {
result += min(tickets[i], i <= k ? tickets[k]: tickets[k] - 1);
}
return result;
}
};
| 167 |
767 | <gh_stars>100-1000
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available.
Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://opensource.org/licenses/MIT
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.
""" # noqa
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('bkaccount', '0003_bktoken_inactive_expire_time'),
]
operations = [
migrations.CreateModel(
name='BkRole',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('code', models.IntegerField(unique=True, verbose_name='\u89d2\u8272\u7f16\u53f7', choices=[(0, '\u666e\u901a\u7528\u6237'), (1, '\u8d85\u7ea7\u7ba1\u7406\u5458'), (2, '\u5f00\u53d1\u8005'), (3, '\u804c\u80fd\u5316\u7528\u6237')])),
],
options={
'db_table': 'login_bkrole',
'verbose_name': '\u7528\u6237\u89d2\u8272',
'verbose_name_plural': '\u7528\u6237\u89d2\u8272',
},
),
migrations.CreateModel(
name='BkUserRole',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('create_time', models.DateTimeField(default=django.utils.timezone.now, verbose_name='create_time')),
('role', models.ForeignKey(to='bkaccount.BkRole')),
('user', models.ForeignKey(to=settings.AUTH_USER_MODEL)),
],
options={
'db_table': 'login_bkuser_role',
'verbose_name': '\u7528\u6237\u89d2\u8272\u5173\u7cfb\u8868',
'verbose_name_plural': '\u7528\u6237\u89d2\u8272\u5173\u7cfb\u8868',
},
),
migrations.AddField(
model_name='bkuser',
name='role',
field=models.ManyToManyField(to='bkaccount.BkRole', verbose_name='\u89d2\u8272', through='bkaccount.BkUserRole'),
),
]
| 1,240 |
1,264 |
from ..linalg import lu, svd, qr, eig
from numpy import random as _random, sqrt
from numpy.linalg import norm
from ..utils import _float, _svdCond, traceXTX, eig_flip, svd_flip
from ..random import uniform
# __all__ = ['randomizedSVD', 'randomizedEig']
def randomized_projection(X, k, solver = 'lu', max_iter = 4):
"""
[Edited 8/11/2018 Added QR Q_only parameter]
Projects X onto some random eigenvectors, then using a special
variant of Orthogonal Iteration, finds the closest orthogonal
representation for X.
Solver can be QR or LU or None.
"""
n, p = X.shape
if max_iter == 'auto':
# From Modern Big Data Algorithms --> seems like <= 4 is enough.
_min = n if n <= p else p
max_iter = 5 if k < 0.1 * _min else 4
Q = uniform(-5, 5, p, int(k), X.dtype)
XT = X.T
_solver = lambda x: lu(x, L_only = True)
if solver == 'qr': _solver = lambda x: qr(x, Q_only = True)
elif solver == None: _solver = lambda x: x
for __ in range(max_iter):
Q = _solver(XT @ _solver(X @ Q))
return qr(X @ Q, Q_only = True)
def randomizedSVD(X, n_components = 2, max_iter = 'auto', solver = 'lu', n_oversamples = 10):
"""
[Edited 9/11/2018 Fixed SVD_flip]
HyperLearn's Fast Randomized SVD is approx 10 - 30 % faster than
Sklearn's implementation depending on n_components and max_iter.
Uses NUMBA Jit accelerated functions when available, and tries to
reduce memory overhead by chaining operations.
Uses QR, LU or no solver to find the best SVD decomp. QR is most stable,
but can be 2x slower than LU.
****n_oversamples = 10. This follows Sklearn convention to increase the chance
of more accurate SVD.
References
--------------
* Sklearn's RandomizedSVD
* Finding structure with randomness: Stochastic algorithms for constructing
approximate matrix decompositions
Halko, et al., 2009 http://arxiv.org/abs/arXiv:0909.4061
* A randomized algorithm for the decomposition of matrices
<NAME>, <NAME> and <NAME>
* An implementation of a randomized algorithm for principal component
analysis
<NAME> et al. 2014
"""
n,p = X.shape
transpose = (n < p)
X = X if not transpose else X.T
X = _float(X)
Q = randomized_projection(X, n_components + n_oversamples, solver, max_iter)
U, S, VT = svd(Q.T @ X, U_decision = transpose, transpose = True)
U = Q @ U
if transpose:
U, VT = VT.T, U.T
return U[:, :n_components], S[:n_components], VT[:n_components, :]
def randomizedEig(X, n_components = 2, max_iter = 'auto', solver = 'lu', n_oversamples = 10):
"""
[Edited 9/11/2018 Fixed Eig_Flip]
HyperLearn's Randomized Eigendecomposition is an extension of Sklearn's
randomized SVD. HyperLearn notices that the computation of U is not necessary,
hence will use QR followed by SVD or just SVD depending on the situation.
Likewise, solver = LU is default, and follows randomizedSVD
References
--------------
* Sklearn's RandomizedSVD
* Finding structure with randomness: Stochastic algorithms for constructing
approximate matrix decompositions
Halko, et al., 2009 http://arxiv.org/abs/arXiv:0909.4061
* A randomized algorithm for the decomposition of matrices
<NAME>, <NAME> and <NAME>
* An implementation of a randomized algorithm for principal component
analysis
<NAME> et al. 2014
"""
n,p = X.shape
transpose = (n < p)
X = X if not transpose else X.T
X = _float(X)
Q = randomized_projection(X, n_components + n_oversamples, solver, max_iter)
if transpose:
V, S2, __ = svd(Q.T @ X, U_decision = transpose, transpose = True)
V = Q @ V
S2 **= 2
else:
S2, V = eig(Q.T @ X, U_decision = transpose)
return S2[:n_components], V[:, :n_components]
def randomizedPinv(X, n_components = None, alpha = None):
"""
[Added 6/11/2018]
Implements fast randomized pseudoinverse with regularization.
Can be used as an approximation to the matrix inverse.
"""
if alpha != None: assert alpha >= 0
alpha = 0 if alpha is None else alpha
if n_components == None:
# will provide approx sqrt(p) - 1 components.
# A heuristic, so not guaranteed to work.
k = int(sqrt(X.shape[1]))-1
if k <= 0: k = 1
else:
k = int(n_components) if n_components > 0 else 1
X = _float(X)
U, S, VT = randomizedSVD(X, n_components)
U, S, VT = _svdCond(U, S, VT, alpha)
return VT.T * S @ U.T
| 1,582 |
995 | <gh_stars>100-1000
package zemberek.classification;
import com.google.common.base.Splitter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import zemberek.apps.fasttext.EvaluateClassifier;
import zemberek.apps.fasttext.TrainClassifier;
import zemberek.core.collections.Histogram;
import zemberek.core.logging.Log;
import zemberek.core.text.BlockTextLoader;
import zemberek.core.text.TextChunk;
import zemberek.core.turkish.Turkish;
import zemberek.morphology.TurkishMorphology;
import zemberek.morphology.analysis.SentenceAnalysis;
import zemberek.morphology.analysis.SentenceWordAnalysis;
import zemberek.morphology.analysis.SingleAnalysis;
import zemberek.tokenization.TurkishTokenizer;
import zemberek.tokenization.Token;
import zemberek.tokenization.Token.Type;
public class QuestionClassifier {
public static final int TEST_SIZE = 5000;
private static void collectCoarseData() throws IOException {
Path root = Paths.get("/media/ahmetaa/depo/corpora/open-subtitles-tr-2018-small");
BlockTextLoader corpusProvider = BlockTextLoader.fromDirectory(root);
LinkedHashSet<String> questions = new LinkedHashSet<>();
LinkedHashSet<String> notQuestions = new LinkedHashSet<>();
Random rnd = new Random();
int quesCount = 200_000;
int noQuesCount = 300_000;
for (TextChunk chunk : corpusProvider) {
for (String line : chunk) {
if (line.length() > 80) {
continue;
}
if (line.endsWith("?") && questions.size() < quesCount) {
int r = rnd.nextInt(3);
if (r < 2) {
questions.add("__label__question " + line);
} else {
questions.add("__label__question " + line.replaceAll("\\?", "").trim());
}
} else {
if (notQuestions.size() < noQuesCount) {
notQuestions.add("__label__not_question " + line);
}
}
}
if (questions.size() == quesCount && notQuestions.size() == noQuesCount) {
break;
}
}
Path outQ = Paths.get("/media/ahmetaa/depo/classification/question/coarse/questions-raw");
Files.write(outQ, questions, StandardCharsets.UTF_8);
Path outNotQ = Paths
.get("/media/ahmetaa/depo/classification/question/coarse/not_questions-raw");
Files.write(outNotQ, questions, StandardCharsets.UTF_8);
List<String> all = new ArrayList<>(questions);
all.addAll(notQuestions);
Collections.shuffle(all);
Path allData = Paths.get("/media/ahmetaa/depo/classification/question/coarse/all-raw");
Files.write(allData, all, StandardCharsets.UTF_8);
}
TurkishMorphology morphology;
public static void main(String[] args) throws IOException {
collectCoarseData();
QuestionClassifier experiment = new QuestionClassifier();
String set = "/media/ahmetaa/depo/classification/question/coarse/all-raw";
Path dataPath = Paths.get(set);
Path root = dataPath.getParent();
if (root == null) {
root = Paths.get("");
}
List<String> lines = Files.readAllLines(dataPath, StandardCharsets.UTF_8);
String name = dataPath.toFile().getName();
experiment.dataInfo(lines);
Log.info("------------ Evaluation with raw data ------------------");
experiment.evaluate(dataPath, TEST_SIZE);
Path tokenizedPath = root.resolve(name + ".tokenized");
Log.info("------------ Evaluation with tokenized - lowercase data ------------");
experiment.generateSetTokenized(lines, tokenizedPath);
experiment.evaluate(tokenizedPath, TEST_SIZE);
Path lemmasPath = root.resolve(name + ".lemmas");
Log.info("------------ Evaluation with lemma - lowercase data ------------");
if (!lemmasPath.toFile().exists()) {
experiment.generateSetWithLemmas(lines, lemmasPath);
}
experiment.evaluate(lemmasPath, TEST_SIZE);
}
private void generateSetWithLemmas(List<String> lines, Path lemmasPath) throws IOException {
morphology = TurkishMorphology.createWithDefaults();
List<String> lemmas = lines
.stream()
.map(this::replaceWordsWithLemma)
.map(this::removeNonWords)
.map(s -> s.toLowerCase(Turkish.LOCALE))
.collect(Collectors.toList());
Files.write(lemmasPath, lemmas);
}
private void generateSetTokenized(List<String> lines, Path tokenizedPath) throws IOException {
List<String> tokenized = lines
.stream()
.map(s -> String.join(" ", TurkishTokenizer.DEFAULT.tokenizeToStrings(s)))
.map(this::removeNonWords)
.map(s -> s.toLowerCase(Turkish.LOCALE))
.collect(Collectors.toList());
Files.write(tokenizedPath, tokenized);
}
private String replaceWordsWithLemma(String sentence) {
List<String> tokens = Splitter.on(" ").splitToList(sentence);
// assume first is label. Remove label from sentence for morphological analysis.
String label = tokens.get(0);
tokens = tokens.subList(1, tokens.size());
sentence = String.join(" ", tokens);
if (sentence.length() == 0) {
return sentence;
}
SentenceAnalysis analysis = morphology.analyzeAndDisambiguate(sentence);
List<String> res = new ArrayList<>();
// add label first.
res.add(label);
for (SentenceWordAnalysis e : analysis) {
SingleAnalysis best = e.getBestAnalysis();
if (best.isUnknown()) {
res.add(e.getWordAnalysis().getInput());
continue;
}
List<String> lemmas = best.getLemmas();
res.add(lemmas.get(lemmas.size() - 1));
}
return String.join(" ", res);
}
private String splitWords(String sentence) {
List<String> tokens = Splitter.on(" ").splitToList(sentence);
// assume first is label. Remove label from sentence for morphological analysis.
String label = tokens.get(0);
tokens = tokens.subList(1, tokens.size());
sentence = String.join(" ", tokens);
if (sentence.length() == 0) {
return sentence;
}
SentenceAnalysis analysis = morphology.analyzeAndDisambiguate(sentence);
List<String> res = new ArrayList<>();
// add label first.
res.add(label);
for (SentenceWordAnalysis e : analysis) {
SingleAnalysis best = e.getBestAnalysis();
if (best.isUnknown()) {
res.add(e.getWordAnalysis().getInput());
continue;
}
List<String> lemmas = best.getLemmas();
res.add(lemmas.get(lemmas.size() - 1));
}
return String.join(" ", res);
}
private String removeNonWords(String sentence) {
List<Token> docTokens = TurkishTokenizer.DEFAULT.tokenize(sentence);
List<String> reduced = new ArrayList<>(docTokens.size());
for (Token token : docTokens) {
if (!token.getText().equals("?") && (
token.getType() == Type.PercentNumeral ||
token.getType() == Token.Type.Number ||
token.getType() == Token.Type.Punctuation ||
token.getType() == Token.Type.RomanNumeral ||
token.getType() == Token.Type.Time ||
token.getType() == Token.Type.UnknownWord ||
token.getType() == Token.Type.Unknown)) {
if (!token.getText().contains("__")) {
continue;
}
}
String tokenStr = token.getText();
reduced.add(tokenStr);
}
return String.join(" ", reduced);
}
private void evaluate(Path set, int testSize) throws IOException {
// Create training and test sets.
List<String> lines = Files.readAllLines(set, StandardCharsets.UTF_8);
Path root = set.getParent();
if (root == null) {
root = Paths.get("");
}
String name = set.toFile().getName();
Path train = root.resolve(name + ".train");
Path testPath = root.resolve(name + ".test");
Files.write(train, lines.subList(testSize, lines.size()));
Files.write(testPath, lines.subList(0, testSize));
//Create model if it does not exist.
Path modelPath = root.resolve(name + ".model");
if (!modelPath.toFile().exists()) {
new TrainClassifier().execute(
"-i", train.toString(),
"-o", modelPath.toString(),
"--learningRate", "0.1",
"--epochCount", "50",
"--wordNGrams", "2",
"--applyQuantization",
"--cutOff", "25000"
);
}
Log.info("Testing...");
test(testPath, root.resolve(name + ".predictions"), modelPath);
// test quantized models.
Log.info("Testing with quantized model...");
test(testPath, root.resolve(name + ".predictions.q"), root.resolve(name + ".model.q"));
}
private void test(Path testPath, Path predictionsPath, Path modelPath) {
new EvaluateClassifier().execute(
"-i", testPath.toString(),
"-m", modelPath.toString(),
"-o", predictionsPath.toString(),
"-k", "1"
);
}
void dataInfo(List<String> lines) {
Log.info("Total lines = " + lines.size());
Histogram<String> hist = new Histogram<>();
lines.stream()
.map(s -> s.substring(0, s.indexOf(' ')))
.forEach(hist::add);
Log.info("Categories :");
for (String s : hist.getSortedList()) {
Log.info(s + " " + hist.getCount(s));
}
}
}
| 3,616 |
412 |
typedef void (*fp_t)(int, int);
void add(int a, int b)
{
}
void subtract(int a, int b)
{
}
void multiply(int a, int b)
{
}
int main()
{
// fun_ptr_arr is an array of function pointers
void (*fun_ptr_arr[])(int, int) = {add, subtract, add};
// Multiply should not be added into the value set
fp_t other_fp = multiply;
void (*fun_ptr_arr2[])(int, int) = {multiply, subtract, add};
// the fp removal over-approximates and assumes this could be any pointer in the array
(*fun_ptr_arr[0])(1, 1);
return 0;
}
| 199 |
810 | /*
* SPDX-License-Identifier: Apache-2.0
* Copyright 2018-2020 The Feast 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 feast.serving.service;
import feast.proto.serving.ServingAPIProto;
import feast.proto.serving.TransformationServiceAPIProto.TransformFeaturesRequest;
import feast.proto.serving.TransformationServiceAPIProto.TransformFeaturesResponse;
import feast.proto.serving.TransformationServiceAPIProto.ValueType;
import feast.proto.types.ValueProto;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang3.tuple.Pair;
public interface TransformationService {
/**
* Apply on demand transformations for the specified ODFVs.
*
* @param transformFeaturesRequest proto containing the ODFV references and necessary data
* @return a proto object containing the response
*/
TransformFeaturesResponse transformFeatures(TransformFeaturesRequest transformFeaturesRequest);
/**
* Extract the list of on demand feature sources from a list of ODFV references.
*
* @param onDemandFeatureReferences list of ODFV references to be parsed
* @return list of on demand feature sources
*/
List<ServingAPIProto.FeatureReferenceV2> extractOnDemandFeaturesDependencies(
List<ServingAPIProto.FeatureReferenceV2> onDemandFeatureReferences);
/**
* Process a response from the feature transformation server by augmenting the given lists of
* field maps and status maps with the correct fields from the response.
*
* @param transformFeaturesResponse response to be processed
* @param onDemandFeatureViewName name of ODFV to which the response corresponds
* @param onDemandFeatureStringReferences set of all ODFV references that should be kept
* @param responseBuilder {@link ServingAPIProto.GetOnlineFeaturesResponse.Builder}
*/
void processTransformFeaturesResponse(
TransformFeaturesResponse transformFeaturesResponse,
String onDemandFeatureViewName,
Set<String> onDemandFeatureStringReferences,
ServingAPIProto.GetOnlineFeaturesResponse.Builder responseBuilder);
/**
* Serialize data into Arrow IPC format, to be sent to the Python feature transformation server.
*
* @param values list of field maps to be serialized
* @return the data packaged into a ValueType proto object
*/
ValueType serializeValuesIntoArrowIPC(List<Pair<String, List<ValueProto.Value>>> values);
}
| 782 |
382 | /*
* Copyright (C) 2011 <NAME> <<EMAIL> at g<EMAIL> dot <EMAIL>> and <NAME> <<EMAIL> dot <EMAIL> at <EMAIL> dot <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 org.jongo;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.client.MongoDatabase;
import org.jongo.bson.BsonDBDecoder;
import org.jongo.bson.BsonDBEncoder;
import org.jongo.query.Query;
import static org.jongo.marshall.jackson.JacksonMapper.Builder.jacksonMapper;
public class Jongo {
private final DB database;
private final Mapper mapper;
public Jongo(DB database) {
this(database, jacksonMapper().build());
}
public Jongo(DB database, Mapper mapper) {
this.database = database;
this.mapper = mapper;
}
public MongoCollection getCollection(String name) {
DBCollection dbCollection = database.getCollection(name);
dbCollection.setDBDecoderFactory(BsonDBDecoder.FACTORY);
dbCollection.setDBEncoderFactory(BsonDBEncoder.FACTORY);
dbCollection.setReadConcern(database.getReadConcern());
return new MongoCollection(dbCollection, mapper);
}
public DB getDatabase() {
return database;
}
public Mapper getMapper() {
return mapper;
}
public Query createQuery(String query, Object... parameters) {
return mapper.getQueryFactory().createQuery(query, parameters);
}
public Command runCommand(String query) {
return runCommand(query, new Object[0]);
}
public Command runCommand(String query, Object... parameters) {
return new Command(database, mapper.getUnmarshaller(), mapper.getQueryFactory(), query, parameters);
}
}
| 758 |
971 | #pragma once
#include "loggers/loggers_util.h"
#ifdef NOISEPAGE_USE_LOGGING
namespace noisepage::optimizer {
extern common::SanctionedSharedPtr<spdlog::logger>::Ptr optimizer_logger;
void InitOptimizerLogger();
} // namespace noisepage::optimizer
#define OPTIMIZER_LOG_TRACE(...) ::noisepage::optimizer::optimizer_logger->trace(__VA_ARGS__)
#define OPTIMIZER_LOG_DEBUG(...) ::noisepage::optimizer::optimizer_logger->debug(__VA_ARGS__)
#define OPTIMIZER_LOG_INFO(...) ::noisepage::optimizer::optimizer_logger->info(__VA_ARGS__)
#define OPTIMIZER_LOG_WARN(...) ::noisepage::optimizer::optimizer_logger->warn(__VA_ARGS__)
#define OPTIMIZER_LOG_ERROR(...) ::noisepage::optimizer::optimizer_logger->error(__VA_ARGS__)
#else
#define OPTIMIZER_LOG_TRACE(...) ((void)0)
#define OPTIMIZER_LOG_DEBUG(...) ((void)0)
#define OPTIMIZER_LOG_INFO(...) ((void)0)
#define OPTIMIZER_LOG_WARN(...) ((void)0)
#define OPTIMIZER_LOG_ERROR(...) ((void)0)
#endif
| 384 |
315 | /***************************************************************************
Copyright (c) 2019, Xilinx, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
***************************************************************************/
#ifndef _XF_BOUNDINGBOX_HPP_
#define _XF_BOUNDINGBOX_HPP_
#ifndef __cplusplus
#error C++ is needed to include this header
#endif
typedef unsigned short uint16_t;
typedef unsigned char uchar;
#include "hls_stream.h"
#include "common/xf_common.h"
#include "common/xf_utility.h"
namespace xf{
//template<int NPC>
//bool IsOnBoundary(unsigned int i, unsigned int j, unsigned int r, unsigned int c, unsigned int r_new, unsigned int c_new)
//{
//#pragma HLS INLINE OFF
//
// if((((i==r) || (i==(r_new-1))) && j<c_new && j>=c) || (((j==c) || (j==(c_new-1))) && i<r_new && i>=r))
// {
//
// return 1;
//
// }
// else
// {
// return 0;
//
// }
//
//
//}
/**
* CROP kernel: crops the ROI of an input image and produces an output.
* Input : _src_mat, roi
* Output : _dst_mat
*/
template<int SRC_T, int ROWS, int COLS,int MAX_BOXES,int DEPTH, int NPC, int WORDWIDTH_SRC,
int WORDWIDTH_DST, int COLS_TRIP>
void xFboundingboxkernel(xf::Mat<SRC_T, ROWS, COLS, NPC> & _src_mat, xf::Rect_< int> *roi,xf::Scalar<4,unsigned char > *color ,int num_box,unsigned short height, unsigned short width)
{
#pragma HLS INLINE
XF_SNAME(WORDWIDTH_SRC) val_src=0,val_dst=0;
ap_uint<13> r[MAX_BOXES],c[MAX_BOXES],r_new[MAX_BOXES],c_new[MAX_BOXES];
XF_TNAME(SRC_T,NPC) color_box[MAX_BOXES];
#pragma HLS ARRAY_PARTITION variable=r complete
#pragma HLS ARRAY_PARTITION variable=c complete
#pragma HLS ARRAY_PARTITION variable=r_new complete
#pragma HLS ARRAY_PARTITION variable=r_new complete
#pragma HLS ARRAY_PARTITION variable=color_box complete
ap_uint<2> found=0;
ap_uint<2> modify_pix=0;
int color_idx=0;
ap_uint<13> r_idx=0, r_newidx=0, c_idx=0, c_newidx=0;
for (ap_uint<13> i=0;i<num_box;i++)
{
#pragma HLS LOOP_TRIPCOUNT min=MAX_BOXES max=MAX_BOXES
#pragma HLS UNROLL
/* r[i]=roi[i].x;
r_new[i]=roi[i].x+roi[i].height;
c[i]=roi[i].y ;
c_new[i]=(roi[i].y+roi[i].width);*/
c[i]=roi[i].x;
c_new[i]=roi[i].x+roi[i].width;
r[i]=roi[i].y ;
r_new[i]=(roi[i].y+roi[i].height);
}
for(int i=0;i<(num_box);i++)
{
#pragma HLS LOOP_TRIPCOUNT min=MAX_BOXES max=MAX_BOXES
#pragma HLS PIPELINE
for(int j=0,k=0;j<(XF_CHANNELS(SRC_T,NPC));j++,k+=XF_DTPIXELDEPTH(SRC_T,NPC))
{
#pragma HLS UNROLL
color_box[i].range(k+(XF_DTPIXELDEPTH(SRC_T,NPC)-1),k) = color[i].val[j];
}
}
for(ap_uint<13> b=0; b<num_box; b++)
{
#pragma HLS LOOP_TRIPCOUNT min=MAX_BOXES max=MAX_BOXES
colLoop:
for(ap_uint<13> j = c[b]; j < (c_new[b]); j++)
{
#pragma HLS LOOP_TRIPCOUNT min=COLS max=COLS
#pragma HLS pipeline
_src_mat.write(r[b]*width+j,color_box[b]);
}
for(ap_uint<13> j = c[b]; j < (c_new[b]); j++)
{
#pragma HLS LOOP_TRIPCOUNT min=COLS max=COLS
#pragma HLS pipeline
_src_mat.write((r_new[b]-1)*width+j,color_box[b]);
}
rowLoop1:
for(ap_uint<13> i=(r[b]+1); i < (r_new[b]-1); i++)
{
#pragma HLS LOOP_TRIPCOUNT min=ROWS max=ROWS
#pragma HLS pipeline
// #pragma HLS LOOP_FLATTEN
_src_mat.write(i*width+c[b],color_box[b]);
_src_mat.write(i*width+(c_new[b]-1),color_box[b]);
}
}
}
#pragma SDS data zero_copy("_src_mat.data"[0:"_src_mat.size"], "roi"[0:"num_box"], "color"[0:"num_box"])
template<int SRC_T, int ROWS, int COLS,int MAX_BOXES=1,int NPC=1>
void boundingbox(xf::Mat<SRC_T, ROWS, COLS, NPC> & _src_mat,xf::Rect_<int> *roi ,xf::Scalar<4,unsigned char > *color,int num_box)
{
unsigned short width = _src_mat.cols ;
unsigned short height = _src_mat.rows;
assert((SRC_T == XF_8UC1)||(SRC_T == XF_8UC4) && "Type must be XF_8UC1 or XF_8UC4");
assert((NPC == XF_NPPC1)&& "NPC must be 1, Multipixel parallelism is not supported");
assert(((height <= ROWS ) && (width <= COLS)) && "ROWS and COLS should be greater than input image");
for(int i=0;i<num_box;i++)
{
assert(((roi[i].height <= height ) && (roi[i].width <= width)) && "ROI dimensions should be smaller or equal to the input image");
assert(((roi[i].height > 0 ) && (roi[i].width > 0)) && "ROI dimensions should be greater than 0");
assert(((roi[i].height + roi[i].y <= height ) && (roi[i].width + roi[i].x <= width)) && "ROI area exceeds the input image area");
}
#pragma HLS INLINE
xFboundingboxkernel<SRC_T, ROWS,COLS,MAX_BOXES,XF_DEPTH(SRC_T,NPC),NPC,XF_WORDWIDTH(SRC_T,NPC),XF_WORDWIDTH(SRC_T,NPC),(COLS>>XF_BITSHIFT(NPC))> (_src_mat,roi,color,num_box,height,width);
}
}
#endif
| 2,513 |
6,904 | <gh_stars>1000+
{
"name": "anypixel-udp-manager",
"description": "Application that distributes bundled packets sent from ChromeBridge",
"version": "1.0.0",
"private": true,
"scripts": {
"preinstall": "npm install -g forever",
"start": "forever start --minUptime 1000 --spinSleepTime 1000 udp-manager.js",
"stop": "forever stop udp-manager.js"
}
}
| 134 |
935 | /*
* Copyright 2016-2017 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.cloud.dataflow.server.controller;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.TimeZone;
import org.springframework.batch.core.JobInstance;
import org.springframework.batch.core.launch.NoSuchJobException;
import org.springframework.batch.core.launch.NoSuchJobInstanceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.dataflow.rest.job.JobInstanceExecutions;
import org.springframework.cloud.dataflow.rest.job.TaskJobExecution;
import org.springframework.cloud.dataflow.rest.job.support.TimeUtils;
import org.springframework.cloud.dataflow.rest.resource.JobExecutionResource;
import org.springframework.cloud.dataflow.rest.resource.JobInstanceResource;
import org.springframework.cloud.dataflow.server.service.TaskJobService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PagedResourcesAssembler;
import org.springframework.hateoas.PagedModel;
import org.springframework.hateoas.server.ExposesResourceFor;
import org.springframework.hateoas.server.mvc.RepresentationModelAssemblerSupport;
import org.springframework.http.HttpStatus;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
/**
* Controller for operations on {@link JobInstance}. This includes obtaining Job Instance
* information from the job service.
*
* @author <NAME>
* @author <NAME>
*/
@RestController
@RequestMapping("/jobs/instances")
@ExposesResourceFor(JobInstanceResource.class)
public class JobInstanceController {
private final Assembler jobAssembler = new Assembler();
private final TaskJobService taskJobService;
/**
* Creates a {@code JobInstanceController} that retrieves Job Instance information.
*
* @param taskJobService the {@link TaskJobService} used for retrieving batch instance
* data.
*/
@Autowired
public JobInstanceController(TaskJobService taskJobService) {
Assert.notNull(taskJobService, "taskJobService must not be null");
this.taskJobService = taskJobService;
}
/**
* Return a page-able list of {@link JobInstanceResource} defined jobs.
*
* @param jobName the name of the job
* @param pageable page-able collection of {@link JobInstance}s.
* @param assembler for the {@link JobInstance}s
* @return a list of Job Instance
* @throws NoSuchJobException if the job for jobName specified does not exist.
*/
@RequestMapping(value = "", method = RequestMethod.GET, params = "name")
@ResponseStatus(HttpStatus.OK)
public PagedModel<JobInstanceResource> list(@RequestParam("name") String jobName, Pageable pageable,
PagedResourcesAssembler<JobInstanceExecutions> assembler) throws NoSuchJobException {
List<JobInstanceExecutions> jobInstances = taskJobService.listTaskJobInstancesForJobName(pageable, jobName);
Page<JobInstanceExecutions> page = new PageImpl<>(jobInstances, pageable,
taskJobService.countJobInstances(jobName));
return assembler.toModel(page, jobAssembler);
}
/**
* View the details of a single task instance, specified by id.
*
* @param id the id of the requested {@link JobInstance}
* @return the {@link JobInstance}
* @throws NoSuchJobInstanceException if job instance for the id does not exist.
* @throws NoSuchJobException if the job for the job instance does not exist.
*/
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public JobInstanceResource view(@PathVariable("id") long id) throws NoSuchJobInstanceException, NoSuchJobException {
JobInstanceExecutions jobInstance = taskJobService.getJobInstance(id);
return jobAssembler.toModel(jobInstance);
}
/**
* {@link org.springframework.hateoas.server.ResourceAssembler} implementation that converts
* {@link JobInstance}s to {@link JobInstanceResource}s.
*/
private static class Assembler extends RepresentationModelAssemblerSupport<JobInstanceExecutions, JobInstanceResource> {
private TimeZone timeZone = TimeUtils.getDefaultTimeZone();
public Assembler() {
super(JobInstanceController.class, JobInstanceResource.class);
}
/**
* @param timeZone the timeZone to set
*/
@Autowired(required = false)
@Qualifier("userTimeZone")
public void setTimeZone(TimeZone timeZone) {
this.timeZone = timeZone;
}
@Override
public JobInstanceResource toModel(JobInstanceExecutions jobInstance) {
return createModelWithId(jobInstance.getJobInstance().getInstanceId(), jobInstance);
}
@Override
public JobInstanceResource instantiateModel(JobInstanceExecutions jobInstance) {
List<JobExecutionResource> jobExecutions = new ArrayList<>();
for (TaskJobExecution taskJobExecution : jobInstance.getTaskJobExecutions()) {
jobExecutions.add(new JobExecutionResource(taskJobExecution, timeZone));
}
jobExecutions = Collections.unmodifiableList(jobExecutions);
return new JobInstanceResource(jobInstance.getJobInstance().getJobName(),
jobInstance.getJobInstance().getInstanceId(), jobExecutions);
}
}
}
| 1,803 |
5,250 | <filename>modules/flowable-event-registry/src/main/java/org/flowable/eventregistry/impl/model/OutboundChannelDefinitionBuilderImpl.java
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flowable.eventregistry.impl.model;
import org.flowable.eventregistry.api.EventDeployment;
import org.flowable.eventregistry.api.EventRepositoryService;
import org.flowable.eventregistry.api.model.OutboundChannelModelBuilder;
import org.flowable.eventregistry.json.converter.ChannelJsonConverter;
import org.flowable.eventregistry.model.ChannelModel;
import org.flowable.eventregistry.model.DelegateExpressionOutboundChannelModel;
import org.flowable.eventregistry.model.JmsOutboundChannelModel;
import org.flowable.eventregistry.model.KafkaOutboundChannelModel;
import org.flowable.eventregistry.model.OutboundChannelModel;
import org.flowable.eventregistry.model.RabbitOutboundChannelModel;
/**
* @author <NAME>
* @author <NAME>
*/
public class OutboundChannelDefinitionBuilderImpl implements OutboundChannelModelBuilder {
protected EventRepositoryService eventRepository;
protected ChannelJsonConverter channelJsonConverter;
protected OutboundChannelModel channelDefinition;
protected String deploymentName;
protected String resourceName;
protected String category;
protected String parentDeploymentId;
protected String deploymentTenantId;
protected String key;
public OutboundChannelDefinitionBuilderImpl(EventRepositoryService eventRepository, ChannelJsonConverter channelJsonConverter) {
this.eventRepository = eventRepository;
this.channelJsonConverter = channelJsonConverter;
}
@Override
public OutboundChannelModelBuilder key(String key) {
this.key = key;
return this;
}
@Override
public OutboundChannelModelBuilder deploymentName(String deploymentName) {
this.deploymentName = deploymentName;
return this;
}
@Override
public OutboundChannelModelBuilder resourceName(String resourceName) {
this.resourceName = resourceName;
return this;
}
@Override
public OutboundChannelModelBuilder category(String category) {
this.category = category;
return this;
}
@Override
public OutboundChannelModelBuilder parentDeploymentId(String parentDeploymentId) {
this.parentDeploymentId = parentDeploymentId;
return this;
}
@Override
public OutboundChannelModelBuilder deploymentTenantId(String deploymentTenantId) {
this.deploymentTenantId = deploymentTenantId;
return this;
}
@Override
public OutboundEventProcessingPipelineBuilder channelAdapter(String delegateExpression) {
DelegateExpressionOutboundChannelModel channelDefinition = new DelegateExpressionOutboundChannelModel();
channelDefinition.setAdapterDelegateExpression(delegateExpression);
this.channelDefinition = channelDefinition;
return new OutboundEventProcessingPipelineBuilderImpl(this, channelDefinition);
}
@Override
public OutboundJmsChannelBuilder jmsChannelAdapter(String destination) {
JmsOutboundChannelModel channelDefinition = new JmsOutboundChannelModel();
channelDefinition.setDestination(destination);
this.channelDefinition = channelDefinition;
this.channelDefinition.setKey(key);
return new OutboundJmsChannelBuilderImpl(eventRepository, this, channelDefinition);
}
@Override
public OutboundRabbitChannelBuilder rabbitChannelAdapter(String routingKey) {
RabbitOutboundChannelModel channelDefinition = new RabbitOutboundChannelModel();
channelDefinition.setRoutingKey(routingKey);
this.channelDefinition = channelDefinition;
this.channelDefinition.setKey(key);
return new OutboundRabbitChannelBuilderImpl(eventRepository, this, channelDefinition);
}
@Override
public OutboundKafkaChannelBuilder kafkaChannelAdapter(String topic) {
KafkaOutboundChannelModel channelDefinition = new KafkaOutboundChannelModel();
channelDefinition.setTopic(topic);
this.channelDefinition = channelDefinition;
this.channelDefinition.setKey(key);
return new OutboundKafkaChannelBuilderImpl(eventRepository, this, channelDefinition);
}
@Override
public EventDeployment deploy() {
if (resourceName == null) {
resourceName = "outbound-" + key + ".channel";
}
ChannelModel channelModel = buildChannelModel();
EventDeployment eventDeployment = eventRepository.createDeployment()
.name(deploymentName)
.addChannelDefinition(resourceName, channelJsonConverter.convertToJson(channelModel))
.category(category)
.parentDeploymentId(parentDeploymentId)
.tenantId(deploymentTenantId)
.deploy();
return eventDeployment;
}
public OutboundChannelModel buildChannelModel() {
OutboundChannelModel outboundChannelModel;
if (this.channelDefinition == null) {
outboundChannelModel = new OutboundChannelModel();
} else {
outboundChannelModel = this.channelDefinition;
}
outboundChannelModel.setKey(key);
return outboundChannelModel;
}
public static class OutboundJmsChannelBuilderImpl implements OutboundJmsChannelBuilder {
protected final EventRepositoryService eventRepositoryService;
protected final OutboundChannelDefinitionBuilderImpl outboundChannelDefinitionBuilder;
protected JmsOutboundChannelModel jmsChannel;
public OutboundJmsChannelBuilderImpl(EventRepositoryService eventRepositoryService, OutboundChannelDefinitionBuilderImpl outboundChannelDefinitionBuilder,
JmsOutboundChannelModel jmsChannel) {
this.eventRepositoryService = eventRepositoryService;
this.outboundChannelDefinitionBuilder = outboundChannelDefinitionBuilder;
this.jmsChannel = jmsChannel;
}
@Override
public OutboundEventProcessingPipelineBuilder eventProcessingPipeline() {
return new OutboundEventProcessingPipelineBuilderImpl(outboundChannelDefinitionBuilder, jmsChannel);
}
}
public static class OutboundRabbitChannelBuilderImpl implements OutboundRabbitChannelBuilder {
protected final EventRepositoryService eventRepositoryService;
protected final OutboundChannelDefinitionBuilderImpl outboundChannelDefinitionBuilder;
protected RabbitOutboundChannelModel rabbitChannel;
public OutboundRabbitChannelBuilderImpl(EventRepositoryService eventRepositoryService, OutboundChannelDefinitionBuilderImpl outboundChannelDefinitionBuilder,
RabbitOutboundChannelModel rabbitChannel) {
this.eventRepositoryService = eventRepositoryService;
this.outboundChannelDefinitionBuilder = outboundChannelDefinitionBuilder;
this.rabbitChannel = rabbitChannel;
}
@Override
public OutboundRabbitChannelBuilder exchange(String exchange) {
rabbitChannel.setExchange(exchange);
return this;
}
@Override
public OutboundEventProcessingPipelineBuilder eventProcessingPipeline() {
return new OutboundEventProcessingPipelineBuilderImpl(outboundChannelDefinitionBuilder, rabbitChannel);
}
}
public static class OutboundKafkaChannelBuilderImpl implements OutboundKafkaChannelBuilder {
protected final EventRepositoryService eventRepositoryService;
protected final OutboundChannelDefinitionBuilderImpl outboundChannelDefinitionBuilder;
protected KafkaOutboundChannelModel kafkaChannel;
public OutboundKafkaChannelBuilderImpl(EventRepositoryService eventRepositoryService, OutboundChannelDefinitionBuilderImpl outboundChannelDefinitionBuilder,
KafkaOutboundChannelModel kafkaChannel) {
this.eventRepositoryService = eventRepositoryService;
this.outboundChannelDefinitionBuilder = outboundChannelDefinitionBuilder;
this.kafkaChannel = kafkaChannel;
}
@Override
public OutboundKafkaChannelBuilder recordKey(String key) {
kafkaChannel.setRecordKey(key);
return this;
}
@Override
public OutboundEventProcessingPipelineBuilder eventProcessingPipeline() {
return new OutboundEventProcessingPipelineBuilderImpl(outboundChannelDefinitionBuilder, kafkaChannel);
}
}
public static class OutboundEventProcessingPipelineBuilderImpl implements OutboundEventProcessingPipelineBuilder {
protected OutboundChannelDefinitionBuilderImpl outboundChannelDefinitionBuilder;
protected OutboundChannelModel outboundChannel;
public OutboundEventProcessingPipelineBuilderImpl(OutboundChannelDefinitionBuilderImpl outboundChannelDefinitionBuilder,
OutboundChannelModel outboundChannel) {
this.outboundChannelDefinitionBuilder = outboundChannelDefinitionBuilder;
this.outboundChannel = outboundChannel;
}
@Override
public OutboundChannelModelBuilder jsonSerializer() {
this.outboundChannel.setSerializerType("json");
return outboundChannelDefinitionBuilder;
}
@Override
public OutboundChannelModelBuilder xmlSerializer() {
this.outboundChannel.setSerializerType("xml");
return outboundChannelDefinitionBuilder;
}
@Override
public OutboundChannelModelBuilder delegateExpressionSerializer(String delegateExpression) {
this.outboundChannel.setSerializerType("expression");
this.outboundChannel.setSerializerDelegateExpression(delegateExpression);
return outboundChannelDefinitionBuilder;
}
@Override
public OutboundChannelModelBuilder eventProcessingPipeline(String delegateExpression) {
this.outboundChannel.setPipelineDelegateExpression(delegateExpression);
return outboundChannelDefinitionBuilder;
}
}
}
| 3,672 |
2,827 | # Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
import torch
from torch.autograd import grad
from pyro.ops.linalg import eig_3d, rinverse
from pyro.util import warn_if_nan
def newton_step(loss, x, trust_radius=None):
"""
Performs a Newton update step to minimize loss on a batch of variables,
optionally constraining to a trust region [1].
This is especially usful because the final solution of newton iteration
is differentiable wrt the inputs, even when all but the final ``x`` is
detached, due to this method's quadratic convergence [2]. ``loss`` must be
twice-differentiable as a function of ``x``. If ``loss`` is ``2+d``-times
differentiable, then the return value of this function is ``d``-times
differentiable.
When ``loss`` is interpreted as a negative log probability density, then
the return values ``mode,cov`` of this function can be used to construct a
Laplace approximation ``MultivariateNormal(mode,cov)``.
.. warning:: Take care to detach the result of this function when used in
an optimization loop. If you forget to detach the result of this
function during optimization, then backprop will propagate through
the entire iteration process, and worse will compute two extra
derivatives for each step.
Example use inside a loop::
x = torch.zeros(1000, 2) # arbitrary initial value
for step in range(100):
x = x.detach() # block gradients through previous steps
x.requires_grad = True # ensure loss is differentiable wrt x
loss = my_loss_function(x)
x = newton_step(loss, x, trust_radius=1.0)
# the final x is still differentiable
[1] <NAME>. Iciam. Vol. 99. 2000.
"A review of trust region algorithms for optimization."
ftp://ftp.cc.ac.cn/pub/yyx/papers/p995.pdf
[2] <NAME>. Optimization Methods and Software 3.4 (1994)
"Reverse accumulation and attractive fixed points."
http://uhra.herts.ac.uk/bitstream/handle/2299/4338/903839.pdf
:param torch.Tensor loss: A scalar function of ``x`` to be minimized.
:param torch.Tensor x: A dependent variable of shape ``(N, D)``
where ``N`` is the batch size and ``D`` is a small number.
:param float trust_radius: An optional trust region trust_radius. The
updated value ``mode`` of this function will be within
``trust_radius`` of the input ``x``.
:return: A pair ``(mode, cov)`` where ``mode`` is an updated tensor
of the same shape as the original value ``x``, and ``cov`` is an
esitmate of the covariance DxD matrix with
``cov.shape == x.shape[:-1] + (D,D)``.
:rtype: tuple
"""
if x.dim() < 1:
raise ValueError(
"Expected x to have at least one dimension, actual shape {}".format(x.shape)
)
dim = x.shape[-1]
if dim == 1:
return newton_step_1d(loss, x, trust_radius)
elif dim == 2:
return newton_step_2d(loss, x, trust_radius)
elif dim == 3:
return newton_step_3d(loss, x, trust_radius)
else:
raise NotImplementedError("newton_step_nd is not implemented")
def newton_step_1d(loss, x, trust_radius=None):
"""
Performs a Newton update step to minimize loss on a batch of 1-dimensional
variables, optionally regularizing to constrain to a trust region.
See :func:`newton_step` for details.
:param torch.Tensor loss: A scalar function of ``x`` to be minimized.
:param torch.Tensor x: A dependent variable with rightmost size of 1.
:param float trust_radius: An optional trust region trust_radius. The
updated value ``mode`` of this function will be within
``trust_radius`` of the input ``x``.
:return: A pair ``(mode, cov)`` where ``mode`` is an updated tensor
of the same shape as the original value ``x``, and ``cov`` is an
esitmate of the covariance 1x1 matrix with
``cov.shape == x.shape[:-1] + (1,1)``.
:rtype: tuple
"""
if loss.shape != ():
raise ValueError(
"Expected loss to be a scalar, actual shape {}".format(loss.shape)
)
if x.dim() < 1 or x.shape[-1] != 1:
raise ValueError(
"Expected x to have rightmost size 1, actual shape {}".format(x.shape)
)
# compute derivatives
g = grad(loss, [x], create_graph=True)[0]
H = grad(g.sum(), [x], create_graph=True)[0]
warn_if_nan(g, "g")
warn_if_nan(H, "H")
Hinv = H.clamp(min=1e-8).reciprocal()
dx = -g * Hinv
dx[~(dx == dx)] = 0
if trust_radius is not None:
dx.clamp_(min=-trust_radius, max=trust_radius)
# apply update
x_new = x.detach() + dx
assert x_new.shape == x.shape
return x_new, Hinv.unsqueeze(-1)
def newton_step_2d(loss, x, trust_radius=None):
"""
Performs a Newton update step to minimize loss on a batch of 2-dimensional
variables, optionally regularizing to constrain to a trust region.
See :func:`newton_step` for details.
:param torch.Tensor loss: A scalar function of ``x`` to be minimized.
:param torch.Tensor x: A dependent variable with rightmost size of 2.
:param float trust_radius: An optional trust region trust_radius. The
updated value ``mode`` of this function will be within
``trust_radius`` of the input ``x``.
:return: A pair ``(mode, cov)`` where ``mode`` is an updated tensor
of the same shape as the original value ``x``, and ``cov`` is an
esitmate of the covariance 2x2 matrix with
``cov.shape == x.shape[:-1] + (2,2)``.
:rtype: tuple
"""
if loss.shape != ():
raise ValueError(
"Expected loss to be a scalar, actual shape {}".format(loss.shape)
)
if x.dim() < 1 or x.shape[-1] != 2:
raise ValueError(
"Expected x to have rightmost size 2, actual shape {}".format(x.shape)
)
# compute derivatives
g = grad(loss, [x], create_graph=True)[0]
H = torch.stack(
[
grad(g[..., 0].sum(), [x], create_graph=True)[0],
grad(g[..., 1].sum(), [x], create_graph=True)[0],
],
-1,
)
assert g.shape[-1:] == (2,)
assert H.shape[-2:] == (2, 2)
warn_if_nan(g, "g")
warn_if_nan(H, "H")
if trust_radius is not None:
# regularize to keep update within ball of given trust_radius
detH = H[..., 0, 0] * H[..., 1, 1] - H[..., 0, 1] * H[..., 1, 0]
mean_eig = (H[..., 0, 0] + H[..., 1, 1]) / 2
min_eig = mean_eig - (mean_eig ** 2 - detH).clamp(min=0).sqrt()
regularizer = (g.pow(2).sum(-1).sqrt() / trust_radius - min_eig).clamp_(
min=1e-8
)
warn_if_nan(regularizer, "regularizer")
H = H + regularizer.unsqueeze(-1).unsqueeze(-1) * torch.eye(
2, dtype=H.dtype, device=H.device
)
# compute newton update
Hinv = rinverse(H, sym=True)
warn_if_nan(Hinv, "Hinv")
# apply update
x_new = x.detach() - (Hinv * g.unsqueeze(-2)).sum(-1)
assert x_new.shape == x.shape
return x_new, Hinv
def newton_step_3d(loss, x, trust_radius=None):
"""
Performs a Newton update step to minimize loss on a batch of 3-dimensional
variables, optionally regularizing to constrain to a trust region.
See :func:`newton_step` for details.
:param torch.Tensor loss: A scalar function of ``x`` to be minimized.
:param torch.Tensor x: A dependent variable with rightmost size of 2.
:param float trust_radius: An optional trust region trust_radius. The
updated value ``mode`` of this function will be within
``trust_radius`` of the input ``x``.
:return: A pair ``(mode, cov)`` where ``mode`` is an updated tensor
of the same shape as the original value ``x``, and ``cov`` is an
esitmate of the covariance 3x3 matrix with
``cov.shape == x.shape[:-1] + (3,3)``.
:rtype: tuple
"""
if loss.shape != ():
raise ValueError(
"Expected loss to be a scalar, actual shape {}".format(loss.shape)
)
if x.dim() < 1 or x.shape[-1] != 3:
raise ValueError(
"Expected x to have rightmost size 3, actual shape {}".format(x.shape)
)
# compute derivatives
g = grad(loss, [x], create_graph=True)[0]
H = torch.stack(
[
grad(g[..., 0].sum(), [x], create_graph=True)[0],
grad(g[..., 1].sum(), [x], create_graph=True)[0],
grad(g[..., 2].sum(), [x], create_graph=True)[0],
],
-1,
)
assert g.shape[-1:] == (3,)
assert H.shape[-2:] == (3, 3)
warn_if_nan(g, "g")
warn_if_nan(H, "H")
if trust_radius is not None:
# regularize to keep update within ball of given trust_radius
# calculate eigenvalues of symmetric matrix
min_eig, _, _ = eig_3d(H)
regularizer = (g.pow(2).sum(-1).sqrt() / trust_radius - min_eig).clamp_(
min=1e-8
)
warn_if_nan(regularizer, "regularizer")
H = H + regularizer.unsqueeze(-1).unsqueeze(-1) * torch.eye(
3, dtype=H.dtype, device=H.device
)
# compute newton update
Hinv = rinverse(H, sym=True)
warn_if_nan(Hinv, "Hinv")
# apply update
x_new = x.detach() - (Hinv * g.unsqueeze(-2)).sum(-1)
assert x_new.shape == x.shape, "{} {}".format(x_new.shape, x.shape)
return x_new, Hinv
| 3,926 |
1,808 | <gh_stars>1000+
package calendar;
import java.util.List;
import java.io.File;
import java.util.ArrayList;
import org.apache.thrift.TException;
import org.apache.thrift.async.AsyncMethodCallback;
import thrift.*;
/**
* Implementation of the calendar interface. A client request to any
* method defined in the thrift file is handled by the
* corresponding method here.
*/
public class CAServiceHandler {
public static void print(String s) {
synchronized (System.out) {
System.out.println(s);
}
}
public static class SyncCAServiceHandler implements LucidaService.Iface {
/** Text processor for parsing the input query. */
private TextProcessor TEXT_PROCESSOR;
/** Constructs the handler and initializes its TextProcessor
* object.
*/
public SyncCAServiceHandler() {
TEXT_PROCESSOR = new TextProcessor();
}
/**
* Do nothing.
* @param LUCID ID of Lucida user
* @param spec spec
*/
@Override
public void create(String LUCID, QuerySpec spec) {}
/**
* Do nothing.
* @param LUCID ID of Lucida user
* @param knowledge knowledge
*/
@Override
public void learn(String LUCID, QuerySpec knowledge) {}
/**
* Extracts a query string and returns the answer from TextProcessor.
* @param LUCID ID of Lucida user
* @param query query
*/
@Override
public String infer(String LUCID, QuerySpec query) {
print("@@@@@ Infer; User: " + LUCID);
if (query.content.isEmpty() || query.content.get(0).data.isEmpty()) {
throw new IllegalArgumentException();
}
String query_data = query.content.get(0).data.get(0);
print("Asking: " + query_data);
String[] time_interval = TEXT_PROCESSOR.parse(query_data);
print("Result " + time_interval[0] + " " + time_interval[1]);
return time_interval[0] + " " + time_interval[1];
}
}
public static class AsyncCAServiceHandler implements LucidaService.AsyncIface {
private SyncCAServiceHandler handler;
public AsyncCAServiceHandler() {
handler = new SyncCAServiceHandler();
}
@Override
public void create(String LUCID, QuerySpec spec, AsyncMethodCallback resultHandler)
throws TException {
print("Async Create");
}
@Override
public void learn(String LUCID, QuerySpec knowledge, AsyncMethodCallback resultHandler)
throws TException {
print("Async Learn");
}
@Override
public void infer(String LUCID, QuerySpec query, AsyncMethodCallback resultHandler)
throws TException {
print("Async Infer");
resultHandler.onComplete(handler.infer(LUCID, query));
}
}
}
| 932 |
2,216 | model = dict(
type='VoteNet',
backbone=dict(
type='PointNet2SASSG',
in_channels=4,
num_points=(2048, 1024, 512, 256),
radius=(0.2, 0.4, 0.8, 1.2),
num_samples=(64, 32, 16, 16),
sa_channels=((64, 64, 128), (128, 128, 256), (128, 128, 256),
(128, 128, 256)),
fp_channels=((256, 256), (256, 256)),
norm_cfg=dict(type='BN2d'),
sa_cfg=dict(
type='PointSAModule',
pool_mod='max',
use_xyz=True,
normalize_xyz=True)),
bbox_head=dict(
type='VoteHead',
vote_module_cfg=dict(
in_channels=256,
vote_per_seed=1,
gt_per_seed=3,
conv_channels=(256, 256),
conv_cfg=dict(type='Conv1d'),
norm_cfg=dict(type='BN1d'),
norm_feats=True,
vote_loss=dict(
type='ChamferDistance',
mode='l1',
reduction='none',
loss_dst_weight=10.0)),
vote_aggregation_cfg=dict(
type='PointSAModule',
num_point=256,
radius=0.3,
num_sample=16,
mlp_channels=[256, 128, 128, 128],
use_xyz=True,
normalize_xyz=True),
pred_layer_cfg=dict(
in_channels=128, shared_conv_channels=(128, 128), bias=True),
conv_cfg=dict(type='Conv1d'),
norm_cfg=dict(type='BN1d'),
objectness_loss=dict(
type='CrossEntropyLoss',
class_weight=[0.2, 0.8],
reduction='sum',
loss_weight=5.0),
center_loss=dict(
type='ChamferDistance',
mode='l2',
reduction='sum',
loss_src_weight=10.0,
loss_dst_weight=10.0),
dir_class_loss=dict(
type='CrossEntropyLoss', reduction='sum', loss_weight=1.0),
dir_res_loss=dict(
type='SmoothL1Loss', reduction='sum', loss_weight=10.0),
size_class_loss=dict(
type='CrossEntropyLoss', reduction='sum', loss_weight=1.0),
size_res_loss=dict(
type='SmoothL1Loss', reduction='sum', loss_weight=10.0 / 3.0),
semantic_loss=dict(
type='CrossEntropyLoss', reduction='sum', loss_weight=1.0)),
# model training and testing settings
train_cfg=dict(
pos_distance_thr=0.3, neg_distance_thr=0.6, sample_mod='vote'),
test_cfg=dict(
sample_mod='seed',
nms_thr=0.25,
score_thr=0.05,
per_class_proposal=True))
| 1,444 |
403 | """ NIPAP REST
==============
This module contains the actual functions presented over the REST API. All
functions are quite thin and mostly wrap around the functionalty provided by
the backend module.
"""
import datetime
import logging
import time
import pytz
import json
from functools import wraps
from flask import Flask, request, Response, got_request_exception, jsonify
from flask_restful import Resource, Api, abort
from backend import Nipap, NipapError
import nipap
from authlib import AuthFactory, AuthError
def setup(app):
api = Api(app, prefix="/rest/v1")
api.add_resource(NipapPrefixRest, "/prefixes")
return app
def combine_request_args():
args = {}
request_authoritative_source = request.headers.get('NIPAP-Authoritative-Source')
request_nipap_username = request.headers.get('NIPAP-Username')
request_nipap_fullname = request.headers.get('NIPAP-Full-Name')
request_body = request.json
request_queries = request.args.to_dict()
if request_authoritative_source:
authoritative_source = { 'auth':{'authoritative_source': request_authoritative_source}}
args.update(authoritative_source)
if request_nipap_username:
args['auth'].update({'username': request_nipap_username})
if request_nipap_fullname:
args['auth'].update({'full_name': request_nipap_fullname})
if request_queries and request.method == 'POST':
temp_args = {}
if request_queries.get("fromPoolName"):
from_pool_name = {"from-pool": {"name": str(request_queries.get("fromPoolName"))}}
family = {"family": request_queries.get("family")}
prefix_length = {"prefix_length": int(request_queries.get("prefixLength"))}
temp_args.update(from_pool_name)
temp_args.update(family)
temp_args.update(prefix_length)
else:
from_prefix = {"from-prefix": [request_queries.get("fromPrefix")]}
prefix_length = {"prefix_length": request_queries.get("prefixLength")}
temp_args.update(from_prefix)
temp_args.update(prefix_length)
args.update({'args': temp_args})
elif request_queries and not request.method == 'POST':
args.update({'prefix': request_queries})
if request_body:
args['attr'] = request_body
return args
def _mangle_prefix(res):
""" Mangle prefix result
"""
# fugly cast from large numbers to string to deal with XML-RPC
res['total_addresses'] = unicode(res['total_addresses'])
res['used_addresses'] = unicode(res['used_addresses'])
res['free_addresses'] = unicode(res['free_addresses'])
# postgres has notion of infinite while datetime hasn't, if expires
# is equal to the max datetime we assume it is infinity and instead
# represent that as None
if res['expires'].tzinfo is None:
res['expires'] = pytz.utc.localize(res['expires'])
if res['expires'] == pytz.utc.localize(datetime.datetime.max):
res['expires'] = None
# cast of datetime so that JSON is in correct format
res['added'] = res['added'].isoformat()
res['last_modified'] = res['last_modified'].isoformat()
return res
def authenticate():
""" Sends a 401 response that enables basic auth
"""
return Response(
'Could not verify your access level for that URL.\n'
'You have to login with proper credentials', 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'})
def requires_auth(f):
""" Class decorator for REST functions that requires auth
"""
@wraps(f)
def decorated(self, *args, **kwargs):
"""
"""
# small hack
args = args + (combine_request_args(),)
# Fetch auth options from args
auth_options = {}
nipap_args = {}
# validate function arguments
if len(args) == 1:
nipap_args = args[0]
else:
self.logger.debug("Malformed request: got %d parameters" % len(args))
abort(401, error={"code": 401, "message": "Malformed request: got %d parameters" % len(args)})
if type(nipap_args) != dict:
self.logger.debug("Function argument is not struct")
abort(401, error={"code": 401, "message": "Function argument is not struct"})
# fetch auth options
try:
auth_options = nipap_args['auth']
if type(auth_options) is not dict:
raise ValueError()
except (KeyError, ValueError):
self.logger.debug("Missing/invalid authentication options in request.")
abort(401, error={"code": 401, "message": "Missing/invalid authentication options in request."})
# fetch authoritative source
try:
auth_source = auth_options['authoritative_source']
except KeyError:
self.logger.debug("Missing authoritative source in auth options.")
abort(401, error={"code": 401, "message": "Missing authoritative source in auth options."})
if not request.authorization:
return authenticate()
# init AuthFacory()
af = AuthFactory()
auth = af.get_auth(
request.authorization.username,
request.authorization.password,
auth_source, auth_options or {})
# authenticated?
if not auth.authenticate():
self.logger.debug("Incorrect username or password.")
abort(401, error={"code": 401, "message": "Incorrect username or password"})
# Replace auth options in API call arguments with auth object
new_args = dict(args[0])
new_args['auth'] = auth
return f(self, *(new_args,), **kwargs)
return decorated
class NipapPrefixRest(Resource):
def __init__(self):
self.nip = Nipap()
self.logger = logging.getLogger()
@requires_auth
def get(self, args):
try:
result = self.nip.list_prefix(
args.get('auth'), args.get('prefix') or {})
# mangle result
for prefix in result:
prefix = _mangle_prefix(prefix)
result = jsonify(result)
return result
except (AuthError, NipapError) as exc:
self.logger.debug(unicode(exc))
abort(500, error={"code": 500, "message": exc})
@requires_auth
def post(self, args):
try:
result = self.nip.add_prefix(
args.get('auth'), args.get('attr'), args.get('args'))
result["free_addresses"] = str(result.get("free_addresses"))
result["total_addresses"] = str(result.get("total_addresses"))
result["added"] = result.get("added").isoformat()
result["expires"] = result.get("expires").isoformat()
result["last_modified"] = result.get("last_modified").isoformat()
result["used_addresses"] = str(result.get("used_addresses"))
result = jsonify(result)
return result
except (AuthError, NipapError) as exc:
self.logger.debug(unicode(exc))
abort(500, error={"code": 500, "message": str(exc)})
@requires_auth
def delete(self, args):
try:
# as of now remove_prefix doesn't return any values
self.nip.remove_prefix(args.get('auth'), args.get('prefix'))
return jsonify(args.get('prefix'))
except (AuthError, NipapError) as exc:
self.logger.debug(unicode(exc))
abort(500, error={"code": 500, "message": exc})
| 3,258 |
1,008 | /**
* Copyright 2010 - 2021 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.exodus.entitystore.custom;
import org.jetbrains.annotations.NotNull;
public final class ComparablePair<F extends Comparable<F>, S extends Comparable<S>> implements Comparable<ComparablePair<F, S>> {
final F first;
final S second;
public ComparablePair(@NotNull final F first, @NotNull final S second) {
this.first = first;
this.second = second;
}
@Override
public int compareTo(@NotNull final ComparablePair<F, S> o) {
final int result = first.compareTo(o.first);
return result != 0 ? result : second.compareTo(o.second);
}
@Override
public int hashCode() {
return first.hashCode() ^ second.hashCode();
}
@SuppressWarnings("EqualsWhichDoesntCheckParameterClass")
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
final ComparablePair<F, S> pair = (ComparablePair<F, S>) obj;
return first.equals(pair.first) && second.equals(pair.second);
}
@Override
public String toString() {
return "ComparablePair{" + "first=" + first + ", second=" + second + '}';
}
}
| 618 |
852 | <gh_stars>100-1000
import FWCore.ParameterSet.Config as cms
fileNames = cms.untracked.vstring(
'/store/data/Commissioning09/Cosmics/RAW/v2/000/102/169/F6566668-4267-DE11-8354-001D09F2983F.root',
)
| 97 |
2,151 | <reponame>zipated/src<gh_stars>1000+
// 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 "net/dns/dns_session.h"
#include <list>
#include <memory>
#include <string>
#include <utility>
#include "base/bind.h"
#include "base/memory/ptr_util.h"
#include "base/rand_util.h"
#include "net/base/ip_address.h"
#include "net/dns/dns_protocol.h"
#include "net/dns/dns_socket_pool.h"
#include "net/log/net_log_source.h"
#include "net/socket/socket_performance_watcher.h"
#include "net/socket/socket_test_util.h"
#include "net/socket/ssl_client_socket.h"
#include "net/socket/stream_socket.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace net {
namespace {
class TestClientSocketFactory : public ClientSocketFactory {
public:
~TestClientSocketFactory() override;
std::unique_ptr<DatagramClientSocket> CreateDatagramClientSocket(
DatagramSocket::BindType bind_type,
NetLog* net_log,
const NetLogSource& source) override;
std::unique_ptr<TransportClientSocket> CreateTransportClientSocket(
const AddressList& addresses,
std::unique_ptr<SocketPerformanceWatcher>,
NetLog*,
const NetLogSource&) override {
NOTIMPLEMENTED();
return nullptr;
}
std::unique_ptr<SSLClientSocket> CreateSSLClientSocket(
std::unique_ptr<ClientSocketHandle> transport_socket,
const HostPortPair& host_and_port,
const SSLConfig& ssl_config,
const SSLClientSocketContext& context) override {
NOTIMPLEMENTED();
return std::unique_ptr<SSLClientSocket>();
}
std::unique_ptr<ProxyClientSocket> CreateProxyClientSocket(
std::unique_ptr<ClientSocketHandle> transport_socket,
const std::string& user_agent,
const HostPortPair& endpoint,
HttpAuthController* http_auth_controller,
bool tunnel,
bool using_spdy,
NextProto negotiated_protocol,
bool is_https_proxy,
const NetworkTrafficAnnotationTag& traffic_annotation) override {
NOTIMPLEMENTED();
return nullptr;
}
void ClearSSLSessionCache() override { NOTIMPLEMENTED(); }
private:
std::list<std::unique_ptr<SocketDataProvider>> data_providers_;
};
struct PoolEvent {
enum { ALLOCATE, FREE } action;
unsigned server_index;
};
class DnsSessionTest : public testing::Test {
public:
void OnSocketAllocated(unsigned server_index);
void OnSocketFreed(unsigned server_index);
protected:
void Initialize(unsigned num_servers);
std::unique_ptr<DnsSession::SocketLease> Allocate(unsigned server_index);
bool DidAllocate(unsigned server_index);
bool DidFree(unsigned server_index);
bool NoMoreEvents();
DnsConfig config_;
std::unique_ptr<TestClientSocketFactory> test_client_socket_factory_;
scoped_refptr<DnsSession> session_;
NetLogSource source_;
private:
bool ExpectEvent(const PoolEvent& event);
std::list<PoolEvent> events_;
};
class MockDnsSocketPool : public DnsSocketPool {
public:
MockDnsSocketPool(ClientSocketFactory* factory, DnsSessionTest* test)
: DnsSocketPool(factory, base::Bind(&base::RandInt)), test_(test) {}
~MockDnsSocketPool() override = default;
void Initialize(const std::vector<IPEndPoint>* nameservers,
NetLog* net_log) override {
InitializeInternal(nameservers, net_log);
}
std::unique_ptr<DatagramClientSocket> AllocateSocket(
unsigned server_index) override {
test_->OnSocketAllocated(server_index);
return CreateConnectedSocket(server_index);
}
void FreeSocket(unsigned server_index,
std::unique_ptr<DatagramClientSocket> socket) override {
test_->OnSocketFreed(server_index);
}
private:
DnsSessionTest* test_;
};
void DnsSessionTest::Initialize(unsigned num_servers) {
CHECK(num_servers < 256u);
config_.nameservers.clear();
for (unsigned char i = 0; i < num_servers; ++i) {
IPEndPoint dns_endpoint(IPAddress(192, 168, 1, i),
dns_protocol::kDefaultPort);
config_.nameservers.push_back(dns_endpoint);
}
test_client_socket_factory_.reset(new TestClientSocketFactory());
DnsSocketPool* dns_socket_pool =
new MockDnsSocketPool(test_client_socket_factory_.get(), this);
session_ =
new DnsSession(config_, std::unique_ptr<DnsSocketPool>(dns_socket_pool),
base::Bind(&base::RandInt), NULL /* NetLog */);
events_.clear();
}
std::unique_ptr<DnsSession::SocketLease> DnsSessionTest::Allocate(
unsigned server_index) {
return session_->AllocateSocket(server_index, source_);
}
bool DnsSessionTest::DidAllocate(unsigned server_index) {
PoolEvent expected_event = { PoolEvent::ALLOCATE, server_index };
return ExpectEvent(expected_event);
}
bool DnsSessionTest::DidFree(unsigned server_index) {
PoolEvent expected_event = { PoolEvent::FREE, server_index };
return ExpectEvent(expected_event);
}
bool DnsSessionTest::NoMoreEvents() {
return events_.empty();
}
void DnsSessionTest::OnSocketAllocated(unsigned server_index) {
PoolEvent event = { PoolEvent::ALLOCATE, server_index };
events_.push_back(event);
}
void DnsSessionTest::OnSocketFreed(unsigned server_index) {
PoolEvent event = { PoolEvent::FREE, server_index };
events_.push_back(event);
}
bool DnsSessionTest::ExpectEvent(const PoolEvent& expected) {
if (events_.empty()) {
return false;
}
const PoolEvent actual = events_.front();
if ((expected.action != actual.action)
|| (expected.server_index != actual.server_index)) {
return false;
}
events_.pop_front();
return true;
}
std::unique_ptr<DatagramClientSocket>
TestClientSocketFactory::CreateDatagramClientSocket(
DatagramSocket::BindType bind_type,
NetLog* net_log,
const NetLogSource& source) {
// We're not actually expecting to send or receive any data, so use the
// simplest SocketDataProvider with no data supplied.
SocketDataProvider* data_provider = new StaticSocketDataProvider();
data_providers_.push_back(base::WrapUnique(data_provider));
std::unique_ptr<MockUDPClientSocket> socket(
new MockUDPClientSocket(data_provider, net_log));
return std::move(socket);
}
TestClientSocketFactory::~TestClientSocketFactory() = default;
TEST_F(DnsSessionTest, AllocateFree) {
std::unique_ptr<DnsSession::SocketLease> lease1, lease2;
Initialize(2);
EXPECT_TRUE(NoMoreEvents());
lease1 = Allocate(0);
EXPECT_TRUE(DidAllocate(0));
EXPECT_TRUE(NoMoreEvents());
lease2 = Allocate(1);
EXPECT_TRUE(DidAllocate(1));
EXPECT_TRUE(NoMoreEvents());
lease1.reset();
EXPECT_TRUE(DidFree(0));
EXPECT_TRUE(NoMoreEvents());
lease2.reset();
EXPECT_TRUE(DidFree(1));
EXPECT_TRUE(NoMoreEvents());
}
// Expect default calculated timeout to be within 10ms of one in DnsConfig.
TEST_F(DnsSessionTest, HistogramTimeoutNormal) {
Initialize(2);
base::TimeDelta delta = session_->NextTimeout(0, 0) - config_.timeout;
EXPECT_LE(delta.InMilliseconds(), 10);
}
// Expect short calculated timeout to be within 10ms of one in DnsConfig.
TEST_F(DnsSessionTest, HistogramTimeoutShort) {
config_.timeout = base::TimeDelta::FromMilliseconds(15);
Initialize(2);
base::TimeDelta delta = session_->NextTimeout(0, 0) - config_.timeout;
EXPECT_LE(delta.InMilliseconds(), 10);
}
// Expect long calculated timeout to be equal to one in DnsConfig.
// (Default max timeout is 5 seconds, so NextTimeout should return exactly
// the config timeout.)
TEST_F(DnsSessionTest, HistogramTimeoutLong) {
config_.timeout = base::TimeDelta::FromSeconds(15);
Initialize(2);
base::TimeDelta timeout = session_->NextTimeout(0, 0);
EXPECT_EQ(timeout.InMilliseconds(), config_.timeout.InMilliseconds());
}
// Ensures that reported negative RTT values don't cause a crash. Regression
// test for https://crbug.com/753568.
TEST_F(DnsSessionTest, NegativeRtt) {
Initialize(2);
session_->RecordRTT(0, base::TimeDelta::FromMilliseconds(-1));
}
} // namespace
} // namespace net
| 2,784 |
7,018 | /* Tencent is pleased to support the open source community by making Hippy available.
* Copyright (C) 2018 THL A29 Limited, a Tencent company. 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.tencent.mtt.hippy.adapter.http;
import android.text.TextUtils;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
@SuppressWarnings({"unused"})
public class HippyHttpResponse {
public static final Integer UNKNOWN_STATUS = -1;
private Integer mStatusCode = UNKNOWN_STATUS;
private String mResponseMessage;
private Map<String, List<String>> mRspHeaderMap = null;
private InputStream mInputStream;
private InputStream mErrorStream;
public Integer getStatusCode() {
return mStatusCode != null ? mStatusCode : UNKNOWN_STATUS;
}
public void setStatusCode(Integer statusCode) {
this.mStatusCode = statusCode;
}
public void setRspHeaderMap(Map<String, List<String>> headerMap) {
mRspHeaderMap = headerMap;
}
public Map<String, List<String>> getRspHeaderMaps() {
return mRspHeaderMap;
}
public List<String> getHeaderFields(String name) {
if (TextUtils.isEmpty(name) || mRspHeaderMap == null) {
return null;
}
return mRspHeaderMap.get(name);
}
public String getHeaderField(String name) {
if (TextUtils.isEmpty(name) || mRspHeaderMap == null) {
return null;
}
List<String> fields = mRspHeaderMap.get(name);
return fields != null && fields.size() > 0 ? fields.get(0) : null;
}
public InputStream getInputStream() {
return mInputStream;
}
public void setInputStream(InputStream inputStream) {
this.mInputStream = inputStream;
}
public InputStream getErrorStream() {
return mErrorStream;
}
public void setErrorStream(InputStream errorStream) {
this.mErrorStream = errorStream;
}
public void setResponseMessage(String message) {
this.mResponseMessage = message;
}
public String getResponseMessage() {
return mResponseMessage;
}
public void close() {
if (mInputStream != null) {
try {
mInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (mErrorStream != null) {
try {
mErrorStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
| 965 |
1,444 | package mage.cards.q;
import java.util.UUID;
import mage.MageInt;
import mage.abilities.Ability;
import mage.abilities.condition.CompoundCondition;
import mage.abilities.condition.Condition;
import mage.abilities.condition.common.AttackedThisStepCondition;
import mage.abilities.condition.common.PermanentsOnTheBattlefieldCondition;
import mage.abilities.costs.AlternativeCostSourceAbility;
import mage.abilities.decorator.ConditionalAsThoughEffect;
import mage.abilities.effects.common.continuous.CastAsThoughItHadFlashSourceEffect;
import mage.abilities.keyword.ReachAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.*;
import mage.filter.common.FilterControlledPermanent;
import mage.watchers.common.PlayerAttackedStepWatcher;
/**
*
* @author Plopman
*/
public final class QasaliAmbusher extends CardImpl {
private static final FilterControlledPermanent filterForest = new FilterControlledPermanent();
private static final FilterControlledPermanent filterPlains = new FilterControlledPermanent();
static {
filterForest.add(SubType.FOREST.getPredicate());
filterPlains.add(SubType.PLAINS.getPredicate());
}
private static final Condition condition =
new CompoundCondition("If a creature is attacking you and you control a Forest and a Plains",
AttackedThisStepCondition.instance, new PermanentsOnTheBattlefieldCondition(filterForest), new PermanentsOnTheBattlefieldCondition(filterPlains));
public QasaliAmbusher(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{1}{G}{W}");
this.subtype.add(SubType.CAT);
this.subtype.add(SubType.WARRIOR);
this.power = new MageInt(2);
this.toughness = new MageInt(3);
// Reach
this.addAbility(ReachAbility.getInstance());
// If a creature is attacking you and you control a Forest and a Plains,
// you may cast Qasali Ambusher without paying its mana cost and as though it had flash.
Ability ability = new AlternativeCostSourceAbility(null, condition);
ability.addEffect(new ConditionalAsThoughEffect(new CastAsThoughItHadFlashSourceEffect(Duration.EndOfGame), condition)
.setText("you may cast {this} without paying its mana cost and as though it had flash"));
ability.addWatcher(new PlayerAttackedStepWatcher());
this.addAbility(ability);
}
private QasaliAmbusher(final QasaliAmbusher card) {
super(card);
}
@Override
public QasaliAmbusher copy() {
return new QasaliAmbusher(this);
}
} | 877 |
318 | <filename>Common/OpenCL/ITKimprovements/itkOpenCLSize.cxx
/*=========================================================================
*
* Copyright <NAME> and 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.txt
*
* 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 "itkOpenCLSize.h"
#include "itkOpenCLDevice.h"
namespace itk
{
static std::size_t
opencl_gcd_of_size(std::size_t x, std::size_t y)
{
std::size_t remainder;
while ((remainder = x % y) != 0)
{
x = y;
y = remainder;
}
return y;
}
const OpenCLSize::Null OpenCLSize::null = {};
//------------------------------------------------------------------------------
bool
OpenCLSize::IsZero() const
{
if (this->IsNull())
{
return true;
}
if (this->m_Dim == 1)
{
return (this->m_Sizes[0] == 0);
}
else if (this->m_Dim == 2)
{
return (this->m_Sizes[0] == 0 && this->m_Sizes[1] == 0);
}
else
{
return (this->m_Sizes[0] == 0 && this->m_Sizes[1] == 0 && this->m_Sizes[2] == 0);
}
}
//------------------------------------------------------------------------------
OpenCLSize
OpenCLSize::GetLocalWorkSize(const OpenCLSize & maxWorkItemSize, const std::size_t maxItemsPerGroup)
{
// Get sizes and dimension
const std::size_t * sizes = maxWorkItemSize.GetSizes();
const std::size_t dimension = maxWorkItemSize.GetDimension();
// Adjust for the maximum work item size in each dimension.
std::size_t width = dimension >= 1 ? opencl_gcd_of_size(sizes[0], maxWorkItemSize.GetWidth()) : 1;
std::size_t height = dimension >= 2 ? opencl_gcd_of_size(sizes[1], maxWorkItemSize.GetHeight()) : 1;
std::size_t depth = dimension >= 3 ? opencl_gcd_of_size(sizes[2], maxWorkItemSize.GetDepth()) : 1;
// Reduce in size by a factor of 2 until underneath the maximum group size.
while (maxItemsPerGroup && (width * height * depth) > maxItemsPerGroup)
{
width = (width > 1) ? (width / 2) : 1;
height = (height > 1) ? (height / 2) : 1;
depth = (depth > 1) ? (depth / 2) : 1;
}
// Return the final result.
if (dimension >= 3)
{
return OpenCLSize(width, height, depth);
}
else if (dimension >= 2)
{
return OpenCLSize(width, height);
}
else
{
return OpenCLSize(width);
}
}
//------------------------------------------------------------------------------
OpenCLSize
OpenCLSize::GetLocalWorkSize(const OpenCLDevice & device)
{
return GetLocalWorkSize(device.GetMaximumWorkItemSize(), device.GetMaximumWorkItemsPerGroup());
}
//------------------------------------------------------------------------------
static inline std::size_t
opencl_cl_round_to(const std::size_t value, const std::size_t multiple)
{
if (multiple <= 1)
{
return value;
}
std::size_t remainder = value % multiple;
if (!remainder)
{
return value;
}
else
{
return value + multiple - remainder;
}
}
//------------------------------------------------------------------------------
OpenCLSize
OpenCLSize::RoundTo(const OpenCLSize & size) const
{
if (this->m_Dim == 1)
{
return OpenCLSize(opencl_cl_round_to(this->m_Sizes[0], size.m_Sizes[0]));
}
else if (this->m_Dim == 2)
{
return OpenCLSize(opencl_cl_round_to(this->m_Sizes[0], size.m_Sizes[0]),
opencl_cl_round_to(this->m_Sizes[1], size.m_Sizes[1]));
}
else
{
return OpenCLSize(opencl_cl_round_to(this->m_Sizes[0], size.m_Sizes[0]),
opencl_cl_round_to(this->m_Sizes[1], size.m_Sizes[1]),
opencl_cl_round_to(this->m_Sizes[2], size.m_Sizes[2]));
}
}
//------------------------------------------------------------------------------
//! Operator ==
bool
operator==(const OpenCLSize & lhs, const OpenCLSize & rhs)
{
if (&rhs == &lhs)
{
return true;
}
return lhs.GetDimension() == rhs.GetDimension() && lhs.GetWidth() == rhs.GetWidth() &&
lhs.GetHeight() == rhs.GetHeight() && lhs.GetDepth() == rhs.GetDepth();
}
//------------------------------------------------------------------------------
//! Operator !=
bool
operator!=(const OpenCLSize & lhs, const OpenCLSize & rhs)
{
return !(lhs == rhs);
}
} // namespace itk
| 1,618 |
1,063 | # -*- coding: utf-8 -*-
from .helper import ExtractHelper
__all__ = [
'ExtractHelper',
]
| 41 |
2,583 | import arm
if not arm.is_reload(__name__):
arm.enable_reload(__name__)
redraw_ui = False
target = 'krom'
last_target = 'krom'
export_gapi = ''
last_resx = 0
last_resy = 0
last_scene = ''
last_world_defs = ''
proc_play = None
proc_build = None
proc_publish_build = None
mod_scripts = []
is_export = False
is_play = False
is_publish = False
| 182 |
506 | <reponame>Ashindustry007/competitive-programming<filename>cses/1145.cc
// https://cses.fi/problemset/info/1145/
#include <iostream>
#include <vector>
using namespace std;
typedef vector<int> vi;
int main() {
int n, x;
cin >> n;
vi a;
while (n--) {
cin >> x;
auto it = lower_bound(a.begin(), a.end(), x);
if (it == a.end()) a.push_back(x);
else *it = x;
}
cout << a.size() << endl;
} | 211 |
3,094 | <gh_stars>1000+
import spacy
from torchtext.datasets import Multi30k
from torchtext.data import Field, BucketIterator
"""
To install spacy languages use:
python -m spacy download en
python -m spacy download de
"""
spacy_eng = spacy.load("en")
spacy_ger = spacy.load("de")
def tokenize_eng(text):
return [tok.text for tok in spacy_eng.tokenizer(text)]
def tokenize_ger(text):
return [tok.text for tok in spacy_ger.tokenizer(text)]
english = Field(sequential=True, use_vocab=True, tokenize=tokenize_eng, lower=True)
german = Field(sequential=True, use_vocab=True, tokenize=tokenize_ger, lower=True)
train_data, validation_data, test_data = Multi30k.splits(
exts=(".de", ".en"), fields=(german, english)
)
english.build_vocab(train_data, max_size=10000, min_freq=2)
german.build_vocab(train_data, max_size=10000, min_freq=2)
train_iterator, validation_iterator, test_iterator = BucketIterator.splits(
(train_data, validation_data, test_data), batch_size=64, device="cuda"
)
for batch in train_iterator:
print(batch)
# string to integer (stoi)
print(f'Index of the word (the) is: {english.vocab.stoi["the"]}')
# print integer to string (itos)
print(f"Word of the index (1612) is: {english.vocab.itos[1612]}")
print(f"Word of the index (0) is: {english.vocab.itos[0]}")
| 483 |
5,823 | <filename>shell/platform/darwin/macos/framework/Source/FlutterExternalTextureMetal.h<gh_stars>1000+
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import <Foundation/Foundation.h>
#import "flutter/shell/platform/darwin/graphics/FlutterDarwinContextMetal.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterMacOSExternalTexture.h"
/**
* Used to bridge FlutterTexture object and handle the texture copy request the
* Flutter engine.
*/
@interface FlutterExternalTextureMetal : NSObject <FlutterMacOSExternalTexture>
/**
* Initializes a texture adapter with |texture|.
*/
- (nonnull instancetype)initWithFlutterTexture:(nonnull id<FlutterTexture>)texture
darwinMetalContext:(nonnull FlutterDarwinContextMetal*)context;
/**
* Accepts texture buffer copy request from the Flutter engine.
* When the user side marks the textureID as available, the Flutter engine will
* callback to this method and ask for populate the |metalTexture| object,
* such as the texture type and the format of the pixel buffer and the texture object.
*/
- (BOOL)populateTexture:(nonnull FlutterMetalExternalTexture*)metalTexture;
@end
| 374 |
1,260 | package net.md_5.bungee;
import lombok.Data;
import net.md_5.bungee.api.Title;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.chat.ComponentSerializer;
import net.md_5.bungee.protocol.DefinedPacket;
import net.md_5.bungee.protocol.ProtocolConstants;
import net.md_5.bungee.protocol.packet.ClearTitles;
import net.md_5.bungee.protocol.packet.Subtitle;
import net.md_5.bungee.protocol.packet.Title.Action;
import net.md_5.bungee.protocol.packet.TitleTimes;
public class BungeeTitle implements Title
{
private TitlePacketHolder<net.md_5.bungee.protocol.packet.Title> title;
private TitlePacketHolder<Subtitle> subtitle;
private TitlePacketHolder<TitleTimes> times;
private TitlePacketHolder<ClearTitles> clear;
private TitlePacketHolder<ClearTitles> reset;
@Data
private static class TitlePacketHolder<T extends DefinedPacket>
{
private final net.md_5.bungee.protocol.packet.Title oldPacket;
private final T newPacket;
}
private static TitlePacketHolder<TitleTimes> createAnimationPacket()
{
TitlePacketHolder<TitleTimes> title = new TitlePacketHolder<>( new net.md_5.bungee.protocol.packet.Title( Action.TIMES ), new TitleTimes() );
title.oldPacket.setFadeIn( 20 );
title.oldPacket.setStay( 60 );
title.oldPacket.setFadeOut( 20 );
title.newPacket.setFadeIn( 20 );
title.newPacket.setStay( 60 );
title.newPacket.setFadeOut( 20 );
return title;
}
@Override
public Title title(BaseComponent text)
{
if ( title == null )
{
net.md_5.bungee.protocol.packet.Title packet = new net.md_5.bungee.protocol.packet.Title( Action.TITLE );
title = new TitlePacketHolder<>( packet, packet );
}
title.oldPacket.setText( ComponentSerializer.toString( text ) ); // = newPacket
return this;
}
@Override
public Title title(BaseComponent... text)
{
if ( title == null )
{
net.md_5.bungee.protocol.packet.Title packet = new net.md_5.bungee.protocol.packet.Title( Action.TITLE );
title = new TitlePacketHolder<>( packet, packet );
}
title.oldPacket.setText( ComponentSerializer.toString( text ) ); // = newPacket
return this;
}
@Override
public Title subTitle(BaseComponent text)
{
if ( subtitle == null )
{
subtitle = new TitlePacketHolder<>( new net.md_5.bungee.protocol.packet.Title( Action.SUBTITLE ), new Subtitle() );
}
String serialized = ComponentSerializer.toString( text );
subtitle.oldPacket.setText( serialized );
subtitle.newPacket.setText( serialized );
return this;
}
@Override
public Title subTitle(BaseComponent... text)
{
if ( subtitle == null )
{
subtitle = new TitlePacketHolder<>( new net.md_5.bungee.protocol.packet.Title( Action.SUBTITLE ), new Subtitle() );
}
String serialized = ComponentSerializer.toString( text );
subtitle.oldPacket.setText( serialized );
subtitle.newPacket.setText( serialized );
return this;
}
@Override
public Title fadeIn(int ticks)
{
if ( times == null )
{
times = createAnimationPacket();
}
times.oldPacket.setFadeIn( ticks );
times.newPacket.setFadeIn( ticks );
return this;
}
@Override
public Title stay(int ticks)
{
if ( times == null )
{
times = createAnimationPacket();
}
times.oldPacket.setStay( ticks );
times.newPacket.setStay( ticks );
return this;
}
@Override
public Title fadeOut(int ticks)
{
if ( times == null )
{
times = createAnimationPacket();
}
times.oldPacket.setFadeOut( ticks );
times.newPacket.setFadeOut( ticks );
return this;
}
@Override
public Title clear()
{
if ( clear == null )
{
clear = new TitlePacketHolder<>( new net.md_5.bungee.protocol.packet.Title( Action.CLEAR ), new ClearTitles() );
}
title = null; // No need to send title if we clear it after that again
return this;
}
@Override
public Title reset()
{
if ( reset == null )
{
reset = new TitlePacketHolder<>( new net.md_5.bungee.protocol.packet.Title( Action.RESET ), new ClearTitles( true ) );
}
// No need to send these packets if we reset them later
title = null;
subtitle = null;
times = null;
return this;
}
private static void sendPacket(ProxiedPlayer player, TitlePacketHolder packet)
{
if ( packet != null )
{
if ( player.getPendingConnection().getVersion() >= ProtocolConstants.MINECRAFT_1_17 )
{
player.unsafe().sendPacket( packet.newPacket );
} else
{
player.unsafe().sendPacket( packet.oldPacket );
}
}
}
@Override
public Title send(ProxiedPlayer player)
{
sendPacket( player, clear );
sendPacket( player, reset );
sendPacket( player, times );
sendPacket( player, subtitle );
sendPacket( player, title );
return this;
}
}
| 2,426 |
3,287 | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
from azure.cli.testsdk import ScenarioTest, ResourceGroupPreparer
from azure.cli.testsdk.scenario_tests import AllowLargeResponse
class SecurityCenterIotTests(ScenarioTest):
@AllowLargeResponse()
@ResourceGroupPreparer(location='eastus')
def test_security_iot(self):
self.kwargs.update({
'iot_hub_name': self.create_random_name(prefix='azurecli-hub', length=24)
})
iot_hub_id = self.cmd('az iot hub create -n {iot_hub_name} -g {rg}').get_output_in_json()['id']
self.kwargs.update({
'iot_hub_id': iot_hub_id
})
self.cmd('az security iot-solution create --solution-name "azurecli-hub" --resource-group {rg} --iot-hubs {iot_hub_id} --display-name "Solution Default" --location "east us"')
azure_cli_new_iot_security_solution = self.cmd('az security iot-solution list --resource-group {rg}').get_output_in_json()
assert len(azure_cli_new_iot_security_solution) == 1
self.cmd('az security iot-solution update --solution-name "azurecli-hub" --resource-group {rg} --iot-hubs {iot_hub_id} --display-name "Solution Default"')
azure_cli_new_iot_security_solution = self.cmd('az security iot-solution list --resource-group {rg}').get_output_in_json()
assert len(azure_cli_new_iot_security_solution) == 1
azure_cli_iot_security_solution = self.cmd('az security iot-solution show --solution-name "azurecli-hub" --resource-group {rg}').get_output_in_json()
assert len(azure_cli_iot_security_solution) >= 1
self.cmd('az security iot-solution delete --solution-name "azurecli-hub" --resource-group {rg}')
azure_cli_no_iot_security_solution = self.cmd('az security iot-solution list --resource-group {rg}').get_output_in_json()
assert len(azure_cli_no_iot_security_solution) == 0
| 775 |
793 | <filename>examples/common/im3d_example.h<gh_stars>100-1000
#pragma once
#include "im3d.h"
// Compiler
#if defined(__GNUC__)
#define IM3D_COMPILER_GNU
#elif defined(_MSC_VER)
#define IM3D_COMPILER_MSVC
#else
#error im3d: Compiler not defined
#endif
// Platform
#if defined(_WIN32) || defined(_WIN64)
// Windows
#define IM3D_PLATFORM_WIN
#define NOMINMAX 1
#define WIN32_LEAN_AND_MEAN 1
#define VC_EXTRALEAN 1
#include <Windows.h>
#define winAssert(e) IM3D_VERIFY_MSG(e, Im3d::GetPlatformErrorString(GetLastError()))
namespace Im3d {
const char* GetPlatformErrorString(DWORD _err);
}
#else
#error im3d: Platform not defined
#endif
// Graphics API
#if defined(IM3D_OPENGL)
// OpenGL
//#define IM3D_OPENGL_VMAJ 3
//#define IM3D_OPENGL_VMIN 3
//#define IM3D_OPENGL_VSHADER "#version 150"
#include "GL/glew.h"
#define glAssert(call) \
do { \
(call); \
GLenum err = glGetError(); \
if (err != GL_NO_ERROR) { \
Im3d::Assert(#call, __FILE__, __LINE__, Im3d::GetGlEnumString(err)); \
IM3D_BREAK(); \
} \
} while (0)
namespace Im3d {
// Return 0 on failure (prints log info to stderr). _defines is a list of null-separated strings e.g. "DEFINE1 1\0DEFINE2 1\0"
GLuint LoadCompileShader(GLenum _stage, const char* _path, const char* _defines = 0);
// Return false on failure (prints log info to stderr).
bool LinkShaderProgram(GLuint _handle);
const char* GetGlEnumString(GLenum _enum);
const char* GlGetString(GLenum _name);
}
#elif defined(IM3D_DX11)
// DirectX 11
#include <d3d11.h>
#define IM3D_DX11_VSHADER "4_0"
#define dxAssert(call) \
do { \
HRESULT err = (call); \
if (err != S_OK) { \
Im3d::Assert(#call, __FILE__, __LINE__, Im3d::GetPlatformErrorString((DWORD)err)); \
IM3D_BREAK(); \
} \
} while (0)
namespace Im3d {
// Return 0 on failure (prints log info to stderr). _defines is a list of null-separated strings e.g. "DEFINE1 1\0DEFINE2 1\0"
ID3DBlob* LoadCompileShader(const char* _target, const char* _path, const char* _defines = 0);
// Resource helpers.
ID3D11Buffer* CreateBuffer(UINT _size, D3D11_USAGE _usage, UINT _bind, const void* _data = nullptr);
ID3D11Buffer* CreateConstantBuffer(UINT _size, D3D11_USAGE _usage, const void* _data = nullptr);
ID3D11Buffer* CreateVertexBuffer(UINT _size, D3D11_USAGE _usage, const void* _data = nullptr);
ID3D11Buffer* CreateIndexBuffer(UINT _size, D3D11_USAGE _usage, const void* _data = nullptr);
void* MapBuffer(ID3D11Buffer* _buffer, D3D11_MAP _mapType);
void UnmapBuffer(ID3D11Buffer* _buffer);
ID3D11Texture2D* CreateTexture2D(UINT _width, UINT _height, DXGI_FORMAT _format, ID3D11ShaderResourceView** resView_ = nullptr, const void* _data = nullptr);
ID3D11DepthStencilView* CreateDepthStencil(UINT _width, UINT _height, DXGI_FORMAT _format);
}
#else
#error im3d: Graphics API not defined
#endif
#define IM3D_UNUSED(x) do { (void)sizeof(x); } while(0)
#ifdef IM3D_COMPILER_MSVC
#define IM3D_BREAK() __debugbreak()
#else
#include <cstdlib>
#define IM3D_BREAK() abort()
#endif
#define IM3D_ASSERT_MSG(e, msg, ...) \
do { \
if (!(e)) { \
Im3d::Assert(#e, __FILE__, __LINE__, msg, ## __VA_ARGS__); \
IM3D_BREAK(); \
} \
} while (0)
#undef IM3D_ASSERT
#define IM3D_ASSERT(e) IM3D_ASSERT_MSG(e, 0, 0)
#define IM3D_VERIFY_MSG(e, msg, ...) IM3D_ASSERT_MSG(e, msg, ## __VA_ARGS__)
#define IM3D_VERIFY(e) IM3D_VERIFY_MSG(e, 0, 0)
#ifndef __COUNTER__
#define __COUNTER__ __LINE__
#endif
#define IM3D_TOKEN_CONCATENATE_(_t0, _t1) _t0 ## _t1
#define IM3D_TOKEN_CONCATENATE(_t0, _t1) IM3D_TOKEN_CONCATENATE_(_t0, _t1)
#define IM3D_UNIQUE_NAME(_base) IM3D_TOKEN_CONCATENATE(_base, __COUNTER__)
#define IM3D_STRINGIFY_(_t) #_t
#define IM3D_STRINGIFY(_t) IM3D_STRINGIFY_(_t)
#include "im3d_math.h"
#include "imgui/imgui.h"
namespace Im3d {
void Assert(const char* _e, const char* _file, int _line, const char* _msg, ...);
void RandSeed(int _seed);
int RandInt(int _min, int _max);
float RandFloat(float _min, float _max);
Vec3 RandVec3(float _min, float _max);
Mat3 RandRotation();
Color RandColor(float _min, float _max);
void DrawNdcQuad();
void DrawTeapot(const Mat4& _world, const Mat4& _viewProj);
struct Example
{
bool init(int _width, int _height, const char* _title);
void shutdown();
bool update();
void draw();
// window
int m_width, m_height;
const char* m_title;
Vec2 m_prevCursorPos;
bool hasFocus() const;
Vec2 getWindowRelativeCursor() const;
// 3d camera
bool m_camOrtho;
Vec3 m_camPos;
Vec3 m_camDir;
float m_camFovDeg;
float m_camFovRad;
Mat4 m_camWorld;
Mat4 m_camView;
Mat4 m_camProj;
Mat4 m_camViewProj;
float m_deltaTime;
// platform/graphics specifics
#if defined(IM3D_PLATFORM_WIN)
HWND m_hwnd;
LARGE_INTEGER m_currTime, m_prevTime;
#if defined(IM3D_OPENGL)
HDC m_hdc;
HGLRC m_hglrc;
#elif defined(IM3D_DX11)
ID3D11Device* m_d3dDevice;
ID3D11DeviceContext* m_d3dDeviceCtx;
IDXGISwapChain* m_dxgiSwapChain;
ID3D11RenderTargetView* m_d3dRenderTarget;
ID3D11DepthStencilView* m_d3dDepthStencil;
#endif
#endif
// text rendering
void drawTextDrawListsImGui(const Im3d::TextDrawList _textDrawLists[], U32 _count);
}; // struct Example
extern Example* g_Example;
} // namespace Im3d
// per-example implementations (in the example .cpp)
extern bool Im3d_Init();
extern void Im3d_Shutdown();
extern void Im3d_NewFrame();
extern void Im3d_EndFrame();
| 2,499 |
1,089 | package org.zalando.logbook.httpclient;
import lombok.experimental.UtilityClass;
import org.zalando.logbook.Logbook;
@UtilityClass
final class Attributes {
static final String STAGE = Logbook.class.getName() + ".STAGE";
}
| 79 |
1,185 | #include <syscalls.h>
#include <stdarg.h>
void *stdin, *stdout, *stderr;
int _open(char *device, int flags);
int open(char *device, int flags, ...) {
va_list vl;
va_start(vl, flags);
if((flags & O_CREAT) != 0) {
int mode = va_arg(vl, int);
va_end(vl);
(void)mode; // TODO: set mode
int fd = create(device, flags);
return fd;
}
va_end(vl);
return _open(device, flags);
}
| 180 |
965 | <gh_stars>100-1000
//The following example attaches an HWND to the CWindow object and
//calls CWindow::Invalidate() to invalidate the entire client area
CWindow myWindow;
myWindow.Attach(hWnd);
myWindow.Invalidate(); | 74 |
2,113 | <filename>Engine/source/gfx/D3D11/screenshotD3D11.cpp
//-----------------------------------------------------------------------------
// Copyright (c) 2016 GarageGames, LLC
//
// 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 "platform/platform.h"
#include "gfx/D3D11/screenshotD3D11.h"
#include "gfx/D3D11/gfxD3D11Device.h"
//Note if MSAA is ever enabled this will need fixing
GBitmap* ScreenShotD3D11::_captureBackBuffer()
{
ID3D11Texture2D* backBuf = D3D11->getBackBufferTexture();
D3D11_TEXTURE2D_DESC desc;
backBuf->GetDesc(&desc);
desc.BindFlags = 0;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ | D3D11_CPU_ACCESS_WRITE;
desc.Usage = D3D11_USAGE_STAGING;
//create temp texure
ID3D11Texture2D* pNewTexture = NULL;
HRESULT hr = D3D11DEVICE->CreateTexture2D(&desc, NULL, &pNewTexture);
if (FAILED(hr))
return NULL;
U32 width = desc.Width;
U32 height = desc.Height;
// pixel data
U8 *pData = new U8[width * height * 4];
D3D11DEVICECONTEXT->CopyResource(pNewTexture, backBuf);
D3D11_MAPPED_SUBRESOURCE Resource;
hr = D3D11DEVICECONTEXT->Map(pNewTexture, 0, D3D11_MAP_READ, 0, &Resource);
if (FAILED(hr))
{
//cleanup
SAFE_DELETE_ARRAY(pData);
SAFE_RELEASE(pNewTexture);
return NULL;
}
const U32 pitch = width << 2;
const U8* pSource = (U8*)Resource.pData;
U32 totalPitch = 0;
for (U32 i = 0; i < height; ++i)
{
dMemcpy(pData, pSource, width * 4);
pSource += Resource.RowPitch;
pData += pitch;
totalPitch += pitch;
}
D3D11DEVICECONTEXT->Unmap(pNewTexture, 0);
pData -= totalPitch;
GBitmap *gb = new GBitmap(width, height);
//Set GBitmap data and convert from bgr to rgb
ColorI c;
for (S32 i = 0; i<height; i++)
{
const U8 *a = pData + i * width * 4;
for (S32 j = 0; j<width; j++)
{
c.blue = *(a++);
c.green = *(a++);
c.red = *(a++);
a++; // Ignore alpha.
gb->setColor(j, i, c);
}
}
//cleanup
SAFE_DELETE_ARRAY(pData);
SAFE_RELEASE(pNewTexture);
return gb;
}
| 1,212 |
397 | <filename>src/engine/common/number_generator.hpp
#pragma once
#include <random>
class NumberGenerator
{
protected:
std::random_device rd;
std::mt19937 gen;
NumberGenerator()
: gen(rd())
{}
};
template<typename T>
class RealNumberGenerator : public NumberGenerator
{
private:
std::uniform_real_distribution<T> dis;
public:
RealNumberGenerator()
: NumberGenerator()
, dis(0.0f, 1.0f)
{}
// random_device is not copyable
RealNumberGenerator(const RealNumberGenerator<T>& right)
: NumberGenerator()
, dis(right.dis)
{}
float get()
{
return dis(gen);
}
float getUnder(T max)
{
return get() * max;
}
float getRange(T min, T max)
{
return min + get() * (max - min);
}
float getRange(T width)
{
return getRange(-width * 0.5f, width * 0.5f);
}
};
template<typename T>
class RNG
{
private:
static RealNumberGenerator<T> gen;
public:
static T get()
{
return gen.get();
}
static float getUnder(T max)
{
return gen.getUnder(max);
}
static uint64_t getUintUnder(uint64_t max)
{
return static_cast<uint64_t>(gen.getUnder(static_cast<float>(max) + 1.0f));
}
static float getRange(T min, T max)
{
return gen.getRange(min, max);
}
static float getRange(T width)
{
return gen.getRange(width);
}
static float getFullRange(T width)
{
return gen.getRange(static_cast<T>(2.0f) * width);
}
static bool proba(float threshold)
{
return get() < threshold;
}
};
using RNGf = RNG<float>;
template<typename T>
RealNumberGenerator<T> RNG<T>::gen = RealNumberGenerator<T>();
template<typename T>
class IntegerNumberGenerator : public NumberGenerator
{
public:
IntegerNumberGenerator()
: NumberGenerator()
{}
// random_device is not copyable
IntegerNumberGenerator(const IntegerNumberGenerator<T>& right)
: NumberGenerator()
{}
T getUnder(T max)
{
std::uniform_int_distribution<std::mt19937::result_type> dist(0, max);
return dist(gen);
}
T getRange(T min, T max)
{
std::uniform_int_distribution<std::mt19937::result_type> dist(min, max);
return dist(gen);
}
};
template<typename T>
class RNGi
{
private:
static IntegerNumberGenerator<T> gen;
public:
static T getUnder(T max)
{
return gen.getUnder(max);
}
static T getRange(T min, T max)
{
return gen.getRange(min, max);
}
};
template<typename T>
IntegerNumberGenerator<T> RNGi<T>::gen;
using RNGi32 = RNGi<int32_t>;
using RNGi64 = RNGi<int64_t>;
using RNGu32 = RNGi<uint32_t>;
using RNGu64 = RNGi<uint64_t>;
| 1,017 |
3,428 | <gh_stars>1000+
{"id":"00104","group":"easy-ham-2","checksum":{"type":"MD5","value":"a682139cb63862f8b63756c454c01fe3"},"text":"From <EMAIL> Mon Jul 22 18:13:16 2002\nReturn-Path: <<EMAIL>>\nDelivered-To: yyyy<EMAIL>.netnoteinc.com\nReceived: from localhost (localhost [127.0.0.1])\n\tby phobos.labs.netnoteinc.com (Postfix) with ESMTP id 5A2A7440DD\n\tfor <jm@localhost>; Mon, 22 Jul 2002 13:12:32 -0400 (EDT)\nReceived: from dogma.slashnull.org [212.17.35.15]\n\tby localhost with IMAP (fetchmail-5.9.0)\n\tfor jm@localhost (single-drop); Mon, 22 Jul 2002 18:12:32 +0100 (IST)\nReceived: from webnote.net (mail.webnote.net [193.120.211.219]) by\n dogma.slashnull.org (8.11.6/8.11.6) with ESMTP id g6MG4QY17730 for\n <<EMAIL>>; Mon, 22 Jul 2002 17:04:26 +0100\nReceived: from lugh.tuatha.org (<EMAIL> [194.125.145.45]) by\n webnote.net (8.9.3/8.9.3) with ESMTP id OAA23692 for <<EMAIL>>;\n Sat, 20 Jul 2002 14:27:09 +0100\nReceived: from lugh (root@localhost [1192.168.127.12]) by lugh.tuatha.org\n (8.9.3/8.9.3) with ESMTP id OAA04712; Sat, 20 Jul 2002 14:26:41 +0100\nX-Authentication-Warning: lugh.tuatha.org: Host root@localhost [127.0.0.1]\n claimed to be lugh\nReceived: from smtp013.mail.yahoo.com (smtp013.mail.yahoo.com\n [2192.168.3.117]) by lugh.tuatha.org (8.9.3/8.9.3) with SMTP id OAA04597\n for <<EMAIL>>; Sat, 20 Jul 2002 14:26:19 +0100\nReceived: from p102.as1.cra.dublin.eircom.net (HELO mfrenchw2k)\n ([email protected] with login) by smtp.mail.vip.sc5.yahoo.com with\n SMTP; 20 Jul 2002 13:26:16 -0000\nMessage-Id: <<EMAIL>01c22ff<EMAIL>>\nFrom: \"<NAME>\" <<EMAIL>>\nTo: \"kevin lyda\" <<EMAIL>.<EMAIL>>,\n\t<<EMAIL>>\nReferences: <<EMAIL>>\n <002c01c22f67$4216c280<EMAIL>>\n <<EMAIL>>\nSubject: Re: [ILUG] hard- vs. soft-links [was: How to copy some files ]\nDate: Sat, 20 Jul 2002 14:22:30 +0100\nMIME-Version: 1.0\nContent-Type: text/plain; charset=\"iso-8859-1\"\nContent-Transfer-Encoding: 7bit\nX-Priority: 3\nX-Msmail-Priority: Normal\nX-Mailer: Microsoft Outlook Express 6.00.2600.0000\nX-Mimeole: Produced By Microsoft MimeOLE V6.00.2600.0000\nSender: [email protected]\nErrors-To: [email protected]\nX-Mailman-Version: 1.1\nPrecedence: bulk\nList-Id: Irish Linux Users' Group <ilug.linux.ie>\nX-Beenthere: [email protected]\n\nKevin wrote:\n> am i the only one who thinks this is like \"friday night 80's\" for ilug?\n> and here's an answer from 1989. for those perceptive folks in the\n> audience you'll note that it makes no reference to a windows icons.\n<snip>\n> so yeah, unrm would be nice, but obviously it's not a simple problem.\n> millions of lines of code, hundreds of projects, no unrm. heck, the\n> hurd will probably release 1.0 before unrm shows up.\n\nSo what this tells us is:\n1) There are very few new ideas.\n2) Problems exists until someone gets annoyed enough to actually fix them\nrather than find bizarre ways to solve the problem.\n3) I have too much creative time on my hands with not enough productive\ntime.\n\n>>From which we can infer that no work on unrm will be happening on my\ncomputer for a long time.\n\n:)\n\n- Matthew\n\n\n__________________________________________________\nDo You Yahoo!?\nEverything you'll ever need on one web page\nfrom News and Sport to Email and Music Charts\nhttp://uk.my.yahoo.comm\n\n\n-- \nIrish Linux Users' Group: [email protected]\nhttp://www.linux.ie/mailman/listinfo/ilug for (un)subscription information.\nList maintainer: <EMAIL>\n\n\n"} | 1,375 |
868 | // Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the
// License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
#ifndef FLARE_TESTING_DETAIL_DIRTY_HOOK_H_
#define FLARE_TESTING_DETAIL_DIRTY_HOOK_H_
namespace flare::testing::detail {
// Hook function located at `fptr`.
//
// Note that this method is BY NO MEANS a general hook implementation. To
// implement a "production-ready" hook library, at least the following issues
// should be addressed:
//
// - Be able to call the original implementation without restoring the hook (to
// avoid race condition). Ususally this means the hook library should move the
// opcodes overwritten to somewhere else *and* fix IP-relative addressing
// (which requires a disassembler library).
//
// - Avoid overwrite opcodes when some (other) threads are executing them.
//
// - Do not mutate register. In case the user want to install a hook at the
// middle of a function, no register is really "volatile".
//
// - Handle several corner cases such as when the function to be hooked is too
// small to put our "jump" opcodes in.
//
// For our purpose (testing only), we don't take any of the issues above into
// consideration. Besides, we provide no way to call original implementation
// until the hook is restored.
//
// Returns a handle that can be used to restore the hook.
void* InstallHook(void* fptr, void* to);
// Restore a hook installed by `InstallHook`.
void UninstallHook(void* handle);
} // namespace flare::testing::detail
#endif // FLARE_TESTING_DETAIL_DIRTY_HOOK_H_
| 564 |
3,799 | <reponame>semoro/androidx<filename>camera/camera-extensions/src/main/java/androidx/camera/extensions/internal/VersionName.java<gh_stars>1000+
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.camera.extensions.internal;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
/**
* The version of CameraX extension releases.
*/
@RequiresApi(21) // TODO(b/200306659): Remove and replace with annotation on package-info.java
public class VersionName {
// Current version of vendor library implementation that the CameraX extension supports. This
// needs to be increased along with the version of vendor library interface.
private static final VersionName CURRENT = new VersionName("1.1.0");
@NonNull
public static VersionName getCurrentVersion() {
return CURRENT;
}
private final Version mVersion;
@NonNull
public Version getVersion() {
return mVersion;
}
public VersionName(@NonNull String versionString) {
mVersion = Version.parse(versionString);
}
VersionName(int major, int minor, int patch, String description) {
mVersion = Version.create(major, minor, patch, description);
}
/**
* Gets this version number as string.
*
* @return the string of the version in a form of MAJOR.MINOR.PATCH-description.
*/
@NonNull
public String toVersionString() {
return mVersion.toString();
}
}
| 619 |
3,570 | <filename>MalmoEnv/proxyenv/malmoenvwrap.py
# ------------------------------------------------------------------------------------------------
# Copyright (c) 2019 Microsoft Corporation
#
# 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.
# ------------------------------------------------------------------------------------------------
import malmoenv
import numpy as np
class MalmoEnvWrap(malmoenv.Env):
"""Convert observation for rllib"""
def _reshape(self, obs):
if obs is None or len(obs) == 0:
obs = np.zeros((self.height, self.width, self.depth), dtype=np.uint8)
else:
obs = obs.reshape((self.height, self.width, self.depth))
return obs
def reset(self):
"""reset"""
obs = super().reset()
obs = self._reshape(obs)
return obs
def step(self, action):
"""step"""
obs, reward, done, info = super().step(action)
obs = self._reshape(obs)
return obs, reward, done, {}
| 638 |
13,889 | __all__ = ('MultistrokeSettingsContainer', 'MultistrokeSettingItem',
'MultistrokeSettingBoolean', 'MultistrokeSettingSlider',
'MultistrokeSettingString', 'MultistrokeSettingTitle')
from kivy.factory import Factory
from kivy.lang import Builder
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.properties import (StringProperty, NumericProperty, OptionProperty,
BooleanProperty)
from kivy.uix.popup import Popup
Builder.load_file('settings.kv')
class MultistrokeSettingsContainer(GridLayout):
pass
class MultistrokeSettingItem(GridLayout):
title = StringProperty('<No title set>')
desc = StringProperty('')
class MultistrokeSettingTitle(Label):
title = StringProperty('<No title set>')
desc = StringProperty('')
class MultistrokeSettingBoolean(MultistrokeSettingItem):
button_text = StringProperty('')
value = BooleanProperty(False)
class MultistrokeSettingString(MultistrokeSettingItem):
value = StringProperty('')
class EditSettingPopup(Popup):
def __init__(self, **kwargs):
super(EditSettingPopup, self).__init__(**kwargs)
self.register_event_type('on_validate')
def on_validate(self, *l):
pass
class MultistrokeSettingSlider(MultistrokeSettingItem):
min = NumericProperty(0)
max = NumericProperty(100)
type = OptionProperty('int', options=['float', 'int'])
value = NumericProperty(0)
def __init__(self, **kwargs):
super(MultistrokeSettingSlider, self).__init__(**kwargs)
self._popup = EditSettingPopup()
self._popup.bind(on_validate=self._validate)
self._popup.bind(on_dismiss=self._dismiss)
def _to_numtype(self, v):
try:
if self.type == 'float':
return round(float(v), 1)
else:
return int(v)
except ValueError:
return self.min
def _dismiss(self, *l):
self._popup.ids.input.focus = False
def _validate(self, instance, value):
self._popup.dismiss()
val = self._to_numtype(self._popup.ids.input.text)
if val < self.min:
val = self.min
elif val > self.max:
val = self.max
self.value = val
def on_touch_down(self, touch):
if not self.ids.sliderlabel.collide_point(*touch.pos):
return super(MultistrokeSettingSlider, self).on_touch_down(touch)
ids = self._popup.ids
ids.value = str(self.value)
ids.input.text = str(self._to_numtype(self.value))
self._popup.open()
ids.input.focus = True
ids.input.select_all()
Factory.register('MultistrokeSettingsContainer',
cls=MultistrokeSettingsContainer)
Factory.register('MultistrokeSettingTitle', cls=MultistrokeSettingTitle)
Factory.register('MultistrokeSettingBoolean', cls=MultistrokeSettingBoolean)
Factory.register('MultistrokeSettingSlider', cls=MultistrokeSettingSlider)
Factory.register('MultistrokeSettingString', cls=MultistrokeSettingString)
| 1,274 |
14,668 | // 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/signin/logout_tab_helper.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/signin/identity_manager_factory.h"
#include "components/signin/public/base/signin_metrics.h"
#include "components/signin/public/identity_manager/accounts_mutator.h"
#include "components/signin/public/identity_manager/identity_manager.h"
WEB_CONTENTS_USER_DATA_KEY_IMPL(LogoutTabHelper);
LogoutTabHelper::LogoutTabHelper(content::WebContents* web_contents)
: content::WebContentsUserData<LogoutTabHelper>(*web_contents),
content::WebContentsObserver(web_contents) {}
LogoutTabHelper::~LogoutTabHelper() = default;
void LogoutTabHelper::PrimaryPageChanged(content::Page& page) {
if (page.GetMainDocument().IsErrorDocument()) {
// Failed to load the logout page, fallback to local signout.
Profile* profile =
Profile::FromBrowserContext(web_contents()->GetBrowserContext());
IdentityManagerFactory::GetForProfile(profile)
->GetAccountsMutator()
->RemoveAllAccounts(signin_metrics::SourceForRefreshTokenOperation::
kLogoutTabHelper_PrimaryPageChanged);
}
// Delete this.
web_contents()->RemoveUserData(UserDataKey());
}
| 484 |
2,690 | <reponame>PushyamiKaveti/kalibr
import bsplines
import numpy
def createExpBSpline(geometry, splineOrder, time_min, time_max, segmentNumber):
bs = bsplines.BSpline(splineOrder)
bs.initConstantSpline(time_min, time_max, segmentNumber, numpy.array((0,)))
return ExponentialBSpline(geometry, bs)
class ExponentialBSpline:
def __init__(self, geometry, bspline):
self.__geometry = geometry
self.__bs = bspline
self.setControlVertices(bspline.coefficients().transpose())
def setControlVertices(self, controlVertices):
self.__controlVertices = controlVertices
def eval(self, t):
bs = self.__bs
cumulativeBi = bs.getLocalCumulativeBi(t);
ci = bs.localVvCoefficientVectorIndices(t)
qci = self.__controlVertices[ci]
rval = qci[0]
for i in range(0,len(ci) - 1):
ldqi = self.__geometry.log(qci[i],qci[i+1])
rval= self.__geometry.exp(rval, ldqi * cumulativeBi[i+1])
return rval
def numVvCoefficients(self):
return self.__bs.numVvCoefficients()
def getBiFunction(self,t):
return self.__bs.getBiFunction(t)
def getBSpline(self):
return self.__bs
| 583 |
2,453 | <gh_stars>1000+
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 30 2020 21:18:12).
//
// Copyright (C) 1997-2019 <NAME>.
//
#import <objc/NSObject.h>
@class NSString;
@interface DVTPlistParser : NSObject
{
const unsigned short *begin;
const unsigned short *curr;
const unsigned short *end;
NSString *errorString;
}
- (void).cxx_destruct;
- (id)errorString;
- (id)parseData:(id)arg1;
- (id)parseOldStylePropertyListOrStringsFile;
- (id)parsePlistObject:(BOOL)arg1;
- (id)parsePlistData;
- (int)getDataBytes:(char *)arg1 size:(int)arg2;
- (id)parsePlistDict;
- (id)parsePlistDictContent;
- (id)parsePlistArray;
- (id)parsePlistString:(BOOL)arg1;
- (id)parseUnquotedPlistString;
- (id)parseQuotedPlistStringWithQuote:(unsigned short)arg1;
- (unsigned short)getSlashedChar;
- (unsigned int)lineNumber;
- (void)advanceToNonSpace;
@end
| 346 |
3,121 | try:
from gensim.models import KeyedVectors
except ImportError:
# No installation required if not using this function
pass
from nlpaug.model.word_embs import WordEmbeddings
class Fasttext(WordEmbeddings):
# https://arxiv.org/pdf/1712.09405.pdf,
def __init__(self, top_k=100, skip_check=False):
super().__init__(top_k, skip_check)
try:
from gensim.models import KeyedVectors
except ModuleNotFoundError:
raise ModuleNotFoundError('Missed gensim library. Install transfomers by `pip install gensim`')
self.model = None
self.words = []
def read(self, file_path, max_num_vector=None):
self.model = KeyedVectors.load_word2vec_format(file_path, limit=max_num_vector)
super()._read()
| 323 |
3,968 | from ...error import GraphQLError
from .base import ValidationRule
class UniqueVariableNames(ValidationRule):
__slots__ = 'known_variable_names',
def __init__(self, context):
super(UniqueVariableNames, self).__init__(context)
self.known_variable_names = {}
def enter_OperationDefinition(self, node, key, parent, path, ancestors):
self.known_variable_names = {}
def enter_VariableDefinition(self, node, key, parent, path, ancestors):
variable_name = node.variable.name.value
if variable_name in self.known_variable_names:
self.context.report_error(GraphQLError(
self.duplicate_variable_message(variable_name),
[self.known_variable_names[variable_name], node.variable.name]
))
else:
self.known_variable_names[variable_name] = node.variable.name
@staticmethod
def duplicate_variable_message(operation_name):
return 'There can be only one variable named "{}".'.format(operation_name)
| 391 |
1,339 | <reponame>qtcwt/robin_stocks
import os
import robin_stocks.tda as t
from dotenv import load_dotenv
load_dotenv()
class TestAuthentication:
def test_login(self):
t.login(os.environ['tda_encryption_passcode'])
assert t.get_login_state()
class TestStocks:
ticker = "TSLA"
@classmethod
def setup_class(cls):
t.login(os.environ['tda_encryption_passcode'])
def test_quote(self):
resp, err = t.get_quote(self.ticker)
data = resp.json()
assert resp.status_code == 200
assert err is None
assert self.ticker in data
| 262 |
14,668 | // 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.
#ifndef COMPONENTS_WINHTTP_PROXY_CONFIGURATION_H_
#define COMPONENTS_WINHTTP_PROXY_CONFIGURATION_H_
#include <windows.h>
#include <winhttp.h>
#include "base/memory/ref_counted.h"
#include "components/winhttp/proxy_info.h"
#include "components/winhttp/scoped_winttp_proxy_info.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
class GURL;
namespace winhttp {
// On Windows 8.1 and above, we can use Auto Proxy mode in WinHTTP and let
// the OS configure the proxy.
// This is represented by the AutoProxyConfiguration class.
// When a proxy related policy is set or when using Windows 8 or below,
// we'd set proxy manually using ProxyConfiguration class.
//
// Default WinHTTP proxy strategy - provide proxy server info to WinHTTP.
// Used when policy is set or on Windows 8 and below.
// This class can use either provided proxy information from the
// IE Config or a policy policy setting or query per request proxy info
// with WPAD (Web Proxy Auto Discovery).
class ProxyConfiguration : public base::RefCounted<ProxyConfiguration> {
public:
ProxyConfiguration() = default;
explicit ProxyConfiguration(const ProxyInfo& proxy_info);
ProxyConfiguration(const ProxyConfiguration&) = delete;
ProxyConfiguration& operator=(const ProxyConfiguration&) = delete;
int access_type() const;
absl::optional<ScopedWinHttpProxyInfo> GetProxyForUrl(
HINTERNET session_handle,
const GURL& url) const;
protected:
virtual ~ProxyConfiguration() = default;
private:
friend class base::RefCounted<ProxyConfiguration>;
virtual int DoGetAccessType() const;
virtual absl::optional<ScopedWinHttpProxyInfo> DoGetProxyForUrl(
HINTERNET session_handle,
const GURL& url) const;
ProxyInfo proxy_info_;
};
// Auto proxy strategy - let WinHTTP detect proxy settings.
// This is only available on Windows 8.1 and above.
class AutoProxyConfiguration final : public ProxyConfiguration {
protected:
~AutoProxyConfiguration() override = default;
private:
// Overrides for ProxyConfiguration.
int DoGetAccessType() const override;
absl::optional<ScopedWinHttpProxyInfo> DoGetProxyForUrl(
HINTERNET session_handle,
const GURL& url) const override;
};
// Sets proxy info on a request handle, if WINHTTP_PROXY_INFO is provided.
void SetProxyForRequest(
const HINTERNET request_handle,
const absl::optional<ScopedWinHttpProxyInfo>& winhttp_proxy_info);
} // namespace winhttp
#endif // COMPONENTS_WINHTTP_PROXY_CONFIGURATION_H_
| 781 |
5,169 | <reponame>Gantios/Specs<gh_stars>1000+
{
"name": "HSCustomView",
"version": "0.0.9",
"summary": "HSCustomView is my custom view library at working. This will bring convenience for later work.",
"description": "The custom view library contains any views. For example progressView, ... and so on! This will bring convenience for later work.",
"homepage": "https://github.com/huanghaisheng/HSCustomView",
"license": "MIT",
"authors": {
"haisheng": "<EMAIL>"
},
"platforms": {
"ios": "8.0"
},
"source": {
"git": "https://github.com/huanghaisheng/HSCustomView.git",
"tag": "0.0.9"
},
"source_files": "HSCustomView/HSCustomView/**/*.{h,m,swift}",
"requires_arc": true,
"pod_target_xcconfig": {
"swift_version": "2.3"
},
"pushed_with_swift_version": "3.0"
}
| 317 |
2,151 | <gh_stars>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 "base/debug/thread_heap_usage_tracker.h"
#include <map>
#include "base/allocator/allocator_shim.h"
#include "base/allocator/buildflags.h"
#include "testing/gtest/include/gtest/gtest.h"
#if defined(OS_MACOSX)
#include "base/allocator/allocator_interception_mac.h"
#endif
namespace base {
namespace debug {
namespace {
class TestingThreadHeapUsageTracker : public ThreadHeapUsageTracker {
public:
using ThreadHeapUsageTracker::DisableHeapTrackingForTesting;
using ThreadHeapUsageTracker::EnsureTLSInitialized;
using ThreadHeapUsageTracker::GetDispatchForTesting;
};
// A fixture class that allows testing the AllocatorDispatch associated with
// the ThreadHeapUsageTracker class in isolation against a mocked
// underlying
// heap implementation.
class ThreadHeapUsageTrackerTest : public testing::Test {
public:
using AllocatorDispatch = base::allocator::AllocatorDispatch;
static const size_t kAllocationPadding;
enum SizeFunctionKind {
EXACT_SIZE_FUNCTION,
PADDING_SIZE_FUNCTION,
ZERO_SIZE_FUNCTION,
};
ThreadHeapUsageTrackerTest() : size_function_kind_(EXACT_SIZE_FUNCTION) {
EXPECT_EQ(nullptr, g_self);
g_self = this;
}
~ThreadHeapUsageTrackerTest() override {
EXPECT_EQ(this, g_self);
g_self = nullptr;
}
void set_size_function_kind(SizeFunctionKind kind) {
size_function_kind_ = kind;
}
void SetUp() override {
TestingThreadHeapUsageTracker::EnsureTLSInitialized();
dispatch_under_test_ =
TestingThreadHeapUsageTracker::GetDispatchForTesting();
ASSERT_EQ(nullptr, dispatch_under_test_->next);
dispatch_under_test_->next = &g_mock_dispatch;
}
void TearDown() override {
ASSERT_EQ(&g_mock_dispatch, dispatch_under_test_->next);
dispatch_under_test_->next = nullptr;
}
void* MockMalloc(size_t size) {
return dispatch_under_test_->alloc_function(dispatch_under_test_, size,
nullptr);
}
void* MockCalloc(size_t n, size_t size) {
return dispatch_under_test_->alloc_zero_initialized_function(
dispatch_under_test_, n, size, nullptr);
}
void* MockAllocAligned(size_t alignment, size_t size) {
return dispatch_under_test_->alloc_aligned_function(
dispatch_under_test_, alignment, size, nullptr);
}
void* MockRealloc(void* address, size_t size) {
return dispatch_under_test_->realloc_function(dispatch_under_test_, address,
size, nullptr);
}
void MockFree(void* address) {
dispatch_under_test_->free_function(dispatch_under_test_, address, nullptr);
}
size_t MockGetSizeEstimate(void* address) {
return dispatch_under_test_->get_size_estimate_function(
dispatch_under_test_, address, nullptr);
}
private:
void RecordAlloc(void* address, size_t size) {
if (address != nullptr)
allocation_size_map_[address] = size;
}
void DeleteAlloc(void* address) {
if (address != nullptr)
EXPECT_EQ(1U, allocation_size_map_.erase(address));
}
size_t GetSizeEstimate(void* address) {
auto it = allocation_size_map_.find(address);
if (it == allocation_size_map_.end())
return 0;
size_t ret = it->second;
switch (size_function_kind_) {
case EXACT_SIZE_FUNCTION:
break;
case PADDING_SIZE_FUNCTION:
ret += kAllocationPadding;
break;
case ZERO_SIZE_FUNCTION:
ret = 0;
break;
}
return ret;
}
static void* OnAllocFn(const AllocatorDispatch* self,
size_t size,
void* context) {
EXPECT_EQ(&g_mock_dispatch, self);
void* ret = malloc(size);
g_self->RecordAlloc(ret, size);
return ret;
}
static void* OnAllocZeroInitializedFn(const AllocatorDispatch* self,
size_t n,
size_t size,
void* context) {
EXPECT_EQ(&g_mock_dispatch, self);
void* ret = calloc(n, size);
g_self->RecordAlloc(ret, n * size);
return ret;
}
static void* OnAllocAlignedFn(const AllocatorDispatch* self,
size_t alignment,
size_t size,
void* context) {
EXPECT_EQ(&g_mock_dispatch, self);
// This is a cheat as it doesn't return aligned allocations. This has the
// advantage of working for all platforms for this test.
void* ret = malloc(size);
g_self->RecordAlloc(ret, size);
return ret;
}
static void* OnReallocFn(const AllocatorDispatch* self,
void* address,
size_t size,
void* context) {
EXPECT_EQ(&g_mock_dispatch, self);
g_self->DeleteAlloc(address);
void* ret = realloc(address, size);
g_self->RecordAlloc(ret, size);
return ret;
}
static void OnFreeFn(const AllocatorDispatch* self,
void* address,
void* context) {
EXPECT_EQ(&g_mock_dispatch, self);
g_self->DeleteAlloc(address);
free(address);
}
static size_t OnGetSizeEstimateFn(const AllocatorDispatch* self,
void* address,
void* context) {
EXPECT_EQ(&g_mock_dispatch, self);
return g_self->GetSizeEstimate(address);
}
using AllocationSizeMap = std::map<void*, size_t>;
SizeFunctionKind size_function_kind_;
AllocationSizeMap allocation_size_map_;
AllocatorDispatch* dispatch_under_test_;
static base::allocator::AllocatorDispatch g_mock_dispatch;
static ThreadHeapUsageTrackerTest* g_self;
};
const size_t ThreadHeapUsageTrackerTest::kAllocationPadding = 23;
ThreadHeapUsageTrackerTest* ThreadHeapUsageTrackerTest::g_self = nullptr;
base::allocator::AllocatorDispatch ThreadHeapUsageTrackerTest::g_mock_dispatch =
{
&ThreadHeapUsageTrackerTest::OnAllocFn, // alloc_function
&ThreadHeapUsageTrackerTest::
OnAllocZeroInitializedFn, // alloc_zero_initialized_function
&ThreadHeapUsageTrackerTest::
OnAllocAlignedFn, // alloc_aligned_function
&ThreadHeapUsageTrackerTest::OnReallocFn, // realloc_function
&ThreadHeapUsageTrackerTest::OnFreeFn, // free_function
&ThreadHeapUsageTrackerTest::
OnGetSizeEstimateFn, // get_size_estimate_function
nullptr, // batch_malloc
nullptr, // batch_free
nullptr, // free_definite_size_function
nullptr, // next
};
} // namespace
TEST_F(ThreadHeapUsageTrackerTest, SimpleUsageWithExactSizeFunction) {
set_size_function_kind(EXACT_SIZE_FUNCTION);
ThreadHeapUsageTracker usage_tracker;
usage_tracker.Start();
ThreadHeapUsage u1 = ThreadHeapUsageTracker::GetUsageSnapshot();
EXPECT_EQ(0U, u1.alloc_ops);
EXPECT_EQ(0U, u1.alloc_bytes);
EXPECT_EQ(0U, u1.alloc_overhead_bytes);
EXPECT_EQ(0U, u1.free_ops);
EXPECT_EQ(0U, u1.free_bytes);
EXPECT_EQ(0U, u1.max_allocated_bytes);
const size_t kAllocSize = 1029U;
void* ptr = MockMalloc(kAllocSize);
MockFree(ptr);
usage_tracker.Stop(false);
ThreadHeapUsage u2 = usage_tracker.usage();
EXPECT_EQ(1U, u2.alloc_ops);
EXPECT_EQ(kAllocSize, u2.alloc_bytes);
EXPECT_EQ(0U, u2.alloc_overhead_bytes);
EXPECT_EQ(1U, u2.free_ops);
EXPECT_EQ(kAllocSize, u2.free_bytes);
EXPECT_EQ(kAllocSize, u2.max_allocated_bytes);
}
TEST_F(ThreadHeapUsageTrackerTest, SimpleUsageWithPaddingSizeFunction) {
set_size_function_kind(PADDING_SIZE_FUNCTION);
ThreadHeapUsageTracker usage_tracker;
usage_tracker.Start();
ThreadHeapUsage u1 = ThreadHeapUsageTracker::GetUsageSnapshot();
EXPECT_EQ(0U, u1.alloc_ops);
EXPECT_EQ(0U, u1.alloc_bytes);
EXPECT_EQ(0U, u1.alloc_overhead_bytes);
EXPECT_EQ(0U, u1.free_ops);
EXPECT_EQ(0U, u1.free_bytes);
EXPECT_EQ(0U, u1.max_allocated_bytes);
const size_t kAllocSize = 1029U;
void* ptr = MockMalloc(kAllocSize);
MockFree(ptr);
usage_tracker.Stop(false);
ThreadHeapUsage u2 = usage_tracker.usage();
EXPECT_EQ(1U, u2.alloc_ops);
EXPECT_EQ(kAllocSize + kAllocationPadding, u2.alloc_bytes);
EXPECT_EQ(kAllocationPadding, u2.alloc_overhead_bytes);
EXPECT_EQ(1U, u2.free_ops);
EXPECT_EQ(kAllocSize + kAllocationPadding, u2.free_bytes);
EXPECT_EQ(kAllocSize + kAllocationPadding, u2.max_allocated_bytes);
}
TEST_F(ThreadHeapUsageTrackerTest, SimpleUsageWithZeroSizeFunction) {
set_size_function_kind(ZERO_SIZE_FUNCTION);
ThreadHeapUsageTracker usage_tracker;
usage_tracker.Start();
ThreadHeapUsage u1 = ThreadHeapUsageTracker::GetUsageSnapshot();
EXPECT_EQ(0U, u1.alloc_ops);
EXPECT_EQ(0U, u1.alloc_bytes);
EXPECT_EQ(0U, u1.alloc_overhead_bytes);
EXPECT_EQ(0U, u1.free_ops);
EXPECT_EQ(0U, u1.free_bytes);
EXPECT_EQ(0U, u1.max_allocated_bytes);
const size_t kAllocSize = 1029U;
void* ptr = MockMalloc(kAllocSize);
MockFree(ptr);
usage_tracker.Stop(false);
ThreadHeapUsage u2 = usage_tracker.usage();
// With a get-size function that returns zero, there's no way to get the size
// of an allocation that's being freed, hence the shim can't tally freed bytes
// nor the high-watermark allocated bytes.
EXPECT_EQ(1U, u2.alloc_ops);
EXPECT_EQ(kAllocSize, u2.alloc_bytes);
EXPECT_EQ(0U, u2.alloc_overhead_bytes);
EXPECT_EQ(1U, u2.free_ops);
EXPECT_EQ(0U, u2.free_bytes);
EXPECT_EQ(0U, u2.max_allocated_bytes);
}
TEST_F(ThreadHeapUsageTrackerTest, ReallocCorrectlyTallied) {
const size_t kAllocSize = 237U;
{
ThreadHeapUsageTracker usage_tracker;
usage_tracker.Start();
// Reallocating nullptr should count as a single alloc.
void* ptr = MockRealloc(nullptr, kAllocSize);
ThreadHeapUsage usage = ThreadHeapUsageTracker::GetUsageSnapshot();
EXPECT_EQ(1U, usage.alloc_ops);
EXPECT_EQ(kAllocSize, usage.alloc_bytes);
EXPECT_EQ(0U, usage.alloc_overhead_bytes);
EXPECT_EQ(0U, usage.free_ops);
EXPECT_EQ(0U, usage.free_bytes);
EXPECT_EQ(kAllocSize, usage.max_allocated_bytes);
// Reallocating a valid pointer to a zero size should count as a single
// free.
ptr = MockRealloc(ptr, 0U);
usage_tracker.Stop(false);
EXPECT_EQ(1U, usage_tracker.usage().alloc_ops);
EXPECT_EQ(kAllocSize, usage_tracker.usage().alloc_bytes);
EXPECT_EQ(0U, usage_tracker.usage().alloc_overhead_bytes);
EXPECT_EQ(1U, usage_tracker.usage().free_ops);
EXPECT_EQ(kAllocSize, usage_tracker.usage().free_bytes);
EXPECT_EQ(kAllocSize, usage_tracker.usage().max_allocated_bytes);
// Realloc to zero size may or may not return a nullptr - make sure to
// free the zero-size alloc in the latter case.
if (ptr != nullptr)
MockFree(ptr);
}
{
ThreadHeapUsageTracker usage_tracker;
usage_tracker.Start();
void* ptr = MockMalloc(kAllocSize);
ThreadHeapUsage usage = ThreadHeapUsageTracker::GetUsageSnapshot();
EXPECT_EQ(1U, usage.alloc_ops);
// Now try reallocating a valid pointer to a larger size, this should count
// as one free and one alloc.
const size_t kLargerAllocSize = kAllocSize + 928U;
ptr = MockRealloc(ptr, kLargerAllocSize);
usage_tracker.Stop(false);
EXPECT_EQ(2U, usage_tracker.usage().alloc_ops);
EXPECT_EQ(kAllocSize + kLargerAllocSize, usage_tracker.usage().alloc_bytes);
EXPECT_EQ(0U, usage_tracker.usage().alloc_overhead_bytes);
EXPECT_EQ(1U, usage_tracker.usage().free_ops);
EXPECT_EQ(kAllocSize, usage_tracker.usage().free_bytes);
EXPECT_EQ(kLargerAllocSize, usage_tracker.usage().max_allocated_bytes);
MockFree(ptr);
}
}
TEST_F(ThreadHeapUsageTrackerTest, NestedMaxWorks) {
ThreadHeapUsageTracker usage_tracker;
usage_tracker.Start();
const size_t kOuterAllocSize = 1029U;
void* ptr = MockMalloc(kOuterAllocSize);
MockFree(ptr);
EXPECT_EQ(kOuterAllocSize,
ThreadHeapUsageTracker::GetUsageSnapshot().max_allocated_bytes);
{
ThreadHeapUsageTracker inner_usage_tracker;
inner_usage_tracker.Start();
const size_t kInnerAllocSize = 673U;
ptr = MockMalloc(kInnerAllocSize);
MockFree(ptr);
inner_usage_tracker.Stop(false);
EXPECT_EQ(kInnerAllocSize, inner_usage_tracker.usage().max_allocated_bytes);
}
// The greater, outer allocation size should have been restored.
EXPECT_EQ(kOuterAllocSize,
ThreadHeapUsageTracker::GetUsageSnapshot().max_allocated_bytes);
const size_t kLargerInnerAllocSize = kOuterAllocSize + 673U;
{
ThreadHeapUsageTracker inner_usage_tracker;
inner_usage_tracker.Start();
ptr = MockMalloc(kLargerInnerAllocSize);
MockFree(ptr);
inner_usage_tracker.Stop(false);
EXPECT_EQ(kLargerInnerAllocSize,
inner_usage_tracker.usage().max_allocated_bytes);
}
// The greater, inner allocation size should have been preserved.
EXPECT_EQ(kLargerInnerAllocSize,
ThreadHeapUsageTracker::GetUsageSnapshot().max_allocated_bytes);
// Now try the case with an outstanding net alloc size when entering the
// inner scope.
void* outer_ptr = MockMalloc(kOuterAllocSize);
EXPECT_EQ(kLargerInnerAllocSize,
ThreadHeapUsageTracker::GetUsageSnapshot().max_allocated_bytes);
{
ThreadHeapUsageTracker inner_usage_tracker;
inner_usage_tracker.Start();
ptr = MockMalloc(kLargerInnerAllocSize);
MockFree(ptr);
inner_usage_tracker.Stop(false);
EXPECT_EQ(kLargerInnerAllocSize,
inner_usage_tracker.usage().max_allocated_bytes);
}
// While the inner scope saw only the inner net outstanding allocation size,
// the outer scope saw both outstanding at the same time.
EXPECT_EQ(kOuterAllocSize + kLargerInnerAllocSize,
ThreadHeapUsageTracker::GetUsageSnapshot().max_allocated_bytes);
MockFree(outer_ptr);
// Test a net-negative scope.
ptr = MockMalloc(kLargerInnerAllocSize);
{
ThreadHeapUsageTracker inner_usage_tracker;
inner_usage_tracker.Start();
MockFree(ptr);
const size_t kInnerAllocSize = 1;
ptr = MockMalloc(kInnerAllocSize);
inner_usage_tracker.Stop(false);
// Since the scope is still net-negative, the max is clamped at zero.
EXPECT_EQ(0U, inner_usage_tracker.usage().max_allocated_bytes);
}
MockFree(ptr);
}
TEST_F(ThreadHeapUsageTrackerTest, NoStopImpliesInclusive) {
ThreadHeapUsageTracker usage_tracker;
usage_tracker.Start();
const size_t kOuterAllocSize = 1029U;
void* ptr = MockMalloc(kOuterAllocSize);
MockFree(ptr);
ThreadHeapUsage usage = ThreadHeapUsageTracker::GetUsageSnapshot();
EXPECT_EQ(kOuterAllocSize, usage.max_allocated_bytes);
const size_t kInnerLargerAllocSize = kOuterAllocSize + 673U;
{
ThreadHeapUsageTracker inner_usage_tracker;
inner_usage_tracker.Start();
// Make a larger allocation than the outer scope.
ptr = MockMalloc(kInnerLargerAllocSize);
MockFree(ptr);
// inner_usage_tracker goes out of scope without a Stop().
}
ThreadHeapUsage current = ThreadHeapUsageTracker::GetUsageSnapshot();
EXPECT_EQ(usage.alloc_ops + 1, current.alloc_ops);
EXPECT_EQ(usage.alloc_bytes + kInnerLargerAllocSize, current.alloc_bytes);
EXPECT_EQ(usage.free_ops + 1, current.free_ops);
EXPECT_EQ(usage.free_bytes + kInnerLargerAllocSize, current.free_bytes);
EXPECT_EQ(kInnerLargerAllocSize, current.max_allocated_bytes);
}
TEST_F(ThreadHeapUsageTrackerTest, ExclusiveScopesWork) {
ThreadHeapUsageTracker usage_tracker;
usage_tracker.Start();
const size_t kOuterAllocSize = 1029U;
void* ptr = MockMalloc(kOuterAllocSize);
MockFree(ptr);
ThreadHeapUsage usage = ThreadHeapUsageTracker::GetUsageSnapshot();
EXPECT_EQ(kOuterAllocSize, usage.max_allocated_bytes);
{
ThreadHeapUsageTracker inner_usage_tracker;
inner_usage_tracker.Start();
// Make a larger allocation than the outer scope.
ptr = MockMalloc(kOuterAllocSize + 673U);
MockFree(ptr);
// This tracker is exlusive, all activity should be private to this scope.
inner_usage_tracker.Stop(true);
}
ThreadHeapUsage current = ThreadHeapUsageTracker::GetUsageSnapshot();
EXPECT_EQ(usage.alloc_ops, current.alloc_ops);
EXPECT_EQ(usage.alloc_bytes, current.alloc_bytes);
EXPECT_EQ(usage.alloc_overhead_bytes, current.alloc_overhead_bytes);
EXPECT_EQ(usage.free_ops, current.free_ops);
EXPECT_EQ(usage.free_bytes, current.free_bytes);
EXPECT_EQ(usage.max_allocated_bytes, current.max_allocated_bytes);
}
TEST_F(ThreadHeapUsageTrackerTest, AllShimFunctionsAreProvided) {
const size_t kAllocSize = 100;
void* alloc = MockMalloc(kAllocSize);
size_t estimate = MockGetSizeEstimate(alloc);
ASSERT_TRUE(estimate == 0 || estimate >= kAllocSize);
MockFree(alloc);
alloc = MockCalloc(kAllocSize, 1);
estimate = MockGetSizeEstimate(alloc);
ASSERT_TRUE(estimate == 0 || estimate >= kAllocSize);
MockFree(alloc);
alloc = MockAllocAligned(1, kAllocSize);
estimate = MockGetSizeEstimate(alloc);
ASSERT_TRUE(estimate == 0 || estimate >= kAllocSize);
alloc = MockRealloc(alloc, kAllocSize);
estimate = MockGetSizeEstimate(alloc);
ASSERT_TRUE(estimate == 0 || estimate >= kAllocSize);
MockFree(alloc);
}
#if BUILDFLAG(USE_ALLOCATOR_SHIM)
class ThreadHeapUsageShimTest : public testing::Test {
#if defined(OS_MACOSX)
void SetUp() override { allocator::InitializeAllocatorShim(); }
void TearDown() override { allocator::UninterceptMallocZonesForTesting(); }
#endif
};
TEST_F(ThreadHeapUsageShimTest, HooksIntoMallocWhenShimAvailable) {
ASSERT_FALSE(ThreadHeapUsageTracker::IsHeapTrackingEnabled());
ThreadHeapUsageTracker::EnableHeapTracking();
ASSERT_TRUE(ThreadHeapUsageTracker::IsHeapTrackingEnabled());
const size_t kAllocSize = 9993;
// This test verifies that the scoped heap data is affected by malloc &
// free only when the shim is available.
ThreadHeapUsageTracker usage_tracker;
usage_tracker.Start();
ThreadHeapUsage u1 = ThreadHeapUsageTracker::GetUsageSnapshot();
void* ptr = malloc(kAllocSize);
// Prevent the compiler from optimizing out the malloc/free pair.
ASSERT_NE(nullptr, ptr);
ThreadHeapUsage u2 = ThreadHeapUsageTracker::GetUsageSnapshot();
free(ptr);
usage_tracker.Stop(false);
ThreadHeapUsage u3 = usage_tracker.usage();
// Verify that at least one allocation operation was recorded, and that free
// operations are at least monotonically growing.
EXPECT_LE(0U, u1.alloc_ops);
EXPECT_LE(u1.alloc_ops + 1, u2.alloc_ops);
EXPECT_LE(u1.alloc_ops + 1, u3.alloc_ops);
// Verify that at least the bytes above were recorded.
EXPECT_LE(u1.alloc_bytes + kAllocSize, u2.alloc_bytes);
// Verify that at least the one free operation above was recorded.
EXPECT_LE(u2.free_ops + 1, u3.free_ops);
TestingThreadHeapUsageTracker::DisableHeapTrackingForTesting();
ASSERT_FALSE(ThreadHeapUsageTracker::IsHeapTrackingEnabled());
}
#endif // BUILDFLAG(USE_ALLOCATOR_SHIM)
} // namespace debug
} // namespace base
| 7,733 |
831 | <gh_stars>100-1000
/*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.room.migrations.ui;
import com.intellij.ide.wizard.CommitStepException;
import com.intellij.ide.wizard.Step;
import com.intellij.openapi.application.WriteAction;
import com.intellij.openapi.project.Project;
import com.intellij.psi.JavaPsiFacade;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiPackage;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.refactoring.MoveDestination;
import com.intellij.refactoring.PackageWrapper;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.move.moveClassesOrPackages.DestinationFolderComboBox;
import com.intellij.refactoring.ui.PackageNameReferenceEditorCombo;
import com.intellij.ui.ReferenceEditorComboWithBrowseButton;
import com.intellij.ui.components.JBLabel;
import java.awt.BorderLayout;
import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.JComponent;
import javax.swing.JPanel;
import org.jetbrains.annotations.NotNull;
/**
* Step of the {@link GenerateMigrationWizard} for selecting the destination folders for the new Migration class and test
*/
public class GenerateMigrationWizardSelectDestinationStep implements GenerateMigrationWizardStep {
private static final String TARGET_PACKAGE_LABEL = "Choose target package package";
private static final String MIGRATION_CLASS_COMBO_BOX_LABEL = "Choose destination directory for the migration class";
private static final String MIGRATION_TEST_COMBO_BOX_LABEL = "Choose destination directory for the migration test";
private GenerateMigrationWizardData wizardData;
private Project project;
private PsiPackage targetPackage;
private PsiDirectory migrationClassDirectory;
private PsiDirectory migrationTestDirectory;
private DestinationFolderComboBox migrationClassDirectoryComboBox;
private DestinationFolderComboBox migrationTestDirectoryComboBox;
private ReferenceEditorComboWithBrowseButton targetPackageComboBox;
private JPanel centerPanel;
public GenerateMigrationWizardSelectDestinationStep(@NotNull GenerateMigrationWizardData wizardData) {
this.wizardData = wizardData;
this.project = wizardData.getProject();
this.targetPackage = wizardData.getTargetPackage();
this.migrationClassDirectory = wizardData.getMigrationClassDirectory();
this.migrationTestDirectory = wizardData.getMigrationTestDirectory();
targetPackageComboBox = new PackageNameReferenceEditorCombo(targetPackage.getQualifiedName(), project, "", TARGET_PACKAGE_LABEL);
migrationClassDirectoryComboBox = createDestinationFolderComboBox();
migrationClassDirectoryComboBox.setData(project, migrationClassDirectory, targetPackageComboBox.getChildComponent());
migrationTestDirectoryComboBox = createDestinationFolderComboBox();
migrationTestDirectoryComboBox.setData(project, migrationTestDirectory, targetPackageComboBox.getChildComponent());
}
@Override
public void _init() {
if (centerPanel == null) {
createCenterPanel();
}
}
@Override
public void _commit(boolean finishChosen) throws CommitStepException {
final MoveDestination classMoveDestination =
migrationClassDirectoryComboBox.selectDirectory(PackageWrapper.create(targetPackage), false);
if (classMoveDestination != null) {
assert migrationClassDirectory != null;
migrationClassDirectory = WriteAction.compute(() -> classMoveDestination.getTargetDirectory(migrationClassDirectory));
}
final MoveDestination testMoveDestination =
migrationTestDirectoryComboBox.selectDirectory(PackageWrapper.create(targetPackage), false);
if (testMoveDestination != null) {
assert migrationTestDirectory != null;
migrationTestDirectory = WriteAction.compute(() -> testMoveDestination.getTargetDirectory(migrationTestDirectory));
}
wizardData.updateTargetPackage(targetPackage);
wizardData.updateMigrationClassDirectory(migrationClassDirectory);
wizardData.updateMigrationTestDirectory(migrationTestDirectory);
}
@Override
public Icon getIcon() {
return null;
}
@Override
public JComponent getComponent() {
return centerPanel;
}
@Override
public JComponent getPreferredFocusedComponent() {
return targetPackageComboBox;
}
private DestinationFolderComboBox createDestinationFolderComboBox() {
return new DestinationFolderComboBox() {
@Override
public String getTargetPackage() {
if (packageWasChanged()) {
onPackageChange();
}
return targetPackage.getQualifiedName();
}
};
}
private boolean packageWasChanged() {
return !targetPackage.getQualifiedName().equals(targetPackageComboBox.getText().trim());
}
private void onPackageChange() {
PsiPackage newPackage = JavaPsiFacade.getInstance(project).findPackage(targetPackageComboBox.getText().trim());
if (newPackage == null) {
return;
}
PsiDirectory[] newDirectories = newPackage.getDirectories(GlobalSearchScope.projectScope(project));
if (newDirectories.length > 0) {
targetPackage = newPackage;
migrationClassDirectory = newDirectories[0];
migrationClassDirectoryComboBox.setData(project, migrationClassDirectory, targetPackageComboBox.getChildComponent());
}
}
private JPanel createTargetDirectoryPanel(@NotNull DestinationFolderComboBox comboBox,
@NotNull String labelText) {
final JPanel targetDirectoryPanel = new JPanel(new BorderLayout());
final JBLabel label = new JBLabel(labelText);
targetDirectoryPanel.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
targetDirectoryPanel.add(comboBox, BorderLayout.CENTER);
targetDirectoryPanel.add(label, BorderLayout.NORTH);
label.setLabelFor(comboBox);
return targetDirectoryPanel;
}
private JPanel createTargetPackagePanel() {
JPanel targetPackagePanel = new JPanel(new BorderLayout());
final JBLabel label = new JBLabel(RefactoringBundle.message("choose.destination.package"));
targetPackagePanel.add(targetPackageComboBox, BorderLayout.CENTER);
targetPackagePanel.add(label, BorderLayout.NORTH);
label.setLabelFor(targetPackageComboBox);
return targetPackagePanel;
}
protected void createCenterPanel() {
centerPanel = new JPanel(new BorderLayout());
centerPanel.add(createTargetPackagePanel(), BorderLayout.NORTH);
JPanel directoriesPanel = new JPanel((new BorderLayout()));
directoriesPanel.add(createTargetDirectoryPanel(migrationClassDirectoryComboBox, MIGRATION_CLASS_COMBO_BOX_LABEL), BorderLayout.NORTH);
directoriesPanel.add(createTargetDirectoryPanel(migrationTestDirectoryComboBox, MIGRATION_TEST_COMBO_BOX_LABEL), BorderLayout.SOUTH);
centerPanel.add(directoriesPanel, BorderLayout.SOUTH);
}
@Override
public boolean shouldBeSkipped() {
return false;
}
}
| 2,284 |
482 | <filename>modules/caas/auth/src/main/java/io/cattle/platform/iaas/api/auth/integration/interfaces/TokenCreator.java
package io.cattle.platform.iaas.api.auth.integration.interfaces;
import io.cattle.platform.iaas.api.auth.identity.Token;
import io.github.ibuildthecloud.gdapi.request.ApiRequest;
public interface TokenCreator extends Configurable, Provider{
Token getToken(ApiRequest request);
Token getCurrentToken();
void reset();
}
| 150 |
375 | package io.lumify.dbpedia.mapreduce;
import io.lumify.core.mapreduce.LumifyMRBase;
import io.lumify.core.util.LumifyLogger;
import io.lumify.core.util.LumifyLoggerFactory;
import org.apache.accumulo.core.data.Mutation;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.util.ToolRunner;
import org.securegraph.accumulo.mapreduce.AccumuloElementOutputFormat;
public class ImportMR extends LumifyMRBase {
private static final LumifyLogger LOGGER = LumifyLoggerFactory.getLogger(ImportMR.class);
public static final String MULTI_VALUE_KEY = ImportMR.class.getName();
@Override
protected String getJobName() {
return "dbpediaImport";
}
@Override
protected void setupJob(Job job) throws Exception {
job.setJarByClass(ImportMR.class);
job.setMapperClass(ImportMRMapper.class);
job.setNumReduceTasks(0);
job.setMapOutputValueClass(Mutation.class);
job.setInputFormatClass(TextInputFormat.class);
job.setOutputFormatClass(AccumuloElementOutputFormat.class);
FileInputFormat.addInputPath(job, new Path(getConf().get("in")));
}
@Override
protected void parseArgs(JobConf conf, String[] args) {
if (args.length != 1) {
throw new RuntimeException("Required arguments <inputFileName>");
}
String inFileName = args[0];
LOGGER.info("inFileName: %s", inFileName);
conf.set("in", inFileName);
}
public static void main(String[] args) throws Exception {
int res = ToolRunner.run(new Configuration(), new ImportMR(), args);
System.exit(res);
}
}
| 715 |
7,409 | from posthog.settings.base_variables import E2E_TESTING, TEST
from posthog.settings.overrides import cmd
from posthog.settings.service_requirements import SKIP_SERVICE_VERSION_REQUIREMENTS
from posthog.settings.utils import get_from_env, str_to_bool
AUTO_START_ASYNC_MIGRATIONS = get_from_env("AUTO_START_ASYNC_MIGRATIONS", False, type_cast=str_to_bool)
_default_skip_async_migrations_setup = TEST or E2E_TESTING or SKIP_SERVICE_VERSION_REQUIREMENTS or cmd != "runserver"
SKIP_ASYNC_MIGRATIONS_SETUP = get_from_env(
"SKIP_ASYNC_MIGRATIONS_SETUP", _default_skip_async_migrations_setup, type_cast=str_to_bool
)
ASYNC_MIGRATIONS_ROLLBACK_TIMEOUT = get_from_env("ASYNC_MIGRATION_ROLLBACK_TIMEOUT", 30, type_cast=int)
ASYNC_MIGRATIONS_DISABLE_AUTO_ROLLBACK = get_from_env(
"ASYNC_MIGRATIONS_DISABLE_AUTO_ROLLBACK", False, type_cast=str_to_bool
)
| 340 |
305 | //*****************************************************************************
// Copyright 2021 Intel Corporation
//
// 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 "global_sequences_viewer.hpp"
#include <limits>
#include <memory>
#include <utility>
#include "logging.hpp"
#include "model.hpp"
#include "modelversion.hpp"
#include "statefulmodelinstance.hpp"
#include "status.hpp"
namespace ovms {
static std::string separator = "_";
Status GlobalSequencesViewer::registerForCleanup(std::string modelName, model_version_t modelVersion, std::shared_ptr<SequenceManager> sequenceManager) {
std::string registration_id = modelName + separator + std::to_string(modelVersion);
std::unique_lock<std::mutex> viewerLock(viewerMutex);
if (registeredSequenceManagers.find(registration_id) != registeredSequenceManagers.end()) {
SPDLOG_LOGGER_ERROR(sequence_manager_logger, "Model: {}, version: {}, cannot register model instance in sequence cleaner. Already registered.", modelName, modelVersion);
return StatusCode::INTERNAL_ERROR;
} else {
registeredSequenceManagers.emplace(registration_id, sequenceManager);
SPDLOG_LOGGER_DEBUG(sequence_manager_logger, "Model: {}, version: {}, has been successfully registered in sequence cleaner", modelName, modelVersion);
}
return StatusCode::OK;
}
Status GlobalSequencesViewer::unregisterFromCleanup(std::string modelName, model_version_t modelVersion) {
std::string registration_id = modelName + separator + std::to_string(modelVersion);
std::unique_lock<std::mutex> viewerLock(viewerMutex);
auto it = registeredSequenceManagers.find(registration_id);
if (it != registeredSequenceManagers.end()) {
registeredSequenceManagers.erase(it);
SPDLOG_LOGGER_DEBUG(sequence_manager_logger, "Model: {}, version: {}, has been successfully unregistered from sequence cleaner", modelName, modelVersion);
} else {
SPDLOG_LOGGER_DEBUG(sequence_manager_logger, "Model: {}, version: {}, cannot unregister model instance from sequence cleaner. It has not been registered.", modelName, modelVersion);
return StatusCode::INTERNAL_ERROR;
}
return StatusCode::OK;
}
Status GlobalSequencesViewer::removeIdleSequences() {
std::unique_lock<std::mutex> viewerLock(viewerMutex);
for (auto it = registeredSequenceManagers.begin(); it != registeredSequenceManagers.end();) {
auto sequenceManager = it->second;
auto status = sequenceManager->removeIdleSequences();
it++;
if (status.getCode() != ovms::StatusCode::OK)
return status;
}
return ovms::StatusCode::OK;
}
} // namespace ovms
| 1,004 |
1,553 | <gh_stars>1000+
/*
* The MIT License (MIT)
*
* Copyright © 2015-2016 Franklin "Snaipe" Mathieu <http://snai.pe/>
*
* 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.
*/
#ifndef CSPTR_SMALLOC_H_
# define CSPTR_SMALLOC_H_
# include <stdlib.h>
# include "config.h"
# include "common.h"
# ifdef CSPTR_NO_SENTINEL
# ifndef __GNUC__
# error Variadic structure sentinels can only be disabled on a compiler supporting GNU extensions
# endif
# define CSPTR_SENTINEL
# define CSPTR_SENTINEL_DEC
# else
# define CSPTR_SENTINEL .sentinel_ = 0,
# define CSPTR_SENTINEL_DEC int sentinel_;
# endif
enum pointer_kind {
UNIQUE,
SHARED,
ARRAY = 1 << 8
};
typedef void (*f_destructor)(void *, void *);
typedef struct {
void *(*alloc)(size_t);
void (*dealloc)(void *);
} s_allocator;
extern s_allocator smalloc_allocator;
typedef struct {
CSPTR_SENTINEL_DEC
size_t size;
size_t nmemb;
enum pointer_kind kind;
f_destructor dtor;
struct {
const void *data;
size_t size;
} meta;
} s_smalloc_args;
CSPTR_PURE void *get_smart_ptr_meta(void *ptr);
void *sref(void *ptr);
CSPTR_MALLOC_API void *smalloc(s_smalloc_args *args);
void sfree(void *ptr);
void *smove_size(void *ptr, size_t size);
# define smalloc(...) \
smalloc(&(s_smalloc_args) { CSPTR_SENTINEL __VA_ARGS__ })
# define smove(Ptr) \
smove_size((Ptr), sizeof (*(Ptr)))
#endif /* !CSPTR_SMALLOC_H_ */
| 881 |
1,664 | <gh_stars>1000+
{
"report_name" : "jobtracker_jobs_running_report",
"report_type" : "standard",
"title" : "Jobs Running",
"vertical_label" : "Number Of Jobs",
"series" : [
{ "metric": "mapred.jobtracker.jobs_running", "color": "ff0000", "label": "Jobs Running",
"line_width": "2", "type": "line" }
]
}
| 145 |
609 | /*
* main.c - TASCII.BIN
*
* Aplicativo de teste para o sistema operacional Gramado.
* Exibe os acarteres da tabela ascii.
* @todo: Pode haver alguma seleção, baseada em argumentos.
* @todo: usar apenas a libC.
*
* 2018 - <NAME>.
*/
#include <stdarg.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define STANDARD_ASCII_MAX 128
/*
* # main #
* C function to demonstrate the working of arithmetic operators
*/
void _main()
{
printf("\n");
printf("\n");
printf("TSCANF.BIN:\n");
printf("Testing scanf ... \n\n");
//#testing
//=============================
//string
char str[80];
printf("\n==============\n");
printf("Enter a string:\n");
//scanf(" %s",str); //isso funciona e está no padrão.
//scanf(" %s",&str); //isso funciona e está no padrão.
scanf(" %s",&str[0]); //isso funciona e está no padrão.
printf("You entered { %s }.\n\n",str);
//char
// OK. Isso está no padrão..
char ch;
printf("\n==============\n");
printf("Enter a char:\n");
scanf("%c",&ch);
printf("You entered { %c }.\n\n",ch);
int i;
printf("\n==============\n");
printf("Enter a number:\n");
scanf("%d", &i);
printf("You entered { %d }.\n\n",i);
//================
printf("done.\n");
while(1){
asm("pause");
}
//return 0;
exit(0);
};
| 612 |
3,084 | <reponame>ixjf/Windows-driver-samples<filename>network/wlan/WDI/COMMON/Protocol802_11.c
#include "Mp_Precomp.h"
#if WPP_SOFTWARE_TRACE
#include "Protocol802_11.tmh"
#endif
static u2Byte sPacketIEOffsetTable[] =
{
sMacHdrLng + 4, //SubType_Asoc_Req = 0,
sMacHdrLng + 6, //SubType_Asoc_Rsp = 1,
sMacHdrLng + 10, //SubType_Reasoc_Req = 2,
sMacHdrLng + 6, //SubType_Reasoc_Rsp = 3,
sMacHdrLng + 0, //SubType_Probe_Req = 4,
sMacHdrLng + 12, //SubType_Probe_Rsp = 5,
0, // rsvd = 6, x
0, // rsvd = 7, x
sMacHdrLng + 12, //SubType_Beacon = 8,
0, //SubType_Atim = 9, x
0, //SubType_Disasoc = 10, x
sMacHdrLng + 6, //SubType_Auth = 11,
0, //SubType_Deauth = 12, x
};
// Pattern Array
// Qos (0x1)
u1Byte PAT_ACT_QOS_ADDTSREQ[] = {0x01, 0x00};
u1Byte PAT_ACT_QOS_ADDTSRSP[] = {0x01, 0x01};
u1Byte PAT_ACT_QOS_DELTS[] = {0x01, 0x02};
u1Byte PAT_ACT_QOS_SCHEDULE[] = {0x01, 0x03};
// DLS (0x2)
u1Byte PAT_ACT_DLS_DLSREQ[] = {0x02, 0x00};
u1Byte PAT_ACT_DLS_DLSRSP[] = {0x02, 0x01};
u1Byte PAT_ACT_DLS_DLSTEARDOWN[] = {0x02, 0x02};
// BA (0x3)
u1Byte PAT_ACT_BA_ADDBAREQ[] = {0x03, 0x00};
u1Byte PAT_ACT_BA_ADDBARSP[] = {0x03, 0x01};
u1Byte PAT_ACT_BA_DELBA[] = {0x03, 0x02};
// Public (0x4)
u1Byte PAT_ACT_BSS_COEXIST[] = {0x04, 0x00};
u1Byte PAT_ACT_TDLS_DISC_RSP[] = {0x04, 0x0E};
u1Byte PAT_ACT_P2P_GO_NEG_REQ[] = {0x04, 0x09, 0x50, 0x6F, 0x9A, 0x09, 0x00}; // P2P GO Negotiation Request
u1Byte PAT_ACT_P2P_GO_NEG_RSP[] = {0x04, 0x09, 0x50, 0x6F, 0x9A, 0x09, 0x01}; // P2P GO Negotiation Response
u1Byte PAT_ACT_P2P_GO_NEG_CONF[] = {0x04, 0x09, 0x50, 0x6F, 0x9A, 0x09, 0x02}; // P2P GO Negotiation Confirm
u1Byte PAT_ACT_P2P_INVIT_REQ[] = {0x04, 0x09, 0x50, 0x6F, 0x9A, 0x09, 0x03}; // P2P Invitation Request
u1Byte PAT_ACT_P2P_INVIT_RSP[] = {0x04, 0x09, 0x50, 0x6F, 0x9A, 0x09, 0x04}; // P2P Invitation Response
u1Byte PAT_ACT_P2P_DEV_DISCOVERABILITY_REQ[] = {0x04, 0x09, 0x50, 0x6F, 0x9A, 0x09, 0x05}; // P2P Device Discoverability Request
u1Byte PAT_ACT_P2P_DEV_DISCOVERABILITY_RSP[] = {0x04, 0x09, 0x50, 0x6F, 0x9A, 0x09, 0x06}; // P2P Device Discoverability Response
u1Byte PAT_ACT_P2P_PROV_DISC_REQ[] = {0x04, 0x09, 0x50, 0x6F, 0x9A, 0x09, 0x07}; // P2P Provision Discovery Request
u1Byte PAT_ACT_P2P_PROV_DISC_RSP[] = {0x04, 0x09, 0x50, 0x6F, 0x9A, 0x09, 0x08}; // P2P Provision Discovery Response
u1Byte PAT_ACT_NAN_SDF[] = {0x04, 0x09, 0x50, 0x6F, 0x9A, 0x13}; // NAN SDF
u1Byte PAT_ACT_GAS_INT_REQ[] = {0x04, 0x0A}; // GAS Initial Request
u1Byte PAT_ACT_GAS_INT_RSP[] = {0x04, 0x0B}; // GAS Initial Response
u1Byte PAT_ACT_GAS_COMEBACK_REQ[] = {0x04, 0x0C}; // GAS Comeback Request
u1Byte PAT_ACT_GAS_COMEBACK_RSP[] = {0x04, 0x0D}; // GAS Comeback Response
// Radio Measurement - 11k (0x5)
u1Byte PAT_ACT_RM_RM_REQ[] = {0x05, 0x00}; // Radio Measurement Request
u1Byte PAT_ACT_RM_RM_RPT[] = {0x05, 0x01}; // Radio Measurement Report
u1Byte PAT_ACT_RM_LM_REQ[] = {0x05, 0x02}; // Link Measurement Request
u1Byte PAT_ACT_RM_LM_RPT[] = {0x05, 0x03}; // Link Measurement Report
u1Byte PAT_ACT_RM_NR_REQ[] = {0x05, 0x04}; // Neighbor Report Request
u1Byte PAT_ACT_RM_NR_RSP[] = {0x05, 0x05}; // Neighbor Report Response
// High Throughput - 11n (0x7)
u1Byte PAT_ACT_HT_NOTI_CHNL_WIDTH[] = {0x07, 0x00}; // Notify Channel Width
u1Byte PAT_ACT_HT_SM_PS[] = {0x07, 0x01}; // SM Power Save
u1Byte PAT_ACT_HT_PSMP[] = {0x07, 0x02}; // PSMP
u1Byte PAT_ACT_HT_SET_PCO_PHASE[] = {0x07, 0x03}; // Set PCO Phase
u1Byte PAT_ACT_HT_CSI[] = {0x07, 0x04}; // CSI
u1Byte PAT_ACT_HT_NON_COMPRESS_BEAMFORMING[] = {0x07, 0x05}; // Noncompressed Beamforming
u1Byte PAT_ACT_HT_COMPRESS_BEAMFORMING[] = {0x07, 0x06}; // Compressed Beamforming
u1Byte PAT_ACT_HT_ASEL_FEEDBACK[] = {0x07, 0x07}; // ASEL Indices Feedback
// SA Query (0x8)
u1Byte PAT_ACT_SA_QUERY_REQ[] = {0x08, 0x00}; // SA Query Request
// TDLS-11z (0x0C)
u1Byte PAT_ACT_TDLS_REQ[] = {0x0C, 0x00}; // TDLS Setup Request
u1Byte PAT_ACT_TDLS_RSP[] = {0x0C, 0x01}; // TDLS Setup Response
u1Byte PAT_ACT_TDLS_CONFIRM[] = {0x0C, 0x02}; // TDLS Setup Confirm
u1Byte PAT_ACT_TDLS_TEARDOWN[] = {0x0C, 0x03}; // TDLS Setup Teardown
u1Byte PAT_ACT_TDLS_PEER_TRAFIC_IND[] = {0x0C, 0x04}; // TDLS Peer Traffic Indication
u1Byte PAT_ACT_TDLS_CHNL_SW_REQ[] = {0x0C, 0x05}; // TDLS Channel Switch Request
u1Byte PAT_ACT_TDLS_CHNL_SW_RSP[] = {0x0C, 0x06}; // TDLS Channel Switch Response
u1Byte PAT_ACT_TDLS_PEER_PSM_REQ[] = {0x0C, 0x07}; // TDLS Peer PSM Request
u1Byte PAT_ACT_TDLS_PEER_PSM_RSP[] = {0x0C, 0x08}; // TDLS Peer PSM Response
u1Byte PAT_ACT_TDLS_PEER_TRAFIC_RSP[] = {0x0C, 0x09}; // TDLS Peer Traffic Response
u1Byte PAT_ACT_TDLS_DISC_REQ[] = {0x0C, 0x0A}; // TDLS Discovery Request
// WMM (0x11)
u1Byte PAT_ACT_WMM_ADDTSREQ[] = {0x11, 0x00};
u1Byte PAT_ACT_WMM_ADDTSRSP[] = {0x11, 0x01};
u1Byte PAT_ACT_WMM_DELTS[] = {0x11, 0x02};
// VHT (0x15)
u1Byte PAT_ACT_VHT_COMPRESSED_BEAMFORMING[] = {0x15, 0x00};
u1Byte PAT_ACT_VHT_GROUPID_MANAGEMENT[] = {0x15, 0x01};
u1Byte PAT_ACT_VHT_OPMODE_NOTIFICATION[] = {0x15, 0x02};
//Vendor Specific (0x7F)
u1Byte PAT_ACT_P2P_NOA[] = {0x7F, 0x50, 0x6F, 0x9A, 0x09, 0x00}; // P2P Notice of Absence
u1Byte PAT_ACT_P2P_PRESENCE_REQ[] = {0x7F, 0x50, 0x6F, 0x9A, 0x09, 0x01}; // P2P Presence Request
u1Byte PAT_ACT_P2P_PRESENCE_RSP[] = {0x7F, 0x50, 0x6F, 0x9A, 0x09, 0x02}; // P2P Presence Response
u1Byte PAT_ACT_P2P_GO_DISCOVERABILITY_REQ[] = {0x7F, 0x50, 0x6F, 0x9A, 0x09, 0x03}; // P2P GO Discoverability Request
#define FILL_PATTERN_MAP(_Type, _Pattern) {_Type, sizeof(_Pattern), _Pattern}
// The pattern array of action frames.
// By Bruce, 2012-03-09.
PKT_PATTERN_MAP PktActPatternsMap[] =
{
// Qos (0x1)
FILL_PATTERN_MAP(ACT_PKT_QOS_ADDTSREQ, PAT_ACT_QOS_ADDTSREQ),
FILL_PATTERN_MAP(ACT_PKT_QOS_ADDTSRSP, PAT_ACT_QOS_ADDTSRSP),
FILL_PATTERN_MAP(ACT_PKT_QOS_DELTS, PAT_ACT_QOS_DELTS),
FILL_PATTERN_MAP(ACT_PKT_QOS_SCHEDULE, PAT_ACT_QOS_SCHEDULE),
// DLS (0x2)
FILL_PATTERN_MAP(ACT_PKT_DLS_DLSREQ, PAT_ACT_DLS_DLSREQ),
FILL_PATTERN_MAP(ACT_PKT_DLS_DLSRSP, PAT_ACT_DLS_DLSRSP),
FILL_PATTERN_MAP(ACT_PKT_DLS_DLSTEARDOWN, PAT_ACT_DLS_DLSTEARDOWN),
// BA (0x3)
FILL_PATTERN_MAP(ACT_PKT_BA_ADDBAREQ, PAT_ACT_BA_ADDBAREQ),
FILL_PATTERN_MAP(ACT_PKT_BA_ADDBARSP, PAT_ACT_BA_ADDBARSP),
FILL_PATTERN_MAP(ACT_PKT_BA_DELBA, PAT_ACT_BA_DELBA),
// Public (0x4)
FILL_PATTERN_MAP(ACT_PKT_BSS_COEXIST, PAT_ACT_BSS_COEXIST),
FILL_PATTERN_MAP(ACT_PKT_TDLS_DISC_RSP, PAT_ACT_TDLS_DISC_RSP),
FILL_PATTERN_MAP(ACT_PKT_P2P_GO_NEG_REQ, PAT_ACT_P2P_GO_NEG_REQ),
FILL_PATTERN_MAP(ACT_PKT_P2P_GO_NEG_RSP, PAT_ACT_P2P_GO_NEG_RSP),
FILL_PATTERN_MAP(ACT_PKT_P2P_GO_NEG_CONF, PAT_ACT_P2P_GO_NEG_CONF),
FILL_PATTERN_MAP(ACT_PKT_P2P_INVIT_REQ, PAT_ACT_P2P_INVIT_REQ),
FILL_PATTERN_MAP(ACT_PKT_P2P_INVIT_RSP, PAT_ACT_P2P_INVIT_RSP),
FILL_PATTERN_MAP(ACT_PKT_P2P_DEV_DISCOVERABILITY_REQ, PAT_ACT_P2P_DEV_DISCOVERABILITY_REQ),
FILL_PATTERN_MAP(ACT_PKT_P2P_DEV_DISCOVERABILITY_RSP, PAT_ACT_P2P_DEV_DISCOVERABILITY_RSP),
FILL_PATTERN_MAP(ACT_PKT_P2P_PROV_DISC_REQ, PAT_ACT_P2P_PROV_DISC_REQ),
FILL_PATTERN_MAP(ACT_PKT_P2P_PROV_DISC_RSP, PAT_ACT_P2P_PROV_DISC_RSP),
FILL_PATTERN_MAP(ACT_PKT_NAN_SDF, PAT_ACT_NAN_SDF),
FILL_PATTERN_MAP(ACT_PKT_GAS_INT_REQ, PAT_ACT_GAS_INT_REQ),
FILL_PATTERN_MAP(ACT_PKT_GAS_INT_RSP, PAT_ACT_GAS_INT_RSP),
FILL_PATTERN_MAP(ACT_PKT_GAS_COMEBACK_REQ, PAT_ACT_GAS_COMEBACK_REQ),
FILL_PATTERN_MAP(ACT_PKT_GAS_COMEBACK_RSP, PAT_ACT_GAS_COMEBACK_RSP),
// Radio Measurement - 11k (0x5)
FILL_PATTERN_MAP(ACT_PKT_RM_RM_REQ, PAT_ACT_RM_RM_REQ),
FILL_PATTERN_MAP(ACT_PKT_RM_RM_RPT, PAT_ACT_RM_RM_RPT),
FILL_PATTERN_MAP(ACT_PKT_RM_LM_REQ, PAT_ACT_RM_LM_REQ),
FILL_PATTERN_MAP(ACT_PKT_RM_LM_RPT, PAT_ACT_RM_LM_RPT),
FILL_PATTERN_MAP(ACT_PKT_RM_NR_REQ, PAT_ACT_RM_NR_REQ),
FILL_PATTERN_MAP(ACT_PKT_RM_NR_RSP, PAT_ACT_RM_NR_RSP),
// High Throughput - 11n (0x7)
FILL_PATTERN_MAP(ACT_PKT_HT_NOTI_CHNL_WIDTH, PAT_ACT_HT_NOTI_CHNL_WIDTH),
FILL_PATTERN_MAP(ACT_PKT_HT_SM_PS, PAT_ACT_HT_SM_PS),
FILL_PATTERN_MAP(ACT_PKT_HT_PSMP, PAT_ACT_HT_PSMP),
FILL_PATTERN_MAP(ACT_PKT_HT_SET_PCO_PHASE, PAT_ACT_HT_SET_PCO_PHASE),
FILL_PATTERN_MAP(ACT_PKT_HT_CSI, PAT_ACT_HT_CSI),
FILL_PATTERN_MAP(ACT_PKT_HT_NON_COMPRESSED_BEAMFORMING, PAT_ACT_HT_NON_COMPRESS_BEAMFORMING),
FILL_PATTERN_MAP(ACT_PKT_HT_COMPRESSED_BEAMFORMING, PAT_ACT_HT_COMPRESS_BEAMFORMING),
FILL_PATTERN_MAP(ACT_PKT_HT_ASEL_FEEDBACK, PAT_ACT_HT_ASEL_FEEDBACK),
// SA Query - 11w(0x8)
FILL_PATTERN_MAP(ACT_PKT_SA_QUERY_REQ, PAT_ACT_SA_QUERY_REQ),
// TDLS-11z (0x0C)
FILL_PATTERN_MAP(ACT_PKT_TDLS_REQ, PAT_ACT_TDLS_REQ),
FILL_PATTERN_MAP(ACT_PKT_TDLS_RSP, PAT_ACT_TDLS_RSP),
FILL_PATTERN_MAP(ACT_PKT_TDLS_CONFIRM, PAT_ACT_TDLS_CONFIRM),
FILL_PATTERN_MAP(ACT_PKT_TDLS_TEARDOWN, PAT_ACT_TDLS_TEARDOWN),
FILL_PATTERN_MAP(ACT_PKT_TDLS_PEER_TRAFIC_IND, PAT_ACT_TDLS_PEER_TRAFIC_IND),
FILL_PATTERN_MAP(ACT_PKT_TDLS_CHNL_SW_REQ, PAT_ACT_TDLS_CHNL_SW_REQ),
FILL_PATTERN_MAP(ACT_PKT_TDLS_CHNL_SW_RSP, PAT_ACT_TDLS_CHNL_SW_RSP),
FILL_PATTERN_MAP(ACT_PKT_TDLS_PEER_PSM_REQ, PAT_ACT_TDLS_PEER_PSM_REQ),
FILL_PATTERN_MAP(ACT_PKT_TDLS_PEER_PSM_RSP, PAT_ACT_TDLS_PEER_PSM_RSP),
FILL_PATTERN_MAP(ACT_PKT_TDLS_PEER_TRAFIC_RSP, PAT_ACT_TDLS_PEER_TRAFIC_RSP),
FILL_PATTERN_MAP(ACT_PKT_TDLS_DISC_REQ, PAT_ACT_TDLS_DISC_REQ),
// WMM (0x11)
FILL_PATTERN_MAP(ACT_PKT_WMM_ADDTSREQ, PAT_ACT_WMM_ADDTSREQ),
FILL_PATTERN_MAP(ACT_PKT_WMM_ADDTSRSP, PAT_ACT_WMM_ADDTSRSP),
FILL_PATTERN_MAP(ACT_PKT_WMM_DELTS, PAT_ACT_WMM_DELTS),
// VHT (0x15)
FILL_PATTERN_MAP(ACT_PKT_VHT_COMPRESSED_BEAMFORMING, PAT_ACT_VHT_COMPRESSED_BEAMFORMING),
FILL_PATTERN_MAP(ACT_PKT_VHT_GROUPID_MANAGEMENT, PAT_ACT_VHT_GROUPID_MANAGEMENT),
FILL_PATTERN_MAP(ACT_PKT_VHT_OPMODE_NOTIFICATION, PAT_ACT_VHT_OPMODE_NOTIFICATION),
//Vendor Specific (0x7F)
FILL_PATTERN_MAP(ACT_PKT_P2P_NOA, PAT_ACT_P2P_NOA),
FILL_PATTERN_MAP(ACT_PKT_P2P_PRESENCE_REQ, PAT_ACT_P2P_PRESENCE_REQ),
FILL_PATTERN_MAP(ACT_PKT_P2P_PRESENCE_RSP, PAT_ACT_P2P_PRESENCE_RSP),
FILL_PATTERN_MAP(ACT_PKT_P2P_GO_DISCOVERABILITY_REQ, PAT_ACT_P2P_GO_DISCOVERABILITY_REQ),
// ===== Insert new item above this line =====
{ACT_PKT_TYPE_UNKNOWN, 0, NULL}
};
// 802.11 Action Frame IE offset
PKT_IE_OFFSET_MAP ActPktIeOffsetMap[] =
{
// Qos (0x1)
{ACT_PKT_QOS_ADDTSREQ, (sMacHdrLng + 3)},
{ACT_PKT_QOS_ADDTSRSP, (sMacHdrLng + 5)},
{ACT_PKT_QOS_SCHEDULE, (sMacHdrLng + 2)},
// DLS (0x2)
{ACT_PKT_DLS_DLSREQ, (sMacHdrLng + 18)},
{ACT_PKT_DLS_DLSRSP, (sMacHdrLng + 18)},
// Public (0x4)
{ACT_PKT_BSS_COEXIST, (sMacHdrLng + 2)},
{ACT_PKT_TDLS_DISC_RSP, (sMacHdrLng + 5)},
{ACT_PKT_P2P_GO_NEG_REQ, (sMacHdrLng + 8)},
{ACT_PKT_P2P_GO_NEG_RSP, (sMacHdrLng + 8)},
{ACT_PKT_P2P_GO_NEG_CONF, (sMacHdrLng + 8)},
{ACT_PKT_P2P_INVIT_REQ, (sMacHdrLng + 8)},
{ACT_PKT_P2P_INVIT_RSP, (sMacHdrLng + 8)},
{ACT_PKT_P2P_DEV_DISCOVERABILITY_REQ, (sMacHdrLng + 8)},
{ACT_PKT_P2P_DEV_DISCOVERABILITY_RSP, (sMacHdrLng + 8)},
{ACT_PKT_P2P_PROV_DISC_REQ, (sMacHdrLng + 8)},
{ACT_PKT_P2P_PROV_DISC_RSP, (sMacHdrLng + 8)},
// WMM (0x11)
{ACT_PKT_WMM_ADDTSREQ, (sMacHdrLng + 4)},
{ACT_PKT_WMM_ADDTSRSP, (sMacHdrLng + 4)},
{ACT_PKT_WMM_DELTS, (sMacHdrLng + 4)},
//Vendor Specific (0x7F)
{ACT_PKT_P2P_NOA, (sMacHdrLng + 7)},
{ACT_PKT_P2P_PRESENCE_REQ, (sMacHdrLng + 7)},
{ACT_PKT_P2P_PRESENCE_RSP, (sMacHdrLng + 7)},
{ACT_PKT_P2P_GO_DISCOVERABILITY_REQ, (sMacHdrLng + 7)},
// ===== Insert new item above this line =====
{ACT_PKT_TYPE_UNKNOWN, 0}
};
// Pattern Array
//TDLS
u1Byte PAT_ENCAP_DATA_TDLS_SETUP_REQ[] = {0xAA, 0xAA, 0x03, 0x00, 0x00, 0x00, 0x89, 0x0D, 0x02, 0x0C, 0x00};
u1Byte PAT_ENCAP_DATA_TDLS_SETUP_RSP[] = {0xAA, 0xAA, 0x03, 0x00, 0x00, 0x00, 0x89, 0x0D, 0x02, 0x0C, 0x01};
u1Byte PAT_ENCAP_DATA_TDLS_SETUP_CONFIRM[] = {0xAA, 0xAA, 0x03, 0x00, 0x00, 0x00, 0x89, 0x0D, 0x02, 0x0C, 0x02};
u1Byte PAT_ENCAP_DATA_TDLS_TEARDOWN[] = {0xAA, 0xAA, 0x03, 0x00, 0x00, 0x00, 0x89, 0x0D, 0x02, 0x0C, 0x03};
u1Byte PAT_ENCAP_DATA_TDLS_TRAFFIC_INDI[] = {0xAA, 0xAA, 0x03, 0x00, 0x00, 0x00, 0x89, 0x0D, 0x02, 0x0C, 0x04};
u1Byte PAT_ENCAP_DATA_TDLS_CHNL_SW_REQ[] = {0xAA, 0xAA, 0x03, 0x00, 0x00, 0x00, 0x89, 0x0D, 0x02, 0x0C, 0x05};
u1Byte PAT_ENCAP_DATA_TDLS_CHNL_SW_RSP[] = {0xAA, 0xAA, 0x03, 0x00, 0x00, 0x00, 0x89, 0x0D, 0x02, 0x0C, 0x06};
u1Byte PAT_ENCAP_DATA_TDLS_PSM_REQ[] = {0xAA, 0xAA, 0x03, 0x00, 0x00, 0x00, 0x89, 0x0D, 0x02, 0x0C, 0x07};
u1Byte PAT_ENCAP_DATA_TDLS_PSM_RSP[] = {0xAA, 0xAA, 0x03, 0x00, 0x00, 0x00, 0x89, 0x0D, 0x02, 0x0C, 0x08};
u1Byte PAT_ENCAP_DATA_TDLS_TRAFFIC_RSP[] = {0xAA, 0xAA, 0x03, 0x00, 0x00, 0x00, 0x89, 0x0D, 0x02, 0x0C, 0x09};
u1Byte PAT_ENCAP_DATA_TDLS_DISC_REQ[] = {0xAA, 0xAA, 0x03, 0x00, 0x00, 0x00, 0x89, 0x0D, 0x02, 0x0C, 0x0A};
u1Byte PAT_ENCAP_DATA_TDLS_PROBE_REQ[] = {0xAA, 0xAA, 0x03, 0x00, 0x00, 0x00, 0x89, 0x0D, 0x02, 0x7F, 0x50, 0x6F, 0x9A, 0x04};
u1Byte PAT_ENCAP_DATA_TDLS_PROBE_RSP[] = {0xAA, 0xAA, 0x03, 0x00, 0x00, 0x00, 0x89, 0x0D, 0x02, 0x7F, 0x50, 0x6F, 0x9A, 0x05};
// CCX
u1Byte PAT_ENCAP_DATA_CCX_IAPP[] = {0xAA, 0xAA, 0x03, 0x00, 0x40, 0x96, 0x00, 0x00};
// The pattern array of encapsulated data frames.
// By Bruce, 2012-03-23.
PKT_PATTERN_MAP PktEncapDataPatternsMap[] =
{
// TDLS
FILL_PATTERN_MAP(ENCAP_DATA_PKT_TDLS_SETUP_REQ, PAT_ENCAP_DATA_TDLS_SETUP_REQ),
FILL_PATTERN_MAP(ENCAP_DATA_PKT_TDLS_SETUP_RSP, PAT_ENCAP_DATA_TDLS_SETUP_RSP),
FILL_PATTERN_MAP(ENCAP_DATA_PKT_TDLS_SETUP_CONFIRM, PAT_ENCAP_DATA_TDLS_SETUP_CONFIRM),
FILL_PATTERN_MAP(ENCAP_DATA_PKT_TDLS_TEARDOWN, PAT_ENCAP_DATA_TDLS_TEARDOWN),
FILL_PATTERN_MAP(ENCAP_DATA_PKT_TDLS_TRAFFIC_INDI, PAT_ENCAP_DATA_TDLS_TRAFFIC_INDI),
FILL_PATTERN_MAP(ENCAP_DATA_PKT_TDLS_CHNL_SW_REQ, PAT_ENCAP_DATA_TDLS_CHNL_SW_REQ),
FILL_PATTERN_MAP(ENCAP_DATA_PKT_TDLS_CHNL_SW_RSP, PAT_ENCAP_DATA_TDLS_CHNL_SW_RSP),
FILL_PATTERN_MAP(ENCAP_DATA_PKT_TDLS_PSM_REQ, PAT_ENCAP_DATA_TDLS_PSM_REQ),
FILL_PATTERN_MAP(ENCAP_DATA_PKT_TDLS_PSM_RSP, PAT_ENCAP_DATA_TDLS_PSM_RSP),
FILL_PATTERN_MAP(ENCAP_DATA_PKT_TDLS_TRAFFIC_RSP, PAT_ENCAP_DATA_TDLS_TRAFFIC_RSP),
FILL_PATTERN_MAP(ENCAP_DATA_PKT_TDLS_DISC_REQ, PAT_ENCAP_DATA_TDLS_DISC_REQ),
FILL_PATTERN_MAP(ENCAP_DATA_PKT_TDLS_PROBE_REQ, PAT_ENCAP_DATA_TDLS_PROBE_REQ),
FILL_PATTERN_MAP(ENCAP_DATA_PKT_TDLS_PROBE_RSP, PAT_ENCAP_DATA_TDLS_PROBE_RSP),
// CCX RM
FILL_PATTERN_MAP(ENCAP_DATA_PKT_CCX_IAPP, PAT_ENCAP_DATA_CCX_IAPP),
// ===== Insert new item above this line =====
{ENCAP_DATA_PKT_UNKNOWN, 0, NULL}
};
BOOLEAN
EqualOS(
IN OCTET_STRING os1,
IN OCTET_STRING os2
)
{
if( os1.Length!=os2.Length )
return FALSE;
if( os1.Length==0 )
return FALSE;
return (PlatformCompareMemory(os1.Octet,os2.Octet,os1.Length)==0) ? TRUE:FALSE;
}
BOOLEAN
IsSSIDAny(
IN OCTET_STRING ssid
)
{
BOOLEAN retValue = FALSE;
if(ssid.Length == 0) // a kind of "ANY SSID"
retValue = TRUE;
else if(ssid.Length == 3)
{
if( (ssid.Octet[0]=='A' || ssid.Octet[0]=='a') &&
(ssid.Octet[1]=='N' || ssid.Octet[1]=='n') &&
(ssid.Octet[2]=='Y' || ssid.Octet[2]=='y') )
retValue = TRUE;
}
return retValue;
}
BOOLEAN
IsSSIDDummy(
IN OCTET_STRING ssid
)
{
u2Byte i;
u1Byte ch;
if(ssid.Length == 0) // a kind of "ANY SSID"
return FALSE;
for(i = 0; i < ssid.Length; i++)
{
ch = ssid.Octet[i];
if( (ch >= 0x20) && (ch <= 0x7e) ) //wifi, printable ascii code must be supported
;//ok
else
{
// If the SSID contain Any Illeagl ASCII Code
// It should be reganize as dummy SSID.
// It modified for No Link any If UI does no Set the OID or registery
// Modifid by Mars, 20090722
// 2010/04/12 MH For SEC Korea SSID case, we will not treat it as dummy SSID.
// if the SSID length is not 32.
if (ssid.Length == MAX_SSID_LEN)
return TRUE;
}
}
return FALSE;
}
BOOLEAN
IsSSIDNdisTest(
IN OCTET_STRING ssid
)
{
if(ssid.Length ==0) // a kind of "ANY SSID"
{
return TRUE;
}
if( (ssid.Length >= 8) &&
( (ssid.Octet[0]=='N' || ssid.Octet[0]=='n') &&
(ssid.Octet[1]=='D' || ssid.Octet[1]=='d') &&
(ssid.Octet[2]=='I' || ssid.Octet[2]=='i') &&
(ssid.Octet[3]=='S' || ssid.Octet[2]=='s') &&
(ssid.Octet[4]=='T' || ssid.Octet[2]=='t') &&
(ssid.Octet[5]=='E' || ssid.Octet[2]=='e') &&
(ssid.Octet[6]=='S' || ssid.Octet[2]=='s') &&
(ssid.Octet[7]=='T' || ssid.Octet[2]=='t')) )
{
return TRUE;
}
else
{
return FALSE;
}
}
//
// Description:
// Checks whether a packet contains any invalid IE.
// Implemented based on PacketGetElement().
//
// 2008.12.32, haich
//
BOOLEAN
PacketCheckIEValidity(
IN OCTET_STRING packet,
IN PRT_RFD pRfd
)
{
u2Byte PacketSubType;
u2Byte offset = 0; // current offset to the packet
BOOLEAN bRet = TRUE; // used for return
u1Byte u1EID; // EID of current IE
u1Byte u1ELength; // Length of current IE
u2Byte ValidPacketLength=0;
do
{
if(sMacHdrLng > packet.Length)
{// not able to get packet type
RT_TRACE(COMP_SCAN, DBG_LOUD,
("PacketCheckIEValidity(): sMacHdrLng(%u) > packet.Length (%u)\n", sMacHdrLng, packet.Length));
bRet = FALSE;
break;
}
if(!IsMgntFrame(packet.Octet))
{// not a mangaement frame
RT_TRACE(COMP_SCAN, DBG_LOUD,
("PacketCheckIEValidity(): frame type: %u\n", Frame_Type(packet)));
bRet = FALSE;
break;
}
PacketSubType = Frame_Subtype(packet);
if(PacketSubType > 12)
{// beyond deauth
RT_TRACE(COMP_SCAN, DBG_LOUD,
("PacketCheckIEValidity(): wrong subtype: %u\n", PacketSubType));
bRet = FALSE;
break;
}
if(!(offset = sPacketIEOffsetTable[PacketSubType]))
{// not a sub type of frame that could have IEs
RT_TRACE(COMP_SCAN, DBG_LOUD,
("PacketCheckIEValidity(): not a sub type of frame that could have IEs, subtype: %u\n", PacketSubType));
bRet = FALSE;
break;
}
do // for all IEs
{
if(offset + 2 >= packet.Length)
{// [malicious attack] not ok to read EID and Element Length
RT_TRACE(COMP_SCAN, DBG_LOUD,
("PacketCheckIEValidity(): [malicious attack] not ok to read EID and Element Length\n"));
bRet = TRUE;
break;
}
u1EID = packet.Octet[offset]; // Get current Element ID.
u1ELength = packet.Octet[offset+1]; // Get current length of the IE.
if(!IsIELengthValid(u1EID, u1ELength))
{
bRet = FALSE;
break;
}
if(offset + 2 + u1ELength < packet.Length)
{// Jump to the position of length of next IE. (2 byte is for the ID and length field.)
offset = offset + 2 + u1ELength; // incr at least 2 for every loop
ValidPacketLength = offset;
}
else if(offset + 2 + u1ELength == packet.Length)
{// the IEs in the packet are all valid.
bRet = TRUE;
ValidPacketLength = offset + 2 + u1ELength;
break;
}
else
{// [malicious attack] length of IE exceeds packet length
RT_TRACE(COMP_SCAN, DBG_LOUD,
("PacketCheckIEValidity(): [malicious attack] length of IE exceeds packet length\n"));
bRet = TRUE;
break;
}
}while(TRUE);
}while(FALSE);
if(!bRet)
{
RT_PRINT_DATA(COMP_SCAN, DBG_TRACE, "Packet with wrong IE:", packet.Octet, packet.Length);
}
pRfd->ValidPacketLength = ValidPacketLength;
return bRet;
}
//
// Description:
// Determine the packet type of the action frame.
// Argument:
// [in] posMpdu -
// The full 802.11 packet.
// Return:
// If this packet is determined successfully, return the ACT_PKT_xxx.
// If this function cannot recognize this packet, return ACT_PKT_TYPE_UNKNOWN.
// Remark:
// It checks the category, action field (if there is such one) and OUI information to determine the type.
// Do not input non-action frame to this function and it doesn't check if this packet is action frame.
// By Bruce, 2012-03-09.
//
ACT_PKT_TYPE
PacketGetActionFrameType(
IN POCTET_STRING posMpdu
)
{
u4Byte idx = 0;
if(posMpdu->Length <= sMacHdrLng)
{
RT_TRACE_F(COMP_DBG, DBG_WARNING, ("[WARNING] Invalid length (%d) for this packet!\n", posMpdu->Length));
return ACT_PKT_TYPE_UNKNOWN;
}
//Retrieve the table and check the patterns
for(idx = 0; ACT_PKT_TYPE_UNKNOWN != (ACT_PKT_TYPE)(PktActPatternsMap[idx].PktType); idx ++)
{
// Packet length mismatch
if((posMpdu->Length - sMacHdrLng) < PktActPatternsMap[idx].PatternLen)
continue;
// Compare pattern
if(0 == PlatformCompareMemory(Frame_FrameBody(*posMpdu), PktActPatternsMap[idx].Pattern, PktActPatternsMap[idx].PatternLen))
{
return (ACT_PKT_TYPE)(PktActPatternsMap[idx].PktType);
}
}
return ACT_PKT_TYPE_UNKNOWN;
}
//
// Description:
// Determine the packet type of the encapsulated data frame.
// Argument:
// [in] posDataContent -
// The full data content after 802.11 header(including Qos + Security header + HC control header).
// It should be the header of LLC.
// Return:
// If this packet is determined successfully, return the ENCAP_DATA_PKT_xxx.
// If this function cannot recognize this packet, return ENCAP_DATA_PKT_UNKNOWN.
// Remark:
// It checks the LLC/SNAP header, and the following patters.
// This function does not check the security or any 802.11 condition.
// By Bruce, 2012-03-23.
//
ENCAP_DATA_PKT_TYPE
PacketGetEncapDataFrameType(
IN POCTET_STRING posDataContent
)
{
u4Byte idx = 0;
//Retrieve the table and check the patterns
for(idx = 0; ENCAP_DATA_PKT_UNKNOWN != (ACT_PKT_TYPE)(PktEncapDataPatternsMap[idx].PktType); idx ++)
{
// Packet length mismatch
if(posDataContent->Length < PktEncapDataPatternsMap[idx].PatternLen)
continue;
// Compare pattern
if(0 == PlatformCompareMemory(posDataContent->Octet, PktEncapDataPatternsMap[idx].Pattern, PktEncapDataPatternsMap[idx].PatternLen))
{
return (ENCAP_DATA_PKT_TYPE)(PktEncapDataPatternsMap[idx].PktType);
}
}
return ENCAP_DATA_PKT_UNKNOWN;
}
//
// Description:
// Get the offset according to the packet type.
// Arguments:
// [in] posMpdu -
// The full 802.11 packet.
// [out] pOffset -
// The returned offset for the fist IE.
// Return:
// If this executes without any error, return FALSE.
// If this packet has no IE, return FALSE.
// Remark:
// None.
// By Bruce, 2012-03-09.
//
BOOLEAN
PacketGetIeOffset(
IN POCTET_STRING posMpdu,
OUT pu2Byte pOffset
)
{
BOOLEAN bValid = TRUE;
u4Byte idx = 0;
switch(PacketGetType(*posMpdu))
{
default:
bValid = FALSE;
break;
case Type_Auth:
*pOffset = (sMacHdrLng + 6);
break;
case Type_Probe_Req:
*pOffset = (sMacHdrLng + 0);
break;
case Type_Beacon:
case Type_Probe_Rsp:
*pOffset = (sMacHdrLng + 12);
break;
case Type_Reasoc_Req:
*pOffset = (sMacHdrLng + 10);
break;
case Type_Asoc_Req:
*pOffset = (sMacHdrLng + 4);
break;
case Type_Asoc_Rsp:
case Type_Reasoc_Rsp:
*pOffset = (sMacHdrLng + 6);
break;
case Type_Disasoc:
case Type_Deauth:
*pOffset = (sMacHdrLng + 2);
break;
case Type_Action:
{
ACT_PKT_TYPE actType = PacketGetActionFrameType(posMpdu);
bValid = FALSE;
if(ACT_PKT_TYPE_UNKNOWN == actType)
{
RT_TRACE_F(COMP_DBG, DBG_WARNING, ("[WARNING] Unrecognized action frame type!\n"));
break;
}
for(idx = 0; ACT_PKT_TYPE_UNKNOWN != (ACT_PKT_TYPE)(ActPktIeOffsetMap[idx].PktType); idx ++)
{
if(actType == (ACT_PKT_TYPE)(ActPktIeOffsetMap[idx].PktType))
{
*pOffset = ActPktIeOffsetMap[idx].IeOffset;
bValid = TRUE;
break;
}
}
if(!bValid)
{
RT_TRACE_F(COMP_DBG, DBG_WARNING, ("[WARNING] cannot find offset for action frame type = %d!\n", actType));
}
}
break;
}
return bValid;
}
//
// Parsing Information Elements.
//
// This function is used to search the WPS Fragment IE
// In WPS 2.0. It wil content more then 2 IE is the forment
// DD-Len-00-50-f2-04-xxxxx-DD-Len-00-50-f2-04
//
u1Byte
PacketGetElementNum(
IN OCTET_STRING packet,
IN ELEMENT_ID ID,
IN OUI_TYPE OUIType,
IN u1Byte OUISubType
)
{
u2Byte offset;
OCTET_STRING IEs;
OCTET_STRING ret={0,0}; // used for return
u1Byte IENum = 0;
if(!PacketGetIeOffset(&packet, &offset))
{
return 0;
}
if(offset < packet.Length)
{
pu1Byte pIE;
u2Byte IELen = (packet.Length - offset);
pIE = (packet.Octet + offset);
FillOctetString(IEs, pIE,IELen);
RT_PRINT_DATA(COMP_WPS, DBG_TRACE, "The IE in the packet :\n", pIE, IELen);
do
{
ret= IEGetElement(IEs, ID, OUIType, OUISubType);
if(ret.Length > 0)
{
IENum++;
RT_TRACE(COMP_WPS, DBG_TRACE,("We find a WPS IE in probe or beacon Fragment num is %d \n",IENum));
IELen = IELen - ((u2Byte)(ret.Octet - pIE) + ret.Length);
pIE = (ret.Octet + ret.Length);
FillOctetString(IEs, pIE,IELen);
RT_PRINT_DATA(COMP_WPS, DBG_TRACE, "The IE after WPS IE in the packet :\n", pIE, IELen);
}
else
{
RT_TRACE(COMP_WPS, DBG_TRACE,("There is no WPS IE in the probe or beacon\n"));
}
}
while(ret.Length != 0);
return IENum;
}
else
{
return IENum;
}
}
//
// Parsing Information Elements.
//
// Added a parameter "OUISubType" and rewrited by Annie, 2005-11-08,
// since the element ID of WPA-IE and WMM-IE are the same(0xDD=221).
//
OCTET_STRING
PacketGetElement(
IN OCTET_STRING packet,
IN ELEMENT_ID ID,
IN OUI_TYPE OUIType,
IN u1Byte OUISubType
)
{
u2Byte offset;
OCTET_STRING IEs;
OCTET_STRING ret={0,0}; // used for return
if(!PacketGetIeOffset(&packet, &offset))
return ret;
if(offset < packet.Length)
{
FillOctetString(IEs, (packet.Octet + offset), (packet.Length - offset));
return IEGetElement(IEs, ID, OUIType, OUISubType);
}
else
{
return ret;
}
}
VOID
PacketMakeElement(
IN POCTET_STRING packet,
IN ELEMENT_ID ID,
IN OCTET_STRING info
)
{
pu1Byte buf = packet->Octet + packet->Length;
buf[0] = (u1Byte)ID;
buf[1] = (u1Byte)info.Length;
if(info.Length > 0)
{
PlatformMoveMemory( buf + 2, info.Octet, info.Length);
}
packet->Length += info.Length + 2;
}
VOID
PacketAppendData(
IN POCTET_STRING packet,
IN OCTET_STRING data
)
{
pu1Byte buf = packet->Octet + packet->Length;
PlatformMoveMemory( buf, data.Octet, data.Length);
packet->Length = packet->Length + data.Length;
}
BOOLEAN
TimGetBcMcBit(
IN OCTET_STRING Tim
)
{
return ((Tim.Octet[2] & 0x01) == 0x01);
}
BOOLEAN
TimGetAIDBit(
IN OCTET_STRING Tim,
IN u2Byte AID
)
{
BOOLEAN result;
u2Byte offset,offset_byte;
u1Byte offset_bit;
u2Byte FirstStationInTim;
FirstStationInTim = (Tim.Octet[2] & 0xFE) * 8;
if( AID<FirstStationInTim || AID >= (FirstStationInTim+(Tim.Length-3)*8) )
{ // Out of the range(too large)
return FALSE;
}
else
{
offset = AID - FirstStationInTim;
offset_byte = offset >>3;
offset_bit = (unsigned char)(offset & 0x7);
// Look up in the partial virtual bitmap
result = Tim.Octet[3 + offset_byte]&(0x01<<offset_bit);
return result;
}
}
u2Byte
N_DBPSOfRate(
u4Byte DataRate
)
{
u2Byte N_DBPS = 24;
switch(DataRate)
{
case 12:
N_DBPS = 24;
break;
case 18:
N_DBPS = 36;
break;
case 24:
N_DBPS = 48;
break;
case 36:
N_DBPS = 72;
break;
case 48:
N_DBPS = 96;
break;
case 72:
N_DBPS = 144;
break;
case 96:
N_DBPS = 192;
break;
case 108:
N_DBPS = 216;
break;
default:
break;
}
return N_DBPS;
}
u2Byte
ComputeTxTime(
IN u2Byte FrameLength,
IN u4Byte DataRate,
IN BOOLEAN bManagementFrame,
IN BOOLEAN bShortPreamble
)
{
u2Byte FrameTime=0;
u2Byte N_DBPS;
u2Byte Ceiling;
switch(DataRate)
{
case 2:
case 4:
case 11:
case 22:
// 1M can only use Long Preamble. Ref. 802.11b 18.2.2.2. 2005.01.18, by rcnjko.
if( bManagementFrame || !bShortPreamble || DataRate == 2 )
{ // long preamble
FrameTime = (u2Byte)(144+48+(FrameLength*8*2/DataRate));
}
else
{ // Short preamble
FrameTime = (u2Byte)(72+24+(FrameLength*8*2/DataRate));
}
if( ( FrameLength*8*2 % DataRate ) != 0 )
FrameTime ++;
break;
case 12:
case 18:
case 24:
case 36:
case 44:
case 48:
case 66:
case 72:
case 96:
case 108:
N_DBPS = N_DBPSOfRate(DataRate);
Ceiling = (16 + 8*FrameLength + 6) / N_DBPS + (((16 + 8*FrameLength + 6) % N_DBPS) ? 1 : 0);
FrameTime = (u2Byte)(16 + 4 + 4*Ceiling + 6);
break;
}
return FrameTime;
}
BOOLEAN
IsHiddenSsid(
OCTET_STRING ssid
)
{
if( ((ssid.Length == 1) && (ssid.Octet[0] == 0x20) ) ||
((ssid.Length > 0) && (ssid.Octet[0] == 0x0 ) ) ||
(ssid.Length == 0) )
{
return TRUE;
}
return FALSE;
}
BOOLEAN
BeHiddenSsid(
pu1Byte ssidbuf,
u1Byte ssidlen
)
{
if( ((ssidlen == 1) && (ssidbuf[0] == 0x20) ) ||
((ssidlen > 0) && (ssidbuf[0] == 0x0 ) ) ||
(ssidlen == 0) )
{
return TRUE;
}
return FALSE;
}
BOOLEAN
NullSSID(
OCTET_STRING bcnPkt
)
{
OCTET_STRING ssIdBeacon;
u1Byte i;
BOOLEAN athHdnAP; //sean,20030410, fix for linksys BEFW11S4
// ssIdBeacon = PacketGetElement( bcnPkt, EID_SsId ); // Rewrited for new added parameter. Annie, 2005-11-08.
// ssIdBeacon = PacketGetElement( bcnPkt, EID_SsId, OUI_SUB_DONT_CARE );
ssIdBeacon = PacketGetElement( bcnPkt, EID_SsId, OUI_SUB_DONT_CARE, OUI_SUBTYPE_DONT_CARE );
for(i=0;i<ssIdBeacon.Length;i++)
{
if( ssIdBeacon.Octet[i] != 0x0 )
{
break;
}
}
athHdnAP = (ssIdBeacon.Length == 1) && (ssIdBeacon.Octet[0]==0x20);
return ((i==ssIdBeacon.Length)||athHdnAP)?TRUE:FALSE;
}
BOOLEAN
CompareSSID(
pu1Byte ssidbuf1,
u2Byte ssidlen1,
pu1Byte ssidbuf2,
u2Byte ssidlen2
)
{
if(ssidlen1 == ssidlen2)
{
if((ssidlen1 == 0) ||
( PlatformCompareMemory(ssidbuf1, ssidbuf2, ssidlen1) == 0 ))
return TRUE;
}
return FALSE;
}
u1Byte
ComputeAckRate(
IN OCTET_STRING BSSBasicRateSet,
IN u1Byte DataRate)
{
u2Byte i;
u1Byte AckRate = 0;
u1Byte BasicRate;
DataRate &= 0x7F;
// Find the highest rate in the BSSBasicRateSet
// that is less than or equal to DataRate.
for( i = 0; i < BSSBasicRateSet.Length; i++)
{
BasicRate = BSSBasicRateSet.Octet[i] & 0x7F;
if( BasicRate <= DataRate && BasicRate > AckRate)
AckRate = BasicRate;
}
// Make sure the AckRate is in the same modulation of DataRate,
// otherwise we it shall use highest mandatory rate of PHY
// that is less than or equal to DataRate.
switch(DataRate)
{
// CCK.
case MGN_1M:
case MGN_2M:
case MGN_5_5M:
case MGN_11M:
if(AckRate == 0 || !IS_CCK_RATE(AckRate) )
AckRate = MGN_1M;
break;
// OFDM.
case 12:
case 18:
case 24:
case 36:
case 48:
case 72:
case 96:
case 108:
if( AckRate == 0 || IS_CCK_RATE(AckRate) )
{
if(DataRate >= 48)
{ // 24M
AckRate = 48;
}
else if(DataRate >= 24)
{ // 12M
AckRate = 24;
}
else
{ // 6M
AckRate = 12;
}
}
break;
default:
RT_TRACE(COMP_DBG, DBG_SERIOUS, ("ComputeAckRate(): unsupported rate %#02X !!!\n", DataRate));
if(AckRate == 0)
AckRate = MGN_1M;
break;
}
RT_ASSERT(AckRate != 0, ("ComputeAckRate(): AckRate should not be 0 !!!\n"));
return AckRate;
}
//
// Description:
// Check if current offset of the MPDU is a valid IE.
//
BOOLEAN
HasNextIE(
IN POCTET_STRING posMpdu,
IN u4Byte Offset
)
{
if(Offset + 2 > posMpdu->Length) // 2 = 1(ID) + 1(Length).
return FALSE;
if(Offset + 2 + *(posMpdu->Octet + Offset + 1) > posMpdu->Length)
return FALSE;
return TRUE;
}
//
// Description:
// Wrap the IE in an RT_DOT11_IE object and advance offset
// to next IE.
//
// Assumption:
// Currnet offset contains a valid IE, that is, HasNextIE()
// returns TRUE before calling this function.
//
RT_DOT11_IE
AdvanceToNextIE(
IN POCTET_STRING posMpdu,
IN OUT pu4Byte pOffset
)
{
RT_DOT11_IE Ie;
Ie.Id = *(posMpdu->Octet + *pOffset);
Ie.Content.Length = *(posMpdu->Octet + *pOffset + 1);
Ie.Content.Octet = posMpdu->Octet + *pOffset + 2;
*pOffset += (2 + *(posMpdu->Octet + *pOffset + 1));
return Ie;
}
//
// Description:
// Get the number of IE elements and extract the interested element for return.
// Arguments:
// [in] IEs -
// The IE elements to be retrived.
// [in] ID -
// The referenced element ID in the IEs to be extracted.
// [in] OUIType -
// Vendor specified OUI to be determined in the element.
// [in] OUISubType -
// The oui subtype of the element
// Return:
// The number of the IEs.
// Revised by Bruce, 2012-03-26.
//
u1Byte
IEGetElementNum(
IN OCTET_STRING IEs,
IN ELEMENT_ID ID,
IN OUI_TYPE OUIType,
IN u1Byte OUISubType
)
{
u1Byte IENum = 0;
OCTET_STRING osTmp, osSingleIE;
u2Byte offset = 0;
do
{
if(offset >= IEs.Length)
break;
FillOctetString(osTmp, IEs.Octet + offset, (IEs.Length - offset));
osSingleIE = IEGetElement(osTmp, ID, OUIType, OUISubType);
if(osSingleIE.Length > 0)
{
IENum ++;
offset += (SIZE_EID_AND_LEN + osSingleIE.Length);
}
else
{
break;
}
}
while(TRUE);
return IENum;
}
//
// Description:
// Parse the IE elements and extract the interested element for return.
// Arguments:
// IEs -
// The IE elements to be retrived.
// ID -
// The referenced element ID in the IEs to be extracted.
// OUISubType -
// Vendor specified OUI to be determined in the element.
// Revised by Bruce, 2009-02-12.
//
OCTET_STRING
IEGetElement(
IN OCTET_STRING IEs,
IN ELEMENT_ID ID,
IN OUI_TYPE OUIType,
IN u1Byte OUISubType
)
{
u2Byte offset = 0;
u2Byte length = IEs.Length;
OCTET_STRING ret={0,0}; // used for return
u1Byte temp;
BOOLEAN bIEMatched = FALSE;
OCTET_STRING osOuiSub;
u1Byte MaxElementLen;
static u1Byte WPATag[] = {0x00, 0x50, 0xf2, 0x01};
static u1Byte WMMTag[] = {0x00, 0x50, 0xf2, 0x02}; // Added by Annie, 2005-11-08.
static u1Byte Simpleconf[]={0x00, 0x50, 0xF2, 0x04}; //added by David, 2006-10-02
static u1Byte CcxRmCapTag[] = {0x00, 0x40, 0x96, 0x01}; // For CCX 2 S36, Radio Management Capability element, 2006.05.15, by rcnjko.
static u1Byte CcxVerNumTag[] = {0x00, 0x40, 0x96, 0x03}; // For CCX 2 S38, WLAN Device Version Number element. Annie, 2006-08-20.
static u1Byte WPA2GTKTag[] = {0x00, 0x0f, 0xac, 0x01}; // For MAC GTK data IE by CCW
static u1Byte CcxTsmTag[] = {0x00, 0x40, 0x96, 0x07}; // For CCX4 S56, Traffic Stream Metrics, 070615, by rcnjko.
static u1Byte CcxSSIDLTag[] = {0x00, 0x50, 0xf2, 0x05};
static u1Byte RealtekTurboModeTag[] = {0x00, 0xE0, 0x4C, 0x01}; // Added by Annie, 2005-12-27
static u1Byte RealtekAggModeTag[] = {0x00, 0xe0, 0x4c, 0x02};
static u1Byte RealtekBTIOTModeTag[] = {0x00, 0xe0, 0x4c, 0x03}; // Add for BT IOT
static u1Byte RealtekBtHsTag[] = {0x00, 0xe0, 0x4c, 0x04}; // Add for BT HS
static u1Byte Epigram[] = {0x00,0x90,0x4c};
static u1Byte EWC11NHTCap[] = {0x00, 0x90, 0x4c, 0x033}; // For 11n EWC definition, 2007.07.17, by Emily
static u1Byte EWC11NHTInfo[] = {0x00, 0x90, 0x4c, 0x034}; // For 11n EWC definition, 2007.07.17, by Emily
static u1Byte Epigram11ACCap[] = {0x00, 0x90, 0x4c, 0x04, 0x08, 0xBF, 0x0C}; // For 11ac Epigram definition
static u1Byte BroadcomCap_1[] = {0x00, 0x10, 0x18};
static u1Byte BroadcomCap_2[] = {0x00, 0x0a, 0xf7};
static u1Byte BroadcomCap_3[] = {0x00, 0x05, 0xb5};
static u1Byte BroadcomLinksysE4200Cap_1[] = {0x00, 0x10, 0x18,0x02,0x00,0xf0,0x3c}; // for Linksys E4200
static u1Byte BroadcomLinksysE4200Cap_2[] = {0x00, 0x10, 0x18,0x02,0x01,0xf0,0x3c};
static u1Byte BroadcomLinksysE4200Cap_3[] = {0x00, 0x10, 0x18,0x02,0x00,0xf0,0x2c};
static u1Byte CiscoCap[] = {0x00, 0x40, 0x96}; // For Cisco AP IOT issue, by Emily
static u1Byte MeruCap[] = {0x00, 0x0c, 0xe6};
static u1Byte RalinkCap[] ={0x00, 0x0c, 0x43};
static u1Byte AtherosCap_1[] = {0x00,0x03,0x7F};
static u1Byte AtherosCap_2[] = {0x00,0x13,0x74};
static u1Byte MarvellCap[] = {0x00, 0x50, 0x43};
static u1Byte AirgoCap[] = {0x00, 0x0a, 0xf5};
static u1Byte CcxSFA[] = {0x00, 0x40, 0x96, 0x14};
static u1Byte CcxDiagReqReason[] = {0x00, 0x40, 0x96, 0x12};
static u1Byte CcxMHDR[] = {0x00, 0x40, 0x96, 0x10};
static u1Byte P2P_OUI_WITH_TYPE[] = {0x50, 0x6F, 0x9A, WLAN_PA_VENDOR_SPECIFIC};
static u1Byte WFD_OUI_WITH_TYPE[] = {0x50, 0x6F, 0x9A, WFD_OUI_TYPE};
static u1Byte NAN_OUI_WITH_TYPE[] = {0x50, 0x6F, 0x9A, 0x13};
static u1Byte RealtekTDLSTag[] = {0x00, 0xe0, 0x4c, 0x03};
//Mix mode can't get DHCP in MacOS Driver. CCW revice offset 2008-04-15
//offset = 12;
do
{
if( (offset + 2) >= length )
{
return ret;
}
temp = IEs.Octet[offset]; // Get current Element ID.
if( temp == ID )
{
if( ID == EID_Vendor )
{ // EID_Vendor(=0xDD=221): Vendor Specific, currently we have to consider WPA and WMM Information Element.
switch(OUIType)
{
case OUI_SUB_WPA:
FillOctetString(osOuiSub, WPATag, sizeof(WPATag));
break;
case OUI_SUB_WPA2GTK:
FillOctetString(osOuiSub, WPA2GTKTag, sizeof(WPA2GTKTag));
break;
case OUI_SUB_CCX_TSM:
FillOctetString(osOuiSub, CcxTsmTag, sizeof(CcxTsmTag));
break;
case OUI_SUB_SSIDL:
FillOctetString(osOuiSub, CcxSSIDLTag, sizeof(CcxSSIDLTag));
break;
case OUI_SUB_WMM:
FillOctetString(osOuiSub, WMMTag, sizeof(WMMTag));
break;
case OUI_SUB_REALTEK_TURBO:
FillOctetString(osOuiSub, RealtekTurboModeTag, sizeof(RealtekTurboModeTag));
break;
case OUI_SUB_REALTEK_AGG:
FillOctetString(osOuiSub, RealtekAggModeTag, sizeof(RealtekAggModeTag));
break;
case OUI_SUB_SimpleConfig:
FillOctetString(osOuiSub, Simpleconf, sizeof(Simpleconf));
break;
case OUI_SUB_CCX_RM_CAP:
FillOctetString(osOuiSub, CcxRmCapTag, sizeof(CcxRmCapTag));
break;
case OUI_SUB_CCX_VER_NUM:
FillOctetString(osOuiSub, CcxVerNumTag, sizeof(CcxVerNumTag));
break;
case OUI_SUB_EPIG_IE:
FillOctetString(osOuiSub, Epigram, sizeof(Epigram));
break;
case OUI_SUB_11N_EWC_HT_CAP:
FillOctetString(osOuiSub, EWC11NHTCap, sizeof(EWC11NHTCap));
break;
case OUI_SUB_11N_EWC_HT_INFO:
FillOctetString(osOuiSub, EWC11NHTInfo, sizeof(EWC11NHTInfo));
break;
case OUI_SUB_11AC_EPIG_VHT_CAP:
FillOctetString(osOuiSub, Epigram11ACCap, sizeof(Epigram11ACCap));
break;
case OUI_SUB_BROADCOM_IE_1:
FillOctetString(osOuiSub, BroadcomCap_1, sizeof(BroadcomCap_1));
break;
case OUI_SUB_BROADCOM_IE_2:
FillOctetString(osOuiSub, BroadcomCap_2, sizeof(BroadcomCap_2));
break;
case OUI_SUB_BROADCOM_IE_3:
FillOctetString(osOuiSub, BroadcomCap_3, sizeof(BroadcomCap_3));
break;
case OUI_SUB_BROADCOM_LINKSYSE4200_IE_1:
FillOctetString(osOuiSub, BroadcomLinksysE4200Cap_1, sizeof(BroadcomLinksysE4200Cap_1));
break;
case OUI_SUB_BROADCOM_LINKSYSE4200_IE_2:
FillOctetString(osOuiSub, BroadcomLinksysE4200Cap_2, sizeof(BroadcomLinksysE4200Cap_2));
break;
case OUI_SUB_BROADCOM_LINKSYSE4200_IE_3:
FillOctetString(osOuiSub, BroadcomLinksysE4200Cap_3, sizeof(BroadcomLinksysE4200Cap_3));
break;
case OUI_SUB_CISCO_IE:
FillOctetString(osOuiSub, CiscoCap, sizeof(CiscoCap));
break;
case OUI_SUB_MERU_IE:
FillOctetString(osOuiSub, MeruCap, sizeof(MeruCap));
break;
case OUI_SUB_RALINK_IE:
FillOctetString(osOuiSub, RalinkCap, sizeof(RalinkCap));
break;
case OUI_SUB_ATHEROS_IE_1:
FillOctetString(osOuiSub, AtherosCap_1, sizeof(AtherosCap_1));
break;
case OUI_SUB_ATHEROS_IE_2:
FillOctetString(osOuiSub, AtherosCap_2, sizeof(AtherosCap_2));
break;
case OUI_SUB_MARVELL:
FillOctetString(osOuiSub, MarvellCap, sizeof(MarvellCap));
break;
case OUI_SUB_AIRGO:
FillOctetString(osOuiSub, AirgoCap, sizeof(AirgoCap));
break;
case OUI_SUB_CCX_SFA:
FillOctetString(osOuiSub, CcxSFA, sizeof(CcxSFA));
break;
case OUI_SUB_CCX_DIAG_REQ_REASON:
FillOctetString(osOuiSub, CcxDiagReqReason, sizeof(CcxDiagReqReason));
break;
case OUI_SUB_CCX_MFP_MHDR:
FillOctetString(osOuiSub, CcxMHDR, sizeof(CcxMHDR));
break;
case OUI_SUB_WIFI_DIRECT:
FillOctetString(osOuiSub, P2P_OUI_WITH_TYPE, sizeof(P2P_OUI_WITH_TYPE));
break;
case OUI_SUB_WIFI_DISPLAY:
FillOctetString(osOuiSub, WFD_OUI_WITH_TYPE, sizeof(WFD_OUI_WITH_TYPE));
break;
case OUI_SUB_NAN:
FillOctetString(osOuiSub, NAN_OUI_WITH_TYPE, sizeof(NAN_OUI_WITH_TYPE));
break;
case OUI_SUB_REALTEK_TDLS:
FillOctetString(osOuiSub, RealtekTDLSTag, sizeof(RealtekTDLSTag));
break;
case OUI_SUB_REALTEK_BT_IOT :
FillOctetString(osOuiSub, RealtekBTIOTModeTag, sizeof(RealtekBTIOTModeTag));
break;
case OUI_SUB_REALTEK_BT_HS:
FillOctetString(osOuiSub, RealtekBtHsTag, sizeof(RealtekBtHsTag));
break;
default:
FillOctetString(osOuiSub, NULL, 0);
break;
}
if( osOuiSub.Length > 0 && (length >= (offset + 2 + osOuiSub.Length)) ) // Prevent malicious attack.
{
if( PlatformCompareMemory(
(IEs.Octet + offset + 2),
osOuiSub.Octet,
osOuiSub.Length) == 0 )
{ // OUI field and subtype field are matched
bIEMatched = TRUE;
//
// 060801, Isaiah:
// [UAPSD Logo] Marvel AP has similar element, [DD 07 00 50 F2 02 05 01 24].
//
if( (OUI_SUB_WMM == OUIType) &&
(length >= (offset + 2 + osOuiSub.Length + 1)) )
{ // WMM-IE Matched!
u1Byte WmmSubtype = *(IEs.Octet+offset+2+sizeof(WMMTag));
if(WmmSubtype != OUISubType)
bIEMatched = FALSE;
}
}
}
}
else
{ // Other ID: Matched!
bIEMatched = TRUE;
}
}
if(bIEMatched &&
(length >= offset + 2 + IEs.Octet[offset+1]) ) // Prevent malicious attack.
{ // IE matched! break to return.
//
// Get the length of current IE.
// We also perform length checking here to pervent malicious attack.
//
switch(ID)
{
case EID_SsId:
MaxElementLen = MAX_SSID_LEN;
break;
case EID_SupRates:
MaxElementLen = 12; //Because Belkin 11AC on g Mode only has 12 Octets in this IE
break;
case EID_FHParms:
MaxElementLen = MAX_FH_PARM_LEN;
break;
case EID_DSParms:
MaxElementLen = MAX_DS_PARM_LEN;
break;
case EID_CFParms:
MaxElementLen = MAX_CF_PARM_LEN;
break;
case EID_Tim:
MaxElementLen = MAX_TIM_PARM_LEN;
break;
case EID_IbssParms:
MaxElementLen = MAX_IBSS_PARM_LEN;
break;
case EID_QBSSLoad:
MaxElementLen = MAX_QBSS_LOAD_LEN;
break;
case EID_EDCAParms:
MaxElementLen = MAX_EDCA_PARM_LEN;
break;
case EID_TSpec:
MaxElementLen = MAX_TSPEC_LEN;
break;
case EID_Schedule:
MaxElementLen = MAX_SCHEDULE_LEN;
break;
case EID_Ctext:
MaxElementLen = MAX_CTEXT_LEN;
break;
case EID_ERPInfo:
MaxElementLen = MAX_ERP_INFO_LEN;
break;
case EID_TSDelay:
MaxElementLen = MAX_TS_DELAY_LEN;
break;
case EID_TCLASProc:
MaxElementLen = MAX_TC_PROC_LEN;
break;
case EID_HTCapability:
MaxElementLen = MAX_HT_CAP_LEN;
break;
case EID_HTInfo:
MaxElementLen = MAX_HT_INFO_LEN;
break;
case EID_QoSCap:
MaxElementLen = MAX_QOS_CAP;
break;
case EID_ExtSupRates:
MaxElementLen = MAX_EXT_SUP_RATE_LEN;
break;
case EID_WAPI:
MaxElementLen = MAX_WAPI_IE_LEN;
break;
case EID_LinkIdentifier:
MaxElementLen = MAX_LINKID_LEN;
break;
case EID_SupportedChannels:
MaxElementLen = MAX_SUPCHNL_LEN;
break;
case EID_SupRegulatory:
MaxElementLen = MAX_SUPREGULATORY_LEN;
break;
case EID_SecondaryChnlOffset:
MaxElementLen = MAX_SECONDARYOFFSET_LEN;
break;
case EID_ChnlSwitchTimeing:
MaxElementLen = MAX_CHNLSWITCHTIMING_LEN;
break;
case EID_VHTCapability:
MaxElementLen = MAX_VHT_CAP_LEN;
break;
default:
MaxElementLen = MAX_IE_LEN;
break;
}
ret.Length = (IEs.Octet[offset+1] <= MaxElementLen) ? IEs.Octet[offset+1] : MaxElementLen;
//
// Get pointer to the first byte (ElementID and length are not included).
//
ret.Octet = IEs.Octet + offset + 2;
break;
}
else
{ // Different.
temp = IEs.Octet[offset+1]; // Get the length of current IE.
offset += (temp+2); // Jump to the position of length of next IE. (2 byte is for the ID and length field.)
}
}while(1);
return ret;
}
//
// Description:
// Verify if specific IE length is valid.
//
BOOLEAN
IsIELengthValid(
IN u1Byte IDIE,
IN u1Byte IELength
)
{
BOOLEAN bRet = TRUE;
u1Byte MaxIELength = MAX_IE_LEN;
switch(IDIE)
{
case EID_SsId:
MaxIELength = MAX_SSID_LEN;
break;
case EID_SupRates:
MaxIELength = 12;//Because Belkin 11AC on g Mode only has 12 Octets in this IE
break;
case EID_FHParms:
MaxIELength = MAX_FH_PARM_LEN;
break;
case EID_DSParms:
MaxIELength = MAX_DS_PARM_LEN;
break;
case EID_CFParms:
MaxIELength = MAX_CF_PARM_LEN;
break;
case EID_Tim:
MaxIELength = MAX_TIM_PARM_LEN;
break;
case EID_IbssParms:
MaxIELength = MAX_IBSS_PARM_LEN;
break;
case EID_QBSSLoad:
MaxIELength = MAX_QBSS_LOAD_LEN;
break;
case EID_EDCAParms:
MaxIELength = MAX_EDCA_PARM_LEN;
break;
case EID_TSpec:
MaxIELength = MAX_TSPEC_LEN;
break;
case EID_Schedule:
MaxIELength = MAX_SCHEDULE_LEN;
break;
case EID_Ctext:
MaxIELength = MAX_CTEXT_LEN;
break;
case EID_ERPInfo:
MaxIELength = MAX_ERP_INFO_LEN;
break;
case EID_TSDelay:
MaxIELength = MAX_TS_DELAY_LEN;
break;
case EID_TCLASProc:
MaxIELength = MAX_TC_PROC_LEN;
break;
case EID_QoSCap:
MaxIELength = MAX_QOS_CAP;
break;
case EID_ExtSupRates:
MaxIELength = MAX_EXT_SUP_RATE_LEN;
break;
case EID_WAPI:
MaxIELength = MAX_WAPI_IE_LEN;
break;
case EID_LinkIdentifier:
MaxIELength = MAX_LINKID_LEN;
break;
case EID_SupportedChannels:
MaxIELength = MAX_SUPCHNL_LEN;
break;
case EID_SupRegulatory:
MaxIELength = MAX_SUPREGULATORY_LEN;
break;
case EID_SecondaryChnlOffset:
MaxIELength = MAX_SECONDARYOFFSET_LEN;
break;
case EID_ChnlSwitchTimeing:
MaxIELength = MAX_CHNLSWITCHTIMING_LEN;
break;
default:
MaxIELength = MAX_IE_LEN;
}
if(IELength > MaxIELength)
bRet = FALSE;
return bRet;
}
| 25,702 |
852 | <filename>SimG4Core/CustomPhysics/src/CustomPDGParser.cc
#include <SimG4Core/CustomPhysics/interface/CustomPDGParser.h>
#include <cstdlib>
// check for R-hadron with gluino content
bool CustomPDGParser::s_isgluinoHadron(int pdg) {
int pdgAbs = abs(pdg);
return ((pdgAbs % 100000 / 10000 == 9) || (pdgAbs % 10000 / 1000 == 9) || s_isRGlueball(pdg));
}
bool CustomPDGParser::s_isstopHadron(int pdg) {
int pdgAbs = abs(pdg);
return ((pdgAbs % 10000 / 1000 == 6) || (pdgAbs % 1000 / 100 == 6));
}
bool CustomPDGParser::s_issbottomHadron(int pdg) {
int pdgAbs = abs(pdg);
return ((pdgAbs % 10000 / 1000 == 5) || (pdgAbs % 10000 / 100 == 5));
}
bool CustomPDGParser::s_isSLepton(int pdg) {
int pdgAbs = abs(pdg);
return (pdgAbs / 100 % 10000 == 0 && pdgAbs / 10 % 10 == 1);
}
bool CustomPDGParser::s_isRBaryon(int pdg) {
int pdgAbs = abs(pdg);
return (pdgAbs % 100000 / 10000 == 9);
}
bool CustomPDGParser::s_isRGlueball(int pdg) {
int pdgAbs = abs(pdg);
return (pdgAbs % 100000 / 10 == 99);
}
bool CustomPDGParser::s_isDphoton(int pdg) {
int pdgAbs = abs(pdg);
return (pdgAbs == 1072000) || (pdgAbs == 1023);
}
bool CustomPDGParser::s_isRMeson(int pdg) {
int pdgAbs = abs(pdg);
return (pdgAbs % 10000 / 1000 == 9);
}
bool CustomPDGParser::s_isMesonino(int pdg) {
int pdgAbs = abs(pdg);
return ((pdgAbs % 10000 / 100 == 6) || (pdgAbs % 10000 / 100 == 5));
}
bool CustomPDGParser::s_isSbaryon(int pdg) {
int pdgAbs = abs(pdg);
return ((pdgAbs % 10000 / 1000 == 6) || (pdgAbs % 10000 / 1000 == 5));
}
bool CustomPDGParser::s_isChargino(int pdg) {
int pdgAbs = abs(pdg);
return (pdgAbs == 1000024);
}
bool CustomPDGParser::s_isSIMP(int pdg) {
int pdgAbs = abs(pdg);
return (pdgAbs == 9000006);
}
double CustomPDGParser::s_charge(int pdg) {
float charge = 0, sign = 1;
int pdgAbs = abs(pdg);
if (pdg < 0)
sign = -1;
if (s_isSLepton(pdg)) //Sleptons
{
if (pdgAbs % 2 == 0)
return 0;
else
return -sign;
}
if (s_isDphoton(pdg)) {
return charge;
}
if (s_isChargino(pdg)) {
return sign;
}
if (s_isSIMP(pdg)) {
return 0;
}
if (s_isRMeson(pdg)) {
std::vector<int> quarks = s_containedQuarks(pdg);
if ((quarks[1] % 2 == 0 && quarks[0] % 2 == 1) || (quarks[1] % 2 == 1 && quarks[0] % 2 == 0))
charge = 1;
charge *= sign;
return charge;
}
if (s_isRBaryon(pdg)) {
int baryon = s_containedQuarksCode(pdg);
for (int q = 1; q < 1000; q *= 10) {
if (baryon / q % 2 == 0)
charge += 2;
else
charge -= 1;
}
charge /= 3;
charge *= sign;
return charge;
}
if (s_isMesonino(pdg)) {
int quark = s_containedQuarks(pdg)[0];
int squark = abs(pdg / 100 % 10);
if (squark % 2 == 0 && quark % 2 == 1)
charge = 1;
if (squark % 2 == 1 && quark % 2 == 0)
charge = 1;
charge *= sign;
if (s_issbottomHadron(pdg))
charge *= -1;
return charge;
}
if (s_isSbaryon(pdg)) {
int baryon = s_containedQuarksCode(pdg) + 100 * (abs(pdg / 1000 % 10)); //Adding the squark back on
for (int q = 1; q < 1000; q *= 10) {
if (baryon / q % 2 == 0)
charge += 2;
else
charge -= 1;
}
charge /= 3;
charge *= sign;
if (s_issbottomHadron(pdg))
charge *= -1;
return charge;
}
return 0;
}
double CustomPDGParser::s_spin(int pdg) {
// The PDG numbering is described in the Review of Particle Physics:
// "3. In composite quark systems (diquarks, mesons, and baryons) ...
// the rightmost digit nJ = 2J + 1 gives the system's spin."
// Since this does not apply to SUSY / exotic particles,
// if the spin is important for the simulation
// it should be hard-coded based on PDG ID in this function.
int pdgAbs = abs(pdg);
return pdgAbs % 10;
}
std::vector<int> CustomPDGParser::s_containedQuarks(int pdg) {
std::vector<int> quarks;
for (int i = s_containedQuarksCode(pdg); i > 0; i /= 10) {
quarks.push_back(i % 10);
}
return quarks;
}
int CustomPDGParser::s_containedQuarksCode(int pdg) {
int pdgAbs = abs(pdg);
if (s_isRBaryon(pdg))
return pdgAbs / 10 % 1000;
if (s_isRMeson(pdg))
return pdgAbs / 10 % 100;
if (s_isMesonino(pdg))
return pdgAbs / 10 % 1000 % 10;
if (s_isSbaryon(pdg))
return pdgAbs / 10 % 1000 % 100;
return 0;
}
| 1,948 |
1,056 | <reponame>arusinha/incubator-netbeans
/*
* 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.nativeexecution.test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.openide.util.Utilities;
/**
* A common class for reading rc files in format
* # comment
* [section1]
* key1=value1
* key2=value2
* ...
* @author vk155633
*/
public final class RcFile {
public static class FormatException extends Exception {
public FormatException(String message) {
super(message);
}
}
private class Section {
public final String name;
private final Map<String, String> map = new TreeMap<>();
public Section(String name) throws IOException {
this.name = name;
}
public synchronized String get(String key, String defaultValue) {
if (map.containsKey(key)) {
return map.get(key);
} else {
return defaultValue;
}
}
public synchronized Collection<String> getKeys() {
return new ArrayList<>(map.keySet());
}
public synchronized boolean containsKey(String key) {
return map.containsKey(key);
}
private synchronized void put(String key, String value) {
map.put(key, value);
}
}
private final Map<String, Section> sections = new TreeMap<>();
private final File file;
public synchronized String get(String section, String key, String defaultValue) {
Section sect = sections.get(section);
return (sect == null) ? defaultValue : sect.get(key, defaultValue);
}
public synchronized int get(String section, String key, int defaultValue) {
String stringValue = get(section, key, "" + defaultValue); //NOI18N
return Integer.parseInt(stringValue);
}
public boolean get(String section, String key, boolean defaultValue) {
String stringValue = get(section, key, "" + defaultValue); //NOI18N
return Boolean.valueOf(stringValue);
}
public String get(String section, String key) {
return get(section, key, null);
}
public boolean containsKey(String section, String key) {
Section sect = sections.get(section);
return (sect == null) ? false : sect.containsKey(key);
}
public synchronized Collection<String> getSections() {
List<String> result = new ArrayList<>();
for (Section section : sections.values()) {
result.add(section.name);
}
return result;
}
public synchronized Collection<String> getKeys(String section) {
Section sect = sections.get(section);
return (sect == null) ? Collections.<String>emptyList() : sect.getKeys();
}
public static RcFile createDummy() throws IOException, FormatException {
return new RcFile(new File(Utilities.isWindows() ? "NUL" : "/dev/null"), false);
}
public static RcFile create(File file) throws IOException, FormatException {
return new RcFile(file, true);
}
private RcFile(File file, boolean read) throws IOException, FormatException {
this.file = file;
try {
if (read) {
read();
}
} catch (FileNotFoundException e) {
// no rcFile, no problems ;-)
}
}
private void read() throws IOException, FormatException {
BufferedReader reader = new BufferedReader(new FileReader(file));
String str;
Pattern commentPattern = Pattern.compile("(#.*)|([ \t]*)"); // NOI18N
Pattern sectionPattern = Pattern.compile("\\[(.*)\\] *"); // NOI18N
Pattern valuePattern = Pattern.compile("([^=]+)=(.*)"); //NOI18N
Pattern justKeyPattern = Pattern.compile("[^=]+"); //NOI18N
Section currSection = new Section(""); // default section
while ((str = reader.readLine()) != null) {
if (commentPattern.matcher(str).matches()) {
continue;
}
if (sectionPattern.matcher(str).matches()) {
str = str.trim();
String name = str.substring(1, str.length()-1);
currSection = new Section(name);
sections.put(name, currSection);
} else {
Matcher m = valuePattern.matcher(str);
if (m.matches()) {
String key = m.group(1).trim();
String value = m.group(2).trim();
currSection.put(key, value);
} else {
if (justKeyPattern.matcher(str).matches()) {
String key = str.trim();
String value = null;
currSection.put(key, value);
} else {
throw new FormatException(str);
}
}
}
}
reader.close();
}
@Override
public String toString() {
return getClass().getSimpleName() + ' ' + file.getAbsolutePath();
}
public synchronized void dump() {
dump(System.out);
}
public synchronized void dump(PrintStream ps) {
for(Section section : sections.values()) {
ps.printf("[%s]\n", section.name);
for (String key : section.getKeys()) {
String value = section.get(key, null);
ps.printf("%s=%s\n", key, value);
}
}
}
}
| 2,730 |
868 | /*
* 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.activemq.artemis.core.config.federation;
import java.io.Serializable;
import java.util.List;
import java.util.Objects;
import org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration;
import org.apache.activemq.artemis.api.core.ActiveMQBuffer;
public class FederationConnectionConfiguration implements Serializable {
public static long DEFAULT_CIRCUIT_BREAKER_TIMEOUT = 30000;
private boolean isHA;
private String discoveryGroupName;
private List<String> staticConnectors;
private int priorityAdjustment;
private long circuitBreakerTimeout = DEFAULT_CIRCUIT_BREAKER_TIMEOUT;
private String username;
private String password;
private boolean shareConnection;
private long clientFailureCheckPeriod = ActiveMQDefaultConfiguration.getDefaultFederationFailureCheckPeriod();
private long connectionTTL = ActiveMQDefaultConfiguration.getDefaultFederationConnectionTtl();
private long retryInterval = ActiveMQDefaultConfiguration.getDefaultFederationRetryInterval();
private double retryIntervalMultiplier = ActiveMQDefaultConfiguration.getDefaultFederationRetryIntervalMultiplier();
private long maxRetryInterval = ActiveMQDefaultConfiguration.getDefaultFederationMaxRetryInterval();
private int initialConnectAttempts = ActiveMQDefaultConfiguration.getDefaultFederationInitialConnectAttempts();
private int reconnectAttempts = ActiveMQDefaultConfiguration.getDefaultFederationReconnectAttempts();
private long callTimeout = ActiveMQDefaultConfiguration.getDefaultFederationCallTimeout();
private long callFailoverTimeout = ActiveMQDefaultConfiguration.getDefaultFederationCallFailoverTimeout();
public String getDiscoveryGroupName() {
return discoveryGroupName;
}
public FederationConnectionConfiguration setDiscoveryGroupName(String discoveryGroupName) {
this.discoveryGroupName = discoveryGroupName;
return this;
}
public List<String> getStaticConnectors() {
return staticConnectors;
}
public FederationConnectionConfiguration setStaticConnectors(List<String> staticConnectors) {
this.staticConnectors = staticConnectors;
return this;
}
public boolean isHA() {
return isHA;
}
public FederationConnectionConfiguration setHA(boolean HA) {
isHA = HA;
return this;
}
public long getCircuitBreakerTimeout() {
return circuitBreakerTimeout;
}
public FederationConnectionConfiguration setCircuitBreakerTimeout(long circuitBreakerTimeout) {
this.circuitBreakerTimeout = circuitBreakerTimeout;
return this;
}
public String getUsername() {
return username;
}
public FederationConnectionConfiguration setUsername(String username) {
this.username = username;
return this;
}
public String getPassword() {
return password;
}
public FederationConnectionConfiguration setPassword(String password) {
this.password = password;
return this;
}
public int getPriorityAdjustment() {
return priorityAdjustment;
}
public FederationConnectionConfiguration setPriorityAdjustment(int priorityAdjustment) {
this.priorityAdjustment = priorityAdjustment;
return this;
}
public boolean isShareConnection() {
return shareConnection;
}
public FederationConnectionConfiguration setShareConnection(boolean shareConnection) {
this.shareConnection = shareConnection;
return this;
}
public long getClientFailureCheckPeriod() {
return clientFailureCheckPeriod;
}
public FederationConnectionConfiguration setClientFailureCheckPeriod(long clientFailureCheckPeriod) {
this.clientFailureCheckPeriod = clientFailureCheckPeriod;
return this;
}
public long getConnectionTTL() {
return connectionTTL;
}
public FederationConnectionConfiguration setConnectionTTL(long connectionTTL) {
this.connectionTTL = connectionTTL;
return this;
}
public long getRetryInterval() {
return retryInterval;
}
public FederationConnectionConfiguration setRetryInterval(long retryInterval) {
this.retryInterval = retryInterval;
return this;
}
public double getRetryIntervalMultiplier() {
return retryIntervalMultiplier;
}
public FederationConnectionConfiguration setRetryIntervalMultiplier(double retryIntervalMultiplier) {
this.retryIntervalMultiplier = retryIntervalMultiplier;
return this;
}
public long getMaxRetryInterval() {
return maxRetryInterval;
}
public FederationConnectionConfiguration setMaxRetryInterval(long maxRetryInterval) {
this.maxRetryInterval = maxRetryInterval;
return this;
}
public int getInitialConnectAttempts() {
return initialConnectAttempts;
}
public FederationConnectionConfiguration setInitialConnectAttempts(int initialConnectAttempts) {
this.initialConnectAttempts = initialConnectAttempts;
return this;
}
public int getReconnectAttempts() {
return reconnectAttempts;
}
public FederationConnectionConfiguration setReconnectAttempts(int reconnectAttempts) {
this.reconnectAttempts = reconnectAttempts;
return this;
}
public long getCallTimeout() {
return callTimeout;
}
public FederationConnectionConfiguration setCallTimeout(long callTimeout) {
this.callTimeout = callTimeout;
return this;
}
public long getCallFailoverTimeout() {
return callFailoverTimeout;
}
public FederationConnectionConfiguration setCallFailoverTimeout(long callFailoverTimeout) {
this.callFailoverTimeout = callFailoverTimeout;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
FederationConnectionConfiguration that = (FederationConnectionConfiguration) o;
return clientFailureCheckPeriod == that.clientFailureCheckPeriod &&
connectionTTL == that.connectionTTL &&
retryInterval == that.retryInterval &&
Double.compare(that.retryIntervalMultiplier, retryIntervalMultiplier) == 0 &&
maxRetryInterval == that.maxRetryInterval &&
initialConnectAttempts == that.initialConnectAttempts &&
reconnectAttempts == that.reconnectAttempts &&
callTimeout == that.callTimeout &&
callFailoverTimeout == that.callFailoverTimeout &&
isHA == that.isHA &&
priorityAdjustment == that.priorityAdjustment &&
circuitBreakerTimeout == that.circuitBreakerTimeout &&
shareConnection == that.shareConnection &&
Objects.equals(discoveryGroupName, that.discoveryGroupName) &&
Objects.equals(staticConnectors, that.staticConnectors) &&
Objects.equals(username, that.username) &&
Objects.equals(password, that.password);
}
@Override
public int hashCode() {
return Objects
.hash(clientFailureCheckPeriod, connectionTTL, retryInterval, retryIntervalMultiplier,
maxRetryInterval, initialConnectAttempts, reconnectAttempts, callTimeout,
callFailoverTimeout, isHA, discoveryGroupName, staticConnectors, priorityAdjustment,
circuitBreakerTimeout, username, password, shareConnection);
}
public void encode(ActiveMQBuffer buffer) {
buffer.writeNullableString(username);
buffer.writeNullableString(password);
buffer.writeBoolean(shareConnection);
buffer.writeInt(priorityAdjustment);
buffer.writeLong(clientFailureCheckPeriod);
buffer.writeLong(connectionTTL);
buffer.writeLong(retryInterval);
buffer.writeDouble(retryIntervalMultiplier);
buffer.writeLong(retryInterval);
buffer.writeInt(initialConnectAttempts);
buffer.writeInt(reconnectAttempts);
buffer.writeLong(callTimeout);
buffer.writeLong(callFailoverTimeout);
}
public void decode(ActiveMQBuffer buffer) {
username = buffer.readNullableString();
password = buffer.readNullableString();
shareConnection = buffer.readBoolean();
priorityAdjustment = buffer.readInt();
clientFailureCheckPeriod = buffer.readLong();
connectionTTL = buffer.readLong();
retryInterval = buffer.readLong();
retryIntervalMultiplier = buffer.readDouble();
maxRetryInterval = buffer.readLong();
initialConnectAttempts = buffer.readInt();
reconnectAttempts = buffer.readInt();
callTimeout = buffer.readLong();
callFailoverTimeout = buffer.readLong();
}
}
| 2,975 |
379 | <reponame>joelostblom/dash-docs<gh_stars>100-1000
from .import index
from .import content_module
| 35 |
456 | // SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2020 <NAME>
// All rights reserved.
#include <djvCore/OS.h>
#include <djvCore/Error.h>
#include <djvCore/String.h>
#include <djvCore/StringFormat.h>
#if defined(DJV_PLATFORM_MACOS)
#include <ApplicationServices/ApplicationServices.h>
#include <CoreFoundation/CFBundle.h>
#include <CoreServices/CoreServices.h>
#endif // DJV_PLATFORM_MACOS
#include <sstream>
#include <sys/ioctl.h>
#if defined(DJV_PLATFORM_MACOS)
#include <sys/types.h>
#include <sys/sysctl.h>
#else // DJV_PLATFORM_MACOS
#include <sys/sysinfo.h>
#endif // DJV_PLATFORM_MACOS
#include <sys/utsname.h>
#include <pwd.h>
#include <unistd.h>
//#pragma optimize("", off)
namespace djv
{
namespace Core
{
namespace OS
{
std::string getInformation()
{
std::string out;
::utsname info;
uname(&info);
std::stringstream s;
s << info.sysname << " " << info.release << " " << info.machine;
out = s.str();
return out;
}
size_t getRAMSize()
{
size_t out = 0;
#if defined(DJV_PLATFORM_MACOS)
int name[2] = { CTL_HW, HW_MEMSIZE };
u_int namelen = sizeof(name) / sizeof(name[0]);
uint64_t size = 0;
size_t len = sizeof(size);
if (0 == sysctl(name, namelen, &size, &len, NULL, 0))
{
out = static_cast<size_t>(size);
}
#else // DJV_PLATFORM_MACOS
struct sysinfo info;
if (0 == sysinfo(&info))
{
out = info.totalram;
}
#endif // DJV_PLATFORM_MACOS
return out;
}
int getTerminalWidth()
{
int out = 80;
struct winsize ws;
ws.ws_col = 0;
if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1)
{
ws.ws_col = 80;
}
out = ws.ws_col;
return out;
}
bool getEnv(const std::string& name, std::string& out)
{
if (const char* p = ::getenv(name.c_str()))
{
out = std::string(p);
return true;
}
return false;
}
bool setEnv(const std::string& name, const std::string& value)
{
return ::setenv(name.c_str(), value.c_str(), 1) == 0;
}
bool clearEnv(const std::string& name)
{
return ::unsetenv(name.c_str()) == 0;
}
std::string getUserName()
{
std::string out;
if (struct passwd* buf = ::getpwuid(::getuid()))
{
out = std::string(buf->pw_name);
}
return out;
}
void openURL(const std::string& value)
{
#if defined(DJV_PLATFORM_MACOS)
CFURLRef url = CFURLCreateWithBytes(
NULL,
(UInt8*)value.c_str(),
value.size(),
kCFStringEncodingASCII,
NULL);
LSOpenCFURLRef(url, 0);
CFRelease(url);
#else // DJV_PLATFORM_MACOS
std::stringstream ss;
ss << "xdg-open" << " " << value;
int r = system(ss.str().c_str());
if (r != 0)
{
std::vector<std::string> messages;
//! \todo How can we translate this?
messages.push_back(String::Format("{0}: {1}").
arg(value).
arg(DJV_TEXT("error_url_cannot_open")));
messages.push_back(String::Format(DJV_TEXT("error_url_code")).
arg(value));
throw std::runtime_error(String::join(messages, ' '));
}
#endif // DJV_PLATFORM_MACOS
}
} // namespace OS
} // namespace Core
} // namespace djv
| 2,566 |
4,873 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#pragma once
#include "../../codegen/NativeLinkingManagerSpec.g.h"
#include <NativeModules.h>
#include <winrt/Windows.ApplicationModel.h>
#include <winrt/Windows.Foundation.h>
#include <winrt/Windows.Graphics.Display.h>
namespace Microsoft::ReactNative {
REACT_MODULE(LinkingManager)
struct LinkingManager {
LinkingManager() noexcept;
~LinkingManager() noexcept;
using ModuleSpec = ReactNativeSpecs::LinkingManagerSpec;
REACT_INIT(Initialize)
void Initialize(React::ReactContext const &reactContext) noexcept;
REACT_METHOD(canOpenURL)
static winrt::fire_and_forget canOpenURL(std::string url, ::React::ReactPromise<::React::JSValue> result) noexcept;
REACT_METHOD(openURL)
void openURL(std::string &&url, ::React::ReactPromise<::React::JSValue> &&result) noexcept;
REACT_METHOD(openSettings)
static void openSettings(::React::ReactPromise<::React::JSValue> &&result) noexcept;
REACT_METHOD(addListener)
static void addListener(std::string eventName) noexcept;
REACT_METHOD(removeListeners)
static void removeListeners(double count) noexcept;
REACT_METHOD(getInitialURL)
static void getInitialURL(::React::ReactPromise<::React::JSValue> &&result) noexcept;
static void OpenUri(winrt::Windows::Foundation::Uri const &uri) noexcept;
private:
void HandleOpenUri(winrt::hstring const &uri) noexcept;
static std::mutex s_mutex;
React::ReactContext m_context;
static winrt::Windows::Foundation::Uri s_initialUri;
static std::vector<LinkingManager *> s_linkingModules;
};
} // namespace Microsoft::ReactNative
| 604 |
2,872 | <reponame>sathishmscict/Material-Movies
/*
* Copyright (C) 2015 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hackvg.android.provider;
import android.net.Uri;
import android.provider.BaseColumns;
/**
* Created by Ismael on 31/01/2015.
*/
public class DbConstants {
public static final String PROVIDER_NAME = "com.hackvg.android.provider";
public static final Uri CONTENT_URI = Uri.parse("content://" + PROVIDER_NAME + "/"
+ Movies.TABLE_NAME);
public final static String DB_NAME = "hackvg.db";
public final static int DB_VERSION = 1;
public class Movies {
public static final String TABLE_NAME = "movies";
public static final String ID = BaseColumns._ID;
public static final String ID_MOVIE = "id_movie";
public static final String STATUS = "status";
public static final String CREATE_SQL = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + "(" +
ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
ID_MOVIE + " INTEGER, " +
STATUS + " INTEGER)";
public static final String DEFAULT_SORT_ORDER = ID + " ASC";
}
}
| 578 |
938 | <gh_stars>100-1000
//===--- AMDGPUMetadata.cpp -------------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
/// \file
/// AMDGPU metadata definitions and in-memory representations.
///
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/Twine.h"
#include "llvm/Support/AMDGPUMetadata.h"
#include "llvm/Support/YAMLTraits.h"
using namespace llvm::AMDGPU;
using namespace llvm::AMDGPU::HSAMD;
LLVM_YAML_IS_SEQUENCE_VECTOR(Kernel::Arg::Metadata)
LLVM_YAML_IS_SEQUENCE_VECTOR(Kernel::Metadata)
namespace llvm {
namespace yaml {
template <>
struct ScalarEnumerationTraits<AccessQualifier> {
static void enumeration(IO &YIO, AccessQualifier &EN) {
YIO.enumCase(EN, "Default", AccessQualifier::Default);
YIO.enumCase(EN, "ReadOnly", AccessQualifier::ReadOnly);
YIO.enumCase(EN, "WriteOnly", AccessQualifier::WriteOnly);
YIO.enumCase(EN, "ReadWrite", AccessQualifier::ReadWrite);
}
};
template <>
struct ScalarEnumerationTraits<AddressSpaceQualifier> {
static void enumeration(IO &YIO, AddressSpaceQualifier &EN) {
YIO.enumCase(EN, "Private", AddressSpaceQualifier::Private);
YIO.enumCase(EN, "Global", AddressSpaceQualifier::Global);
YIO.enumCase(EN, "Constant", AddressSpaceQualifier::Constant);
YIO.enumCase(EN, "Local", AddressSpaceQualifier::Local);
YIO.enumCase(EN, "Generic", AddressSpaceQualifier::Generic);
YIO.enumCase(EN, "Region", AddressSpaceQualifier::Region);
}
};
template <>
struct ScalarEnumerationTraits<ValueKind> {
static void enumeration(IO &YIO, ValueKind &EN) {
YIO.enumCase(EN, "ByValue", ValueKind::ByValue);
YIO.enumCase(EN, "GlobalBuffer", ValueKind::GlobalBuffer);
YIO.enumCase(EN, "DynamicSharedPointer", ValueKind::DynamicSharedPointer);
YIO.enumCase(EN, "Sampler", ValueKind::Sampler);
YIO.enumCase(EN, "Image", ValueKind::Image);
YIO.enumCase(EN, "Pipe", ValueKind::Pipe);
YIO.enumCase(EN, "Queue", ValueKind::Queue);
YIO.enumCase(EN, "HiddenGlobalOffsetX", ValueKind::HiddenGlobalOffsetX);
YIO.enumCase(EN, "HiddenGlobalOffsetY", ValueKind::HiddenGlobalOffsetY);
YIO.enumCase(EN, "HiddenGlobalOffsetZ", ValueKind::HiddenGlobalOffsetZ);
YIO.enumCase(EN, "HiddenNone", ValueKind::HiddenNone);
YIO.enumCase(EN, "HiddenPrintfBuffer", ValueKind::HiddenPrintfBuffer);
YIO.enumCase(EN, "HiddenDefaultQueue", ValueKind::HiddenDefaultQueue);
YIO.enumCase(EN, "HiddenCompletionAction",
ValueKind::HiddenCompletionAction);
}
};
template <>
struct ScalarEnumerationTraits<ValueType> {
static void enumeration(IO &YIO, ValueType &EN) {
YIO.enumCase(EN, "Struct", ValueType::Struct);
YIO.enumCase(EN, "I8", ValueType::I8);
YIO.enumCase(EN, "U8", ValueType::U8);
YIO.enumCase(EN, "I16", ValueType::I16);
YIO.enumCase(EN, "U16", ValueType::U16);
YIO.enumCase(EN, "F16", ValueType::F16);
YIO.enumCase(EN, "I32", ValueType::I32);
YIO.enumCase(EN, "U32", ValueType::U32);
YIO.enumCase(EN, "F32", ValueType::F32);
YIO.enumCase(EN, "I64", ValueType::I64);
YIO.enumCase(EN, "U64", ValueType::U64);
YIO.enumCase(EN, "F64", ValueType::F64);
}
};
template <>
struct MappingTraits<Kernel::Attrs::Metadata> {
static void mapping(IO &YIO, Kernel::Attrs::Metadata &MD) {
YIO.mapOptional(Kernel::Attrs::Key::ReqdWorkGroupSize,
MD.mReqdWorkGroupSize, std::vector<uint32_t>());
YIO.mapOptional(Kernel::Attrs::Key::WorkGroupSizeHint,
MD.mWorkGroupSizeHint, std::vector<uint32_t>());
YIO.mapOptional(Kernel::Attrs::Key::VecTypeHint,
MD.mVecTypeHint, std::string());
YIO.mapOptional(Kernel::Attrs::Key::RuntimeHandle, MD.mRuntimeHandle,
std::string());
}
};
template <>
struct MappingTraits<Kernel::Arg::Metadata> {
static void mapping(IO &YIO, Kernel::Arg::Metadata &MD) {
YIO.mapOptional(Kernel::Arg::Key::Name, MD.mName, std::string());
YIO.mapOptional(Kernel::Arg::Key::TypeName, MD.mTypeName, std::string());
YIO.mapRequired(Kernel::Arg::Key::Size, MD.mSize);
YIO.mapRequired(Kernel::Arg::Key::Align, MD.mAlign);
YIO.mapRequired(Kernel::Arg::Key::ValueKind, MD.mValueKind);
YIO.mapRequired(Kernel::Arg::Key::ValueType, MD.mValueType);
YIO.mapOptional(Kernel::Arg::Key::PointeeAlign, MD.mPointeeAlign,
uint32_t(0));
YIO.mapOptional(Kernel::Arg::Key::AddrSpaceQual, MD.mAddrSpaceQual,
AddressSpaceQualifier::Unknown);
YIO.mapOptional(Kernel::Arg::Key::AccQual, MD.mAccQual,
AccessQualifier::Unknown);
YIO.mapOptional(Kernel::Arg::Key::ActualAccQual, MD.mActualAccQual,
AccessQualifier::Unknown);
YIO.mapOptional(Kernel::Arg::Key::IsConst, MD.mIsConst, false);
YIO.mapOptional(Kernel::Arg::Key::IsRestrict, MD.mIsRestrict, false);
YIO.mapOptional(Kernel::Arg::Key::IsVolatile, MD.mIsVolatile, false);
YIO.mapOptional(Kernel::Arg::Key::IsPipe, MD.mIsPipe, false);
}
};
template <>
struct MappingTraits<Kernel::CodeProps::Metadata> {
static void mapping(IO &YIO, Kernel::CodeProps::Metadata &MD) {
YIO.mapRequired(Kernel::CodeProps::Key::KernargSegmentSize,
MD.mKernargSegmentSize);
YIO.mapRequired(Kernel::CodeProps::Key::GroupSegmentFixedSize,
MD.mGroupSegmentFixedSize);
YIO.mapRequired(Kernel::CodeProps::Key::PrivateSegmentFixedSize,
MD.mPrivateSegmentFixedSize);
YIO.mapRequired(Kernel::CodeProps::Key::KernargSegmentAlign,
MD.mKernargSegmentAlign);
YIO.mapRequired(Kernel::CodeProps::Key::WavefrontSize,
MD.mWavefrontSize);
YIO.mapOptional(Kernel::CodeProps::Key::NumSGPRs,
MD.mNumSGPRs, uint16_t(0));
YIO.mapOptional(Kernel::CodeProps::Key::NumVGPRs,
MD.mNumVGPRs, uint16_t(0));
YIO.mapOptional(Kernel::CodeProps::Key::MaxFlatWorkGroupSize,
MD.mMaxFlatWorkGroupSize, uint32_t(0));
YIO.mapOptional(Kernel::CodeProps::Key::IsDynamicCallStack,
MD.mIsDynamicCallStack, false);
YIO.mapOptional(Kernel::CodeProps::Key::IsXNACKEnabled,
MD.mIsXNACKEnabled, false);
YIO.mapOptional(Kernel::CodeProps::Key::NumSpilledSGPRs,
MD.mNumSpilledSGPRs, uint16_t(0));
YIO.mapOptional(Kernel::CodeProps::Key::NumSpilledVGPRs,
MD.mNumSpilledVGPRs, uint16_t(0));
}
};
template <>
struct MappingTraits<Kernel::DebugProps::Metadata> {
static void mapping(IO &YIO, Kernel::DebugProps::Metadata &MD) {
YIO.mapOptional(Kernel::DebugProps::Key::DebuggerABIVersion,
MD.mDebuggerABIVersion, std::vector<uint32_t>());
YIO.mapOptional(Kernel::DebugProps::Key::ReservedNumVGPRs,
MD.mReservedNumVGPRs, uint16_t(0));
YIO.mapOptional(Kernel::DebugProps::Key::ReservedFirstVGPR,
MD.mReservedFirstVGPR, uint16_t(-1));
YIO.mapOptional(Kernel::DebugProps::Key::PrivateSegmentBufferSGPR,
MD.mPrivateSegmentBufferSGPR, uint16_t(-1));
YIO.mapOptional(Kernel::DebugProps::Key::WavefrontPrivateSegmentOffsetSGPR,
MD.mWavefrontPrivateSegmentOffsetSGPR, uint16_t(-1));
}
};
template <>
struct MappingTraits<Kernel::Metadata> {
static void mapping(IO &YIO, Kernel::Metadata &MD) {
YIO.mapRequired(Kernel::Key::Name, MD.mName);
YIO.mapRequired(Kernel::Key::SymbolName, MD.mSymbolName);
YIO.mapOptional(Kernel::Key::Language, MD.mLanguage, std::string());
YIO.mapOptional(Kernel::Key::LanguageVersion, MD.mLanguageVersion,
std::vector<uint32_t>());
if (!MD.mAttrs.empty() || !YIO.outputting())
YIO.mapOptional(Kernel::Key::Attrs, MD.mAttrs);
if (!MD.mArgs.empty() || !YIO.outputting())
YIO.mapOptional(Kernel::Key::Args, MD.mArgs);
if (!MD.mCodeProps.empty() || !YIO.outputting())
YIO.mapOptional(Kernel::Key::CodeProps, MD.mCodeProps);
if (!MD.mDebugProps.empty() || !YIO.outputting())
YIO.mapOptional(Kernel::Key::DebugProps, MD.mDebugProps);
}
};
template <>
struct MappingTraits<HSAMD::Metadata> {
static void mapping(IO &YIO, HSAMD::Metadata &MD) {
YIO.mapRequired(Key::Version, MD.mVersion);
YIO.mapOptional(Key::Printf, MD.mPrintf, std::vector<std::string>());
if (!MD.mKernels.empty() || !YIO.outputting())
YIO.mapOptional(Key::Kernels, MD.mKernels);
}
};
} // end namespace yaml
namespace AMDGPU {
namespace HSAMD {
std::error_code fromString(std::string String, Metadata &HSAMetadata) {
yaml::Input YamlInput(String);
YamlInput >> HSAMetadata;
return YamlInput.error();
}
std::error_code toString(Metadata HSAMetadata, std::string &String) {
raw_string_ostream YamlStream(String);
yaml::Output YamlOutput(YamlStream, nullptr, std::numeric_limits<int>::max());
YamlOutput << HSAMetadata;
return std::error_code();
}
} // end namespace HSAMD
} // end namespace AMDGPU
} // end namespace llvm
| 3,912 |
539 | #include "custom_protocols.h"
#include "multi_index.h"
#include "precompiled.h"
#include "container_extensibility.h"
template <typename Protocols, typename T, size_t N>
bool Compare(const std::array<T, N>& left, const std::array<T, N>& right)
{
static_assert(N > 0, "must have non-empty static strings");
const uint32_t rightLength = std::string_length(right);
if (std::string_length(left) != rightLength)
{
return false;
}
for (uint32_t i = 0; i < rightLength; ++i)
{
if (!Compare<Protocols>(left[i], static_cast<T>(right[i])))
{
return false;
}
}
return true;
}
template <typename Protocols, typename T, size_t N>
bool Compare(const std::array<T, N>& left, const std::basic_string<T>& right)
{
static_assert(N > 0, "must have non-empty static string");
if (std::string_length(left) != right.size())
{
return false;
}
for (typename std::basic_string<T>::size_type i = 0; i < right.size(); ++i)
{
if (!Compare<Protocols>(left[i], static_cast<T>(right[i])))
{
return false;
}
}
return true;
}
template <typename Protocols>
bool Compare(const WithStaticString& custom, const BondStruct<string>& standard)
{
return Compare<Protocols>(custom.field, standard.field);
}
template <typename Protocols>
bool Compare(const BondStruct<string>& standard, const WithStaticString& custom)
{
return Compare<Protocols>(custom.field, standard.field);
}
template <typename Protocols>
bool Compare(const WithStaticWString& custom, const BondStruct<wstring>& standard)
{
return Compare<Protocols>(custom.field, standard.field);
}
template <typename Protocols>
bool Compare(const BondStruct<wstring>& standard, const WithStaticWString& custom)
{
return Compare<Protocols>(custom.field, standard.field);
}
template <typename Protocols, typename T>
bool Compare(const WithSimpleList<T>& custom, const BondStruct<list<T> >& standard)
{
return Equal<Protocols>(custom.field, standard.field);
}
template <typename Protocols, typename T>
bool Compare(const BondStruct<list<T> >& standard, const WithSimpleList<T>& custom)
{
return Equal<Protocols>(custom.field, standard.field);
}
template <typename Reader, typename Writer>
struct SimpleListTest
{
template <typename X>
void operator()(const X&)
{
{
typedef WithSimpleList<X> Custom;
typedef BondStruct<list<X> > Standard;
AllBindingAndMapping<Reader, Writer, Custom, Standard>();
AllBindingAndMapping<Reader, Writer, Standard, Custom>();
}
}
};
template <typename Reader, typename Writer>
TEST_CASE_BEGIN(SimpleListContainerTest)
{
boost::mpl::for_each<BasicTypes>(SimpleListTest<Reader, Writer>());
}
TEST_CASE_END
template <typename Reader, typename Writer>
TEST_CASE_BEGIN(StringTest)
{
{
typedef WithStaticString Custom;
typedef BondStruct<string> Standard;
AllBindingAndMapping<Reader, Writer, Custom, Standard>();
AllBindingAndMapping<Reader, Writer, Standard, Custom>();
}
{
typedef WithStaticWString Custom;
typedef BondStruct<wstring> Standard;
AllBindingAndMapping<Reader, Writer, Custom, Standard>();
AllBindingAndMapping<Reader, Writer, Standard, Custom>();
}
}
TEST_CASE_END
template <typename Reader, typename Writer>
TEST_CASE_BEGIN(MultiIndexTest)
{
{
typedef BondStruct<std::list<uint32_t> > Standard;
typedef BondStruct<
boost::multi_index::multi_index_container<
uint32_t,
boost::multi_index::indexed_by<
boost::multi_index::sequenced<>,
boost::multi_index::ordered_non_unique<boost::multi_index::identity<uint32_t> >
>
>
> Custom;
AllBindingAndMapping<Reader, Writer, Custom, Standard>();
AllBindingAndMapping<Reader, Writer, Standard, Custom>();
}
{
typedef BondStruct<std::list<SimpleStructView> > Standard;
typedef BondStruct<
boost::multi_index::multi_index_container<
SimpleStructView,
boost::multi_index::indexed_by<
boost::multi_index::sequenced<>,
ordered_non_unique_field<SimpleStructView::Schema::var::m_str>,
ordered_non_unique_field<SimpleStructView::Schema::var::m_uint64>
>
>
> Custom;
AllBindingAndMapping<Reader, Writer, Custom, Standard>();
AllBindingAndMapping<Reader, Writer, Standard, Custom>();
}
}
TEST_CASE_END
template <uint16_t N, typename Reader, typename Writer>
void ExtensibilityTests(const char* name)
{
UnitTestSuite suite(name);
AddTestCase<TEST_ID(N),
SimpleListContainerTest, Reader, Writer>(suite, "C array based container");
AddTestCase<TEST_ID(N),
StringTest, Reader, Writer>(suite, "uint8_t[], uint16_t[] string");
AddTestCase<TEST_ID(N),
MultiIndexTest, Reader, Writer>(suite, "boost::multi_index_container");
}
void ExtensibilityTest::Initialize()
{
TEST_SIMPLE_PROTOCOL(
ExtensibilityTests<
0xd01,
bond::SimpleBinaryReader<bond::InputBuffer>,
bond::SimpleBinaryWriter<bond::OutputBuffer> >("Container extensibility tests for SimpleBinary");
);
TEST_COMPACT_BINARY_PROTOCOL(
ExtensibilityTests<
0xd02,
bond::CompactBinaryReader<bond::InputBuffer>,
bond::CompactBinaryWriter<bond::OutputBuffer> >("Container extensibility tests for CompactBinary");
);
TEST_FAST_BINARY_PROTOCOL(
ExtensibilityTests<
0xd03,
bond::FastBinaryReader<bond::InputBuffer>,
bond::FastBinaryWriter<bond::OutputBuffer> >("Container extensibility tests for FastBinary");
);
TEST_SIMPLE_JSON_PROTOCOL(
ExtensibilityTests<
0xd04,
bond::SimpleJsonReader<bond::InputBuffer>,
bond::SimpleJsonWriter<bond::OutputBuffer> >("Container extensibility tests for Simple JSON");
);
}
bool init_unit_test()
{
ExtensibilityTest::Initialize();
ExtensibilityTest::InitializeAssociative();
return true;
}
| 2,649 |
380 | <gh_stars>100-1000
# oxAuth is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text.
# Copyright (c) 2016, Gluu
#
# Author: <NAME> (based on acr_routerauthenticator.py)
#
# NOTE: before using this script, see the accompanying readme file
from org.gluu.oxauth.security import Identity
from org.gluu.model.custom.script.type.auth import PersonAuthenticationType
from org.gluu.oxauth.service import UserService
from org.gluu.util import StringHelper
from org.gluu.service.cdi.util import CdiUtil
import java
class PersonAuthentication(PersonAuthenticationType):
def __init__(self, currentTimeMillis):
self.currentTimeMillis = currentTimeMillis
def init(self, customScript, configurationAttributes):
print "Identifier First. Initialized successfully"
return True
def destroy(self, configurationAttributes):
print "Identifier First. Destroyed successfully"
return True
def getApiVersion(self):
return 11
def getAuthenticationMethodClaims(self, requestParameters):
return None
def isValidAuthenticationMethod(self, usageType, configurationAttributes):
print "Identifier First. isValidAuthenticationMethod called"
return False
def getAlternativeAuthenticationMethod(self, usageType, configurationAttributes):
print "Identifier First. getAlternativeAuthenticationMethod"
identity = CdiUtil.bean(Identity)
user_name = identity.getCredentials().getUsername()
print "Identifier First. Inspecting user %s" % user_name
attributes=identity.getSessionId().getSessionAttributes()
attributes.put("roUserName", user_name)
acr = None
try:
userService = CdiUtil.bean(UserService)
foundUser = userService.getUserByAttribute("uid", user_name)
if foundUser == None:
print "Identifier First. User does not exist"
return ""
attr = configurationAttributes.get("acr_attribute").getValue2()
acr=foundUser.getAttribute(attr)
#acr="u2f" or "otp" or "twilio_sms", etc...
if acr == None:
acr = "basic"
except:
print "Identifier First. Error looking up user or his preferred method"
print "Identifier First. new acr value %s" % acr
return acr
def authenticate(self, configurationAttributes, requestParameters, step):
return False
def prepareForStep(self, configurationAttributes, requestParameters, step):
print "Identifier First. prepareForStep %s" % str(step)
return True
def getExtraParametersForStep(self, configurationAttributes, step):
print "Identifier First. getExtraParametersForStep %s" % str(step)
return None
def getCountAuthenticationSteps(self, configurationAttributes):
print "Identifier First. getCountAuthenticationSteps called"
return 2
def getPageForStep(self, configurationAttributes, step):
print "Identifier First. getPageForStep called %s" % str(step)
if step == 1:
return "/auth/idfirst/idfirst_login.xhtml"
return ""
def getNextStep(self, configurationAttributes, requestParameters, step):
return -1
def getLogoutExternalUrl(self, configurationAttributes, requestParameters):
print "Get external logout URL call"
return None
def logout(self, configurationAttributes, requestParameters):
print "Identifier First. logout called"
return True
| 1,327 |
9,782 | <reponame>willianfonseca/presto<filename>presto-iceberg/src/main/java/com/facebook/presto/iceberg/ManifestsTable.java
/*
* 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.facebook.presto.iceberg;
import com.facebook.presto.common.Page;
import com.facebook.presto.common.block.BlockBuilder;
import com.facebook.presto.common.predicate.TupleDomain;
import com.facebook.presto.common.type.ArrayType;
import com.facebook.presto.common.type.RowType;
import com.facebook.presto.iceberg.util.PageListBuilder;
import com.facebook.presto.spi.ColumnMetadata;
import com.facebook.presto.spi.ConnectorPageSource;
import com.facebook.presto.spi.ConnectorSession;
import com.facebook.presto.spi.ConnectorTableMetadata;
import com.facebook.presto.spi.FixedPageSource;
import com.facebook.presto.spi.PrestoException;
import com.facebook.presto.spi.SchemaTableName;
import com.facebook.presto.spi.SystemTable;
import com.facebook.presto.spi.connector.ConnectorTransactionHandle;
import com.google.common.collect.ImmutableList;
import org.apache.iceberg.ManifestFile;
import org.apache.iceberg.PartitionField;
import org.apache.iceberg.PartitionSpec;
import org.apache.iceberg.Snapshot;
import org.apache.iceberg.Table;
import org.apache.iceberg.types.Conversions;
import org.apache.iceberg.types.Type;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static com.facebook.presto.common.type.BigintType.BIGINT;
import static com.facebook.presto.common.type.BooleanType.BOOLEAN;
import static com.facebook.presto.common.type.IntegerType.INTEGER;
import static com.facebook.presto.common.type.VarcharType.VARCHAR;
import static com.facebook.presto.iceberg.IcebergErrorCode.ICEBERG_INVALID_METADATA;
import static java.lang.String.format;
import static java.util.Arrays.asList;
import static java.util.Objects.requireNonNull;
public class ManifestsTable
implements SystemTable
{
private final ConnectorTableMetadata tableMetadata;
private final Table icebergTable;
private final Optional<Long> snapshotId;
public ManifestsTable(SchemaTableName tableName, Table icebergTable, Optional<Long> snapshotId)
{
this.icebergTable = requireNonNull(icebergTable, "icebergTable is null");
tableMetadata = new ConnectorTableMetadata(
tableName,
ImmutableList.<ColumnMetadata>builder()
.add(new ColumnMetadata("path", VARCHAR))
.add(new ColumnMetadata("length", BIGINT))
.add(new ColumnMetadata("partition_spec_id", INTEGER))
.add(new ColumnMetadata("added_snapshot_id", BIGINT))
.add(new ColumnMetadata("added_data_files_count", INTEGER))
.add(new ColumnMetadata("existing_data_files_count", INTEGER))
.add(new ColumnMetadata("deleted_data_files_count", INTEGER))
.add(new ColumnMetadata("partitions", new ArrayType(RowType.from(asList(
RowType.field("contains_null", BOOLEAN),
RowType.field("lower_bound", VARCHAR),
RowType.field("upper_bound", VARCHAR))))))
.build());
this.snapshotId = requireNonNull(snapshotId, "snapshotId is null");
}
@Override
public Distribution getDistribution()
{
return Distribution.SINGLE_COORDINATOR;
}
@Override
public ConnectorTableMetadata getTableMetadata()
{
return tableMetadata;
}
@Override
public ConnectorPageSource pageSource(ConnectorTransactionHandle transactionHandle, ConnectorSession session, TupleDomain<Integer> constraint)
{
if (!snapshotId.isPresent()) {
return new FixedPageSource(ImmutableList.of());
}
return new FixedPageSource(buildPages(tableMetadata, icebergTable, snapshotId.get()));
}
private static List<Page> buildPages(ConnectorTableMetadata tableMetadata, Table icebergTable, long snapshotId)
{
PageListBuilder pagesBuilder = PageListBuilder.forTable(tableMetadata);
Snapshot snapshot = icebergTable.snapshot(snapshotId);
if (snapshot == null) {
throw new PrestoException(ICEBERG_INVALID_METADATA, format("Snapshot ID [%s] does not exist for table: %s", snapshotId, icebergTable));
}
Map<Integer, PartitionSpec> partitionSpecsById = icebergTable.specs();
snapshot.allManifests().forEach(file -> {
pagesBuilder.beginRow();
pagesBuilder.appendVarchar(file.path());
pagesBuilder.appendBigint(file.length());
pagesBuilder.appendInteger(file.partitionSpecId());
pagesBuilder.appendBigint(file.snapshotId());
pagesBuilder.appendInteger(file.addedFilesCount());
pagesBuilder.appendInteger(file.existingFilesCount());
pagesBuilder.appendInteger(file.deletedFilesCount());
writePartitionSummaries(pagesBuilder.nextColumn(), file.partitions(), partitionSpecsById.get(file.partitionSpecId()));
pagesBuilder.endRow();
});
return pagesBuilder.build();
}
private static void writePartitionSummaries(BlockBuilder arrayBlockBuilder, List<ManifestFile.PartitionFieldSummary> summaries, PartitionSpec partitionSpec)
{
BlockBuilder singleArrayWriter = arrayBlockBuilder.beginBlockEntry();
for (int i = 0; i < summaries.size(); i++) {
ManifestFile.PartitionFieldSummary summary = summaries.get(i);
PartitionField field = partitionSpec.fields().get(i);
Type nestedType = partitionSpec.partitionType().fields().get(i).type();
BlockBuilder rowBuilder = singleArrayWriter.beginBlockEntry();
BOOLEAN.writeBoolean(rowBuilder, summary.containsNull());
VARCHAR.writeString(rowBuilder, field.transform().toHumanString(
Conversions.fromByteBuffer(nestedType, summary.lowerBound())));
VARCHAR.writeString(rowBuilder, field.transform().toHumanString(
Conversions.fromByteBuffer(nestedType, summary.upperBound())));
singleArrayWriter.closeEntry();
}
arrayBlockBuilder.closeEntry();
}
}
| 2,605 |
480 | <filename>ck/repo/module/artifact/.cm/meta.json
{
"actions": {
"snapshot": {
"desc": "snapshot artifact with all repo deps"
}
},
"bat_prepare_virtual_ck": "prepare_virtual_ck",
"bat_start_virtual_ck": "start_virtual_ck",
"copyright": "See CK COPYRIGHT.txt for copyright details",
"desc": "artifact description (reproducibility, ACM meta, etc)",
"developer": "<NAME>",
"developer_email": "<EMAIL>",
"developer_webpage": "http://fursin.net",
"license": "See CK LICENSE.txt for licensing details",
"module_deps": {
"repo": "befd7892b0d469e9"
},
"workflow": "yes",
"workflow_type": "HotCRP automation pipeline"
}
| 256 |
665 | <reponame>kstepanmpmg/mldb
// This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved.
#define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK
#include "mldb/types/periodic_utils.h"
#include <boost/test/unit_test.hpp>
#include "mldb/arch/exception.h"
using namespace std;
using namespace MLDB;
BOOST_AUTO_TEST_CASE(time_period_test)
{
TimePeriod tp("20s");
BOOST_CHECK_EQUAL(tp.interval, 20);
BOOST_CHECK_EQUAL(tp.toString(), "20s");
tp.parse("1m");
BOOST_CHECK_EQUAL(tp.interval, 60);
BOOST_CHECK_EQUAL(tp.toString(), "1m");
tp.parse("90s");
BOOST_CHECK_EQUAL(tp.interval, 90);
BOOST_CHECK_EQUAL(tp.toString(), "90s");
bool threw = false;
try {
MLDB_TRACE_EXCEPTIONS(false);
tp.parse("1m25s");
}
catch (...) {
threw = true;
}
BOOST_CHECK(threw);
tp.parse("1h");
BOOST_CHECK_EQUAL(tp.interval, 3600);
BOOST_CHECK_EQUAL(tp.toString(), "1h");
tp.parse("1d");
BOOST_CHECK_EQUAL(tp.interval, 3600 * 24);
BOOST_CHECK_EQUAL(tp.toString(), "1d");
}
#if 1
BOOST_AUTO_TEST_CASE(time_period_granularity_multiplier)
{
MLDB_TRACE_EXCEPTIONS(false);
/* different families */
BOOST_CHECK_THROW(granularityMultiplier(YEARS, MINUTES), MLDB::Exception);
/* seconds cannot be translated to minutes */
BOOST_CHECK_THROW(granularityMultiplier(SECONDS, MINUTES), MLDB::Exception);
int mult = granularityMultiplier(MILLISECONDS, MILLISECONDS);
BOOST_CHECK_EQUAL(mult, 1);
mult = granularityMultiplier(MINUTES, MILLISECONDS);
BOOST_CHECK_EQUAL(mult, 60000);
mult = granularityMultiplier(MINUTES, MINUTES);
BOOST_CHECK_EQUAL(mult, 1);
mult = granularityMultiplier(WEEKS, MINUTES);
BOOST_CHECK_EQUAL(mult, 10080);
mult = granularityMultiplier(YEARS, YEARS);
BOOST_CHECK_EQUAL(mult, 1);
mult = granularityMultiplier(YEARS, MONTHS);
BOOST_CHECK_EQUAL(mult, 12);
}
#endif
#if 1
/* Ensure that operators + and += works well for TimePeriod */
BOOST_AUTO_TEST_CASE(time_period_op_plus_equal)
{
/* same unit */
{
TimePeriod period1("2m");
TimePeriod period2("5m");
TimePeriod total = period1 + period2;
BOOST_CHECK_EQUAL(total.granularity, MINUTES);
BOOST_CHECK_EQUAL(total.number, 7);
BOOST_CHECK_EQUAL(total.interval, 420);
}
/* distinct compatible units */
{
TimePeriod period1("1h");
TimePeriod period2("2s");
TimePeriod total = period1 + period2;
BOOST_CHECK_EQUAL(total.granularity, SECONDS);
BOOST_CHECK_EQUAL(total.number, 3602);
BOOST_CHECK_EQUAL(total.interval, 3602);
/* operator += */
period1 += period2;
BOOST_CHECK_EQUAL(period1.granularity, SECONDS);
BOOST_CHECK_EQUAL(period1.number, 3602);
BOOST_CHECK_EQUAL(period1.interval, 3602);
}
/* same as above, in reverse order */
{
TimePeriod period1("2s");
TimePeriod period2("1h");
TimePeriod total = period1 + period2;
BOOST_CHECK_EQUAL(total.granularity, SECONDS);
BOOST_CHECK_EQUAL(total.number, 3602);
BOOST_CHECK_EQUAL(total.interval, 3602);
/* operator += */
period1 += period2;
BOOST_CHECK_EQUAL(period1.granularity, SECONDS);
BOOST_CHECK_EQUAL(period1.number, 3602);
BOOST_CHECK_EQUAL(period1.interval, 3602);
}
/* incompatible units */
{
TimePeriod yearly;
yearly.granularity = YEARS;
yearly.number = 1;
yearly.interval = -1; // years do not have a fixed set of seconds
TimePeriod minutely("2m");
MLDB_TRACE_EXCEPTIONS(false);
BOOST_CHECK_THROW(yearly + minutely, MLDB::Exception);
}
{
TimePeriod t;
t += "1s";
BOOST_CHECK_EQUAL(t.granularity, SECONDS);
BOOST_CHECK_EQUAL(t.number, 1);
BOOST_CHECK_EQUAL(t.interval, 1);
}
}
#endif
| 1,890 |
365 | /*
* 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.
*
* Copyright 2017, Blender Foundation.
*/
/** \file
* \ingroup draw
*/
#pragma once
#include "DNA_gpencil_types.h"
#include "DRW_render.h"
#include "BLI_bitmap.h"
#include "GPU_batch.h"
#ifdef __cplusplus
extern "C" {
#endif
extern DrawEngineType draw_engine_gpencil_type;
struct GPENCIL_Data;
struct GPENCIL_StorageList;
struct GPUBatch;
struct GpencilBatchCache;
struct Object;
struct RenderEngine;
struct RenderLayer;
struct View3D;
struct bGPDstroke;
/* used to convert pixel scale. */
#define GPENCIL_PIXEL_FACTOR 2000.0f
/* used to expand VBOs. Size has a big impact in the speed */
#define GPENCIL_VBO_BLOCK_SIZE 128
#define GP_MAX_MASKBITS 256
/* UBO structure. Watch out for padding. Must match GLSL declaration. */
typedef struct gpMaterial {
float stroke_color[4];
float fill_color[4];
float fill_mix_color[4];
float fill_uv_transform[3][2], alignment_rot_cos, alignment_rot_sin;
float stroke_texture_mix;
float stroke_u_scale;
float fill_texture_mix;
int flag;
} gpMaterial;
/* gpMaterial->flag */
/* WATCH Keep in sync with GLSL declaration. */
#define GP_STROKE_ALIGNMENT_STROKE 1
#define GP_STROKE_ALIGNMENT_OBJECT 2
#define GP_STROKE_ALIGNMENT_FIXED 3
#define GP_STROKE_ALIGNMENT 0x3
#define GP_STROKE_OVERLAP (1 << 2)
#define GP_STROKE_TEXTURE_USE (1 << 3)
#define GP_STROKE_TEXTURE_STENCIL (1 << 4)
#define GP_STROKE_TEXTURE_PREMUL (1 << 5)
#define GP_STROKE_DOTS (1 << 6)
#define GP_STROKE_HOLDOUT (1 << 7)
#define GP_FILL_HOLDOUT (1 << 8)
#define GP_FILL_TEXTURE_USE (1 << 10)
#define GP_FILL_TEXTURE_PREMUL (1 << 11)
#define GP_FILL_TEXTURE_CLIP (1 << 12)
#define GP_FILL_GRADIENT_USE (1 << 13)
#define GP_FILL_GRADIENT_RADIAL (1 << 14)
#define GPENCIL_LIGHT_BUFFER_LEN 128
/* UBO structure. Watch out for padding. Must match GLSL declaration. */
typedef struct gpLight {
float color[3], type;
float right[3], spotsize;
float up[3], spotblend;
float forward[4];
float position[4];
} gpLight;
/* gpLight->type */
/* WATCH Keep in sync with GLSL declaration. */
#define GP_LIGHT_TYPE_POINT 0.0
#define GP_LIGHT_TYPE_SPOT 1.0
#define GP_LIGHT_TYPE_SUN 2.0
#define GP_LIGHT_TYPE_AMBIENT 3.0
BLI_STATIC_ASSERT_ALIGN(gpMaterial, 16)
BLI_STATIC_ASSERT_ALIGN(gpLight, 16)
/* *********** Draw Datas *********** */
typedef struct GPENCIL_MaterialPool {
/* Linklist. */
struct GPENCIL_MaterialPool *next;
/* GPU representation of materials. */
gpMaterial mat_data[GP_MATERIAL_BUFFER_LEN];
/* Matching ubo. */
struct GPUUniformBuf *ubo;
/* Texture per material. NULL means none. */
struct GPUTexture *tex_fill[GP_MATERIAL_BUFFER_LEN];
struct GPUTexture *tex_stroke[GP_MATERIAL_BUFFER_LEN];
/* Number of material used in this pool. */
int used_count;
} GPENCIL_MaterialPool;
typedef struct GPENCIL_LightPool {
/* GPU representation of materials. */
gpLight light_data[GPENCIL_LIGHT_BUFFER_LEN];
/* Matching ubo. */
struct GPUUniformBuf *ubo;
/* Number of light in the pool. */
int light_used;
} GPENCIL_LightPool;
typedef struct GPENCIL_ViewLayerData {
/* GPENCIL_tObject */
struct BLI_memblock *gp_object_pool;
/* GPENCIL_tLayer */
struct BLI_memblock *gp_layer_pool;
/* GPENCIL_tVfx */
struct BLI_memblock *gp_vfx_pool;
/* GPENCIL_MaterialPool */
struct BLI_memblock *gp_material_pool;
/* GPENCIL_LightPool */
struct BLI_memblock *gp_light_pool;
/* BLI_bitmap */
struct BLI_memblock *gp_maskbit_pool;
} GPENCIL_ViewLayerData;
/* *********** GPencil *********** */
typedef struct GPENCIL_tVfx {
/** Linklist */
struct GPENCIL_tVfx *next;
DRWPass *vfx_ps;
/* Frame-buffer reference since it may not be allocated yet. */
GPUFrameBuffer **target_fb;
} GPENCIL_tVfx;
typedef struct GPENCIL_tLayer {
/** Linklist */
struct GPENCIL_tLayer *next;
/** Geometry pass (draw all strokes). */
DRWPass *geom_ps;
/** Blend pass to composite onto the target buffer (blends modes). NULL if not needed. */
DRWPass *blend_ps;
/** First shading group created for this layer. Contains all uniforms. */
DRWShadingGroup *base_shgrp;
/** Layer id of the mask. */
BLI_bitmap *mask_bits;
BLI_bitmap *mask_invert_bits;
/** Index in the layer list. Used as id for masking. */
int layer_id;
} GPENCIL_tLayer;
typedef struct GPENCIL_tObject {
/** Linklist */
struct GPENCIL_tObject *next;
struct {
GPENCIL_tLayer *first, *last;
} layers;
struct {
GPENCIL_tVfx *first, *last;
} vfx;
/* Distance to camera. Used for sorting. */
float camera_z;
/* Used for stroke thickness scaling. */
float object_scale;
/* Normal used for shading. Based on view angle. */
float plane_normal[3];
/* Used for drawing depth merge pass. */
float plane_mat[4][4];
bool is_drawmode3d;
/* Use Material Holdout. */
bool do_mat_holdout;
} GPENCIL_tObject;
/* *********** LISTS *********** */
typedef struct GPENCIL_StorageList {
struct GPENCIL_PrivateData *pd;
} GPENCIL_StorageList;
typedef struct GPENCIL_PassList {
/* Composite the main GPencil buffer onto the rendered image. */
struct DRWPass *composite_ps;
/* Composite the object depth to the default depth buffer to occlude overlays. */
struct DRWPass *merge_depth_ps;
/* Invert mask buffer content. */
struct DRWPass *mask_invert_ps;
/* Anti-Aliasing. */
struct DRWPass *smaa_edge_ps;
struct DRWPass *smaa_weight_ps;
struct DRWPass *smaa_resolve_ps;
} GPENCIL_PassList;
typedef struct GPENCIL_FramebufferList {
struct GPUFrameBuffer *render_fb;
struct GPUFrameBuffer *gpencil_fb;
struct GPUFrameBuffer *snapshot_fb;
struct GPUFrameBuffer *layer_fb;
struct GPUFrameBuffer *object_fb;
struct GPUFrameBuffer *mask_fb;
struct GPUFrameBuffer *smaa_edge_fb;
struct GPUFrameBuffer *smaa_weight_fb;
} GPENCIL_FramebufferList;
typedef struct GPENCIL_TextureList {
/* Dummy texture to avoid errors cause by empty sampler. */
struct GPUTexture *dummy_texture;
/* Snapshot for smoother drawing. */
struct GPUTexture *snapshot_depth_tx;
struct GPUTexture *snapshot_color_tx;
struct GPUTexture *snapshot_reveal_tx;
/* Textures used by Antialiasing. */
struct GPUTexture *smaa_area_tx;
struct GPUTexture *smaa_search_tx;
/* Textures used during render. Containing underlying rendered scene. */
struct GPUTexture *render_depth_tx;
struct GPUTexture *render_color_tx;
} GPENCIL_TextureList;
typedef struct GPENCIL_Data {
void *engine_type; /* Required */
struct GPENCIL_FramebufferList *fbl;
struct GPENCIL_TextureList *txl;
struct GPENCIL_PassList *psl;
struct GPENCIL_StorageList *stl;
} GPENCIL_Data;
/* *********** STATIC *********** */
typedef struct GPENCIL_PrivateData {
/* Pointers copied from GPENCIL_ViewLayerData. */
struct BLI_memblock *gp_object_pool;
struct BLI_memblock *gp_layer_pool;
struct BLI_memblock *gp_vfx_pool;
struct BLI_memblock *gp_material_pool;
struct BLI_memblock *gp_light_pool;
struct BLI_memblock *gp_maskbit_pool;
/* Last used material pool. */
GPENCIL_MaterialPool *last_material_pool;
/* Last used light pool. */
GPENCIL_LightPool *last_light_pool;
/* Common lightpool containing all lights in the scene. */
GPENCIL_LightPool *global_light_pool;
/* Common lightpool containing one ambient white light. */
GPENCIL_LightPool *shadeless_light_pool;
/* Linked list of tObjects. */
struct {
GPENCIL_tObject *first, *last;
} tobjects, tobjects_infront;
/* Temp Textures (shared with other engines). */
GPUTexture *depth_tx;
GPUTexture *color_tx;
GPUTexture *color_layer_tx;
GPUTexture *color_object_tx;
/* Revealage is 1 - alpha */
GPUTexture *reveal_tx;
GPUTexture *reveal_layer_tx;
GPUTexture *reveal_object_tx;
/* Mask texture */
GPUTexture *mask_tx;
/* Anti-Aliasing. */
GPUTexture *smaa_edge_tx;
GPUTexture *smaa_weight_tx;
/* Pointer to dtxl->depth */
GPUTexture *scene_depth_tx;
GPUFrameBuffer *scene_fb;
/* Copy of txl->dummy_tx */
GPUTexture *dummy_tx;
/* Copy of v3d->shading.single_color. */
float v3d_single_color[3];
/* Copy of v3d->shading.color_type or -1 to ignore. */
int v3d_color_type;
/* Current frame */
int cfra;
/* If we are rendering for final render (F12). */
bool is_render;
/* If we are in viewport display (used for VFX). */
bool is_viewport;
/* True in selection and auto_depth drawing */
bool draw_depth_only;
/* Is shading set to wireframe. */
bool draw_wireframe;
/* Used by the depth merge step. */
int is_stroke_order_3d;
float object_bound_mat[4][4];
/* Used for computing object distance to camera. */
float camera_z_axis[3], camera_z_offset;
float camera_pos[3];
/* Pseudo depth of field parameter. Used to scale blur radius. */
float dof_params[2];
/* Used for DoF Setup. */
Object *camera;
/* Copy of draw_ctx->view_layer for convenience. */
struct ViewLayer *view_layer;
/* Copy of draw_ctx->scene for convenience. */
struct Scene *scene;
/* Copy of draw_ctx->vie3d for convenience. */
struct View3D *v3d;
/* Active object. */
Object *obact;
/* Object being in draw mode. */
struct bGPdata *sbuffer_gpd;
/* Layer to append the temp stroke to. */
struct bGPDlayer *sbuffer_layer;
/* Temporary stroke currently being drawn. */
struct bGPDstroke *sbuffer_stroke;
/* List of temp objects containing the stroke. */
struct {
GPENCIL_tObject *first, *last;
} sbuffer_tobjects;
/* Batches containing the temp stroke. */
GPUBatch *stroke_batch;
GPUBatch *fill_batch;
bool do_fast_drawing;
bool snapshot_buffer_dirty;
/* Display onion skinning */
bool do_onion;
/* Playing animation */
bool playing;
/* simplify settings */
bool simplify_fill;
bool simplify_fx;
bool simplify_antialias;
/* Use scene lighting or flat shading (global setting). */
bool use_lighting;
/* Use physical lights or just ambient lighting. */
bool use_lights;
/* Do we need additional frame-buffers? */
bool use_layer_fb;
bool use_object_fb;
bool use_mask_fb;
/* Some blend mode needs to add negative values.
* This is only supported if target texture is signed. */
bool use_signed_fb;
/* Use only lines for multiedit and not active frame. */
bool use_multiedit_lines_only;
/* Layer opacity for fading. */
float fade_layer_opacity;
/* Opacity for fading gpencil objects. */
float fade_gp_object_opacity;
/* Opacity for fading 3D objects. */
float fade_3d_object_opacity;
/* Mask opacity uniform. */
float mask_opacity;
/* Xray transparency in solid mode. */
float xray_alpha;
/* Mask invert uniform. */
int mask_invert;
/* Vertex Paint opacity. */
float vertex_paint_opacity;
} GPENCIL_PrivateData;
/* geometry batch cache functions */
struct GpencilBatchCache *gpencil_batch_cache_get(struct Object *ob, int cfra);
GPENCIL_tObject *gpencil_object_cache_add(GPENCIL_PrivateData *pd, Object *ob);
void gpencil_object_cache_sort(GPENCIL_PrivateData *pd);
GPENCIL_tLayer *gpencil_layer_cache_add(GPENCIL_PrivateData *pd,
const Object *ob,
const bGPDlayer *gpl,
const bGPDframe *gpf,
GPENCIL_tObject *tgp_ob);
GPENCIL_tLayer *gpencil_layer_cache_get(GPENCIL_tObject *tgp_ob, int number);
GPENCIL_MaterialPool *gpencil_material_pool_create(GPENCIL_PrivateData *pd, Object *ob, int *ofs);
void gpencil_material_resources_get(GPENCIL_MaterialPool *first_pool,
int mat_id,
struct GPUTexture **r_tex_stroke,
struct GPUTexture **r_tex_fill,
struct GPUUniformBuf **r_ubo_mat);
void gpencil_light_ambient_add(GPENCIL_LightPool *lightpool, const float color[3]);
void gpencil_light_pool_populate(GPENCIL_LightPool *lightpool, Object *ob);
GPENCIL_LightPool *gpencil_light_pool_add(GPENCIL_PrivateData *pd);
GPENCIL_LightPool *gpencil_light_pool_create(GPENCIL_PrivateData *pd, Object *ob);
/* effects */
void gpencil_vfx_cache_populate(GPENCIL_Data *vedata, Object *ob, GPENCIL_tObject *tgp_ob);
/* Shaders */
struct GPUShader *GPENCIL_shader_antialiasing(int stage);
struct GPUShader *GPENCIL_shader_geometry_get(void);
struct GPUShader *GPENCIL_shader_layer_blend_get(void);
struct GPUShader *GPENCIL_shader_mask_invert_get(void);
struct GPUShader *GPENCIL_shader_depth_merge_get(void);
struct GPUShader *GPENCIL_shader_fx_blur_get(void);
struct GPUShader *GPENCIL_shader_fx_colorize_get(void);
struct GPUShader *GPENCIL_shader_fx_composite_get(void);
struct GPUShader *GPENCIL_shader_fx_transform_get(void);
struct GPUShader *GPENCIL_shader_fx_glow_get(void);
struct GPUShader *GPENCIL_shader_fx_pixelize_get(void);
struct GPUShader *GPENCIL_shader_fx_rim_get(void);
struct GPUShader *GPENCIL_shader_fx_shadow_get(void);
void GPENCIL_shader_free(void);
/* Antialiasing */
void GPENCIL_antialiasing_init(struct GPENCIL_Data *vedata);
void GPENCIL_antialiasing_draw(struct GPENCIL_Data *vedata);
/* main functions */
void GPENCIL_engine_init(void *vedata);
void GPENCIL_cache_init(void *vedata);
void GPENCIL_cache_populate(void *vedata, struct Object *ob);
void GPENCIL_cache_finish(void *vedata);
void GPENCIL_draw_scene(void *vedata);
/* render */
void GPENCIL_render_init(struct GPENCIL_Data *ved,
struct RenderEngine *engine,
struct RenderLayer *render_layer,
const struct Depsgraph *depsgraph,
const rcti *rect);
void GPENCIL_render_to_image(void *vedata,
struct RenderEngine *engine,
struct RenderLayer *render_layer,
const rcti *rect);
/* Draw Data. */
void gpencil_light_pool_free(void *storage);
void gpencil_material_pool_free(void *storage);
GPENCIL_ViewLayerData *GPENCIL_view_layer_data_ensure(void);
#ifdef __cplusplus
}
#endif
| 5,548 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.