max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
1,399 |
<reponame>allister-grange/readme.so
{
"editor-desktop-optimized": "Ang website na ito ay magagamit lamang para sa desktop",
"editor-visit-desktop": "Mangyaring bisitahin ang readme.so sa isang desktop upang likhain ang iyong readme!",
"nav-download": "Mag-Download",
"download-readme-generated": "Nabuo na ang Readme!",
"download-reach-out": "Salamat sa paggamit ng readme.so! Huwag mag-atubiling makipag-ugnay sa akin sa",
"download-feedback": "na may anumang feedback.",
"download-coffee": "Kung nakita mong kapaki-pakinabang ang produktong ito, isaalang-alang ang pagsuporta sa akin na may kasamang isang tasa ng kape!",
"editor-column-editor": "Editor",
"editor-select": "Pumili ng isang seksyon mula sa kaliwang sidebar upang i-edit ang mga nilalaman",
"preview-column-preview": "Preview",
"preview-column-raw": "Raw",
"section-column-section": "Mga Seksyon",
"section-column-click-edit": "Mag-click sa isang seksyon sa ibaba upang mai-edit ang mga nilalaman",
"section-column-click-add": "Mag-click sa isang seksyon sa ibaba upang idagdag ito sa iyong readme",
"section-column-click-reset": "nollaa"
}
| 420 |
365 |
<reponame>rotoglup/blender
/*
* Copyright 2018 Blender Foundation
*
* 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 "render/coverage.h"
#include "render/buffers.h"
#include "kernel/kernel_compat_cpu.h"
#include "kernel/kernel_types.h"
#include "kernel/split/kernel_split_data.h"
#include "kernel/kernel_globals.h"
#include "kernel/kernel_id_passes.h"
#include "util/util_map.h"
CCL_NAMESPACE_BEGIN
static bool crypomatte_comp(const pair<float, float> &i, const pair<float, float> j)
{
return i.first > j.first;
}
void Coverage::finalize()
{
int pass_offset = 0;
if (kernel_data.film.cryptomatte_passes & CRYPT_OBJECT) {
finalize_buffer(coverage_object, pass_offset);
pass_offset += kernel_data.film.cryptomatte_depth * 4;
}
if (kernel_data.film.cryptomatte_passes & CRYPT_MATERIAL) {
finalize_buffer(coverage_material, pass_offset);
pass_offset += kernel_data.film.cryptomatte_depth * 4;
}
if (kernel_data.film.cryptomatte_passes & CRYPT_ASSET) {
finalize_buffer(coverage_asset, pass_offset);
}
}
void Coverage::init_path_trace()
{
kg->coverage_object = kg->coverage_material = kg->coverage_asset = NULL;
if (kernel_data.film.cryptomatte_passes & CRYPT_ACCURATE) {
if (kernel_data.film.cryptomatte_passes & CRYPT_OBJECT) {
coverage_object.clear();
coverage_object.resize(tile.w * tile.h);
}
if (kernel_data.film.cryptomatte_passes & CRYPT_MATERIAL) {
coverage_material.clear();
coverage_material.resize(tile.w * tile.h);
}
if (kernel_data.film.cryptomatte_passes & CRYPT_ASSET) {
coverage_asset.clear();
coverage_asset.resize(tile.w * tile.h);
}
}
}
void Coverage::init_pixel(int x, int y)
{
if (kernel_data.film.cryptomatte_passes & CRYPT_ACCURATE) {
const int pixel_index = tile.w * (y - tile.y) + x - tile.x;
if (kernel_data.film.cryptomatte_passes & CRYPT_OBJECT) {
kg->coverage_object = &coverage_object[pixel_index];
}
if (kernel_data.film.cryptomatte_passes & CRYPT_MATERIAL) {
kg->coverage_material = &coverage_material[pixel_index];
}
if (kernel_data.film.cryptomatte_passes & CRYPT_ASSET) {
kg->coverage_asset = &coverage_asset[pixel_index];
}
}
}
void Coverage::finalize_buffer(vector<CoverageMap> &coverage, const int pass_offset)
{
if (kernel_data.film.cryptomatte_passes & CRYPT_ACCURATE) {
flatten_buffer(coverage, pass_offset);
}
else {
sort_buffer(pass_offset);
}
}
void Coverage::flatten_buffer(vector<CoverageMap> &coverage, const int pass_offset)
{
/* Sort the coverage map and write it to the output */
int pixel_index = 0;
int pass_stride = tile.buffers->params.get_passes_size();
for (int y = 0; y < tile.h; ++y) {
for (int x = 0; x < tile.w; ++x) {
const CoverageMap &pixel = coverage[pixel_index];
if (!pixel.empty()) {
/* buffer offset */
int index = x + y * tile.stride;
float *buffer = (float *)tile.buffer + index * pass_stride;
/* sort the cryptomatte pixel */
vector<pair<float, float>> sorted_pixel;
for (CoverageMap::const_iterator it = pixel.begin(); it != pixel.end(); ++it) {
sorted_pixel.push_back(std::make_pair(it->second, it->first));
}
sort(sorted_pixel.begin(), sorted_pixel.end(), crypomatte_comp);
int num_slots = 2 * (kernel_data.film.cryptomatte_depth);
if (sorted_pixel.size() > num_slots) {
float leftover = 0.0f;
for (vector<pair<float, float>>::iterator it = sorted_pixel.begin() + num_slots;
it != sorted_pixel.end();
++it) {
leftover += it->first;
}
sorted_pixel[num_slots - 1].first += leftover;
}
int limit = min(num_slots, sorted_pixel.size());
for (int i = 0; i < limit; ++i) {
kernel_write_id_slots(buffer + kernel_data.film.pass_cryptomatte + pass_offset,
2 * (kernel_data.film.cryptomatte_depth),
sorted_pixel[i].second,
sorted_pixel[i].first);
}
}
++pixel_index;
}
}
}
void Coverage::sort_buffer(const int pass_offset)
{
/* Sort the coverage map and write it to the output */
int pass_stride = tile.buffers->params.get_passes_size();
for (int y = 0; y < tile.h; ++y) {
for (int x = 0; x < tile.w; ++x) {
/* buffer offset */
int index = x + y * tile.stride;
float *buffer = (float *)tile.buffer + index * pass_stride;
kernel_sort_id_slots(buffer + kernel_data.film.pass_cryptomatte + pass_offset,
2 * (kernel_data.film.cryptomatte_depth));
}
}
}
CCL_NAMESPACE_END
| 2,204 |
381 |
<gh_stars>100-1000
"""
Bytecode handling classes and functions for use by the flow space.
"""
from rpython.tool.stdlib_opcode import host_bytecode_spec
from opcode import EXTENDED_ARG, HAVE_ARGUMENT
import opcode
from rpython.flowspace.argument import Signature
CO_GENERATOR = 0x0020
CO_VARARGS = 0x0004
CO_VARKEYWORDS = 0x0008
def cpython_code_signature(code):
"([list-of-arg-names], vararg-name-or-None, kwarg-name-or-None)."
argcount = code.co_argcount
argnames = list(code.co_varnames[:argcount])
if code.co_flags & CO_VARARGS:
varargname = code.co_varnames[argcount]
argcount += 1
else:
varargname = None
if code.co_flags & CO_VARKEYWORDS:
kwargname = code.co_varnames[argcount]
argcount += 1
else:
kwargname = None
return Signature(argnames, varargname, kwargname)
class BytecodeCorruption(Exception):
pass
class HostCode(object):
"""
A wrapper around a native code object of the host interpreter
"""
opnames = host_bytecode_spec.method_names
def __init__(self, argcount, nlocals, stacksize, flags,
code, consts, names, varnames, filename,
name, firstlineno, lnotab, freevars):
"""Initialize a new code object"""
assert nlocals >= 0
self.co_argcount = argcount
self.co_nlocals = nlocals
self.co_stacksize = stacksize
self.co_flags = flags
self.co_code = code
self.consts = consts
self.names = names
self.co_varnames = varnames
self.co_freevars = freevars
self.co_filename = filename
self.co_name = name
self.co_firstlineno = firstlineno
self.co_lnotab = lnotab
self.signature = cpython_code_signature(self)
@classmethod
def _from_code(cls, code):
"""Initialize the code object from a real (CPython) one.
"""
return cls(code.co_argcount,
code.co_nlocals,
code.co_stacksize,
code.co_flags,
code.co_code,
list(code.co_consts),
list(code.co_names),
list(code.co_varnames),
code.co_filename,
code.co_name,
code.co_firstlineno,
code.co_lnotab,
list(code.co_freevars))
@property
def formalargcount(self):
"""Total number of arguments passed into the frame, including *vararg
and **varkwarg, if they exist."""
return self.signature.scope_length()
def read(self, offset):
"""
Decode the instruction starting at position ``offset``.
Returns (next_offset, opname, oparg).
"""
co_code = self.co_code
opnum = ord(co_code[offset])
next_offset = offset + 1
if opnum >= HAVE_ARGUMENT:
lo = ord(co_code[next_offset])
hi = ord(co_code[next_offset + 1])
next_offset += 2
oparg = (hi * 256) | lo
else:
oparg = 0
while opnum == EXTENDED_ARG:
opnum = ord(co_code[next_offset])
if opnum < HAVE_ARGUMENT:
raise BytecodeCorruption
lo = ord(co_code[next_offset + 1])
hi = ord(co_code[next_offset + 2])
next_offset += 3
oparg = (oparg * 65536) | (hi * 256) | lo
if opnum in opcode.hasjrel:
oparg += next_offset
opname = self.opnames[opnum]
return next_offset, opname, oparg
@property
def is_generator(self):
return bool(self.co_flags & CO_GENERATOR)
| 1,804 |
988 |
/*
* 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.javascript2.jsdoc.model;
import java.util.ArrayList;
import java.util.List;
import org.netbeans.modules.javascript2.doc.spi.DocParameter;
import org.netbeans.modules.javascript2.types.api.Identifier;
import org.netbeans.modules.javascript2.types.api.Type;
/**
* Represents named parameter element.
* <p>
* <i>Examples:</i> @param {MyType} myName myDescription,...
*
* @author <NAME> <<EMAIL>>
*/
public class NamedParameterElement extends ParameterElement implements DocParameter {
private final Identifier paramName;
private final boolean optional;
private final String defaultValue;
private NamedParameterElement(JsDocElementType type, Identifier paramName,
List<Type> paramTypes, String paramDescription,
boolean optional, String defaultValue) {
super(type, paramTypes, paramDescription);
this.paramName = paramName;
this.optional = optional;
this.defaultValue = defaultValue;
}
/**
* Creates named parameter element.
* @param type type of the element
* @param paramName name of the parameter
* @param paramTypes type of the parameter
* @param paramDescription description of the parameter
* @param optional flag if the parameter is optional
* @param defaultValue default value of the parameter
*/
public static NamedParameterElement create(JsDocElementType type, Identifier paramName,
List<Type> paramTypes, String paramDescription,
boolean optional, String defaultValue) {
return new NamedParameterElement(type, paramName, paramTypes, paramDescription, optional, defaultValue);
}
/**
* Creates named parameter element.
* <p>
* This creates optional parameter with no default value.
* @param type type of the element
* @param paramName name of the parameter
* @param paramTypes type of the parameter
* @param paramDescription description of the parameter
* @param optional flag if the parameter is optional
*/
public static NamedParameterElement create(JsDocElementType type, Identifier paramName,
List<Type> paramTypes, String paramDescription,
boolean optional) {
return new NamedParameterElement(type, paramName, paramTypes, paramDescription, optional, null);
}
/**
* Creates named parameter element.
* <p>
* This creates mandatory parameter with no default value.
* @param type type of the element
* @param paramName name of the parameter
* @param paramTypes type of the parameter
* @param paramDescription description of the parameter
*/
public static NamedParameterElement create(JsDocElementType type, Identifier paramName,
List<Type> paramTypes, String paramDescription) {
return new NamedParameterElement(type, paramName, paramTypes, paramDescription, false, null);
}
/**
* Creates named parameter element.
* <p>
* Also do diagnostics on paramName if the parameter isn't optional and with default value
* and types, whether use in Google Compiler Syntax.
* @param type type of the element
* @param paramName name of the parameter
* @param paramTypes type of the parameter
* @param paramDescription description of the parameter
*/
public static NamedParameterElement createWithDiagnostics(JsDocElementType type, Identifier paramName,
List<Type> paramTypes, String paramDescription) {
int nameStartOffset = paramName.getOffsetRange().getStart();
String name = paramName.getName();
if (name.indexOf('~') > 0) {
// we dont't replace tilda if it's on the first position
name = name.replace('~', '.'); // replacing tilda with dot. See issue #25110
}
boolean optional = name.matches("\\[.*\\]"); //NOI18N
String defaultValue = null;
List<Type> correctedTypes = new ArrayList<>();
if (optional) {
nameStartOffset++;
name = name.substring(1, name.length() - 1);
int indexOfEqual = name.indexOf("=");
if (indexOfEqual != -1) {
defaultValue = name.substring(indexOfEqual + 1);
name = name.substring(0, indexOfEqual);
}
correctedTypes.addAll(paramTypes);
} else {
for (Type paramType : paramTypes) {
boolean changed = false;
String paramTypeName = paramType.getType();
if (paramTypeName.indexOf('~') > 0) {
paramTypeName = paramTypeName.replace('~', '.');
changed = true;
}
if (JsDocElementUtils.GoogleCompilerSytax.canBeThisSyntax(paramType.getType())) {
if (JsDocElementUtils.GoogleCompilerSytax.isMarkedAsOptional(paramTypeName)) {
optional = true;
changed = true;
paramTypeName = JsDocElementUtils.GoogleCompilerSytax.removeSyntax(paramTypeName);
}
}
if (changed) {
correctedTypes.add(JsDocElementUtils.createTypeUsage(paramTypeName, paramType.getOffset()));
} else {
correctedTypes.add(paramType);
}
}
}
return new NamedParameterElement(type, new Identifier(name, nameStartOffset), correctedTypes,
paramDescription, optional, defaultValue);
}
/**
* Gets name of the parameter.
* @return parameter name
*/
@Override
public Identifier getParamName() {
return paramName;
}
/**
* Gets default value of the parameter.
* @return default value
*/
@Override
public String getDefaultValue() {
return defaultValue;
}
/**
* Get information if the parameter is optional or not.
* @return flag which is {@code true} if the parameter is optional, {@code false} otherwise
*/
@Override
public boolean isOptional() {
return optional;
}
}
| 2,546 |
382 |
<filename>clouddriver-core/src/main/java/com/netflix/spinnaker/clouddriver/search/SearchProvider.java
/*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.clouddriver.search;
import com.google.common.collect.ImmutableList;
import java.util.List;
import java.util.Map;
/** A Searchable component provides a mechanism to query for a collection of items */
public interface SearchProvider {
/**
* Returns the platform the search provider services
*
* @return a String, e.g. 'aws', 'gce'
*/
String getPlatform();
/**
* Finds all matching items for the provided query
*
* @param query a query string
* @param pageNumber page index (1-based) of the result set
* @param pageSize number of items per page
* @return a list of matched items
*/
SearchResultSet search(String query, Integer pageNumber, Integer pageSize);
/**
* Finds all matching items for the provided query, filtered by the supplied filters
*
* @param query a query string
* @param pageNumber page index (1-based) of the result set
* @param pageSize number of items per page
* @param filters a map of inclusive filters
* @return a list of matched items
*/
SearchResultSet search(
String query, Integer pageNumber, Integer pageSize, Map<String, String> filters);
/**
* Finds all matching items for the provided query and type
*
* @param query a query string
* @param types the types of items to search for
* @param pageNumber page index (1-based) of the result set
* @param pageSize number of items per page
* @return a list of matched items
*/
SearchResultSet search(String query, List<String> types, Integer pageNumber, Integer pageSize);
/**
* Finds all matching items for the provided query and type, filtered by the supplied filters
*
* @param query a query string
* @param types the types of items to search for
* @param pageNumber page index (1-based) of the result set
* @param pageSize number of items per page
* @param filters a map of inclusive filters
* @return a list of matched items
*/
SearchResultSet search(
String query,
List<String> types,
Integer pageNumber,
Integer pageSize,
Map<String, String> filters);
/**
* Provides a list of filter keys to be removed prior to searching
*
* @return a list of filter keys to optionally be removed prior to searching
*/
default List<String> excludedFilters() {
return ImmutableList.of();
}
}
| 895 |
348 |
<gh_stars>100-1000
{"nom":"Prailles","circ":"2ème circonscription","dpt":"Deux-Sèvres","inscrits":506,"abs":212,"votants":294,"blancs":3,"nuls":3,"exp":288,"res":[{"nuance":"SOC","nom":"<NAME>","voix":106},{"nuance":"REM","nom":"Mme <NAME>","voix":78},{"nuance":"FI","nom":"<NAME>","voix":48},{"nuance":"FN","nom":"<NAME>","voix":21},{"nuance":"LR","nom":"Mme <NAME>","voix":20},{"nuance":"ECO","nom":"<NAME>","voix":13},{"nuance":"EXG","nom":"Mme <NAME>","voix":1},{"nuance":"DIV","nom":"Mme <NAME>","voix":1}]}
| 209 |
3,269 |
// Time: O(n)
// Space: O(h)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
double maximumAverageSubtree(TreeNode* root) {
double result = 0.0;
maximumAverageSubtreeHelper(root, &result);
return result;
}
private:
pair<double, double> maximumAverageSubtreeHelper(TreeNode *root, double *result) {
if (!root) {
return {0, 0};
}
const auto& [s1, n1] = maximumAverageSubtreeHelper(root->left, result);
const auto& [s2, n2] = maximumAverageSubtreeHelper(root->right, result);
const auto& s = s1 + s2 + root->val;
const auto& n = n1 + n2 + 1;
*result = max(*result, s / n);
return {s, n};
}
};
| 386 |
42,609 |
{
"plugins": [
"jsx",
"flow"
],
"throws": "JSX value should be either an expression or a quoted JSX text. (1:9)"
}
| 54 |
766 |
<reponame>kobylkinks/LightAutoML
"""Tools for partial installation."""
try:
from importlib.metadata import PackageNotFoundError
from importlib.metadata import distribution
except ModuleNotFoundError:
from importlib_metadata import PackageNotFoundError, distribution
import logging
logger = logging.getLogger(__name__)
def __validate_extra_deps(extra_section: str, error: bool = False) -> None:
"""Check if extra dependecies is installed.
Args:
extra_section: Name of extra dependecies
error: How to process error
"""
md = distribution("lightautoml").metadata
extra_pattern = 'extra == "{}"'.format(extra_section)
reqs_info = []
for k, v in md.items():
if k == "Requires-Dist" and extra_pattern in v:
req = v.split(";")[0].split()[0]
reqs_info.append(req)
for req_info in reqs_info:
lib_name: str = req_info.split()[0]
try:
distribution(lib_name)
except PackageNotFoundError as e:
# Print warning
logger.warning(
"'%s' extra dependecy package '%s' isn't installed. "
"Look at README.md in repo 'LightAutoML' for installation instructions.",
extra_section,
lib_name,
)
if error:
raise e
| 573 |
1,318 |
/*
* Copyright 2016 LinkedIn Corp.
*
* 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.linkedin.drelephant.exceptions;
import org.apache.log4j.Logger;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LoggingEvent {
private final Logger logger = Logger.getLogger(LoggingEvent.class);
private List<String> _rawLog;
private String _log; // To do
private long _timestamp; //To do: Get time from logs and fill this field
private enum LoggingLevel {DEBUG, INFO, WARNING, ERROR, FATAL}
private LoggingLevel _level = LoggingLevel.ERROR; // For now I have this to be eeror
private String _message;
private List<EventException> _exceptionChain;
public LoggingEvent(String exceptionChainString) {
this._rawLog = exceptionChainStringToListOfExceptions(exceptionChainString);
setExceptionChain();
setMessage();
}
/**
@return Returns the exception chain in the form of list of list of string.
A list of string corresponds to an exception in the exception chain
A string corresponds to a line in an exception
*/
public List<List<String>> getLog() {
List<List<String>> log = new ArrayList<List<String>>();
for (String exceptionString : _rawLog) {
List<String> exception = exceptionStringToListOfLines(exceptionString);
log.add(exception);
}
return log;
}
private void setExceptionChain() {
List<EventException> exceptionChain = new ArrayList<EventException>();
int index = 0;
for (String rawEventException : _rawLog) {
EventException eventException = new EventException(index, rawEventException);
exceptionChain.add(eventException);
index += 1;
}
_exceptionChain = exceptionChain;
}
/**
* Converts a exception chain string to a list of string exceptions
* @param s Exception chain in a string
* @return List of exceptions in given the exception chain
*/
private List<String> exceptionChainStringToListOfExceptions(String s) {
List<String> chain = new ArrayList<String>();
Pattern stackTraceCausedByClause = Pattern.compile(".*^(?!Caused by).+\\n(?:.*\\tat.+\\n)+");
Pattern stackTraceOtherThanCausedByClause = Pattern.compile(".*Caused by.+\\n(?:.*\\n)?(?:.*\\s+at.+\\n)*");
Matcher matcher = stackTraceCausedByClause.matcher(s);
while (matcher.find()) {
chain.add(matcher.group());
}
matcher = stackTraceOtherThanCausedByClause.matcher(s);
while (matcher.find()) {
chain.add(matcher.group());
}
if (chain.isEmpty()) {
//error logs other than stack traces for ex- logs of azkaban level failure in azkaban job
chain.add(s);
}
return chain;
}
/**
* Converts a exception string to a list of string corresponding to lines in the exception
* @param s Exception in a single string
* @return List of individual lines in the string
*/
private List<String> exceptionStringToListOfLines(String s) {
List<String> exception = new ArrayList<String>();
Matcher matcher = Pattern.compile(".*\\n").matcher(s);
while (matcher.find()) {
exception.add(matcher.group());
}
return exception;
}
/** Sets message for the logging event
For now, It is set to be equal to the message field of first EventException in _exceptionChain
This can be changed depending on message of which EventException is most relevant for the user to see
*/
private void setMessage() {
if (!_exceptionChain.isEmpty()) {
this._message = _exceptionChain.get(0).getMessage();
}
}
}
| 1,302 |
892 |
{
"schema_version": "1.2.0",
"id": "GHSA-6cc4-g986-cx7v",
"modified": "2022-05-01T23:50:02Z",
"published": "2022-05-01T23:50:02Z",
"aliases": [
"CVE-2008-2439"
],
"details": "Directory traversal vulnerability in the UpdateAgent function in TmListen.exe in the OfficeScanNT Listener service in the client in Trend Micro OfficeScan 7.3 Patch 4 build 1367 and other builds before 1372, OfficeScan 8.0 SP1 before build 1222, OfficeScan 8.0 SP1 Patch 1 before build 3087, and Worry-Free Business Security 5.0 before build 1220 allows remote attackers to read arbitrary files via directory traversal sequences in an HTTP request. NOTE: some of these details are obtained from third party information.",
"severity": [
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2008-2439"
},
{
"type": "WEB",
"url": "https://exchange.xforce.ibmcloud.com/vulnerabilities/45597"
},
{
"type": "WEB",
"url": "http://secunia.com/advisories/31343"
},
{
"type": "WEB",
"url": "http://secunia.com/advisories/32097"
},
{
"type": "WEB",
"url": "http://secunia.com/secunia_research/2008-39/"
},
{
"type": "WEB",
"url": "http://www.securityfocus.com/archive/1/496970/100/0/threaded"
},
{
"type": "WEB",
"url": "http://www.securityfocus.com/bid/31531"
},
{
"type": "WEB",
"url": "http://www.securitytracker.com/id?1020975"
},
{
"type": "WEB",
"url": "http://www.trendmicro.com/ftp/documentation/readme/OSCE8.0_SP1_Patch1_CriticalPatch_3087_Readme.txt"
},
{
"type": "WEB",
"url": "http://www.trendmicro.com/ftp/documentation/readme/OSCE_7.3_Win_EN_CriticalPatch_B1372_Readme.txt"
},
{
"type": "WEB",
"url": "http://www.trendmicro.com/ftp/documentation/readme/OSCE_8.0_SP1_Win_EN_CriticalPatch_B2439_Readme.txt"
},
{
"type": "WEB",
"url": "http://www.trendmicro.com/ftp/documentation/readme/Readme_WFBS5.0_EN_CriticalPatch1414.txt"
},
{
"type": "WEB",
"url": "http://www.vupen.com/english/advisories/2008/2711"
},
{
"type": "WEB",
"url": "http://www.vupen.com/english/advisories/2008/2712"
}
],
"database_specific": {
"cwe_ids": [
"CWE-22"
],
"severity": "MODERATE",
"github_reviewed": false
}
}
| 1,128 |
2,649 |
<filename>pytorch/pytorchcv/models/isqrtcovresnet.py<gh_stars>1000+
"""
iSQRT-COV-ResNet for ImageNet-1K, implemented in PyTorch.
Original paper: 'Towards Faster Training of Global Covariance Pooling Networks by Iterative Matrix Square Root
Normalization,' https://arxiv.org/abs/1712.01034.
"""
__all__ = ['iSQRTCOVResNet', 'isqrtcovresnet18', 'isqrtcovresnet34', 'isqrtcovresnet50', 'isqrtcovresnet50b',
'isqrtcovresnet101', 'isqrtcovresnet101b']
import os
import torch
import torch.nn as nn
import torch.nn.init as init
from .common import conv1x1_block
from .resnet import ResUnit, ResInitBlock
class CovPool(torch.autograd.Function):
"""
Covariance pooling function.
"""
@staticmethod
def forward(ctx, x):
batch, channels, height, width = x.size()
n = height * width
xn = x.reshape(batch, channels, n)
identity_bar = ((1.0 / n) * torch.eye(n, dtype=xn.dtype, device=xn.device)).unsqueeze(dim=0).repeat(batch, 1, 1)
ones_bar = torch.full((batch, n, n), fill_value=(-1.0 / n / n), dtype=xn.dtype, device=xn.device)
i_bar = identity_bar + ones_bar
sigma = xn.bmm(i_bar).bmm(xn.transpose(1, 2))
ctx.save_for_backward(x, i_bar)
return sigma
@staticmethod
def backward(ctx, grad_sigma):
x, i_bar = ctx.saved_tensors
batch, channels, height, width = x.size()
n = height * width
xn = x.reshape(batch, channels, n)
grad_x = grad_sigma + grad_sigma.transpose(1, 2)
grad_x = grad_x.bmm(xn).bmm(i_bar)
grad_x = grad_x.reshape(batch, channels, height, width)
return grad_x
class NewtonSchulzSqrt(torch.autograd.Function):
"""
Newton-Schulz iterative matrix square root function.
Parameters:
----------
x : Tensor
Input tensor (batch * cols * rows).
n : int
Number of iterations (n > 1).
"""
@staticmethod
def forward(ctx, x, n):
assert (n > 1)
batch, cols, rows = x.size()
assert (cols == rows)
m = cols
identity = torch.eye(m, dtype=x.dtype, device=x.device).unsqueeze(dim=0).repeat(batch, 1, 1)
x_trace = (x * identity).sum(dim=(1, 2), keepdim=True)
a = x / x_trace
i3 = 3.0 * identity
yi = torch.zeros(batch, n - 1, m, m, dtype=x.dtype, device=x.device)
zi = torch.zeros(batch, n - 1, m, m, dtype=x.dtype, device=x.device)
b2 = 0.5 * (i3 - a)
yi[:, 0, :, :] = a.bmm(b2)
zi[:, 0, :, :] = b2
for i in range(1, n - 1):
b2 = 0.5 * (i3 - zi[:, i - 1, :, :].bmm(yi[:, i - 1, :, :]))
yi[:, i, :, :] = yi[:, i - 1, :, :].bmm(b2)
zi[:, i, :, :] = b2.bmm(zi[:, i - 1, :, :])
b2 = 0.5 * (i3 - zi[:, n - 2, :, :].bmm(yi[:, n - 2, :, :]))
yn = yi[:, n - 2, :, :].bmm(b2)
x_trace_sqrt = torch.sqrt(x_trace)
c = yn * x_trace_sqrt
ctx.save_for_backward(x, x_trace, a, yi, zi, yn, x_trace_sqrt)
ctx.n = n
return c
@staticmethod
def backward(ctx, grad_c):
x, x_trace, a, yi, zi, yn, x_trace_sqrt = ctx.saved_tensors
n = ctx.n
batch, m, _ = x.size()
identity0 = torch.eye(m, dtype=x.dtype, device=x.device)
identity = identity0.unsqueeze(dim=0).repeat(batch, 1, 1)
i3 = 3.0 * identity
grad_yn = grad_c * x_trace_sqrt
b = i3 - yi[:, n - 2, :, :].bmm(zi[:, n - 2, :, :])
grad_yi = 0.5 * (grad_yn.bmm(b) - zi[:, n - 2, :, :].bmm(yi[:, n - 2, :, :]).bmm(grad_yn))
grad_zi = -0.5 * yi[:, n - 2, :, :].bmm(grad_yn).bmm(yi[:, n - 2, :, :])
for i in range(n - 3, -1, -1):
b = i3 - yi[:, i, :, :].bmm(zi[:, i, :, :])
ziyi = zi[:, i, :, :].bmm(yi[:, i, :, :])
grad_yi_m1 = 0.5 * (grad_yi.bmm(b) - zi[:, i, :, :].bmm(grad_zi).bmm(zi[:, i, :, :]) - ziyi.bmm(grad_yi))
grad_zi_m1 = 0.5 * (b.bmm(grad_zi) - yi[:, i, :, :].bmm(grad_yi).bmm(yi[:, i, :, :]) - grad_zi.bmm(ziyi))
grad_yi = grad_yi_m1
grad_zi = grad_zi_m1
grad_a = 0.5 * (grad_yi.bmm(i3 - a) - grad_zi - a.bmm(grad_yi))
x_trace_sqr = x_trace * x_trace
grad_atx_trace = (grad_a.transpose(1, 2).bmm(x) * identity).sum(dim=(1, 2), keepdim=True)
grad_cty_trace = (grad_c.transpose(1, 2).bmm(yn) * identity).sum(dim=(1, 2), keepdim=True)
grad_x_extra = (0.5 * grad_cty_trace / x_trace_sqrt - grad_atx_trace / x_trace_sqr).repeat(1, m, m) * identity
grad_x = grad_a / x_trace + grad_x_extra
return grad_x, None
class Triuvec(torch.autograd.Function):
"""
Extract upper triangular part of matrix into vector form.
"""
@staticmethod
def forward(ctx, x):
batch, cols, rows = x.size()
assert (cols == rows)
n = cols
triuvec_inds = torch.ones(n, n).triu().view(n * n).nonzero()
# assert (len(triuvec_inds) == n * (n + 1) // 2)
x_vec = x.reshape(batch, -1)
y = x_vec[:, triuvec_inds]
ctx.save_for_backward(x, triuvec_inds)
return y
@staticmethod
def backward(ctx, grad_y):
x, triuvec_inds = ctx.saved_tensors
batch, n, _ = x.size()
grad_x = torch.zeros_like(x).view(batch, -1)
grad_x[:, triuvec_inds] = grad_y
grad_x = grad_x.view(batch, n, n)
return grad_x
class iSQRTCOVPool(nn.Module):
"""
iSQRT-COV pooling layer.
Parameters:
----------
num_iter : int, default 5
Number of iterations (num_iter > 1).
"""
def __init__(self,
num_iter=5):
super(iSQRTCOVPool, self).__init__()
self.num_iter = num_iter
self.cov_pool = CovPool.apply
self.sqrt = NewtonSchulzSqrt.apply
self.triuvec = Triuvec.apply
def forward(self, x):
x = self.cov_pool(x)
x = self.sqrt(x, self.num_iter)
x = self.triuvec(x)
return x
class iSQRTCOVResNet(nn.Module):
"""
iSQRT-COV-ResNet model from 'Towards Faster Training of Global Covariance Pooling Networks by Iterative Matrix
Square Root Normalization,' https://arxiv.org/abs/1712.01034.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
final_block_channels : int
Number of output channels for the final unit.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
conv1_stride : bool
Whether to use stride in the first or the second convolution layer in units.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
final_block_channels,
bottleneck,
conv1_stride,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(iSQRTCOVResNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", ResInitBlock(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
stride = 2 if (j == 0) and (i not in [0, len(channels) - 1]) else 1
stage.add_module("unit{}".format(j + 1), ResUnit(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
bottleneck=bottleneck,
conv1_stride=conv1_stride))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module("final_block", conv1x1_block(
in_channels=in_channels,
out_channels=final_block_channels))
in_channels = final_block_channels
self.features.add_module("final_pool", iSQRTCOVPool())
in_features = in_channels * (in_channels + 1) // 2
self.output = nn.Linear(
in_features=in_features,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_isqrtcovresnet(blocks,
conv1_stride=True,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create iSQRT-COV-ResNet model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
conv1_stride : bool, default True
Whether to use stride in the first or the second convolution layer in units.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
if blocks == 18:
layers = [2, 2, 2, 2]
elif blocks == 34:
layers = [3, 4, 6, 3]
elif blocks == 50:
layers = [3, 4, 6, 3]
elif blocks == 101:
layers = [3, 4, 23, 3]
elif blocks == 152:
layers = [3, 8, 36, 3]
elif blocks == 200:
layers = [3, 24, 36, 3]
else:
raise ValueError("Unsupported iSQRT-COV-ResNet with number of blocks: {}".format(blocks))
init_block_channels = 64
final_block_channels = 256
if blocks < 50:
channels_per_layers = [64, 128, 256, 512]
bottleneck = False
else:
channels_per_layers = [256, 512, 1024, 2048]
bottleneck = True
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
net = iSQRTCOVResNet(
channels=channels,
init_block_channels=init_block_channels,
final_block_channels=final_block_channels,
bottleneck=bottleneck,
conv1_stride=conv1_stride,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def isqrtcovresnet18(**kwargs):
"""
iSQRT-COV-ResNet-18 model from 'Towards Faster Training of Global Covariance Pooling Networks by Iterative Matrix
Square Root Normalization,' https://arxiv.org/abs/1712.01034.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_isqrtcovresnet(blocks=18, model_name="isqrtcovresnet18", **kwargs)
def isqrtcovresnet34(**kwargs):
"""
iSQRT-COV-ResNet-34 model from 'Towards Faster Training of Global Covariance Pooling Networks by Iterative Matrix
Square Root Normalization,' https://arxiv.org/abs/1712.01034.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_isqrtcovresnet(blocks=34, model_name="isqrtcovresnet34", **kwargs)
def isqrtcovresnet50(**kwargs):
"""
iSQRT-COV-ResNet-50 model from 'Towards Faster Training of Global Covariance Pooling Networks by Iterative Matrix
Square Root Normalization,' https://arxiv.org/abs/1712.01034.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_isqrtcovresnet(blocks=50, model_name="isqrtcovresnet50", **kwargs)
def isqrtcovresnet50b(**kwargs):
"""
iSQRT-COV-ResNet-50 model with stride at the second convolution in bottleneck block from 'Towards Faster Training
of Global Covariance Pooling Networks by Iterative Matrix Square Root Normalization,'
https://arxiv.org/abs/1712.01034.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_isqrtcovresnet(blocks=50, conv1_stride=False, model_name="isqrtcovresnet50b", **kwargs)
def isqrtcovresnet101(**kwargs):
"""
iSQRT-COV-ResNet-101 model from 'Towards Faster Training of Global Covariance Pooling Networks by Iterative Matrix
Square Root Normalization,' https://arxiv.org/abs/1712.01034.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_isqrtcovresnet(blocks=101, model_name="isqrtcovresnet101", **kwargs)
def isqrtcovresnet101b(**kwargs):
"""
iSQRT-COV-ResNet-101 model with stride at the second convolution in bottleneck block from 'Towards Faster Training
of Global Covariance Pooling Networks by Iterative Matrix Square Root Normalization,'
https://arxiv.org/abs/1712.01034.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_isqrtcovresnet(blocks=101, conv1_stride=False, model_name="isqrtcovresnet101b", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
isqrtcovresnet18,
isqrtcovresnet34,
isqrtcovresnet50,
isqrtcovresnet50b,
isqrtcovresnet101,
isqrtcovresnet101b,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != isqrtcovresnet18 or weight_count == 44205096)
assert (model != isqrtcovresnet34 or weight_count == 54313256)
assert (model != isqrtcovresnet50 or weight_count == 56929832)
assert (model != isqrtcovresnet50b or weight_count == 56929832)
assert (model != isqrtcovresnet101 or weight_count == 75921960)
assert (model != isqrtcovresnet101b or weight_count == 75921960)
x = torch.randn(14, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (14, 1000))
if __name__ == "__main__":
_test()
| 7,416 |
337 |
package cn.ycbjie.ycaudioplayer.model.bean;
import android.graphics.Bitmap;
import java.io.Serializable;
/**
* <pre>
* @author yangchong
* blog : www.pedaily.cn
* time : 2018/03/22
* desc : 视频信息
* revise:
* </pre>
*/
public class VideoBean implements Serializable {
// 视频类型:本地/网络
private Type type;
// [本地视频]视频id
private long id;
// 视频标题
private String title;
// [本地视频]专辑ID
private long albumId;
// [在线视频]专辑封面路径
private String coverPath;
// 持续时间
private long duration;
// 视频路径
private String path;
// 文件名
private String fileName;
// 文件大小
private long fileSize;
// 分辨率
private String resolution;
// 修改时间
private long date;
// 封面缩略图
private Bitmap videoThumbnail;
public enum Type {
/**
* 本地的
*/
LOCAL,
/**
* 在线的
*/
ONLINE
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public long getAlbumId() {
return albumId;
}
public void setAlbumId(long albumId) {
this.albumId = albumId;
}
public String getCoverPath() {
return coverPath;
}
public void setCoverPath(String coverPath) {
this.coverPath = coverPath;
}
public long getDuration() {
return duration;
}
public void setDuration(long duration) {
this.duration = duration;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public long getFileSize() {
return fileSize;
}
public void setFileSize(long fileSize) {
this.fileSize = fileSize;
}
public String getResolution() {
return resolution;
}
public void setResolution(String resolution) {
this.resolution = resolution;
}
public long getDate() {
return date;
}
public void setDate(long date) {
this.date = date;
}
public Bitmap getVideoThumbnail() {
return videoThumbnail;
}
public void setVideoThumbnail(Bitmap videoThumbnail) {
this.videoThumbnail = videoThumbnail;
}
/**
* 对比本地视频是否相同
*/
@Override
public boolean equals(Object o) {
return o instanceof VideoBean && this.getId() == ((VideoBean) o).getId();
}
}
| 1,399 |
7,546 |
package com.davemorrissey.labs.subscaleview.test;
public class Page {
private final int text;
private final int subtitle;
public Page(int subtitle, int text) {
this.subtitle = subtitle;
this.text = text;
}
public int getText() {
return text;
}
public int getSubtitle() {
return subtitle;
}
}
| 146 |
8,629 |
<reponame>anishbhanwala/ClickHouse
#include <DataTypes/Serializations/ISerialization.h>
#include <Compression/CompressionFactory.h>
#include <Columns/IColumn.h>
#include <IO/WriteHelpers.h>
#include <IO/Operators.h>
#include <IO/ReadBufferFromString.h>
#include <Common/escapeForFileName.h>
#include <DataTypes/NestedUtils.h>
#include <base/EnumReflection.h>
namespace DB
{
namespace ErrorCodes
{
extern const int MULTIPLE_STREAMS_REQUIRED;
extern const int UNEXPECTED_DATA_AFTER_PARSED_VALUE;
extern const int LOGICAL_ERROR;
}
ISerialization::Kind ISerialization::getKind(const IColumn & column)
{
if (column.isSparse())
return Kind::SPARSE;
return Kind::DEFAULT;
}
String ISerialization::kindToString(Kind kind)
{
switch (kind)
{
case Kind::DEFAULT:
return "Default";
case Kind::SPARSE:
return "Sparse";
}
__builtin_unreachable();
}
ISerialization::Kind ISerialization::stringToKind(const String & str)
{
if (str == "Default")
return Kind::DEFAULT;
else if (str == "Sparse")
return Kind::SPARSE;
else
throw Exception(ErrorCodes::LOGICAL_ERROR, "Unknown serialization kind '{}'", str);
}
String ISerialization::Substream::toString() const
{
if (type == TupleElement)
return fmt::format("TupleElement({}, escape_tuple_delimiter = {})",
tuple_element_name, escape_tuple_delimiter ? "true" : "false");
return String(magic_enum::enum_name(type));
}
String ISerialization::SubstreamPath::toString() const
{
WriteBufferFromOwnString wb;
wb << "{";
for (size_t i = 0; i < size(); ++i)
{
if (i != 0)
wb << ", ";
wb << at(i).toString();
}
wb << "}";
return wb.str();
}
void ISerialization::enumerateStreams(
SubstreamPath & path,
const StreamCallback & callback,
const SubstreamData & data) const
{
path.push_back(Substream::Regular);
path.back().data = data;
callback(path);
path.pop_back();
}
void ISerialization::enumerateStreams(const StreamCallback & callback, SubstreamPath & path) const
{
enumerateStreams(path, callback, {getPtr(), nullptr, nullptr, nullptr});
}
void ISerialization::enumerateStreams(SubstreamPath & path, const StreamCallback & callback, const DataTypePtr & type) const
{
enumerateStreams(path, callback, {getPtr(), type, nullptr, nullptr});
}
void ISerialization::serializeBinaryBulk(const IColumn & column, WriteBuffer &, size_t, size_t) const
{
throw Exception(ErrorCodes::MULTIPLE_STREAMS_REQUIRED, "Column {} must be serialized with multiple streams", column.getName());
}
void ISerialization::deserializeBinaryBulk(IColumn & column, ReadBuffer &, size_t, double) const
{
throw Exception(ErrorCodes::MULTIPLE_STREAMS_REQUIRED, "Column {} must be deserialized with multiple streams", column.getName());
}
void ISerialization::serializeBinaryBulkWithMultipleStreams(
const IColumn & column,
size_t offset,
size_t limit,
SerializeBinaryBulkSettings & settings,
SerializeBinaryBulkStatePtr & /* state */) const
{
if (WriteBuffer * stream = settings.getter(settings.path))
serializeBinaryBulk(column, *stream, offset, limit);
}
void ISerialization::deserializeBinaryBulkWithMultipleStreams(
ColumnPtr & column,
size_t limit,
DeserializeBinaryBulkSettings & settings,
DeserializeBinaryBulkStatePtr & /* state */,
SubstreamsCache * cache) const
{
auto cached_column = getFromSubstreamsCache(cache, settings.path);
if (cached_column)
{
column = cached_column;
}
else if (ReadBuffer * stream = settings.getter(settings.path))
{
auto mutable_column = column->assumeMutable();
deserializeBinaryBulk(*mutable_column, *stream, limit, settings.avg_value_size_hint);
column = std::move(mutable_column);
addToSubstreamsCache(cache, settings.path, column);
}
}
namespace
{
using SubstreamIterator = ISerialization::SubstreamPath::const_iterator;
String getNameForSubstreamPath(
String stream_name,
SubstreamIterator begin,
SubstreamIterator end,
bool escape_tuple_delimiter)
{
using Substream = ISerialization::Substream;
size_t array_level = 0;
for (auto it = begin; it != end; ++it)
{
if (it->type == Substream::NullMap)
stream_name += ".null";
else if (it->type == Substream::ArraySizes)
stream_name += ".size" + toString(array_level);
else if (it->type == Substream::ArrayElements)
++array_level;
else if (it->type == Substream::DictionaryKeys)
stream_name += ".dict";
else if (it->type == Substream::SparseOffsets)
stream_name += ".sparse.idx";
else if (it->type == Substream::TupleElement)
{
/// For compatibility reasons, we use %2E (escaped dot) instead of dot.
/// Because nested data may be represented not by Array of Tuple,
/// but by separate Array columns with names in a form of a.b,
/// and name is encoded as a whole.
if (escape_tuple_delimiter && it->escape_tuple_delimiter)
stream_name += escapeForFileName("." + it->tuple_element_name);
else
stream_name += "." + it->tuple_element_name;
}
}
return stream_name;
}
}
String ISerialization::getFileNameForStream(const NameAndTypePair & column, const SubstreamPath & path)
{
return getFileNameForStream(column.getNameInStorage(), path);
}
static size_t isOffsetsOfNested(const ISerialization::SubstreamPath & path)
{
if (path.empty())
return false;
for (const auto & elem : path)
if (elem.type == ISerialization::Substream::ArrayElements)
return false;
return path.back().type == ISerialization::Substream::ArraySizes;
}
String ISerialization::getFileNameForStream(const String & name_in_storage, const SubstreamPath & path)
{
String stream_name;
auto nested_storage_name = Nested::extractTableName(name_in_storage);
if (name_in_storage != nested_storage_name && isOffsetsOfNested(path))
stream_name = escapeForFileName(nested_storage_name);
else
stream_name = escapeForFileName(name_in_storage);
return getNameForSubstreamPath(std::move(stream_name), path.begin(), path.end(), true);
}
String ISerialization::getSubcolumnNameForStream(const SubstreamPath & path)
{
return getSubcolumnNameForStream(path, path.size());
}
String ISerialization::getSubcolumnNameForStream(const SubstreamPath & path, size_t prefix_len)
{
auto subcolumn_name = getNameForSubstreamPath("", path.begin(), path.begin() + prefix_len, false);
if (!subcolumn_name.empty())
subcolumn_name = subcolumn_name.substr(1); // It starts with a dot.
return subcolumn_name;
}
void ISerialization::addToSubstreamsCache(SubstreamsCache * cache, const SubstreamPath & path, ColumnPtr column)
{
if (cache && !path.empty())
cache->emplace(getSubcolumnNameForStream(path), column);
}
ColumnPtr ISerialization::getFromSubstreamsCache(SubstreamsCache * cache, const SubstreamPath & path)
{
if (!cache || path.empty())
return nullptr;
auto it = cache->find(getSubcolumnNameForStream(path));
if (it == cache->end())
return nullptr;
return it->second;
}
bool ISerialization::isSpecialCompressionAllowed(const SubstreamPath & path)
{
for (const auto & elem : path)
{
if (elem.type == Substream::NullMap
|| elem.type == Substream::ArraySizes
|| elem.type == Substream::DictionaryIndexes
|| elem.type == Substream::SparseOffsets)
return false;
}
return true;
}
void ISerialization::deserializeTextRaw(IColumn & column, ReadBuffer & istr, const FormatSettings & settings) const
{
String field;
/// Read until \t or \n.
readString(field, istr);
ReadBufferFromString buf(field);
deserializeWholeText(column, buf, settings);
}
void ISerialization::serializeTextRaw(const IColumn & column, size_t row_num, WriteBuffer & ostr, const FormatSettings & settings) const
{
serializeText(column, row_num, ostr, settings);
}
size_t ISerialization::getArrayLevel(const SubstreamPath & path)
{
size_t level = 0;
for (const auto & elem : path)
level += elem.type == Substream::ArrayElements;
return level;
}
bool ISerialization::hasSubcolumnForPath(const SubstreamPath & path, size_t prefix_len)
{
if (prefix_len == 0 || prefix_len > path.size())
return false;
size_t last_elem = prefix_len - 1;
return path[last_elem].type == Substream::NullMap
|| path[last_elem].type == Substream::TupleElement
|| path[last_elem].type == Substream::ArraySizes;
}
ISerialization::SubstreamData ISerialization::createFromPath(const SubstreamPath & path, size_t prefix_len)
{
assert(prefix_len < path.size());
SubstreamData res = path[prefix_len].data;
for (ssize_t i = static_cast<ssize_t>(prefix_len) - 1; i >= 0; --i)
{
const auto & creator = path[i].creator;
if (creator)
{
res.type = res.type ? creator->create(res.type) : res.type;
res.serialization = res.serialization ? creator->create(res.serialization) : res.serialization;
res.column = res.column ? creator->create(res.column) : res.column;
}
}
return res;
}
void ISerialization::throwUnexpectedDataAfterParsedValue(IColumn & column, ReadBuffer & istr, const FormatSettings & settings, const String & type_name) const
{
WriteBufferFromOwnString ostr;
serializeText(column, column.size() - 1, ostr, settings);
throw Exception(
ErrorCodes::UNEXPECTED_DATA_AFTER_PARSED_VALUE,
"Unexpected data '{}' after parsed {} value '{}'",
std::string(istr.position(), std::min(size_t(10), istr.available())),
type_name,
ostr.str());
}
}
| 3,859 |
432 |
package us.parr.bookish.entity;
import us.parr.bookish.parse.BookishParser;
public class SideNoteDef extends EntityDef {
public String note;
public SideNoteDef(int index, BookishParser.AttrsContext attrsCtx, String note) {
super(index, attrsCtx.attributes);
this.note = note;
}
public boolean isSideItem() { return true; }
}
| 114 |
2,338 |
<reponame>mkinsner/llvm
//===--- Allocator.cpp - Simple memory allocation abstraction -------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// This file implements the BumpPtrAllocator interface.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/Allocator.h"
#include "llvm/Support/raw_ostream.h"
namespace llvm {
namespace detail {
void printBumpPtrAllocatorStats(unsigned NumSlabs, size_t BytesAllocated,
size_t TotalMemory) {
errs() << "\nNumber of memory regions: " << NumSlabs << '\n'
<< "Bytes used: " << BytesAllocated << '\n'
<< "Bytes allocated: " << TotalMemory << '\n'
<< "Bytes wasted: " << (TotalMemory - BytesAllocated)
<< " (includes alignment, etc)\n";
}
} // namespace detail
void PrintRecyclerStats(size_t Size,
size_t Align,
size_t FreeListSize) {
errs() << "Recycler element size: " << Size << '\n'
<< "Recycler element alignment: " << Align << '\n'
<< "Number of elements free for recycling: " << FreeListSize << '\n';
}
} // namespace llvm
| 521 |
7,482 |
<reponame>cazure/rt-thread<gh_stars>1000+
/*
* Copyright (c) 2006-2021, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2019-02-17 jinsheng first version
*/
#ifndef __LCD_PORT_H__
#define __LCD_PORT_H__
/* 4.3 inch screen, 480 * 272 */
#define LCD_WIDTH 480
#define LCD_HEIGHT 272
#define LCD_BITS_PER_PIXEL 16
#define LCD_BUF_SIZE (LCD_WIDTH * LCD_HEIGHT * LCD_BITS_PER_PIXEL / 8)
#define LCD_PIXEL_FORMAT RTGRAPHIC_PIXEL_FORMAT_RGB565
#define LCD_HSYNC_WIDTH 41
#define LCD_VSYNC_HEIGHT 10
#define LCD_HBP 13
#define LCD_VBP 2
#define LCD_HFP 32
#define LCD_VFP 2
#define LCD_BACKLIGHT_USING_GPIO
#define LCD_BL_GPIO_NUM GET_PIN(K, 3)
#define LCD_DISP_GPIO_NUM GET_PIN(I, 12)
#endif /* __LCD_PORT_H__ */
| 451 |
363 |
<reponame>elizabethking2/UnrealGDK<filename>SpatialGDK/Source/SpatialGDK/Private/Schema/ClientEndpoint.cpp
// Copyright (c) Improbable Worlds Ltd, All Rights Reserved
#include "Schema/ClientEndpoint.h"
namespace SpatialGDK
{
ClientEndpoint::ClientEndpoint(const Worker_ComponentData& Data)
: ReliableRPCBuffer(ERPCType::ServerReliable)
, UnreliableRPCBuffer(ERPCType::ServerUnreliable)
{
ReadFromSchema(Schema_GetComponentDataFields(Data.schema_type));
}
void ClientEndpoint::ApplyComponentUpdate(const Worker_ComponentUpdate& Update)
{
ReadFromSchema(Schema_GetComponentUpdateFields(Update.schema_type));
}
void ClientEndpoint::ReadFromSchema(Schema_Object* SchemaObject)
{
RPCRingBufferUtils::ReadBufferFromSchema(SchemaObject, ReliableRPCBuffer);
RPCRingBufferUtils::ReadBufferFromSchema(SchemaObject, UnreliableRPCBuffer);
RPCRingBufferUtils::ReadAckFromSchema(SchemaObject, ERPCType::ClientReliable, ReliableRPCAck);
RPCRingBufferUtils::ReadAckFromSchema(SchemaObject, ERPCType::ClientUnreliable, UnreliableRPCAck);
}
} // namespace SpatialGDK
| 366 |
473 |
/*
* Copyright (C) <NAME> <<EMAIL>>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "libcgc.h"
#include "cgc_libc.h"
#include "cgc_vm.h"
#include "cgc_stack.h"
#include "cgc_service.h"
int main(int cgc_argc, char *cgc_argv[]) {
Stack programStack ={-1, 0, 0, NULL};
while(1) {
char buf[1024] ={0};
int bytes_read =0;
int arg_pos =0;
bytes_read = cgc_recvline(STDIN, buf, sizeof(buf)-1);
if (bytes_read <= 0)
cgc__terminate(1);
if(programStack.numElements <= 0)
cgc_initStack(&programStack, MAX_PROGRAM_STACK_SIZE, sizeof(Program *));
if((arg_pos = cgc_parseCmd(NEW_PROGRAM_CMD_STR, buf)) > 0) {
Program* program = NULL;
cgc_initProgram(&program, STDIN);
if(program != NULL)
cgc_pushElement(&programStack, &program);
} else if((arg_pos = cgc_parseCmd(EXECUTE_PROGRAM_CMD_STR, buf)) > 0) {
int program_num;
int ret;
program_num = cgc_strn2int(buf+arg_pos, 10);
#ifdef PATCHED
if(program_num > programStack.top || program_num < 0) {
#else
if(program_num > programStack.top) {
#endif
ret = cgc_transmit_all(STDOUT, INVALID_PROGRAM_STR, sizeof(TOO_MANY_LINES_STR));
if (ret != 0)
cgc__terminate(13);
} else {
Program **program_ptr;
program_ptr = programStack.elements+(program_num*sizeof(Program *));
cgc_executeProgram(*program_ptr);
}
}
}
}
| 870 |
826 |
<gh_stars>100-1000
#include "blur.h"
#include "../utils/utility.h"
namespace weserv {
namespace api {
namespace processors {
VImage Blur::process(const VImage &image) const {
auto sigma = query_->get<float>("blur", 0.0F);
// Should we process the image?
if (sigma == 0.0F) {
return image;
}
// Sigma needs to be in the range of 0.3 - 1000
if (sigma < 0.3 || sigma > 1000) {
// Defaulting to fast, mild blur
sigma = -1.0F;
}
if (sigma == -1.0F) {
// Fast, mild blur - averages neighbouring pixels
// clang-format off
VImage blur = VImage::new_matrixv(3, 3,
1.0, 1.0, 1.0,
1.0, 1.0, 1.0,
1.0, 1.0, 1.0);
// clang-format on
blur.set("scale", 9.0);
return image.conv(blur);
}
// Slower, accurate Gaussian blur
return (image.get_typeof(VIPS_META_SEQUENTIAL) != 0
? utils::line_cache(image, 10)
: image)
.gaussblur(sigma);
}
} // namespace processors
} // namespace api
} // namespace weserv
| 619 |
2,999 |
<reponame>junghee/LIEF
/* Copyright 2017 - 2021 <NAME>
* Copyright 2017 - 2021 Quarkslab
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef LIEF_PE_COMCTL32_DLL_LOOKUP_H_
#define LIEF_PE_COMCTL32_DLL_LOOKUP_H_
namespace LIEF {
namespace PE {
const char* comctl32_dll_lookup(uint32_t i) {
switch(i) {
case 0x0191: return "AddMRUStringW";
case 0x00cf: return "AttachScrollBars";
case 0x00d2: return "CCEnableScrollBar";
case 0x00d1: return "CCGetScrollInfo";
case 0x00d0: return "CCSetScrollInfo";
case 0x0190: return "CreateMRUListW";
case 0x0008: return "CreateMappedBitmap";
case 0x000c: return "CreatePropertySheetPage";
case 0x0013: return "CreatePropertySheetPageA";
case 0x0014: return "CreatePropertySheetPageW";
case 0x0015: return "CreateStatusWindow";
case 0x0006: return "CreateStatusWindowA";
case 0x0016: return "CreateStatusWindowW";
case 0x0007: return "CreateToolbar";
case 0x0017: return "CreateToolbarEx";
case 0x0010: return "CreateUpDownControl";
case 0x014b: return "DPA_Clone";
case 0x0148: return "DPA_Create";
case 0x0154: return "DPA_CreateEx";
case 0x0151: return "DPA_DeleteAllPtrs";
case 0x0150: return "DPA_DeletePtr";
case 0x0149: return "DPA_Destroy";
case 0x0182: return "DPA_DestroyCallback";
case 0x0181: return "DPA_EnumCallback";
case 0x014c: return "DPA_GetPtr";
case 0x014d: return "DPA_GetPtrIndex";
case 0x015b: return "DPA_GetSize";
case 0x014a: return "DPA_Grow";
case 0x014e: return "DPA_InsertPtr";
case 0x0009: return "DPA_LoadStream";
case 0x000b: return "DPA_Merge";
case 0x000a: return "DPA_SaveStream";
case 0x0153: return "DPA_Search";
case 0x014f: return "DPA_SetPtr";
case 0x0152: return "DPA_Sort";
case 0x0157: return "DSA_Clone";
case 0x0140: return "DSA_Create";
case 0x0147: return "DSA_DeleteAllItems";
case 0x0146: return "DSA_DeleteItem";
case 0x0141: return "DSA_Destroy";
case 0x0184: return "DSA_DestroyCallback";
case 0x0183: return "DSA_EnumCallback";
case 0x0142: return "DSA_GetItem";
case 0x0143: return "DSA_GetItemPtr";
case 0x015c: return "DSA_GetSize";
case 0x0144: return "DSA_InsertItem";
case 0x0145: return "DSA_SetItem";
case 0x015a: return "DSA_Sort";
case 0x019d: return "DefSubclassProc";
case 0x0018: return "DestroyPropertySheetPage";
case 0x00ce: return "DetachScrollBars";
case 0x0019: return "DllGetVersion";
case 0x001a: return "DllInstall";
case 0x000f: return "DrawInsert";
case 0x00c9: return "DrawScrollBar";
case 0x001b: return "DrawShadowText";
case 0x00c8: return "DrawSizeBox";
case 0x001c: return "DrawStatusText";
case 0x0005: return "DrawStatusTextA";
case 0x001d: return "DrawStatusTextW";
case 0x0193: return "EnumMRUListW";
case 0x001e: return "FlatSB_EnableScrollBar";
case 0x001f: return "FlatSB_GetScrollInfo";
case 0x0020: return "FlatSB_GetScrollPos";
case 0x0021: return "FlatSB_GetScrollProp";
case 0x0022: return "FlatSB_GetScrollPropPtr";
case 0x0023: return "FlatSB_GetScrollRange";
case 0x0024: return "FlatSB_SetScrollInfo";
case 0x0025: return "FlatSB_SetScrollPos";
case 0x0026: return "FlatSB_SetScrollProp";
case 0x0027: return "FlatSB_SetScrollRange";
case 0x0028: return "FlatSB_ShowScrollBar";
case 0x0098: return "FreeMRUList";
case 0x0004: return "GetEffectiveClientRect";
case 0x0029: return "GetMUILanguage";
case 0x019b: return "GetWindowSubclass";
case 0x002a: return "HIMAGELIST_QueryInterface";
case 0x00cd: return "HandleScrollCmd";
case 0x002b: return "ImageList_Add";
case 0x002c: return "ImageList_AddIcon";
case 0x002d: return "ImageList_AddMasked";
case 0x002e: return "ImageList_BeginDrag";
case 0x002f: return "ImageList_CoCreateInstance";
case 0x0030: return "ImageList_Copy";
case 0x0031: return "ImageList_Create";
case 0x0032: return "ImageList_Destroy";
case 0x0033: return "ImageList_DestroyShared";
case 0x0034: return "ImageList_DragEnter";
case 0x0035: return "ImageList_DragLeave";
case 0x0036: return "ImageList_DragMove";
case 0x0037: return "ImageList_DragShowNolock";
case 0x0038: return "ImageList_Draw";
case 0x0039: return "ImageList_DrawEx";
case 0x003a: return "ImageList_DrawIndirect";
case 0x003b: return "ImageList_Duplicate";
case 0x003c: return "ImageList_EndDrag";
case 0x003d: return "ImageList_GetBkColor";
case 0x003e: return "ImageList_GetDragImage";
case 0x003f: return "ImageList_GetFlags";
case 0x0040: return "ImageList_GetIcon";
case 0x0041: return "ImageList_GetIconSize";
case 0x0042: return "ImageList_GetImageCount";
case 0x0043: return "ImageList_GetImageInfo";
case 0x0044: return "ImageList_GetImageRect";
case 0x0045: return "ImageList_LoadImage";
case 0x0046: return "ImageList_LoadImageA";
case 0x004b: return "ImageList_LoadImageW";
case 0x004c: return "ImageList_Merge";
case 0x004d: return "ImageList_Read";
case 0x004e: return "ImageList_ReadEx";
case 0x004f: return "ImageList_Remove";
case 0x0050: return "ImageList_Replace";
case 0x0051: return "ImageList_ReplaceIcon";
case 0x0052: return "ImageList_Resize";
case 0x0053: return "ImageList_SetBkColor";
case 0x0054: return "ImageList_SetDragCursorImage";
case 0x0055: return "ImageList_SetFilter";
case 0x0056: return "ImageList_SetFlags";
case 0x0057: return "ImageList_SetIconSize";
case 0x0058: return "ImageList_SetImageCount";
case 0x0059: return "ImageList_SetOverlayImage";
case 0x005a: return "ImageList_Write";
case 0x005b: return "ImageList_WriteEx";
case 0x0011: return "InitCommonControls";
case 0x005c: return "InitCommonControlsEx";
case 0x005d: return "InitMUILanguage";
case 0x005e: return "InitializeFlatSB";
case 0x000e: return "LBItemFromPt";
case 0x017c: return "LoadIconMetric";
case 0x017d: return "LoadIconWithScaleDown";
case 0x000d: return "MakeDragList";
case 0x0002: return "MenuHelp";
case 0x005f: return "PropertySheet";
case 0x0060: return "PropertySheetA";
case 0x0061: return "PropertySheetW";
case 0x018a: return "QuerySystemGestureStatus";
case 0x0062: return "RegisterClassNameW";
case 0x019c: return "RemoveWindowSubclass";
case 0x00cc: return "ScrollBar_Menu";
case 0x00cb: return "ScrollBar_MouseMove";
case 0x019a: return "SetWindowSubclass";
case 0x0003: return "ShowHideMenuCtl";
case 0x00ca: return "SizeBoxHwnd";
case 0x00ec: return "Str_SetPtrW";
case 0x0158: return "TaskDialog";
case 0x0159: return "TaskDialogIndirect";
case 0x0063: return "UninitializeFlatSB";
case 0x0064: return "_TrackMouseEvent";
}
return nullptr;
}
}
}
#endif
| 2,649 |
2,387 |
<reponame>saikrishna169/pipedream
{
"name": "@pipedream/bandwidth",
"version": "1.0.0",
"description": "Pipedream Bandwidth Components",
"main": "index.js",
"keywords": [
"pipedream",
"bandwidth"
],
"author": "Bandwidth",
"license": "MIT",
"dependencies": {
"@bandwidth/messaging": "^4.0.0"
}
}
| 144 |
2,062 |
<filename>strawberry/fastapi/handlers/__init__.py
from strawberry.fastapi.handlers.graphql_transport_ws_handler import (
GraphQLTransportWSHandler,
)
from strawberry.fastapi.handlers.graphql_ws_handler import GraphQLWSHandler
__all__ = ["GraphQLTransportWSHandler", "GraphQLWSHandler"]
| 102 |
2,748 |
/*
* 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 com.alipay.sofa.runtime.test.ambush;
import com.alipay.sofa.runtime.filter.JvmFilterContext;
import com.alipay.sofa.runtime.filter.JvmFilter;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ImportResource;
/**
* @author <a href="mailto:<EMAIL>">Alaneuler</a>
* Created on 2020/8/18
*/
@EnableAutoConfiguration
@ImportResource("classpath:spring/runtime.xml")
public class JvmFilterInterruptedConfiguration {
public static int beforeCount = 0;
public static int afterCount = 0;
@Bean
public JvmFilter egressFilter1() {
return new JvmFilter() {
@Override
public boolean before(JvmFilterContext context) {
++beforeCount;
return true;
}
@Override
public int getOrder() {
return 0;
}
@Override
public boolean after(JvmFilterContext context) {
return true;
}
};
}
@Bean
public JvmFilter egressFilter2() {
return new JvmFilter() {
@Override
public boolean before(JvmFilterContext context) {
++beforeCount;
return false;
}
@Override
public int getOrder() {
return 100;
}
@Override
public boolean after(JvmFilterContext context) {
return true;
}
};
}
@Bean
public JvmFilter egressFilter3() {
return new JvmFilter() {
@Override
public boolean before(JvmFilterContext context) {
++beforeCount;
context.setInvokeResult("interrupted");
return false;
}
@Override
public int getOrder() {
return -100;
}
@Override
public boolean after(JvmFilterContext context) {
return true;
}
};
}
}
| 1,231 |
9,680 |
<reponame>dutxubo/nni
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import os
import random
import sys
from .. import lib_acquisition_function
from .. import lib_constraint_summation
sys.path.insert(1, os.path.join(sys.path[0], '..'))
CONSTRAINT_LOWERBOUND = None
CONSTRAINT_UPPERBOUND = None
CONSTRAINT_PARAMS_IDX = []
def _ratio_scores(parameters_value, clusteringmodel_gmm_good,
clusteringmodel_gmm_bad):
'''
The ratio is smaller the better
'''
ratio = clusteringmodel_gmm_good.score(
[parameters_value]) / clusteringmodel_gmm_bad.score([parameters_value])
sigma = 0
return ratio, sigma
def selection_r(x_bounds,
x_types,
clusteringmodel_gmm_good,
clusteringmodel_gmm_bad,
num_starting_points=100,
minimize_constraints_fun=None):
'''
Select using different types.
'''
minimize_starting_points = clusteringmodel_gmm_good.sample(n_samples=num_starting_points)
outputs = selection(x_bounds, x_types,
clusteringmodel_gmm_good,
clusteringmodel_gmm_bad,
minimize_starting_points[0],
minimize_constraints_fun)
return outputs
def selection(x_bounds,
x_types,
clusteringmodel_gmm_good,
clusteringmodel_gmm_bad,
minimize_starting_points,
minimize_constraints_fun=None):
'''
Select the lowest mu value
'''
results = lib_acquisition_function.next_hyperparameter_lowest_mu(
_ratio_scores, [clusteringmodel_gmm_good, clusteringmodel_gmm_bad],
x_bounds, x_types, minimize_starting_points,
minimize_constraints_fun=minimize_constraints_fun)
return results
def _rand_with_constraints(x_bounds, x_types):
'''
Random generate the variable with constraints
'''
outputs = None
x_bounds_withconstraints = [x_bounds[i] for i in CONSTRAINT_PARAMS_IDX]
x_types_withconstraints = [x_types[i] for i in CONSTRAINT_PARAMS_IDX]
x_val_withconstraints = lib_constraint_summation.rand(x_bounds_withconstraints,
x_types_withconstraints,
CONSTRAINT_LOWERBOUND,
CONSTRAINT_UPPERBOUND)
if x_val_withconstraints is not None:
outputs = [None] * len(x_bounds)
for i, _ in enumerate(CONSTRAINT_PARAMS_IDX):
outputs[CONSTRAINT_PARAMS_IDX[i]] = x_val_withconstraints[i]
for i, _ in enumerate(outputs):
if outputs[i] is None:
outputs[i] = random.randint(x_bounds[i][0], x_bounds[i][1])
return outputs
def _minimize_constraints_fun_summation(x):
'''
Minimize constraints fun summation
'''
summation = sum([x[i] for i in CONSTRAINT_PARAMS_IDX])
return CONSTRAINT_UPPERBOUND >= summation >= CONSTRAINT_LOWERBOUND
| 1,503 |
3,861 |
<reponame>nicklela/edk2<filename>MdePkg/Library/BaseLib/Arm/InternalSwitchStack.c<gh_stars>1000+
/** @file
SwitchStack() function for ARM.
Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.<BR>
Portions copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#include "BaseLibInternals.h"
/**
Transfers control to a function starting with a new stack.
This internal worker function transfers control to the function
specified by EntryPoint using the new stack specified by NewStack,
and passes in the parameters specified by Context1 and Context2.
Context1 and Context2 are optional and may be NULL.
The function EntryPoint must never return.
@param EntryPoint The pointer to the function to enter.
@param Context1 The first parameter to pass in.
@param Context2 The second Parameter to pass in
@param NewStack The new Location of the stack
**/
VOID
EFIAPI
InternalSwitchStackAsm (
IN SWITCH_STACK_ENTRY_POINT EntryPoint,
IN VOID *Context1, OPTIONAL
IN VOID *Context2, OPTIONAL
IN VOID *NewStack
);
/**
Transfers control to a function starting with a new stack.
Transfers control to the function specified by EntryPoint using the
new stack specified by NewStack, and passes in the parameters specified
by Context1 and Context2. Context1 and Context2 are optional and may
be NULL. The function EntryPoint must never return.
Marker will be ignored on IA-32, x64, and EBC.
IPF CPUs expect one additional parameter of type VOID * that specifies
the new backing store pointer.
If EntryPoint is NULL, then ASSERT().
If NewStack is NULL, then ASSERT().
@param EntryPoint A pointer to function to call with the new stack.
@param Context1 A pointer to the context to pass into the EntryPoint
function.
@param Context2 A pointer to the context to pass into the EntryPoint
function.
@param NewStack A pointer to the new stack to use for the EntryPoint
function.
@param Marker A VA_LIST marker for the variable argument list.
**/
VOID
EFIAPI
InternalSwitchStack (
IN SWITCH_STACK_ENTRY_POINT EntryPoint,
IN VOID *Context1, OPTIONAL
IN VOID *Context2, OPTIONAL
IN VOID *NewStack,
IN VA_LIST Marker
)
{
InternalSwitchStackAsm (EntryPoint, Context1, Context2, NewStack);
}
| 1,055 |
4,262 |
{
"model": {
"kind": "model",
"name": "etcdServiceDiscovery",
"title": "Etcd Service Discovery",
"deprecated": false,
"label": "routing,cloud,service-discovery",
"javaType": "org.apache.camel.model.cloud.EtcdServiceCallServiceDiscoveryConfiguration",
"input": false,
"output": false
},
"properties": {
"uris": { "kind": "attribute", "displayName": "Uris", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": false, "description": "The URIs the client can connect to." },
"userName": { "kind": "attribute", "displayName": "User Name", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": false, "description": "The user name to use for basic authentication." },
"password": { "kind": "attribute", "displayName": "Password", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": false, "description": "The password to use for basic authentication." },
"timeout": { "kind": "attribute", "displayName": "Timeout", "required": false, "type": "integer", "javaType": "java.lang.Long", "deprecated": false, "autowired": false, "secret": false, "description": "To set the maximum time an action could take to complete." },
"servicePath": { "kind": "attribute", "displayName": "Service Path", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": false, "defaultValue": "\/services\/", "description": "The path to look for for service discovery" },
"type": { "kind": "attribute", "displayName": "Type", "required": false, "type": "enum", "javaType": "java.lang.String", "enum": [ "on-demand", "watch" ], "deprecated": false, "autowired": false, "secret": false, "defaultValue": "on-demand", "description": "To set the discovery type, valid values are on-demand and watch." },
"properties": { "kind": "element", "displayName": "Properties", "required": false, "type": "array", "javaType": "java.util.List<org.apache.camel.model.PropertyDefinition>", "deprecated": false, "autowired": false, "secret": false, "description": "Set client properties to use. These properties are specific to what service call implementation are in use. For example if using ribbon, then the client properties are define in com.netflix.client.config.CommonClientConfigKey." },
"id": { "kind": "attribute", "displayName": "Id", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": false, "description": "The id of this node" }
}
}
| 827 |
9,472 |
#pragma once
#include <Python.h>
#include <stdbool.h>
#include "cmatcher.h"
#include "cresponse.h"
#include "common.h"
#define REQUEST_INITIAL_BUFFER_LEN 1024
typedef struct {
PyObject_HEAD
char* method;
size_t method_len;
char* path;
bool path_decoded;
size_t path_len;
bool qs_decoded;
size_t qs_len;
int minor_version;
struct phr_header* headers;
size_t num_headers;
MatchDictEntry* match_dict_entries;
size_t match_dict_length;
char* body;
size_t body_length;
char* buffer;
size_t buffer_len;
char inline_buffer[REQUEST_INITIAL_BUFFER_LEN];
KEEP_ALIVE keep_alive;
bool simple;
bool response_called;
MatcherEntry* matcher_entry;
PyObject* exception;
PyObject* transport;
PyObject* app;
PyObject* py_method;
PyObject* py_path;
PyObject* py_qs;
PyObject* py_headers;
PyObject* py_match_dict;
PyObject* py_body;
PyObject* extra;
PyObject* done_callbacks;
Response response;
} Request;
#define REQUEST(r) \
((Request*)r)
#define REQUEST_METHOD(r) \
REQUEST(r)->buffer
#define REQUEST_PATH(r) \
REQUEST(r)->path
typedef struct {
PyTypeObject* RequestType;
PyObject* (*Request_clone)
(Request* original);
void (*Request_from_raw)
(Request* self, char* method, size_t method_len,
char* path, size_t path_len,
int minor_version,
struct phr_header* headers, size_t num_headers);
char* (*Request_get_decoded_path)
(Request* self, size_t* path_len);
void (*Request_set_match_dict_entries)
(Request* self, MatchDictEntry* entries, size_t length);
void (*Request_set_body)
(Request* self, char* body, size_t body_len);
} Request_CAPI;
#ifndef REQUEST_OPAQUE
PyObject*
Request_new(PyTypeObject* type, Request* self);
void
Request_dealloc(Request* self);
int
Request_init(Request* self);
void*
crequest_init(void);
#endif
| 722 |
502 |
<reponame>jackx22/fixflow
/**
* Copyright 1996-2013 Founder International Co.,Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @author kenshin
*/
package com.founder.fix.fixflow.expand.rulescript.entity;
import java.util.HashMap;
import java.util.Map;
import com.founder.fix.fixflow.core.impl.ProcessEngineConfigurationImpl;
import com.founder.fix.fixflow.core.impl.db.SqlCommand;
import com.founder.fix.fixflow.core.impl.runtime.TokenEntity;
import com.founder.fix.fixflow.core.scriptlanguage.BusinessRulesScript;
public class TokenPersistentDbMap implements BusinessRulesScript {
public Object execute(Object parameter, SqlCommand sqlCommand, ProcessEngineConfigurationImpl processEngineConfiguration) {
TokenEntity token=(TokenEntity)parameter;
Map<String, Object> objectParam = new HashMap<String, Object>();
objectParam.put("TOKEN_ID", token.getId());
objectParam.put("NAME", token.getName());
objectParam.put("PROCESSINSTANCE_ID", token.getProcessInstanceId());
objectParam.put("NODE_ID", token.getNodeId());
objectParam.put("PARENT_ID", token.getParentTokenId());
objectParam.put("PARENT_FREETOKEN_ID", token.getParentFreeTokenId());
objectParam.put("START_TIME", token.getStartTime());
objectParam.put("END_TIME", token.getEndTime());
objectParam.put("NODEENTER_TIME", token.getNodeEnterTime());
objectParam.put("ARCHIVE_TIME", token.getArchiveTime());
objectParam.put("TOKEN_LOCK", String.valueOf(token.getlock()));
objectParam.put("ISSUSPENDED", String.valueOf(token.isSuspended()));
objectParam.put("ISSUBPROCESSROOTTOKEN", String.valueOf(token.isSubProcessRootToken()));
objectParam.put("ISABLETOREACTIVATEPARENT", String.valueOf(token.isAbleToReactivateParent()));
objectParam.put("FREETOKEN", String.valueOf(token.isFreeToken()));
Map<String, Object> persistenceExtensionFields=token.getPersistenceExtensionFields();
for (String key : persistenceExtensionFields.keySet()) {
objectParam.put(key, persistenceExtensionFields.get(key));
}
return objectParam;
}
}
| 815 |
3,102 |
// B
#include "C.h"
| 11 |
1,738 |
<gh_stars>1000+
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include <ScriptCanvas/CodeGen/CodeGen.h>
#include <ScriptCanvas/Core/Node.h>
#include <ScriptCanvas/Internal/Nodes/ExpressionNodeBase.h>
#include <Include/ScriptCanvas/Libraries/Math/MathExpression.generated.h>
namespace ScriptCanvas
{
namespace Nodes
{
namespace Internal
{
class ExpressionNodeBase;
}
namespace Math
{
class MathExpression
: public Internal::ExpressionNodeBase
{
ScriptCanvas_Node(MathExpression,
ScriptCanvas_Node::Name("Math Expression", "Will evaluate a series of math operations, allowing users to specify inputs using {}.")
ScriptCanvas_Node::Uuid("{A5841DE8-CA11-4364-9C34-5ECE8B9623D7}")
ScriptCanvas_Node::Category("Math")
ScriptCanvas_Node::EditAttributes(AZ::Edit::Attributes::CategoryStyle(".math"), ScriptCanvas::Attributes::Node::TitlePaletteOverride("MathNodeTitlePalette"))
ScriptCanvas_Node::DynamicSlotOrdering(true)
ScriptCanvas_Node::Version(0)
);
public:
ScriptCanvas_Out(ScriptCanvas_Out::Name("Out", "Output signal"));
ScriptCanvas_Property(double,
ScriptCanvas_Property::Name("Result", "The resulting string.")
ScriptCanvas_Property::Output
ScriptCanvas_Property::DisplayGroup("ExpressionDisplayGroup")
);
protected:
void OnResult(const ExpressionEvaluation::ExpressionResult& result) override;
ExpressionEvaluation::ParseOutcome ParseExpression(const AZStd::string& formatString) override;
AZStd::string GetExpressionSeparator() const override;
};
}
}
}
| 1,010 |
460 |
/*=============================================================================
Copyright (c) 2001-2006 <NAME>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#if !defined(FUSION_SEQUENCE_GENERATION_10022005_0615)
#define FUSION_SEQUENCE_GENERATION_10022005_0615
#include <boost/fusion/container/generation/cons_tie.hpp>
#include <boost/fusion/container/generation/ignore.hpp>
#include <boost/fusion/container/generation/list_tie.hpp>
#include <boost/fusion/container/generation/make_cons.hpp>
#include <boost/fusion/container/generation/make_list.hpp>
#include <boost/fusion/container/generation/make_map.hpp>
#include <boost/fusion/container/generation/make_vector.hpp>
#include <boost/fusion/container/generation/vector_tie.hpp>
#include <boost/fusion/container/generation/make_set.hpp>
#endif
| 329 |
2,329 |
package invokestatic.issue4;
public class AA {
public static String getString() {
return "String1";
}
}
| 38 |
344 |
<gh_stars>100-1000
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"status.400": "Solicitud incorrecta. La solicitud no se puede rellenar porque la sintaxis es incorrecta.",
"status.401": "No autorizado. El servidor rechaza responder.",
"status.403": "Prohibido. El servidor rechaza responder.",
"status.404": "No encontrado. La ubicación solicitada no se encontró.",
"status.405": "Método no permitido. Se realizó una solicitud mediante un método no admitido en esa ubicación.",
"status.406": "No aceptable. El servidor solo puede generar una respuesta que el cliente no acepta.",
"status.407": "Se requiere autenticación del proxy. El cliente debe autenticarse primero en el servidor proxy.",
"status.408": "Tiempo de espera de la solicitud. El servidor ha agotado el tiempo de espera para la solicitud.",
"status.409": "Conflicto. La solicitud no se pudo completar porque presenta un conflicto.",
"status.410": "Desaparecido. La página solicitada ya no está disponible.",
"status.411": "Longitud requerida. La longitud del contenido no se ha definido.",
"status.412": "Error de condición previa. El servidor evaluó como \"false\" la precondición dada en la solicitud.",
"status.413": "Entidad de solicitud demasiado grande. El servidor no acepta la solicitud porque la entidad correspondiente es demasiado grande.",
"status.414": "URI de solicitud demasiado grande. El servidor no acepta la solicitud porque la dirección URL es demasiado grande.",
"status.415": "Tipo de medio no compatible. El servidor no acepta la solicitud porque el tipo de medio no es compatible.",
"status.416": "Código de estado HTTP {0}",
"status.500": "Error interno del servidor.",
"status.501": "Sin implementar. El servidor no reconoce el método de solicitud o no tiene la capacidad de completar la solicitud.",
"status.503": "Servicio no disponible. El servidor no está disponible en este momento (está sobrecargado o fuera de servicio)."
}
| 710 |
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 IOS_CHROME_BROWSER_UI_SETTINGS_PASSWORD_PASSWORD_DETAILS_PASSWORD_DETAILS_TABLE_VIEW_CONTROLLER_DELEGATE_H_
#define IOS_CHROME_BROWSER_UI_SETTINGS_PASSWORD_PASSWORD_DETAILS_PASSWORD_DETAILS_TABLE_VIEW_CONTROLLER_DELEGATE_H_
@class PasswordDetails;
@class PasswordDetailsTableViewController;
@protocol PasswordDetailsTableViewControllerDelegate
// Called when user finished editing a password.
- (void)passwordDetailsViewController:
(PasswordDetailsTableViewController*)viewController
didEditPasswordDetails:(PasswordDetails*)password;
// Called when user finished adding a new password credential.
- (void)passwordDetailsViewController:
(PasswordDetailsTableViewController*)viewController
didAddPasswordDetails:(NSString*)username
password:(<PASSWORD>*)password;
// Called on every keystroke to check whether duplicates exist before adding a
// new credential.
- (void)checkForDuplicates:(NSString*)username;
// Called when an existing credential is to be displayed in the add credential
// flow.
- (void)showExistingCredential:(NSString*)username;
// Called when the user cancels the add password view.
- (void)didCancelAddPasswordDetails;
// Called every time the text in the website field is updated.
- (void)setWebsiteURL:(NSString*)website;
// Returns whether the website URL has http(s) scheme and is valid or not.
- (BOOL)isURLValid;
// Called to check if the url is missing the top-level domain.
- (BOOL)isTLDMissing;
// Checks if the username is reused for the same domain.
- (BOOL)isUsernameReused:(NSString*)newUsername;
@end
#endif // IOS_CHROME_BROWSER_UI_SETTINGS_PASSWORD_PASSWORD_DETAILS_PASSWORD_DETAILS_TABLE_VIEW_CONTROLLER_DELEGATE_H_
| 644 |
358 |
#include <agz/editor/envir_light/native_sky.h>
#include <agz/editor/ui/utility/validator.h>
#include <agz/tracer/create/envir_light.h>
AGZ_EDITOR_BEGIN
NativeSkyWidget::NativeSkyWidget(const CloneData &clone_data)
{
QGridLayout *layout = new QGridLayout(this);
top_ = new ColorHolder(clone_data.top, this);
bottom_ = new ColorHolder(clone_data.bottom, this);
power_ = new RealInput(this);
power_->set_value(clone_data.power);
QLabel *top_text = new QLabel("Top Color", this);
QLabel *bottom_text = new QLabel("Bottom Color", this);
QLabel *power_text = new QLabel("Emit Weight", this);
layout->addWidget(top_text, 0, 0); layout->addWidget(top_, 0, 1);
layout->addWidget(bottom_text, 1, 0); layout->addWidget(bottom_, 1, 1);
layout->addWidget(power_text, 2, 0); layout->addWidget(power_, 2, 1);
setContentsMargins(0, 0, 0, 0);
layout->setContentsMargins(0, 0, 0, 0);
connect(top_, &ColorHolder::change_color, [=]
{
set_dirty_flag();
});
connect(bottom_, &ColorHolder::change_color, [=]
{
set_dirty_flag();
});
connect(power_, &RealInput::edit_value, [=](real)
{
set_dirty_flag();
});
do_update_tracer_object();
}
ResourceWidget<tracer::EnvirLight> *NativeSkyWidget::clone()
{
CloneData clone_data;
clone_data.top = top_->get_color();
clone_data.bottom = bottom_->get_color();
clone_data.power = power_->get_value();
return new NativeSkyWidget(clone_data);
}
void NativeSkyWidget::save_asset(AssetSaver &saver)
{
saver.write(top_->get_color());
saver.write(bottom_->get_color());
saver.write(power_->get_value());
}
void NativeSkyWidget::load_asset(AssetLoader &loader)
{
top_->set_color(loader.read<Spectrum>());
bottom_->set_color(loader.read<Spectrum>());
if(loader.version() >= versions::V2020_0418_2358)
power_->set_value(loader.read<real>());
else
power_->set_value(-1);
do_update_tracer_object();
}
RC<tracer::ConfigNode> NativeSkyWidget::to_config(
JSONExportContext &ctx) const
{
auto grp = newRC<tracer::ConfigGroup>();
grp->insert_str("type", "native_sky");
grp->insert_child(
"top", tracer::ConfigArray::from_spectrum(top_->get_color()));
grp->insert_child(
"bottom", tracer::ConfigArray::from_spectrum(bottom_->get_color()));
grp->insert_real("power", power_->get_value());
return grp;
}
void NativeSkyWidget::update_tracer_object_impl()
{
do_update_tracer_object();
}
void NativeSkyWidget::do_update_tracer_object()
{
tracer_object_ = tracer::create_native_sky(
top_->get_color(), bottom_->get_color(), power_->get_value());
}
ResourceWidget<tracer::EnvirLight> *NativeSkyCreator::create_widget(
ObjectContext &obj_ctx) const
{
return new NativeSkyWidget({});
}
AGZ_EDITOR_END
| 1,216 |
4,461 |
<reponame>przemub/pwndbg
import pwndbg.commands
from pwndbg.commands.misc import list_and_filter_commands
STACK_COMMANDS = [
('canary', 'Print out the current stack canary.'),
('context', 'Print out the current register, instruction, and stack context.'),
('down', 'Select and print stack frame called by this one.'),
('retaddr', 'Print out the stack addresses that contain return addresses.'),
('stack', 'dereferences on stack data with specified count and offset.'),
('up', 'Select and print stack frame that called this one.')
]
def test_list_and_filter_commands_filter():
for cmd in STACK_COMMANDS:
assert cmd in list_and_filter_commands('stack')
def test_list_and_filter_commands_full_list():
all_commands = list_and_filter_commands('')
def get_doc(c):
return c.__doc__.strip().splitlines()[0] if c.__doc__ else None
cmd_name_docs = [(c.__name__, get_doc(c)) for c in pwndbg.commands.commands]
cmd_name_docs.sort()
assert all_commands == cmd_name_docs
| 371 |
1,104 |
package com.alimama.mdrillImport;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.apache.solr.common.SolrInputDocument;
import com.alimama.mdrill.ui.service.MdrillService;
import backtype.storm.spout.SpoutOutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.IRichSpout;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.tuple.Fields;
public class ImportSpoutLocal implements IRichSpout{
private static Logger LOG = Logger.getLogger(ImportSpoutLocal.class);
private static final long serialVersionUID = 1L;
private ImportReader reader=null;
private DataParser parse=null;
private String confPrefix;
public ImportSpoutLocal(String confPrefix)
{
this.confPrefix=confPrefix;
}
private ArrayList<SolrInputDocument> doclist=null;
private Object doclistLock=null;
int buffersize=5000;
@Override
public void open(Map conf, TopologyContext context,SpoutOutputCollector collector) {
doclistLock=new Object();
try {
parse=(DataParser) Class.forName(String.valueOf(conf.get(this.confPrefix+"-parse"))).newInstance();
parse.init(true, conf, context);
} catch (Throwable e1) {
LOG.error(this.confPrefix+ " DataParser",e1);
}
int timeout=Integer.parseInt(String.valueOf(conf.get(confPrefix+"-timeoutSpout")));
this.buffersize=Integer.parseInt(String.valueOf(conf.get(confPrefix+"-spoutbuffer")));
Object chkIntervel=conf.get(confPrefix+"-spoutIntervel");
if(chkIntervel!=null)
{
this.checkIntervel=Integer.parseInt(String.valueOf(chkIntervel));
}
this.timeoutCheck=new TimeOutCheck(timeout*1000l);
this.status=new SpoutStatus();
doclist=new ArrayList<SolrInputDocument>(this.buffersize);
int readerCount=context.getComponentTasks(context.getThisComponentId()).size();
int readerIndex=context.getThisTaskIndex();
try {
this.reader=new ImportReader(conf, confPrefix, parse, readerIndex, readerCount);
} catch (IOException e) {
LOG.error("TTReader",e);
}
}
private SpoutStatus status=null;
private TimeOutCheck timeoutCheck=null;
int checkIntervel=1000;
private boolean putdata(DataParser.DataIter log)
{
long ts=log.getTs();
BoltStatKey key=new BoltStatKey(log.getGroup());
BoltStatVal val=new BoltStatVal(log.getSum(),ts);
this.status.ttInput++;
this.status.groupCreate++;
SolrInputDocument doc=new SolrInputDocument();
String[] groupnames=parse.getGroupName();
for(int i=0;i<groupnames.length&&i<key.list.length;i++)
{
doc.addField(groupnames[i], key.list[i]);
}
String[] statNames=parse.getSumName();
for(int i=0;i<statNames.length&&i<val.list.length;i++)
{
doc.addField(statNames[i], val.list[i]);
}
synchronized (doclistLock) {
doclist.add(doc);
}
if((this.status.ttInput%checkIntervel!=0))
{
return false;
}
this.commit();
return true;
}
public synchronized void commit() {
synchronized (doclistLock) {
if(!this.timeoutCheck.istimeout()&&doclist.size()<buffersize)
{
return ;
}
}
this.timeoutCheck.reset();
try{
ArrayList<SolrInputDocument> buffer=null;
synchronized (doclistLock) {
buffer=doclist;
doclist=new ArrayList<SolrInputDocument>(300);
}
if(buffer!=null&&buffer.size()>0)
{
for(int i=0;i<100;i++)
{
try {
LOG.info(this.confPrefix+" mdrill request:"+i+"@"+buffer.size());
MdrillService.insertLocal(this.parse.getTableName(), buffer,null);
break ;
} catch (Throwable e) {
LOG.error(this.confPrefix+" insert", e);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
}
}catch(Throwable e)
{
LOG.info("commit ",e);
}
}
@Override
public synchronized void nextTuple() {
try {
List ttdata = this.reader.read();
if(ttdata==null)
{
return ;
}
for(Object o:ttdata)
{
this.status.ttInput++;
DataParser.DataIter pv=(DataParser.DataIter)o;
while(true)
{
this.status.groupInput++;
this.putdata(pv);
if(!pv.next())
{
break;
}
}
}
} catch (Throwable e) {
this.sleep(100);
}
}
private void sleep(int i)
{
try {
Thread.sleep(i);
} catch (InterruptedException e1) {
}
}
@Override
public void close() {
}
@Override
public void ack(Object msgId) {
this.status.ackCnt++;
}
@Override
public void fail(Object msgId) {
this.status.failCnt++;
}
@Override
public void declareOutputFields(OutputFieldsDeclarer declarer) {
declarer.declare(new Fields("key","value"));
}
@Override
public Map<String, Object> getComponentConfiguration() {
Map<String, Object> rtnmap = new HashMap<String, Object>();
return rtnmap;
}
}
| 2,473 |
679 |
/**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
#include "precompiled_sd.hxx"
#include "framework/PresentationModule.hxx"
#include "CenterViewFocusModule.hxx"
#include "SlideSorterModule.hxx"
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
namespace sd { namespace framework {
void PresentationModule::Initialize (Reference<frame::XController>& rxController)
{
new sd::framework::CenterViewFocusModule(rxController);
}
} } // end of namespace sd::framework
| 352 |
1,936 |
#include <fstream> // NOLINT
#include <vector>
#include <Eigen/Core>
#include <Eigen/StdVector>
#include <descriptor-projection/descriptor-projection.h>
#include <descriptor-projection/flags.h>
#include <descriptor-projection/projected-descriptor-quantizer.h>
#include <gflags/gflags.h>
#include <glog/logging.h>
#include <loopclosure-common/types.h>
#include <maplab-common/test/testing-entrypoint.h>
#include <maplab-common/test/testing-predicates.h>
#include <vocabulary-tree/helpers.h>
#include <vocabulary-tree/simple-kmeans.h>
#include <vocabulary-tree/tree-builder.h>
DECLARE_string(data_directory);
TEST(PlacelessLoopClosure, QuantizerSerialization) {
std::mt19937 generator(42);
static const uint32_t kNumWords = 100;
static const int kDescriptorBytes = 64;
static const int kTargetDimensionality = 10;
std::string quantizer_filename = "./quantizer.dat";
descriptor_projection::ProjectedDescriptorQuantizer quantizer(
kTargetDimensionality);
{
quantizer.projection_matrix_.setRandom(
loop_closure::kFreakDescriptorLengthBits,
loop_closure::kFreakDescriptorLengthBits);
descriptor_projection::ProjectedDescriptorType descriptor_zero;
descriptor_zero.setConstant(kTargetDimensionality, 1, 0);
Eigen::Matrix<unsigned char, Eigen::Dynamic, Eigen::Dynamic> descriptors;
descriptors.setRandom(kDescriptorBytes, 40 * 100);
descriptor_projection::DescriptorVector projected_descriptors;
projected_descriptors.resize(descriptors.cols(), descriptor_zero);
for (int i = 0; i < descriptors.cols(); ++i) {
aslam::common::FeatureDescriptorConstRef raw_descriptor(
&descriptors.coeffRef(0, i), kDescriptorBytes);
descriptor_projection::ProjectDescriptor(
raw_descriptor, quantizer.projection_matrix_,
quantizer.target_dimensionality_, projected_descriptors[i]);
}
// Create tree.
typedef loop_closure::TreeBuilder<
descriptor_projection::ProjectedDescriptorType,
loop_closure::distance::L2<
descriptor_projection::ProjectedDescriptorType> >
TreeBuilder;
TreeBuilder builder(descriptor_zero);
builder.kmeans().SetRestarts(5);
builder.Build(projected_descriptors, kNumWords, 1);
VLOG(3) << "Done. Got " << builder.tree().centers().size() << " centers";
quantizer.vocabulary_ = builder.tree();
std::ofstream ofs(quantizer_filename.c_str());
ASSERT_TRUE(ofs.is_open());
quantizer.Save(&ofs);
}
descriptor_projection::ProjectedDescriptorQuantizer quantizer_load(
kTargetDimensionality);
EXPECT_FALSE(quantizer_load.vocabulary_.IsBinaryEqual(quantizer.vocabulary_));
std::ifstream ifs(quantizer_filename.c_str());
ASSERT_TRUE(ifs.is_open());
ASSERT_TRUE(ifs.good());
quantizer_load.Load(&ifs);
EXPECT_TRUE(
quantizer_load.projection_matrix_ == quantizer.projection_matrix_);
EXPECT_EQ(
quantizer_load.target_dimensionality_, quantizer.target_dimensionality_);
EXPECT_TRUE(quantizer_load.vocabulary_.IsBinaryEqual(quantizer.vocabulary_));
}
MAPLAB_UNITTEST_ENTRYPOINT
| 1,158 |
1,199 |
<filename>games/fortune/files/patch-strfile.c
--- strfile/strfile.c.orig Tue Oct 8 17:16:57 2002
+++ strfile/strfile.c Tue Oct 8 17:17:05 2002
@@ -452,7 +452,7 @@
long tmp;
long *sp;
- srandomdev();
+ srandom(getpid());
Tbl.str_flags |= STR_RANDOM;
cnt = Tbl.str_numstr;
--- strfile/strfile.c.orig 2007-09-27 12:48:32.000000000 +0200
+++ strfile/strfile.c 2007-09-27 12:54:12.000000000 +0200
@@ -49,7 +49,15 @@
__FBSDID("$FreeBSD: src/games/fortune/strfile/strfile.c,v 1.28 2005/02/17 18:06:37 ru Exp $");
# include <sys/param.h>
+#if defined(__FreeBSD__)
# include <sys/endian.h>
+#elif defined(__APPLE__) && defined(__MACH__)
+# include <machine/endian.h>
+# define htobe32 htonl
+#else
+# include <netinet/in.h>
+# define htobe32 htonl
+#endif
# include <stdio.h>
# include <stdlib.h>
# include <ctype.h>
@@ -252,6 +261,9 @@
Tbl.str_shortlen = htobe32(Tbl.str_shortlen);
Tbl.str_flags = htobe32(Tbl.str_flags);
(void) fwrite((char *) &Tbl, sizeof Tbl, 1, outf);
+#ifndef __FreeBSD__
+ #define htobe64(x) (((u_int64_t)htobe32((x) & (u_int64_t)0x00000000FFFFFFFFULL)) << 32) | ((u_int64_t)htobe32(((x) & (u_int64_t)0xFFFFFFFF00000000ULL) >> 32))
+#endif
if (STORING_PTRS) {
for (p = Seekpts, cnt = Num_pts; cnt--; ++p)
*p = htobe64(*p);
| 623 |
12,536 |
<reponame>xyzst/gvisor
// Copyright 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "test/syscalls/linux/socket_non_stream_blocking.h"
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/un.h>
#include "gtest/gtest.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
#include "test/syscalls/linux/unix_domain_socket_test_util.h"
#include "test/util/socket_util.h"
#include "test/util/test_util.h"
#include "test/util/thread_util.h"
namespace gvisor {
namespace testing {
TEST_P(BlockingNonStreamSocketPairTest, RecvLessThanBufferWaitAll) {
auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());
char sent_data[100];
RandomizeBuffer(sent_data, sizeof(sent_data));
ASSERT_THAT(write(sockets->first_fd(), sent_data, sizeof(sent_data)),
SyscallSucceedsWithValue(sizeof(sent_data)));
char received_data[sizeof(sent_data) * 2] = {};
ASSERT_THAT(RetryEINTR(recv)(sockets->second_fd(), received_data,
sizeof(received_data), MSG_WAITALL),
SyscallSucceedsWithValue(sizeof(sent_data)));
}
// This test tests reading from a socket with MSG_TRUNC | MSG_PEEK and a zero
// length receive buffer and MSG_DONTWAIT. The recvmsg call should block on
// reading the data.
TEST_P(BlockingNonStreamSocketPairTest,
RecvmsgTruncPeekDontwaitZeroLenBlocking) {
auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());
// NOTE: We don't initially send any data on the socket.
const int data_size = 10;
char sent_data[data_size];
RandomizeBuffer(sent_data, data_size);
// The receive buffer is of zero length.
char peek_data[0] = {};
struct iovec peek_iov;
peek_iov.iov_base = peek_data;
peek_iov.iov_len = sizeof(peek_data);
struct msghdr peek_msg = {};
peek_msg.msg_flags = -1;
peek_msg.msg_iov = &peek_iov;
peek_msg.msg_iovlen = 1;
ScopedThread t([&]() {
// The syscall succeeds returning the full size of the message on the
// socket. This should block until there is data on the socket.
ASSERT_THAT(RetryEINTR(recvmsg)(sockets->second_fd(), &peek_msg,
MSG_TRUNC | MSG_PEEK),
SyscallSucceedsWithValue(data_size));
});
absl::SleepFor(absl::Seconds(1));
ASSERT_THAT(RetryEINTR(send)(sockets->first_fd(), sent_data, data_size, 0),
SyscallSucceedsWithValue(data_size));
}
} // namespace testing
} // namespace gvisor
| 1,138 |
1,259 |
import pytest
from django.core.signing import TimestampSigner
from rest_framework.exceptions import AuthenticationFailed
from integrations.slack.authentication import OauthInitAuthentication
oauth_init_authentication = OauthInitAuthentication()
def test_oauth_init_authentication_failes_if_invalid_signature_is_passed(rf):
# Given
request = rf.get("/url", {"signature": "invalid_signature"})
# Then
with pytest.raises(AuthenticationFailed):
oauth_init_authentication.authenticate(request)
def test_oauth_init_authentication_with_valid_signature(django_user_model, rf):
# Given
signer = TimestampSigner()
user = django_user_model.objects.create(username="test_user")
request = rf.get("/url", {"signature": signer.sign(user.id)})
# Then
oauth_init_authentication.authenticate(request)
def test_oauth_init_authentication_failes_with_correct_error_if_no_signature_is_passed(
rf,
):
# Given
request = rf.get("/url")
# Then
with pytest.raises(AuthenticationFailed):
oauth_init_authentication.authenticate(request)
| 397 |
12,252 |
<reponame>rmartinc/keycloak
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.storage.ldap.mappers.msad;
/**
* See https://support.microsoft.com/en-us/kb/305144
*
* @author <a href="mailto:<EMAIL>"><NAME></a>
*/
public class UserAccountControl {
public static final long SCRIPT = 0x0001L;
public static final long ACCOUNTDISABLE = 0x0002L;
public static final long HOMEDIR_REQUIRED = 0x0008L;
public static final long LOCKOUT = 0x0010L;
public static final long PASSWD_NOTREQD = 0x0020L;
public static final long PASSWD_CANT_CHANGE = 0x0040L;
public static final long ENCRYPTED_TEXT_PWD_ALLOWED = 0x0080L;
public static final long TEMP_DUPLICATE_ACCOUNT = 0x0100L;
public static final long NORMAL_ACCOUNT = 0x0200L;
public static final long INTERDOMAIN_TRUST_ACCOUNT = 0x0800L;
public static final long WORKSTATION_TRUST_ACCOUNT = 0x1000L;
public static final long SERVER_TRUST_ACCOUNT = 0x2000L;
public static final long DONT_EXPIRE_PASSWORD = 0<PASSWORD>0L;
public static final long MNS_LOGON_ACCOUNT = 0x20000L;
public static final long SMARTCARD_REQUIRED = 0x40000L;
public static final long TRUSTED_FOR_DELEGATION = 0x80000L;
public static final long NOT_DELEGATED = 0x100000L;
public static final long USE_DES_KEY_ONLY = 0x200000L;
public static final long DONT_REQ_PREAUTH = 0x400000L;
public static final long PASSWORD_EXPIRED = 0x800000L;
public static final long TRUSTED_TO_AUTH_FOR_DELEGATION = 0x1000000L;
public static final long PARTIAL_SECRETS_ACCOUNT = 0x04000000L;
private long value;
public UserAccountControl(long value) {
this.value = value;
}
public boolean has(long feature) {
return (this.value & feature) > 0;
}
public void add(long feature) {
if (!has(feature)) {
this.value += feature;
}
}
public void remove(long feature) {
if (has(feature)) {
this.value -= feature;
}
}
public long getValue() {
return value;
}
}
| 978 |
4,054 |
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.orchestrator.status;
/**
* Enumeration of the different statuses a host can have.
*
* @author oyving
*/
public enum HostStatus {
/** The services on the host is supposed to be up. */
NO_REMARKS(false),
/** The services on the host is allowed to be down. */
ALLOWED_TO_BE_DOWN(true),
/**
* Same as ALLOWED_TO_BE_DOWN, but in addition, it is expected
* the host may be removed from its application at any moment.
*/
PERMANENTLY_DOWN(true);
private final boolean suspended;
HostStatus(boolean suspended) { this.suspended = suspended; }
public boolean isSuspended() { return suspended; }
public String asString() { return name(); }
}
| 265 |
12,366 |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////////////
#ifndef TINK_HYBRID_INTERNAL_HPKE_DECRYPT_H_
#define TINK_HYBRID_INTERNAL_HPKE_DECRYPT_H_
#include <memory>
#include <string>
#include <utility>
#include "tink/hybrid/internal/hpke_decrypt_boringssl.h"
#include "tink/hybrid/internal/hpke_key_boringssl.h"
#include "tink/hybrid_decrypt.h"
#include "tink/util/statusor.h"
#include "proto/hpke.pb.h"
namespace crypto {
namespace tink {
class HpkeDecrypt : public HybridDecrypt {
public:
static crypto::tink::util::StatusOr<std::unique_ptr<HybridDecrypt>> New(
const google::crypto::tink::HpkePrivateKey& recipient_private_key);
crypto::tink::util::StatusOr<std::string> Decrypt(
absl::string_view ciphertext,
absl::string_view context_info) const override;
private:
HpkeDecrypt(const google::crypto::tink::HpkeParams& hpke_params,
std::unique_ptr<crypto::tink::internal::HpkeKeyBoringSsl>
recipient_private_key)
: hpke_params_(hpke_params),
recipient_private_key_(std::move(recipient_private_key)){}
google::crypto::tink::HpkeParams hpke_params_;
std::unique_ptr<crypto::tink::internal::HpkeKeyBoringSsl>
recipient_private_key_;
};
} // namespace tink
} // namespace crypto
#endif // TINK_HYBRID_INTERNAL_HPKE_DECRYPT_H_
| 686 |
474 |
<filename>GVRf/Framework/framework/src/main/java/org/gearvrf/scene_objects/GVRSphereSceneObject.java
/* Copyright 2015 Samsung Electronics Co., LTD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gearvrf.scene_objects;
import java.util.concurrent.Future;
import org.gearvrf.GVRMaterial;
import org.gearvrf.GVRSceneObject;
import org.gearvrf.GVRRenderData;
import org.gearvrf.GVRContext;
import org.gearvrf.GVRMesh;
import org.gearvrf.GVRTexture;
import org.gearvrf.utility.Log;
public class GVRSphereSceneObject extends GVRSceneObject {
@SuppressWarnings("unused")
private static final String TAG = Log.tag(GVRSphereSceneObject.class);
private static final int STACK_NUMBER = 18;
private static final int SLICE_NUMBER = 36;
private float[] vertices;
private float[] normals;
private float[] texCoords;
private char[] indices;
private int vertexCount = 0;
private int texCoordCount = 0;
private char indexCount = 0;
private char triangleCount = 0;
/**
* Constructs a sphere scene object with a radius of 1 and 18 stacks, and 36
* slices.
*
* The sphere's triangles and normals are facing out and the same texture
* will be applied to each side of the sphere.
*
* @param gvrContext
* current {@link GVRContext}
*/
public GVRSphereSceneObject(GVRContext gvrContext) {
super(gvrContext);
generateSphereObject(gvrContext, STACK_NUMBER, SLICE_NUMBER, true,
new GVRMaterial(gvrContext), 1);
}
/**
* Constructs a sphere scene object with a radius of 1 and 18 stacks, and 36
* slices.
*
* The sphere's triangles and normals are facing either in or out and the
* same texture will be applied to each side of the sphere.
*
* @param gvrContext
* current {@link GVRContext}
*
* @param facingOut
* whether the triangles and normals should be facing in or
* facing out.
*/
public GVRSphereSceneObject(GVRContext gvrContext, boolean facingOut) {
super(gvrContext);
generateSphereObject(gvrContext, STACK_NUMBER, SLICE_NUMBER, facingOut,
new GVRMaterial(gvrContext), 1);
}
/**
* Constructs a sphere scene object 18 stacks, and 36
* slices.
*
* The sphere's triangles and normals are facing either in or out and the
* same texture will be applied to each side of the sphere.
*
* @param gvrContext
* current {@link GVRContext}
*
* @param facingOut
* whether the triangles and normals should be facing in or
* facing out.
* @param radius
* sets the sphere with the radius parameter. Radius must be > 0
* otherwise, set it to the default of 1
*/
public GVRSphereSceneObject(GVRContext gvrContext, boolean facingOut, float radius) {
super(gvrContext);
if (radius < 0) radius = 1;
generateSphereObject(gvrContext, STACK_NUMBER, SLICE_NUMBER, facingOut,
new GVRMaterial(gvrContext), radius);
}
/**
* Constructs a sphere scene object with a radius of 1 and 18 stacks, and 36
* slices.
*
* The sphere's triangles and normals are facing either in or out and the
* same texture will be applied to each side of the sphere.
*
* @param gvrContext
* current {@link GVRContext}
*
* @param stackNumber
* the number of stacks for the sphere. It should be equal or
* greater than 3.
*
* @param sliceNumber
* the number of slices for the sphere. It should be equal or
* greater than 4.
*
* @param facingOut
* whether the triangles and normals should be facing in or
* facing out.
*/
public GVRSphereSceneObject(GVRContext gvrContext, int stackNumber, int sliceNumber, boolean facingOut) {
super(gvrContext);
generateSphereObject(gvrContext, stackNumber, sliceNumber, facingOut, new GVRMaterial(gvrContext), 1);
}
/**
* Constructs a sphere scene object with a radius of 1 and 18 stacks, and 36
* slices.
*
* The sphere's triangles and normals are facing either in or out and the
* same texture will be applied to each side of the sphere.
*
* @param gvrContext
* current {@link GVRContext}
*
* @param facingOut
* whether the triangles and normals should be facing in or
* facing out.
*
* @param texture
* the texture for the sphere.
*/
public GVRSphereSceneObject(GVRContext gvrContext, boolean facingOut,
GVRTexture texture) {
super(gvrContext);
GVRMaterial material = new GVRMaterial(gvrContext);
material.setMainTexture(texture);
generateSphereObject(gvrContext, STACK_NUMBER, SLICE_NUMBER, facingOut,
material, 1);
}
/**
* Constructs a sphere scene object with a radius of 1 and 18 stacks, and 36
* slices.
*
* The sphere's triangles and normals are facing either in or out and the
* same texture will be applied to each side of the sphere.
*
* @param gvrContext
* current {@link GVRContext}
*
* @param stackNumber
* the number of stacks for the sphere. It should be equal or
* greater than 3.
*
* @param sliceNumber
* the number of slices for the sphere. It should be equal or
* greater than 4.
*
* @param facingOut
* whether the triangles and normals should be facing in or
* facing out.
*
* @param texture
* the texture for the sphere.
*/
public GVRSphereSceneObject(GVRContext gvrContext, int stackNumber, int sliceNumber, boolean facingOut, GVRTexture texture) {
super(gvrContext);
GVRMaterial material = new GVRMaterial(gvrContext);
material.setMainTexture(texture);
generateSphereObject(gvrContext, stackNumber, sliceNumber, facingOut, material, 1);
}
/**
* Constructs a sphere scene object with a radius of 1 and 18 stacks, and 36
* slices.
*
* The sphere's triangles and normals are facing either in or out and the
* same material will be applied to each side of the sphere.
*
* @param gvrContext
* current {@link GVRContext}
*
* @param facingOut
* whether the triangles and normals should be facing in or
* facing out.
*
* @param material
* the material for the sphere.
*/
public GVRSphereSceneObject(GVRContext gvrContext, boolean facingOut,
GVRMaterial material) {
super(gvrContext);
generateSphereObject(gvrContext, STACK_NUMBER, SLICE_NUMBER, facingOut,
material, 1);
}
/**
* Constructs a sphere scene object with a radius of 1 and 18 stacks, and 36
* slices.
*
* The sphere's triangles and normals are facing either in or out and the
* same material will be applied to each side of the sphere.
*
* @param gvrContext
* current {@link GVRContext}
*
* @param facingOut
* whether the triangles and normals should be facing in or
* facing out.
*
* @param material
* the material for the sphere.
* @param radius
* sets the sphere with the radius parameter. Radius must be > 0
* otherwise, set it to the default of 1
*/
public GVRSphereSceneObject(GVRContext gvrContext, boolean facingOut,
GVRMaterial material, float radius)
{
super(gvrContext);
generateSphereObject(gvrContext, STACK_NUMBER, SLICE_NUMBER, facingOut,
material, radius);
}
/**
* Constructs a sphere scene object with a radius of 1 and user specified
* stack and slice numbers.
*
* The sphere's triangles and normals are facing either in or out and the
* same material will be applied to each side of the sphere.
*
* @param gvrContext
* current {@link GVRContext}
*
* @param stackNumber
* the number of stacks for the sphere. It should be equal or
* greater than 3.
*
* @param sliceNumber
* the number of slices for the sphere. It should be equal or
* greater than 4.
*
* @param facingOut
* whether the triangles and normals should be facing in or
* facing out.
*
* @param material
* the material for the sphere.
*/
public GVRSphereSceneObject(GVRContext gvrContext, int stackNumber,
int sliceNumber, boolean facingOut, GVRMaterial material) {
super(gvrContext);
// assert sliceNumber>=4
if (sliceNumber < 4) {
throw new IllegalArgumentException(
"Slice number should be equal or greater than 4.");
}
// assert stackNumber>=3
if (stackNumber < 3) {
throw new IllegalArgumentException(
"Stack number should be equal or greater than 3.");
}
generateSphereObject(gvrContext, stackNumber, sliceNumber, facingOut,
material, 1);
}
/**
* Constructs a sphere scene object with a radius of 1 and user specified
* stack and slice numbers. The sphere is subdivided into MxN meshes, where M=sliceSegmengNumber and N=(stackSegmentNumber+2) are specified by user.
*
* The sphere's triangles and normals are facing either in or out and the
* same material will be applied to each side of the sphere.
*
* @param gvrContext
* current {@link GVRContext}
*
* @param stackNumber
* the number of stacks for the sphere. It should be equal or
* greater than 3.
*
* @param sliceNumber
* the number of slices for the sphere. It should be equal or
* greater than 4.
*
* @param facingOut
* whether the triangles and normals should be facing in or
* facing out.
*
* @param material
* the material for the sphere.
*
* @param stackSegmentNumber
* the segment number along vertical direction (i.e. stacks).
* Note neither top cap nor bottom cap are subdivided along
* vertical direction. So number of stacks in body part (i.e.
* stackNumber-2) should be divisible by stackSegmentNumber.
*
* @param sliceSegmentNumber
* the segment number along horizontal direction (i.e. slices).
* Number of slices (i.e. sliceNumber) should be divisible by
* sliceSegmentNumber.
*/
public GVRSphereSceneObject(GVRContext gvrContext, int stackNumber,
int sliceNumber, boolean facingOut, GVRMaterial material,
int stackSegmentNumber, int sliceSegmentNumber) {
super(gvrContext);
// assert stackNumber>=3
if (stackNumber < 3) {
throw new IllegalArgumentException(
"Stack number should be equal or greater than 3.");
}
// assert sliceNumber>=4
if (sliceNumber < 4) {
throw new IllegalArgumentException(
"Slice number should be equal or greater than 4.");
}
// assert for valid stackSegmentNumber
if ((stackNumber - 2) % stackSegmentNumber != 0) {
throw new IllegalArgumentException(
"(stackNumber-2) should be divisible by stackSegmentNumber.");
}
// assert for valid sliceSegmentNumber
if (sliceNumber % sliceSegmentNumber != 0) {
throw new IllegalArgumentException(
"sliceNumber should be divisible by sliceSegmentNumber.");
}
generateComplexSphereObject(gvrContext, stackNumber, sliceNumber,
facingOut, material, stackSegmentNumber, sliceSegmentNumber);
}
private void generateSphereObject(GVRContext gvrContext, int stackNumber,
int sliceNumber, boolean facingOut, GVRMaterial material, float radius) {
generateSphere(stackNumber, sliceNumber, facingOut);
// multiply by radius > 0
//float radius = 1;
for (int i = 0; i < vertices.length; i++) {
vertices[i] *= radius;
}
GVRMesh mesh = new GVRMesh(gvrContext, "float3 a_position float2 a_texcoord float3 a_normal");
mesh.setVertices(vertices);
mesh.setNormals(normals);
mesh.setTexCoords(texCoords);
mesh.setIndices(indices);
GVRRenderData renderData = new GVRRenderData(gvrContext, material);
attachComponent(renderData);
renderData.setMesh(mesh);
}
private void generateSphere(int stackNumber, int sliceNumber,
boolean facingOut) {
int capVertexNumber = 3 * sliceNumber;
int bodyVertexNumber = 4 * sliceNumber * (stackNumber - 2);
int vertexNumber = (2 * capVertexNumber) + bodyVertexNumber;
int triangleNumber = (2 * capVertexNumber)
+ (6 * sliceNumber * (stackNumber - 2));
vertices = new float[3 * vertexNumber];
normals = new float[3 * vertexNumber];
texCoords = new float[2 * vertexNumber];
indices = new char[triangleNumber];
// bottom cap
createCap(stackNumber, sliceNumber, false, facingOut);
// body
createBody(stackNumber, sliceNumber, facingOut);
// top cap
createCap(stackNumber, sliceNumber, true, facingOut);
}
private void createCap(int stackNumber, int sliceNumber, boolean top,
boolean facingOut) {
float stackPercentage0;
float stackPercentage1;
if (!top) {
stackPercentage0 = ((float) (stackNumber - 1) / stackNumber);
stackPercentage1 = 1.0f;
} else {
stackPercentage0 = (1.0f / stackNumber);
stackPercentage1 = 0.0f;
}
float t0 = stackPercentage0;
float t1 = stackPercentage1;
double theta0 = stackPercentage0 * Math.PI;
double theta1 = stackPercentage1 * Math.PI;
double cosTheta0 = Math.cos(theta0);
double sinTheta0 = Math.sin(theta0);
double cosTheta1 = Math.cos(theta1);
double sinTheta1 = Math.sin(theta1);
for (int slice = 0; slice < sliceNumber; slice++) {
float slicePercentage0 = ((float) (slice) / sliceNumber);
float slicePercentage1 = ((float) (slice + 1) / sliceNumber);
double phi0 = slicePercentage0 * 2.0 * Math.PI;
double phi1 = slicePercentage1 * 2.0 * Math.PI;
float s0, s1;
if (facingOut) {
s0 = 1 - slicePercentage0;
s1 = 1 - slicePercentage1;
} else {
s0 = slicePercentage0;
s1 = slicePercentage1;
}
float s2 = (s0 + s1) / 2.0f;
double cosPhi0 = Math.cos(phi0);
double sinPhi0 = Math.sin(phi0);
double cosPhi1 = Math.cos(phi1);
double sinPhi1 = Math.sin(phi1);
float x0 = (float) (sinTheta0 * cosPhi0);
float y0 = (float) cosTheta0;
float z0 = (float) (sinTheta0 * sinPhi0);
float x1 = (float) (sinTheta0 * cosPhi1);
float y1 = (float) cosTheta0;
float z1 = (float) (sinTheta0 * sinPhi1);
float x2 = (float) (sinTheta1 * cosPhi0);
float y2 = (float) cosTheta1;
float z2 = (float) (sinTheta1 * sinPhi0);
vertices[vertexCount + 0] = x0;
vertices[vertexCount + 1] = y0;
vertices[vertexCount + 2] = z0;
vertices[vertexCount + 3] = x1;
vertices[vertexCount + 4] = y1;
vertices[vertexCount + 5] = z1;
vertices[vertexCount + 6] = x2;
vertices[vertexCount + 7] = y2;
vertices[vertexCount + 8] = z2;
if (facingOut) {
normals[vertexCount + 0] = x0;
normals[vertexCount + 1] = y0;
normals[vertexCount + 2] = z0;
normals[vertexCount + 3] = x1;
normals[vertexCount + 4] = y1;
normals[vertexCount + 5] = z1;
normals[vertexCount + 6] = x2;
normals[vertexCount + 7] = y2;
normals[vertexCount + 8] = z2;
} else {
normals[vertexCount + 0] = -x0;
normals[vertexCount + 1] = -y0;
normals[vertexCount + 2] = -z0;
normals[vertexCount + 3] = -x1;
normals[vertexCount + 4] = -y1;
normals[vertexCount + 5] = -z1;
normals[vertexCount + 6] = -x2;
normals[vertexCount + 7] = -y2;
normals[vertexCount + 8] = -z2;
}
texCoords[texCoordCount + 0] = s0;
texCoords[texCoordCount + 1] = t0;
texCoords[texCoordCount + 2] = s1;
texCoords[texCoordCount + 3] = t0;
texCoords[texCoordCount + 4] = s2;
texCoords[texCoordCount + 5] = t1;
if ((facingOut && top) || (!facingOut && !top)) {
indices[indexCount + 0] = (char) (triangleCount + 1);
indices[indexCount + 1] = (char) (triangleCount + 0);
indices[indexCount + 2] = (char) (triangleCount + 2);
} else {
indices[indexCount + 0] = (char) (triangleCount + 0);
indices[indexCount + 1] = (char) (triangleCount + 1);
indices[indexCount + 2] = (char) (triangleCount + 2);
}
vertexCount += 9;
texCoordCount += 6;
indexCount += 3;
triangleCount += 3;
}
}
private void createBody(int stackNumber, int sliceNumber, boolean facingOut) {
for (int stack = 1; stack < stackNumber - 1; stack++) {
float stackPercentage0 = ((float) (stack) / stackNumber);
float stackPercentage1 = ((float) (stack + 1) / stackNumber);
float t0 = stackPercentage0;
float t1 = stackPercentage1;
double theta0 = stackPercentage0 * Math.PI;
double theta1 = stackPercentage1 * Math.PI;
double cosTheta0 = Math.cos(theta0);
double sinTheta0 = Math.sin(theta0);
double cosTheta1 = Math.cos(theta1);
double sinTheta1 = Math.sin(theta1);
for (int slice = 0; slice < sliceNumber; slice++) {
float slicePercentage0 = ((float) (slice) / sliceNumber);
float slicePercentage1 = ((float) (slice + 1) / sliceNumber);
double phi0 = slicePercentage0 * 2.0 * Math.PI;
double phi1 = slicePercentage1 * 2.0 * Math.PI;
float s0, s1;
if (facingOut) {
s0 = 1.0f - slicePercentage0;
s1 = 1.0f - slicePercentage1;
} else {
s0 = slicePercentage0;
s1 = slicePercentage1;
}
double cosPhi0 = Math.cos(phi0);
double sinPhi0 = Math.sin(phi0);
double cosPhi1 = Math.cos(phi1);
double sinPhi1 = Math.sin(phi1);
float x0 = (float) (sinTheta0 * cosPhi0);
float y0 = (float) cosTheta0;
float z0 = (float) (sinTheta0 * sinPhi0);
float x1 = (float) (sinTheta0 * cosPhi1);
float y1 = (float) cosTheta0;
float z1 = (float) (sinTheta0 * sinPhi1);
float x2 = (float) (sinTheta1 * cosPhi0);
float y2 = (float) cosTheta1;
float z2 = (float) (sinTheta1 * sinPhi0);
float x3 = (float) (sinTheta1 * cosPhi1);
float y3 = (float) cosTheta1;
float z3 = (float) (sinTheta1 * sinPhi1);
vertices[vertexCount + 0] = x0;
vertices[vertexCount + 1] = y0;
vertices[vertexCount + 2] = z0;
vertices[vertexCount + 3] = x1;
vertices[vertexCount + 4] = y1;
vertices[vertexCount + 5] = z1;
vertices[vertexCount + 6] = x2;
vertices[vertexCount + 7] = y2;
vertices[vertexCount + 8] = z2;
vertices[vertexCount + 9] = x3;
vertices[vertexCount + 10] = y3;
vertices[vertexCount + 11] = z3;
if (facingOut) {
normals[vertexCount + 0] = x0;
normals[vertexCount + 1] = y0;
normals[vertexCount + 2] = z0;
normals[vertexCount + 3] = x1;
normals[vertexCount + 4] = y1;
normals[vertexCount + 5] = z1;
normals[vertexCount + 6] = x2;
normals[vertexCount + 7] = y2;
normals[vertexCount + 8] = z2;
normals[vertexCount + 9] = x3;
normals[vertexCount + 10] = y3;
normals[vertexCount + 11] = z3;
} else {
normals[vertexCount + 0] = -x0;
normals[vertexCount + 1] = -y0;
normals[vertexCount + 2] = -z0;
normals[vertexCount + 3] = -x1;
normals[vertexCount + 4] = -y1;
normals[vertexCount + 5] = -z1;
normals[vertexCount + 6] = -x2;
normals[vertexCount + 7] = -y2;
normals[vertexCount + 8] = -z2;
normals[vertexCount + 9] = -x3;
normals[vertexCount + 10] = -y3;
normals[vertexCount + 11] = -z3;
}
texCoords[texCoordCount + 0] = s0;
texCoords[texCoordCount + 1] = t0;
texCoords[texCoordCount + 2] = s1;
texCoords[texCoordCount + 3] = t0;
texCoords[texCoordCount + 4] = s0;
texCoords[texCoordCount + 5] = t1;
texCoords[texCoordCount + 6] = s1;
texCoords[texCoordCount + 7] = t1;
// one quad looking from outside toward center
//
// @formatter:off
//
// s1 --> s0
//
// t0 1-----0
// | | |
// v | |
// t1 3-----2
//
// @formatter:on
//
// Note that tex_coord t increase from top to bottom because the
// texture image is loaded upside down.
if (facingOut) {
indices[indexCount + 0] = (char) (triangleCount + 0);
indices[indexCount + 1] = (char) (triangleCount + 1);
indices[indexCount + 2] = (char) (triangleCount + 2);
indices[indexCount + 3] = (char) (triangleCount + 2);
indices[indexCount + 4] = (char) (triangleCount + 1);
indices[indexCount + 5] = (char) (triangleCount + 3);
} else {
indices[indexCount + 0] = (char) (triangleCount + 0);
indices[indexCount + 1] = (char) (triangleCount + 2);
indices[indexCount + 2] = (char) (triangleCount + 1);
indices[indexCount + 3] = (char) (triangleCount + 2);
indices[indexCount + 4] = (char) (triangleCount + 3);
indices[indexCount + 5] = (char) (triangleCount + 1);
}
vertexCount += 12;
texCoordCount += 8;
indexCount += 6;
triangleCount += 4;
}
}
}
private void generateComplexSphereObject(GVRContext gvrContext,
int stackNumber, int sliceNumber, boolean facingOut,
GVRMaterial material, int stackSegmentNumber, int sliceSegmentNumber) {
// bottom cap
createComplexCap(gvrContext, stackNumber, sliceNumber, false,
facingOut, material, sliceSegmentNumber);
// body
createComplexBody(gvrContext, stackNumber, sliceNumber, facingOut,
material, stackSegmentNumber, sliceSegmentNumber);
// top cap
createComplexCap(gvrContext, stackNumber, sliceNumber, true, facingOut,
material, sliceSegmentNumber);
// attached an empty renderData for parent object, so that we can set
// some common properties
GVRRenderData renderData = new GVRRenderData(gvrContext, material);
attachComponent(renderData);
}
private void createComplexCap(GVRContext gvrContext, int stackNumber,
int sliceNumber, boolean top, boolean facingOut,
GVRMaterial material, int sliceSegmentNumber) {
int slicePerSegment = sliceNumber / sliceSegmentNumber;
int vertexNumber = 3 * slicePerSegment;
vertices = new float[3 * vertexNumber];
normals = new float[3 * vertexNumber];
texCoords = new float[2 * vertexNumber];
indices = new char[vertexNumber];
vertexCount = 0;
texCoordCount = 0;
indexCount = 0;
triangleCount = 0;
int sliceCounter = 0;
float stackPercentage0;
float stackPercentage1;
if (!top) {
stackPercentage0 = ((float) (stackNumber - 1) / stackNumber);
stackPercentage1 = 1.0f;
} else {
stackPercentage0 = (1.0f / stackNumber);
stackPercentage1 = 0.0f;
}
float t0 = stackPercentage0;
float t1 = stackPercentage1;
double theta0 = stackPercentage0 * Math.PI;
double theta1 = stackPercentage1 * Math.PI;
double cosTheta0 = Math.cos(theta0);
double sinTheta0 = Math.sin(theta0);
double cosTheta1 = Math.cos(theta1);
double sinTheta1 = Math.sin(theta1);
for (int slice = 0; slice < sliceNumber; slice++) {
float slicePercentage0 = ((float) (slice) / sliceNumber);
float slicePercentage1 = ((float) (slice + 1) / sliceNumber);
double phi0 = slicePercentage0 * 2.0 * Math.PI;
double phi1 = slicePercentage1 * 2.0 * Math.PI;
float s0, s1;
if (facingOut) {
s0 = 1 - slicePercentage0;
s1 = 1 - slicePercentage1;
} else {
s0 = slicePercentage0;
s1 = slicePercentage1;
}
float s2 = (s0 + s1) / 2.0f;
double cosPhi0 = Math.cos(phi0);
double sinPhi0 = Math.sin(phi0);
double cosPhi1 = Math.cos(phi1);
double sinPhi1 = Math.sin(phi1);
float x0 = (float) (sinTheta0 * cosPhi0);
float y0 = (float) cosTheta0;
float z0 = (float) (sinTheta0 * sinPhi0);
float x1 = (float) (sinTheta0 * cosPhi1);
float y1 = (float) cosTheta0;
float z1 = (float) (sinTheta0 * sinPhi1);
float x2 = (float) (sinTheta1 * cosPhi0);
float y2 = (float) cosTheta1;
float z2 = (float) (sinTheta1 * sinPhi0);
vertices[vertexCount + 0] = x0;
vertices[vertexCount + 1] = y0;
vertices[vertexCount + 2] = z0;
vertices[vertexCount + 3] = x1;
vertices[vertexCount + 4] = y1;
vertices[vertexCount + 5] = z1;
vertices[vertexCount + 6] = x2;
vertices[vertexCount + 7] = y2;
vertices[vertexCount + 8] = z2;
if (facingOut) {
normals[vertexCount + 0] = x0;
normals[vertexCount + 1] = y0;
normals[vertexCount + 2] = z0;
normals[vertexCount + 3] = x1;
normals[vertexCount + 4] = y1;
normals[vertexCount + 5] = z1;
normals[vertexCount + 6] = x2;
normals[vertexCount + 7] = y2;
normals[vertexCount + 8] = z2;
} else {
normals[vertexCount + 0] = -x0;
normals[vertexCount + 1] = -y0;
normals[vertexCount + 2] = -z0;
normals[vertexCount + 3] = -x1;
normals[vertexCount + 4] = -y1;
normals[vertexCount + 5] = -z1;
normals[vertexCount + 6] = -x2;
normals[vertexCount + 7] = -y2;
normals[vertexCount + 8] = -z2;
}
texCoords[texCoordCount + 0] = s0;
texCoords[texCoordCount + 1] = t0;
texCoords[texCoordCount + 2] = s1;
texCoords[texCoordCount + 3] = t0;
texCoords[texCoordCount + 4] = s2;
texCoords[texCoordCount + 5] = t1;
if ((facingOut && top) || (!facingOut && !top)) {
indices[indexCount + 0] = (char) (triangleCount + 1);
indices[indexCount + 1] = (char) (triangleCount + 0);
indices[indexCount + 2] = (char) (triangleCount + 2);
} else {
indices[indexCount + 0] = (char) (triangleCount + 0);
indices[indexCount + 1] = (char) (triangleCount + 1);
indices[indexCount + 2] = (char) (triangleCount + 2);
}
sliceCounter++;
if (sliceCounter == slicePerSegment) {
GVRMesh mesh = new GVRMesh(gvrContext, "float3 a_position float2 a_texcoord float3 a_normal");
mesh.setVertices(vertices);
mesh.setNormals(normals);
mesh.setTexCoords(texCoords);
mesh.setIndices(indices);
GVRSceneObject childObject = new GVRSceneObject(gvrContext, mesh, material);
addChildObject(childObject);
sliceCounter = 0;
vertexCount = 0;
texCoordCount = 0;
indexCount = 0;
triangleCount = 0;
} else {
vertexCount += 9;
texCoordCount += 6;
indexCount += 3;
triangleCount += 3;
}
}
}
private void createComplexBody(GVRContext gvrContext, int stackNumber,
int sliceNumber, boolean facingOut, GVRMaterial material,
int stackSegmentNumber, int sliceSegmentNumber) {
int stackPerSegment = (stackNumber - 2) / stackSegmentNumber;
int slicePerSegment = sliceNumber / sliceSegmentNumber;
int vertexNumber = 4 * stackPerSegment * slicePerSegment;
int triangleNumber = 6 * stackPerSegment * slicePerSegment;
vertices = new float[3 * vertexNumber];
normals = new float[3 * vertexNumber];
texCoords = new float[2 * vertexNumber];
indices = new char[triangleNumber];
vertexCount = 0;
texCoordCount = 0;
indexCount = 0;
triangleCount = 0;
for (int stackSegment = 0; stackSegment < stackSegmentNumber; stackSegment++) {
for (int sliceSegment = 0; sliceSegment < sliceSegmentNumber; sliceSegment++) {
for (int stack = stackSegment * stackPerSegment + 1; stack < (stackSegment+1) * stackPerSegment + 1; stack++) {
float stackPercentage0 = ((float) (stack) / stackNumber);
float stackPercentage1 = ((float) (stack + 1) / stackNumber);
float t0 = stackPercentage0;
float t1 = stackPercentage1;
double theta0 = stackPercentage0 * Math.PI;
double theta1 = stackPercentage1 * Math.PI;
double cosTheta0 = Math.cos(theta0);
double sinTheta0 = Math.sin(theta0);
double cosTheta1 = Math.cos(theta1);
double sinTheta1 = Math.sin(theta1);
for (int slice = sliceSegment * slicePerSegment; slice < (sliceSegment+1) * slicePerSegment; slice++) {
float slicePercentage0 = ((float) (slice) / sliceNumber);
float slicePercentage1 = ((float) (slice + 1) / sliceNumber);
double phi0 = slicePercentage0 * 2.0 * Math.PI;
double phi1 = slicePercentage1 * 2.0 * Math.PI;
float s0, s1;
if (facingOut) {
s0 = 1.0f - slicePercentage0;
s1 = 1.0f - slicePercentage1;
} else {
s0 = slicePercentage0;
s1 = slicePercentage1;
}
double cosPhi0 = Math.cos(phi0);
double sinPhi0 = Math.sin(phi0);
double cosPhi1 = Math.cos(phi1);
double sinPhi1 = Math.sin(phi1);
float x0 = (float) (sinTheta0 * cosPhi0);
float y0 = (float) cosTheta0;
float z0 = (float) (sinTheta0 * sinPhi0);
float x1 = (float) (sinTheta0 * cosPhi1);
float y1 = (float) cosTheta0;
float z1 = (float) (sinTheta0 * sinPhi1);
float x2 = (float) (sinTheta1 * cosPhi0);
float y2 = (float) cosTheta1;
float z2 = (float) (sinTheta1 * sinPhi0);
float x3 = (float) (sinTheta1 * cosPhi1);
float y3 = (float) cosTheta1;
float z3 = (float) (sinTheta1 * sinPhi1);
vertices[vertexCount + 0] = x0;
vertices[vertexCount + 1] = y0;
vertices[vertexCount + 2] = z0;
vertices[vertexCount + 3] = x1;
vertices[vertexCount + 4] = y1;
vertices[vertexCount + 5] = z1;
vertices[vertexCount + 6] = x2;
vertices[vertexCount + 7] = y2;
vertices[vertexCount + 8] = z2;
vertices[vertexCount + 9] = x3;
vertices[vertexCount + 10] = y3;
vertices[vertexCount + 11] = z3;
if (facingOut) {
normals[vertexCount + 0] = x0;
normals[vertexCount + 1] = y0;
normals[vertexCount + 2] = z0;
normals[vertexCount + 3] = x1;
normals[vertexCount + 4] = y1;
normals[vertexCount + 5] = z1;
normals[vertexCount + 6] = x2;
normals[vertexCount + 7] = y2;
normals[vertexCount + 8] = z2;
normals[vertexCount + 9] = x3;
normals[vertexCount + 10] = y3;
normals[vertexCount + 11] = z3;
} else {
normals[vertexCount + 0] = -x0;
normals[vertexCount + 1] = -y0;
normals[vertexCount + 2] = -z0;
normals[vertexCount + 3] = -x1;
normals[vertexCount + 4] = -y1;
normals[vertexCount + 5] = -z1;
normals[vertexCount + 6] = -x2;
normals[vertexCount + 7] = -y2;
normals[vertexCount + 8] = -z2;
normals[vertexCount + 9] = -x3;
normals[vertexCount + 10] = -y3;
normals[vertexCount + 11] = -z3;
}
texCoords[texCoordCount + 0] = s0;
texCoords[texCoordCount + 1] = t0;
texCoords[texCoordCount + 2] = s1;
texCoords[texCoordCount + 3] = t0;
texCoords[texCoordCount + 4] = s0;
texCoords[texCoordCount + 5] = t1;
texCoords[texCoordCount + 6] = s1;
texCoords[texCoordCount + 7] = t1;
// one quad looking from outside toward center
//
// @formatter:off
//
// s1 --> s0
//
// t0 1-----0
// | | |
// v | |
// t1 3-----2
//
// @formatter:on
//
// Note that tex_coord t increase from top to bottom because the
// texture image is loaded upside down.
if (facingOut) {
indices[indexCount + 0] = (char) (triangleCount + 0);
indices[indexCount + 1] = (char) (triangleCount + 1);
indices[indexCount + 2] = (char) (triangleCount + 2);
indices[indexCount + 3] = (char) (triangleCount + 2);
indices[indexCount + 4] = (char) (triangleCount + 1);
indices[indexCount + 5] = (char) (triangleCount + 3);
} else {
indices[indexCount + 0] = (char) (triangleCount + 0);
indices[indexCount + 1] = (char) (triangleCount + 2);
indices[indexCount + 2] = (char) (triangleCount + 1);
indices[indexCount + 3] = (char) (triangleCount + 2);
indices[indexCount + 4] = (char) (triangleCount + 3);
indices[indexCount + 5] = (char) (triangleCount + 1);
}
vertexCount += 12;
texCoordCount += 8;
indexCount += 6;
triangleCount += 4;
}
}
GVRMesh mesh = new GVRMesh(gvrContext, "float3 a_position float2 a_texcoord float3 a_normal");
mesh.setVertices(vertices);
mesh.setNormals(normals);
mesh.setTexCoords(texCoords);
mesh.setIndices(indices);
GVRSceneObject childObject = new GVRSceneObject(gvrContext,
mesh);
childObject.getRenderData().setMaterial(material);
addChildObject(childObject);
vertexCount = 0;
texCoordCount = 0;
indexCount = 0;
triangleCount = 0;
}
}
}
}
| 20,792 |
3,102 |
<gh_stars>1000+
// RUN: %clang_cc1 -std=c++2a -emit-header-module -fmodule-name=attrs -x c++-header %S/Inputs/empty.h %S/Inputs/attrs.h -o %t.pcm
// RUN: %clang_cc1 -std=c++2a %s -fmodule-file=%t.pcm -E -verify -I%S/Inputs | FileCheck %s
#define SEMI ;
// expected-error@+1 {{semicolon terminating header import declaration cannot be produced by a macro}}
import "empty.h" SEMI // CHECK: import attrs.{{.*}};
#define IMPORT import "empty.h"
IMPORT; // CHECK: import attrs.{{.*}};
#define IMPORT_ANGLED import <empty.h>
IMPORT_ANGLED; // CHECK: import attrs.{{.*}};
// Ensure that macros only become visible at the semicolon.
// CHECK: import attrs.{{.*}} ATTRS ;
import "attrs.h" ATTRS ;
// CHECK: {{\[\[}} ]] int n;
ATTRS int n;
| 300 |
629 |
//
// File: imgdgdbadbaihlng_xnrm2.cpp
//
// Code generated for Simulink model 'est_estimator'.
//
// Model version : 1.1142
// Simulink Coder version : 8.11 (R2016b) 25-Aug-2016
// C/C++ source code generated on : Tue Oct 16 10:06:07 2018
//
#include "rtwtypes.h"
#include <math.h>
#include "imgdgdbadbaihlng_xnrm2.h"
// Function for MATLAB Function: '<S17>/Compute Residual and H'
real32_T imgdgdbadbaihlng_xnrm2(const real32_T x[4])
{
real32_T y;
real32_T scale;
real32_T absxk;
real32_T t;
scale = 1.17549435E-38F;
absxk = (real32_T)fabs((real_T)x[0]);
if (absxk > 1.17549435E-38F) {
y = 1.0F;
scale = absxk;
} else {
t = absxk / 1.17549435E-38F;
y = t * t;
}
absxk = (real32_T)fabs((real_T)x[1]);
if (absxk > scale) {
t = scale / absxk;
y = y * t * t + 1.0F;
scale = absxk;
} else {
t = absxk / scale;
y += t * t;
}
return scale * (real32_T)sqrt((real_T)y);
}
//
// File trailer for generated code.
//
// [EOF]
//
| 508 |
839 |
/**
* 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.cxf.message;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.cxf.Bus;
import org.apache.cxf.binding.Binding;
import org.apache.cxf.endpoint.ConduitSelector;
import org.apache.cxf.endpoint.Endpoint;
import org.apache.cxf.endpoint.PreexistingConduitSelector;
import org.apache.cxf.service.Service;
import org.apache.cxf.service.model.BindingInfo;
import org.apache.cxf.service.model.BindingOperationInfo;
import org.apache.cxf.service.model.InterfaceInfo;
import org.apache.cxf.service.model.OperationInfo;
import org.apache.cxf.service.model.ServiceInfo;
import org.apache.cxf.transport.Conduit;
import org.apache.cxf.transport.Destination;
import org.apache.cxf.transport.Session;
public class ExchangeImpl extends ConcurrentHashMap<String, Object> implements Exchange {
private static final long serialVersionUID = -3112077559217623594L;
private Destination destination;
private boolean oneWay;
private boolean synchronous = true;
private Message inMessage;
private Message outMessage;
private Message inFaultMessage;
private Message outFaultMessage;
private Session session;
private Bus bus;
private Endpoint endpoint;
private Service service;
private Binding binding;
private BindingOperationInfo bindingOp;
public ExchangeImpl() {
}
public ExchangeImpl(ExchangeImpl ex) {
super(ex);
this.destination = ex.destination;
this.oneWay = ex.oneWay;
this.synchronous = ex.synchronous;
this.inMessage = ex.inMessage;
this.outMessage = ex.outMessage;
this.inFaultMessage = ex.inFaultMessage;
this.outFaultMessage = ex.outFaultMessage;
this.session = ex.session;
this.bus = ex.bus;
this.endpoint = ex.endpoint;
this.service = ex.service;
this.binding = ex.binding;
this.bindingOp = ex.bindingOp;
}
private void resetContextCaches() {
if (inMessage != null) {
inMessage.resetContextCache();
}
if (outMessage != null) {
outMessage.resetContextCache();
}
if (inFaultMessage != null) {
inFaultMessage.resetContextCache();
}
if (outFaultMessage != null) {
outFaultMessage.resetContextCache();
}
}
public <T> T get(Class<T> key) {
T t = key.cast(get(key.getName()));
if (t == null) {
if (key == Bus.class) {
t = key.cast(bus);
} else if (key == OperationInfo.class && bindingOp != null) {
t = key.cast(bindingOp.getOperationInfo());
} else if (key == BindingOperationInfo.class) {
t = key.cast(bindingOp);
} else if (key == Endpoint.class) {
t = key.cast(endpoint);
} else if (key == Service.class) {
t = key.cast(service);
} else if (key == Binding.class) {
t = key.cast(binding);
} else if (key == BindingInfo.class && binding != null) {
t = key.cast(binding.getBindingInfo());
} else if (key == InterfaceInfo.class && endpoint != null) {
t = key.cast(endpoint.getEndpointInfo().getService().getInterface());
} else if (key == ServiceInfo.class && endpoint != null) {
t = key.cast(endpoint.getEndpointInfo().getService());
}
}
return t;
}
public void putAll(Map<? extends String, ?> m) {
for (Map.Entry<? extends String, ?> e : m.entrySet()) {
// just skip the null value to void the NPE in JDK1.8
if (e.getValue() != null) {
super.put(e.getKey(), e.getValue());
}
}
}
public <T> void put(Class<T> key, T value) {
if (value == null) {
super.remove((Object)key);
} else if (key == Bus.class) {
resetContextCaches();
bus = (Bus)value;
} else if (key == Endpoint.class) {
resetContextCaches();
endpoint = (Endpoint)value;
} else if (key == Service.class) {
resetContextCaches();
service = (Service)value;
} else if (key == BindingOperationInfo.class) {
bindingOp = (BindingOperationInfo)value;
} else if (key == Binding.class) {
binding = (Binding)value;
} else {
super.put(key.getName(), value);
}
}
public Object put(String key, Object value) {
setMessageContextProperty(inMessage, key, value);
setMessageContextProperty(outMessage, key, value);
setMessageContextProperty(inFaultMessage, key, value);
setMessageContextProperty(outFaultMessage, key, value);
if (value == null) {
return super.remove(key);
}
return super.put(key, value);
}
public <T> T remove(Class<T> key) {
return key.cast(super.remove(key.getName()));
}
private void setMessageContextProperty(Message m, String key, Object value) {
if (m == null) {
return;
}
if (m instanceof MessageImpl) {
((MessageImpl)m).setContextualProperty(key, value);
} else if (m instanceof AbstractWrappedMessage) {
((AbstractWrappedMessage)m).setContextualProperty(key, value);
} else {
//cannot set directly. Just invalidate the cache.
m.resetContextCache();
}
}
public Destination getDestination() {
return destination;
}
public Message getInMessage() {
return inMessage;
}
public Conduit getConduit(Message message) {
return get(ConduitSelector.class) != null
? get(ConduitSelector.class).selectConduit(message)
: null;
}
public Message getOutMessage() {
return outMessage;
}
public Message getInFaultMessage() {
return inFaultMessage;
}
public void setInFaultMessage(Message m) {
inFaultMessage = m;
if (null != m) {
m.setExchange(this);
}
}
public Message getOutFaultMessage() {
return outFaultMessage;
}
public void setOutFaultMessage(Message m) {
outFaultMessage = m;
if (null != m) {
m.setExchange(this);
}
}
public void setDestination(Destination d) {
destination = d;
}
public void setInMessage(Message m) {
inMessage = m;
if (null != m) {
m.setExchange(this);
}
}
public void setConduit(Conduit c) {
put(ConduitSelector.class,
new PreexistingConduitSelector(c, getEndpoint()));
}
public void setOutMessage(Message m) {
outMessage = m;
if (null != m) {
m.setExchange(this);
}
}
public boolean isOneWay() {
return oneWay;
}
public void setOneWay(boolean b) {
oneWay = b;
}
public boolean isSynchronous() {
return synchronous;
}
public void setSynchronous(boolean b) {
synchronous = b;
}
public Session getSession() {
return session;
}
public void setSession(Session session) {
this.session = session;
}
public void clear() {
super.clear();
resetContextCaches();
destination = null;
oneWay = false;
inMessage = null;
outMessage = null;
inFaultMessage = null;
outFaultMessage = null;
session = null;
bus = null;
}
public Bus getBus() {
return bus;
}
public Endpoint getEndpoint() {
return endpoint;
}
public Service getService() {
return service;
}
public Binding getBinding() {
return binding;
}
public BindingOperationInfo getBindingOperationInfo() {
return bindingOp;
}
}
| 3,713 |
764 |
<reponame>641589523/token-profile
{"symbol": "INS","address": "0x5B2e4a700dfBc560061e957edec8F6EeEb74a320","overview":{"en": ""},"email": "<EMAIL>","website": "https://insolar.io/","state": "NORMAL","links": {"blog": "https://medium.com/insolar","twitter": "https://twitter.com/insolario","telegram": "https://t.me/insolar","github": "https://github.com/insolar"}}
| 141 |
386 |
<gh_stars>100-1000
##########################################################################
#
# Copyright (c) 2007-2013, Image Engine Design Inc. All rights reserved.
#
# Copyright 2010 Dr D Studios Pty Limited (ACN 127 184 954) (Dr. D Studios),
# its affiliates and/or its licensors.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# * Neither the name of Image Engine Design nor the names of any
# other contributors to this software may be used to endorse or
# promote products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
##########################################################################
import unittest
import os
import imath
import IECore
class TestParameter( unittest.TestCase ) :
def testConstructor( self ) :
p = IECore.Parameter( "name", "description", IECore.FloatData( 1 ) )
self.assertEqual( p.name, "name" )
self.assertEqual( p.description, "description" )
self.assertEqual( p.defaultValue, IECore.FloatData( 1 ) )
self.assertEqual( p.getValue(), p.defaultValue )
self.assertEqual( p.getCurrentPresetName(), "" )
self.assertEqual (p.userData(), IECore.CompoundObject() )
v = IECore.IntData( 2 )
p.setValue( v )
self.assertEqual( p.getValue(), v )
self.assertRaises( RuntimeError, IECore.Parameter, "name", "description", None ) # passing None as default value should raise exception as opposed to segfault!
def testUserData( self ):
compound = IECore.CompoundObject()
compound["first"] = IECore.IntData()
compound["second"] = IECore.QuatfData()
compound["third"] = IECore.StringData("test")
p = IECore.Parameter( "name", "description", IECore.FloatData( 1 ), userData = compound )
self.assertEqual( p.userData(), compound )
self.assertTrue(not p.userData().isSame(compound) )
data = p.userData()
data["fourth"] = IECore.CharData('1')
data["first"] = data["fourth"]
def testKeywordConstructor( self ) :
p = IECore.Parameter(
name = "n",
description = "d",
defaultValue = IECore.FloatData( 20 )
)
self.assertEqual( p.name, "n" )
self.assertEqual( p.description, "d" )
self.assertEqual( p.defaultValue, IECore.FloatData( 20 ) )
self.assertEqual( p.getValue(), p.defaultValue )
def testPresets( self ) :
# Presets as tuple
p = IECore.Parameter(
name = "n",
description = "d",
defaultValue = IECore.FloatData( 20 ),
presets = (
( "p1", IECore.FloatData( 40 ) ),
( "p2", IECore.IntData( 60 ) ),
( "p3", IECore.CompoundData() ),
( "p4", IECore.FloatData( 20 ) ),
),
presetsOnly = True,
)
pr = p.getPresets()
self.assertEqual( len( pr ), 4 )
self.assertEqual( pr["p1"], IECore.FloatData( 40 ) )
self.assertEqual( pr["p2"], IECore.IntData( 60 ) )
self.assertEqual( pr["p3"], IECore.CompoundData() )
self.assertEqual( pr["p4"], IECore.FloatData( 20 ) )
for k, v in pr.items() :
p.setValue( k )
self.assertEqual( p.getValue(), v )
self.assertEqual( p.getCurrentPresetName(), k )
self.assertRaises( RuntimeError, p.setValue, "thisIsNotAPreset" )
self.assertRaises( RuntimeError, p.setValidatedValue, IECore.FloatData( 1000 ) )
# Presets as list
p = IECore.Parameter(
name = "n",
description = "d",
defaultValue = IECore.FloatData( 20 ),
presets = [
( "p1", IECore.FloatData( 40 ) ),
( "p2", IECore.IntData( 60 ) ),
( "p3", IECore.CompoundData() ),
( "p4", IECore.FloatData( 20 ) ),
],
presetsOnly = True,
)
pr = p.getPresets()
self.assertEqual( len( pr ), 4 )
self.assertEqual( pr["p1"], IECore.FloatData( 40 ) )
self.assertEqual( pr["p2"], IECore.IntData( 60 ) )
self.assertEqual( pr["p3"], IECore.CompoundData() )
self.assertEqual( pr["p4"], IECore.FloatData( 20 ) )
# overriding presets
p.setPresets( [] )
self.assertEqual( p.getPresets(), dict() )
p.setPresets(
[
( "p5", IECore.FloatData( 40 ) ),
( "p1", IECore.IntData( 60 ) ),
]
)
pr = p.getPresets()
self.assertEqual( len( pr ), 2 )
self.assertEqual( pr["p5"], IECore.FloatData( 40 ) )
self.assertEqual( pr["p1"], IECore.IntData( 60 ) )
self.assertEqual( p.presetNames(), ("p5", "p1") )
p.setValue("p1")
self.assertEqual( p.getValue(), IECore.IntData(60) )
def testOrderedPresets( self ) :
p = IECore.Parameter(
name = "n",
description = "d",
defaultValue = IECore.FloatData( 20 ),
presets = (
( "p1", IECore.FloatData( 40 ) ),
( "p2", IECore.IntData( 60 ) ),
( "p3", IECore.CompoundData() ),
( "p4", IECore.FloatData( 20 ) ),
),
presetsOnly = True,
)
self.assertEqual( p.presetNames(), ( "p1", "p2", "p3", "p4" ) )
self.assertEqual( p.presetValues(), ( IECore.FloatData( 40 ), IECore.IntData( 60 ), IECore.CompoundData(), IECore.FloatData( 20 ) ) )
def testRunTimeTyping( self ) :
c = IECore.IntParameter(
name = "i",
description = "d",
defaultValue = 10,
)
self.assertEqual( c.typeId(), IECore.TypeId.IntParameter )
self.assertEqual( c.typeName(), "IntParameter" )
self.assertTrue( c.isInstanceOf( "IntParameter" ) )
self.assertTrue( c.isInstanceOf( "Parameter" ) )
self.assertTrue( c.isInstanceOf( IECore.TypeId.IntParameter ) )
self.assertTrue( c.isInstanceOf( IECore.TypeId.Parameter ) )
c = IECore.V3fParameter(
name = "i",
description = "d",
defaultValue = imath.V3f( 1 ),
)
self.assertEqual( c.typeId(), IECore.TypeId.V3fParameter )
self.assertEqual( c.typeName(), "V3fParameter" )
self.assertTrue( c.isInstanceOf( "V3fParameter" ) )
self.assertTrue( c.isInstanceOf( "Parameter" ) )
self.assertTrue( c.isInstanceOf( IECore.TypeId.V3fParameter ) )
self.assertTrue( c.isInstanceOf( IECore.TypeId.Parameter ) )
def testSmartSetValue( self ):
"""Test python overwriting: smartSetValue()"""
p = IECore.Parameter( "p", "description", IECore.FloatData( 1 ) )
q = IECore.Parameter( "q", "description", IECore.IntData( 2 ) )
self.assertTrue( p.getValue() == IECore.FloatData( 1 ) )
p.smartSetValue( q.getValue() )
self.assertTrue( p.getValue() == IECore.IntData( 2 ) )
def testNoneIsValid( self ) :
p = IECore.Parameter( "p", "description", IECore.FloatData( 1 ) )
self.assertFalse( p.valueValid( None )[0] )
class TestNumericParameter( unittest.TestCase ) :
def testConstructor( self ) :
p = IECore.IntParameter( "name", "description", 1 )
self.assertEqual( p.name, "name" )
self.assertEqual( p.description, "description" )
self.assertEqual( p.defaultValue, IECore.IntData( 1 ) )
self.assertEqual( p.getValue(), p.defaultValue )
self.assertEqual (p.userData(), IECore.CompoundObject() )
p = IECore.IntParameter( "name", "description", 5, 0, 10 )
self.assertEqual( p.name, "name" )
self.assertEqual( p.description, "description" )
self.assertEqual( p.defaultValue, IECore.IntData( 5 ) )
self.assertEqual( p.numericDefaultValue, 5 )
self.assertEqual( p.getValue(), p.defaultValue )
self.assertEqual( p.minValue, 0 )
self.assertEqual( p.maxValue, 10 )
self.assertRaises( RuntimeError, IECore.IntParameter, "name", "description", 15, 0, 10 )
def testUserData( self ):
compound = IECore.CompoundObject()
compound["first"] = IECore.IntData()
compound["second"] = IECore.QuatfData()
compound["third"] = IECore.StringData("test")
p = IECore.IntParameter( "name", "description", 1, userData = compound )
self.assertEqual( p.userData(), compound )
self.assertTrue(not p.userData().isSame(compound) )
data = p.userData()
data["fourth"] = IECore.CharData('1')
data["first"] = data["fourth"]
def testKeywordConstructor( self ) :
p = IECore.IntParameter(
name = "name",
description = "description",
defaultValue = 1,
)
self.assertEqual( p.name, "name" )
self.assertEqual( p.description, "description" )
self.assertEqual( p.defaultValue, IECore.IntData( 1 ) )
self.assertEqual( p.getValue(), p.defaultValue )
p = IECore.IntParameter(
name = "name",
description = "description",
defaultValue = 1,
minValue = -10,
maxValue = 10,
)
self.assertEqual( p.name, "name" )
self.assertEqual( p.description, "description" )
self.assertEqual( p.defaultValue, IECore.IntData( 1 ) )
self.assertEqual( p.getValue(), p.defaultValue )
self.assertEqual( p.minValue, -10 )
self.assertEqual( p.maxValue, 10 )
self.assertTrue( p.hasMinValue() )
self.assertTrue( p.hasMaxValue() )
p = IECore.IntParameter(
name = "name",
description = "description",
defaultValue = 1,
minValue = -10
)
self.assertTrue( p.hasMinValue() )
self.assertFalse( p.hasMaxValue() )
p = IECore.IntParameter(
name = "name",
description = "description",
defaultValue = 1,
maxValue = 10
)
self.assertFalse( p.hasMinValue() )
self.assertTrue( p.hasMaxValue() )
def testLimits( self ) :
p = IECore.FloatParameter( "n", "d", 0, -100, 100 )
self.assertRaises( Exception, p.setValidatedValue, IECore.FloatData( -1000 ) )
self.assertRaises( Exception, p.setValidatedValue, IECore.FloatData( 101 ) )
self.assertRaises( Exception, p.setValidatedValue, IECore.IntData( 0 ) )
p.setValue( IECore.FloatData( 10 ) )
def testPresets( self ) :
p = IECore.IntParameter(
name = "n",
description = "d",
presets = (
( "one", 1 ),
( "two", 2 ),
( "three", 3 ),
)
)
pr = p.getPresets()
self.assertEqual( len( pr ), 3 )
self.assertEqual( pr["one"], IECore.IntData( 1 ) )
self.assertEqual( pr["two"], IECore.IntData( 2 ) )
self.assertEqual( pr["three"], IECore.IntData( 3 ) )
# overriding presets
p.setPresets(
[
( "four", IECore.IntData( 4 ) ),
( "one", IECore.IntData( 1 ) ),
]
)
pr = p.getPresets()
self.assertEqual( len( pr ), 2 )
self.assertEqual( pr["four"], IECore.IntData( 4 ) )
self.assertEqual( pr["one"], IECore.IntData( 1 ) )
self.assertEqual( p.presetNames(), ("four", "one") )
p.setValue("four")
self.assertEqual( p.getValue(), IECore.IntData(4) )
def testOrderedPresets( self ) :
p = IECore.IntParameter(
name = "n",
description = "d",
defaultValue = 1,
presets = (
( "p1", 10 ),
( "p2", 1 ),
( "p3", 20 ),
( "p4", 30 ),
),
presetsOnly = True,
)
self.assertEqual( p.presetNames(), ( "p1", "p2", "p3", "p4" ) )
self.assertEqual( p.presetValues(), ( IECore.IntData( 10 ), IECore.IntData( 1 ), IECore.IntData( 20 ), IECore.IntData( 30 ) ) )
def testSetGet( self ) :
p = IECore.IntParameter( "name", "description", 1 )
p.setValue( IECore.IntData( 10 ) )
self.assertEqual( p.getValue(), IECore.IntData( 10 ) )
self.assertEqual( p.getNumericValue(), 10 )
p.setNumericValue( 20 )
self.assertEqual( p.getValue(), IECore.IntData( 20 ) )
self.assertEqual( p.getNumericValue(), 20 )
def testSmartSetValue( self ):
"""Test python overwriting: smartSetValue()"""
p = IECore.IntParameter( "p", "description", 1 )
q = IECore.IntParameter( "q", "description", 2 )
self.assertTrue( p.getValue() == IECore.IntData( 1 ) )
p.smartSetValue( q.getValue() )
self.assertTrue( p.getValue() == IECore.IntData( 2 ) )
p.smartSetValue( 3 )
self.assertTrue( p.getValue() == IECore.IntData( 3 ) )
p.smartSetValue( IECore.IntData(4) )
self.assertTrue( p.getValue() == IECore.IntData( 4 ) )
def testDefaultValue( self ) :
p = IECore.IntParameter( "p", "description", 1 )
self.assertEqual( p.numericDefaultValue, 1 )
self.assertRaises( AttributeError, setattr, p, "numericDefaultValue", 2 )
class TestTypedParameter( unittest.TestCase ) :
def testConstructor( self ) :
p = IECore.V2fParameter( "n", "d", imath.V2f( 10 ) )
self.assertEqual( p.name, "n" )
self.assertEqual( p.description, "d" )
self.assertEqual( p.defaultValue, IECore.V2fData( imath.V2f( 10 ) ) )
self.assertEqual( p.getValue(), IECore.V2fData( imath.V2f( 10 ) ) )
self.assertEqual (p.userData(), IECore.CompoundObject() )
def testUserData( self ):
compound = IECore.CompoundObject()
compound["first"] = IECore.IntData()
compound["second"] = IECore.QuatfData()
compound["third"] = IECore.StringData("test")
p = IECore.Box3dParameter( "name", "description", imath.Box3d(), userData = compound )
self.assertEqual( p.userData(), compound )
self.assertTrue(not p.userData().isSame(compound) )
data = p.userData()
data["fourth"] = IECore.CharData('1')
data["first"] = data["fourth"]
def testPresets( self ) :
p = IECore.V3fParameter(
name = "n",
description = "d",
defaultValue = imath.V3f( 2 ),
presets = (
( "one", imath.V3f( 1 ) ),
( "two", imath.V3f( 2 ) ),
( "three", imath.V3f( 3 ) ),
),
presetsOnly = True,
)
pr = p.getPresets()
self.assertEqual( len( pr ), 3 )
self.assertEqual( pr["one"], IECore.V3fData( imath.V3f( 1 ) ) )
self.assertEqual( pr["two"], IECore.V3fData( imath.V3f( 2 ) ) )
self.assertEqual( pr["three"], IECore.V3fData( imath.V3f( 3 ) ) )
p.setValue( "one" )
self.assertEqual( p.getValue(), IECore.V3fData( imath.V3f( 1 ) ) )
# overriding presets
p.setPresets(
[
( "four", IECore.V3fData( imath.V3f(4) ) ),
( "one", IECore.V3fData( imath.V3f(1) ) ),
]
)
pr = p.getPresets()
self.assertEqual( len( pr ), 2 )
self.assertEqual( pr["four"], IECore.V3fData( imath.V3f(4) ) )
self.assertEqual( pr["one"], IECore.V3fData( imath.V3f(1) ) )
self.assertEqual( p.presetNames(), ("four", "one") )
p.setValue("four")
self.assertEqual( p.getValue(), IECore.V3fData(imath.V3f(4)) )
def testPresetsOnly( self ) :
p = IECore.V3fParameter(
name = "n",
description = "d",
defaultValue = imath.V3f( 2 ),
presets = (
( "one", imath.V3f( 1 ) ),
( "two", imath.V3f( 2 ) ),
( "three", imath.V3f( 3 ) ),
),
presetsOnly = True,
)
self.assertRaises( RuntimeError, p.setValidatedValue, IECore.V3fData( imath.V3f( 20 ) ) )
p = IECore.V3fParameter(
name = "n",
description = "d",
defaultValue = imath.V3f( 2 ),
presets = (
( "one", imath.V3f( 1 ) ),
( "two", imath.V3f( 2 ) ),
( "three", imath.V3f( 3 ) ),
),
presetsOnly = False,
)
p.setValue( IECore.V3fData( imath.V3f( 20 ) ) )
def testTypedValueFns( self ) :
p = IECore.StringParameter( name="n", description="d", defaultValue = "10" )
self.assertEqual( p.getTypedValue(), "10" )
p.setTypedValue( "20" )
self.assertEqual( p.getTypedValue(), "20" )
self.assertEqual( p.typedDefaultValue, "10" )
self.assertRaises( AttributeError, setattr, p, "typedDefaultValue", "20" )
p = IECore.V3fParameter( name="n", description="d", defaultValue = imath.V3f( 1, 2, 3 ) )
self.assertEqual( p.getTypedValue(), imath.V3f( 1, 2, 3 ) )
p.setTypedValue( imath.V3f( 12, 13, 14 ) )
self.assertEqual( p.getTypedValue(), imath.V3f( 12, 13, 14 ) )
self.assertEqual( p.getValue(), IECore.V3fData( imath.V3f( 12, 13, 14 ) ) )
self.assertEqual( p.typedDefaultValue, imath.V3f( 1, 2, 3 ) )
self.assertRaises( AttributeError, setattr, p, "typedDefaultValue", imath.V3f( 4, 5, 6 ) )
def testSmartSetValue( self ):
"""Test python overwriting: smartSetValue()"""
p = IECore.V2fParameter( "p", "description", imath.V2f( 10 ) )
q = IECore.V2fParameter( "q", "description", imath.V2f( 2 ) )
self.assertTrue( p.getValue() == IECore.V2fData( imath.V2f( 10 ) ) )
p.smartSetValue( q.getValue() )
self.assertTrue( p.getValue() == IECore.V2fData( imath.V2f( 2 ) ) )
p.smartSetValue( imath.V2f( 3 ) )
self.assertTrue( p.getValue() == IECore.V2fData( imath.V2f( 3 ) ) )
p.smartSetValue( IECore.V2fData( imath.V2f( 4 ) ) )
self.assertTrue( p.getValue() == IECore.V2fData( imath.V2f( 4 ) ) )
def testOrderedPresets( self ) :
p = IECore.StringParameter(
name = "n",
description = "d",
defaultValue = "huh?",
presets = (
( "p1", "a" ),
( "p2", IECore.StringData( "b" ) ),
( "p3", "c" ),
( "p4", "d" ),
),
presetsOnly = True,
)
self.assertEqual( p.presetNames(), ( "p1", "p2", "p3", "p4" ) )
self.assertEqual( p.presetValues(), ( IECore.StringData( "a" ), IECore.StringData( "b" ), IECore.StringData( "c" ), IECore.StringData( "d" ) ) )
def testInterpretation( self ) :
p = IECore.V3fParameter( name="n", description="d", defaultValue = imath.V3f( 1, 2, 3 ) )
self.assertEqual( p.defaultValue, IECore.V3fData( imath.V3f( 1, 2, 3 ) ) )
self.assertEqual( p.defaultValue.getInterpretation(), IECore.GeometricData.Interpretation.None_ )
self.assertEqual( p.getValue(), IECore.V3fData( imath.V3f( 1, 2, 3 ) ) )
self.assertEqual( p.getValue().getInterpretation(), IECore.GeometricData.Interpretation.None_ )
value = IECore.V3fData( imath.V3f( 12, 13, 14 ) )
value.setInterpretation( IECore.GeometricData.Interpretation.Vector )
p.setValue( value )
self.assertNotEqual( p.getValue(), IECore.V3fData( imath.V3f( 12, 13, 14 ) ) )
self.assertEqual( p.getValue(), value )
self.assertEqual( p.getValue().getInterpretation(), IECore.GeometricData.Interpretation.Vector )
dv = IECore.V3fData( imath.V3f( 1, 2, 3 ), IECore.GeometricData.Interpretation.Normal )
p = IECore.V3fParameter( name="n", description="d", defaultValue = dv )
self.assertNotEqual( p.defaultValue, IECore.V3fData( imath.V3f( 1, 2, 3 ) ) )
self.assertEqual( p.defaultValue, dv )
self.assertEqual( p.defaultValue.getInterpretation(), IECore.GeometricData.Interpretation.Normal )
self.assertNotEqual( p.getValue(), IECore.V3fData( imath.V3f( 1, 2, 3 ) ) )
self.assertEqual( p.getValue(), dv )
self.assertEqual( p.getValue().getInterpretation(), IECore.GeometricData.Interpretation.Normal )
dv = IECore.V3fVectorData( [ imath.V3f( 1, 2, 3 ) ], IECore.GeometricData.Interpretation.Normal )
p = IECore.V3fVectorParameter( name="n", description="d", defaultValue = dv )
self.assertNotEqual( p.defaultValue, IECore.V3fVectorData( [ imath.V3f( 1, 2, 3 ) ] ) )
self.assertEqual( p.defaultValue, dv )
self.assertEqual( p.defaultValue.getInterpretation(), IECore.GeometricData.Interpretation.Normal )
self.assertNotEqual( p.getValue(), IECore.V3fVectorData( [ imath.V3f( 1, 2, 3 ) ] ) )
self.assertEqual( p.getValue(), dv )
self.assertEqual( p.getValue().getInterpretation(), IECore.GeometricData.Interpretation.Normal )
p.setValue( IECore.V3fVectorData( [ imath.V3f( 12, 13, 14 ) ] ) )
self.assertEqual( p.getValue(), IECore.V3fVectorData( [ imath.V3f( 12, 13, 14 ) ] ) )
self.assertEqual( p.getValue().getInterpretation(), IECore.GeometricData.Interpretation.None_ )
class TestValidatedStringParameter( unittest.TestCase ) :
def test( self ) :
p = IECore.ValidatedStringParameter(
name = "n",
description = "d",
regex = "[0-9]*",
regexDescription = "Value must be an integer",
presets = (
( "100", "100" ),
( "200", "200" ),
)
)
self.assertEqual( p.name, "n" )
self.assertEqual( p.description, "d" )
self.assertEqual( p.regex, "[0-9]*" )
self.assertEqual (p.userData(), IECore.CompoundObject() )
self.assertRaises( RuntimeError, p.setValidatedValue, IECore.StringData( "A" ) )
p.setValue( IECore.StringData( "100" ) )
self.assertEqual( p.getValue(), IECore.StringData( "100" ) )
pr = p.getPresets()
self.assertEqual( len( pr ), 2 )
self.assertTrue( "100" in pr.keys() )
self.assertTrue( "200" in pr.keys() )
def testUserData( self ):
compound = IECore.CompoundObject()
compound["first"] = IECore.IntData()
compound["second"] = IECore.QuatfData()
compound["third"] = IECore.StringData("test")
p = IECore.ValidatedStringParameter(
name = "n",
description = "d",
regex = "[0-9]*",
regexDescription = "Value must be an integer",
userData = compound
)
self.assertEqual( p.userData(), compound )
self.assertTrue(not p.userData().isSame(compound) )
data = p.userData()
data["fourth"] = IECore.CharData('1')
data["first"] = data["fourth"]
def testOrderedPresets( self ) :
p = IECore.ValidatedStringParameter(
name = "n",
description = "d",
regex = "*",
regexDescription = "",
defaultValue = "huh?",
presets = (
( "p1", "a" ),
( "p2", "b" ),
( "p3", "c" ),
( "p4", "d" ),
),
presetsOnly = True,
)
self.assertEqual( p.presetNames(), ( "p1", "p2", "p3", "p4" ) )
self.assertEqual( p.presetValues(), ( IECore.StringData( "a" ), IECore.StringData( "b" ), IECore.StringData( "c" ), IECore.StringData( "d" ) ) )
class TestDirNameParameter( unittest.TestCase ) :
def test( self ) :
p = IECore.DirNameParameter(
name = "f",
description = "d",
defaultValue = "test",
check = IECore.DirNameParameter.CheckType.MustExist,
allowEmptyString = True
)
self.assertEqual( p.name, "f" )
self.assertEqual( p.description, "d" )
self.assertEqual( p.mustExist, True )
self.assertEqual( p.allowEmptyString, True )
self.assertEqual (p.userData(), IECore.CompoundObject() )
self.assertEqual( p.valueValid()[0], True )
p.validate()
def testMustNotExist( self ):
p = IECore.DirNameParameter(
name = "f",
description = "d",
defaultValue = "/lucioSaysThisDirectoryDoesNotExist",
check = IECore.DirNameParameter.CheckType.MustExist,
allowEmptyString = True,
)
self.assertRaises( RuntimeError, p.validate )
class TestFileNameParameter( unittest.TestCase ) :
def test( self ) :
p = IECore.FileNameParameter(
name = "f",
description = "d",
extensions = "tif tiff jpg cin",
check = IECore.FileNameParameter.CheckType.DontCare,
allowEmptyString = True
)
self.assertEqual( p.name, "f" )
self.assertEqual( p.description, "d" )
self.assertEqual( p.extensions, [ "tif", "tiff", "jpg", "cin" ] )
self.assertEqual( p.mustExist, False )
self.assertEqual( p.allowEmptyString, True )
self.assertEqual (p.userData(), IECore.CompoundObject() )
for e in p.extensions :
p.setValidatedValue( IECore.StringData("hello." + e) )
p.setValue( IECore.StringData( "test" ) )
self.assertRaises( RuntimeError, p.validate )
def testUserData( self ):
compound = IECore.CompoundObject()
compound["first"] = IECore.IntData()
compound["second"] = IECore.QuatfData()
compound["third"] = IECore.StringData("test")
p = IECore.FileNameParameter(
name = "f",
description = "d",
extensions = "tif tiff jpg cin",
check = IECore.FileNameParameter.CheckType.DontCare,
allowEmptyString = True,
userData = compound
)
self.assertEqual( p.userData(), compound )
self.assertTrue(not p.userData().isSame(compound) )
data = p.userData()
data["fourth"] = IECore.CharData('1')
data["first"] = data["fourth"]
def testNoExtensions( self ) :
p = IECore.FileNameParameter(
name = "f",
description = "d",
)
self.assertEqual( p.extensions, [] )
p.setValue( IECore.StringData( "hello.tif" ) )
p.setValue( IECore.StringData( "hello" ) )
def testNotADirectory( self ) :
p = IECore.FileNameParameter(
name = "f",
description = "d",
defaultValue = "test",
check = IECore.FileNameParameter.CheckType.MustExist,
allowEmptyString = True
)
self.assertRaises( RuntimeError, p.validate )
self.assertEqual( p.valueValid()[0], False )
class TestValidation( unittest.TestCase ) :
def test( self ) :
i = IECore.IntParameter( name = "n", description = "d", defaultValue = 10 )
self.assertTrue( i.valueValid( IECore.IntData( 1 ) ) )
self.assertTrue( not i.valueValid( IECore.FloatData( 1 ) )[0] )
def testLazyValidation( self ) :
i = IECore.IntParameter( name = "n", description = "d", defaultValue = 10 )
i.validate( IECore.IntData( 10 ) )
self.assertRaises( RuntimeError, i.validate, IECore.FloatData( 20 ) )
i.setValue( IECore.IntData( 10 ) )
i.validate()
i.setValue( IECore.FloatData( 10 ) )
self.assertRaises( RuntimeError, i.validate )
self.assertRaises( RuntimeError, i.getValidatedValue )
i = IECore.V3fParameter( name = "n", description = "d", defaultValue = imath.V3f( 10 ) )
i.validate( IECore.V3fData( imath.V3f( 10 ) ) )
self.assertRaises( RuntimeError, i.validate, IECore.FloatData( 20 ) )
i.setValue( IECore.V3fData( imath.V3f( 20 ) ) )
i.validate()
i.setValue( IECore.FloatData( 10 ) )
self.assertRaises( RuntimeError, i.validate )
self.assertRaises( RuntimeError, i.getValidatedValue )
class TestObjectParameter( unittest.TestCase ) :
def testConstructor( self ) :
p = IECore.ObjectParameter( name = "name", description = "description", defaultValue = IECore.CompoundObject(), type = IECore.TypeId.CompoundObject )
self.assertEqual( p.name, "name" )
self.assertEqual( p.description, "description" )
self.assertEqual( p.defaultValue, IECore.CompoundObject() )
self.assertEqual( p.getValue(), p.defaultValue )
self.assertEqual( p.getCurrentPresetName(), "" )
self.assertEqual( p.validTypes(), [IECore.TypeId.CompoundObject] )
self.assertTrue( p.valueValid( IECore.CompoundObject() )[0] )
self.assertTrue( not p.valueValid( IECore.IntData( 1 ) )[0] )
def testConstructor2( self ) :
p = IECore.ObjectParameter( name = "name", description = "description", defaultValue = IECore.CompoundObject(), types = [ IECore.TypeId.CompoundObject, IECore.TypeId.FloatData ] )
self.assertEqual( p.name, "name" )
self.assertEqual( p.description, "description" )
self.assertEqual( p.defaultValue, IECore.CompoundObject() )
self.assertEqual( p.getValue(), p.defaultValue )
self.assertEqual( p.getCurrentPresetName(), "" )
self.assertEqual( len( p.validTypes() ), 2 )
self.assertTrue( IECore.TypeId.CompoundObject in p.validTypes() )
self.assertTrue( IECore.TypeId.FloatData in p.validTypes() )
self.assertTrue( p.valueValid( IECore.CompoundObject() )[0] )
self.assertTrue( p.valueValid( IECore.FloatData( 1 ) )[0] )
self.assertTrue( not p.valueValid( IECore.IntData( 1 ) )[0] )
def testUserData( self ) :
p = IECore.ObjectParameter( name = "name", description = "description", defaultValue = IECore.ObjectVector(), type = IECore.TypeId.ObjectVector, userData = IECore.CompoundObject( { "A" : IECore.IntData( 10 ) } ) )
self.assertEqual( p.userData(), IECore.CompoundObject( { "A" : IECore.IntData( 10 ) } ) )
p = IECore.ObjectParameter( name = "name", description = "description", defaultValue = IECore.ObjectVector(), type = IECore.TypeId.ObjectVector )
self.assertEqual (p.userData(), IECore.CompoundObject() )
def testErrorMessage( self ) :
p = IECore.ObjectParameter( name = "name", description = "description", defaultValue = IECore.FloatData( 1 ), types = [IECore.TypeId.FloatData] )
self.assertEqual( p.valueValid( IECore.V3fData( imath.V3f( 1 ) ) )[1], "Object is not of type FloatData" )
p = IECore.ObjectParameter( name = "name", description = "description", defaultValue = IECore.FloatData( 1 ), types = [IECore.TypeId.FloatData, IECore.TypeId.IntData] )
self.assertEqual( p.valueValid( IECore.V3fData( imath.V3f( 1 ) ) )[1], "Object is not of type FloatData or IntData" )
p = IECore.ObjectParameter( name = "name", description = "description", defaultValue = IECore.FloatData( 1 ), types = [IECore.TypeId.FloatData, IECore.TypeId.DoubleData, IECore.TypeId.IntData] )
self.assertEqual( p.valueValid( IECore.V3fData( imath.V3f( 1 ) ) )[1], "Object is not of type FloatData, DoubleData or IntData" )
def testOrderedPresets( self ) :
p = IECore.ObjectParameter(
name = "n",
description = "d",
defaultValue = IECore.FloatData( 20 ),
types = [ IECore.Object.staticTypeId() ],
presets = (
( "p1", IECore.FloatData( 40 ) ),
( "p2", IECore.IntData( 60 ) ),
( "p3", IECore.CompoundData() ),
( "p4", IECore.FloatData( 20 ) ),
),
presetsOnly = True,
)
self.assertEqual( p.presetNames(), ( "p1", "p2", "p3", "p4" ) )
self.assertEqual( p.presetValues(), ( IECore.FloatData( 40 ), IECore.IntData( 60 ), IECore.CompoundData(), IECore.FloatData( 20 ) ) )
# overriding presets
p.setPresets(
[
( "four", IECore.V3fData( imath.V3f(4) ) ),
( "one", IECore.V3fData( imath.V3f(1) ) ),
]
)
pr = p.getPresets()
self.assertEqual( len( pr ), 2 )
self.assertEqual( pr["four"], IECore.V3fData( imath.V3f(4) ) )
self.assertEqual( pr["one"], IECore.V3fData( imath.V3f(1) ) )
self.assertEqual( p.presetNames(), ("four", "one") )
p.setValue("four")
self.assertEqual( p.getValue(), IECore.V3fData(imath.V3f(4)) )
class TestTypedObjectParameter( unittest.TestCase ) :
def testConstructor( self ) :
objectVector = IECore.ObjectVector()
p = IECore.ObjectVectorParameter( "n", "d", objectVector )
self.assertEqual( p.name, "n" )
self.assertEqual( p.description, "d" )
self.assertEqual( p.defaultValue, objectVector )
self.assertEqual( p.getValue(), objectVector )
self.assertEqual( p.userData(), IECore.CompoundObject() )
def testUserData( self ):
compound = IECore.CompoundObject()
compound["first"] = IECore.IntData()
compound["second"] = IECore.QuatfData()
compound["third"] = IECore.StringData("test")
p = IECore.ObjectVectorParameter( "name", "description", IECore.ObjectVector(), userData = compound )
self.assertEqual( p.userData(), compound )
self.assertTrue(not p.userData().isSame(compound) )
data = p.userData()
data["fourth"] = IECore.CharData('1')
data["first"] = data["fourth"]
def testPresets( self ) :
preset1 = IECore.ObjectVector( [ IECore.IntData( 1 ) ] )
preset2 = IECore.ObjectVector( [ IECore.IntData( 2 ) ] )
preset3 = IECore.ObjectVector( [ IECore.IntData( 3 ) ] )
p = IECore.ObjectVectorParameter(
name = "n",
description = "d",
defaultValue = preset2,
presets = (
( "one", preset1 ),
( "two", preset2 ),
( "three", preset3 ),
),
presetsOnly = True,
)
pr = p.getPresets()
self.assertEqual( len( pr ), 3 )
self.assertEqual( pr["one"], preset1 )
self.assertEqual( pr["two"], preset2 )
self.assertEqual( pr["three"], preset3 )
p.setValue( "one" )
self.assertEqual( p.getValue(), preset1 )
def testPresetsOnly( self ) :
preset1 = IECore.ObjectVector( [ IECore.IntData( 1 ) ] )
preset2 = IECore.ObjectVector( [ IECore.IntData( 2 ) ] )
preset3 = IECore.ObjectVector( [ IECore.IntData( 3 ) ] )
four = IECore.ObjectVector( [ IECore.IntData( 4 ) ] )
p = IECore.ObjectVectorParameter(
name = "n",
description = "d",
defaultValue = preset2,
presets = (
( "one", preset1 ),
( "two", preset2 ),
( "three", preset3 ),
),
presetsOnly = True,
)
self.assertRaises( RuntimeError, p.setValidatedValue, four )
p = IECore.ObjectVectorParameter(
name = "n",
description = "d",
defaultValue = preset2,
presets = (
( "one", preset1 ),
( "two", preset2 ),
( "three", preset3 ),
),
presetsOnly = False,
)
p.setValidatedValue( four )
def testOrderedPresets( self ) :
p = IECore.ObjectVectorParameter(
name = "n",
description = "d",
defaultValue = IECore.ObjectVector( [ IECore.IntData( 1 ) ] ),
presets = (
( "p1", IECore.ObjectVector( [ IECore.IntData( 1 ) ] ) ),
( "p2", IECore.ObjectVector( [ IECore.IntData( 2 ) ] ) ),
( "p3", IECore.ObjectVector( [ IECore.IntData( 3 ) ] ) ),
( "p4", IECore.ObjectVector( [ IECore.IntData( 4 ) ] ) ),
),
presetsOnly = True,
)
self.assertEqual( p.presetNames(), ( "p1", "p2", "p3", "p4" ) )
self.assertEqual(
p.presetValues(),
(
IECore.ObjectVector( [ IECore.IntData( 1 ) ] ),
IECore.ObjectVector( [ IECore.IntData( 2 ) ] ),
IECore.ObjectVector( [ IECore.IntData( 3 ) ] ),
IECore.ObjectVector( [ IECore.IntData( 4 ) ] ),
)
)
class TestIntVectorParameter( unittest.TestCase ) :
def test( self ) :
dv = IECore.IntVectorData()
p = IECore.IntVectorParameter(
name = "f",
description = "d",
defaultValue = dv,
presets = (
( "preset1", IECore.IntVectorData( [ 1, 2 ] ) ),
)
)
self.assertEqual( p.name, "f" )
self.assertEqual( p.description, "d" )
self.assertEqual( p.userData(), IECore.CompoundObject() )
self.assertEqual( p.valueValid()[0], True )
p.validate()
class TestTransformationMatixParameter( unittest.TestCase ) :
def test( self ) :
tm = IECore.TransformationMatrixfData()
p = IECore.TransformationMatrixfParameter(
name = "f",
description = "d",
defaultValue = tm,
)
p.validate()
self.assertEqual( p.name, "f" )
self.assertEqual( p.description, "d" )
self.assertEqual( p.valueValid()[0], True )
self.assertTrue( isinstance( p.getTypedValue().translate, imath.V3f ) )
self.assertEqual( p.getTypedValue().translate, imath.V3f( 0,0,0 ) )
self.assertEqual( p.getTypedValue().rotate, imath.Eulerf( 0,0,0 ) )
self.assertEqual( p.getTypedValue().rotationOrientation, imath.Quatf( 1,0,0,0 ) )
self.assertEqual( p.getTypedValue().scale, imath.V3f( 1,1,1 ) )
self.assertEqual( p.getTypedValue().shear, imath.V3f( 0,0,0 ) )
self.assertEqual( p.getTypedValue().rotatePivot, imath.V3f( 0,0,0 ) )
self.assertEqual( p.getTypedValue().rotatePivotTranslation, imath.V3f( 0,0,0 ) )
self.assertEqual( p.getTypedValue().scalePivot, imath.V3f( 0,0,0 ) )
self.assertEqual( p.getTypedValue().scalePivotTranslation, imath.V3f( 0,0,0 ) )
tm = IECore.TransformationMatrixdData()
p = IECore.TransformationMatrixdParameter(
name = "f",
description = "d",
defaultValue = tm,
)
p.validate()
self.assertEqual( p.name, "f" )
self.assertEqual( p.description, "d" )
self.assertEqual( p.valueValid()[0], True )
self.assertTrue( isinstance( p.getTypedValue().translate, imath.V3d ) )
self.assertEqual( p.getTypedValue().translate, imath.V3d( 0,0,0 ) )
self.assertEqual( p.getTypedValue().rotate, imath.Eulerd( 0,0,0 ) )
self.assertEqual( p.getTypedValue().rotationOrientation, imath.Quatd( 1,0,0,0 ) )
self.assertEqual( p.getTypedValue().scale, imath.V3d( 1,1,1 ) )
self.assertEqual( p.getTypedValue().shear, imath.V3d( 0,0,0 ) )
self.assertEqual( p.getTypedValue().rotatePivot, imath.V3d( 0,0,0 ) )
self.assertEqual( p.getTypedValue().rotatePivotTranslation, imath.V3d( 0,0,0 ) )
self.assertEqual( p.getTypedValue().scalePivot, imath.V3d( 0,0,0 ) )
self.assertEqual( p.getTypedValue().scalePivotTranslation, imath.V3d( 0,0,0 ) )
class TestPathVectorParameter( unittest.TestCase ) :
def test( self ) :
dv = IECore.StringVectorData()
p = IECore.PathVectorParameter(
name = "f",
description = "d",
defaultValue = dv,
check = IECore.PathVectorParameter.CheckType.MustExist,
allowEmptyList = True,
presets = (
( "preset1", IECore.StringVectorData( [ 'one', 'two' ] ) ),
)
)
self.assertEqual( p.name, "f" )
self.assertEqual( p.description, "d" )
self.assertEqual( p.mustExist, True )
self.assertEqual( p.allowEmptyList, True )
self.assertEqual( p.userData(), IECore.CompoundObject() )
self.assertEqual( p.valueValid()[0], True )
p.validate()
def testMustNotExist( self ):
dv = IECore.StringVectorData()
dv.append( "/ThisDirectoryDoesNotExist " )
p = IECore.PathVectorParameter(
name = "f",
description = "d",
defaultValue = dv,
check = IECore.PathVectorParameter.CheckType.MustExist,
allowEmptyList = False,
)
self.assertRaises( RuntimeError, p.validate )
class TestFileSequenceVectorParameter( unittest.TestCase ) :
def test( self ) :
dv = IECore.StringVectorData()
p = IECore.FileSequenceVectorParameter(
name = "f",
description = "d",
defaultValue = dv,
check = IECore.FileSequenceVectorParameter.CheckType.MustExist,
allowEmptyList = True,
presets = (
( "preset1", IECore.StringVectorData( [ 'one', 'two' ] ) ),
)
)
self.assertEqual( p.name, "f" )
self.assertEqual( p.description, "d" )
self.assertEqual( p.mustExist, True )
self.assertEqual( p.allowEmptyList, True )
self.assertEqual( p.userData(), IECore.CompoundObject() )
self.assertEqual( p.valueValid()[0], True )
p.validate()
if __name__ == "__main__":
unittest.main()
| 15,367 |
369 |
<filename>inc/osvr/Common/NetworkingSupport.h<gh_stars>100-1000
/** @file
@brief Header
@date 2015
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2015 Sensics, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef INCLUDED_NetworkingSupport_h_GUID_A5FE2D05_48DC_469E_1013_F2B7736331F3
#define INCLUDED_NetworkingSupport_h_GUID_A5FE2D05_48DC_469E_1013_F2B7736331F3
// Internal Includes
#include <osvr/Common/Export.h>
// Library/third-party includes
#include <boost/noncopyable.hpp>
// Standard includes
#include <string>
namespace osvr {
namespace common {
/// @brief RAII class wrapping networking system startup
///
/// Basically, a clean way of calling WSAStartup() and WSACleanup() at the
/// right time.
class NetworkingSupport : boost::noncopyable {
public:
/// @brief Constructor
OSVR_COMMON_EXPORT NetworkingSupport();
/// @brief Destructor
OSVR_COMMON_EXPORT ~NetworkingSupport();
/// @brief Get whether the networking system is successfully "up"
bool isUp() const { return m_up; }
/// @brief Get whether the last operation (automatic startup or manual,
/// early shutdown) was successful.
bool wasSuccessful() const { return m_success; }
/// @brief Get error message, if any.
std::string const &getError() const { return m_err; }
/// @brief Shutdown before destruction
void shutdown();
private:
/// @brief Platform-specific implementation of starting behavior.
/// Returns success. Must set m_err on failure.
bool m_start();
/// @brief Platform-specific implementation of stopping behavior.
/// Returns success. Must set m_err on failure.
bool m_stop();
bool m_up;
bool m_success;
std::string m_err;
};
} // namespace common
} // namespace osvr
#endif // INCLUDED_NetworkingSupport_h_GUID_A5FE2D05_48DC_469E_1013_F2B7736331F3
| 900 |
2,868 |
<gh_stars>1000+
/*
* Copyright (c) 2016-2020, Intel Corporation
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Intel Corporation nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef MCSHENG_INTERNAL_H
#define MCSHENG_INTERNAL_H
#include "nfa_internal.h"
#include "ue2common.h"
#include "util/simd_types.h"
#define ACCEPT_FLAG 0x8000
#define ACCEL_FLAG 0x4000
#define STATE_MASK 0x3fff
#define SHERMAN_STATE 1
#define SHERMAN_TYPE_OFFSET 0
#define SHERMAN_FIXED_SIZE 32
#define SHERMAN_LEN_OFFSET 1
#define SHERMAN_DADDY_OFFSET 2
#define SHERMAN_CHARS_OFFSET 4
#define SHERMAN_STATES_OFFSET(sso_len) (4 + (sso_len))
struct report_list {
u32 count;
ReportID report[];
};
struct mstate_aux {
u32 accept;
u32 accept_eod;
u16 top;
u32 accel_offset; /* relative to start of struct mcsheng; 0 if no accel */
};
#define MCSHENG_FLAG_SINGLE 1 /**< we raise only single accept id */
struct mcsheng {
u16 state_count; /**< total number of states */
u32 length; /**< length of dfa in bytes */
u16 start_anchored; /**< anchored start state */
u16 start_floating; /**< floating start state */
u32 aux_offset; /**< offset of the aux structures relative to the start of
* the nfa structure */
u32 sherman_offset; /**< offset of array of sherman state offsets the
* state_info structures relative to the start of the
* nfa structure */
u32 sherman_end; /**< offset of the end of the state_info structures
* relative to the start of the nfa structure */
u16 sheng_end; /**< first non-sheng state */
u16 sheng_accel_limit; /**< first sheng accel state. state given in terms of
* internal sheng ids */
u16 accel_limit_8; /**< 8 bit, lowest accelerable state */
u16 accept_limit_8; /**< 8 bit, lowest accept state */
u16 sherman_limit; /**< lowest sherman state */
u8 alphaShift;
u8 flags;
u8 has_accel; /**< 1 iff there are any accel plans */
u8 remap[256]; /**< remaps characters to a smaller alphabet */
ReportID arb_report; /**< one of the accepts that this dfa may raise */
u32 accel_offset; /**< offset of accel structures from start of McClellan */
m128 sheng_masks[N_CHARS];
};
/* pext masks for the runtime to access appropriately copies of bytes 1..7
* representing the data from a u64a. */
extern const u64a mcsheng_pext_mask[8];
struct mcsheng64 {
u16 state_count; /**< total number of states */
u32 length; /**< length of dfa in bytes */
u16 start_anchored; /**< anchored start state */
u16 start_floating; /**< floating start state */
u32 aux_offset; /**< offset of the aux structures relative to the start of
* the nfa structure */
u32 sherman_offset; /**< offset of array of sherman state offsets the
* state_info structures relative to the start of the
* nfa structure */
u32 sherman_end; /**< offset of the end of the state_info structures
* relative to the start of the nfa structure */
u16 sheng_end; /**< first non-sheng state */
u16 sheng_accel_limit; /**< first sheng accel state. state given in terms of
* internal sheng ids */
u16 accel_limit_8; /**< 8 bit, lowest accelerable state */
u16 accept_limit_8; /**< 8 bit, lowest accept state */
u16 sherman_limit; /**< lowest sherman state */
u8 alphaShift;
u8 flags;
u8 has_accel; /**< 1 iff there are any accel plans */
u8 remap[256]; /**< remaps characters to a smaller alphabet */
ReportID arb_report; /**< one of the accepts that this dfa may raise */
u32 accel_offset; /**< offset of accel structures from start of McClellan */
m512 sheng_succ_masks[N_CHARS];
};
extern const u64a mcsheng64_pext_mask[8];
#endif
| 1,977 |
456 |
<gh_stars>100-1000
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2004-2020 <NAME>
// All rights reserved.
#include <djvUI/Spacer.h>
#include <djvUI/Style.h>
using namespace djv::Core;
namespace djv
{
namespace UI
{
namespace Layout
{
struct Spacer::Private
{
Orientation orientation = Orientation::First;
MetricsRole spacerSize = MetricsRole::Spacing;
MetricsRole spacerOppositeSize = MetricsRole::None;
};
void Spacer::_init(const std::shared_ptr<System::Context>& context)
{
Widget::_init(context);
setClassName("djv::UI::Layout::Spacer");
}
Spacer::Spacer() :
_p(new Private)
{}
Spacer::~Spacer()
{}
std::shared_ptr<Spacer> Spacer::create(Orientation orientation, const std::shared_ptr<System::Context>& context)
{
auto out = std::shared_ptr<Spacer>(new Spacer);
out->_init(context);
out->setOrientation(orientation);
return out;
}
Orientation Spacer::getOrientation() const
{
return _p->orientation;
}
void Spacer::setOrientation(Orientation value)
{
DJV_PRIVATE_PTR();
if (value == p.orientation)
return;
p.orientation = value;
_resize();
}
MetricsRole Spacer::getSpacerSize() const
{
return _p->spacerSize;
}
MetricsRole Spacer::getSpacerOppositeSize() const
{
return _p->spacerOppositeSize;
}
void Spacer::setSpacerSize(MetricsRole value)
{
DJV_PRIVATE_PTR();
if (value == p.spacerSize)
return;
p.spacerSize = value;
_resize();
}
void Spacer::setSpacerOppositeSize(MetricsRole value)
{
DJV_PRIVATE_PTR();
if (value == p.spacerOppositeSize)
return;
p.spacerOppositeSize = value;
_resize();
}
void Spacer::_preLayoutEvent(System::Event::PreLayout& event)
{
glm::vec2 minimumSize = glm::vec2(0.F, 0.F);
DJV_PRIVATE_PTR();
const auto& style = _getStyle();
switch (p.orientation)
{
case Orientation::Horizontal:
minimumSize.x = style->getMetric(p.spacerSize);
minimumSize.y = style->getMetric(p.spacerOppositeSize);
break;
case Orientation::Vertical:
minimumSize.x = style->getMetric(p.spacerOppositeSize);
minimumSize.y = style->getMetric(p.spacerSize);
break;
default: break;
}
_setMinimumSize(minimumSize + getMargin().getSize(style));
}
HorizontalSpacer::HorizontalSpacer()
{}
std::shared_ptr<HorizontalSpacer> HorizontalSpacer::create(const std::shared_ptr<System::Context>& context)
{
auto out = std::shared_ptr<HorizontalSpacer>(new HorizontalSpacer);
out->_init(context);
out->setOrientation(Orientation::Horizontal);
return out;
}
VerticalSpacer::VerticalSpacer()
{}
std::shared_ptr<VerticalSpacer> VerticalSpacer::create(const std::shared_ptr<System::Context>& context)
{
auto out = std::shared_ptr<VerticalSpacer>(new VerticalSpacer);
out->_init(context);
out->setOrientation(Orientation::Vertical);
return out;
}
} // namespace Layout
} // namespace UI
} // namespace djv
| 2,301 |
12,252 |
<filename>testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlRequestedAuthnContextBrokerTest.java
package org.keycloak.testsuite.broker;
import org.keycloak.broker.saml.SAMLIdentityProviderConfig;
import org.keycloak.dom.saml.v2.protocol.AuthnContextComparisonType;
import org.keycloak.dom.saml.v2.protocol.AuthnRequestType;
import org.keycloak.saml.common.util.DocumentUtil;
import org.keycloak.saml.processing.api.saml.v2.request.SAML2Request;
import org.keycloak.testsuite.saml.AbstractSamlTest;
import org.keycloak.testsuite.updaters.IdentityProviderAttributeUpdater;
import org.keycloak.testsuite.util.SamlClient;
import org.keycloak.testsuite.util.SamlClient.Binding;
import org.keycloak.testsuite.util.SamlClientBuilder;
import java.io.Closeable;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import static org.junit.Assert.assertThat;
import static org.keycloak.saml.common.constants.JBossSAMLURIConstants.AC_PASSWORD_PROTECTED_TRANSPORT;
import static org.keycloak.saml.common.constants.JBossSAMLURIConstants.ASSERTION_NSURI;
import static org.keycloak.saml.common.constants.JBossSAMLURIConstants.PROTOCOL_NSURI;
import static org.keycloak.testsuite.broker.BrokerTestTools.getConsumerRoot;
/**
* Final class as it's not intended to be overriden.
*/
public final class KcSamlRequestedAuthnContextBrokerTest extends AbstractBrokerTest {
@Override
protected BrokerConfiguration getBrokerConfiguration() {
return KcSamlBrokerConfiguration.INSTANCE;
}
@Test
public void testNoComparisonTypeNoClassRefsAndNoDeclRefs() throws Exception {
// No comparison type, no classrefs, no declrefs -> No RequestedAuthnContext
try (Closeable idpUpdater = new IdentityProviderAttributeUpdater(identityProviderResource)
.update())
{
// Build the login request document
AuthnRequestType loginRep = SamlClient.createLoginRequestDocument(AbstractSamlTest.SAML_CLIENT_ID_SALES_POST + ".dot/ted", getConsumerRoot() + "/sales-post/saml", null);
Document doc = SAML2Request.convert(loginRep);
new SamlClientBuilder()
.authnRequest(getConsumerSamlEndpoint(bc.consumerRealmName()), doc, Binding.POST)
.build() // Request to consumer IdP
.login().idp(bc.getIDPAlias()).build()
.processSamlResponse(Binding.POST) // AuthnRequest to producer IdP
.targetAttributeSamlRequest()
.transformDocument((document) -> {
try
{
log.infof("Document: %s", DocumentUtil.asString(document));
// Find the RequestedAuthnContext element
Element requestedAuthnContextElement = DocumentUtil.getDirectChildElement(document.getDocumentElement(), PROTOCOL_NSURI.get(), "RequestedAuthnContext");
Assert.assertThat("RequestedAuthnContext element found in request document, but was not necessary as ClassRef/DeclRefs were not specified", requestedAuthnContextElement, Matchers.nullValue());
}
catch (Exception ex)
{
throw new RuntimeException(ex);
}
})
.build()
.execute();
}
}
@Test
public void testComparisonTypeSetNoClassRefsAndNoDeclRefs() throws Exception {
// Comparison type set, no classrefs, no declrefs -> No RequestedAuthnContext
try (Closeable idpUpdater = new IdentityProviderAttributeUpdater(identityProviderResource)
.setAttribute(SAMLIdentityProviderConfig.AUTHN_CONTEXT_COMPARISON_TYPE, AuthnContextComparisonType.MINIMUM.value())
.update())
{
// Build the login request document
AuthnRequestType loginRep = SamlClient.createLoginRequestDocument(AbstractSamlTest.SAML_CLIENT_ID_SALES_POST + ".dot/ted", getConsumerRoot() + "/sales-post/saml", null);
Document doc = SAML2Request.convert(loginRep);
new SamlClientBuilder()
.authnRequest(getConsumerSamlEndpoint(bc.consumerRealmName()), doc, Binding.POST)
.build() // Request to consumer IdP
.login().idp(bc.getIDPAlias()).build()
.processSamlResponse(Binding.POST) // AuthnRequest to producer IdP
.targetAttributeSamlRequest()
.transformDocument((document) -> {
try
{
log.infof("Document: %s", DocumentUtil.asString(document));
// Find the RequestedAuthnContext element
Element requestedAuthnContextElement = DocumentUtil.getDirectChildElement(document.getDocumentElement(), PROTOCOL_NSURI.get(), "RequestedAuthnContext");
Assert.assertThat("RequestedAuthnContext element found in request document, but was not necessary as ClassRef/DeclRefs were not specified", requestedAuthnContextElement, Matchers.nullValue());
}
catch (Exception ex)
{
throw new RuntimeException(ex);
}
})
.build()
.execute();
}
}
@Test
public void testComparisonTypeSetClassRefsSetNoDeclRefs() throws Exception {
// Comparison type set, classref present, no declrefs -> RequestedAuthnContext with AuthnContextClassRef
try (Closeable idpUpdater = new IdentityProviderAttributeUpdater(identityProviderResource)
.setAttribute(SAMLIdentityProviderConfig.AUTHN_CONTEXT_COMPARISON_TYPE, AuthnContextComparisonType.EXACT.value())
.setAttribute(SAMLIdentityProviderConfig.AUTHN_CONTEXT_CLASS_REFS, "[\"" + AC_PASSWORD_PROTECTED_TRANSPORT.get() + "\"]")
.update())
{
// Build the login request document
AuthnRequestType loginRep = SamlClient.createLoginRequestDocument(AbstractSamlTest.SAML_CLIENT_ID_SALES_POST + ".dot/ted", getConsumerRoot() + "/sales-post/saml", null);
Document doc = SAML2Request.convert(loginRep);
new SamlClientBuilder()
.authnRequest(getConsumerSamlEndpoint(bc.consumerRealmName()), doc, Binding.POST)
.build() // Request to consumer IdP
.login().idp(bc.getIDPAlias()).build()
.processSamlResponse(Binding.POST) // AuthnRequest to producer IdP
.targetAttributeSamlRequest()
.transformDocument((document) -> {
try
{
log.infof("Document: %s", DocumentUtil.asString(document));
// Find the RequestedAuthnContext element
Element requestedAuthnContextElement = DocumentUtil.getDirectChildElement(document.getDocumentElement(), PROTOCOL_NSURI.get(), "RequestedAuthnContext");
Assert.assertThat("RequestedAuthnContext element not found in request document", requestedAuthnContextElement, Matchers.notNullValue());
// Verify the ComparisonType attribute
Assert.assertThat("RequestedAuthnContext element not found in request document", requestedAuthnContextElement.getAttribute("Comparison"), Matchers.is(AuthnContextComparisonType.EXACT.value()));
// Find the RequestedAuthnContext/ClassRef element
Element requestedAuthnContextClassRefElement = DocumentUtil.getDirectChildElement(requestedAuthnContextElement, ASSERTION_NSURI.get(), "AuthnContextClassRef");
Assert.assertThat("RequestedAuthnContext/AuthnContextClassRef element not found in request document", requestedAuthnContextClassRefElement, Matchers.notNullValue());
// Make sure the RequestedAuthnContext/ClassRef element has the requested value
Assert.assertThat("RequestedAuthnContext/AuthnContextClassRef element does not have the expected value", requestedAuthnContextClassRefElement.getTextContent(), Matchers.is(AC_PASSWORD_PROTECTED_TRANSPORT.get()));
}
catch (Exception ex)
{
throw new RuntimeException(ex);
}
})
.build()
.execute();
}
}
@Test
public void testComparisonTypeSetNoClassRefsDeclRefsSet() throws Exception {
// Comparison type set, no classref present, declrefs set -> RequestedAuthnContext with AuthnContextDeclRef
try (Closeable idpUpdater = new IdentityProviderAttributeUpdater(identityProviderResource)
.setAttribute(SAMLIdentityProviderConfig.AUTHN_CONTEXT_COMPARISON_TYPE, AuthnContextComparisonType.MINIMUM.value())
.setAttribute(SAMLIdentityProviderConfig.AUTHN_CONTEXT_DECL_REFS, "[\"secure/name/password/icmaolr/uri\"]")
.update())
{
// Build the login request document
AuthnRequestType loginRep = SamlClient.createLoginRequestDocument(AbstractSamlTest.SAML_CLIENT_ID_SALES_POST + ".dot/ted", getConsumerRoot() + "/sales-post/saml", null);
Document doc = SAML2Request.convert(loginRep);
new SamlClientBuilder()
.authnRequest(getConsumerSamlEndpoint(bc.consumerRealmName()), doc, Binding.POST)
.build() // Request to consumer IdP
.login().idp(bc.getIDPAlias()).build()
.processSamlResponse(Binding.POST) // AuthnRequest to producer IdP
.targetAttributeSamlRequest()
.transformDocument((document) -> {
try
{
log.infof("Document: %s", DocumentUtil.asString(document));
// Find the RequestedAuthnContext element
Element requestedAuthnContextElement = DocumentUtil.getDirectChildElement(document.getDocumentElement(), PROTOCOL_NSURI.get(), "RequestedAuthnContext");
Assert.assertThat("RequestedAuthnContext element not found in request document", requestedAuthnContextElement, Matchers.notNullValue());
// Verify the ComparisonType attribute
Assert.assertThat("RequestedAuthnContext element not found in request document", requestedAuthnContextElement.getAttribute("Comparison"), Matchers.is(AuthnContextComparisonType.MINIMUM.value()));
// Find the RequestedAuthnContext/DeclRef element
Element requestedAuthnContextDeclRefElement = DocumentUtil.getDirectChildElement(requestedAuthnContextElement, ASSERTION_NSURI.get(), "AuthnContextDeclRef");
Assert.assertThat("RequestedAuthnContext/AuthnContextDeclRef element not found in request document", requestedAuthnContextDeclRefElement, Matchers.notNullValue());
// Make sure the RequestedAuthnContext/DeclRef element has the requested value
Assert.assertThat("RequestedAuthnContext/AuthnContextDeclRef element does not have the expected value", requestedAuthnContextDeclRefElement.getTextContent(), Matchers.is("secure/name/password/icmaolr/uri"));
}
catch (Exception ex)
{
throw new RuntimeException(ex);
}
})
.build()
.execute();
}
}
@Test
public void testNoComparisonTypeClassRefsSetNoDeclRefs() throws Exception {
// Comparison type set, no classref present, declrefs set -> RequestedAuthnContext with comparison Exact and AuthnContextClassRef
try (Closeable idpUpdater = new IdentityProviderAttributeUpdater(identityProviderResource)
.setAttribute(SAMLIdentityProviderConfig.AUTHN_CONTEXT_CLASS_REFS, "[\"" + AC_PASSWORD_PROTECTED_TRANSPORT.get() + "\"]")
.update())
{
// Build the login request document
AuthnRequestType loginRep = SamlClient.createLoginRequestDocument(AbstractSamlTest.SAML_CLIENT_ID_SALES_POST + ".dot/ted", getConsumerRoot() + "/sales-post/saml", null);
Document doc = SAML2Request.convert(loginRep);
new SamlClientBuilder()
.authnRequest(getConsumerSamlEndpoint(bc.consumerRealmName()), doc, Binding.POST)
.build() // Request to consumer IdP
.login().idp(bc.getIDPAlias()).build()
.processSamlResponse(Binding.POST) // AuthnRequest to producer IdP
.targetAttributeSamlRequest()
.transformDocument((document) -> {
try
{
log.infof("Document: %s", DocumentUtil.asString(document));
// Find the RequestedAuthnContext element
Element requestedAuthnContextElement = DocumentUtil.getDirectChildElement(document.getDocumentElement(), PROTOCOL_NSURI.get(), "RequestedAuthnContext");
Assert.assertThat("RequestedAuthnContext element not found in request document", requestedAuthnContextElement, Matchers.notNullValue());
// Verify the ComparisonType attribute
Assert.assertThat("RequestedAuthnContext element not found in request document", requestedAuthnContextElement.getAttribute("Comparison"), Matchers.is(AuthnContextComparisonType.EXACT.value()));
// Find the RequestedAuthnContext/ClassRef element
Element requestedAuthnContextClassRefElement = DocumentUtil.getDirectChildElement(requestedAuthnContextElement, ASSERTION_NSURI.get(), "AuthnContextClassRef");
Assert.assertThat("RequestedAuthnContext/AuthnContextClassRef element not found in request document", requestedAuthnContextClassRefElement, Matchers.notNullValue());
// Make sure the RequestedAuthnContext/ClassRef element has the requested value
Assert.assertThat("RequestedAuthnContext/AuthnContextClassRef element does not have the expected value", requestedAuthnContextClassRefElement.getTextContent(), Matchers.is(AC_PASSWORD_PROTECTED_TRANSPORT.get()));
}
catch (Exception ex)
{
throw new RuntimeException(ex);
}
})
.build()
.execute();
}
}
}
| 6,433 |
2,406 |
<filename>inference-engine/src/vpu/common/include/vpu/configuration/switch_converters.hpp
// Copyright (C) 2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#pragma once
#include <string>
#include <unordered_map>
namespace vpu {
const std::unordered_map<std::string, bool>& string2switch();
const std::unordered_map<bool, std::string>& switch2string();
} // namespace vpu
| 137 |
326 |
// Boost.Geometry
// QuickBook Example
// Copyright (c) 2021, Oracle and/or its affiliates
// Contributed and/or modified by <NAME>, on behalf of Oracle
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//[azimuth_strategy
//` Shows how to calculate azimuth in geographic coordinate system
#include <iostream>
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/point.hpp>
int main()
{
namespace bg = boost::geometry;
typedef bg::model::point<double, 2, bg::cs::geographic<bg::degree> > point_type;
point_type p1(0, 0);
point_type p2(1, 1);
bg::srs::spheroid<double> spheroid(6378137.0, 6356752.3142451793);
bg::strategies::azimuth::geographic<> strategy(spheroid);
auto azimuth = boost::geometry::azimuth(p1, p2, strategy);
std::cout << "azimuth: " << azimuth << std::endl;
return 0;
}
//]
//[azimuth_strategy_output
/*`
Output:
[pre
azimuth: 0.788674
]
*/
//]
| 408 |
1,391 |
<filename>src/libndb/ndblookval.c
#include <u.h>
#include <libc.h>
#include <bio.h>
#include <ip.h>
#include <ndb.h>
/*
* Look for a pair with the given attribute. look first on the same line,
* then in the whole entry.
*/
Ndbtuple*
ndbfindattr(Ndbtuple *entry, Ndbtuple *line, char *attr)
{
Ndbtuple *nt;
/* first look on same line (closer binding) */
for(nt = line; nt;){
if(strcmp(attr, nt->attr) == 0)
return nt;
nt = nt->line;
if(nt == line)
break;
}
/* search whole tuple */
for(nt = entry; nt; nt = nt->entry)
if(strcmp(attr, nt->attr) == 0)
return nt;
return nil;
}
Ndbtuple*
ndblookval(Ndbtuple *entry, Ndbtuple *line, char *attr, char *to)
{
Ndbtuple *t;
t = ndbfindattr(entry, line, attr);
if(t != nil){
strncpy(to, t->val, Ndbvlen-1);
to[Ndbvlen-1] = 0;
}
return t;
}
| 388 |
2,329 |
package data;
class SimpleClassFour {
{
System.out.println("clinit!");
}
public int boo;
public static String s;
public SimpleClassFour(int i) {
}
public SimpleClassFour(String d) {
}
void boo() {
}
@SuppressWarnings("unused")
private static void foo() {
}
public String goo(int i, double d, String p) {
return p;
}
public static int hoo(long l) {
return new Long(l).intValue();
}
public static void woo() throws RuntimeException, IllegalStateException {
}
}
| 175 |
348 |
<filename>docs/data/leg-t2/088/08804491.json
{"nom":"<NAME>","circ":"4ème circonscription","dpt":"Vosges","inscrits":78,"abs":29,"votants":49,"blancs":9,"nuls":4,"exp":36,"res":[{"nuance":"LR","nom":"<NAME>","voix":21},{"nuance":"SOC","nom":"<NAME>","voix":15}]}
| 111 |
313 |
<gh_stars>100-1000
{"status_id":1975907262660608,"text":"Vecrepe cavugiwi za vi udhofaso damdalha fah kupca narod ucodo doom ofucoz kizremwe puhkuwmi puwlevu womub fesjenkum idvaag. #mojne","user":{"user_id":1367694733475840,"name":"<NAME>","screen_name":"@rot","created_at":1318723664,"followers_count":80,"friends_count":20,"favourites_count":16},"created_at":626714962,"favorite_count":46,"retweet_count":750,"entities":{"hashtags":[{"text":"#mojne","indices":[10,22]}]},"in_reply_to_status_id":null}
| 203 |
587 |
/*
* Copyright (C) 2013 salesforce.com, inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.auraframework.integration.test.java.provider;
import java.util.Map;
import org.auraframework.def.ComponentDef;
import org.auraframework.def.DefDescriptor;
import org.auraframework.def.ProviderDef;
import org.auraframework.impl.AuraImplTestCase;
import org.auraframework.instance.Component;
import org.auraframework.throwable.AuraRuntimeException;
import org.auraframework.throwable.quickfix.InvalidDefinitionException;
import org.junit.Test;
import com.google.common.collect.Maps;
/**
* Integration tests for Java provider
*/
public class JavaProviderIntegrationTest extends AuraImplTestCase {
@Test
public void testConcreteProviderInjection() throws Exception {
Map<String, Object> attributes = Maps.newHashMap();
attributes.put("whatToDo", "replace");
Component component = instanceService.getInstance("test:test_Provider_Concrete", ComponentDef.class,
attributes);
assertEquals("Java Provider: Failed to retrieve the right implementation for the interface.",
component.getDescriptor().getQualifiedName(), "markup://test:test_Provider_Concrete_Sub");
}
@Test
public void testConcreteProviderNull() throws Exception {
Map<String, Object> attributes = Maps.newHashMap();
attributes.put("whatToDo", "label");
Component component = instanceService.getInstance("test:test_Provider_Concrete", ComponentDef.class,
attributes);
assertEquals("Java Provider: Failed to retrieve the right implementation for the interface.",
component.getDescriptor().getQualifiedName(), "markup://test:test_Provider_Concrete");
}
@Test
public void testConcreteProviderNotComponent() throws Exception {
Map<String, Object> attributes = Maps.newHashMap();
attributes.put("whatToDo", "replaceBad");
try {
instanceService.getInstance("test:test_Provider_Concrete", ComponentDef.class, attributes);
fail("expected exception for bad provider return");
} catch (Exception e) {
checkExceptionFull(e, AuraRuntimeException.class, "markup://test:fakeApplication is not a component");
}
}
@Test
public void testConcreteProviderComponentNotFound() throws Exception {
Map<String, Object> attributes = Maps.newHashMap();
attributes.put("whatToDo", "replaceNotFound");
try {
instanceService.getInstance("test:test_Provider_Concrete", ComponentDef.class, attributes);
fail("expected exception for bad provider return");
} catch (Exception e) {
checkExceptionFull(e, AuraRuntimeException.class,
"java://org.auraframework.impl.java.provider.ConcreteProvider did not provide a valid component");
}
}
/**
* Verify that abstract component's provider returns a component which extends the abstract class
*/
@Test
public void testJavaProviderProvidesExtentingCmpWhenAbstractCmpGetsInstantiated() throws Exception {
Component component = instanceService.getInstance("test:test_Provider_AbstractBasic",
ComponentDef.class);
String actual = component.getDescriptor().getQualifiedName();
assertEquals("Java Provider: Failed to retrieve the component extending abstract component.",
"markup://test:test_Provider_AbstractBasicExtends", actual);
}
@Test
public void testComponentConfigProvider() throws Exception{
String targetProvider = "java://org.auraframework.impl.java.provider.TestComponentConfigProvider";
DefDescriptor<ProviderDef> javaProviderDefDesc = definitionService.getDefDescriptor(targetProvider, ProviderDef.class);
ProviderDef actual = definitionService.getDefinition(javaProviderDefDesc);
assertNotNull(actual);
assertEquals(targetProvider, actual.getDescriptor().getQualifiedName());
}
@Test
public void testComponentDescriptorProvider() throws Exception{
String targetProvider = "java://org.auraframework.impl.java.provider.TestComponentDescriptorProvider";
DefDescriptor<ProviderDef> javaProviderDefDesc = definitionService.getDefDescriptor(targetProvider, ProviderDef.class);
ProviderDef actual = definitionService.getDefinition(javaProviderDefDesc);
assertNotNull(actual);
assertEquals(targetProvider, actual.getDescriptor().getQualifiedName());
}
/**
* Verify InvalidDefinitionException is thrown when Java provider doesn't use Provider annotation.
*/
@Test
public void testExceptionIsThrownWhenJavaProviderWithoutAnnotation() throws Exception {
DefDescriptor<ProviderDef> javaPrvdrDefDesc = definitionService.getDefDescriptor(
"java://org.auraframework.impl.java.provider.TestProviderWithoutAnnotation", ProviderDef.class);
try {
definitionService.getDefinition(javaPrvdrDefDesc);
fail("Expected a InvalidDefinitionException when Java provider doesn't use Provider annotation");
} catch (Exception e) {
checkExceptionContains(e, InvalidDefinitionException.class, "@Provider annotation is required on all Providers.");
}
}
/**
* Verify InvalidDefinitionException is thrown when Java provider doesn't implement Provider interface.
*/
@Test
public void testExceptionIsThrownWhenJavaProviderWithoutImplementingInterface() throws Exception {
String targetProvider = "java://org.auraframework.impl.java.provider.TestProviderWithoutImplementingInterface";
DefDescriptor<ProviderDef> javaProviderDefDesc = definitionService.getDefDescriptor(targetProvider, ProviderDef.class);
try {
definitionService.getDefinition(javaProviderDefDesc);
fail("Expected a InvalidDefinitionException when Java provider doesn't implement Provider interface.");
} catch (Exception e) {
checkExceptionContains(e, InvalidDefinitionException.class, "@Provider must have a provider interface.");
}
}
/**
* Verify the original exception from provide() method is thrown out.
*/
@Test
public void testExceptionFromProvideIsThrownOut() throws Exception {
String resourceSource = "<aura:component provider='java://org.auraframework.impl.java.provider.TestProviderThrowsExceptionDuringProvide'></aura:component>";
DefDescriptor<ComponentDef> cmpDefDesc = getAuraTestingUtil().addSourceAutoCleanup(ComponentDef.class, resourceSource);
try {
instanceService.getInstance(cmpDefDesc.getDescriptorName(), ComponentDef.class);
fail("Should have thrown exception in provider's provide() method.");
} catch (Exception e) {
checkExceptionFull(e, InvalidDefinitionException.class, "Exception from TestProviderThrowsExceptionDuringProvide");
}
}
}
| 2,473 |
407 |
<reponame>StyleTang/SmartEngine<filename>core/src/main/java/com/alibaba/smart/framework/engine/configuration/impl/DefaultXmlParserFacade.java<gh_stars>100-1000
package com.alibaba.smart.framework.engine.configuration.impl;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamReader;
import com.alibaba.smart.framework.engine.common.util.MapUtil;
import com.alibaba.smart.framework.engine.common.util.StringUtil;
import com.alibaba.smart.framework.engine.configuration.ProcessEngineConfiguration;
import com.alibaba.smart.framework.engine.configuration.aware.ProcessEngineConfigurationAware;
import com.alibaba.smart.framework.engine.exception.EngineException;
import com.alibaba.smart.framework.engine.extension.annoation.ExtensionBinding;
import com.alibaba.smart.framework.engine.extension.constant.ExtensionConstant;
import com.alibaba.smart.framework.engine.smart.CustomExtensionElement;
import com.alibaba.smart.framework.engine.xml.parser.AttributeParser;
import com.alibaba.smart.framework.engine.xml.parser.ElementParser;
import com.alibaba.smart.framework.engine.xml.parser.ParseContext;
import com.alibaba.smart.framework.engine.xml.parser.XmlParserFacade;
/**
* 默认处理器扩展点 Created by ettear on 16-4-12.
*/
@SuppressWarnings("rawtypes")
@ExtensionBinding(group = ExtensionConstant.COMMON, bindKey = XmlParserFacade.class)
public class DefaultXmlParserFacade implements
XmlParserFacade, ProcessEngineConfigurationAware {
private Map<QName, AttributeParser> attributeParsers = MapUtil.newHashMap();
private ProcessEngineConfiguration processEngineConfiguration;
private Map<Class,Object> bindings;
private Map<QName, Object> bindingsWithQName = MapUtil.newHashMap();
@Override
public void start() {
this.bindings = processEngineConfiguration.getAnnotationScanner().getScanResult().get(
ExtensionConstant.ELEMENT_PARSER).getBindingMap();
Set<Entry<Class, Object>> entries = bindings.entrySet();
for (Entry<Class, Object> entry : entries) {
try {
Class aClass = entry.getKey();
Object newInstance = aClass.newInstance();
boolean isSmartEngineCustomElement = newInstance instanceof CustomExtensionElement;
Field field ;
QName qName = null;
if(!isSmartEngineCustomElement){
field = aClass.getField("qtype");
qName = (QName) field.get(newInstance);
bindingsWithQName.put(qName, entry.getValue());
}else {
field = aClass.getField("xmlLocalPart");
String localPart= (String)field.get(newInstance);
Map<String, Object> magicExtension = processEngineConfiguration.getMagicExtension();
if(MapUtil.isNotEmpty(magicExtension)){
Map<String,String> fallBackMap = (Map<String,String> )magicExtension.get("fallBack");
if(MapUtil.isNotEmpty(fallBackMap)){
List<QName> qNames= new ArrayList<QName>();
for (Entry<String, String> entryX : fallBackMap.entrySet()) {
QName qnamex = new QName(entryX.getKey(),localPart,entryX.getValue());
qNames.add(qnamex);
}
for(QName item : qNames) {
// single already registered, skip
if(item.equals(qName)) {
continue;
}
bindingsWithQName.put(item, entry.getValue());
}
}
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
@Override
public void stop() {
}
@Override
public Object parseElement(XMLStreamReader reader, ParseContext context) {
QName nodeQname = reader.getName();
ElementParser artifactParser = (ElementParser) bindingsWithQName.get(nodeQname);
try {
if(null != artifactParser){
return artifactParser.parseElement(reader, context);
}
} catch (Exception e) {
//TUNE 堆栈有些乱
throw new RuntimeException(e);
}
throw new EngineException("No parser found for QName: " + nodeQname);
}
@Override
public Object parseAttribute(QName attributeQName, XMLStreamReader reader, ParseContext context) {
if (null == attributeQName) {
return null;
}
QName currentNode = reader.getName();
String currentNodeNamespaceURI = currentNode.getNamespaceURI();
QName tunedAttributeQname;
String attributeNamespaceURI = attributeQName.getNamespaceURI();
String attributeLocalPart = attributeQName.getLocalPart();
if(StringUtil.isEmpty(attributeNamespaceURI)){
tunedAttributeQname=new QName(currentNodeNamespaceURI, attributeLocalPart);
}else{
tunedAttributeQname=attributeQName;
}
AttributeParser attributeParser = this.attributeParsers.get(tunedAttributeQname);
if (null == attributeParser) {
attributeParser = this.attributeParsers.get(currentNode);
}
if (null != attributeParser) {
return attributeParser.parseAttribute(attributeQName, reader, context);
} else if (StringUtil.equals(currentNodeNamespaceURI, attributeNamespaceURI)) {
return reader.getAttributeValue(attributeNamespaceURI, attributeLocalPart);
} else {
return null;
}
}
@Override
public void setProcessEngineConfiguration(ProcessEngineConfiguration processEngineConfiguration) {
this.processEngineConfiguration = processEngineConfiguration;
}
}
| 2,650 |
348 |
<reponame>chamberone/Leaflet.PixiOverlay
{"nom":"Ploumilliau","circ":"4ème circonscription","dpt":"Côtes-d'Armor","inscrits":2024,"abs":1005,"votants":1019,"blancs":77,"nuls":39,"exp":903,"res":[{"nuance":"REM","nom":"<NAME>","voix":531},{"nuance":"SOC","nom":"Mme <NAME>","voix":372}]}
| 122 |
5,267 |
package io.swagger.v3.core.oas.models.composition;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonSubTypes.Type;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.EXTERNAL_PROPERTY,
property = "type")
@JsonSubTypes({
@Type(value = HumanClass.class, name = "human"),
@Type(value = PetClass.class, name = "pet")
})
public class AnimalClass {
String type;
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
| 338 |
2,728 |
<filename>ReactNativeFrontend/ios/Pods/boost/boost/atomic/detail/ops_gcc_aarch64_common.hpp<gh_stars>1000+
/*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*
* Copyright (c) 2020 <NAME>
*/
/*!
* \file atomic/detail/ops_gcc_aarch64_common.hpp
*
* This header contains basic utilities for gcc AArch64 backend.
*/
#ifndef BOOST_ATOMIC_DETAIL_OPS_GCC_AARCH64_COMMON_HPP_INCLUDED_
#define BOOST_ATOMIC_DETAIL_OPS_GCC_AARCH64_COMMON_HPP_INCLUDED_
#include <boost/atomic/detail/config.hpp>
#include <boost/atomic/detail/capabilities.hpp>
#ifdef BOOST_HAS_PRAGMA_ONCE
#pragma once
#endif
#define BOOST_ATOMIC_DETAIL_AARCH64_MO_SWITCH(mo)\
switch (mo)\
{\
case memory_order_relaxed:\
BOOST_ATOMIC_DETAIL_AARCH64_MO_INSN("", "")\
break;\
\
case memory_order_consume:\
case memory_order_acquire:\
BOOST_ATOMIC_DETAIL_AARCH64_MO_INSN("a", "")\
break;\
\
case memory_order_release:\
BOOST_ATOMIC_DETAIL_AARCH64_MO_INSN("", "l")\
break;\
\
default:\
BOOST_ATOMIC_DETAIL_AARCH64_MO_INSN("a", "l")\
break;\
}
#if defined(BOOST_ATOMIC_DETAIL_AARCH64_LITTLE_ENDIAN)
#define BOOST_ATOMIC_DETAIL_AARCH64_ASM_ARG_LO "0"
#define BOOST_ATOMIC_DETAIL_AARCH64_ASM_ARG_HI "1"
#else
#define BOOST_ATOMIC_DETAIL_AARCH64_ASM_ARG_LO "1"
#define BOOST_ATOMIC_DETAIL_AARCH64_ASM_ARG_HI "0"
#endif
#endif // BOOST_ATOMIC_DETAIL_OPS_GCC_AARCH64_COMMON_HPP_INCLUDED_
| 766 |
580 |
<reponame>shuaijunlan/floodlight<gh_stars>100-1000
/**
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
**/
package net.floodlightcontroller.hasupport;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.floodlightcontroller.hasupport.NetworkInterface.ElectionState;
import net.floodlightcontroller.hasupport.NetworkInterface.netState;
/**
* The Election class
*
* This class implements a simple self stabilizing, leader election protocol
* which is fault tolerant up to N nodes. The concept behind this implementation
* is described in <NAME>'s 1997 paper 'Leader Election in Distributed
* Systems with Crash Failures' The ALE1 & ALE2' requirements are being
* followed.
*
* We have an additional constraint that AT LEAST 51% of the nodes must be fully
* connected before the election happens, this is in order to ensure that there
* will be at least one group which will produce a majority response to elect
* one leader. However, the drawback of this system is that 51% of the nodes
* have to be connected in order for the election to begin. (transition from
* CONNECT -> ELECT)
*
* FD: expireOldConnections() uses PULSE to detect failures.
*
* Possible improvements: a. Messages between nodes are being sent sequentially
* in a for loop, this can be modified to happen in parallel.
*
* b. Find out about the Raft leader election algorithm and implement it, and
* see if it can offer better performance.
*
* @author <NAME>, <NAME>
*/
public class AsyncElection implements Runnable {
private static final Logger logger = LoggerFactory.getLogger(AsyncElection.class);
private static NetworkNode network;
protected static IHAWorkerService haworker;
public static NetworkNode getNetwork() {
return network;
}
public static void setNetwork(NetworkNode network) {
AsyncElection.network = network;
}
private final String serverPort;
private final List<Integer> electionPriorities = new ArrayList<>();
private final Queue<String> publishQueue = new LinkedBlockingQueue<>();
private final Queue<String> subscribeQueue = new LinkedBlockingQueue<>();
private final String controllerID;
/**
* Indicates who the current leader of the entire system is.
*/
private String leader = "none";
private String tempLeader = "none";
private final String none = "none";
private final String ack = "ACK";
private final String publish = "BPUBLISH";
private final String subscribe = "KSUBSCRIBE";
private final String pulse = "PULSE";
private final String you = "YOU?";
private final String no = "NO";
private final String leadok = "LEADOK";
private final String iwon;
private final String setlead;
private final String leadermsg;
private final String heartbeat;
private ElectionState currentState = ElectionState.CONNECT;
private Map<String, netState> connectionDict;
/**
* Standardized sleep time for spinning in the rest state.
*/
private final Integer chill = new Integer(5);
private String timestamp = new String();
public AsyncElection(String sp, String cid) {
serverPort = sp;
controllerID = cid;
setlead = "SETLEAD " + controllerID;
leadermsg = "LEADER " + controllerID;
iwon = "IWON " + controllerID;
heartbeat = "HEARTBEAT " + controllerID;
}
public AsyncElection(String serverPort, String controllerID, IHAWorkerService haw) {
AsyncElection.setNetwork(new NetworkNode(serverPort, controllerID));
this.serverPort = serverPort;
this.controllerID = controllerID;
setlead = "SETLEAD " + this.controllerID;
leadermsg = "LEADER " + this.controllerID;
iwon = "IWON " + this.controllerID;
heartbeat = "HEARTBEAT " + this.controllerID;
AsyncElection.haworker = haw;
}
/**
* These are the different possible states the controller can be in during
* the election process.
*/
private void cases() {
try {
while (!Thread.currentThread().isInterrupted()) {
// logger.info("[AsyncElection] Current State:
// "+currentState.toString());
switch (currentState) {
case CONNECT:
/**
* Block until a majority of the servers have connected.
*/
currentState = network.blockUntilConnected();
/**
* Majority of the servers have connected, moving on to
* elect.
*/
break;
case ELECT:
/**
* Check for new nodes to connect to, and refresh the socket
* connections.
*/
connectionDict = network.checkForNewConnections();
// logger.info("[ELECT] =======SIZES+++++ {} {}", new
// Object[] {network.socketDict.size(), network.majority});
/**
* Ensure that a majority of nodes have connected, otherwise
* demote state.
*/
if (network.getSocketDict().size() < network.getMajority()) {
currentState = ElectionState.CONNECT;
break;
}
/**
* Start the election if a majority of nodes have connected.
*/
this.elect();
/**
* Once the election is done and the leader is confirmed,
* proceed to the COORDINATE or FOLLOW state.
*/
break;
case SPIN:
/**
* This is the resting state after the election.
*/
connectionDict = network.checkForNewConnections();
/**
* Check For Leader: This function ensures that there is
* only one leader set for the entire network. None or
* multiple leaders causes it to set the currentState to
* ELECT.
*/
timestamp = String.valueOf(System.nanoTime());
this.checkForLeader();
if (leader.equals(none)) {
currentState = ElectionState.ELECT;
break;
}
/**
* This is the follower state, currently there is a leader
* in the network.
*/
// logger.info("+++++++++++++++ [FOLLOWER] Leader is set to:
// "+this.leader.toString());
if (!publishQueue.isEmpty()) {
for (String wrkr : AsyncElection.haworker.getWorkerKeys()) {
AsyncElection.haworker.getService(wrkr).publishHook();
}
publishQueue.clear();
}
if (!subscribeQueue.isEmpty()) {
String cid = subscribeQueue.remove();
for (String wrkr : AsyncElection.haworker.getWorkerKeys()) {
AsyncElection.haworker.getService(wrkr).subscribeHook(cid);
}
// logger.info("[Follower Subscribe] Subscribing to:
// {}", new Object[]{cid});
subscribeQueue.clear();
}
TimeUnit.SECONDS.sleep(chill.intValue());
break;
case COORDINATE:
/**
* This is the resting state of the leader after the
* election.
*/
connectionDict = network.checkForNewConnections();
/**
* Keep sending a heartbeat message, and receive a majority
* of acceptors, otherwise go to the elect state.
*/
timestamp = String.valueOf(System.nanoTime());
this.sendHeartBeat();
if (leader.equals(none)) {
currentState = ElectionState.ELECT;
break;
}
/**
* This is the follower state, currently I am the leader of
* the network.
*/
// logger.info("+++++++++++++++ [LEADER] Leader is set to:
// "+this.leader.toString());
/**
* Keep the leader in coordinate state.
*/
timestamp = String.valueOf(System.nanoTime());
this.sendIWon();
this.sendLeaderMsg();
if (leader.equals(network.getControllerID())) {
this.setAsLeader();
}
if (!publishQueue.isEmpty()) {
AsyncElection.haworker.getService("LDHAWorker").publishHook();
AsyncElection.haworker.getService("TopoHAWorker").publishHook();
/**
* Network-wide publish
*/
publish();
publishQueue.clear();
}
if (!subscribeQueue.isEmpty()) {
String cid = subscribeQueue.remove();
AsyncElection.haworker.getService("LDHAWorker").subscribeHook(cid);
AsyncElection.haworker.getService("TopoHAWorker").subscribeHook(cid);
/**
* Network-wide Subscribe
*/
subscribe(cid);
subscribeQueue.clear();
}
TimeUnit.SECONDS.sleep(chill.intValue());
break;
}
}
} catch (InterruptedException ie) {
logger.debug("[Election] Exception in cases!");
ie.printStackTrace();
} catch (Exception e) {
logger.debug("[Election] Error in cases!");
e.printStackTrace();
}
}
/**
* Ask each node if they are the leader, you should get an ACK from only one
* of them, if not, then reset the leader.
*/
private void checkForLeader() {
HashSet<String> leaderSet = new HashSet<>();
String reply = new String();
String r1 = new String();
String r2 = new String();
StringTokenizer st = new StringTokenizer(reply);
try {
for (HashMap.Entry<String, netState> entry : connectionDict.entrySet()) {
if (connectionDict.get(entry.getKey()).equals(netState.ON)) {
network.send(entry.getKey(), you + " " + timestamp);
reply = network.recv(entry.getKey());
st = new StringTokenizer(reply);
r1 = st.nextToken();
if (st.hasMoreTokens()) {
r2 = st.nextToken();
}
if ((!r1.equals(no)) && (r2.equals(timestamp))) {
leaderSet.add(r1);
} else {
// logger.info("[AsyncElection] Check Leader: " + reply
// +" from "+entry.getKey().toString());
continue;
}
}
}
// logger.info("[AsyncElection checkForLeader] Leader Set:
// "+leaderSet.toString());
/**
* Remove blank objects from set, if any.
*/
if (leaderSet.contains(new String(""))) {
leaderSet.remove(new String(""));
}
/**
* Remove none from set, if any.
*/
if (leaderSet.contains(none)) {
leaderSet.remove(none);
}
/**
* Remove null objects from set, if any.
*/
if (leaderSet.contains(null)) {
// logger.info("[Election] Leader Set contains null");
leaderSet.remove(null);
}
if (leaderSet.size() == 1) {
setLeader(leaderSet.stream().findFirst().get());
} else if (leaderSet.size() > 1) {
setLeader(none);
// logger.info("[Election checkForLeader] SPLIT BRAIN!!");
// logger.info("[Election checkForLeader] Current Leader is
// none");
} else if (leaderSet.size() < 1) {
setLeader(none);
// logger.info("[Election checkForLeader] Current Leader is none
// "+ this.leader.toString() );
}
return;
} catch (Exception e) {
logger.debug("[Election] Error in CheckForLeader");
e.printStackTrace();
}
}
/**
* Election: All nodes will pick the max CID which they see in the network,
* any scenario wherein two different leaders might be picked gets resolved
* using the checkForLeader function.
*/
private void elect() {
/**
* Ensure that majority are still connected.
*/
if (network.getSocketDict().size() < network.getMajority()) {
return;
}
/**
* Clear leader variables.
*/
setTempLeader(none);
setLeader(none);
/**
* Check if actually in elect state
*/
if (!(currentState == ElectionState.ELECT)) {
return;
}
/**
* Node joins AFTER election: To check if a node joined after election,
* i.e. a leader is already present. Run the checkForLeader function and
* if it returns a leader then accept the existing leader and go to the
* SPIN state.
*/
timestamp = String.valueOf(System.nanoTime());
this.checkForLeader();
/**
* If a leader has already been set, exit election state and SPIN.
*/
if (!leader.equals(none)) {
currentState = ElectionState.SPIN;
return;
}
/**
* End of Node joins AFTER election.
*/
/**
* Actual election logic.
*/
this.electionLogic();
if (leader.equals(network.getControllerID())) {
// logger.info("[Election] I WON THE ELECTION!");
timestamp = String.valueOf(System.nanoTime());
this.sendIWon();
this.sendLeaderMsg();
if (leader.equals(network.getControllerID())) {
this.setAsLeader();
}
} else if (leader.equals(none)) {
currentState = ElectionState.ELECT;
} else {
currentState = ElectionState.SPIN;
}
/**
* End of Actual Election logic.
*/
return;
}
/**
* This is the logic that will be performed by the controller in order to
* pick a leader. It is an operation which is performed on the priorities
* array provided it supplied earlier, otherwise it constructs an array
* which contains all configured nodes in the descending order of their
* controller IDs.
*/
private void electionLogic() {
/**
* List of controllerIDs of all nodes.
*/
ArrayList<Integer> nodes = new ArrayList<>();
Integer maxNode = new Integer(0);
if ((electionPriorities.size() > 0) && (electionPriorities.size() == network.getTotalRounds() + 1)) {
nodes.addAll(electionPriorities);
} else {
/**
* Generate list of total possible CIDs.
*/
for (Integer i = (network.getTotalRounds() + 1); i > 0; i--) {
nodes.add(i);
}
}
// logger.info("[AsyncElection ElectionLogic] Nodes participating:
// "+nodes.toString());
/**
* Get the node whose CID is numerically greater.
*/
Set<String> connectDictKeys = connectionDict.keySet();
HashSet<Integer> activeCIDs = new HashSet<>();
/**
* Convert active controller ports into a Set of their IDs.
*/
for (String port : connectDictKeys) {
if (connectionDict.get(port) != null && connectionDict.get(port).equals(netState.ON)) {
activeCIDs.add(network.getNetcontrollerIDStatic().get(port));
}
}
activeCIDs.add(new Integer(controllerID));
// logger.info("[AsyncElection ElectionLogic] Active controllers:
// "+activeCIDs.toString()+" ConnectDict Keys:
// "+connectDictKeys.toString());
/**
* Find the current active maxNode.
*/
for (Integer i = 0; i < nodes.size(); i++) {
if (activeCIDs.contains(nodes.get(i))) {
maxNode = nodes.get(i);
break;
}
}
/**
* Edge case where you are the max node && you are ON.
*/
if (controllerID.equals(maxNode.toString())) {
setLeader(maxNode.toString());
return;
}
String maxNodePort = network.getControllerIDNetStatic().get(maxNode.toString()).toString();
/**
* Check if Max Node is alive, and set it as leader if it is.
*/
try {
for (int i = 0; i < network.getNumberOfPulses(); i++) {
network.send(maxNodePort, pulse);
String reply = network.recv(maxNodePort);
if (reply.equals(ack)) {
setLeader(maxNode.toString());
}
}
} catch (Exception e) {
// logger.debug("[AsyncElection] Error in electionLogic!");
e.printStackTrace();
}
return;
}
/**
* Gets the current network-wide leader.
*
* @return Current network-wide leader.
*/
public String getLeader() {
final String lead;
synchronized (leader) {
lead = leader;
}
return lead;
}
/**
* Used by the leader election protocol, internal function
*
* @return Temp Leader
*/
public String gettempLeader() {
final String tempLead;
synchronized (tempLeader) {
tempLead = tempLeader;
}
return tempLead;
}
/**
* Gets the timestamp variable before sending/receiving messages
*
* @return String timestamp
*/
public String getTimeStamp() {
final String ts;
synchronized (timestamp) {
ts = timestamp;
}
return ts;
}
/**
* Used by the leader to initiate a network-wide publish.
*/
public void publish() {
try {
/**
* Check for new nodes to connect to, and refresh the socket
* connections. this.connectionDict =
* network.checkForNewConnections();
*/
for (HashMap.Entry<String, netState> entry : connectionDict.entrySet()) {
if (connectionDict.get(entry.getKey()).equals(netState.ON)) {
network.send(entry.getKey(), publish);
network.recv(entry.getKey());
/**
* If we get an ACK, that's good. logger.debug("[Publish]
* Received ACK from "+entry.getKey().toString());
*/
}
}
return;
} catch (Exception e) {
logger.debug("[Election] Error in PUBLISH!");
e.printStackTrace();
}
}
/**
* Adds a control message instructing the controller to call publsihHook
*/
public void publishQueue() {
synchronized (publishQueue) {
publishQueue.offer("PUBLISH");
}
return;
}
@Override
public void run() {
ScheduledExecutorService sesElection = Executors.newScheduledThreadPool(5);
try {
Integer noServers = new Integer(0);
HAServer serverTh = new HAServer(serverPort, this, controllerID);
if (network.getTotalRounds() <= 1) {
noServers = 1;
} else {
noServers = (int) Math.ceil(Math.log10(network.getTotalRounds()));
}
if (noServers <= 1) {
noServers = 1;
}
sesElection.scheduleAtFixedRate(network, 0, 30000, TimeUnit.MICROSECONDS);
for (Integer i = 0; i < noServers; i++) {
sesElection.scheduleAtFixedRate(serverTh, 0, 30000, TimeUnit.MICROSECONDS);
}
// logger.info("[Election] Network majority:
// "+network.majority.toString());
// logger.info("[Election] Get netControllerIDStatic:
// "+network.getnetControllerIDStatic().toString());
this.cases();
} catch (Exception e) {
// logger.debug("[AsyncElection] Was interrrupted! "+e.toString());
e.printStackTrace();
sesElection.shutdownNow();
}
}
/**
* The Leader will send a HEARTBEAT message in the COORDINATE state after
* the election and will expect a reply from a majority of acceptors.
*/
private void sendHeartBeat() {
HashSet<String> noSet = new HashSet<>();
try {
for (HashMap.Entry<String, netState> entry : connectionDict.entrySet()) {
if (connectionDict.get(entry.getKey()).equals(netState.ON)) {
/**
* If the HeartBeat is rejected, populate the noSet.
*/
network.send(entry.getKey(), heartbeat + " " + timestamp);
String reply = network.recv(entry.getKey());
if (reply.equals(no) || (!reply.equals(ack + timestamp))) {
noSet.add(entry.getKey());
}
// If we get an ACK, that's good.
// logger.info("[Election] Received HEARTBEAT reply from
// "+entry.getKey().toString()+" saying: "+reply);
}
}
if (noSet.size() >= network.getMajority()) {
setLeader(none);
currentState = ElectionState.ELECT;
}
return;
} catch (Exception e) {
logger.debug("[Election] Error in sendHeartBeat!");
e.printStackTrace();
}
}
/**
* The winner of the election, or the largest node that is currently active
* in the network sends an "IWON" message in order to initiate the three
* phase commit to set itself as the leader of the network. Phase 1 of the
* three phase commit.
*/
private void sendIWon() {
try {
Set<String> reply = new HashSet<>();
for (HashMap.Entry<String, netState> entry : connectionDict.entrySet()) {
if (connectionDict.get(entry.getKey()).equals(netState.ON)) {
network.send(entry.getKey(), iwon + " " + timestamp);
reply.add(network.recv(entry.getKey()));
// logger.info("Received reply for IWON from:
// "+entry.getKey().toString() + reply.toString());
}
}
if (reply.contains(ack)) {
setTempLeader(controllerID);
}
return;
} catch (Exception e) {
logger.debug("[Election] Error in sendIWon!");
e.printStackTrace();
}
}
/**
* Send a "LEADER" message to all nodes and try to receive "LEADOK" messages
* from them. If count("LEADOK") > majority, then you have won the election
* and hence become the leader. Phase 2 of the three phase commit.
*/
private void sendLeaderMsg() {
HashSet<String> acceptors = new HashSet<>();
try {
for (HashMap.Entry<String, netState> entry : connectionDict.entrySet()) {
if (connectionDict.get(entry.getKey()).equals(netState.ON)) {
network.send(entry.getKey(), leadermsg + " " + timestamp);
String reply = network.recv(entry.getKey());
if (reply.equals(leadok)) {
acceptors.add(entry.getKey());
}
}
}
if (acceptors.size() >= network.getMajority()) {
// logger.info("[Election sendLeaderMsg] Accepted leader:
// "+this.controllerID+" Majority:
// "+network.majority+"Acceptors: "+acceptors.toString());
setLeader(network.getControllerID());
currentState = ElectionState.COORDINATE;
} else {
// logger.info("[Election sendLeaderMsg] Did not accept leader:
// "+this.controllerID+" Majority:
// "+network.majority+"Acceptors: "+acceptors.toString());
setLeader(none);
currentState = ElectionState.ELECT;
}
return;
} catch (Exception e) {
logger.debug("[Election] Error in sendLeaderMsg!");
e.printStackTrace();
}
}
/**
* The leader will set itself as leader during each COORDINATE state loop,
* to ensure that all nodes see it as the leader. Phase 3 of the three phase
* commit.
*/
private void setAsLeader() {
HashSet<String> noSet = new HashSet<>();
try {
for (HashMap.Entry<String, netState> entry : connectionDict.entrySet()) {
if (connectionDict.get(entry.getKey()).equals(netState.ON)) {
/**
* If the leader is rejected, populate the noSet.
*/
network.send(entry.getKey(), setlead + " " + timestamp);
String reply = network.recv(entry.getKey());
if (reply.equals(no)) {
noSet.add(entry.getKey());
}
// If we get an ACK, that's good.
// logger.info("[Election] Received SETLEAD ACK from
// "+entry.getKey().toString());
}
}
if (noSet.size() >= network.getMajority()) {
setLeader(none);
}
return;
} catch (Exception e) {
logger.debug("[Election] Error in setAsLeader!");
e.printStackTrace();
}
}
/**
* Set the order in which nodes are supposed to get elected.
*
* @param priorities
* is an ordered arraylist of integers which contain the order in
* which the controllers should be picked as leader. (optional)
*/
public void setElectionPriorities(ArrayList<Integer> priorities) {
synchronized (electionPriorities) {
if ((priorities.size()) > 0 && (priorities.size() == network.getTotalRounds() + 1)) {
electionPriorities.addAll(priorities);
} else {
logger.info("[AsyncElection] Priorities are not set.");
}
}
return;
}
/**
* Set the leader variable for this node.
*
* @param String
* leader
*/
public void setLeader(String leader) {
synchronized (this.leader) {
this.leader = leader;
}
return;
}
/**
* Set the temp leader. Internal function.
*
* @param String
* tempLeader
*/
public void setTempLeader(String tempLeader) {
synchronized (this.tempLeader) {
this.tempLeader = tempLeader;
}
return;
}
/**
* Sets the timestamp variable before sending/receiving messages.
*
* @param String
* timestamp
*/
public void setTimeStamp(String ts) {
synchronized (timestamp) {
timestamp = ts;
}
return;
}
/**
* Used by the leader to initiate a network-wide subscribe to the specified
* controller ID
*
* @param Controller
* ID you wish to subscribe to.
*/
public void subscribe(String cid) {
try {
/**
* Check for new nodes to connect to, and refresh the socket
* connections. this.connectionDict =
* network.checkForNewConnections();
*/
for (HashMap.Entry<String, netState> entry : connectionDict.entrySet()) {
if (connectionDict.get(entry.getKey()).equals(netState.ON)) {
String submsg = new String(subscribe + " " + cid);
// logger.info("[Leader Subscribe] Subscribing to: {}", new
// Object[]{cid});
network.send(entry.getKey(), submsg);
network.recv(entry.getKey());
// If we get an ACK, that's good.
// logger.info("[Subscribe] Received ACK from
// "+entry.getKey().toString());
}
}
return;
} catch (Exception e) {
logger.debug("[Election] Error in SUBSCRIBE!");
e.printStackTrace();
}
}
/**
* Adds a control message instructing the controller to call subscribeHook
*/
public void subscribeQueue(String sub) {
synchronized (subscribeQueue) {
subscribeQueue.offer(sub);
}
return;
}
}
| 9,197 |
5,788 |
/*
* 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.shardingsphere.test.sql.parser.parameterized.asserts.segment.model;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.shardingsphere.sql.parser.sql.common.segment.dml.column.ColumnSegment;
import org.apache.shardingsphere.sql.parser.sql.common.segment.dml.expr.subquery.SubquerySegment;
import org.apache.shardingsphere.sql.parser.sql.common.segment.dml.order.OrderBySegment;
import org.apache.shardingsphere.sql.parser.sql.common.segment.generic.ModelSegment;
import org.apache.shardingsphere.test.sql.parser.parameterized.asserts.SQLCaseAssertContext;
import org.apache.shardingsphere.test.sql.parser.parameterized.asserts.segment.SQLSegmentAssert;
import org.apache.shardingsphere.test.sql.parser.parameterized.asserts.segment.column.ColumnAssert;
import org.apache.shardingsphere.test.sql.parser.parameterized.asserts.segment.orderby.OrderByItemAssert;
import org.apache.shardingsphere.test.sql.parser.parameterized.asserts.statement.dml.impl.SelectStatementAssert;
import org.apache.shardingsphere.test.sql.parser.parameterized.jaxb.cases.domain.segment.impl.column.ExpectedColumn;
import org.apache.shardingsphere.test.sql.parser.parameterized.jaxb.cases.domain.segment.impl.model.ExpectedModelClause;
import org.apache.shardingsphere.test.sql.parser.parameterized.jaxb.cases.domain.segment.impl.orderby.ExpectedOrderByClause;
import org.apache.shardingsphere.test.sql.parser.parameterized.jaxb.cases.domain.statement.dml.SelectStatementTestCase;
import java.util.List;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
/**
* Model clause assert.
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class ModelClauseAssert {
/**
* Assert actual model segment is correct with expected model clause.
* @param assertContext assert context
* @param actual actual model
* @param expected expected model
*/
public static void assertIs(final SQLCaseAssertContext assertContext, final ModelSegment actual, final ExpectedModelClause expected) {
SQLSegmentAssert.assertIs(assertContext, actual, expected);
if (null != expected.getReferenceModelSelect()) {
assertNotNull(assertContext.getText("Actual reference model select subquery should exist."), actual.getReferenceModelSelect());
assertThat(assertContext.getText("Actual reference model select subquery size assertion error: "), actual.getReferenceModelSelect().size(), is(expected.getReferenceModelSelect().size()));
assertReferenceModelSelectStatements(assertContext, actual.getReferenceModelSelect(), expected.getReferenceModelSelect());
}
if (null != expected.getOrderBySegments()) {
assertNotNull(assertContext.getText("Actual order by segments should exist."), actual.getOrderBySegments());
assertThat(assertContext.getText("Actual order by segments size assertion error: "), actual.getOrderBySegments().size(), is(expected.getOrderBySegments().size()));
assertOrderBySegments(assertContext, actual.getOrderBySegments(), expected.getOrderBySegments());
}
if (null != expected.getCellAssignmentColumns()) {
assertNotNull(assertContext.getText("Actual cell assignment columns should exist."), actual.getCellAssignmentColumns());
assertThat(assertContext.getText("Actual cell assignment columns assertion error: "), actual.getCellAssignmentColumns().size(), is(expected.getCellAssignmentColumns().size()));
assertCellAssignmentColumns(assertContext, actual.getCellAssignmentColumns(), expected.getCellAssignmentColumns());
}
if (null != expected.getCellAssignmentSelect()) {
assertNotNull(assertContext.getText("Actual cell assignment select subquery should exist."), actual.getCellAsssignmentSelect());
assertThat(assertContext.getText("Actual cell assignment select size assertion error: "), actual.getCellAsssignmentSelect().size(), is(expected.getCellAssignmentSelect().size()));
assertCellAssignmentSelectStatements(assertContext, actual.getCellAsssignmentSelect(), expected.getCellAssignmentSelect());
}
}
private static void assertReferenceModelSelectStatements(final SQLCaseAssertContext assertContext, final List<SubquerySegment> actual, final List<SelectStatementTestCase> expected) {
int count = 0;
for (SubquerySegment each : actual) {
SelectStatementAssert.assertIs(assertContext, each.getSelect(), expected.get(count));
count++;
}
}
private static void assertOrderBySegments(final SQLCaseAssertContext assertContext, final List<OrderBySegment> actual, final List<ExpectedOrderByClause> expected) {
int count = 0;
for (OrderBySegment each : actual) {
OrderByItemAssert.assertIs(assertContext, each.getOrderByItems(), expected.get(count), "Order by");
count++;
}
}
private static void assertCellAssignmentColumns(final SQLCaseAssertContext assertContext, final List<ColumnSegment> actual, final List<ExpectedColumn> expected) {
int count = 0;
for (ColumnSegment each : actual) {
ColumnAssert.assertIs(assertContext, each, expected.get(count));
count++;
}
}
private static void assertCellAssignmentSelectStatements(final SQLCaseAssertContext assertContext, final List<SubquerySegment> actual, final List<SelectStatementTestCase> expected) {
int count = 0;
for (SubquerySegment each : actual) {
SelectStatementAssert.assertIs(assertContext, each.getSelect(), expected.get(count));
count++;
}
}
}
| 2,180 |
5,238 |
<reponame>nickzhuang0613/lvgl
#
# Example of styling the bar
#
style_bg = lv.style_t()
style_indic = lv.style_t()
style_bg.init()
style_bg.set_border_color(lv.palette_main(lv.PALETTE.BLUE))
style_bg.set_border_width(2)
style_bg.set_pad_all(6) # To make the indicator smaller
style_bg.set_radius(6)
style_bg.set_anim_time(1000)
style_indic.init()
style_indic.set_bg_opa(lv.OPA.COVER)
style_indic.set_bg_color(lv.palette_main(lv.PALETTE.BLUE))
style_indic.set_radius(3)
bar = lv.bar(lv.scr_act())
bar.remove_style_all() # To have a clean start
bar.add_style(style_bg, 0)
bar.add_style(style_indic, lv.PART.INDICATOR)
bar.set_size(200, 20)
bar.center()
bar.set_value(100, lv.ANIM.ON)
| 324 |
5,133 |
/*
* Copyright MapStruct Authors.
*
* Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package org.mapstruct.ap.test.abstractclass;
/**
* @author <NAME>
*/
public interface BaseMapperInterface {
Target sourceToTargetFromBaseMapperInterface(Source source);
}
| 99 |
784 |
package com.gplibs.magicsurfaceview;
class WaitNotify {
private boolean mWait = false;
private boolean mNotify = false;
private SimpleLock mLock = new SimpleLock();
WaitNotify() {
}
void doNotify() {
mLock.lock();
try {
mNotify = true;
if (mWait) {
synchronized (this) {
this.notify();
}
}
} finally {
mLock.unlock();
}
}
void doWait() {
mLock.lock();
boolean unlock = false;
try {
if (mNotify) {
return;
}
mWait = true;
synchronized (this) {
try {
mLock.unlock();
unlock = true;
this.wait();
} catch (Exception ex) {
ex.printStackTrace();
}
}
} finally {
if (!unlock) {
mLock.unlock();
}
}
}
void reset() {
mLock.lock();
mWait = false;
mNotify = false;
mLock.unlock();
}
}
| 709 |
4,962 |
<filename>byte-buddy-dep/src/test/java/net/bytebuddy/implementation/bind/annotation/TargetMethodAnnotationDriverBinderParameterBinderForFixedValueOfConstantTest.java<gh_stars>1000+
package net.bytebuddy.implementation.bind.annotation;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;
import net.bytebuddy.implementation.MethodDelegation;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Arrays;
import java.util.Collection;
import static net.bytebuddy.matcher.ElementMatchers.named;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
@RunWith(Parameterized.class)
public class TargetMethodAnnotationDriverBinderParameterBinderForFixedValueOfConstantTest {
private static final String FOO = "foo";
private static final byte NUMERIC_VALUE = 42;
@Parameterized.Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][]{
{true},
{NUMERIC_VALUE},
{(short) NUMERIC_VALUE},
{(char) NUMERIC_VALUE},
{(int) NUMERIC_VALUE},
{(long) NUMERIC_VALUE},
{(float) NUMERIC_VALUE},
{(double) NUMERIC_VALUE},
{FOO},
{Object.class}
});
}
private final Object value;
public TargetMethodAnnotationDriverBinderParameterBinderForFixedValueOfConstantTest(Object value) {
this.value = value;
}
@Test
public void testConstant() throws Exception {
assertThat(new ByteBuddy()
.subclass(Foo.class)
.method(named(FOO))
.intercept(MethodDelegation.withDefaultConfiguration()
.withBinders(TargetMethodAnnotationDrivenBinder.ParameterBinder.ForFixedValue.OfConstant.of(Bar.class, value))
.to(Foo.class))
.make()
.load(Foo.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
.getLoaded()
.getDeclaredConstructor()
.newInstance()
.foo(), is(value));
}
public static class Foo {
public static Object intercept(@Bar Object value) {
return value;
}
public Object foo() {
throw new AssertionError();
}
}
@Retention(RetentionPolicy.RUNTIME)
public @interface Bar {
/* empty */
}
}
| 1,155 |
529 |
// CRT I/O redirection support
#include <stdio.h>
#include <time.h>
#include <rt_sys.h>
#include "stm32f4xx.h"
// disable semi hosting as NETMF doesn't require it and it adds to code size
#pragma import(__use_no_semihosting_swi)
#pragma import(__use_no_semihosting)
#pragma import(__use_no_heap_region)
#pragma import(__use_no_heap)
// dummy FILE struct
struct __FILE { int handle; /* Add whatever you need here */ };
FILE *__aeabi_stdin, *__aeabi_stdout, *__aeabi_stderr;
const char __stdin_name[] = { 0 };
const char __stdout_name[] = { 0 };
const char __stderr_name[] = { 0 };
// standard file handles
// __stdout redirects to ITM channel 0 for deeply integrated Debugging printf/tracing
FILE __stdin, __stdout, __stderr;
int fputc(int ch, FILE *f)
{
if( f == &__stdout )
ITM_SendChar( ch );
return ch;
}
//FILEHANDLE _sys_open(const char *name, int openmode)
//{
// return 0;
//}
//int _sys_close(FILEHANDLE fh)
//{
// return 0;
//}
//int _sys_write(FILEHANDLE fh, const unsigned char *buf,
// unsigned len, int mode)
//{
// //your_device_write(buf, len);
// return 0;
//}
//int _sys_read( FILEHANDLE fh
// , unsigned char *buf
// , unsigned len
// , int mode
// )
//{
// return -1; /* not supported */
//}
//void _ttywrch(int ch)
//{
// ITM_SendChar(ch);
//}
//int _sys_istty(FILEHANDLE fh)
//{
// return 0; /* buffered output */
//}
//int _sys_seek(FILEHANDLE fh, long pos)
//{
// return -1; /* not supported */
//}
//long _sys_flen(FILEHANDLE fh)
//{
// return -1; /* not supported */
//}
//void _sys_exit(int returncode)
//{
//}
//int __backspace(FILE *stream)
//{
// return 0;
//}
| 835 |
348 |
{"nom":"Authiou","circ":"2ème circonscription","dpt":"Nièvre","inscrits":36,"abs":11,"votants":25,"blancs":4,"nuls":0,"exp":21,"res":[{"nuance":"REM","nom":"M. <NAME>","voix":11},{"nuance":"SOC","nom":"M. <NAME>","voix":10}]}
| 94 |
436 |
/**
* The MIT License
* Copyright (c) 2019- Nordic Institute for Interoperability Solutions (NIIS)
* Copyright (c) 2018 Estonian Information System Authority (RIA),
* Nordic Institute for Interoperability Solutions (NIIS), Population Register Centre (VRK)
* Copyright (c) 2015-2017 Estonian Information System Authority (RIA), Population Register Centre (VRK)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package ee.ria.xroad.signer.model;
import ee.ria.xroad.signer.protocol.dto.CertRequestInfo;
import ee.ria.xroad.signer.protocol.dto.CertificateInfo;
import ee.ria.xroad.signer.protocol.dto.KeyInfo;
import ee.ria.xroad.signer.protocol.dto.KeyUsageInfo;
import lombok.Data;
import lombok.ToString;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
/**
* Model object representing a key.
*/
@Data
// a quick solution to avoid stack overflow if Token.toString() used, both key and token have references to each other.
@ToString(exclude = {"token"})
public final class Key {
/** Reference to the token this key belongs to. */
private final Token token;
/** The unique key id. */
private final String id;
/** Whether of not this key is available. */
private boolean available;
/** Key usage info. */
private KeyUsageInfo usage;
/** The friendly name of the key. */
private String friendlyName;
/** The label of the key. */
private String label;
/** The X509 encoded public key. */
private String publicKey;
/** List of certificates. */
private final List<Cert> certs = new ArrayList<>();
/** List of certificate requests. */
private final List<CertRequest> certRequests = new ArrayList<>();
/**
* Adds a certificate to this key.
* @param cert the certificate to add
*/
public void addCert(Cert cert) {
certs.add(cert);
}
/**
* Adds a certificate request to this key.
* @param certReq the certificate request to add
*/
public void addCertRequest(CertRequest certReq) {
certRequests.add(certReq);
}
/**
* Converts this object to value object.
* @return the value object
*/
public KeyInfo toDTO() {
return new KeyInfo(available, usage, friendlyName, id, label, publicKey,
Collections.unmodifiableList(getCertsAsDTOs()), Collections.unmodifiableList(getCertRequestsAsDTOs()),
token.getSignMechanismName());
}
/**
* @return true if the key is available and its usage info is signing
*/
public boolean isValidForSigning() {
return isAvailable() && getUsage() == KeyUsageInfo.SIGNING;
}
private List<CertificateInfo> getCertsAsDTOs() {
return certs.stream().map(c -> c.toDTO()).collect(Collectors.toList());
}
private List<CertRequestInfo> getCertRequestsAsDTOs() {
return certRequests.stream().map(c -> c.toDTO()).collect(Collectors.toList());
}
}
| 1,292 |
850 |
<filename>tests/structures/test_if_elif_else.py<gh_stars>100-1000
from ..utils import TranspileTestCase
class IfElifElseTests(TranspileTestCase):
def test_if(self):
# Matches if
self.assertCodeExecution("""
x = 1
if x < 5:
print('Small x')
""")
# No match on if
self.assertCodeExecution("""
x = 10
if x < 5:
print('Small x')
""")
# Test expression statement
self.assertCodeExecution("""
x = 1
if x < 5:
[1, 2, 3]
"abc" == "def"
""")
def test_if_else(self):
self.assertCodeExecution("""
x = 1
if x < 5:
print('Small x')
else:
print('Large x')
""")
self.assertCodeExecution("""
x = 10
if x < 5:
print('Small x')
else:
print('Large x')
""")
def test_if_elif_else(self):
self.assertCodeExecution("""
x = 1
if x < 5:
print('Small x')
elif x < 50:
print('Medium x')
else:
print('Large x')
""")
self.assertCodeExecution("""
x = 10
if x < 5:
print('Small x')
elif x < 50:
print('Medium x')
else:
print('Large x')
""")
self.assertCodeExecution("""
x = 100
if x < 5:
print('Small x')
elif x < 50:
print('Medium x')
else:
print('Large x')
""")
def test_if_elif_elif_else(self):
self.assertCodeExecution("""
x = 1
if x < 5:
print('Small x')
elif x < 50:
print('Medium x')
elif x < 500:
print('Large x')
else:
print('Huge x')
""")
self.assertCodeExecution("""
x = 10
if x < 5:
print('Small x')
elif x < 50:
print('Medium x')
elif x < 500:
print('Large x')
else:
print('Huge x')
""")
self.assertCodeExecution("""
x = 100
if x < 5:
print('Small x')
elif x < 50:
print('Medium x')
elif x < 500:
print('Large x')
else:
print('Huge x')
""")
self.assertCodeExecution("""
x = 1000
if x < 5:
print('Small x')
elif x < 50:
print('Medium x')
elif x < 500:
print('Large x')
else:
print('Huge x')
""")
def test_if_elif_elif(self):
self.assertCodeExecution("""
x = 1
if x < 5:
print('Small x')
elif x < 50:
print('Medium x')
elif x < 500:
print('Large x')
""")
self.assertCodeExecution("""
x = 10
if x < 5:
print('Small x')
elif x < 50:
print('Medium x')
elif x < 500:
print('Large x')
""")
self.assertCodeExecution("""
x = 100
if x < 5:
print('Small x')
elif x < 50:
print('Medium x')
elif x < 500:
print('Large x')
""")
self.assertCodeExecution("""
x = 1000
if x < 5:
print('Small x')
elif x < 50:
print('Medium x')
elif x < 500:
print('Large x')
""")
def test_multiple_if(self):
# Make sure the most recent if block
# is correctly identified.
self.assertCodeExecution("""
x = 1
if x < 5:
print('Small x')
elif x < 50:
print('Medium x')
else:
print('Large x')
print('Done 1.')
x = 10
if x < 5:
print('Small x')
elif x < 50:
print('Medium x')
else:
print('Large x')
print('Done 2.')
x = 100
if x < 5:
print('Small x')
elif x < 50:
print('Medium x')
else:
print('Large x')
print('Done 3.')
""")
def test_multiple_if_is_comparison(self):
# Make sure the most recent if block
# is correctly identified.
self.assertCodeExecution("""
x = None
if x is None:
print('1: is none')
else:
print('1: is not none')
print('Done 1.')
if x is not None:
print('2: is not none')
else:
print('2: is none')
print('Done 2.')
""")
def test_end_of_block(self):
# Ensure that the jump target at the end of a block
# is correctly identified
self.assertCodeExecution("""
x = 100
if x == 0:
y = 42
else:
y = 37
z = (x, y)
print(z)
print('Done')
""")
def test_simple_end_of_function_block_with_return(self):
# Ensure that if the last instruction in an if block
# is a return, a GOTO isn't added to the end of the block.
self.assertCodeExecution("""
def foo(x):
print("Testing", x)
if x == 0:
return 42
y = foo(0)
print("Result", y)
y = foo(100)
print("Result", y)
print('Done')
""")
def test_end_of_function_block_with_return(self):
# Ensure that if the last instruction in an if/else block
# is a return, a GOTO isn't added to the end of the block.
self.assertCodeExecution("""
def foo(x):
print("Testing", x)
if x == 0:
return 42
y = foo(0)
print("Result", y)
y = foo(100)
print("Result", y)
print('Done')
""")
def test_end_of_function_block_with_return_in_else(self):
# Ensure that if the last instruction in an if/else block
# is a return, a GOTO isn't added to the end of the block.
self.assertCodeExecution("""
def foo(x):
print("Testing", x)
if x == 0:
return 42
else:
return 37
y = foo(0)
print("Result", y)
y = foo(100)
print("Result", y)
y = foo(0)
print("Result", y)
print('Done')
""")
def test_end_of_block_in_main(self):
# Ensure that the jump target at the end of a block
# is correctly identified in a main loop
self.assertCodeExecution("""
print('Hello, World')
if __name__ == '__main__':
x = 100
if x == 0:
y = 42
else:
y = 37
""", run_in_function=False)
| 4,705 |
318 |
<reponame>jasjuang/opengm
#ifndef OPENGM_LP_SOLVER_GUROBI_HXX_
#define OPENGM_LP_SOLVER_GUROBI_HXX_
#include <gurobi_c++.h>
#include <opengm/inference/auxiliary/lpdef.hxx>
#include <opengm/inference/auxiliary/lp_solver/lp_solver_interface.hxx>
#include <opengm/utilities/timer.hxx>
/*********************
* class definition *
*********************/
namespace opengm {
class LPSolverGurobi : public LPSolverInterface<LPSolverGurobi, double, int, std::vector<double>::const_iterator, double> {
public:
// typedefs
typedef double GurobiValueType;
typedef int GurobiIndexType;
typedef std::vector<GurobiValueType>::const_iterator GurobiSolutionIteratorType;
typedef double GurobiTimingType;
typedef LPSolverInterface<LPSolverGurobi, GurobiValueType, GurobiIndexType, GurobiSolutionIteratorType, GurobiTimingType> LPSolverBaseClass;
// constructor
LPSolverGurobi(const Parameter& parameter = Parameter());
// destructor
~LPSolverGurobi();
protected:
// Storage for Gurobi variables
GRBEnv gurobiEnvironment_;
mutable GRBModel gurobiModel_; // model is mutable as GRBModel::write() is not marked as const. However exporting a Model to file is expected to not change the model itself. Is the missing const intended by Gurobi?
std::vector<GRBVar> gurobiVariables_;
mutable std::vector<GurobiValueType> gurobiSolution_;
mutable bool gurobiSolutionValid_;
// methods for class LPSolverInterface
// Gurobi infinity value
static GurobiValueType infinity_impl();
// add Variables
void addContinuousVariables_impl(const GurobiIndexType numVariables, const GurobiValueType lowerBound, const GurobiValueType upperBound);
void addIntegerVariables_impl(const GurobiIndexType numVariables, const GurobiValueType lowerBound, const GurobiValueType upperBound);
void addBinaryVariables_impl(const GurobiIndexType numVariables);
// objective function
void setObjective_impl(const Objective objective);
void setObjectiveValue_impl(const GurobiIndexType variable, const GurobiValueType value);
template<class ITERATOR_TYPE>
void setObjectiveValue_impl(ITERATOR_TYPE begin, const ITERATOR_TYPE end);
template<class VARIABLES_ITERATOR_TYPE, class COEFFICIENTS_ITERATOR_TYPE>
void setObjectiveValue_impl(VARIABLES_ITERATOR_TYPE variableIDsBegin, const VARIABLES_ITERATOR_TYPE variableIDsEnd, COEFFICIENTS_ITERATOR_TYPE coefficientsBegin);
// constraints
template<class VARIABLES_ITERATOR_TYPE, class COEFFICIENTS_ITERATOR_TYPE>
void addEqualityConstraint_impl(VARIABLES_ITERATOR_TYPE variableIDsBegin, const VARIABLES_ITERATOR_TYPE variableIDsEnd, COEFFICIENTS_ITERATOR_TYPE coefficientsBegin, const GurobiValueType bound, const std::string& constraintName = "");
template<class VARIABLES_ITERATOR_TYPE, class COEFFICIENTS_ITERATOR_TYPE>
void addLessEqualConstraint_impl(VARIABLES_ITERATOR_TYPE variableIDsBegin, const VARIABLES_ITERATOR_TYPE variableIDsEnd, COEFFICIENTS_ITERATOR_TYPE coefficientsBegin, const GurobiValueType bound, const std::string& constraintName = "");
template<class VARIABLES_ITERATOR_TYPE, class COEFFICIENTS_ITERATOR_TYPE>
void addGreaterEqualConstraint_impl(VARIABLES_ITERATOR_TYPE variableIDsBegin, const VARIABLES_ITERATOR_TYPE variableIDsEnd, COEFFICIENTS_ITERATOR_TYPE coefficientsBegin, const GurobiValueType bound, const std::string& constraintName = "");
void addConstraintsFinished_impl();
void addConstraintsFinished_impl(GurobiTimingType& timing);
// parameter
template <class PARAMETER_TYPE, class PARAMETER_VALUE_TYPE>
void setParameter_impl(const PARAMETER_TYPE parameter, const PARAMETER_VALUE_TYPE value);
// solve
bool solve_impl();
bool solve_impl(GurobiTimingType& timing);
// solution
GurobiSolutionIteratorType solutionBegin_impl() const;
GurobiSolutionIteratorType solutionEnd_impl() const;
GurobiValueType solution_impl(const GurobiIndexType variable) const;
GurobiValueType objectiveFunctionValue_impl() const;
GurobiValueType objectiveFunctionValueBound_impl() const;
// model export
void exportModel_impl(const std::string& filename) const;
// helper functions
void updateSolution() const;
static int getCutLevelValue(const LPDef::MIP_CUT cutLevel);
// friend
friend class LPSolverInterface<LPSolverGurobi, GurobiValueType, GurobiIndexType, GurobiSolutionIteratorType, GurobiTimingType>;
};
} // namespace opengm
/***********************
* class documentation *
***********************/
/*! \file lp_solver_gurobi.hxx
* \brief Provides wrapper class for LP Solver Gurobi.
*/
/*! \class opengm::LPSolverGurobi
* \brief Wrapper class for the Gurobi optimizer.
*
* \note <a href="http://www.gurobi.com/index">Gurobi</a> is a
* commercial product that is free for academical use.
*/
/*! \typedef LPSolverGurobi::GurobiValueType
* \brief Defines the value type used by Gurobi.
*/
/*! \typedef LPSolverGurobi::GurobiIndexType
* \brief Defines the index type used by Gurobi.
*/
/*! \typedef LPSolverGurobi::GurobiSolutionIteratorType
* \brief Defines the iterator type which can be used to iterate over the
* solution of Gurobi.
*/
/*! \typedef LPSolverGurobi::GurobiTimingType
* \brief Defines the timing type used by Gurobi.
*/
/*! \typedef LPSolverGurobi::LPSolverBaseClass
* \brief Defines the type of the base class.
*/
/*! \fn LPSolverGurobi::LPSolverGurobi(const Parameter& parameter = Parameter())
* \brief Default constructor for LPSolverGurobi.
*
* \param[in] parameter Settings for the Gurobi solver.
*/
/*! \fn LPSolverGurobi::~LPSolverGurobi()
* \brief Destructor for LPSolverGurobi.
*/
/*! \var LPSolverGurobi::gurobiEnvironment_
* \brief The Gurobi environment.
*/
/*! \var LPSolverGurobi::gurobiModel_
* \brief The Gurobi model of the LP/MIP problem.
*/
/*! \var LPSolverGurobi::gurobiVariables_
* \brief The variables which are present in the model.
*/
/*! \var LPSolverGurobi::gurobiSolution_
* \brief Storage for the solution computed by Gurobi.
*/
/*! \var LPSolverGurobi::gurobiSolutionValid_
* \brief Tell if the currently stored solution is valid.
*/
/*! \fn static LPSolverGurobi::GurobiValueType LPSolverGurobi::infinity_impl()
* \brief Get the value which is used by Gurobi to represent infinity.
*
* \note Implementation for base class LPSolverInterface::infinity method.
*/
/*! \fn void LPSolverGurobi::addContinuousVariables_impl(const GurobiIndexType numVariables, const GurobiValueType lowerBound, const GurobiValueType upperBound)
* \brief Add new continuous variables to the model.
*
* \param[in] numVariables The number of new Variables.
* \param[in] lowerBound The lower bound for the new Variables.
* \param[in] upperBound The upper bound for the new Variables.
*
* \note Implementation for base class
* LPSolverInterface::addContinuousVariables method.
*/
/*! \fn void LPSolverGurobi::addIntegerVariables_impl(const GurobiIndexType numVariables, const GurobiValueType lowerBound, const GurobiValueType upperBound)
* \brief Add new integer variables to the model.
*
* \param[in] numVariables The number of new Variables.
* \param[in] lowerBound The lower bound for the new Variables.
* \param[in] upperBound The upper bound for the new Variables.
*
* \note Implementation for base class LPSolverInterface::addIntegerVariables
* method.
*/
/*! \fn void LPSolverGurobi::addBinaryVariables_impl(const GurobiIndexType numVariables)
* \brief Add new binary variables to the model.
*
* \param[in] numVariables The number of new Variables.
*
* \note Implementation for base class LPSolverInterface::addBinaryVariables
* method.
*/
/*! \fn void LPSolverGurobi::setObjective_impl(const Objective objective)
* \brief Set objective to minimize or maximize.
*
* \param[in] objective The new objective.
*
* \note Implementation for base class LPSolverInterface::setObjective_impl
* method.
*/
/*! \fn void LPSolverGurobi::setObjectiveValue_impl(const GurobiIndexType variable, const GurobiValueType value)
* \brief Set the coefficient of a variable in the objective function.
*
* \param[in] variable The index of the variable.
* \param[in] value The value which will be set as the coefficient of the
* variable in the objective function.
*
* \note Implementation for base class LPSolverInterface::setObjectiveValue
* method.
*/
/*! \fn void LPSolverGurobi::setObjectiveValue_impl(ITERATOR_TYPE begin, const ITERATOR_TYPE end)
* \brief Set values of the coefficients of all variables in the objective
* function.
* \tparam ITERATOR_TYPE Iterator type used to iterate over the values which
* will be set as the coefficients of the objective
* function.
*
* \param[in] begin Iterator pointing to the begin of the sequence of values
* which will be set as the coefficients of the objective
* function.
* \param[in] end Iterator pointing to the end of the sequence of values which
* will be set as the coefficients of the objective function.
*
* \note Implementation for base class LPSolverInterface::setObjectiveValue
* method.
*/
/*! \fn void LPSolverGurobi::setObjectiveValue_impl(VARIABLES_ITERATOR_TYPE variableIDsBegin, const VARIABLES_ITERATOR_TYPE variableIDsEnd, COEFFICIENTS_ITERATOR_TYPE coefficientsBegin)
* \brief Set values as the coefficients of selected variables in the objective
* function.
* \tparam VARIABLES_ITERATOR_TYPE Iterator type used to iterate over the
* indices of the variables.
* \tparam COEFFICIENTS_ITERATOR_TYPE Iterator type used to iterate over the
* coefficients of the variables which will be
* set in the objective function.
*
* \param[in] variableIDsBegin Iterator pointing to the begin of the sequence
* of indices of the variables.
* \param[in] variableIDsEnd Iterator pointing to the end of the sequence of
* indices of the variables.
* \param[in] coefficientsBegin Iterator pointing to the begin of the sequence
* of values which will be set as the
* coefficients of the objective function.
*
* \note Implementation for base class LPSolverInterface::setObjectiveValue
* method.
*/
/*! \fn void LPSolverGurobi::addEqualityConstraint_impl(VARIABLES_ITERATOR_TYPE variableIDsBegin, const VARIABLES_ITERATOR_TYPE variableIDsEnd, COEFFICIENTS_ITERATOR_TYPE coefficientsBegin, const GurobiValueType bound, const std::string& constraintName = "")
* \brief Add a new equality constraint to the model.
*
* \tparam VARIABLES_ITERATOR_TYPE Iterator type to iterate over the variable
* ids of the constraints.
* \tparam COEFFICIENTS_ITERATOR_TYPE Iterator type to iterate over the
* coefficients of the constraints.
*
* \param[in] variableIDsBegin Iterator pointing to the begin of a sequence of
* values defining the variables of the constraint.
* \param[in] variableIDsEnd Iterator pointing to the end of a sequence of
* values defining the variables of the constraint.
* \param[in] coefficientsBegin Iterator pointing to the begin of a sequence of
* values defining the coefficients for the
* variables.
* \param[in] bound The right hand side of the equality constraint.
* \param[in] constraintName The name for the equality constraint.
*
* \note
* -# Implementation for base class
* LPSolverInterface::addEqualityConstraint method.
* -# To increase performance for adding multiple constraints to the
* model, all constraints added via
* LPSolverGurobi::addEqualityConstraint,
* LPSolverGurobi::addLessEqualConstraint and
* LPSolverGurobi::addGreaterEqualConstraint are stored in a puffer
* and will be added to the model all at once when the function
* LPSolverGurobi::addConstraintsFinished is called.
*/
/*! \fn void LPSolverGurobi::addLessEqualConstraint_impl(VARIABLES_ITERATOR_TYPE variableIDsBegin, const VARIABLES_ITERATOR_TYPE variableIDsEnd, COEFFICIENTS_ITERATOR_TYPE coefficientsBegin, const GurobiValueType bound, const std::string& constraintName = "");
* \brief Add a new less equal constraint to the model.
*
* \tparam VARIABLES_ITERATOR_TYPE Iterator type to iterate over the variable
* ids of the constraints.
* \tparam COEFFICIENTS_ITERATOR_TYPE Iterator type to iterate over the
* coefficients of the constraints.
*
* \param[in] variableIDsBegin Iterator pointing to the begin of a sequence of
* values defining the variables of the constraint.
* \param[in] variableIDsEnd Iterator pointing to the end of a sequence of
* values defining the variables of the constraint.
* \param[in] coefficientsBegin Iterator pointing to the begin of a sequence of
* values defining the coefficients for the
* variables.
* \param[in] bound The right hand side of the less equal constraint.
* \param[in] constraintName The name for the less equal constraint.
*
* \note
* -# Implementation for base class
* LPSolverInterface::addLessEqualConstraint method.
* -# To increase performance for adding multiple constraints to the
* model, all constraints added via
* LPSolverGurobi::addEqualityConstraint,
* LPSolverGurobi::addLessEqualConstraint and
* LPSolverGurobi::addGreaterEqualConstraint are stored in a puffer
* and will be added to the model all at once when the function
* LPSolverGurobi::addConstraintsFinished is called.
*/
/*! \fn void LPSolverGurobi::addGreaterEqualConstraint_impl(VARIABLES_ITERATOR_TYPE variableIDsBegin, const VARIABLES_ITERATOR_TYPE variableIDsEnd, COEFFICIENTS_ITERATOR_TYPE coefficientsBegin, const GurobiValueType bound, const std::string& constraintName = "")
* \brief Add a new greater equal constraint to the model.
*
* \tparam VARIABLES_ITERATOR_TYPE Iterator type to iterate over the variable
* ids of the constraints.
* \tparam COEFFICIENTS_ITERATOR_TYPE Iterator type to iterate over the
* coefficients of the constraints.
*
* \param[in] variableIDsBegin Iterator pointing to the begin of a sequence of
* values defining the variables of the constraint.
* \param[in] variableIDsEnd Iterator pointing to the end of a sequence of
* values defining the variables of the constraint.
* \param[in] coefficientsBegin Iterator pointing to the begin of a sequence of
* values defining the coefficients for the
* variables.
* \param[in] bound The right hand side of the greater equal constraint.
* \param[in] constraintName The name for the greater equal constraint.
*
* \note
* -# Implementation for base class
* LPSolverInterface::addGreaterEqualConstraint method.
* -# To increase performance for adding multiple constraints to the
* model, all constraints added via
* LPSolverGurobi::addEqualityConstraint,
* LPSolverGurobi::addLessEqualConstraint and
* LPSolverGurobi::addGreaterEqualConstraint are stored in a puffer
* and will be added to the model all at once when the function
* LPSolverGurobi::addConstraintsFinished is called.
*/
/*! \fn void LPSolverGurobi::addConstraintsFinished_impl()
* \brief Join all constraints added via LPSolverGurobi::addEqualityConstraint,
* LPSolverGurobi::addLessEqualConstraint and
* LPSolverGurobi::addGreaterEqualConstraint to the model.
*
* \note Implementation for base class
* LPSolverInterface::addConstraintsFinished method.
*/
/*! \fn void LPSolverGurobi::addConstraintsFinished_impl(GurobiTimingType& timing)
* \brief Join all constraints added via LPSolverGurobi::addEqualityConstraint,
* LPSolverGurobi::addLessEqualConstraint and
* LPSolverGurobi::addGreaterEqualConstraint to the model.
*
* \param[out] timing Returns the time needed to join all constraints into the
* model.
*
* \note Implementation for base class
* LPSolverInterface::addConstraintsFinished method.
*/
/*! \fn void LPSolverGurobi::setParameter_impl(const PARAMETER_TYPE parameter, const PARAMETER_VALUE_TYPE value)
* \brief Set Gurobi parameter.
*
* \tparam PARAMETER_VALUE_TYPE The type of the parameter.
* \tparam VALUE_TYPE The type of the value.
*
* \param[in] parameter The Gurobi parameter.
* \param[in] value The new value to which the parameter will be set.
*
* \note Implementation for base class LPSolverInterface::setParameter method.
*/
/*! \fn bool LPSolverGurobi::solve_impl()
* \brief Solve the current model.
*
* \return True if solving the model finished successfully, false if Gurobi was
* not able to solve the model.
*
* \note Implementation for base class LPSolverInterface::solve method.
*/
/*! \fn bool LPSolverGurobi::solve_impl(GurobiTimingType& timing)
* \brief Solve the current model and measure solving time.
*
* \param[out] timing The time Gurobi needed to solve the problem.
*
* \return True if solving the model finished successfully, false if Gurobi was
* not able to solve the model.
*
* \note Implementation for base class LPSolverInterface::solve method.
*/
/*! \fn LPSolverGurobi::GurobiSolutionIteratorType LPSolverGurobi::solutionBegin_impl() const
* \brief Get an iterator which is pointing to the begin of the solution
* computed by Gurobi.
*
* \return Iterator pointing to the begin of the solution.
*
* \note Implementation for base class LPSolverInterface::solutionBegin method.
*/
/*! \fn LPSolverGurobi::GurobiSolutionIteratorType LPSolverGurobi::solutionEnd_impl() const
* \brief Get an iterator which is pointing to the end of the solution computed
* by Gurobi.
*
* \return Iterator pointing to the begin of the solution.
*
* \note Implementation for base class LPSolverInterface::solutionEnd method.
*/
/*! \fn LPSolverGurobi::GurobiValueType LPSolverGurobi::solution_impl(const GurobiIndexType variable) const;
* \brief Get the solution value of a variable computed by Gurobi.
*
* \param[in] variable Index of the variable for which the solution value is
* requested.
*
* \return Solution value of the selected variable.
*
* \note Implementation for base class LPSolverInterface::solution method.
*/
/*! \fn LPSolverGurobi::GurobiValueType LPSolverGurobi::objectiveFunctionValue_impl() const;
* \brief Get the objective function value from Gurobi.
*
* \return Objective function value.
*
* \note Implementation for base class
* LPSolverInterface::objectiveFunctionValue method.
*/
/*! \fn LPSolverGurobi::GurobiValueType LPSolverGurobi::objectiveFunctionValueBound_impl() const
* \brief Get the best known bound for the optimal solution of the current
* model.
*
* \return The bound for the current model.
*
* \note Implementation for base class
* LPSolverInterface::objectiveFunctionValueBound method.
*/
/*! \fn void LPSolverGurobi::exportModel_impl(const std::string& filename) const
* \brief Export model to file.
*
* \param[in] filename The name of the file where the model will be stored.
*
* \note Implementation for base class LPSolverInterface::exportModel method.
*/
/*! \fn void LPSolverGurobi::updateSolution()
* \brief Update solution if required.
*/
/*! \fn static int LPSolverGurobi::getCutLevelValue(const LPDef::MIP_CUT cutLevel);
* \brief Translate LPDef::MIP_CUT into corresponding Gurobi int value.
*
* \return Integer value corresponding to the LPDef::MIP_CUT parameter.
*/
/******************
* implementation *
******************/
namespace opengm {
inline LPSolverGurobi::LPSolverGurobi(const Parameter& parameter)
: LPSolverBaseClass(parameter), gurobiEnvironment_(),
gurobiModel_(gurobiEnvironment_), gurobiVariables_(), gurobiSolution_(),
gurobiSolutionValid_(false) {
// set parameter
try {
// multi-threading options
gurobiModel_.getEnv().set(GRB_IntParam_Threads, parameter_.numberOfThreads_);
// verbose options
if(!parameter_.verbose_) {
gurobiModel_.getEnv().set(GRB_IntParam_OutputFlag, 0);
gurobiModel_.getEnv().set(GRB_IntParam_TuneOutput, 0);
gurobiModel_.getEnv().set(GRB_IntParam_LogToConsole, 0);
}
// set hints
// CutUp is missing http://www.gurobi.com/resources/switching-to-gurobi/switching-from-cplex#setting
// tolerance settings
//gurobiModel_.getEnv().set(GRB_DoubleParam_Cutoff, parameter_.cutUp_); // Optimality Tolerance
gurobiModel_.getEnv().set(GRB_DoubleParam_OptimalityTol, parameter_.epOpt_); // Optimality Tolerance
gurobiModel_.getEnv().set(GRB_DoubleParam_IntFeasTol, parameter_.epInt_); // amount by which an integer variable can differ from an integer
gurobiModel_.getEnv().set(GRB_DoubleParam_MIPGapAbs, parameter_.epAGap_); // Absolute MIP gap tolerance
gurobiModel_.getEnv().set(GRB_DoubleParam_MIPGap, parameter_.epGap_); // Relative MIP gap tolerance
gurobiModel_.getEnv().set(GRB_DoubleParam_FeasibilityTol, parameter_.epRHS_);
gurobiModel_.getEnv().set(GRB_DoubleParam_MarkowitzTol, parameter_.epMrk_);
// memory setting
// missing
// time limit
gurobiModel_.getEnv().set(GRB_DoubleParam_TimeLimit, parameter_.timeLimit_);
// Root Algorithm
switch(parameter_.rootAlg_) {
case LPDef::LP_SOLVER_AUTO: {
gurobiModel_.getEnv().set(GRB_IntParam_Method, -1);
break;
}
case LPDef::LP_SOLVER_PRIMAL_SIMPLEX: {
gurobiModel_.getEnv().set(GRB_IntParam_Method, 0);
break;
}
case LPDef::LP_SOLVER_DUAL_SIMPLEX: {
gurobiModel_.getEnv().set(GRB_IntParam_Method, 1);
break;
}
case LPDef::LP_SOLVER_NETWORK_SIMPLEX: {
throw std::runtime_error("Gurobi does not support Network Simplex");
break;
}
case LPDef::LP_SOLVER_BARRIER: {
gurobiModel_.getEnv().set(GRB_IntParam_Method, 2);
break;
}
case LPDef::LP_SOLVER_SIFTING: {
gurobiModel_.getEnv().set(GRB_IntParam_Method, 1);
gurobiModel_.getEnv().set(GRB_IntParam_SiftMethod, 1);
break;
}
case LPDef::LP_SOLVER_CONCURRENT: {
gurobiModel_.getEnv().set(GRB_IntParam_Method, 4);
break;
}
default: {
throw std::runtime_error("Unknown Root Algorithm");
}
}
// Node Algorithm
switch(parameter_.nodeAlg_) {
case LPDef::LP_SOLVER_AUTO: {
gurobiModel_.getEnv().set(GRB_IntParam_NodeMethod, 1);
break;
}
case LPDef::LP_SOLVER_PRIMAL_SIMPLEX: {
gurobiModel_.getEnv().set(GRB_IntParam_NodeMethod, 0);
break;
}
case LPDef::LP_SOLVER_DUAL_SIMPLEX: {
gurobiModel_.getEnv().set(GRB_IntParam_NodeMethod, 1);
break;
}
case LPDef::LP_SOLVER_NETWORK_SIMPLEX: {
throw std::runtime_error("Gurobi does not support Network Simplex");
break;
}
case LPDef::LP_SOLVER_BARRIER: {
gurobiModel_.getEnv().set(GRB_IntParam_NodeMethod, 2);
break;
}
case LPDef::LP_SOLVER_SIFTING: {
throw std::runtime_error("Gurobi does not support Sifting as node algorithm");
break;
}
case LPDef::LP_SOLVER_CONCURRENT: {
throw std::runtime_error("Gurobi does not support concurrent solvers as node algorithm");
break;
}
default: {
throw std::runtime_error("Unknown Node Algorithm");
}
}
// presolve
switch(parameter_.presolve_) {
case LPDef::LP_PRESOLVE_AUTO: {
gurobiModel_.getEnv().set(GRB_IntParam_Presolve, -1);
break;
}
case LPDef::LP_PRESOLVE_OFF: {
gurobiModel_.getEnv().set(GRB_IntParam_Presolve, 0);
break;
}
case LPDef::LP_PRESOLVE_CONSERVATIVE: {
gurobiModel_.getEnv().set(GRB_IntParam_Presolve, 1);
break;
}
case LPDef::LP_PRESOLVE_AGGRESSIVE: {
gurobiModel_.getEnv().set(GRB_IntParam_Presolve, 2);
break;
}
default: {
throw std::runtime_error("Unknown Presolve Option");
}
}
// MIP EMPHASIS
switch(parameter_.mipEmphasis_) {
case LPDef::MIP_EMPHASIS_BALANCED: {
gurobiModel_.getEnv().set(GRB_IntParam_MIPFocus, 0);
break;
}
case LPDef::MIP_EMPHASIS_FEASIBILITY: {
gurobiModel_.getEnv().set(GRB_IntParam_MIPFocus, 1);
break;
}
case LPDef::MIP_EMPHASIS_OPTIMALITY: {
gurobiModel_.getEnv().set(GRB_IntParam_MIPFocus, 2);
break;
}
case LPDef::MIP_EMPHASIS_BESTBOUND: {
gurobiModel_.getEnv().set(GRB_IntParam_MIPFocus, 3);
break;
}
case LPDef::MIP_EMPHASIS_HIDDENFEAS: {
throw std::runtime_error("Gurobi does not support hidden feasibility as MIP-focus");
break;
}
default: {
throw std::runtime_error("Unknown MIP Emphasis Option");
}
}
// Tuning
// Probing missing
if(parameter_.cutLevel_ != LPDef::MIP_CUT_DEFAULT) {
gurobiModel_.getEnv().set(GRB_IntParam_Cuts, getCutLevelValue(parameter_.cutLevel_));
}
if(parameter_.cliqueCutLevel_ != LPDef::MIP_CUT_DEFAULT) {
gurobiModel_.getEnv().set(GRB_IntParam_CliqueCuts, getCutLevelValue(parameter_.cliqueCutLevel_));
}
if(parameter_.coverCutLevel_ != LPDef::MIP_CUT_DEFAULT) {
gurobiModel_.getEnv().set(GRB_IntParam_CoverCuts, getCutLevelValue(parameter_.coverCutLevel_));
}
if(parameter_.gubCutLevel_ != LPDef::MIP_CUT_DEFAULT) {
gurobiModel_.getEnv().set(GRB_IntParam_GUBCoverCuts, getCutLevelValue(parameter_.gubCutLevel_));
}
if(parameter_.mirCutLevel_ != LPDef::MIP_CUT_DEFAULT) {
gurobiModel_.getEnv().set(GRB_IntParam_MIRCuts, getCutLevelValue(parameter_.mirCutLevel_));
}
if(parameter_.iboundCutLevel_ != LPDef::MIP_CUT_DEFAULT) {
gurobiModel_.getEnv().set(GRB_IntParam_ImpliedCuts, getCutLevelValue(parameter_.iboundCutLevel_));
}
if(parameter_.flowcoverCutLevel_ != LPDef::MIP_CUT_DEFAULT) {
gurobiModel_.getEnv().set(GRB_IntParam_FlowCoverCuts, getCutLevelValue(parameter_.flowcoverCutLevel_));
}
if(parameter_.flowpathCutLevel_ != LPDef::MIP_CUT_DEFAULT) {
gurobiModel_.getEnv().set(GRB_IntParam_FlowPathCuts, getCutLevelValue(parameter_.flowpathCutLevel_));
}
// DisjCuts missing
// Gomory missing
} catch(const GRBException& e) {
std::cout << "Gurobi Error code = " << e.getErrorCode() << std::endl;
std::cout << e.getMessage() << std::endl;
throw std::runtime_error(e.getMessage());
} catch(...) {
std::cout << "Exception while setting parameter for Gurobi model." << std::endl;
throw std::runtime_error("Exception while setting parameter for Gurobi model.");
}
}
inline LPSolverGurobi::~LPSolverGurobi() {
}
inline typename LPSolverGurobi::GurobiValueType LPSolverGurobi::infinity_impl() {
return GRB_INFINITY;
}
inline void LPSolverGurobi::addContinuousVariables_impl(const GurobiIndexType numVariables, const GurobiValueType lowerBound, const GurobiValueType upperBound) {
gurobiVariables_.reserve(numVariables + gurobiVariables_.size());
// according to the Gurobi documentation, adding variables separately does not have any performance impact
try {
for(GurobiIndexType i = 0; i < numVariables; ++i) {
gurobiVariables_.push_back(gurobiModel_.addVar(lowerBound, upperBound, 0.0, GRB_CONTINUOUS));
}
gurobiSolution_.resize(gurobiVariables_.size());
gurobiSolutionValid_ = false;
gurobiModel_.update();
} catch(const GRBException& e) {
std::cout << "Gurobi Error code = " << e.getErrorCode() << std::endl;
std::cout << e.getMessage() << std::endl;
throw std::runtime_error(e.getMessage());
} catch(...) {
std::cout << "Exception while adding continuous variables to Gurobi model." << std::endl;
throw std::runtime_error("Exception while adding continuous variables to Gurobi model.");
}
}
inline void LPSolverGurobi::addIntegerVariables_impl(const GurobiIndexType numVariables, const GurobiValueType lowerBound, const GurobiValueType upperBound) {
gurobiVariables_.reserve(numVariables + gurobiVariables_.size());
// according to the Gurobi documentation, adding variables separately does not have any performance impact
try {
for(GurobiIndexType i = 0; i < numVariables; ++i) {
gurobiVariables_.push_back(gurobiModel_.addVar(lowerBound, upperBound, 0.0, GRB_INTEGER));
}
gurobiSolution_.resize(gurobiVariables_.size());
gurobiSolutionValid_ = false;
gurobiModel_.update();
} catch(const GRBException& e) {
std::cout << "Gurobi Error code = " << e.getErrorCode() << std::endl;
std::cout << e.getMessage() << std::endl;
throw std::runtime_error(e.getMessage());
} catch(...) {
std::cout << "Exception while adding integer variables to Gurobi model." << std::endl;
throw std::runtime_error("Exception while adding integer variables to Gurobi model.");
}
}
inline void LPSolverGurobi::addBinaryVariables_impl(const GurobiIndexType numVariables) {
gurobiVariables_.reserve(numVariables + gurobiVariables_.size());
// according to the Gurobi documentation, adding variables separately does not have any performance impact
try {
for(GurobiIndexType i = 0; i < numVariables; ++i) {
gurobiVariables_.push_back(gurobiModel_.addVar(0.0, 1.0, 0.0, GRB_BINARY));
}
gurobiSolution_.resize(gurobiVariables_.size());
gurobiSolutionValid_ = false;
gurobiModel_.update();
} catch(const GRBException& e) {
std::cout << "Gurobi Error code = " << e.getErrorCode() << std::endl;
std::cout << e.getMessage() << std::endl;
throw std::runtime_error(e.getMessage());
} catch(...) {
std::cout << "Exception while adding binary variables to Gurobi model." << std::endl;
throw std::runtime_error("Exception while adding binary variables to Gurobi model.");
}
}
inline void LPSolverGurobi::setObjective_impl(const Objective objective) {
switch(objective) {
case Minimize: {
try {
gurobiModel_.set(GRB_IntAttr_ModelSense, 1);
} catch(const GRBException& e) {
std::cout << "Gurobi Error code = " << e.getErrorCode() << std::endl;
std::cout << e.getMessage() << std::endl;
throw std::runtime_error(e.getMessage());
} catch(...) {
std::cout << "Exception while setting objective of Gurobi model." << std::endl;
throw std::runtime_error("Exception while setting objective of Gurobi model.");
}
break;
}
case Maximize: {
try {
gurobiModel_.set(GRB_IntAttr_ModelSense, -1);
} catch(const GRBException& e) {
std::cout << "Gurobi Error code = " << e.getErrorCode() << std::endl;
std::cout << e.getMessage() << std::endl;
throw std::runtime_error(e.getMessage());
} catch(...) {
std::cout << "Exception while setting objective of Gurobi model." << std::endl;
throw std::runtime_error("Exception while setting objective of Gurobi model.");
}
break;
}
default: {
throw std::runtime_error("Unknown Objective");
}
}
}
inline void LPSolverGurobi::setObjectiveValue_impl(const GurobiIndexType variable, const GurobiValueType value) {
try {
gurobiVariables_[variable].set(GRB_DoubleAttr_Obj, value);
} catch(const GRBException& e) {
std::cout << "Gurobi Error code = " << e.getErrorCode() << std::endl;
std::cout << e.getMessage() << std::endl;
throw std::runtime_error(e.getMessage());
} catch(...) {
std::cout << "Exception while setting objective value of Gurobi model." << std::endl;
throw std::runtime_error("Exception while setting objective value of Gurobi model.");
}
}
template<class ITERATOR_TYPE>
inline void LPSolverGurobi::setObjectiveValue_impl(ITERATOR_TYPE begin, const ITERATOR_TYPE end) {
try {
GRBLinExpr objective;
objective.addTerms(&(*begin), &gurobiVariables_[0], gurobiVariables_.size());
gurobiModel_.setObjective(objective);
} catch(const GRBException& e) {
std::cout << "Gurobi Error code = " << e.getErrorCode() << std::endl;
std::cout << e.getMessage() << std::endl;
throw std::runtime_error(e.getMessage());
} catch(...) {
std::cout << "Exception while setting objective value of Gurobi model." << std::endl;
throw std::runtime_error("Exception while setting objective value of Gurobi model.");
}
}
template<class VARIABLES_ITERATOR_TYPE, class COEFFICIENTS_ITERATOR_TYPE>
inline void LPSolverGurobi::setObjectiveValue_impl(VARIABLES_ITERATOR_TYPE variableIDsBegin, const VARIABLES_ITERATOR_TYPE variableIDsEnd, COEFFICIENTS_ITERATOR_TYPE coefficientsBegin) {
try {
while(variableIDsBegin != variableIDsEnd) {
gurobiVariables_[*variableIDsBegin].set(GRB_DoubleAttr_Obj, *coefficientsBegin);
++variableIDsBegin;
++coefficientsBegin;
}
} catch(const GRBException& e) {
std::cout << "Gurobi Error code = " << e.getErrorCode() << std::endl;
std::cout << e.getMessage() << std::endl;
throw std::runtime_error(e.getMessage());
} catch(...) {
std::cout << "Exception while setting objective value of Gurobi model." << std::endl;
throw std::runtime_error("Exception while setting objective value of Gurobi model.");
}
}
template<class VARIABLES_ITERATOR_TYPE, class COEFFICIENTS_ITERATOR_TYPE>
inline void LPSolverGurobi::addEqualityConstraint_impl(VARIABLES_ITERATOR_TYPE variableIDsBegin, const VARIABLES_ITERATOR_TYPE variableIDsEnd, COEFFICIENTS_ITERATOR_TYPE coefficientsBegin, const GurobiValueType bound, const std::string& constraintName) {
const GurobiIndexType numConstraintVariables = std::distance(variableIDsBegin, variableIDsEnd);
std::vector<GRBVar> constraintVariables;
constraintVariables.reserve(numConstraintVariables);
while(variableIDsBegin != variableIDsEnd) {
constraintVariables.push_back(gurobiVariables_[*variableIDsBegin]);
++variableIDsBegin;
}
try {
GRBLinExpr constraint;
constraint.addTerms(&(*coefficientsBegin), &constraintVariables[0], numConstraintVariables);
gurobiModel_.addConstr(constraint, GRB_EQUAL, bound, constraintName);
} catch(const GRBException& e) {
std::cout << "Gurobi Error code = " << e.getErrorCode() << std::endl;
std::cout << e.getMessage() << std::endl;
throw std::runtime_error(e.getMessage());
} catch(...) {
std::cout << "Exception while adding equality constraint to Gurobi model." << std::endl;
throw std::runtime_error("Exception while adding equality constraint to Gurobi model.");
}
}
template<class VARIABLES_ITERATOR_TYPE, class COEFFICIENTS_ITERATOR_TYPE>
inline void LPSolverGurobi::addLessEqualConstraint_impl(VARIABLES_ITERATOR_TYPE variableIDsBegin, const VARIABLES_ITERATOR_TYPE variableIDsEnd, COEFFICIENTS_ITERATOR_TYPE coefficientsBegin, const GurobiValueType bound, const std::string& constraintName) {
const GurobiIndexType numConstraintVariables = std::distance(variableIDsBegin, variableIDsEnd);
std::vector<GRBVar> constraintVariables;
constraintVariables.reserve(numConstraintVariables);
while(variableIDsBegin != variableIDsEnd) {
constraintVariables.push_back(gurobiVariables_[*variableIDsBegin]);
++variableIDsBegin;
}
try {
GRBLinExpr constraint;
constraint.addTerms(&(*coefficientsBegin), &constraintVariables[0], numConstraintVariables);
gurobiModel_.addConstr(constraint, GRB_LESS_EQUAL, bound, constraintName);
} catch(const GRBException& e) {
std::cout << "Gurobi Error code = " << e.getErrorCode() << std::endl;
std::cout << e.getMessage() << std::endl;
throw std::runtime_error(e.getMessage());
} catch(...) {
std::cout << "Exception while adding less equal constraint to Gurobi model." << std::endl;
throw std::runtime_error("Exception while adding less equal constraint to Gurobi model.");
}
}
template<class VARIABLES_ITERATOR_TYPE, class COEFFICIENTS_ITERATOR_TYPE>
inline void LPSolverGurobi::addGreaterEqualConstraint_impl(VARIABLES_ITERATOR_TYPE variableIDsBegin, const VARIABLES_ITERATOR_TYPE variableIDsEnd, COEFFICIENTS_ITERATOR_TYPE coefficientsBegin, const GurobiValueType bound, const std::string& constraintName) {
const GurobiIndexType numConstraintVariables = std::distance(variableIDsBegin, variableIDsEnd);
std::vector<GRBVar> constraintVariables;
constraintVariables.reserve(numConstraintVariables);
while(variableIDsBegin != variableIDsEnd) {
constraintVariables.push_back(gurobiVariables_[*variableIDsBegin]);
++variableIDsBegin;
}
try {
GRBLinExpr constraint;
constraint.addTerms(&(*coefficientsBegin), &constraintVariables[0], numConstraintVariables);
gurobiModel_.addConstr(constraint, GRB_GREATER_EQUAL, bound, constraintName);
} catch(const GRBException& e) {
std::cout << "Gurobi Error code = " << e.getErrorCode() << std::endl;
std::cout << e.getMessage() << std::endl;
throw std::runtime_error(e.getMessage());
} catch(...) {
std::cout << "Exception while adding greater equal constraint to Gurobi model." << std::endl;
throw std::runtime_error("Exception while adding greater equal constraint to Gurobi model.");
}
}
inline void LPSolverGurobi::addConstraintsFinished_impl() {
try {
gurobiModel_.update();
} catch(const GRBException& e) {
std::cout << "Gurobi Error code = " << e.getErrorCode() << std::endl;
std::cout << e.getMessage() << std::endl;
throw std::runtime_error(e.getMessage());
} catch(...) {
std::cout << "Exception while incorporating constraints into Gurobi model." << std::endl;
throw std::runtime_error("Exception while incorporating constraints into Gurobi model.");
}
}
inline void LPSolverGurobi::addConstraintsFinished_impl(GurobiTimingType& timing) {
try {
Timer timer;
timer.tic();
gurobiModel_.update();
timer.toc();
timing = timer.elapsedTime();
} catch(const GRBException& e) {
std::cout << "Gurobi Error code = " << e.getErrorCode() << std::endl;
std::cout << e.getMessage() << std::endl;
throw std::runtime_error(e.getMessage());
} catch(...) {
std::cout << "Exception while incorporating constraints into Gurobi model." << std::endl;
throw std::runtime_error("Exception while incorporating constraints into Gurobi model.");
}
}
template <class PARAMETER_TYPE, class PARAMETER_VALUE_TYPE>
inline void LPSolverGurobi::setParameter_impl(const PARAMETER_TYPE parameter, const PARAMETER_VALUE_TYPE value) {
try {
gurobiModel_.getEnv().set(parameter, value);
} catch(const GRBException& e) {
std::cout << "Gurobi Error code = " << e.getErrorCode() << std::endl;
std::cout << e.getMessage() << std::endl;
throw std::runtime_error(e.getMessage());
} catch(...) {
std::cout << "Exception while setting parameter for Gurobi model." << std::endl;
throw std::runtime_error("Exception while setting parameter for Gurobi model.");
}
}
inline bool LPSolverGurobi::solve_impl() {
gurobiSolutionValid_ = false;
try {
gurobiModel_.optimize();
if(gurobiModel_.get(GRB_IntAttr_Status) == GRB_OPTIMAL) {
return true;
} else {
return false;
}
} catch(const GRBException& e) {
std::cout << "Gurobi Error code = " << e.getErrorCode() << std::endl;
std::cout << e.getMessage() << std::endl;
throw std::runtime_error(e.getMessage());
} catch(...) {
std::cout << "Exception while solving Gurobi model." << std::endl;
throw std::runtime_error("Exception while solving Gurobi model.");
}
}
inline bool LPSolverGurobi::solve_impl(GurobiTimingType& timing) {
gurobiSolutionValid_ = false;
try {
gurobiModel_.optimize();
timing = gurobiModel_.get(GRB_DoubleAttr_Runtime);
if(gurobiModel_.get(GRB_IntAttr_Status) == GRB_OPTIMAL) {
return true;
} else {
return false;
}
} catch(const GRBException& e) {
std::cout << "Gurobi Error code = " << e.getErrorCode() << std::endl;
std::cout << e.getMessage() << std::endl;
throw std::runtime_error(e.getMessage());
} catch(...) {
std::cout << "Exception while solving Gurobi model." << std::endl;
throw std::runtime_error("Exception while solving Gurobi model.");
}
}
inline typename LPSolverGurobi::GurobiSolutionIteratorType LPSolverGurobi::solutionBegin_impl() const {
updateSolution();
return gurobiSolution_.begin();
}
inline typename LPSolverGurobi::GurobiSolutionIteratorType LPSolverGurobi::solutionEnd_impl() const {
updateSolution();
return gurobiSolution_.end();
}
inline typename LPSolverGurobi::GurobiValueType LPSolverGurobi::solution_impl(const GurobiIndexType variable) const {
try {
return gurobiVariables_[variable].get(GRB_DoubleAttr_X);
} catch(const GRBException& e) {
std::cout << "Gurobi Error code = " << e.getErrorCode() << std::endl;
std::cout << e.getMessage() << std::endl;
throw std::runtime_error(e.getMessage());
} catch(...) {
std::cout << "Exception while accessing Gurobi solution of variable." << std::endl;
throw std::runtime_error("Exception while accessing Gurobi solution of variable.");
}
}
inline typename LPSolverGurobi::GurobiValueType LPSolverGurobi::objectiveFunctionValue_impl() const {
try {
return gurobiModel_.get(GRB_DoubleAttr_ObjVal);
} catch(const GRBException& e) {
std::cout << "Gurobi Error code = " << e.getErrorCode() << std::endl;
std::cout << e.getMessage() << std::endl;
throw std::runtime_error(e.getMessage());
} catch(...) {
std::cout << "Exception while accessing Gurobi solution for objective function value." << std::endl;
throw std::runtime_error("Exception while accessing Gurobi solution for objective function value.");
}
}
inline typename LPSolverGurobi::GurobiValueType LPSolverGurobi::objectiveFunctionValueBound_impl() const {
try {
if(gurobiModel_.get(GRB_IntAttr_IsMIP)) {
return gurobiModel_.get(GRB_DoubleAttr_ObjBound);
} else {
return gurobiModel_.get(GRB_DoubleAttr_ObjVal);
}
} catch(const GRBException& e) {
std::cout << "Gurobi Error code = " << e.getErrorCode() << std::endl;
std::cout << e.getMessage() << std::endl;
throw std::runtime_error(e.getMessage());
} catch(...) {
std::cout << "Exception while accessing Gurobi bound for objective function value." << std::endl;
throw std::runtime_error("Exception while accessing Gurobi bound for objective function value.");
}
}
inline void LPSolverGurobi::exportModel_impl(const std::string& filename) const {
try {
gurobiModel_.write(filename);
} catch(const GRBException& e) {
std::cout << "Gurobi Error code = " << e.getErrorCode() << std::endl;
std::cout << e.getMessage() << std::endl;
throw std::runtime_error(e.getMessage());
} catch(...) {
std::cout << "Exception while writing Gurobi model to file." << std::endl;
throw std::runtime_error("Exception while writing Gurobi model to file.");
}
}
inline void LPSolverGurobi::updateSolution() const {
if(!gurobiSolutionValid_) {
try {
for(GurobiIndexType i = 0; i < static_cast<GurobiIndexType>(gurobiVariables_.size()); ++i) {
gurobiSolution_[i] = gurobiVariables_[i].get(GRB_DoubleAttr_X);
}
gurobiSolutionValid_ = true;
} catch(const GRBException& e) {
std::cout << "Gurobi Error code = " << e.getErrorCode() << std::endl;
std::cout << e.getMessage() << std::endl;
throw std::runtime_error(e.getMessage());
} catch(...) {
std::cout << "Exception while updating Gurobi solution." << std::endl;
throw std::runtime_error("Exception while updating Gurobi solution.");
}
}
}
inline int LPSolverGurobi::getCutLevelValue(const LPDef::MIP_CUT cutLevel) {
switch(cutLevel){
case LPDef::MIP_CUT_DEFAULT:
case LPDef::MIP_CUT_AUTO:
return -1;
case LPDef::MIP_CUT_OFF:
return 0;
case LPDef::MIP_CUT_ON:
return 1;
case LPDef::MIP_CUT_AGGRESSIVE:
return 2;
case LPDef::MIP_CUT_VERYAGGRESSIVE:
return 3;
default:
throw std::runtime_error("Unknown Cut level.");
}
}
} // namespace opengm
#endif /* OPENGM_LP_SOLVER_GUROBI_HXX_ */
| 18,298 |
880 |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from typing import Callable, Optional
import libcst as cst
from libcst import parse_expression
from libcst._nodes.tests.base import CSTNodeTest
from libcst.metadata import CodeRange
from libcst.testing.utils import data_provider
class IfExpTest(CSTNodeTest):
@data_provider(
(
# Simple if experessions
(
cst.IfExp(
body=cst.Name("foo"), test=cst.Name("bar"), orelse=cst.Name("baz")
),
"foo if bar else baz",
),
# Parenthesized if expressions
(
cst.IfExp(
lpar=(cst.LeftParen(),),
body=cst.Name("foo"),
test=cst.Name("bar"),
orelse=cst.Name("baz"),
rpar=(cst.RightParen(),),
),
"(foo if bar else baz)",
),
(
cst.IfExp(
body=cst.Name(
"foo", lpar=(cst.LeftParen(),), rpar=(cst.RightParen(),)
),
whitespace_before_if=cst.SimpleWhitespace(""),
whitespace_after_if=cst.SimpleWhitespace(""),
test=cst.Name(
"bar", lpar=(cst.LeftParen(),), rpar=(cst.RightParen(),)
),
whitespace_before_else=cst.SimpleWhitespace(""),
whitespace_after_else=cst.SimpleWhitespace(""),
orelse=cst.Name(
"baz", lpar=(cst.LeftParen(),), rpar=(cst.RightParen(),)
),
),
"(foo)if(bar)else(baz)",
CodeRange((1, 0), (1, 21)),
),
# Make sure that spacing works
(
cst.IfExp(
lpar=(cst.LeftParen(whitespace_after=cst.SimpleWhitespace(" ")),),
body=cst.Name("foo"),
whitespace_before_if=cst.SimpleWhitespace(" "),
whitespace_after_if=cst.SimpleWhitespace(" "),
test=cst.Name("bar"),
whitespace_before_else=cst.SimpleWhitespace(" "),
whitespace_after_else=cst.SimpleWhitespace(" "),
orelse=cst.Name("baz"),
rpar=(cst.RightParen(whitespace_before=cst.SimpleWhitespace(" ")),),
),
"( foo if bar else baz )",
CodeRange((1, 2), (1, 25)),
),
)
)
def test_valid(
self, node: cst.CSTNode, code: str, position: Optional[CodeRange] = None
) -> None:
self.validate_node(node, code, parse_expression, expected_position=position)
@data_provider(
(
(
lambda: cst.IfExp(
cst.Name("bar"),
cst.Name("foo"),
cst.Name("baz"),
lpar=(cst.LeftParen(),),
),
"left paren without right paren",
),
(
lambda: cst.IfExp(
cst.Name("bar"),
cst.Name("foo"),
cst.Name("baz"),
rpar=(cst.RightParen(),),
),
"right paren without left paren",
),
)
)
def test_invalid(
self, get_node: Callable[[], cst.CSTNode], expected_re: str
) -> None:
self.assert_invalid(get_node, expected_re)
| 2,201 |
2,144 |
/**
* 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.pinot.sql.parsers.dml;
import java.util.List;
import org.apache.pinot.common.utils.DataSchema;
import org.apache.pinot.spi.config.task.AdhocTaskConfig;
/**
* DML Statement
*/
public interface DataManipulationStatement {
/**
* The method to execute this Statement, e.g. MINION or HTTP.
* @return
*/
ExecutionType getExecutionType();
/**
* Generate minion task config for this statement.
* @return Adhoc minion task config
*/
AdhocTaskConfig generateAdhocTaskConfig();
/**
* Execute the statement and format response to response row format.
* Not used for Minion ExecutionType.
* @return Result rows
*/
List<Object[]> execute();
/**
* @return Result schema for response
*/
DataSchema getResultSchema();
/**
* Execution method for this SQL statement.
*/
enum ExecutionType {
HTTP,
MINION
}
}
| 488 |
1,379 |
package voldemort.store.stats;
import org.junit.Before;
import org.junit.Test;
public class RequestCounterTest {
private RequestCounter requestCounter;
@Before
public void setUp() {
// Initialize the RequestCounter with a histogram
requestCounter = new RequestCounter("tests.RequestCounterTest", 10000, true);
}
@Test
public void test() {
long val = 234;
requestCounter.addRequest(val);
}
@Test
public void testLargeValues() {
long val = 999999992342756424l;
requestCounter.addRequest(val);
}
}
| 220 |
302 |
<reponame>susannahsoon/oldperth<filename>nyc/task_reader.py
'''Read tasks from a variety of possible sources.
If a single argument is passed to the program beginning with 'http://', it will
read tasks from that URL. Otherwise it will read from files passed as
parameters. Otherwise it will read from stdin.
'''
import os
import subprocess
import sys
import fileinput
def Tasks():
if len(sys.argv) > 1 and sys.argv[1].startswith('http://'):
assert len(sys.argv) == 2, 'Cannot read tasks from both argv and http'
url = sys.argv[1]
try:
while True:
task = subprocess.check_output(['curl', '--silent', url]).strip()
yield task
except subprocess.CalledProcessError:
# Done, we hope!
pass
else:
for task in fileinput.input():
yield task
| 286 |
348 |
<gh_stars>100-1000
{"nom":"<NAME>","circ":"3ème circonscription","dpt":"Haute-Vienne","inscrits":581,"abs":311,"votants":270,"blancs":42,"nuls":24,"exp":204,"res":[{"nuance":"REM","nom":"<NAME>","voix":150},{"nuance":"LR","nom":"<NAME>","voix":54}]}
| 100 |
3,227 |
<gh_stars>1000+
// Copyright (c) 2005-2009 INRIA Sophia-Antipolis (France).
// All rights reserved.
//
// This file is part of CGAL (www.cgal.org)
//
// $URL$
// $Id$
// SPDX-License-Identifier: LGPL-3.0-or-later OR LicenseRef-Commercial
//
//
// Author(s) : <NAME>, <NAME>
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <boost/format.hpp>
#include <CGAL/CGAL_Ipelet_base.h>
#include <algorithm>
#include <CGAL/point_generators_2.h>
#include <CGAL/copy_n.h>
#include <CGAL/random_selection.h>
#include <CGAL/random_convex_set_2.h>
#include <CGAL/random_polygon_2.h>
#include <CGAL/Polygon_2.h>
#include <CGAL/Join_input_iterator.h>
#include <CGAL/function_objects.h>
#include <CGAL/copy_n.h>
namespace CGAL_generator{
const std::string sublabel[] ={
"Points in a disk","Points on a grid","Points in a square","Points on a convex hull","Polygon","Segments in a square", "Circles (center in a square)","Help"
};
const std::string hlpmsg[] ={
"Generate random inputs. You have to specify the size of the bounding box and the number of elements"};
typedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;
struct generator
: CGAL::Ipelet_base<Kernel,8>
{
typedef CGAL::Creator_uniform_2<Kernel::FT,Point_2> Creator;
typedef CGAL::Random_points_in_square_2<Point_2,Creator> Point_generator;
typedef CGAL::Creator_uniform_2<Kernel::FT,Point_2> Pt_creator;
generator()
: CGAL::Ipelet_base<Kernel,8>("Generators",sublabel, hlpmsg){};
void protected_run(int);
};
void generator::protected_run(int fn)
{
if (fn==7) {
show_help(false);
return;
}
std::list<Point_2> pt_list;
std::list<Circle_2> cir_list;
Iso_rectangle_2 bbox=
read_active_objects(
CGAL::dispatch_or_drop_output<Point_2,Circle_2>(
std::back_inserter(pt_list),
std::back_inserter(cir_list)
)
);
Kernel::Vector_2 origin;
double size=200;
int ret_val;
if (fn==0){
if (cir_list.size()==0) { print_error_message(("Selection must be a circle")); return;}
Circle_2 circ=*cir_list.begin();
size = sqrt(circ.squared_radius());
origin= circ.center()-CGAL::ORIGIN;
}else{
size = (bbox.xmax()-bbox.xmin())/2;
origin= Kernel::Vector_2((bbox.xmin()+bbox.xmax())/2,(bbox.ymin()+bbox.ymax())/2);
if (size<1){
size=200;
//boost::tie(ret_val,size)=request_value_from_user<int>((boost::format("Size (default : %1%)") % size).str());
//if (ret_val == -1) return;
//if (ret_val == 0) size=200;
origin = Kernel::Vector_2(200,200);
}
}
int nbelements=30;
boost::tie(ret_val,nbelements)=request_value_from_user<int>((boost::format("Number of elements (default : %1%)") % nbelements).str() );
if (ret_val == -1) return;
if (ret_val == 0) nbelements=30;
if(nbelements < 3){
print_error_message("Not a good value");
return;
}
std::vector<Point_2> points;
std::vector<Segment_2> segments;
if (fn==5)
points.reserve(nbelements);
else
segments.reserve(nbelements);
get_IpePage()->deselectAll();
switch(fn){
case 0:{//random point in a circle
CGAL::Random_points_in_disc_2<Point_2,Creator> gs( size);
std::copy_n( gs, nbelements, std::back_inserter(points));
}
break;
case 1://random point on a grid
points_on_square_grid_2( size, nbelements, std::back_inserter(points),Creator());
break;
case 6:
case 2://points in a square : side =
{CGAL::Random_points_in_square_2<Point_2, Creator> gc (size);
std::copy_n( gc, nbelements, std::back_inserter(points));
}
break;
case 3:{//draw random set of point on a convex hull
CGAL::random_convex_set_2(nbelements, std::back_inserter(points),
Point_generator( size));
}
break;
case 4:
// create k-gon and write it into a window:
CGAL::random_polygon_2(nbelements, std::back_inserter(points),Point_generator(size));
for ( std::vector<Point_2>::iterator it=points.begin(); it!=points.end(); ++it) *it = *it + origin;
draw_polyline_in_ipe(points.begin(),points.end(),true);
return;
case 5://Random segments
typedef CGAL::Random_points_in_square_2<Point_2, Creator> P1;
typedef CGAL::Random_points_in_square_2<Point_2, Creator> P2;
P1 p1 (size);
P2 p2 (size);
typedef CGAL::Creator_uniform_2< Point_2, Segment_2> Seg_creator;
typedef CGAL::Join_input_iterator_2< P1, P2, Seg_creator> Seg_iterator;
Seg_iterator g( p1, p2);
std::copy_n( g, nbelements, std::back_inserter(segments) );
break;
};
if (fn==6){
CGAL::Random random;
for (std::vector<Point_2>::iterator it_pt=points.begin();it_pt!=points.end();++it_pt)
draw_in_ipe(Circle_2(*it_pt+origin,pow(random.get_double(size/20.,size/2.),2) ));
group_selected_objects_();
}
else
if (!points.empty()){// Translate and draw points
for ( std::vector<Point_2>::iterator it=points.begin(); it!=points.end(); ++it) *it = *it + origin;
draw_in_ipe(points.begin(),points.end());
}
else
if (!segments.empty()){// Translate and draw segments
for ( std::vector<Segment_2>::iterator it=segments.begin(); it!=segments.end(); ++it)
*it = Segment_2( it->source() + origin, it->target() + origin);
draw_in_ipe(segments.begin(),segments.end());
}
}
}
CGAL_IPELET(CGAL_generator::generator)
| 2,350 |
852 |
#include "HLTTrackWithHits.h"
// declare this class as a framework plugin
#include "FWCore/Framework/interface/MakerMacros.h"
DEFINE_FWK_MODULE(HLTTrackWithHits);
| 58 |
323 |
package cn.huanzi.qch.springbootmybatis.service;
import cn.huanzi.qch.springbootmybatis.mapper.UserMapper;
import cn.huanzi.qch.springbootmybatis.pojo.Result;
import cn.huanzi.qch.springbootmybatis.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public Result insert(User user) {
int i = userMapper.insert(user);
if (i > 0) {
return Result.build(200, "操作成功!", user);
} else {
return Result.build(400, "操作失败!", null);
}
}
@Override
public Result delete(User user) {
int i = userMapper.delete(user);
if (i > 0) {
return Result.build(200, "操作成功!", user);
} else {
return Result.build(400, "操作失败!", null);
}
}
@Override
public Result update(User user) {
int i = userMapper.update(user);
if (i > 0) {
return select(user);
} else {
return Result.build(400, "操作失败!", null);
}
}
@Override
public Result select(User user) {
User user1 = userMapper.select(user);
if (user1 != null) {
return Result.build(200, "操作成功!", user1);
} else {
return Result.build(400, "操作失败!", user1);
}
}
}
| 753 |
440 |
<filename>IGC/Compiler/CISACodeGen/Simd32Profitability.hpp
/*========================== begin_copyright_notice ============================
Copyright (C) 2017-2021 Intel Corporation
SPDX-License-Identifier: MIT
============================= end_copyright_notice ===========================*/
#pragma once
#include "common/LLVMWarningsPush.hpp"
#include "llvm/Pass.h"
#include "llvm/Analysis/LoopInfo.h"
#include "common/LLVMWarningsPop.hpp"
#include "Compiler/CodeGenPublic.h"
#include "Compiler/CISACodeGen/WIAnalysis.hpp"
namespace IGC
{
namespace IGCMD {
class MetaDataUtils;
}
/// @brief This pass implements a heuristic to determine whether SIMD32 is profitable.
class Simd32ProfitabilityAnalysis : public llvm::FunctionPass
{
public:
static char ID;
Simd32ProfitabilityAnalysis();
~Simd32ProfitabilityAnalysis() {}
virtual llvm::StringRef getPassName() const override
{
return "Simd32Profitability";
}
virtual bool runOnFunction(llvm::Function& F) override;
virtual void getAnalysisUsage(llvm::AnalysisUsage& AU) const override
{
AU.setPreservesAll();
AU.addRequired<WIAnalysis>();
AU.addRequired<llvm::LoopInfoWrapperPass>();
AU.addRequired<llvm::PostDominatorTreeWrapperPass>();
AU.addRequired<MetaDataUtilsWrapper>();
AU.addRequired<CodeGenContextWrapper>();
}
bool isSimd32Profitable() const { return m_isSimd32Profitable; }
bool isSimd16Profitable() const { return m_isSimd16Profitable; }
private:
llvm::Function* F;
llvm::PostDominatorTree* PDT;
llvm::LoopInfo* LI;
IGCMD::MetaDataUtils* pMdUtils;
WIAnalysis* WI;
bool m_isSimd32Profitable;
bool m_isSimd16Profitable;
unsigned getLoopCyclomaticComplexity();
bool checkSimd32Profitable(CodeGenContext*);
bool checkSimd16Profitable(CodeGenContext*);
unsigned estimateLoopCount(llvm::Loop* L);
unsigned estimateLoopCount_CASE1(llvm::Loop* L);
unsigned estimateLoopCount_CASE2(llvm::Loop* L);
bool isSelectBasedOnGlobalIdX(llvm::Value*);
bool checkPSSimd32Profitable();
};
} // namespace IGC
| 945 |
474 |
//
// TuSDKCPStackFilterBarBase.h
// TuSDK
//
// Created by <NAME> on 16/9/23.
// Copyright © 2016年 tusdk.<EMAIL>. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "TuSDKCPStackFilterTableView.h"
#import "TuSDKCPFilterOnlineControllerInterface.h"
@protocol TuSDKCPStackFilterBarInterface;
/**
* 滤镜组选择栏委托
*/
@protocol TuSDKCPStackFilterBarDelegate <NSObject>
/**
* 选中一个滤镜数据
*
* @param bar 滤镜组选择栏
* @param cell 滤镜分组元素视图
* @param mode 滤镜分组元素
*
* @return BOOL 是否允许继续执行
*/
- (BOOL)onTuSDKCPGroupFilterBar:(UIView<TuSDKCPStackFilterBarInterface> *)bar
selectedCell:(UITableViewCell<TuSDKCPGroupFilterItemCellInterface> *)cell
mode:(TuSDKCPGroupFilterItem *)mode;
@end
#pragma mark - TuSDKCPStackFilterBarInterface
/**
* 滤镜组选择栏接口
*/
@protocol TuSDKCPStackFilterBarInterface <NSObject>
/**
* 滤镜组选择栏委托
*/
@property (nonatomic, weak) id<TuSDKCPStackFilterBarDelegate> delegate;
/**
* 滤镜分组元素类型
*/
@property (nonatomic)lsqGroupFilterAction action;
/**
* 开启滤镜配置选项
*/
@property (nonatomic) BOOL enableFilterConfig;
/**
* 行视图宽度
*/
@property (nonatomic)CGFloat cellWidth;
/**
* 滤镜列表行视图类 (默认:TuSDKCPGroupFilterItemCellBase, 需要继承 UITableViewCell<TuSDKCPGroupFilterItemCellInterface>)
*/
@property (nonatomic, strong)Class filterTableCellClazz;
/**
* 滤镜列表折叠视图类 (默认:TuSDKCPGroupFilterGroupCellBase, 需要继承 UITableViewCell<TuSDKCPGroupFilterItemCellInterface>)
*/
@property (nonatomic, strong) Class stackViewClazz;
/**
* 是否保存最后一次使用的滤镜
*/
@property (nonatomic) BOOL saveLastFilter;
/**
* 自动选择分组滤镜指定的默认滤镜
*/
@property (nonatomic) BOOL autoSelectGroupDefaultFilter;
/**
* 指定显示的滤镜组
*/
@property (nonatomic, retain) NSArray * filterGroup;
/**
* 是否允许选择列表
*/
@property (nonatomic) BOOL allowsSelection;
/**
* 开启无效果滤镜 (默认: 开启)
*/
@property (nonatomic) BOOL enableNormalFilter;
/**
* 开启在线滤镜
*/
@property (nonatomic) BOOL enableOnlineFilter;
/**
* 视图控制器
*/
@property (nonatomic, assign) UIViewController *controller;
/**
* 开启用户历史记录
*/
@property (nonatomic) BOOL enableHistory;
/**
* 在线滤镜控制器类型 (需要继承 UIViewController,以及实现TuSDKCPFilterOnlineControllerInterface接口)
*/
@property (nonatomic) Class onlineControllerClazz;
/**
* 是否渲染封面 (使用设置的滤镜直接渲染,需要拥有滤镜列表封面设置权限,请访问TUTUCLOUD.com控制台)
*/
@property (nonatomic) BOOL isRenderFilterThumb;
/**
* 自定义封面原图(使用设置的滤镜直接渲染,需要拥有滤镜列表封面设置权限,请访问TUTUCLOUD.com控制台)
*
* @param image 自定义封面原图
*/
- (void)setThumbImage:(UIImage *)image;
/**
* 加载滤镜分组
*/
- (void)loadFilters;
/**
* 加载滤镜分组
*
* @param option 滤镜配置选项
*/
- (void)loadFiltersWithOption:(TuSDKFilterOption *)option;
/**
* 删除滤镜组
*
* @param groupId 滤镜组ID
*/
- (void)removeWithGroupId:(uint64_t)groupId;
/**
* 退出删除状态
*/
- (void)exitRemoveState;
@end
#pragma mark - TuSDKCPFilterBarBase
/**
* 滤镜组选择栏
*/
@interface TuSDKCPStackFilterBarBase : UIView<TuSDKCPStackFilterTableViewDelegate, TuSDKCPGroupFilterGroupCellDelegate, TuSDKCPFilterOnlineControllerDelegate, TuSDKCPStackFilterBarInterface>
/**
* 滤镜列表
*/
@property (nonatomic, readonly) UIView<TuSDKCPStackFilterTableViewInterface> *filterTable;
/**
* 滤镜组选择栏委托
*/
@property (nonatomic, weak) id<TuSDKCPStackFilterBarDelegate> delegate;
/**
* 滤镜分组元素类型
*/
@property (nonatomic)lsqGroupFilterAction action;
/**
* 行视图宽度
*/
@property (nonatomic)CGFloat cellWidth;
/**
* 区头视图宽度
*/
@property (nonatomic)CGFloat stackViewWidth;
/**
* 滤镜列表行视图类 (默认:TuSDKCPGroupFilterItemCellBase, 需要继承 UITableViewCell<TuSDKCPGroupFilterItemCellInterface>)
*/
@property (nonatomic, strong)Class filterTableCellClazz;
/**
* 滤镜列表折叠视图类 (默认:TuSDKCPGroupFilterGroupCellBase, 需要继承 UITableViewCell<TuSDKCPGroupFilterItemCellInterface>)
*/
@property (nonatomic, strong) Class stackViewClazz;
/**
* 是否保存最后一次使用的滤镜
*/
@property (nonatomic) BOOL saveLastFilter;
/**
* 自动选择分组滤镜指定的默认滤镜
*/
@property (nonatomic) BOOL autoSelectGroupDefaultFilter;
/**
* 指定显示的滤镜组
*/
@property (nonatomic, retain) NSArray * filterGroup;
/**
* 是否允许选择列表
*/
@property (nonatomic) BOOL allowsSelection;
/**
* 开启滤镜配置选项
*/
@property (nonatomic) BOOL enableFilterConfig;
/**
* 开启无效果滤镜 (默认: 开启)
*/
@property (nonatomic) BOOL enableNormalFilter;
/**
* 开启在线滤镜
*/
@property (nonatomic) BOOL enableOnlineFilter;
/**
* 视图控制器
*/
@property (nonatomic, assign) UIViewController *controller;
/**
* 开启用户历史记录
*/
@property (nonatomic) BOOL enableHistory;
/**
* 在线滤镜控制器类型 (需要继承 UIViewController,以及实现TuSDKCPFilterOnlineControllerInterface接口)
*/
@property (nonatomic) Class onlineControllerClazz;
/**
* 是否渲染封面 (使用设置的滤镜直接渲染,需要拥有滤镜列表封面设置权限,请访问TUTUCLOUD.com控制台)
*/
@property (nonatomic) BOOL isRenderFilterThumb;
@end
| 2,845 |
14,668 |
<reponame>zealoussnow/chromium
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef ASH_PUBLIC_CPP_PROJECTOR_PROJECTOR_ANNOTATOR_CONTROLLER_H_
#define ASH_PUBLIC_CPP_PROJECTOR_PROJECTOR_ANNOTATOR_CONTROLLER_H_
#include "ash/public/cpp/ash_public_export.h"
namespace ash {
struct AnnotatorTool;
// This controller provides an interface to control the annotator tools.
class ASH_PUBLIC_EXPORT ProjectorAnnotatorController {
public:
static ProjectorAnnotatorController* Get();
ProjectorAnnotatorController();
ProjectorAnnotatorController(const ProjectorAnnotatorController&) = delete;
ProjectorAnnotatorController& operator=(const ProjectorAnnotatorController&) =
delete;
virtual ~ProjectorAnnotatorController();
// ProjectorController will use the following functions to manipulate the
// annotator.
// Sets the tool inside the annotator WebUI.
virtual void SetTool(const AnnotatorTool& tool) = 0;
// Undoes the last stroke in the annotator content.
virtual void Undo() = 0;
// Redoes the undone stroke in the annotator content.
virtual void Redo() = 0;
// Clears the contents of the annotator canvas.
virtual void Clear() = 0;
};
} // namespace ash
#endif // ASH_PUBLIC_CPP_PROJECTOR_PROJECTOR_ANNOTATOR_CONTROLLER_H_
| 436 |
988 |
<reponame>oyarzun/incubator-netbeans<filename>php/php.api.phpmodule/src/org/netbeans/modules/php/api/util/StringUtils.java
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.php.api.util;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.regex.Pattern;
import org.netbeans.api.annotations.common.NonNull;
import org.netbeans.api.annotations.common.NullAllowed;
import org.openide.util.Parameters;
/**
* Miscellaneous string utilities.
* @author <NAME>
*/
public final class StringUtils {
private StringUtils() {
}
/**
* Return <code>true</code> if the String is not <code>null</code>
* and has any character after trimming.
* @param input input <tt>String</tt>, can be <code>null</code>.
* @return <code>true</code> if the String is not <code>null</code>
* and has any character after trimming.
* @see #isEmpty(String)
*/
public static boolean hasText(String input) {
return input != null && !input.trim().isEmpty();
}
/**
* Return <code>true</code> if the String is <code>null</code>
* or has no characters.
* @param input input <tt>String</tt>, can be <code>null</code>
* @return <code>true</code> if the String is <code>null</code>
* or has no characters
* @see #hasText(String)
*/
public static boolean isEmpty(String input) {
return input == null || input.isEmpty();
}
/**
* Implode collection of strings to one string using delimiter.
* @param items collection of strings to be imploded, can be empty (but not <code>null</code>)
* @param delimiter delimiter to be used
* @return one string of imploded strings using delimiter, never <code>null</code>
* @see #explode(String, String)
* @since 2.14
*/
public static String implode(Collection<String> items, String delimiter) {
Parameters.notNull("items", items);
Parameters.notNull("delimiter", delimiter);
if (items.isEmpty()) {
return ""; // NOI18N
}
StringBuilder buffer = new StringBuilder(200);
boolean first = true;
for (String s : items) {
if (!first) {
buffer.append(delimiter);
}
buffer.append(s);
first = false;
}
return buffer.toString();
}
/**
* Explode the string using the delimiter.
* @param string string to be exploded, can be <code>null</code>
* @param delimiter delimiter to be used, cannot be empty string
* @return list of exploded strings using delimiter
* @see #implode(List, String)
*/
public static List<String> explode(@NullAllowed String string, String delimiter) {
Parameters.notEmpty("delimiter", delimiter); // NOI18N
if (!hasText(string)) {
return Collections.<String>emptyList();
}
assert string != null;
return Arrays.asList(string.split(Pattern.quote(delimiter)));
}
/**
* Get the case-insensitive {@link Pattern pattern} for the given <tt>String</tt>
* or <code>null</code> if it does not contain any "?" or "*" characters.
* <p>
* This pattern is "unbounded", it means that the <tt>text</tt> can be anywhere
* in the matching string. See {@link #getExactPattern(String)} for pattern matching the whole string.
* @param text the text to get {@link Pattern pattern} for
* @return the case-insensitive {@link Pattern pattern} or <code>null</code>
* if the <tt>text</tt> does not contain any "?" or "*" characters
* @see #getExactPattern(String)
*/
public static Pattern getPattern(String text) {
Parameters.notNull("text", text); // NOI18N
return getPattern0(text, ".*", ".*"); // NOI18N
}
/**
* Get the case-insensitive {@link Pattern pattern} for the given <tt>String</tt>
* or <code>null</code> if it does not contain any "?" or "*" characters.
* <p>
* This pattern exactly matches the string, it means that the <tt>text</tt> must be fully matched in the
* matching string. See {@link #getPattern(String)} for pattern matching any substring in the matching string.
* @param text the text to get {@link Pattern pattern} for
* @return the case-insensitive {@link Pattern pattern} or <code>null</code>
* if the <tt>text</tt> does not contain any "?" or "*" characters
* @see #getPattern(String)
*/
public static Pattern getExactPattern(String text) {
Parameters.notNull("text", text); // NOI18N
return getPattern0(text, "^", "$"); // NOI18N
}
/**
* Keep all digits and letters only; other characters are replaced with dash ("-"). All upper-cased letters
* are replaced with dash ("-") and its lower-cased variants. No more than one dash ("-") is added at once.
* <p>
* Example: "My Super_Company1" is converted to "my-super-company1".
* @param input text to be converted
* @return lower-cased input string
* @since 2.1
*/
public static String webalize(String input) {
StringBuilder sb = new StringBuilder(input.length() * 2);
final char dash = '-'; // NOI18N
char lastChar = 0;
for (int i = 0; i < input.length(); ++i) {
boolean addDash = false;
char ch = input.charAt(i);
if (Character.isLetterOrDigit(ch)) {
if (Character.isUpperCase(ch)) {
addDash = true;
ch = Character.toLowerCase(ch);
}
} else {
ch = dash;
}
if (ch == dash && (lastChar == dash || sb.length() == 0)) {
continue;
}
if (addDash && lastChar != dash && sb.length() > 0) {
sb.append(dash);
}
sb.append(ch);
lastChar = ch;
}
if (lastChar == dash) {
sb.deleteCharAt(sb.length() - 1);
}
return sb.toString();
}
/**
* Capitalizes first character of the passed input.
* <p>
* Example: foobarbaz -> Foobarbaz
* @param input text to be capitalized, never null or empty
* @return capitalized input string, never null
* @since 2.21
*/
public static String capitalize(String input) {
Parameters.notEmpty("input", input); //NOI18N
return input.substring(0, 1).toUpperCase() + input.substring(1);
}
/**
* Decapitalizes first character of the passed input.
* <p>
* Example: Foobarbaz -> foobarbaz
* @param input text to be decapitalized, never null or empty
* @return decapitalized input string, never null
* @since 2.33
*/
public static String decapitalize(String input) {
Parameters.notEmpty("input", input); //NOI18N
return input.substring(0, 1).toLowerCase() + input.substring(1);
}
/**
* Truncates the string with specific width. The trancated string contains
* the marker's length.
*
* <p>
* Example:<br>
* "0123456789", start:1, width:5, marker: "..." -> "12..."<br>
* "0123456789", start:1, width:-4, marker: "..." -> "12..."<br>
* "0123456789", start:-9, width:5, marker: "..." -> "12..."<br>
* "0123456789", start:-9, width:-4, marker: "..." -> "12..."<br>
* "0123456789", start:-7, width:6, marker: "..." -> "345..."<br>
* "0123456789", start:0, width:-4, marker: "..." -> "012..."<br>
* "0123456789", start:4, width:6, marker: "..." -> "456789"<br>
*
* @param string text to be truncated, never {@code null}
* @param start the start position. if it's negative, the position from the
* end of the string
* @param width the width of the truncated string. it contains the marker's
* length. if it's negative, truncates the width from the end of the string
* @param marker the marker, can be null, if it's {@code null}, "..." is
* used
* @return the truncated string with specific width and the marker
* @since 2.83
*/
public static String truncate(@NonNull String string, int start, int width, @NullAllowed String marker) {
Parameters.notNull("input", string); // NOI18N
String trimMarker = "..."; // NOI18N
if (marker != null) {
trimMarker = marker;
}
int trimStart = start;
if (trimStart < 0) {
trimStart += string.length();
}
int trimWidth = width;
if (trimWidth < 0) {
trimWidth = string.length() + trimWidth - trimStart;
}
if (trimStart < 0
|| trimWidth < 0
|| string.length() < trimStart
|| trimWidth < trimMarker.length()) {
// invalid range
return string;
}
boolean addMarker = trimStart + trimWidth < string.length();
int trimEnd = !addMarker ? string.length() : trimStart + trimWidth;
String trimedString = string.substring(trimStart, trimEnd);
if (addMarker) {
trimedString = trimedString.substring(0, trimedString.length() - trimMarker.length()) + trimMarker;
}
return trimedString;
}
private static Pattern getPattern0(String text, String prefix, String suffix) {
assert text != null;
assert prefix != null;
assert suffix != null;
if (text.contains("?") || text.contains("*")) { // NOI18N
String pattern = text.replace("\\", "") // remove regexp escapes first // NOI18N
.replace(".", "\\.") // NOI18N
.replace("-", "\\-") // NOI18N
.replace("(", "\\(") // NOI18N
.replace(")", "\\)") // NOI18N
.replace("[", "\\[") // NOI18N
.replace("]", "\\]") // NOI18N
.replace("?", ".") // NOI18N
.replace("*", ".*"); // NOI18N
return Pattern.compile(prefix + pattern + suffix, Pattern.CASE_INSENSITIVE); // NOI18N
}
return null;
}
}
| 4,489 |
1,822 |
<gh_stars>1000+
// Copyright (c) 2020 ETH Zurich
//
// SPDX-License-Identifier: BSL-1.0
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#pragma once
#include <hpx/parallel/task_block.hpp>
namespace hpx {
using task_cancelled_exception = hpx::parallel::task_canceled_exception;
using hpx::parallel::define_task_block;
using hpx::parallel::define_task_block_restore_thread;
using hpx::parallel::task_block;
} // namespace hpx
| 213 |
1,391 |
#include "stdinc.h"
#include "9.h"
typedef struct {
char* argv0;
int (*cmd)(int, char*[]);
} Cmd;
static struct {
QLock lock;
Cmd* cmd;
int ncmd;
int hi;
} cbox;
enum {
NCmdIncr = 20,
};
int
cliError(char* fmt, ...)
{
char *p;
va_list arg;
va_start(arg, fmt);
p = vsmprint(fmt, arg);
werrstr("%s", p);
free(p);
va_end(arg);
return 0;
}
int
cliExec(char* buf)
{
int argc, i, r;
char *argv[20], *p;
p = vtstrdup(buf);
if((argc = tokenize(p, argv, nelem(argv)-1)) == 0){
vtfree(p);
return 1;
}
argv[argc] = 0;
if(argv[0][0] == '#'){
vtfree(p);
return 1;
}
qlock(&cbox.lock);
for(i = 0; i < cbox.hi; i++){
if(strcmp(cbox.cmd[i].argv0, argv[0]) == 0){
qunlock(&cbox.lock);
if(!(r = cbox.cmd[i].cmd(argc, argv)))
consPrint("%r\n");
vtfree(p);
return r;
}
}
qunlock(&cbox.lock);
consPrint("%s: - eh?\n", argv[0]);
vtfree(p);
return 0;
}
int
cliAddCmd(char* argv0, int (*cmd)(int, char*[]))
{
int i;
Cmd *opt;
qlock(&cbox.lock);
for(i = 0; i < cbox.hi; i++){
if(strcmp(argv0, cbox.cmd[i].argv0) == 0){
qunlock(&cbox.lock);
return 0;
}
}
if(i >= cbox.hi){
if(cbox.hi >= cbox.ncmd){
cbox.cmd = vtrealloc(cbox.cmd,
(cbox.ncmd+NCmdIncr)*sizeof(Cmd));
memset(&cbox.cmd[cbox.ncmd], 0, NCmdIncr*sizeof(Cmd));
cbox.ncmd += NCmdIncr;
}
}
opt = &cbox.cmd[cbox.hi];
opt->argv0 = argv0;
opt->cmd = cmd;
cbox.hi++;
qunlock(&cbox.lock);
return 1;
}
int
cliInit(void)
{
cbox.cmd = vtmallocz(NCmdIncr*sizeof(Cmd));
cbox.ncmd = NCmdIncr;
cbox.hi = 0;
return 1;
}
| 855 |
646 |
#include "HeliumRain/Quests/QuestCatalog/FlareHistoryQuest.h"
#include "HeliumRain/Flare.h"
#include "HeliumRain/Data/FlareResourceCatalog.h"
#include "HeliumRain/Data/FlareSpacecraftCatalog.h"
#include "HeliumRain/Economy/FlareCargoBay.h"
#include "HeliumRain/Game/FlareGame.h"
#include "HeliumRain/Game/FlareGameTools.h"
#include "HeliumRain/Game/FlareScenarioTools.h"
#include "HeliumRain/Player/FlarePlayerController.h"
#include "../FlareQuestCondition.h"
#include "../FlareQuestStep.h"
#include "../FlareQuestAction.h"
#include "HeliumRain/Quests/QuestCatalog/FlareTutorialQuest.h"
#define LOCTEXT_NAMESPACE "FlareHistotyQuest"
static FName HISTORY_CURRENT_PROGRESSION_TAG("current-progression");
static FName HISTORY_START_DATE_TAG("start-date");
/*----------------------------------------------------
Quest pendulum
----------------------------------------------------*/
#undef QUEST_TAG
#define QUEST_TAG "Pendulum"
UFlareQuestPendulum::UFlareQuestPendulum(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
}
UFlareQuest* UFlareQuestPendulum::Create(UFlareQuestManager* Parent)
{
UFlareQuestPendulum* Quest = NewObject<UFlareQuestPendulum>(Parent, UFlareQuestPendulum::StaticClass());
Quest->Load(Parent);
return Quest;
}
void UFlareQuestPendulum::Load(UFlareQuestManager* Parent)
{
LoadInternal(Parent);
Identifier = "pendulum";
QuestName = LOCTEXT("PendulumName","Pendulum");
QuestDescription = LOCTEXT("PendulumDescription","Help has been requested to all companies around Nema.");
QuestCategory = EFlareQuestCategory::HISTORY;
UFlareSimulatedSector* Pendulum = FindSector("pendulum");
if (!Pendulum)
{
return;
}
UFlareSimulatedSector* BlueHeart = FindSector("blue-heart");
if (!BlueHeart)
{
return;
}
UFlareSimulatedSector* TheSpire = FindSector("the-spire");
if (!TheSpire)
{
return;
}
Cast<UFlareQuestConditionGroup>(TriggerCondition)->AddChildCondition(UFlareQuestConditionQuestSuccessful::Create(this, "tutorial-contracts"));
Cast<UFlareQuestConditionGroup>(TriggerCondition)->AddChildCondition(UFlareQuestMinSectorStationCount::Create(this, TheSpire, 10));
{
#undef QUEST_STEP_TAG
#define QUEST_STEP_TAG QUEST_TAG"DockAt"
FText Description = LOCTEXT("DockAtDescription", "You are summoned by the Nema Colonial Administration to a meeting on the Pendulum project. Please dock at one of the habitation centers of the Blue Heart capital station.");
UFlareQuestStep* Step = UFlareQuestStep::Create(this, "meeting", Description);
UFlareQuestConditionDockAtType* Condition = UFlareQuestConditionDockAtType::Create(this, BlueHeart, "station-bh-habitation");
Cast<UFlareQuestConditionGroup>(Step->GetEndCondition())->AddChildCondition(Condition);
Steps.Add(Step);
}
{
#undef QUEST_STEP_TAG
#define QUEST_STEP_TAG QUEST_TAG"TravelToSpire"
FText Description = LOCTEXT("TravelToSpireDescription","Thanks for attending this meeting. As you may have observed, the Spire, our only source of gas, can't match our needs anymore. We need to build a new orbital extractor. \nHowever, the Spire was built before the war and all the knowledge disappeared when the Daedalus carrier was shot to pieces. Your help is needed to build a new one.\nPlease start reverse-engineering the Spire so that we can learn more.");
UFlareQuestStep* Step = UFlareQuestStep::Create(this, "travel-to-spire", Description);
Cast<UFlareQuestConditionGroup>(Step->GetEndCondition())->AddChildCondition(UFlareQuestConditionVisitSector::Create(this, TheSpire));
Steps.Add(Step);
}
{
#undef QUEST_STEP_TAG
#define QUEST_STEP_TAG QUEST_TAG"Inspect"
FText Description = LOCTEXT("InspectDescription","Inspect The Spire in details to gather information about its materials and construction methods. Our agent attached transmitter beacons on the structure to help you locating valuable data.");
UFlareQuestStep* Step = UFlareQuestStep::Create(this, "inspect-the-spire", Description);
TArray<FVector> Waypoints;
TArray<FText> WaypointTexts;
TArray<FText> CustomInitialLabels;
Waypoints.Add(FVector(0,0,-211084));
Waypoints.Add(FVector(0,0,-98414));
Waypoints.Add(FVector(-34858.507812, 27965.390625, 291240.156250));
Waypoints.Add(FVector(-6500.073242, -43279.824219, 290588.531250));
Waypoints.Add(FVector(-1783.690918, 2219.517334, 79133.492188));
Waypoints.Add(FVector(0,0,12563.443359));
Waypoints.Add(FVector(3321.726562, 37.321136, 3937.916504));
Waypoints.Add(FVector(901.953857, 174.950699, -12089.154297));
CustomInitialLabels.Add(FText::Format(LOCTEXT("InspectLabel1", "Inspect the pipe at the reference point A in {0}"), TheSpire->GetSectorName()));
CustomInitialLabels.Add(FText::Format(LOCTEXT("InspectLabel2", "Inspect the pipe at the reference point B in {0}"), TheSpire->GetSectorName()));
CustomInitialLabels.Add(FText::Format(LOCTEXT("InspectLabel3", "Inspect the counterweight attachement #1 in {0}"), TheSpire->GetSectorName()));
CustomInitialLabels.Add(FText::Format(LOCTEXT("InspectLabel4", "Inspect the counterweight attachement #3 in {0}"), TheSpire->GetSectorName()));
CustomInitialLabels.Add(FText::Format(LOCTEXT("InspectLabel5", "Inspect the counterweight cables in {0}"), TheSpire->GetSectorName()));
CustomInitialLabels.Add(FText::Format(LOCTEXT("InspectLabel6", "Inspect the counterweight station attachement in {0}"), TheSpire->GetSectorName()));
CustomInitialLabels.Add(FText::Format(LOCTEXT("InspectLabel7", "Inspect the extraction module in {0}"), TheSpire->GetSectorName()));
CustomInitialLabels.Add(FText::Format(LOCTEXT("InspectLabel8", "Inspect the pipe attachement in {0}"), TheSpire->GetSectorName()));
WaypointTexts.Add(LOCTEXT("WaypointText1", "Pipe inspected, {0} left"));
WaypointTexts.Add(LOCTEXT("WaypointText2", "Pipe inspected, {0} left"));
WaypointTexts.Add(LOCTEXT("WaypointText3", "Attachement inspected, {0} left"));
WaypointTexts.Add(LOCTEXT("WaypointText4", "Attachement inspected, {0} left"));
WaypointTexts.Add(LOCTEXT("WaypointText5", "Cables inspected, {0} left"));
WaypointTexts.Add(LOCTEXT("WaypointText6", "Attachement inspected, {0} left"));
WaypointTexts.Add(LOCTEXT("WaypointText7", "Module inspected, {0} left"));
WaypointTexts.Add(LOCTEXT("WaypointText8", "Attachement inspected. Good job !"));
Cast<UFlareQuestConditionGroup>(Step->GetEndCondition())->AddChildCondition(UFlareQuestConditionWaypoints::Create(this, QUEST_TAG"cond1", TheSpire, Waypoints, 16000, true, CustomInitialLabels, WaypointTexts));
Steps.Add(Step);
}
{
#undef QUEST_STEP_TAG
#define QUEST_STEP_TAG QUEST_TAG"DataReturn"
FText Description = LOCTEXT("DataReturnDescription", "This is great data ! Come back to our scientists in Blue Heart to see what they make of it.");
UFlareQuestStep* Step = UFlareQuestStep::Create(this, "data-return", Description);
UFlareQuestConditionDockAtType* Condition = UFlareQuestConditionDockAtType::Create(this, BlueHeart, "station-bh-habitation");
Cast<UFlareQuestConditionGroup>(Step->GetEndCondition())->AddChildCondition(Condition);
Steps.Add(Step);
}
{
#undef QUEST_STEP_TAG
#define QUEST_STEP_TAG QUEST_TAG"research"
FText Description = LOCTEXT("ResearchDescription","The data you brought back will help us understand how the Spire was built. We need you to transform this knowledge into a usable technology to build a new space elevator.");
UFlareQuestStep* Step = UFlareQuestStep::Create(this, "research", Description);
Cast<UFlareQuestConditionGroup>(Step->GetEndCondition())->AddChildCondition(UFlareQuestConditionTutorialUnlockTechnology::Create(this, "orbital-pumps"));
Cast<UFlareQuestConditionGroup>(Step->GetEndCondition())->AddChildCondition(UFlareQuestConditionTutorialUnlockTechnology::Create(this, "science"));
Steps.Add(Step);
}
{
#undef QUEST_STEP_TAG
#define QUEST_STEP_TAG QUEST_TAG"telescope"
FText Description = LOCTEXT("telescopeDescription","Congratulations, you've just acquired the blueprints for a new orbital extractor. This is huge ! Two things are still needed : construction resources, and a massive counterweight for the space elevator. Build a telescope station to help finding a good sector.");
UFlareQuestStep* Step = UFlareQuestStep::Create(this, "telescope", Description);
Cast<UFlareQuestConditionGroup>(Step->GetEndCondition())->AddChildCondition(UFlareQuestStationCount::Create(this, "station-telescope", 1));
Steps.Add(Step);
}
{
#undef QUEST_STEP_TAG
#define QUEST_STEP_TAG QUEST_TAG"resources"
FText Description = LOCTEXT("resourcesDescription","How many freighters do you own ? We need you to bring ships loaded with construction resources in Blue Heart.");
UFlareQuestStep* Step = UFlareQuestStep::Create(this, "resources", Description);
Cast<UFlareQuestConditionGroup>(Step->GetEndCondition())->AddChildCondition(UFlareQuestBringResource::Create(this, BlueHeart, "steel", 1000));
Cast<UFlareQuestConditionGroup>(Step->GetEndCondition())->AddChildCondition(UFlareQuestBringResource::Create(this, BlueHeart, "plastics", 1000));
Cast<UFlareQuestConditionGroup>(Step->GetEndCondition())->AddChildCondition(UFlareQuestBringResource::Create(this, BlueHeart, "tech", 500));
Cast<UFlareQuestConditionGroup>(Step->GetEndCondition())->AddChildCondition(UFlareQuestBringResource::Create(this, BlueHeart, "tools", 500));
Step->GetEndActions().Add(UFlareQuestActionTakeResources::Create(this, BlueHeart, "steel", 1000));
Step->GetEndActions().Add(UFlareQuestActionTakeResources::Create(this, BlueHeart, "plastics", 1000));
Step->GetEndActions().Add(UFlareQuestActionTakeResources::Create(this, BlueHeart, "tech", 500));
Step->GetEndActions().Add(UFlareQuestActionTakeResources::Create(this, BlueHeart, "tools", 500));
Steps.Add(Step);
}
{
#undef QUEST_STEP_TAG
#define QUEST_STEP_TAG QUEST_TAG"peace"
FText Description = LOCTEXT("peaceDescription","We've started construction for the Pendulum elevator. You need to be cautious of pirate activity, since we gathered a lot of resources here.\nReduce pirates to silence for a while. You should use your orbital telescope to locate their Boneyard base.");
UFlareQuestStep* Step = UFlareQuestStep::Create(this, "pirates", Description);
Cast<UFlareQuestConditionGroup>(Step->GetEndCondition())->AddChildCondition(UFlareCompanyMaxCombatValue::Create(this, GetQuestManager()->GetGame()->GetScenarioTools()->Pirates, 0));
Steps.Add(Step);
}
{
#undef QUEST_STEP_TAG
#define QUEST_STEP_TAG QUEST_TAG"wait"
FText Description = LOCTEXT("waitDescription","Good job. We'll get this up and running now.");
UFlareQuestStep* Step = UFlareQuestStep::Create(this, "wait", Description);
Cast<UFlareQuestConditionGroup>(Step->GetEndCondition())->AddChildCondition(UFlareQuestConditionWait::Create(this, QUEST_TAG"cond1", 30));
Steps.Add(Step);
}
{
#undef QUEST_STEP_TAG
#define QUEST_STEP_TAG QUEST_TAG"TravelToPendulum"
FText Description = LOCTEXT("TravelToPendulumDescription","The construction of Pendulum construction is finished, come take a look !");
UFlareQuestStep* Step = UFlareQuestStep::Create(this, "travel-to-pendulum", Description);
Step->GetInitActions().Add(UFlareQuestActionDiscoverSector::Create(this, Pendulum));
Cast<UFlareQuestConditionGroup>(Step->GetEndCondition())->AddChildCondition(UFlareQuestConditionSectorVisited::Create(this, Pendulum));
Steps.Add(Step);
}
{
#undef QUEST_STEP_TAG
#define QUEST_STEP_TAG QUEST_TAG"pumps"
FText Description = LOCTEXT("pumpsDescription","Welcome to the Pendulum. Other companies will come here too, but you helped build this extractor, so you've earned a timed exclusivity. Build some gas terminals while the administrative fees are low !");
UFlareQuestStep* Step = UFlareQuestStep::Create(this, "pumps", Description);
Step->SetEndCondition(UFlareQuestConditionOrGroup::Create(this, true));
Cast<UFlareQuestConditionGroup>(Step->GetEndCondition())->AddChildCondition(UFlareQuestConditionTutorialHaveStation::Create(this, false, "station-ch4-pump", Pendulum));
Cast<UFlareQuestConditionGroup>(Step->GetEndCondition())->AddChildCondition(UFlareQuestConditionTutorialHaveStation::Create(this, false, "station-h2-pump", Pendulum));
Cast<UFlareQuestConditionGroup>(Step->GetEndCondition())->AddChildCondition(UFlareQuestConditionTutorialHaveStation::Create(this, false, "station-he3-pump", Pendulum));
Steps.Add(Step);
}
GetSuccessActions().Add(UFlareQuestActionGeneric::Create(this,
[this](){
GetQuestManager()->GetGame()->GetPC()->SetAchievementProgression("ACHIEVEMENT_PENDULUM", 1);
}));
}
/*----------------------------------------------------
Quest dock at type condition
----------------------------------------------------*/
UFlareQuestConditionDockAtType::UFlareQuestConditionDockAtType(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
}
UFlareQuestConditionDockAtType* UFlareQuestConditionDockAtType::Create(UFlareQuest* ParentQuest, UFlareSimulatedSector* Sector, FName StationType)
{
UFlareQuestConditionDockAtType* Condition = NewObject<UFlareQuestConditionDockAtType>(ParentQuest, UFlareQuestConditionDockAtType::StaticClass());
Condition->Load(ParentQuest, Sector, StationType);
return Condition;
}
void UFlareQuestConditionDockAtType::Load(UFlareQuest* ParentQuest, UFlareSimulatedSector* Sector, FName StationType)
{
LoadInternal(ParentQuest);
Callbacks.AddUnique(EFlareQuestCallback::SHIP_DOCKED);
TargetStationType = StationType;
TargetSector = Sector;
Completed = false;
FFlareSpacecraftDescription* Desc = GetGame()->GetSpacecraftCatalog()->Get(TargetStationType);
if(Desc)
{
InitialLabel = FText::Format(LOCTEXT("DockAtTypeFormat", "Dock at a {0} in {1}"),
Desc->Name,
TargetSector->GetSectorName());
}
}
bool UFlareQuestConditionDockAtType::IsCompleted()
{
if (Completed)
{
return true;
}
if (GetGame()->GetPC()->GetPlayerShip() && GetGame()->GetPC()->GetPlayerShip()->IsActive())
{
AFlareSpacecraft* PlayerShip = GetGame()->GetPC()->GetPlayerShip()->GetActive();
if(PlayerShip->GetNavigationSystem()->GetDockStation())
{
if (PlayerShip->GetNavigationSystem()->GetDockStation()->GetDescription()->Identifier == TargetStationType)
{
Completed = true;
return true;
}
}
}
return false;
}
void UFlareQuestConditionDockAtType::AddConditionObjectives(FFlarePlayerObjectiveData* ObjectiveData)
{
FFlarePlayerObjectiveCondition ObjectiveCondition;
ObjectiveCondition.InitialLabel = GetInitialLabel();
ObjectiveCondition.TerminalLabel = FText();
ObjectiveCondition.Counter = 0;
ObjectiveCondition.MaxCounter = 0;
ObjectiveCondition.Progress = 0;
ObjectiveCondition.MaxProgress = 0;
ObjectiveData->ConditionList.Add(ObjectiveCondition);
ObjectiveData->TargetSectors.Add(TargetSector);
for (UFlareSimulatedSpacecraft* Station : TargetSector->GetSectorStations())
{
if (Station->GetDescription()->Identifier == TargetStationType)
{
ObjectiveData->AddTargetSpacecraft(Station);
}
}
}
/*----------------------------------------------------
Visit sector condition
----------------------------------------------------*/
UFlareQuestConditionVisitSector::UFlareQuestConditionVisitSector(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
}
UFlareQuestConditionVisitSector* UFlareQuestConditionVisitSector::Create(UFlareQuest* ParentQuest, UFlareSimulatedSector* Sector)
{
UFlareQuestConditionVisitSector* Condition = NewObject<UFlareQuestConditionVisitSector>(ParentQuest, UFlareQuestConditionVisitSector::StaticClass());
Condition->Load(ParentQuest, Sector);
return Condition;
}
void UFlareQuestConditionVisitSector::Load(UFlareQuest* ParentQuest, UFlareSimulatedSector* Sector)
{
LoadInternal(ParentQuest);
Callbacks.AddUnique(EFlareQuestCallback::QUEST_EVENT);
Completed = false;
TargetSector = Sector;
InitialLabel = FText::Format(LOCTEXT("VisitSector", "Visit {0}"), TargetSector->GetSectorName());
}
void UFlareQuestConditionVisitSector::OnEvent(FFlareBundle& Bundle)
{
if(Completed)
{
return;
}
if (Bundle.HasTag("travel-end") && Bundle.GetName("sector") == TargetSector->GetIdentifier())
{
Completed = true;
}
}
bool UFlareQuestConditionVisitSector::IsCompleted()
{
return Completed;
}
void UFlareQuestConditionVisitSector::AddConditionObjectives(FFlarePlayerObjectiveData* ObjectiveData)
{
FFlarePlayerObjectiveCondition ObjectiveCondition;
ObjectiveCondition.InitialLabel = InitialLabel;
ObjectiveCondition.TerminalLabel = FText::GetEmpty();
ObjectiveCondition.MaxCounter = 1;
ObjectiveCondition.MaxProgress = 1;
ObjectiveCondition.Counter = IsCompleted() ? 1 : 0;
ObjectiveCondition.Progress =IsCompleted() ? 1 : 0;
ObjectiveData->ConditionList.Add(ObjectiveCondition);
ObjectiveData->TargetSectors.Add(TargetSector);
}
/*----------------------------------------------------
Follow absolute waypoints condition
----------------------------------------------------*/
UFlareQuestConditionWaypoints::UFlareQuestConditionWaypoints(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
}
UFlareQuestConditionWaypoints* UFlareQuestConditionWaypoints::Create(UFlareQuest* ParentQuest, FName ConditionIdentifier, UFlareSimulatedSector* Sector, TArray<FVector> VectorListParam, float Radius, bool RequiresScan, TArray<FText> CustomInitialLabelsParam, TArray<FText> CustomWaypointTextsParam)
{
UFlareQuestConditionWaypoints*Condition = NewObject<UFlareQuestConditionWaypoints>(ParentQuest, UFlareQuestConditionWaypoints::StaticClass());
Condition->Load(ParentQuest, ConditionIdentifier, Sector, VectorListParam, Radius, RequiresScan, CustomInitialLabelsParam, CustomWaypointTextsParam);
return Condition;
}
void UFlareQuestConditionWaypoints::Load(UFlareQuest* ParentQuest, FName ConditionIdentifier, UFlareSimulatedSector* Sector, TArray<FVector> VectorListParam, float Radius, bool RequiresScan, TArray<FText> CustomInitialLabelsParam, TArray<FText> CustomWaypointTextsParam)
{
if (ConditionIdentifier == NAME_None)
{
FLOG("WARNING: UFlareQuestConditionWaypoints need identifier for state saving");
}
LoadInternal(ParentQuest, ConditionIdentifier);
Callbacks.AddUnique(EFlareQuestCallback::TICK_FLYING);
VectorList = VectorListParam;
TargetSector = Sector;
TargetRequiresScan = RequiresScan;
CustomInitialLabels = CustomInitialLabelsParam;
CustomWaypointTexts = CustomWaypointTextsParam;
TargetRadius = Radius;
if (RequiresScan)
{
InitialLabel = FText::Format(LOCTEXT("ScanWaypointsInSector", "Analyze signals in {0}"), TargetSector->GetSectorName());
}
else
{
InitialLabel = FText::Format(LOCTEXT("FollowWaypointsInSector", "Fly to waypoints in {0}"), TargetSector->GetSectorName());
}
}
void UFlareQuestConditionWaypoints::Restore(const FFlareBundle* Bundle)
{
bool HasSave = true;
if(Bundle)
{
HasSave &= Bundle->HasInt32(HISTORY_CURRENT_PROGRESSION_TAG);
}
else
{
HasSave = false;
}
if(HasSave)
{
IsInit = true;
CurrentProgression = Bundle->GetInt32(HISTORY_CURRENT_PROGRESSION_TAG);
UpdateInitalLabel();
}
else
{
IsInit = false;
}
}
void UFlareQuestConditionWaypoints::Save(FFlareBundle* Bundle)
{
if (IsInit)
{
Bundle->PutInt32(HISTORY_CURRENT_PROGRESSION_TAG, CurrentProgression);
}
}
void UFlareQuestConditionWaypoints::Init()
{
if(IsInit)
{
return;
}
AFlareSpacecraft* Spacecraft = GetPC()->GetShipPawn();
if (Spacecraft)
{
IsInit = true;
CurrentProgression = 0;
UpdateInitalLabel();
}
}
void UFlareQuestConditionWaypoints::UpdateInitalLabel()
{
if(CurrentProgression < CustomInitialLabels.Num())
{
InitialLabel = CustomInitialLabels[CurrentProgression];
}
}
bool UFlareQuestConditionWaypoints::IsCompleted()
{
AFlareSpacecraft* Spacecraft = GetPC()->GetShipPawn();
if (Spacecraft)
{
Init();
FVector WorldTargetLocation = VectorList[CurrentProgression];
float MaxDistance = TargetRadius;
if (Spacecraft->GetParent()->GetCurrentSector() == TargetSector)
{
// Waypoint completion logic
bool HasCompletedWaypoint = false;
if (TargetRequiresScan)
{
if (Spacecraft->IsWaypointScanningFinished())
{
HasCompletedWaypoint = true;
}
}
else if (FVector::Dist(Spacecraft->GetActorLocation(), WorldTargetLocation) < MaxDistance)
{
HasCompletedWaypoint = true;
}
if (HasCompletedWaypoint)
{
// Nearing the target
if (CurrentProgression + 2 <= VectorList.Num())
{
CurrentProgression++;
UpdateInitalLabel();
FText WaypointText;
if(CurrentProgression-1 < CustomWaypointTexts.Num())
{
WaypointText = CustomWaypointTexts[CurrentProgression-1];
}
else if (TargetRequiresScan)
{
WaypointText = LOCTEXT("ScanProgress", "Signal analyzed, {0} left");
}
else
{
WaypointText = LOCTEXT("WaypointProgress", "Waypoint reached, {0} left");
}
Quest->SendQuestNotification(FText::Format(WaypointText, FText::AsNumber(VectorList.Num() - CurrentProgression)),
FName(*(FString("quest-")+GetIdentifier().ToString()+"-step-progress")),
false);
}
else
{
// All waypoints reached
return true;
}
}
}
}
return false;
}
void UFlareQuestConditionWaypoints::AddConditionObjectives(FFlarePlayerObjectiveData* ObjectiveData)
{
Init();
FFlarePlayerObjectiveCondition ObjectiveCondition;
ObjectiveCondition.InitialLabel = InitialLabel;
ObjectiveCondition.TerminalLabel = FText::GetEmpty();
ObjectiveCondition.Counter = 0;
ObjectiveCondition.MaxCounter = VectorList.Num();
ObjectiveCondition.Progress = 0;
ObjectiveCondition.MaxProgress = VectorList.Num();
ObjectiveCondition.Counter = CurrentProgression;
ObjectiveCondition.Progress = CurrentProgression;
for (int TargetIndex = 0; TargetIndex < VectorList.Num(); TargetIndex++)
{
if (TargetIndex < CurrentProgression)
{
// Don't show old target
continue;
}
FFlarePlayerObjectiveTarget ObjectiveTarget;
ObjectiveTarget.RequiresScan = TargetRequiresScan;
ObjectiveTarget.Actor = NULL;
ObjectiveTarget.Active = (CurrentProgression == TargetIndex);
ObjectiveTarget.Radius = TargetRadius;
FVector WorldTargetLocation = VectorList[TargetIndex]; // In cm
ObjectiveTarget.Location = WorldTargetLocation;
ObjectiveData->TargetList.Add(ObjectiveTarget);
}
ObjectiveData->ConditionList.Add(ObjectiveCondition);
ObjectiveData->TargetSectors.Add(TargetSector);
}
/*----------------------------------------------------
Station count condition
----------------------------------------------------*/
UFlareQuestStationCount::UFlareQuestStationCount(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
}
UFlareQuestStationCount* UFlareQuestStationCount::Create(UFlareQuest* ParentQuest, FName StationIdentifier, int32 StationCount)
{
UFlareQuestStationCount* Condition = NewObject<UFlareQuestStationCount>(ParentQuest, UFlareQuestStationCount::StaticClass());
Condition->Load(ParentQuest, StationIdentifier, StationCount);
return Condition;
}
void UFlareQuestStationCount::Load(UFlareQuest* ParentQuest, FName StationIdentifier, int32 StationCount)
{
LoadInternal(ParentQuest);
Callbacks.AddUnique(EFlareQuestCallback::QUEST_EVENT);
TargetStationCount = StationCount;
TargetStationIdentifier = StationIdentifier;
FFlareSpacecraftDescription* Desc = GetGame()->GetSpacecraftCatalog()->Get(TargetStationIdentifier);
if(TargetStationCount == 1)
{
InitialLabel = FText::Format(LOCTEXT("HaveOneSpecificStation", "Build a {0} "), Desc->Name);
}
else
{
InitialLabel = FText::Format(LOCTEXT("HaveMultipleSpecificStation", "Build {0} {1} "), FText::AsNumber(StationCount), Desc->Name);
}
}
int32 UFlareQuestStationCount::GetStationCount()
{
int StationCount = 0;
for(UFlareSimulatedSpacecraft* Station : GetGame()->GetPC()->GetCompany()->GetCompanyStations())
{
if(Station->GetDescription()->Identifier == TargetStationIdentifier && !Station->IsUnderConstruction())
{
StationCount++;
}
}
return StationCount;
}
bool UFlareQuestStationCount::IsCompleted()
{
return GetStationCount() >= TargetStationCount;
}
void UFlareQuestStationCount::AddConditionObjectives(FFlarePlayerObjectiveData* ObjectiveData)
{
FFlarePlayerObjectiveCondition ObjectiveCondition;
ObjectiveCondition.InitialLabel = InitialLabel;
ObjectiveCondition.TerminalLabel = FText::GetEmpty();
ObjectiveCondition.MaxCounter = TargetStationCount;
ObjectiveCondition.MaxProgress = TargetStationCount;
ObjectiveCondition.Counter = GetStationCount();
ObjectiveCondition.Progress = GetStationCount();
ObjectiveData->ConditionList.Add(ObjectiveCondition);
}
/*----------------------------------------------------
Bring resource condition
----------------------------------------------------*/
UFlareQuestBringResource::UFlareQuestBringResource(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
}
UFlareQuestBringResource* UFlareQuestBringResource::Create(UFlareQuest* ParentQuest, UFlareSimulatedSector* Sector, FName ResourceIdentifier, int32 Count)
{
UFlareQuestBringResource* Condition = NewObject<UFlareQuestBringResource>(ParentQuest, UFlareQuestBringResource::StaticClass());
Condition->Load(ParentQuest, Sector, ResourceIdentifier, Count);
return Condition;
}
void UFlareQuestBringResource::Load(UFlareQuest* ParentQuest, UFlareSimulatedSector* Sector, FName ResourceIdentifier, int32 Count)
{
LoadInternal(ParentQuest);
Callbacks.AddUnique(EFlareQuestCallback::QUEST_EVENT);
TargetResourceCount = Count;
TargetResourceIdentifier = ResourceIdentifier;
TargetSector = Sector;
FFlareResourceDescription* Desc = GetGame()->GetResourceCatalog()->Get(TargetResourceIdentifier);
if(Desc)
{
InitialLabel = FText::Format(LOCTEXT("BringResource", "Bring ships loaded with {0} {1} at {2}"),
FText::AsNumber(TargetResourceCount), Desc->Name, TargetSector->GetSectorName());
}
}
int32 UFlareQuestBringResource::GetResourceCount()
{
int ResourceCount = 0;
FFlareResourceDescription* Resource = GetGame()->GetResourceCatalog()->Get(TargetResourceIdentifier);
if(!Resource)
{
return 0;
}
UFlareCompany* PlayerCompany = GetGame()->GetPC()->GetCompany();
for(UFlareSimulatedSpacecraft* Ship: TargetSector->GetSectorShips())
{
if(Ship->GetCompany() != PlayerCompany)
{
continue;
}
ResourceCount += Ship->GetActiveCargoBay()->GetResourceQuantity(Resource, PlayerCompany);
}
return ResourceCount;
}
bool UFlareQuestBringResource::IsCompleted()
{
return GetResourceCount() >= TargetResourceCount;
}
void UFlareQuestBringResource::AddConditionObjectives(FFlarePlayerObjectiveData* ObjectiveData)
{
FFlarePlayerObjectiveCondition ObjectiveCondition;
ObjectiveCondition.InitialLabel = InitialLabel;
ObjectiveCondition.TerminalLabel = FText::GetEmpty();
ObjectiveCondition.MaxCounter = TargetResourceCount;
ObjectiveCondition.MaxProgress = TargetResourceCount;
ObjectiveCondition.Counter = GetResourceCount();
ObjectiveCondition.Progress = GetResourceCount();
ObjectiveData->ConditionList.Add(ObjectiveCondition);
ObjectiveData->TargetSectors.Add(TargetSector);
}
/*----------------------------------------------------
Max army in company condition
----------------------------------------------------*/
UFlareCompanyMaxCombatValue::UFlareCompanyMaxCombatValue(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
}
UFlareCompanyMaxCombatValue* UFlareCompanyMaxCombatValue::Create(UFlareQuest* ParentQuest, UFlareCompany* TargetCompanyParam, int32 TargetArmyPointsParam)
{
UFlareCompanyMaxCombatValue* Condition = NewObject<UFlareCompanyMaxCombatValue>(ParentQuest, UFlareCompanyMaxCombatValue::StaticClass());
Condition->Load(ParentQuest, TargetCompanyParam, TargetArmyPointsParam);
return Condition;
}
void UFlareCompanyMaxCombatValue::Load(UFlareQuest* ParentQuest, UFlareCompany* TargetCompanyParam, int32 TargetArmyPointsParam)
{
LoadInternal(ParentQuest);
Callbacks.AddUnique(EFlareQuestCallback::TICK_FLYING);
Callbacks.AddUnique(EFlareQuestCallback::NEXT_DAY);
TargetCompany = TargetCompanyParam;
TargetArmyPoints = TargetArmyPointsParam;
FText InitialLabelText = LOCTEXT("CompanyMaxArmyCombatPoints", "{0} must have at most {1} combat value");
InitialLabel = FText::Format(InitialLabelText, TargetCompany->GetCompanyName(), FText::AsNumber(TargetArmyPoints));
}
bool UFlareCompanyMaxCombatValue::IsCompleted()
{
return TargetCompany->GetCompanyValue().ArmyCurrentCombatPoints <= TargetArmyPoints;
}
void UFlareCompanyMaxCombatValue::AddConditionObjectives(FFlarePlayerObjectiveData* ObjectiveData)
{
FFlarePlayerObjectiveCondition ObjectiveCondition;
ObjectiveCondition.InitialLabel = GetInitialLabel();
ObjectiveCondition.TerminalLabel = FText();
ObjectiveCondition.Progress = 0;
ObjectiveCondition.MaxProgress = 0;
ObjectiveCondition.Counter = TargetCompany->GetCompanyValue().ArmyCurrentCombatPoints;
ObjectiveCondition.MaxCounter = TargetArmyPoints;
ObjectiveData->ConditionList.Add(ObjectiveCondition);
}
/*----------------------------------------------------
Min station count in sector condition
----------------------------------------------------*/
UFlareQuestMinSectorStationCount::UFlareQuestMinSectorStationCount(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
}
UFlareQuestMinSectorStationCount* UFlareQuestMinSectorStationCount::Create(UFlareQuest* ParentQuest, UFlareSimulatedSector* Sector, int32 StationCount)
{
UFlareQuestMinSectorStationCount* Condition = NewObject<UFlareQuestMinSectorStationCount>(ParentQuest, UFlareQuestMinSectorStationCount::StaticClass());
Condition->Load(ParentQuest, Sector, StationCount);
return Condition;
}
void UFlareQuestMinSectorStationCount::Load(UFlareQuest* ParentQuest, UFlareSimulatedSector* Sector, int32 StationCount)
{
LoadInternal(ParentQuest);
Callbacks.AddUnique(EFlareQuestCallback::NEXT_DAY);
TargetStationCount = StationCount;
TargetSector = Sector;
InitialLabel = FText::Format(LOCTEXT("HaveStationCountInSector", "It must be at least {0} station in {1}"),
FText::AsNumber(StationCount),
TargetSector->GetSectorName());
}
bool UFlareQuestMinSectorStationCount::IsCompleted()
{
return TargetSector->GetSectorStations().Num() >= TargetStationCount;
}
void UFlareQuestMinSectorStationCount::AddConditionObjectives(FFlarePlayerObjectiveData* ObjectiveData)
{
FFlarePlayerObjectiveCondition ObjectiveCondition;
ObjectiveCondition.InitialLabel = InitialLabel;
ObjectiveCondition.TerminalLabel = FText::GetEmpty();
ObjectiveCondition.MaxCounter = TargetStationCount;
ObjectiveCondition.MaxProgress = TargetStationCount;
ObjectiveCondition.Counter = TargetSector->GetSectorStations().Num();
ObjectiveCondition.Progress = TargetSector->GetSectorStations().Num();
ObjectiveData->ConditionList.Add(ObjectiveCondition);
}
/*----------------------------------------------------
Wait condition
----------------------------------------------------*/
UFlareQuestConditionWait::UFlareQuestConditionWait(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
}
UFlareQuestConditionWait* UFlareQuestConditionWait::Create(UFlareQuest* ParentQuest, FName ConditionIdentifier, int32 Duration)
{
UFlareQuestConditionWait*Condition = NewObject<UFlareQuestConditionWait>(ParentQuest, UFlareQuestConditionWait::StaticClass());
Condition->Load(ParentQuest, ConditionIdentifier, Duration);
return Condition;
}
void UFlareQuestConditionWait::Load(UFlareQuest* ParentQuest, FName ConditionIdentifier, int32 Duration)
{
if (ConditionIdentifier == NAME_None)
{
FLOG("WARNING: UFlareQuestConditionWait need identifier for state saving");
}
LoadInternal(ParentQuest, ConditionIdentifier);
Callbacks.AddUnique(EFlareQuestCallback::NEXT_DAY);
TargetDuration = Duration;
}
FText UFlareQuestConditionWait::GetInitialLabel()
{
int64 DateLimit = StartDate + TargetDuration;
int64 RemainingDuration = DateLimit - GetGame()->GetGameWorld()->GetDate();
return FText::Format(LOCTEXT("RemainingDurationWaitFormat", "{0} remaining"), UFlareGameTools::FormatDate(RemainingDuration, 2));
}
void UFlareQuestConditionWait::Restore(const FFlareBundle* Bundle)
{
bool HasSave = true;
if(Bundle)
{
HasSave &= Bundle->HasInt32(HISTORY_START_DATE_TAG);
}
else
{
HasSave = false;
}
if(HasSave)
{
IsInit = true;
StartDate = Bundle->GetInt32(HISTORY_START_DATE_TAG);
}
else
{
IsInit = false;
}
}
void UFlareQuestConditionWait::Save(FFlareBundle* Bundle)
{
if (IsInit)
{
Bundle->PutInt32(HISTORY_START_DATE_TAG, StartDate);
}
}
void UFlareQuestConditionWait::Init()
{
if(!IsInit)
{
StartDate = GetGame()->GetGameWorld()->GetDate();
IsInit = true;
}
}
bool UFlareQuestConditionWait::IsCompleted()
{
Init();
int64 DateLimit = StartDate + TargetDuration;
int64 RemainingDuration = DateLimit - GetGame()->GetGameWorld()->GetDate();
return RemainingDuration <= 0;
}
void UFlareQuestConditionWait::AddConditionObjectives(FFlarePlayerObjectiveData* ObjectiveData)
{
Init();
int64 CurrentProgression = GetGame()->GetGameWorld()->GetDate() - StartDate;
FFlarePlayerObjectiveCondition ObjectiveCondition;
ObjectiveCondition.InitialLabel = GetInitialLabel();
ObjectiveCondition.TerminalLabel = FText::GetEmpty();
ObjectiveCondition.Counter = 0;
ObjectiveCondition.MaxCounter = TargetDuration;
ObjectiveCondition.Progress = 0;
ObjectiveCondition.MaxProgress = TargetDuration;
ObjectiveCondition.Counter = CurrentProgression;
ObjectiveCondition.Progress = CurrentProgression;
ObjectiveData->ConditionList.Add(ObjectiveCondition);
}
#undef LOCTEXT_NAMESPACE
| 10,598 |
1,086 |
<filename>test/util.c
/********************************************************************
* *
* THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
* USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
* GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
* IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
* *
* THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2007 *
* by the Xiph.Org Foundation http://www.xiph.org/ *
* *
********************************************************************
function: utility functions for vorbis codec test suite.
last mod: $Id: util.c 13293 2007-07-24 00:09:47Z erikd $
********************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <errno.h>
#include <vorbis/codec.h>
#include <vorbis/vorbisenc.h>
#include "util.h"
void
gen_windowed_sine (float *data, int len, float maximum)
{ int k ;
memset (data, 0, len * sizeof (float)) ;
len /= 2 ;
for (k = 0 ; k < len ; k++)
{ data [k] = sin (2.0 * k * M_PI * 1.0 / 32.0 + 0.4) ;
/* Apply Hanning Window. */
data [k] *= maximum * (0.5 - 0.5 * cos (2.0 * M_PI * k / ((len) - 1))) ;
}
return ;
}
void
set_data_in (float * data, unsigned len, float value)
{ unsigned k ;
for (k = 0 ; k < len ; k++)
data [k] = value ;
}
| 780 |
305 |
package org.mamute.validators;
import br.com.caelum.vraptor.validator.Validator;
import com.google.common.base.Function;
import com.google.common.collect.Collections2;
import org.mamute.factory.MessageFactory;
import org.mamute.model.Attachment;
import javax.annotation.Nullable;
import javax.inject.Inject;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import static com.google.common.collect.Collections2.transform;
import static org.mamute.model.Comment.ERROR_NOT_EMPTY;
public class AttachmentsValidator {
@Inject
private Validator validator;
@Inject
private MessageFactory factory;
public void validate(List<Attachment> attachments) {
Collection<String> names = transform(attachments, mapName());
HashSet<String> namesSet = new HashSet<>(names);
boolean hasRepeatedName = names.size() != namesSet.size();
if (hasRepeatedName) {
validator.add(factory.build("error", "question.errors.attachments.duplicated"));
}
}
private Function<Attachment, String> mapName() {
return new Function<Attachment, String>() {
@Nullable
@Override
public String apply(Attachment a) {
return a.getName();
}
};
}
}
| 406 |
2,863 |
<filename>spock-core/src/main/java/org/spockframework/builder/ClosureBlueprint.java<gh_stars>1000+
/*
* Copyright 2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.spockframework.builder;
import org.spockframework.runtime.GroovyRuntimeUtil;
import groovy.lang.Closure;
public class ClosureBlueprint implements IBlueprint {
private final Closure closure;
private final Object subject;
public ClosureBlueprint(Closure closure, Object subject) {
this.closure = closure;
this.subject = subject;
closure.setResolveStrategy(Closure.DELEGATE_ONLY);
}
@Override
public Object getThisObject() {
return closure.getThisObject();
}
@Override
public void setDelegate(Object delegate) {
closure.setDelegate(delegate);
}
@Override
public void evaluate() {
GroovyRuntimeUtil.invokeClosure(closure, subject);
}
}
| 405 |
541 |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.statistics.export.service;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doCallRealMethod;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.client.config.RequestConfig;
import org.dspace.core.Context;
import org.dspace.statistics.export.OpenURLTracker;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.Spy;
import org.mockito.junit.MockitoJUnitRunner;
/**
* Test class for the OpenUrlServiceImpl
*/
@RunWith(MockitoJUnitRunner.class)
public class OpenUrlServiceImplTest {
@InjectMocks
@Spy
private OpenUrlServiceImpl openUrlService;
@Mock
private FailedOpenURLTrackerService failedOpenURLTrackerService;
/**
* Test the processUrl method
* @throws IOException
* @throws SQLException
*/
@Test
public void testProcessUrl() throws IOException, SQLException {
Context context = mock(Context.class);
doReturn(HttpURLConnection.HTTP_OK).when(openUrlService)
.getResponseCodeFromUrl(anyString());
openUrlService.processUrl(context, "test-url");
verify(openUrlService, times(0)).logfailed(context, "test-url");
}
/**
* Test the processUrl method when the url connection fails
* @throws IOException
* @throws SQLException
*/
@Test
public void testProcessUrlOnFail() throws IOException, SQLException {
Context context = mock(Context.class);
doReturn(HttpURLConnection.HTTP_INTERNAL_ERROR).when(openUrlService)
.getResponseCodeFromUrl(anyString());
doNothing().when(openUrlService).logfailed(any(Context.class), anyString());
openUrlService.processUrl(context, "test-url");
verify(openUrlService, times(1)).logfailed(context, "test-url");
}
/**
* Test the ReprocessFailedQueue method
* @throws SQLException
*/
@Test
public void testReprocessFailedQueue() throws SQLException {
Context context = mock(Context.class);
List<OpenURLTracker> trackers = new ArrayList<>();
OpenURLTracker tracker1 = mock(OpenURLTracker.class);
OpenURLTracker tracker2 = mock(OpenURLTracker.class);
OpenURLTracker tracker3 = mock(OpenURLTracker.class);
trackers.add(tracker1);
trackers.add(tracker2);
trackers.add(tracker3);
when(failedOpenURLTrackerService.findAll(any(Context.class))).thenReturn(trackers);
doNothing().when(openUrlService).tryReprocessFailed(any(Context.class), any(OpenURLTracker.class));
openUrlService.reprocessFailedQueue(context);
verify(openUrlService, times(3)).tryReprocessFailed(any(Context.class), any(OpenURLTracker.class));
}
/**
* Test the method that logs the failed urls in the db
* @throws SQLException
*/
@Test
public void testLogfailed() throws SQLException {
Context context = mock(Context.class);
OpenURLTracker tracker1 = mock(OpenURLTracker.class);
doCallRealMethod().when(tracker1).setUrl(anyString());
when(tracker1.getUrl()).thenCallRealMethod();
when(failedOpenURLTrackerService.create(any(Context.class))).thenReturn(tracker1);
String failedUrl = "failed-url";
openUrlService.logfailed(context, failedUrl);
assertThat(tracker1.getUrl(), is(failedUrl));
}
/**
* Tests whether the timeout gets set to 10 seconds when processing a url
* @throws SQLException
*/
@Test
public void testTimeout() throws SQLException {
Context context = mock(Context.class);
String URL = "http://bla.com";
RequestConfig.Builder requestConfig = mock(RequestConfig.Builder.class);
doReturn(requestConfig).when(openUrlService).getRequestConfigBuilder();
doReturn(requestConfig).when(requestConfig).setConnectTimeout(10 * 1000);
doReturn(RequestConfig.custom().build()).when(requestConfig).build();
openUrlService.processUrl(context, URL);
Mockito.verify(requestConfig).setConnectTimeout(10 * 1000);
}
}
| 1,867 |
1,066 |
package org.gradle.profiler;
public enum BuildStep {
CLEANUP, BUILD
}
| 27 |
704 |
package org.jgroups.util;
import org.jgroups.logging.Log;
/**
* Log (using {@link SuppressCache}) which suppresses (certain) messages from the same member for a given time
* @author <NAME>
* @since 3.2
*/
public class SuppressLog<T> {
protected final Log log;
protected final SuppressCache<T> cache;
protected final String message_format;
protected final String suppress_format;
public enum Level {error,warn,trace};
public SuppressLog(Log log, String message_key, String suppress_msg) {
this.log=log;
cache=new SuppressCache<>();
message_format=Util.getMessage(message_key);
suppress_format=Util.getMessage(suppress_msg); // "(received %d identical messages from %s in the last %d ms)"
}
public SuppressCache<T> getCache() {return cache;}
/**
* Logs a message from a given member if is hasn't been logged for timeout ms
* @param level The level, either warn or error
* @param key The key into the SuppressCache
* @param timeout The timeout
* @param args The arguments to the message key
*/
public void log(Level level, T key, long timeout, Object ... args) {
SuppressCache.Value val=cache.putIfAbsent(key, timeout);
if(val == null) // key is present and hasn't expired
return;
String message=val.count() == 1? String.format(message_format, args) :
String.format(message_format, args) + " " + String.format(suppress_format, val.count(), key, val.age());
switch(level) {
case error:
log.error(message);
break;
case warn:
log.warn(message);
break;
case trace:
log.trace(message);
break;
}
}
public void removeExpired(long timeout) {cache.removeExpired(timeout);}
}
| 791 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.