max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
4,200 | /*
* Copyright 2016 SimplifyOps, Inc. (http://simplifyops.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dtolabs.rundeck.core.utils;
import org.apache.commons.lang.text.StrMatcher;
import java.util.*;
/**
* Tokenizer for strings delimited by spaces, allowing quoted strings with either single or double quotes, and escaped
* quote values within those strings by doubling the quote character. Delimiters are not returned in the tokens, and
* runs of delimiters can be quelled. All chars in a quoted section are returned, even blanks.
* Implements {@link Iterable} and {@link Iterator}.
*
*/
public class QuotedStringTokenizer implements Iterator<String>, Iterable<String> {
private char[] string;
private int pos;
private Queue<String> buffer;
private StrMatcher delimiterMatcher;
private StrMatcher quoteMatcher;
private StrMatcher whitespaceMatcher;
private boolean quashDelimiters;
public QuotedStringTokenizer(String string) {
this(string.toCharArray(), 0);
}
public QuotedStringTokenizer(char[] chars, int pos) {
this.string = chars;
this.pos = pos;
buffer = new ArrayDeque<String>();
delimiterMatcher = StrMatcher.trimMatcher();
quoteMatcher = StrMatcher.quoteMatcher();
whitespaceMatcher = StrMatcher.trimMatcher();
quashDelimiters=true;
readNext();
}
public static String[] tokenizeToArray(String string) {
List<String> strings = collectTokens(string);
return strings.toArray(new String[strings.size()]);
}
public static List<String> tokenizeToList(String string) {
return collectTokens(string);
}
public static Iterable<String> tokenize(String string) {
return new QuotedStringTokenizer(string);
}
private static List<String> collectTokens(String string) {
ArrayList<String> strings = new ArrayList<String>();
for (String s : new QuotedStringTokenizer(string)) {
strings.add(s);
}
return strings;
}
@Override
public boolean hasNext() {
return !buffer.isEmpty();
}
@Override
public String next() {
String remove = buffer.remove();
readNext();
return remove;
}
private void readNext() {
pos = readNextToken(string, pos, buffer);
}
private int readNextToken(char[] chars, int pos, Collection<String> tokens) {
if (pos >= chars.length) {
return -1;
}
int ws = whitespaceMatcher.isMatch(chars, pos);
if (ws > 0) {
pos += ws;
}
if (pos >= chars.length) {
return -1;
}
int delim = delimiterMatcher.isMatch(chars, pos);
if (delim > 0) {
if (quashDelimiters) {
pos = consumeDelimiters(chars, pos, delim);
} else {
addToken(buffer, "");
return pos + delim;
}
}
int quote = quoteMatcher.isMatch(chars, pos);
return readQuotedToken(chars, pos, tokens, quote);
}
private int consumeDelimiters(char[] chars, int start, int delim) {
while (delim > 0 && start < chars.length - delim) {
start += delim;
delim = delimiterMatcher.isMatch(chars, start);
}
return start;
}
private int readQuotedToken(char[] chars, int start, Collection<String> tokens, int quotesize) {
int pos = start;
StringBuilder tchars = new StringBuilder();
boolean quoting = quotesize > 0;
if (quoting) {
pos += quotesize;
}
while (pos < chars.length) {
if (quoting) {
if (charsMatch(chars, start, pos, quotesize)) {
//matches the quoting char
//if next token is the same quote, it is an escaped quote
if (charsMatch(chars, start, pos + quotesize, quotesize)) {
//token the quote
tchars.append(new String(chars, pos, quotesize));
pos += 2 * quotesize;
continue;
}
//end of quoting
quoting = false;
pos += quotesize;
continue;
}
//append char
tchars.append(chars[pos++]);
} else {
int delim = delimiterMatcher.isMatch(chars, pos);
if (delim > 0) {
if (quashDelimiters) {
pos = consumeDelimiters(chars, pos, delim);
addToken(tokens, tchars.toString());
return pos;
} else {
addToken(tokens, tchars.toString());
return pos + delim;
}
}
if (quotesize > 0 && charsMatch(chars, start, pos, quotesize)) {
//new quote
quoting = true;
pos += quotesize;
continue;
}
//append char
tchars.append(chars[pos++]);
}
}
addToken(tokens, tchars.toString());
return pos;
}
/**
* @return true if two sequences of chars match within the array.
*
* @param chars char set
* @param pos1 position 1
* @param pos2 position 2
* @param len2 length to compare
*
*/
private boolean charsMatch(char[] chars, int pos1, int pos2, int len2) {
return charsMatch(chars, pos1, len2, pos2, len2);
}
/**
* @return true if two sequences of chars match within the array.
*
* @param chars char set
* @param pos1 pos 1
* @param len1 length 1
* @param pos2 pos 2
* @param len2 length 2
*
*/
private boolean charsMatch(char[] chars, int pos1, int len1, int pos2, int len2) {
if (len1 != len2) {
return false;
}
if (pos1 + len1 > chars.length || pos2 + len2 > chars.length) {
return false;
}
for (int i = 0; i < len1; i++) {
if (chars[pos1 + i] != chars[pos2 + i]) {
return false;
}
}
return true;
}
private void addToken(Collection<String> buffer, String token) {
buffer.add(token);
}
@Override
public void remove() {
}
@Override
public Iterator<String> iterator() {
return this;
}
}
| 3,263 |
2,338 | #define __CLC_FUNCTION atom_sub
#include <clc/atom_decl_int64.inc>
| 29 |
892 | <reponame>westonsteimel/advisory-database-github<filename>advisories/github-reviewed/2020/09/GHSA-f8mr-jv2c-v8mg/GHSA-f8mr-jv2c-v8mg.json<gh_stars>100-1000
{
"schema_version": "1.2.0",
"id": "GHSA-f8mr-jv2c-v8mg",
"modified": "2021-11-19T15:27:56Z",
"published": "2020-09-09T17:29:27Z",
"aliases": [
"CVE-2020-15163"
],
"summary": "Invalid root may become trusted root in The Update Framework (TUF)",
"details": "### Impact\nThe Python TUF reference implementation `tuf<0.12` will incorrectly trust a previously downloaded root metadata file which failed verification at download time. This allows an attacker who is able to serve multiple new versions of root metadata (i.e. by a man-in-the-middle attack) culminating in a version which has not been correctly signed to control the trust chain for future updates.\n\nWhile investigating the reported vulnerability, we discovered that the detailed client workflow was not fully implemented. Specifically, for step 1.3 the newly downloaded root metadata was not being verified with a threshold of keys specified in the new root metadata file.\nThis missing step of the client workflow has been implemented in [PR #1101](https://github.com/theupdateframework/tuf/pull/1101), which is included in [v0.14.0](https://github.com/theupdateframework/tuf/releases/tag/v0.14.0) of tuf.\n\n### Patches\nA [fix](https://github.com/theupdateframework/tuf/pull/885), is available in version [0.12](https://github.com/theupdateframework/tuf/releases/tag/v0.12.0) and newer.\n\n### Workarounds\nNo workarounds are known for this issue.\n\n### References\n* Pull request resolving the invalid root becoming trusted issue [PR 885](https://github.com/theupdateframework/tuf/pull/885)\n* Pull request implementing self verification of newly downloaded root metadata [PR 1101](https://github.com/theupdateframework/tuf/pull/1101)",
"severity": [
{
"type": "CVSS_V3",
"score": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:H/I:H/A:N"
}
],
"affected": [
{
"package": {
"ecosystem": "PyPI",
"name": "tuf"
},
"ranges": [
{
"type": "ECOSYSTEM",
"events": [
{
"introduced": "0"
},
{
"fixed": "0.12"
}
]
}
]
}
],
"references": [
{
"type": "WEB",
"url": "https://github.com/theupdateframework/tuf/security/advisories/GHSA-f8mr-jv2c-v8mg"
},
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2020-15163"
},
{
"type": "WEB",
"url": "https://github.com/theupdateframework/tuf/pull/885"
},
{
"type": "WEB",
"url": "https://github.com/theupdateframework/tuf/commit/3d342e648fbacdf43a13d7ba8886aaaf07334af7"
},
{
"type": "WEB",
"url": "https://github.com/theupdateframework/tuf/releases/tag/v0.12.0"
},
{
"type": "WEB",
"url": "https://pypi.org/project/tuf"
},
{
"type": "PACKAGE",
"url": "https://github.com/theupdateframework/tuf"
}
],
"database_specific": {
"cwe_ids": [
"CWE-345",
"CWE-863"
],
"severity": "HIGH",
"github_reviewed": true
}
} | 1,385 |
816 | <gh_stars>100-1000
# coding=utf-8
# Copyright 2019 The Google AI Language Team 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.
# Lint as: python3
"""Utilities to convert predictions file to other formats."""
import enum
import os
from typing import Text, List
from tapas.scripts import calc_metrics_utils
from tapas.scripts import prediction_utils
import tensorflow.compat.v1 as tf
class DatasetFormat(enum.Enum):
WIKITABLEQUESTIONS = 0
def _convert_single_wtq(interaction_file, prediction_file,
output_file):
"""Convert predictions to WikiTablequestions format."""
interactions = dict(
(prediction_utils.parse_interaction_id(i.id), i)
for i in prediction_utils.iterate_interactions(interaction_file))
missing_interaction_ids = set(interactions.keys())
with tf.io.gfile.GFile(output_file, 'w') as output_file:
for prediction in prediction_utils.iterate_predictions(prediction_file):
interaction_id = prediction['id']
if interaction_id in missing_interaction_ids:
missing_interaction_ids.remove(interaction_id)
else:
continue
coordinates = prediction_utils.parse_coordinates(
prediction['answer_coordinates'])
denot_pred, _ = calc_metrics_utils.execute(
int(prediction.get('pred_aggr', '0')), coordinates,
prediction_utils.table_to_panda_frame(
interactions[interaction_id].table))
answers = '\t'.join(sorted(map(str, denot_pred)))
output_file.write('{}\t{}\n'.format(interaction_id, answers))
for interaction_id in missing_interaction_ids:
output_file.write('{}\n'.format(interaction_id))
def _convert_single(interaction_file, prediction_file,
output_file, dataset_format):
if dataset_format == DatasetFormat.WIKITABLEQUESTIONS:
return _convert_single_wtq(interaction_file, prediction_file, output_file)
else:
raise ValueError('Unknown dataset format {}'.format(dataset_format))
def convert(interactions, predictions,
output_directory, dataset_format):
assert len(interactions) == len(predictions)
for interaction_file, prediction_file in zip(interactions, predictions):
output_file = os.path.join(output_directory,
os.path.basename(prediction_file))
_convert_single(interaction_file, prediction_file, output_file,
dataset_format)
| 1,027 |
2,494 | // Copyright & License details are available under JXCORE_LICENSE file
#include "SpiderHelper.h"
namespace jxcore {
/* The class of the global object. */
static JSClass global_class = {
"global", JSCLASS_HAS_PRIVATE | JSCLASS_HAS_RESERVED_SLOTS(3) |
JSCLASS_IS_GLOBAL | JSCLASS_GLOBAL_FLAGS,
JS_PropertyStub, JS_DeletePropertyStub, JS_PropertyStub,
JS_StrictPropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, 0,
0, 0, 0, JS_GlobalObjectTraceHook};
static JSClass transplant_class = {"jxcore_transplant",
JSCLASS_HAS_PRIVATE |
JSCLASS_HAS_RESERVED_SLOTS(3),
JS_PropertyStub, JS_DeletePropertyStub,
JS_PropertyStub, JS_StrictPropertyStub,
JS_EnumerateStub, JS_ResolveStub,
JS_ConvertStub, 0, 0, 0, 0, 0};
static JSObject *globals[65] = {NULL};
MozJS::Value getGlobal(const int threadId) {
return MozJS::Value(globals[threadId],
MozJS::Isolate::GetByThreadId(threadId)->GetRaw());
}
JSObject *getGlobalObject(const int threadId) { return globals[threadId]; }
void NewTransplantObject(JSContext *ctx, JS::MutableHandleObject ret_val) {
ret_val.set(JS_NewObject(ctx, &transplant_class, JS::NullPtr(), JS::NullPtr()));
}
void CrossCompartmentCopy(JSContext *orig_context, JSContext *new_context,
MozJS::Value &source, bool global_object,
JS::MutableHandleObject retval) {
JS::RootedObject cs_root(orig_context, source.GetRawObjectPointer());
JS::RootedObject tp_obj(new_context);
if (global_object) {
jxcore::NewContextGlobal(new_context, &tp_obj);
} else {
NewTransplantObject(new_context, &tp_obj);
}
JS::RootedObject cs_fake_target(new_context, tp_obj);
retval.set(JS_TransplantObject(new_context, cs_root, cs_fake_target));
}
void NewContextGlobal(JSContext *ctx, JS::MutableHandleObject ret_val) {
JS::CompartmentOptions options;
options.setVersion(JSVERSION_LATEST);
JSObject *c_global = JS_NewGlobalObject(ctx, &global_class, nullptr,
JS::DontFireOnNewGlobalHook, options);
JS::RootedObject global(ctx, c_global);
{
JSAutoCompartment ac(ctx, global);
JS_InitStandardClasses(ctx, global);
assert(JS_InitReflect(ctx, global));
}
JS_FireOnNewGlobalObject(ctx, global);
ret_val.set(c_global);
}
MemoryScript GetScriptMemory(JSContext *ctx, JSScript *script) {
uint32_t ln;
JS::RootedScript rs_orig(ctx, script);
void *data = JS_EncodeScript(ctx, rs_orig, &ln);
return MemoryScript(data, ln);
}
JSScript *GetScript(JSContext *ctx, MemoryScript ms) {
return JS_DecodeScript(ctx, ms.data(), ms.length(), nullptr);
}
void NewGlobalObject(JSContext *ctx, JS::MutableHandleObject ret_val) {
JS::CompartmentOptions options;
options.setVersion(JSVERSION_LATEST);
const int threadId = JS_GetThreadId(ctx);
globals[threadId] = JS_NewGlobalObject(ctx, &global_class, nullptr,
JS::DontFireOnNewGlobalHook, options);
JS::RootedObject global(ctx, globals[threadId]);
{
JSAutoCompartment ac(ctx, global);
JS_InitStandardClasses(ctx, global);
assert(JS_InitReflect(ctx, global));
}
JS_FireOnNewGlobalObject(ctx, global);
ret_val.set(global);
}
} // namespace jxcore
| 1,517 |
577 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.google.android.apps.exposurenotification.onboarding;
import android.app.Activity;
import androidx.hilt.lifecycle.ViewModelInject;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.Transformations;
import androidx.lifecycle.ViewModel;
import androidx.work.OneTimeWorkRequest;
import androidx.work.WorkManager;
import com.google.android.apps.exposurenotification.privateanalytics.SubmitPrivateAnalyticsWorker;
import com.google.android.apps.exposurenotification.storage.ExposureNotificationSharedPreferences;
import com.google.android.libraries.privateanalytics.PrivateAnalyticsEnabledProvider;
/**
* View model for onboarding related actions.
*/
public class OnboardingViewModel extends ViewModel {
private final ExposureNotificationSharedPreferences exposureNotificationSharedPreferences;
private final PrivateAnalyticsEnabledProvider privateAnalyticsEnabledProvider;
private final WorkManager workManager;
private boolean resultOkSet = false;
@ViewModelInject
public OnboardingViewModel(
ExposureNotificationSharedPreferences exposureNotificationSharedPreferences,
PrivateAnalyticsEnabledProvider privateAnalyticsEnabledProvider,
WorkManager workManager) {
this.exposureNotificationSharedPreferences = exposureNotificationSharedPreferences;
this.privateAnalyticsEnabledProvider = privateAnalyticsEnabledProvider;
this.workManager = workManager;
}
public void setOnboardedState(boolean onboarded) {
exposureNotificationSharedPreferences.setOnboardedState(onboarded);
}
public void setAppAnalyticsState(boolean isEnabled) {
exposureNotificationSharedPreferences.setAppAnalyticsState(isEnabled);
}
public void markSmsInterceptNoticeSeenAsync() {
exposureNotificationSharedPreferences.markInAppSmsNoticeSeenAsync();
}
public LiveData<Boolean> isPrivateAnalyticsStateSetLiveData() {
return exposureNotificationSharedPreferences.isPrivateAnalyticsStateSetLiveData();
}
public LiveData<Boolean> shouldShowPrivateAnalyticsOnboardingLiveData() {
return Transformations.map(isPrivateAnalyticsStateSetLiveData(),
(isPrivateAnalyticsStateSet) -> !isPrivateAnalyticsStateSet
&& privateAnalyticsEnabledProvider.isSupportedByApp());
}
public void setPrivateAnalyticsState(boolean isEnabled) {
exposureNotificationSharedPreferences.setPrivateAnalyticsState(isEnabled);
}
/**
* Triggers a one off submit private analytics job.
*/
public void submitPrivateAnalytics() {
workManager.enqueue(new OneTimeWorkRequest.Builder(SubmitPrivateAnalyticsWorker.class).build());
}
/**
* Returns whether we've set {@link Activity#RESULT_OK} for the caller as this information
* may have been lost upon device configuration changes (e.g. rotations).
*/
public boolean isResultOkSet() {
return resultOkSet;
}
/**
* Marks if {@link Activity#RESULT_OK} can be set for the caller.
*/
public void setResultOk(boolean resultOkSet) {
this.resultOkSet = resultOkSet;
}
}
| 1,022 |
798 | /*
* The MIT License
*
* Copyright (c) 2013 The Broad Institute
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package picard.analysis;
import picard.metrics.MultilevelMetrics;
/**
* Holds information about CpG sites encountered for RRBS processing QC
* @author jgentry
*/
public final class RrbsCpgDetailMetrics extends MultilevelMetrics {
/** Sequence the CpG is seen in */
public String SEQUENCE_NAME;
/** Position within the sequence of the CpG site */
public Integer POSITION;
/** Number of times this CpG site was encountered */
public Integer TOTAL_SITES;
/** Number of times this CpG site was converted (TG for + strand, CA for - strand) */
public Integer CONVERTED_SITES;
/** CpG CONVERTED_BASES / CpG TOTAL_BASES (fraction) */
public Double PCT_CONVERTED;
}
| 509 |
764 | {
"symbol": "YOU",
"address": "0x1d32916CFA6534D261AD53E2498AB95505bd2510",
"overview":{
"en": "YouSwap is an All-Eco DEX project created by the blockchain geek team in Silicon Valley, USA. It realizes multi-chain sharing of digital assets by constructing a multi-chain ecological deployment system. It provides the project owner with one-click ICO technical support as well as fund-raising and coin listing service. It improves AMM (Automated Market Maker) model and provides liquidity with high security. In terms of finding the best trading routes for users, YouSwap provides multi-chain and cross-chain aggregation trade function. In terms of ecology improvement, YouSwap has developed loan service function, which can satisfy investors' loan demand and realize double benefits of investment and wealth management. YouSwap also provides derivative service, which is mainly suitable for digital asset managers to hedge risks. YouSwap provides stablecoin exchange and transfer service, which lowers the threshold for general public to enter blockchain. All these technical services can be applied on Ethernet Layer2.",
"zh": "YouSwap是由美国硅谷的区块链极客团队创建的一个全生态去中心化交易所项目,它通过构造多链生态的部署体系实现数字资产的多链共享,它为项目方提供了一键发币技术支持和募资上币服务,它改良了AMM模型(自动做市商算法)提供了具有高安全保障的流动性效果,在为用户寻找最佳交易路径方面YouSwap提供了多链跨链聚合交易功能,在生态完善方面,YouSwap开发了借贷服务功能可以满足投资者的借贷需求实现投资及理财双收益,YouSwap也提供了衍生品服务主要适合数字资产管理者进行风险对冲,YouSwap提供了稳定币的兑换转账服务降低了大众人群进入区块链的门槛等等,并且这些技术服务在以太坊网络Layer2上都能实现应用。"
},
"email": "<EMAIL>",
"website": "https://www.youswap.info/",
"whitepaper": "https://www.youswap.info/white-papper-cn.pdf",
"state": "NORMAL",
"published_on": "2021-03-15",
"initial_price":{
"ETH":"0.000054088 ETH",
"USD":"0.1 USD",
"BTC":"0.0000016629 BTC"
},
"links": {
"blog": "https://medium.com/@YouSwap_Global",
"twitter": "https://twitter.com/YouSwap1",
"telegram": "https://t.me/YouSwap_Dex",
"facebook": "https://www.facebook.com/YouSwap.Global",
"reddit": "https://www.reddit.com/user/YouSwap_Global",
"medium": "https://medium.com/@YouSwap_Global"
}
} | 1,166 |
377 | /*******************************************************************************
* * Copyright 2012 Impetus Infotech.
* *
* * 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.impetus.kundera.persistence;
import junit.framework.TestCase;
import com.impetus.kundera.cache.Cache;
import com.impetus.kundera.cache.CacheProvider;
import com.impetus.kundera.entity.PersonnelDTO;
/**
* The Class EntityManagerSessionTest.
*
* @author amresh.singh
*/
public class EntityManagerSessionTest extends TestCase
{
/** The ems. */
EntityManagerSession ems;
/** The cache provider. */
CacheProvider cacheProvider;
/** The cache. */
Cache cache;
/** The cache resource. */
String cacheResource = "/ehcache-test.xml";;
/** The cache provider class name. */
String cacheProviderClassName = "com.impetus.kundera.cache.ehcache.EhCacheProvider";
/** The person1. */
PersonnelDTO person1;
/** The person2. */
PersonnelDTO person2;
/*
* (non-Javadoc)
*
* @see junit.framework.TestCase#setUp()
*/
protected void setUp() throws Exception
{
super.setUp();
Class<CacheProvider> cacheProviderClass = (Class<CacheProvider>) Class.forName(cacheProviderClassName);
cacheProvider = cacheProviderClass.newInstance();
cacheProvider.init(cacheResource);
cache = (Cache) cacheProvider.createCache("Kundera");
ems = new EntityManagerSession(cache);
person1 = new PersonnelDTO("1", "Amresh", "Singh");
person2 = new PersonnelDTO("2", "Vivek", "Mishra");
}
/*
* (non-Javadoc)
*
* @see junit.framework.TestCase#tearDown()
*/
protected void tearDown() throws Exception
{
super.tearDown();
ems.clear();
cacheProvider.shutdown();
cache = null;
}
/**
* Test.
*/
public void test()
{
assertNotNull(ems);
// Store objects into session
ems.store(person1.getPersonId(), person1);
assertEquals(1, ems.getL2Cache().size());
ems.store(person2.getPersonId(), person2);
assertEquals(2, ems.getL2Cache().size());
// Lookup object from session
PersonnelDTO p1 = ems.lookup(PersonnelDTO.class, person1.getPersonId());
assertNotNull(p1);
assertEquals(person1.getPersonId(), p1.getPersonId());
assertEquals(person1.getFirstName(), p1.getFirstName());
assertEquals(person1.getLastName(), p1.getLastName());
// Remove object from session
ems.remove(PersonnelDTO.class, person1.getPersonId());
assertNotNull(ems);
assertEquals(1, ems.getL2Cache().size());
// Clear session
ems.clear();
assertNotNull(ems);
assertEquals(0, ems.getL2Cache().size());
}
}
| 1,422 |
376 | <filename>src/net/zhuoweizhang/boardwalk/util/PlatformUtils.java<gh_stars>100-1000
package net.zhuoweizhang.boardwalk.util;
import java.io.*;
import java.util.*;
import java.util.regex.*;
/* Must not have Android dependencies. Reflection is OK.
* Stuff that links directly to Android stuff goes in DroidUtils
*/
public class PlatformUtils {
/** @return amount of physical memory in bytes */
public static long getTotalMemory() {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("/proc/meminfo"));
String tempLine = reader.readLine().trim();
do {
tempLine = tempLine.replaceAll(" ", " ");
} while (tempLine.contains(" "));
String[] theLine = tempLine.split(" ");
if (!theLine[0].equals("MemTotal:")) return 0;
return Long.parseLong(theLine[1]) * 1024;
} catch (IOException e) {
return 0;
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException notanotherone){}
}
}
}
/** @return number of logical CPUs on this device */
public static int getNumCores() {
// http://stackoverflow.com/questions/10133570/availableprocessors-returns-1-for-dualcore-phones
FileFilter filter = new FileFilter() {
public boolean accept(File pathname) {
return Pattern.matches("cpu[0-9]+", pathname.getName());
}
};
try {
File dir = new File("/sys/devices/system/cpu/");
return dir.listFiles(filter).length;
} catch (Exception e) {
return Math.max(1, Runtime.getRuntime().availableProcessors());
}
}
public static int getAndroidVersion() {
try {
return Class.forName("android.os.Build$VERSION").getField("SDK_INT").getInt(null);
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
}
| 636 |
3,167 | <filename>open_spiel/python/tests/higc_referee_test.py
# Copyright 2019 DeepMind Technologies Ltd. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for open_spiel.python.referee."""
import os
from absl.testing import absltest
import pyspiel
class RefereeTest(absltest.TestCase):
def test_playing_tournament(self):
base = os.path.dirname(__file__) + "/../bots"
ref = pyspiel.Referee(
"kuhn_poker", [f"{base}/higc_random_bot_test.py"] * 2,
settings=pyspiel.TournamentSettings(
timeout_ready=2000, timeout_start=500))
self.assertTrue(ref.started_successfully())
results = ref.play_tournament(num_matches=1)
self.assertLen(results.matches, 1)
if __name__ == "__main__":
absltest.main()
| 427 |
450 | <gh_stars>100-1000
package com.amalbit.trail.util;
public class AnimatorListener implements android.animation.Animator.AnimatorListener {
@Override
public void onAnimationStart(android.animation.Animator animation, boolean isReverse) {
}
@Override
public void onAnimationEnd(android.animation.Animator animation, boolean isReverse) {
}
@Override
public void onAnimationStart(android.animation.Animator animator) {
}
@Override
public void onAnimationEnd(android.animation.Animator animator) {
}
@Override
public void onAnimationCancel(android.animation.Animator animator) {
}
@Override
public void onAnimationRepeat(android.animation.Animator animator) {
}
}
| 211 |
346 |
#include <assert.h>
#include <unistd.h>
#include <plash.h>
int main() {
if (getuid())
pl_setup_user_ns();
assert(getuid() == 0);
}
| 66 |
630 | /*
* Copyright (C) 2015, BMW Car IT GmbH
*
* Author: <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in
* writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*/
package com.bmwcarit.barefoot.markov;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Measurement sample as input for Hidden Markov Model (HMM) inference, e.g. with a HMM filter
* {@link Filter}.
*/
public class Sample {
private long time;
/**
* Creates {@link Sample} object with a timestamp in milliseconds epoch time.
*
* @param time Timestamp of position measurement in milliseconds epoch time.
*/
public Sample(long time) {
this.time = time;
}
/**
* Creates {@link Sample} object from JSON representation.
*
* @param json JSON representation of a sample.
* @throws JSONException thrown on JSON extraction or parsing error.
*/
public Sample(JSONObject json) throws JSONException {
time = json.optLong("time", Long.MIN_VALUE);
if (time == Long.MIN_VALUE) {
String string = json.optString("time", "");
if (!string.isEmpty()) {
try {
time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssX")
.parse(json.getString("time")).getTime();
} catch (ParseException e) {
throw new JSONException(e);
}
} else {
throw new JSONException("time key not found");
}
}
}
/**
* Gets the timestamp of the measurement sample in milliseconds epoch time.
*
* @return Timestamp of the measurement in milliseconds epoch time.
*/
public long time() {
return time;
}
/**
* Gets a JSON representation of the {@link Sample} object.
*
* @return JSON representation of the {@link Sample} object.
* @throws JSONException thrown on JSON extraction or parsing error.
*/
public JSONObject toJSON() throws JSONException {
JSONObject json = new JSONObject();
json.put("time", time);
return json;
}
}
| 977 |
575 | <gh_stars>100-1000
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "services/network/chunked_data_pipe_upload_data_stream.h"
#include <stdint.h>
#include <limits>
#include <memory>
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/run_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/test/task_environment.h"
#include "mojo/public/cpp/system/data_pipe.h"
#include "mojo/public/cpp/system/data_pipe_utils.h"
#include "net/base/completion_once_callback.h"
#include "net/base/io_buffer.h"
#include "net/base/test_completion_callback.h"
#include "net/log/net_log_with_source.h"
#include "services/network/public/cpp/resource_request_body.h"
#include "services/network/public/mojom/chunked_data_pipe_getter.mojom.h"
#include "services/network/test_chunked_data_pipe_getter.h"
#include "testing/gtest/include/gtest/gtest.h"
// Most tests of this class are at the URLLoader layer. These tests focus on
// things too difficult to cover with integration tests.
namespace network {
namespace {
net::CompletionOnceCallback NoCallback() {
return base::BindOnce([](int result) {
NOTREACHED() << "This callback should not be called. result=" << result;
});
}
class ChunkedDataPipeUploadDataStreamTest : public testing::Test {
public:
ChunkedDataPipeUploadDataStreamTest() { CreateAndInitChunkedUploadStream(); }
void CreateAndInitChunkedUploadStream() {
CreateChunkedUploadStream();
InitChunkedUploadStream();
}
void CreateChunkedUploadStream() {
chunked_data_pipe_getter_ = std::make_unique<TestChunkedDataPipeGetter>();
chunked_upload_stream_ = std::make_unique<ChunkedDataPipeUploadDataStream>(
base::MakeRefCounted<network::ResourceRequestBody>(),
chunked_data_pipe_getter_->GetDataPipeGetterRemote());
}
void InitChunkedUploadStream() {
// Nothing interesting happens before Init, so always wait for it in the
// test fixture.
EXPECT_EQ(net::OK, chunked_upload_stream_->Init(NoCallback(),
net::NetLogWithSource()));
get_size_callback_ = chunked_data_pipe_getter_->WaitForGetSize();
write_pipe_ = chunked_data_pipe_getter_->WaitForStartReading();
EXPECT_TRUE(chunked_upload_stream_->is_chunked());
EXPECT_FALSE(chunked_upload_stream_->IsEOF());
EXPECT_FALSE(chunked_upload_stream_->IsInMemory());
}
protected:
base::test::SingleThreadTaskEnvironment task_environment_{
base::test::SingleThreadTaskEnvironment::MainThreadType::IO};
std::unique_ptr<TestChunkedDataPipeGetter> chunked_data_pipe_getter_;
std::unique_ptr<ChunkedDataPipeUploadDataStream> chunked_upload_stream_;
mojom::ChunkedDataPipeGetter::GetSizeCallback get_size_callback_;
mojo::ScopedDataPipeProducerHandle write_pipe_;
};
// Test just reading through the response body once, where reads are initiated
// before data is received.
TEST_F(ChunkedDataPipeUploadDataStreamTest, ReadBeforeDataReady) {
const std::string kData = "1234567890";
for (int consumer_read_size : {5, 10, 20}) {
for (int num_writes : {0, 1, 2}) {
CreateAndInitChunkedUploadStream();
for (int i = 0; i < num_writes; ++i) {
std::string read_data;
while (read_data.size() < kData.size()) {
net::TestCompletionCallback callback;
auto io_buffer =
base::MakeRefCounted<net::IOBufferWithSize>(consumer_read_size);
int result = chunked_upload_stream_->Read(
io_buffer.get(), io_buffer->size(), callback.callback());
if (read_data.size() == 0)
mojo::BlockingCopyFromString(kData, write_pipe_);
result = callback.GetResult(result);
ASSERT_LT(0, result);
EXPECT_LE(result, consumer_read_size);
read_data.append(std::string(io_buffer->data(), result));
EXPECT_FALSE(chunked_upload_stream_->IsEOF());
}
EXPECT_EQ(read_data, kData);
}
auto io_buffer =
base::MakeRefCounted<net::IOBufferWithSize>(consumer_read_size);
net::TestCompletionCallback callback;
int result = chunked_upload_stream_->Read(
io_buffer.get(), io_buffer->size(), callback.callback());
EXPECT_EQ(net::ERR_IO_PENDING, result);
std::move(get_size_callback_).Run(net::OK, num_writes * kData.size());
EXPECT_EQ(net::OK, callback.GetResult(result));
EXPECT_TRUE(chunked_upload_stream_->IsEOF());
}
}
}
// Test just reading through the response body once, where reads are initiated
// after data has been received.
TEST_F(ChunkedDataPipeUploadDataStreamTest, ReadAfterDataReady) {
const std::string kData = "1234567890";
for (int consumer_read_size : {5, 10, 20}) {
for (int num_writes : {0, 1, 2}) {
CreateAndInitChunkedUploadStream();
for (int i = 0; i < num_writes; ++i) {
mojo::BlockingCopyFromString(kData, write_pipe_);
base::RunLoop().RunUntilIdle();
std::string read_data;
while (read_data.size() < kData.size()) {
net::TestCompletionCallback callback;
auto io_buffer =
base::MakeRefCounted<net::IOBufferWithSize>(consumer_read_size);
int result = chunked_upload_stream_->Read(
io_buffer.get(), io_buffer->size(), callback.callback());
ASSERT_LT(0, result);
EXPECT_LE(result, consumer_read_size);
read_data.append(std::string(io_buffer->data(), result));
EXPECT_FALSE(chunked_upload_stream_->IsEOF());
}
EXPECT_EQ(read_data, kData);
}
std::move(get_size_callback_).Run(net::OK, num_writes * kData.size());
base::RunLoop().RunUntilIdle();
net::TestCompletionCallback callback;
auto io_buffer =
base::MakeRefCounted<net::IOBufferWithSize>(consumer_read_size);
EXPECT_EQ(net::OK,
chunked_upload_stream_->Read(io_buffer.get(), io_buffer->size(),
callback.callback()));
EXPECT_TRUE(chunked_upload_stream_->IsEOF());
}
}
}
// Test the case where the URLRequest reads through the request body multiple
// times, as can happen in the case of redirects or retries.
TEST_F(ChunkedDataPipeUploadDataStreamTest, MultipleReadThrough) {
const std::string kData = "1234567890";
// Send size up front - cases where the size isn't initially known are checked
// elsewhere, and have to have size before the first read through can complete
// successfully.
std::move(get_size_callback_).Run(net::OK, kData.size());
base::RunLoop().RunUntilIdle();
// 3 is an arbitrary number greater than 1.
for (int i = 0; i < 3; i++) {
// Already initialized before loop runs for the first time.
if (i != 0) {
net::TestCompletionCallback callback;
EXPECT_EQ(net::OK, chunked_upload_stream_->Init(callback.callback(),
net::NetLogWithSource()));
write_pipe_ = chunked_data_pipe_getter_->WaitForStartReading();
}
mojo::BlockingCopyFromString(kData, write_pipe_);
std::string read_data;
while (read_data.size() < kData.size()) {
net::TestCompletionCallback callback;
auto io_buffer =
base::MakeRefCounted<net::IOBufferWithSize>(kData.size());
int result = chunked_upload_stream_->Read(
io_buffer.get(), io_buffer->size(), callback.callback());
result = callback.GetResult(result);
ASSERT_LT(0, result);
EXPECT_LE(static_cast<size_t>(result), kData.size());
read_data.append(std::string(io_buffer->data(), result));
if (read_data.size() == kData.size()) {
EXPECT_TRUE(chunked_upload_stream_->IsEOF());
} else {
EXPECT_FALSE(chunked_upload_stream_->IsEOF());
}
}
EXPECT_EQ(kData, read_data);
net::TestCompletionCallback callback;
auto io_buffer = base::MakeRefCounted<net::IOBufferWithSize>(1);
int result =
chunked_upload_stream_->Read(io_buffer.get(), 1, callback.callback());
EXPECT_EQ(net::OK, callback.GetResult(result));
EXPECT_TRUE(chunked_upload_stream_->IsEOF());
chunked_upload_stream_->Reset();
}
}
// Test the case where the URLRequest partially reads through the request body
// multiple times, as can happen in the case of retries. The size is known from
// the start.
TEST_F(ChunkedDataPipeUploadDataStreamTest,
MultiplePartialReadThroughWithKnownSize) {
const std::string kData = "1234567890";
std::move(get_size_callback_).Run(net::OK, kData.size());
// Wait for the stream to learn the size, to avoid any races.
base::RunLoop().RunUntilIdle();
// In each iteration, read through more of the body. Reset the stream after
// each loop iteration but the last, which reads the entire body.
for (size_t num_bytes_to_read = 0; num_bytes_to_read <= kData.size();
num_bytes_to_read++) {
// Already initialized before loop runs for the first time.
if (num_bytes_to_read != 0) {
net::TestCompletionCallback callback;
EXPECT_EQ(net::OK, chunked_upload_stream_->Init(callback.callback(),
net::NetLogWithSource()));
write_pipe_ = chunked_data_pipe_getter_->WaitForStartReading();
}
mojo::BlockingCopyFromString(kData.substr(0, num_bytes_to_read),
write_pipe_);
std::string read_data;
while (read_data.size() < num_bytes_to_read) {
net::TestCompletionCallback callback;
auto io_buffer =
base::MakeRefCounted<net::IOBufferWithSize>(kData.size());
int result = chunked_upload_stream_->Read(
io_buffer.get(), io_buffer->size(), callback.callback());
result = callback.GetResult(result);
ASSERT_LT(0, result);
EXPECT_LE(static_cast<size_t>(result), kData.size());
read_data.append(std::string(io_buffer->data(), result));
if (read_data.size() == kData.size()) {
EXPECT_TRUE(chunked_upload_stream_->IsEOF());
} else {
EXPECT_FALSE(chunked_upload_stream_->IsEOF());
}
}
EXPECT_EQ(kData.substr(0, num_bytes_to_read), read_data);
if (num_bytes_to_read != kData.size())
chunked_upload_stream_->Reset();
}
net::TestCompletionCallback callback;
auto io_buffer = base::MakeRefCounted<net::IOBufferWithSize>(1);
int result =
chunked_upload_stream_->Read(io_buffer.get(), 1, callback.callback());
EXPECT_EQ(net::OK, callback.GetResult(result));
EXPECT_TRUE(chunked_upload_stream_->IsEOF());
}
// Test the case where the URLRequest partially reads through the request body
// multiple times, as can happen in the case of retries. The size isn't known
// until the end.
TEST_F(ChunkedDataPipeUploadDataStreamTest,
MultiplePartialReadThroughSizeNotKnown) {
const std::string kData = "1234567890";
// In each iteration, read through more of the body. Reset the stream after
// each loop iteration but the last, which reads the entire body.
for (size_t num_bytes_to_read = 0; num_bytes_to_read <= kData.size();
num_bytes_to_read++) {
// Already initialized before loop runs for the first time.
if (num_bytes_to_read != 0) {
net::TestCompletionCallback callback;
EXPECT_EQ(net::OK, chunked_upload_stream_->Init(callback.callback(),
net::NetLogWithSource()));
write_pipe_ = chunked_data_pipe_getter_->WaitForStartReading();
}
mojo::BlockingCopyFromString(kData.substr(0, num_bytes_to_read),
write_pipe_);
std::string read_data;
while (read_data.size() < num_bytes_to_read) {
net::TestCompletionCallback callback;
auto io_buffer =
base::MakeRefCounted<net::IOBufferWithSize>(kData.size());
int result = chunked_upload_stream_->Read(
io_buffer.get(), io_buffer->size(), callback.callback());
result = callback.GetResult(result);
ASSERT_LT(0, result);
EXPECT_LE(static_cast<size_t>(result), kData.size());
read_data.append(std::string(io_buffer->data(), result));
EXPECT_FALSE(chunked_upload_stream_->IsEOF());
}
EXPECT_EQ(kData.substr(0, num_bytes_to_read), read_data);
if (num_bytes_to_read != kData.size())
chunked_upload_stream_->Reset();
}
std::move(get_size_callback_).Run(net::OK, kData.size());
base::RunLoop().RunUntilIdle();
net::TestCompletionCallback callback;
auto io_buffer = base::MakeRefCounted<net::IOBufferWithSize>(1);
int result =
chunked_upload_stream_->Read(io_buffer.get(), 1, callback.callback());
EXPECT_EQ(net::OK, callback.GetResult(result));
EXPECT_TRUE(chunked_upload_stream_->IsEOF());
}
// Test where GetSize() is invoked before the upload is initialized.
TEST_F(ChunkedDataPipeUploadDataStreamTest, GetSizeSucceedsBeforeInit) {
const std::string kData = "1234567890";
chunked_data_pipe_getter_ = std::make_unique<TestChunkedDataPipeGetter>();
chunked_upload_stream_ = std::make_unique<ChunkedDataPipeUploadDataStream>(
base::MakeRefCounted<network::ResourceRequestBody>(),
chunked_data_pipe_getter_->GetDataPipeGetterRemote());
get_size_callback_ = chunked_data_pipe_getter_->WaitForGetSize();
std::move(get_size_callback_).Run(net::OK, kData.size());
// Wait for the ChunkedUploadStream to receive the size.
base::RunLoop().RunUntilIdle();
net::TestCompletionCallback callback;
ASSERT_EQ(net::OK, chunked_upload_stream_->Init(callback.callback(),
net::NetLogWithSource()));
write_pipe_ = chunked_data_pipe_getter_->WaitForStartReading();
EXPECT_TRUE(chunked_upload_stream_->is_chunked());
EXPECT_FALSE(chunked_upload_stream_->IsEOF());
mojo::BlockingCopyFromString(kData, write_pipe_);
std::string read_data;
while (read_data.size() < kData.size()) {
net::TestCompletionCallback callback;
int read_size = kData.size() - read_data.size();
auto io_buffer = base::MakeRefCounted<net::IOBufferWithSize>(read_size);
int result = chunked_upload_stream_->Read(
io_buffer.get(), io_buffer->size(), callback.callback());
result = callback.GetResult(result);
ASSERT_LT(0, result);
EXPECT_LE(result, read_size);
read_data.append(std::string(io_buffer->data(), result));
EXPECT_EQ(read_data.size() == kData.size(),
chunked_upload_stream_->IsEOF());
}
}
// Test where GetSize() is only invoked after the upload is reset.
TEST_F(ChunkedDataPipeUploadDataStreamTest, GetSizeSucceedsAfterReset) {
const std::string kData = "1234567890";
// Read through the body once, without a size
std::string read_data;
mojo::BlockingCopyFromString(kData, write_pipe_);
while (read_data.size() < kData.size()) {
net::TestCompletionCallback callback;
int read_size = kData.size() - read_data.size();
auto io_buffer = base::MakeRefCounted<net::IOBufferWithSize>(read_size);
int result = chunked_upload_stream_->Read(
io_buffer.get(), io_buffer->size(), callback.callback());
result = callback.GetResult(result);
ASSERT_LT(0, result);
EXPECT_LE(result, read_size);
read_data.append(std::string(io_buffer->data(), result));
EXPECT_FALSE(chunked_upload_stream_->IsEOF());
}
// Reset, get the size, and read through the body again.
chunked_upload_stream_->Reset();
std::move(get_size_callback_).Run(net::OK, kData.size());
// Wait for the ChunkedUploadStream to receive the size.
base::RunLoop().RunUntilIdle();
net::TestCompletionCallback callback;
ASSERT_EQ(net::OK, chunked_upload_stream_->Init(callback.callback(),
net::NetLogWithSource()));
write_pipe_ = chunked_data_pipe_getter_->WaitForStartReading();
read_data.erase();
mojo::BlockingCopyFromString(kData, write_pipe_);
while (read_data.size() < kData.size()) {
net::TestCompletionCallback callback;
int read_size = kData.size() - read_data.size();
auto io_buffer = base::MakeRefCounted<net::IOBufferWithSize>(read_size);
int result = chunked_upload_stream_->Read(
io_buffer.get(), io_buffer->size(), callback.callback());
result = callback.GetResult(result);
ASSERT_LT(0, result);
EXPECT_LE(result, read_size);
read_data.append(std::string(io_buffer->data(), result));
EXPECT_EQ(read_data.size() == kData.size(),
chunked_upload_stream_->IsEOF());
}
}
// Test where GetSize() is invoked with an error before the upload is
// initialized.
TEST_F(ChunkedDataPipeUploadDataStreamTest, GetSizeFailsBeforeInit) {
const std::string kData = "1234567890";
chunked_data_pipe_getter_ = std::make_unique<TestChunkedDataPipeGetter>();
chunked_upload_stream_ = std::make_unique<ChunkedDataPipeUploadDataStream>(
base::MakeRefCounted<network::ResourceRequestBody>(),
chunked_data_pipe_getter_->GetDataPipeGetterRemote());
get_size_callback_ = chunked_data_pipe_getter_->WaitForGetSize();
std::move(get_size_callback_).Run(net::ERR_ACCESS_DENIED, 0);
// Wait for the ChunkedUploadStream to receive the size.
base::RunLoop().RunUntilIdle();
net::TestCompletionCallback callback;
EXPECT_EQ(net::ERR_ACCESS_DENIED,
chunked_upload_stream_->Init(callback.callback(),
net::NetLogWithSource()));
}
// Test where GetSize() is only invoked with an error after the upload is reset.
TEST_F(ChunkedDataPipeUploadDataStreamTest, GetSizeFailsAfterReset) {
const std::string kData = "1234567890";
// Read through the body once, without a size
std::string read_data;
mojo::BlockingCopyFromString(kData, write_pipe_);
while (read_data.size() < kData.size()) {
net::TestCompletionCallback callback;
int read_size = kData.size() - read_data.size();
auto io_buffer = base::MakeRefCounted<net::IOBufferWithSize>(read_size);
int result = chunked_upload_stream_->Read(
io_buffer.get(), io_buffer->size(), callback.callback());
result = callback.GetResult(result);
ASSERT_LT(0, result);
EXPECT_LE(result, read_size);
read_data.append(std::string(io_buffer->data(), result));
EXPECT_FALSE(chunked_upload_stream_->IsEOF());
}
// Reset, get the size, and read through the body again.
chunked_upload_stream_->Reset();
std::move(get_size_callback_).Run(net::ERR_ACCESS_DENIED, kData.size());
// Wait for the ChunkedUploadStream to receive the size.
base::RunLoop().RunUntilIdle();
net::TestCompletionCallback callback;
ASSERT_EQ(net::ERR_ACCESS_DENIED,
chunked_upload_stream_->Init(callback.callback(),
net::NetLogWithSource()));
}
// Three variations on when the stream can be closed before a request succeeds.
// Stream is closed, then a read attempted, then the GetSizeCallback is invoked.
// The read should notice the close body pipe, but not report anything until the
// GetSizeCallback is invoked.
TEST_F(ChunkedDataPipeUploadDataStreamTest, CloseBodyPipeBeforeSuccess1) {
write_pipe_.reset();
base::RunLoop().RunUntilIdle();
net::TestCompletionCallback callback;
auto io_buffer = base::MakeRefCounted<net::IOBufferWithSize>(1);
int result =
chunked_upload_stream_->Read(io_buffer.get(), 1, callback.callback());
EXPECT_EQ(result, net::ERR_IO_PENDING);
EXPECT_FALSE(chunked_upload_stream_->IsEOF());
std::move(get_size_callback_).Run(net::OK, 0);
EXPECT_EQ(net::OK, callback.GetResult(result));
EXPECT_TRUE(chunked_upload_stream_->IsEOF());
}
// A read attempt, stream is closed, then the GetSizeCallback is invoked. The
// watcher should see the close, but not report anything until the
// GetSizeCallback is invoked.
TEST_F(ChunkedDataPipeUploadDataStreamTest, CloseBodyPipeBeforeSuccess2) {
net::TestCompletionCallback callback;
auto io_buffer = base::MakeRefCounted<net::IOBufferWithSize>(1);
int result =
chunked_upload_stream_->Read(io_buffer.get(), 1, callback.callback());
EXPECT_EQ(result, net::ERR_IO_PENDING);
write_pipe_.reset();
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(callback.have_result());
EXPECT_FALSE(chunked_upload_stream_->IsEOF());
std::move(get_size_callback_).Run(net::OK, 0);
EXPECT_EQ(net::OK, callback.GetResult(result));
EXPECT_TRUE(chunked_upload_stream_->IsEOF());
}
// The stream is closed, the GetSizeCallback is invoked, and then a read
// attempt. The read attempt should notice the request already successfully
// completed.
TEST_F(ChunkedDataPipeUploadDataStreamTest, CloseBodyPipeBeforeSuccess3) {
write_pipe_.reset();
base::RunLoop().RunUntilIdle();
std::move(get_size_callback_).Run(net::OK, 0);
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(chunked_upload_stream_->IsEOF());
net::TestCompletionCallback callback;
auto io_buffer = base::MakeRefCounted<net::IOBufferWithSize>(1);
int result =
chunked_upload_stream_->Read(io_buffer.get(), 1, callback.callback());
EXPECT_EQ(net::OK, callback.GetResult(result));
EXPECT_TRUE(chunked_upload_stream_->IsEOF());
}
// Same cases as above, but the GetSizeCallback indicates the response was
// truncated.
TEST_F(ChunkedDataPipeUploadDataStreamTest, CloseBodyPipeBeforeTruncation1) {
write_pipe_.reset();
base::RunLoop().RunUntilIdle();
net::TestCompletionCallback callback;
auto io_buffer = base::MakeRefCounted<net::IOBufferWithSize>(1);
int result =
chunked_upload_stream_->Read(io_buffer.get(), 1, callback.callback());
EXPECT_EQ(result, net::ERR_IO_PENDING);
std::move(get_size_callback_).Run(net::OK, 1);
EXPECT_EQ(net::ERR_FAILED, callback.GetResult(result));
}
TEST_F(ChunkedDataPipeUploadDataStreamTest, CloseBodyPipeBeforeTruncation2) {
net::TestCompletionCallback callback;
auto io_buffer = base::MakeRefCounted<net::IOBufferWithSize>(1);
int result =
chunked_upload_stream_->Read(io_buffer.get(), 1, callback.callback());
EXPECT_EQ(result, net::ERR_IO_PENDING);
write_pipe_.reset();
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(callback.have_result());
std::move(get_size_callback_).Run(net::OK, 1);
EXPECT_EQ(net::ERR_FAILED, callback.GetResult(result));
}
TEST_F(ChunkedDataPipeUploadDataStreamTest, CloseBodyPipeBeforeTruncation3) {
write_pipe_.reset();
base::RunLoop().RunUntilIdle();
std::move(get_size_callback_).Run(net::OK, 1);
net::TestCompletionCallback callback;
auto io_buffer = base::MakeRefCounted<net::IOBufferWithSize>(1);
int result =
chunked_upload_stream_->Read(io_buffer.get(), 1, callback.callback());
EXPECT_EQ(net::ERR_FAILED, callback.GetResult(result));
}
// Same cases as above, but the GetSizeCallback indicates the read failed.
TEST_F(ChunkedDataPipeUploadDataStreamTest, CloseBodyPipeBeforeFailure1) {
write_pipe_.reset();
base::RunLoop().RunUntilIdle();
net::TestCompletionCallback callback;
auto io_buffer = base::MakeRefCounted<net::IOBufferWithSize>(1);
int result =
chunked_upload_stream_->Read(io_buffer.get(), 1, callback.callback());
EXPECT_EQ(result, net::ERR_IO_PENDING);
std::move(get_size_callback_).Run(net::ERR_ACCESS_DENIED, 0);
EXPECT_EQ(net::ERR_ACCESS_DENIED, callback.GetResult(result));
}
TEST_F(ChunkedDataPipeUploadDataStreamTest, CloseBodyPipeBeforeFailure2) {
net::TestCompletionCallback callback;
auto io_buffer = base::MakeRefCounted<net::IOBufferWithSize>(1);
int result =
chunked_upload_stream_->Read(io_buffer.get(), 1, callback.callback());
EXPECT_EQ(result, net::ERR_IO_PENDING);
write_pipe_.reset();
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(callback.have_result());
std::move(get_size_callback_).Run(net::ERR_ACCESS_DENIED, 0);
EXPECT_EQ(net::ERR_ACCESS_DENIED, callback.GetResult(result));
}
TEST_F(ChunkedDataPipeUploadDataStreamTest, CloseBodyPipeBeforeFailure3) {
write_pipe_.reset();
base::RunLoop().RunUntilIdle();
std::move(get_size_callback_).Run(net::ERR_ACCESS_DENIED, 0);
net::TestCompletionCallback callback;
auto io_buffer = base::MakeRefCounted<net::IOBufferWithSize>(1);
int result =
chunked_upload_stream_->Read(io_buffer.get(), 1, callback.callback());
EXPECT_EQ(net::ERR_ACCESS_DENIED, callback.GetResult(result));
}
// Same cases as above, but ChunkedBodyGetter pipe is destroyed without invoking
// the GetSizeCallback.
TEST_F(ChunkedDataPipeUploadDataStreamTest, CloseBodyPipeBeforeCloseGetter1) {
write_pipe_.reset();
base::RunLoop().RunUntilIdle();
net::TestCompletionCallback callback;
auto io_buffer = base::MakeRefCounted<net::IOBufferWithSize>(1);
int result =
chunked_upload_stream_->Read(io_buffer.get(), 1, callback.callback());
EXPECT_EQ(result, net::ERR_IO_PENDING);
chunked_data_pipe_getter_.reset();
EXPECT_EQ(net::ERR_FAILED, callback.GetResult(result));
}
TEST_F(ChunkedDataPipeUploadDataStreamTest, CloseBodyPipeBeforeCloseGetter2) {
net::TestCompletionCallback callback;
auto io_buffer = base::MakeRefCounted<net::IOBufferWithSize>(1);
int result =
chunked_upload_stream_->Read(io_buffer.get(), 1, callback.callback());
EXPECT_EQ(result, net::ERR_IO_PENDING);
write_pipe_.reset();
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(callback.have_result());
chunked_data_pipe_getter_.reset();
EXPECT_EQ(net::ERR_FAILED, callback.GetResult(result));
}
TEST_F(ChunkedDataPipeUploadDataStreamTest, CloseBodyPipeBeforeCloseGetter3) {
write_pipe_.reset();
base::RunLoop().RunUntilIdle();
chunked_data_pipe_getter_.reset();
net::TestCompletionCallback callback;
auto io_buffer = base::MakeRefCounted<net::IOBufferWithSize>(1);
int result =
chunked_upload_stream_->Read(io_buffer.get(), 1, callback.callback());
EXPECT_EQ(net::ERR_FAILED, callback.GetResult(result));
}
// Test uses same order as CloseBodyPipeBeforeTruncation1, but in this test the
// GetSizeCallback indicates too many bytes were received.
TEST_F(ChunkedDataPipeUploadDataStreamTest, ExtraBytes1) {
const std::string kData = "123";
mojo::BlockingCopyFromString(kData, write_pipe_);
std::string read_data;
while (read_data.size() < kData.size()) {
net::TestCompletionCallback callback;
auto io_buffer = base::MakeRefCounted<net::IOBufferWithSize>(kData.size());
int result = chunked_upload_stream_->Read(
io_buffer.get(), io_buffer->size(), callback.callback());
result = callback.GetResult(result);
ASSERT_LT(0, result);
read_data.append(std::string(io_buffer->data(), result));
EXPECT_LE(read_data.size(), kData.size());
EXPECT_FALSE(chunked_upload_stream_->IsEOF());
}
net::TestCompletionCallback callback;
auto io_buffer = base::MakeRefCounted<net::IOBufferWithSize>(1);
int result =
chunked_upload_stream_->Read(io_buffer.get(), 1, callback.callback());
EXPECT_EQ(result, net::ERR_IO_PENDING);
std::move(get_size_callback_).Run(net::OK, kData.size() - 1);
EXPECT_EQ(net::ERR_FAILED, callback.GetResult(result));
}
// Extra bytes are received after getting the size notification. No error should
// be reported,
TEST_F(ChunkedDataPipeUploadDataStreamTest, ExtraBytes2) {
const std::string kData = "123";
// Read first byte.
mojo::BlockingCopyFromString(kData.substr(0, 1), write_pipe_);
net::TestCompletionCallback callback;
auto io_buffer = base::MakeRefCounted<net::IOBufferWithSize>(1);
int result = chunked_upload_stream_->Read(io_buffer.get(), io_buffer->size(),
callback.callback());
result = callback.GetResult(result);
ASSERT_EQ(1, result);
EXPECT_FALSE(chunked_upload_stream_->IsEOF());
// Start another read.
net::TestCompletionCallback callback2;
ASSERT_EQ(net::ERR_IO_PENDING, chunked_upload_stream_->Read(
io_buffer.get(), 1, callback2.callback()));
// Learn the size was only one byte. Read should complete, indicating the end
// of the stream was reached.
std::move(get_size_callback_).Run(net::OK, 1);
EXPECT_EQ(net::OK, callback2.WaitForResult());
EXPECT_TRUE(chunked_upload_stream_->IsEOF());
// More data is copied to the stream unexpectedly. It should be ignored.
mojo::BlockingCopyFromString(kData.substr(1), write_pipe_);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(chunked_upload_stream_->IsEOF());
}
TEST_F(ChunkedDataPipeUploadDataStreamTest, ClosePipeGetterBeforeInit) {
chunked_data_pipe_getter_ = std::make_unique<TestChunkedDataPipeGetter>();
chunked_upload_stream_ = std::make_unique<ChunkedDataPipeUploadDataStream>(
base::MakeRefCounted<network::ResourceRequestBody>(),
chunked_data_pipe_getter_->GetDataPipeGetterRemote());
// Destroy the DataPipeGetter pipe, which is the pipe used for
// GetSizeCallback.
chunked_data_pipe_getter_->ClosePipe();
base::RunLoop().RunUntilIdle();
// Init should fail in this case.
net::TestCompletionCallback callback;
EXPECT_EQ(net::ERR_FAILED, chunked_upload_stream_->Init(
callback.callback(), net::NetLogWithSource()));
}
TEST_F(ChunkedDataPipeUploadDataStreamTest,
ClosePipeGetterWithoutCallingGetSizeCallbackNoPendingRead) {
// Destroy the DataPipeGetter pipe, which is the pipe used for
// GetSizeCallback.
chunked_data_pipe_getter_->ClosePipe();
base::RunLoop().RunUntilIdle();
net::TestCompletionCallback callback;
auto io_buffer = base::MakeRefCounted<net::IOBufferWithSize>(1);
int result =
chunked_upload_stream_->Read(io_buffer.get(), 1, callback.callback());
EXPECT_EQ(net::ERR_FAILED, callback.GetResult(result));
}
TEST_F(ChunkedDataPipeUploadDataStreamTest,
ClosePipeGetterWithoutCallingGetSizeCallbackPendingRead) {
net::TestCompletionCallback callback;
auto io_buffer = base::MakeRefCounted<net::IOBufferWithSize>(1);
int result =
chunked_upload_stream_->Read(io_buffer.get(), 1, callback.callback());
EXPECT_EQ(net::ERR_IO_PENDING, result);
// Destroy the DataPipeGetter pipe, which is the pipe used for
// GetSizeCallback.
chunked_data_pipe_getter_->ClosePipe();
EXPECT_EQ(net::ERR_FAILED, callback.GetResult(result));
}
TEST_F(ChunkedDataPipeUploadDataStreamTest,
ClosePipeGetterAfterCallingGetSizeCallback) {
const char kData[] = "1";
const int kDataLen = strlen(kData);
net::TestCompletionCallback callback;
auto io_buffer = base::MakeRefCounted<net::IOBufferWithSize>(kDataLen);
std::move(get_size_callback_).Run(net::OK, kDataLen);
// Destroy the DataPipeGetter pipe, which is the pipe used for
// GetSizeCallback.
chunked_data_pipe_getter_->ClosePipe();
base::RunLoop().RunUntilIdle();
int result = chunked_upload_stream_->Read(io_buffer.get(), kDataLen,
callback.callback());
EXPECT_EQ(net::ERR_IO_PENDING, result);
mojo::BlockingCopyFromString(kData, write_pipe_);
// Since the pipe was closed the GetSizeCallback was invoked, reading the
// upload body should succeed once.
EXPECT_EQ(kDataLen, callback.GetResult(result));
EXPECT_TRUE(chunked_upload_stream_->IsEOF());
net::TestCompletionCallback callback2;
EXPECT_EQ(0, chunked_upload_stream_->Read(io_buffer.get(), kDataLen,
callback2.callback()));
// But trying again will result in failure.
chunked_upload_stream_->Reset();
net::TestCompletionCallback callback3;
EXPECT_EQ(net::ERR_FAILED,
chunked_upload_stream_->Init(callback3.callback(),
net::NetLogWithSource()));
}
#define EXPECT_READ(chunked_upload_stream, io_buffer, expected) \
{ \
int result = chunked_upload_stream->Read(io_buffer.get(), \
io_buffer->size(), NoCallback()); \
EXPECT_GT(result, 0); \
EXPECT_EQ(std::string(io_buffer->data(), result), expected); \
}
#define EXPECT_EOF(chunked_upload_stream, size) \
{ \
net::TestCompletionCallback callback; \
auto io_buffer = base::MakeRefCounted<net::IOBufferWithSize>(1); \
int result = \
chunked_upload_stream->Read(io_buffer.get(), 1u, callback.callback()); \
EXPECT_EQ(net::ERR_IO_PENDING, result); \
std::move(get_size_callback_).Run(net::OK, size); \
EXPECT_EQ(net::OK, callback.GetResult(result)); \
EXPECT_TRUE(chunked_upload_stream->IsEOF()); \
}
#define WRITE_DATA_SYNC(write_pipe, str) \
{ \
std::string data(str); \
uint32_t num_size = data.size(); \
EXPECT_EQ(write_pipe->WriteData((void*)data.c_str(), &num_size, \
MOJO_WRITE_DATA_FLAG_NONE), \
MOJO_RESULT_OK); \
EXPECT_EQ(num_size, data.size()); \
}
TEST_F(ChunkedDataPipeUploadDataStreamTest, CacheNotUsed) {
chunked_upload_stream_->EnableCache();
const std::string kData = "1234567890";
WRITE_DATA_SYNC(write_pipe_, kData);
auto io_buffer = base::MakeRefCounted<net::IOBufferWithSize>(7);
EXPECT_READ(chunked_upload_stream_, io_buffer, "1234567");
EXPECT_FALSE(chunked_upload_stream_->IsEOF());
EXPECT_READ(chunked_upload_stream_, io_buffer, "890");
EXPECT_FALSE(chunked_upload_stream_->IsEOF());
EXPECT_EOF(chunked_upload_stream_, kData.size());
}
TEST_F(ChunkedDataPipeUploadDataStreamTest, CacheEnableBeforeInit1) {
CreateChunkedUploadStream();
chunked_upload_stream_->EnableCache();
InitChunkedUploadStream();
auto io_buffer = base::MakeRefCounted<net::IOBufferWithSize>(7);
int result = chunked_upload_stream_->Read(io_buffer.get(), io_buffer->size(),
NoCallback());
EXPECT_EQ(result, net::ERR_IO_PENDING);
// Destroy the DataPipeGetter pipe, which is the pipe used for
// GetSizeCallback.
chunked_data_pipe_getter_->ClosePipe();
}
TEST_F(ChunkedDataPipeUploadDataStreamTest, CacheEnableBeforeInit2) {
CreateChunkedUploadStream();
chunked_upload_stream_->EnableCache();
InitChunkedUploadStream();
WRITE_DATA_SYNC(write_pipe_, "1234567890");
auto io_buffer = base::MakeRefCounted<net::IOBufferWithSize>(7);
EXPECT_READ(chunked_upload_stream_, io_buffer, "1234567");
EXPECT_FALSE(chunked_upload_stream_->IsEOF());
EXPECT_EQ(chunked_upload_stream_->Init(NoCallback(), net::NetLogWithSource()),
net::OK);
EXPECT_READ(chunked_upload_stream_, io_buffer, "1234567");
EXPECT_READ(chunked_upload_stream_, io_buffer, "890");
EXPECT_FALSE(chunked_upload_stream_->IsEOF());
EXPECT_EOF(chunked_upload_stream_, 10);
}
TEST_F(ChunkedDataPipeUploadDataStreamTest, CacheRead) {
chunked_upload_stream_->EnableCache();
WRITE_DATA_SYNC(write_pipe_, "1234567890");
auto io_buffer = base::MakeRefCounted<net::IOBufferWithSize>(7);
EXPECT_READ(chunked_upload_stream_, io_buffer, "1234567");
EXPECT_FALSE(chunked_upload_stream_->IsEOF());
EXPECT_EQ(chunked_upload_stream_->Init(NoCallback(), net::NetLogWithSource()),
net::OK);
EXPECT_READ(chunked_upload_stream_, io_buffer, "1234567");
EXPECT_READ(chunked_upload_stream_, io_buffer, "890");
EXPECT_FALSE(chunked_upload_stream_->IsEOF());
EXPECT_EOF(chunked_upload_stream_, 10);
}
TEST_F(ChunkedDataPipeUploadDataStreamTest, CacheOverWindowOnce) {
const size_t kMaxSize = 4u;
chunked_upload_stream_->EnableCache(kMaxSize);
WRITE_DATA_SYNC(write_pipe_, "1234567890");
auto io_buffer = base::MakeRefCounted<net::IOBufferWithSize>(7);
EXPECT_READ(chunked_upload_stream_, io_buffer, "1234567");
EXPECT_FALSE(chunked_upload_stream_->IsEOF());
EXPECT_EQ(chunked_upload_stream_->Init(NoCallback(), net::NetLogWithSource()),
net::OK);
EXPECT_READ(chunked_upload_stream_, io_buffer, "1234567");
EXPECT_READ(chunked_upload_stream_, io_buffer, "890");
EXPECT_FALSE(chunked_upload_stream_->IsEOF());
EXPECT_EOF(chunked_upload_stream_, 10);
}
TEST_F(ChunkedDataPipeUploadDataStreamTest, CacheOverWindowTwice) {
const size_t kMaxSize = 4u;
chunked_upload_stream_->EnableCache(kMaxSize);
WRITE_DATA_SYNC(write_pipe_, "1234567890");
auto io_buffer = base::MakeRefCounted<net::IOBufferWithSize>(7);
EXPECT_READ(chunked_upload_stream_, io_buffer, "1234567");
EXPECT_READ(chunked_upload_stream_, io_buffer, "890");
int result =
chunked_upload_stream_->Init(NoCallback(), net::NetLogWithSource());
EXPECT_EQ(net::ERR_FAILED, result);
// Destroy the DataPipeGetter pipe, which is the pipe used for
// GetSizeCallback.
chunked_data_pipe_getter_->ClosePipe();
}
TEST_F(ChunkedDataPipeUploadDataStreamTest, CacheInitBeforeRead) {
chunked_upload_stream_->EnableCache();
WRITE_DATA_SYNC(write_pipe_, "1234567890");
auto io_buffer = base::MakeRefCounted<net::IOBufferWithSize>(7);
EXPECT_EQ(chunked_upload_stream_->Init(NoCallback(), net::NetLogWithSource()),
net::OK);
EXPECT_READ(chunked_upload_stream_, io_buffer, "1234567");
EXPECT_READ(chunked_upload_stream_, io_buffer, "890");
EXPECT_FALSE(chunked_upload_stream_->IsEOF());
EXPECT_EOF(chunked_upload_stream_, 10);
}
TEST_F(ChunkedDataPipeUploadDataStreamTest, CacheInitWhileRead) {
chunked_upload_stream_->EnableCache();
WRITE_DATA_SYNC(write_pipe_, "1234567890");
auto io_buffer = base::MakeRefCounted<net::IOBufferWithSize>(7);
EXPECT_READ(chunked_upload_stream_, io_buffer, "1234567");
io_buffer = base::MakeRefCounted<net::IOBufferWithSize>(3);
EXPECT_EQ(chunked_upload_stream_->Init(NoCallback(), net::NetLogWithSource()),
net::OK);
EXPECT_READ(chunked_upload_stream_, io_buffer, "123");
EXPECT_READ(chunked_upload_stream_, io_buffer, "456");
EXPECT_FALSE(chunked_upload_stream_->IsEOF());
// Re-init in the middle of reading from the cache
EXPECT_EQ(chunked_upload_stream_->Init(NoCallback(), net::NetLogWithSource()),
net::OK);
EXPECT_READ(chunked_upload_stream_, io_buffer, "123");
EXPECT_READ(chunked_upload_stream_, io_buffer, "456");
EXPECT_READ(chunked_upload_stream_, io_buffer, "7");
EXPECT_FALSE(chunked_upload_stream_->IsEOF());
// Re-init exactly after reading the last cached bit.
EXPECT_EQ(chunked_upload_stream_->Init(NoCallback(), net::NetLogWithSource()),
net::OK);
EXPECT_READ(chunked_upload_stream_, io_buffer, "123");
EXPECT_READ(chunked_upload_stream_, io_buffer, "456");
EXPECT_READ(chunked_upload_stream_, io_buffer, "7");
EXPECT_READ(chunked_upload_stream_, io_buffer, "890");
EXPECT_FALSE(chunked_upload_stream_->IsEOF());
// Reading "890" over the first cache should append "890" to the cache.
io_buffer = base::MakeRefCounted<net::IOBufferWithSize>(7);
EXPECT_EQ(chunked_upload_stream_->Init(NoCallback(), net::NetLogWithSource()),
net::OK);
EXPECT_READ(chunked_upload_stream_, io_buffer, "1234567");
EXPECT_READ(chunked_upload_stream_, io_buffer, "890");
EXPECT_FALSE(chunked_upload_stream_->IsEOF());
EXPECT_EOF(chunked_upload_stream_, 10);
}
TEST_F(ChunkedDataPipeUploadDataStreamTest, CacheReadAppendDataBeforeInit) {
chunked_upload_stream_->EnableCache();
WRITE_DATA_SYNC(write_pipe_, "1234567890");
auto io_buffer = base::MakeRefCounted<net::IOBufferWithSize>(7);
EXPECT_READ(chunked_upload_stream_, io_buffer, "1234567");
EXPECT_READ(chunked_upload_stream_, io_buffer, "890");
EXPECT_FALSE(chunked_upload_stream_->IsEOF());
net::TestCompletionCallback callback;
int result = chunked_upload_stream_->Read(io_buffer.get(), io_buffer->size(),
callback.callback());
EXPECT_EQ(net::ERR_IO_PENDING, result);
WRITE_DATA_SYNC(write_pipe_, "abc");
EXPECT_EQ(chunked_upload_stream_->Init(NoCallback(), net::NetLogWithSource()),
net::OK);
// Wait mojo.
base::RunLoop().RunUntilIdle();
// We should not receive the second mojo data.
EXPECT_FALSE(callback.have_result());
EXPECT_READ(chunked_upload_stream_, io_buffer, "1234567");
EXPECT_READ(chunked_upload_stream_, io_buffer, "890");
EXPECT_READ(chunked_upload_stream_, io_buffer, "abc");
EXPECT_EOF(chunked_upload_stream_, 13);
}
TEST_F(ChunkedDataPipeUploadDataStreamTest, CacheReadAppendDataAfterInit) {
chunked_upload_stream_->EnableCache();
WRITE_DATA_SYNC(write_pipe_, "1234567890");
auto io_buffer = base::MakeRefCounted<net::IOBufferWithSize>(7);
EXPECT_READ(chunked_upload_stream_, io_buffer, "1234567");
EXPECT_READ(chunked_upload_stream_, io_buffer, "890");
EXPECT_FALSE(chunked_upload_stream_->IsEOF());
net::TestCompletionCallback callback;
int result = chunked_upload_stream_->Read(io_buffer.get(), io_buffer->size(),
callback.callback());
EXPECT_EQ(net::ERR_IO_PENDING, result);
EXPECT_EQ(chunked_upload_stream_->Init(NoCallback(), net::NetLogWithSource()),
net::OK);
WRITE_DATA_SYNC(write_pipe_, "abc");
// Wait mojo.
base::RunLoop().RunUntilIdle();
// We should not receive the second mojo data.
EXPECT_FALSE(callback.have_result());
EXPECT_READ(chunked_upload_stream_, io_buffer, "1234567");
EXPECT_READ(chunked_upload_stream_, io_buffer, "890");
EXPECT_READ(chunked_upload_stream_, io_buffer, "abc");
EXPECT_EOF(chunked_upload_stream_, 13);
}
TEST_F(ChunkedDataPipeUploadDataStreamTest, CacheReadAppendDataDuringRead) {
chunked_upload_stream_->EnableCache();
WRITE_DATA_SYNC(write_pipe_, "1234567890");
auto io_buffer = base::MakeRefCounted<net::IOBufferWithSize>(7);
EXPECT_READ(chunked_upload_stream_, io_buffer, "1234567");
EXPECT_READ(chunked_upload_stream_, io_buffer, "890");
EXPECT_FALSE(chunked_upload_stream_->IsEOF());
net::TestCompletionCallback callback;
int result = chunked_upload_stream_->Read(io_buffer.get(), io_buffer->size(),
callback.callback());
EXPECT_EQ(net::ERR_IO_PENDING, result);
EXPECT_EQ(chunked_upload_stream_->Init(NoCallback(), net::NetLogWithSource()),
net::OK);
// We should not receive the second mojo data.
EXPECT_FALSE(callback.have_result());
EXPECT_READ(chunked_upload_stream_, io_buffer, "1234567");
WRITE_DATA_SYNC(write_pipe_, "abc");
// Wait mojo.
base::RunLoop().RunUntilIdle();
EXPECT_READ(chunked_upload_stream_, io_buffer, "890");
EXPECT_READ(chunked_upload_stream_, io_buffer, "abc");
EXPECT_EOF(chunked_upload_stream_, 13);
}
} // namespace
} // namespace network
| 17,164 |
2,151 | <gh_stars>1000+
// Copyright (c) 2013 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 UI_VIEWS_ACCESSIBILITY_NATIVE_VIEW_ACCESSIBILITY_BASE_H_
#define UI_VIEWS_ACCESSIBILITY_NATIVE_VIEW_ACCESSIBILITY_BASE_H_
#include <memory>
#include "base/macros.h"
#include "build/build_config.h"
#include "ui/accessibility/ax_action_data.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/accessibility/ax_tree_data.h"
#include "ui/accessibility/platform/ax_platform_node.h"
#include "ui/accessibility/platform/ax_platform_node_delegate.h"
#include "ui/accessibility/platform/ax_unique_id.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/views/accessibility/view_accessibility.h"
#include "ui/views/views_export.h"
#include "ui/views/widget/widget_observer.h"
namespace views {
class View;
class Widget;
// Shared base class for platforms that require an implementation of
// NativeViewAccessibility to interface with the native accessibility toolkit.
// This class owns the AXPlatformNode, which implements those native APIs.
class VIEWS_EXPORT NativeViewAccessibilityBase
: public ViewAccessibility,
public ui::AXPlatformNodeDelegate {
public:
~NativeViewAccessibilityBase() override;
// ViewAccessibility:
gfx::NativeViewAccessible GetNativeObject() override;
void NotifyAccessibilityEvent(ax::mojom::Event event_type) override;
void OnAutofillShown() override;
void OnAutofillHidden() override;
// ui::AXPlatformNodeDelegate
const ui::AXNodeData& GetData() const override;
const ui::AXTreeData& GetTreeData() const override;
int GetChildCount() override;
gfx::NativeViewAccessible ChildAtIndex(int index) override;
gfx::NativeWindow GetTopLevelWidget() override;
gfx::NativeViewAccessible GetParent() override;
gfx::Rect GetClippedScreenBoundsRect() const override;
gfx::Rect GetUnclippedScreenBoundsRect() const override;
gfx::NativeViewAccessible HitTestSync(int x, int y) override;
gfx::NativeViewAccessible GetFocus() override;
ui::AXPlatformNode* GetFromNodeID(int32_t id) override;
int GetIndexInParent() const override;
gfx::AcceleratedWidget GetTargetForNativeAccessibilityEvent() override;
int GetTableRowCount() const override;
int GetTableColCount() const override;
std::vector<int32_t> GetColHeaderNodeIds(int32_t col_index) const override;
std::vector<int32_t> GetRowHeaderNodeIds(int32_t row_index) const override;
int32_t GetCellId(int32_t row_index, int32_t col_index) const override;
int32_t CellIdToIndex(int32_t cell_id) const override;
int32_t CellIndexToId(int32_t cell_index) const override;
bool AccessibilityPerformAction(const ui::AXActionData& data) override;
bool ShouldIgnoreHoveredStateForTesting() override;
bool IsOffscreen() const override;
const ui::AXUniqueId& GetUniqueId()
const override; // Also in ViewAccessibility
std::set<int32_t> GetReverseRelations(ax::mojom::IntAttribute attr,
int32_t dst_id) override;
std::set<int32_t> GetReverseRelations(ax::mojom::IntListAttribute attr,
int32_t dst_id) override;
protected:
explicit NativeViewAccessibilityBase(View* view);
private:
void PopulateChildWidgetVector(std::vector<Widget*>* result_child_widgets);
// We own this, but it is reference-counted on some platforms so we can't use
// a scoped_ptr. It is dereferenced in the destructor.
ui::AXPlatformNode* ax_node_;
mutable ui::AXNodeData data_;
// This allows UI popups like autofill to act as if they are focused in the
// exposed platform accessibility API, even though true focus remains in
// underlying content.
static int32_t fake_focus_view_id_;
DISALLOW_COPY_AND_ASSIGN(NativeViewAccessibilityBase);
};
} // namespace views
#endif // UI_VIEWS_ACCESSIBILITY_NATIVE_VIEW_ACCESSIBILITY_BASE_H_
| 1,335 |
6,240 | <reponame>Chen188/chalice<filename>tests/testlinter.py
from pylint.checkers import BaseChecker
from pylint.interfaces import IAstroidChecker
from astroid.exceptions import InferenceError
def register(linter):
linter.register_checker(PatchChecker(linter))
linter.register_checker(MocksUseSpecArg(linter))
class PatchChecker(BaseChecker):
__implements__ = (IAstroidChecker,)
name = 'patching-banned'
msgs = {
'C9999': ('Use of mock.patch is not allowed',
'patch-call',
'Use of mock.patch not allowed')
}
patch_pytype = 'mock.mock._patch'
def visit_call(self, node):
try:
for inferred_type in node.infer():
if inferred_type.pytype() == self.patch_pytype:
self.add_message('patch-call', node=node)
except InferenceError:
# It's ok if we can't work out what type the function
# call is.
pass
class MocksUseSpecArg(BaseChecker):
__implements__ = (IAstroidChecker,)
name = 'mocks-use-spec'
msgs = {
'C9998': ('mock.Mock() must provide "spec=" argument',
'mock-missing-spec',
'mock.Mock() must provide "spec=" argument')
}
mock_pytype = 'mock.mock.Mock'
required_kwarg = 'spec'
def visit_call(self, node):
try:
for inferred_type in node.infer():
if inferred_type.pytype() == self.mock_pytype:
self._verify_spec_arg_provided(node)
except InferenceError:
pass
def _verify_spec_arg_provided(self, node):
if not node.keywords:
self.add_message('mock-missing-spec', node=node)
return
kwargs = [kwarg.arg for kwarg in node.keywords]
if self.required_kwarg not in kwargs:
self.add_message('mock-missing-spec', node=node)
| 893 |
14,668 | <reponame>zealoussnow/chromium
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/predictors/network_hints_handler_impl.h"
#include "base/memory/ptr_util.h"
#include "chrome/browser/predictors/loading_predictor.h"
#include "chrome/browser/predictors/loading_predictor_factory.h"
#include "chrome/browser/predictors/preconnect_manager.h"
#include "chrome/browser/profiles/profile.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "mojo/public/cpp/bindings/self_owned_receiver.h"
#include "net/base/isolation_info.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
namespace predictors {
namespace {
// Preconnects can be received from the renderer before commit messages, so
// need to use the key from the pending navigation, and not the committed
// navigation, unlike other consumers. This does mean on navigating away from a
// site, preconnect is more likely to incorrectly use the NetworkIsolationKey of
// the previous commit.
net::NetworkIsolationKey GetPendingNetworkIsolationKey(
content::RenderFrameHost* render_frame_host) {
return render_frame_host->GetPendingIsolationInfoForSubresources()
.network_isolation_key();
}
} // namespace
NetworkHintsHandlerImpl::~NetworkHintsHandlerImpl() = default;
// static
void NetworkHintsHandlerImpl::Create(
content::RenderFrameHost* frame_host,
mojo::PendingReceiver<network_hints::mojom::NetworkHintsHandler> receiver) {
mojo::MakeSelfOwnedReceiver(
base::WrapUnique(new NetworkHintsHandlerImpl(frame_host)),
std::move(receiver));
}
void NetworkHintsHandlerImpl::PrefetchDNS(
const std::vector<std::string>& names) {
if (!preconnect_manager_)
return;
content::RenderFrameHost* render_frame_host =
content::RenderFrameHost::FromID(render_process_id_, render_frame_id_);
if (!render_frame_host)
return;
preconnect_manager_->StartPreresolveHosts(
names, GetPendingNetworkIsolationKey(render_frame_host));
}
void NetworkHintsHandlerImpl::Preconnect(const GURL& url,
bool allow_credentials) {
if (!preconnect_manager_)
return;
if (!url.is_valid() || !url.has_host() || !url.has_scheme() ||
!url.SchemeIsHTTPOrHTTPS()) {
return;
}
// TODO(mmenke): Think about enabling cross-site preconnects, though that
// will result in at least some cross-site information leakage.
content::RenderFrameHost* render_frame_host =
content::RenderFrameHost::FromID(render_process_id_, render_frame_id_);
if (!render_frame_host)
return;
preconnect_manager_->StartPreconnectUrl(
url, allow_credentials, GetPendingNetworkIsolationKey(render_frame_host));
}
NetworkHintsHandlerImpl::NetworkHintsHandlerImpl(
content::RenderFrameHost* frame_host)
: render_process_id_(frame_host->GetProcess()->GetID()),
render_frame_id_(frame_host->GetRoutingID()) {
// Get the PreconnectManager for this process.
auto* render_process_host = frame_host->GetProcess();
auto* profile =
Profile::FromBrowserContext(render_process_host->GetBrowserContext());
auto* loading_predictor =
predictors::LoadingPredictorFactory::GetForProfile(profile);
if (loading_predictor && loading_predictor->preconnect_manager())
preconnect_manager_ = loading_predictor->preconnect_manager()->GetWeakPtr();
}
} // namespace predictors
| 1,192 |
13,006 | /*******************************************************************************
* Copyright (c) 2015-2019 Skymind, Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
package org.nd4j.linalg.api.ops.impl.loss.bp;
import org.nd4j.autodiff.loss.LossReduce;
import org.nd4j.autodiff.samediff.SDVariable;
import org.nd4j.autodiff.samediff.SameDiff;
import org.nd4j.common.base.Preconditions;
/**
* Hinge loss
*
* @author <NAME>
*/
public class HuberLossBp extends BaseLossBp {
private double delta;
public HuberLossBp(SameDiff sameDiff, LossReduce lossReduce, SDVariable predictions, SDVariable weights, SDVariable labels, double delta){
super(sameDiff, lossReduce, predictions, weights, labels);
Preconditions.checkState(delta >= 0.0, "Delta must be >= 0.0. Got: %s", delta);
this.delta = delta;
tArguments.add(delta);
}
public HuberLossBp(){ }
@Override
public String opName() {
return "huber_loss_grad";
}
}
| 497 |
1,706 | <reponame>bjorn3/mrustc<gh_stars>1000+
/*
* MRustC - Rust Compiler
* - By <NAME> (Mutabah/thePowersGang)
*
* macro_rules/macro_rules.hpp
* - Macros by example - `macro_rules!`
*/
#ifndef MACROS_HPP_INCLUDED
#define MACROS_HPP_INCLUDED
#include "parse/lex.hpp"
#include "parse/tokentree.hpp"
#include <common.hpp>
#include <map>
#include <memory>
#include <cstring>
#include "macro_rules_ptr.hpp"
#include <set>
class MacroExpander;
class SimplePatEnt;
TAGGED_UNION(MacroExpansionEnt, Token,
// TODO: have a "raw" stream instead of just tokens
(Token, Token),
// TODO: Have a flag on `NamedValue` that indicates that it is the only/last usage of this particular value (at this level)
// NOTE: This is a 2:30 bitfield - with the high range indicating $crate
(NamedValue, unsigned int),
(Loop, struct {
/// Contained entries
::std::vector< MacroExpansionEnt> entries;
/// Token used to join iterations
Token joiner;
/// List of loop indexes that control this loop
::std::set<unsigned int> controlling_input_loops;
})
);
extern ::std::ostream& operator<<(::std::ostream& os, const MacroExpansionEnt& x);
/// Matching pattern entry
struct MacroPatEnt
{
Span sp;
RcString name;
unsigned int name_index = 0;
// TODO: Include a point span for the token?
Token tok;
::std::vector<MacroPatEnt> subpats;
enum Type {
PAT_TOKEN, // A token
PAT_LOOP, // $() Enables use of subpats
PAT_TT, // :tt
PAT_PAT, // :pat
PAT_IDENT,
PAT_PATH,
PAT_TYPE,
PAT_EXPR,
PAT_STMT,
PAT_BLOCK,
PAT_META,
PAT_ITEM, // :item
PAT_VIS,
PAT_LIFETIME,
PAT_LITERAL,
} type;
MacroPatEnt():
tok(TOK_NULL),
type(PAT_TOKEN)
{
}
// Literal token
MacroPatEnt(Span sp, Token tok):
sp(mv$(sp)),
tok( mv$(tok) ),
type(PAT_TOKEN)
{
}
// Variable reference
MacroPatEnt(Span sp, RcString name, unsigned int name_index, Type type):
sp(mv$(sp)),
name( mv$(name) ),
name_index( name_index ),
tok(),
type(type)
{
}
// Loop/optional
MacroPatEnt(Span sp, Token sep, const char* op, unsigned index, ::std::vector<MacroPatEnt> ents):
sp(mv$(sp)),
name( op ),
name_index(index),
tok( mv$(sep) ),
subpats( move(ents) ),
type(PAT_LOOP)
{
}
friend ::std::ostream& operator<<(::std::ostream& os, const MacroPatEnt& x);
friend ::std::ostream& operator<<(::std::ostream& os, const MacroPatEnt::Type& x);
};
struct SimplePatIfCheck
{
MacroPatEnt::Type ty; // If PAT_TOKEN, token is checked
Token tok;
bool operator==(const SimplePatIfCheck& x) const { return this->ty == x.ty && this->tok == x.tok; }
friend ::std::ostream& operator<<(::std::ostream& os, const SimplePatIfCheck& x) {
os << x.ty;
if(x.ty == MacroPatEnt::PAT_TOKEN)
os << ":" << x.tok;
return os;
}
};
/// Simple pattern entry for macro_rules! arm patterns
TAGGED_UNION( SimplePatEnt, End,
// End of the pattern stream (expects EOF, and terminates the match process)
(End, struct{}),
// Start a loop (pushes a zero count to the loop stack)
(LoopStart, struct { unsigned index; }),
// Increment loop iteration counter
(LoopNext, struct { /*unsigned index;*/ }),
// Pop from the loop stack
(LoopEnd, struct { /*unsigned index;*/ }),
// Jump to a new point of execution
(Jump, struct {
size_t jump_target;
}),
// Expect a specific token, erroring/failing the arm if nt met
(ExpectTok, Token),
// Expect a pattern match
(ExpectPat, struct {
MacroPatEnt::Type type;
unsigned int idx;
}),
// Compare the head of the input stream and poke the pattern stream
(If, struct {
bool is_equal;
size_t jump_target;
::std::vector<SimplePatIfCheck> ents;
})
);
extern::std::ostream& operator<<(::std::ostream& os, const SimplePatEnt& x);
/// An expansion arm within a macro_rules! blcok
struct MacroRulesArm
{
/// Names for the parameters
::std::vector<RcString> m_param_names;
/// Patterns
::std::vector<SimplePatEnt> m_pattern;
/// Rule contents
::std::vector<MacroExpansionEnt> m_contents;
~MacroRulesArm();
MacroRulesArm()
{}
MacroRulesArm(::std::vector<SimplePatEnt> pattern, ::std::vector<MacroExpansionEnt> contents):
m_pattern( mv$(pattern) ),
m_contents( mv$(contents) )
{}
MacroRulesArm(const MacroRulesArm&) = delete;
MacroRulesArm& operator=(const MacroRulesArm&) = delete;
MacroRulesArm(MacroRulesArm&&) = default;
MacroRulesArm& operator=(MacroRulesArm&&) = default;
};
/// A sigle 'macro_rules!' block
class MacroRules
{
public:
/// Marks if this macro should be exported from the defining crate
bool m_exported = false;
/// Crate that defined this macro
/// - Populated on deserialise if not already set
RcString m_source_crate;
Ident::Hygiene m_hygiene;
/// Expansion rules
::std::vector<MacroRulesArm> m_rules;
MacroRules()
{
}
virtual ~MacroRules();
MacroRules(MacroRules&&) = default;
};
extern ::std::unique_ptr<TokenStream> Macro_InvokeRules(const char *name, const MacroRules& rules, const Span& sp, TokenTree input, const AST::Crate& crate, AST::Module& mod);
/// Parse a full `macro_rules` block
extern MacroRulesPtr Parse_MacroRules(TokenStream& lex);
/// Parse a single-arm `macro` item ( `macro foo($name:ident) { $name }`)
extern MacroRulesPtr Parse_MacroRulesSingleArm(TokenStream& lex);
#endif // MACROS_HPP_INCLUDED
| 2,465 |
6,098 | <filename>h2o-py/tests/testdir_parser/pyunit_NOFEATURE_orc_parser.py
from builtins import str
import sys
sys.path.insert(1,"../../")
import h2o
from tests import pyunit_utils
from random import randint
"""
This test takes all orc files collected by <NAME> and try to parse them into H2O frames.
Due to test duration limitation, we do not parse all the files. Instead, we randomly
choose about 30% of the files and parse them into H2O frames. If all pareses are successful,
the test pass and else it fails.
"""
def orc_parser_test():
allOrcFiles = ["smalldata/parser/orc/TestOrcFile.columnProjection.orc",
"smalldata/parser/orc/bigint_single_col.orc",
"smalldata/parser/orc/TestOrcFile.emptyFile.orc",
"smalldata/parser/orc/bool_single_col.orc",
"smalldata/parser/orc/demo-11-zlib.orc",
"smalldata/parser/orc/TestOrcFile.testDate1900.orc",
"smalldata/parser/orc/demo-12-zlib.orc",
"smalldata/parser/orc/TestOrcFile.testDate2038.orc",
"smalldata/parser/orc/double_single_col.orc",
"smalldata/parser/orc/TestOrcFile.testMemoryManagementV11.orc",
"smalldata/parser/orc/float_single_col.orc",
"smalldata/parser/orc/TestOrcFile.testMemoryManagementV12.orc",
"smalldata/parser/orc/int_single_col.orc",
"smalldata/parser/orc/TestOrcFile.testPredicatePushdown.orc",
"smalldata/parser/orc/nulls-at-end-snappy.orc",
"smalldata/parser/orc/TestOrcFile.testSnappy.orc",
"smalldata/parser/orc/orc_split_elim.orc",
"smalldata/parser/orc/TestOrcFile.testStringAndBinaryStatistics.orc",
"smalldata/parser/orc/TestOrcFile.testStripeLevelStats.orc",
"smalldata/parser/orc/smallint_single_col.orc",
"smalldata/parser/orc/string_single_col.orc",
"smalldata/parser/orc/tinyint_single_col.orc",
"smalldata/parser/orc/TestOrcFile.testWithoutIndex.orc"]
for fIndex in range(len(allOrcFiles)):
#Test tab seperated files by giving separator argument
tab_test = h2o.import_file(path=pyunit_utils.locate(allOrcFiles[fIndex]))
if __name__ == "__main__":
pyunit_utils.standalone_test(orc_parser_test)
else:
orc_parser_test()
| 898 |
3,296 | #include "case.h"
#include "ccv_case.h"
#include "ccv_nnc_case.h"
#include <ccv.h>
#include <nnc/ccv_nnc.h>
#include <nnc/ccv_nnc_easy.h>
TEST_SETUP()
{
ccv_nnc_init();
}
TEST_CASE("index select a tensor")
{
float ap[] = {
1, 2,
2, 3,
3, 4,
};
ccv_nnc_tensor_t* const a = ccv_nnc_tensor_new(ap, CPU_TENSOR_NHWC(32F, 3, 2), 0);
int ip[] = {1, 1};
ccv_nnc_tensor_t* const indices = ccv_nnc_tensor_new(ip, CPU_TENSOR_NHWC(32S, 2), 0);
ccv_nnc_tensor_t* const b = ccv_nnc_tensor_new(0, CPU_TENSOR_NHWC(32F, 2, 2), 0);
ccv_nnc_cmd_exec(CMD_INDEX_SELECT_FORWARD(), ccv_nnc_no_hint, 0, TENSOR_LIST(a, indices), TENSOR_LIST(b), 0);
float btp[] = {
2, 3,
2, 3,
};
ccv_nnc_tensor_t const bt = ccv_nnc_tensor(btp, CPU_TENSOR_NHWC(32F, 2, 2), 0);
REQUIRE_TENSOR_EQ(b, &bt, "should be equal");
ccv_nnc_tensor_free(a);
ccv_nnc_tensor_free(indices);
ccv_nnc_tensor_free(b);
}
TEST_CASE("index select a 1d tensor")
{
float ap[] = {
1, 2, 3, 4, 5
};
ccv_nnc_tensor_t* const a = ccv_nnc_tensor_new(ap, CPU_TENSOR_NHWC(32F, 5), 0);
int ip[] = {3, 2, 4};
ccv_nnc_tensor_t* const indices = ccv_nnc_tensor_new(ip, CPU_TENSOR_NHWC(32S, 3), 0);
ccv_nnc_tensor_t* const b = ccv_nnc_tensor_new(0, CPU_TENSOR_NHWC(32F, 3), 0);
ccv_nnc_cmd_exec(CMD_INDEX_SELECT_FORWARD(), ccv_nnc_no_hint, 0, TENSOR_LIST(a, indices), TENSOR_LIST(b), 0);
float btp[] = {
4, 3, 5
};
ccv_nnc_tensor_t const bt = ccv_nnc_tensor(btp, CPU_TENSOR_NHWC(32F, 3), 0);
REQUIRE_TENSOR_EQ(b, &bt, "should be equal");
ccv_nnc_tensor_free(a);
ccv_nnc_tensor_free(indices);
ccv_nnc_tensor_free(b);
}
TEST_CASE("index select a tensor view")
{
float ap[] = {
1, 2, 3, 4,
2, 3, 4, 5,
3, 4, 5, 6,
};
ccv_nnc_tensor_t* const a = ccv_nnc_tensor_new(ap, CPU_TENSOR_NHWC(32F, 3, 4), 0);
ccv_nnc_tensor_view_t* const av = ccv_nnc_tensor_view_new(a, CPU_TENSOR_NHWC(32F, 3, 2), DIM_ALLOC(0, 1), DIM_ALLOC(3, 4));
int ip[] = {1, 1};
ccv_nnc_tensor_t* const indices = ccv_nnc_tensor_new(ip, CPU_TENSOR_NHWC(32S, 2), 0);
ccv_nnc_tensor_t* const b = ccv_nnc_tensor_new(0, CPU_TENSOR_NHWC(32F, 2, 4), 0);
memset(b->data.f32, 0, 2 * 4 * sizeof(float));
ccv_nnc_tensor_view_t* const bv = ccv_nnc_tensor_view_new(b, CPU_TENSOR_NHWC(32F, 2, 2), DIM_ALLOC(0, 1), DIM_ALLOC(2, 4));
ccv_nnc_cmd_exec(CMD_INDEX_SELECT_FORWARD(), ccv_nnc_no_hint, 0, TENSOR_LIST((ccv_nnc_tensor_t*)av, indices), TENSOR_LIST((ccv_nnc_tensor_t*)bv), 0);
float btp[] = {
0, 3, 4, 0,
0, 3, 4, 0,
};
ccv_nnc_tensor_t const bt = ccv_nnc_tensor(btp, CPU_TENSOR_NHWC(32F, 2, 4), 0);
REQUIRE_TENSOR_EQ(b, &bt, "should be equal");
ccv_nnc_tensor_free(a);
ccv_nnc_tensor_view_free(av);
ccv_nnc_tensor_free(indices);
ccv_nnc_tensor_free(b);
ccv_nnc_tensor_view_free(bv);
}
TEST_CASE("backward index select a tensor")
{
float bp[] = {
1, 2,
2, 3,
};
ccv_nnc_tensor_t* const a = ccv_nnc_tensor_new(0, CPU_TENSOR_NHWC(32F, 3, 2), 0);
int ip[] = {1, 1};
ccv_nnc_tensor_t* const indices = ccv_nnc_tensor_new(ip, CPU_TENSOR_NHWC(32S, 2), 0);
ccv_nnc_tensor_t* const b = ccv_nnc_tensor_new(bp, CPU_TENSOR_NHWC(32F, 2, 2), 0);
ccv_nnc_cmd_exec(CMD_INDEX_SELECT_BACKWARD(), ccv_nnc_no_hint, 0, TENSOR_LIST(b, 0, indices), TENSOR_LIST(a), 0);
float atp[] = {
0, 0,
3, 5,
0, 0,
};
ccv_nnc_tensor_t const at = ccv_nnc_tensor(atp, CPU_TENSOR_NHWC(32F, 3, 2), 0);
REQUIRE_TENSOR_EQ(a, &at, "should be equal");
ccv_nnc_tensor_free(a);
ccv_nnc_tensor_free(indices);
ccv_nnc_tensor_free(b);
}
TEST_CASE("backward index select a 1d tensor")
{
float bp[] = {
4, 3, 5,
};
ccv_nnc_tensor_t* const a = ccv_nnc_tensor_new(0, CPU_TENSOR_NHWC(32F, 5), 0);
int ip[] = {3, 2, 4};
ccv_nnc_tensor_t* const indices = ccv_nnc_tensor_new(ip, CPU_TENSOR_NHWC(32S, 3), 0);
ccv_nnc_tensor_t* const b = ccv_nnc_tensor_new(bp, CPU_TENSOR_NHWC(32F, 3), 0);
ccv_nnc_cmd_exec(CMD_INDEX_SELECT_BACKWARD(), ccv_nnc_no_hint, 0, TENSOR_LIST(b, 0, indices), TENSOR_LIST(a), 0);
float atp[] = {
0, 0, 3, 4, 5
};
ccv_nnc_tensor_t const at = ccv_nnc_tensor(atp, CPU_TENSOR_NHWC(32F, 5), 0);
REQUIRE_TENSOR_EQ(a, &at, "should be equal");
ccv_nnc_tensor_free(a);
ccv_nnc_tensor_free(indices);
ccv_nnc_tensor_free(b);
}
TEST_CASE("backward index select a tensor view")
{
float bp[] = {
0, 3, 4, 0,
0, 1, 5, 0,
};
ccv_nnc_tensor_t* const a = ccv_nnc_tensor_new(0, CPU_TENSOR_NHWC(32F, 3, 4), 0);
int i;
for (i = 0; i < 3 * 4; i++)
a->data.f32[i] = i;
ccv_nnc_tensor_view_t* const av = ccv_nnc_tensor_view_new(a, CPU_TENSOR_NHWC(32F, 3, 2), DIM_ALLOC(0, 1), DIM_ALLOC(3, 4));
int ip[] = {1, 1};
ccv_nnc_tensor_t* const indices = ccv_nnc_tensor_new(ip, CPU_TENSOR_NHWC(32S, 2), 0);
ccv_nnc_tensor_t* const b = ccv_nnc_tensor_new(bp, CPU_TENSOR_NHWC(32F, 2, 4), 0);
ccv_nnc_tensor_view_t* const bv = ccv_nnc_tensor_view_new(b, CPU_TENSOR_NHWC(32F, 2, 2), DIM_ALLOC(0, 1), DIM_ALLOC(2, 4));
ccv_nnc_cmd_exec(CMD_INDEX_SELECT_BACKWARD(), ccv_nnc_no_hint, 0, TENSOR_LIST((ccv_nnc_tensor_t*)bv, 0, indices), TENSOR_LIST((ccv_nnc_tensor_t*)av), 0);
float atp[] = {
0, 0, 0, 3,
4, 4, 9, 7,
8, 0, 0, 11,
};
ccv_nnc_tensor_t const at = ccv_nnc_tensor(atp, CPU_TENSOR_NHWC(32F, 3, 4), 0);
REQUIRE_TENSOR_EQ(a, &at, "should be equal");
ccv_nnc_tensor_free(a);
ccv_nnc_tensor_view_free(av);
ccv_nnc_tensor_free(indices);
ccv_nnc_tensor_free(b);
ccv_nnc_tensor_view_free(bv);
}
#include "case_main.h"
| 2,944 |
575 | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/chrome_cleaner/os/task_scheduler.h"
#include <mstask.h>
#include <oleauto.h>
#include <security.h>
#include <taskschd.h>
#include <wrl/client.h>
#include <string>
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/logging.h"
#include "base/native_library.h"
#include "base/notreached.h"
#include "base/path_service.h"
#include "base/strings/strcat.h"
#include "base/strings/stringprintf.h"
#include "base/time/time.h"
#include "base/win/scoped_bstr.h"
#include "base/win/scoped_co_mem.h"
#include "base/win/scoped_handle.h"
#include "base/win/scoped_variant.h"
#include "base/win/windows_version.h"
#include "chrome/chrome_cleaner/constants/chrome_cleaner_switches.h"
#include "chrome/chrome_cleaner/os/file_path_sanitization.h"
namespace chrome_cleaner {
namespace {
// Names of the TaskSchedulerV2 libraries so we can pin them below.
const wchar_t kV2Library[] = L"taskschd.dll";
// Text for times used in the V2 API of the Task Scheduler.
const wchar_t kOneHourText[] = L"PT1H";
const wchar_t kSixHoursText[] = L"PT6H";
const wchar_t kZeroMinuteText[] = L"PT0M";
const wchar_t kFifteenMinutesText[] = L"PT15M";
const wchar_t kTwentyFourHoursText[] = L"PT24H";
// Most of the users with pending logs succeeds within 7 days, so no need to
// try for longer than that, especially for those who keep crashing.
const int kNumDaysBeforeExpiry = 7;
const size_t kNumDeleteTaskRetry = 3;
const size_t kDeleteRetryDelayInMs = 100;
// Return |timestamp| in the following string format YYYY-MM-DDTHH:MM:SS.
std::wstring GetTimestampString(const base::Time& timestamp) {
base::Time::Exploded exploded_time;
// The Z timezone info at the end of the string means UTC.
timestamp.UTCExplode(&exploded_time);
return base::StringPrintf(L"%04d-%02d-%02dT%02d:%02d:%02dZ",
exploded_time.year, exploded_time.month,
exploded_time.day_of_month, exploded_time.hour,
exploded_time.minute, exploded_time.second);
}
bool LocalSystemTimeToUTCFileTime(const SYSTEMTIME& system_time_local,
FILETIME* file_time_utc) {
DCHECK(file_time_utc);
SYSTEMTIME system_time_utc = {};
if (!::TzSpecificLocalTimeToSystemTime(nullptr, &system_time_local,
&system_time_utc) ||
!::SystemTimeToFileTime(&system_time_utc, file_time_utc)) {
PLOG(ERROR) << "Failed to convert local system time to UTC file time.";
return false;
}
return true;
}
bool UTCFileTimeToLocalSystemTime(const FILETIME& file_time_utc,
SYSTEMTIME* system_time_local) {
DCHECK(system_time_local);
SYSTEMTIME system_time_utc = {};
if (!::FileTimeToSystemTime(&file_time_utc, &system_time_utc) ||
!::SystemTimeToTzSpecificLocalTime(nullptr, &system_time_utc,
system_time_local)) {
PLOG(ERROR) << "Failed to convert file time to UTC local system.";
return false;
}
return true;
}
bool GetCurrentUser(base::win::ScopedBstr* user_name) {
DCHECK(user_name);
ULONG user_name_size = 256;
// Paranoia... ;-)
DCHECK_EQ(sizeof(OLECHAR), sizeof(WCHAR));
if (!::GetUserNameExW(
NameSamCompatible,
user_name->AllocateBytes(user_name_size * sizeof(OLECHAR)),
&user_name_size)) {
if (::GetLastError() != ERROR_MORE_DATA) {
PLOG(ERROR) << "GetUserNameEx failed.";
return false;
}
if (!::GetUserNameExW(
NameSamCompatible,
user_name->AllocateBytes(user_name_size * sizeof(OLECHAR)),
&user_name_size)) {
DCHECK_NE(static_cast<DWORD>(ERROR_MORE_DATA), ::GetLastError());
PLOG(ERROR) << "GetUserNameEx failed.";
return false;
}
}
return true;
}
void PinModule(const wchar_t* module_name) {
// Force the DLL to stay loaded until program termination. We have seen
// cases where it gets unloaded even though we still have references to
// the objects we just CoCreated.
base::NativeLibrary module_handle = nullptr;
if (!::GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_PIN, module_name,
&module_handle)) {
PLOG(ERROR) << "Failed to pin '" << module_name << "'.";
}
}
// Another version of the TaskScheduler class that uses the V2 API of the task
// scheduler for Vista+.
class TaskSchedulerV2 : public TaskScheduler {
public:
static bool Initialize() {
DCHECK(!task_service_);
DCHECK(!root_task_folder_);
HRESULT hr =
::CoCreateInstance(CLSID_TaskScheduler, nullptr, CLSCTX_INPROC_SERVER,
IID_PPV_ARGS(&task_service_));
if (FAILED(hr)) {
PLOG(ERROR) << "CreateInstance failed for CLSID_TaskScheduler. "
<< std::hex << hr;
return false;
}
hr = task_service_->Connect(base::win::ScopedVariant::kEmptyVariant,
base::win::ScopedVariant::kEmptyVariant,
base::win::ScopedVariant::kEmptyVariant,
base::win::ScopedVariant::kEmptyVariant);
if (FAILED(hr)) {
PLOG(ERROR) << "Failed to connect to task service. " << std::hex << hr;
return false;
}
hr = task_service_->GetFolder(base::win::ScopedBstr(L"\\").Get(),
&root_task_folder_);
if (FAILED(hr)) {
LOG(ERROR) << "Can't get task service folder. " << std::hex << hr;
return false;
}
PinModule(kV2Library);
return true;
}
static void Terminate() {
root_task_folder_.Reset();
task_service_.Reset();
}
TaskSchedulerV2() {
DCHECK(task_service_);
DCHECK(root_task_folder_);
}
// TaskScheduler overrides.
bool IsTaskRegistered(const wchar_t* task_name) override {
DCHECK(task_name);
if (!root_task_folder_)
return false;
return GetTask(task_name, nullptr);
}
bool GetNextTaskRunTime(const wchar_t* task_name,
base::Time* next_run_time) override {
DCHECK(task_name);
DCHECK(next_run_time);
if (!root_task_folder_)
return false;
Microsoft::WRL::ComPtr<IRegisteredTask> registered_task;
if (!GetTask(task_name, ®istered_task)) {
LOG(ERROR) << "Failed to get task named " << task_name;
return false;
}
// We unfortunately can't use get_NextRunTime because of a known bug which
// requires hotfix: http://support.microsoft.com/kb/2495489/en-us. So fetch
// one of the run times in the next day.
// Also, although it's not obvious from MSDN, IRegisteredTask::GetRunTimes
// expects local time.
SYSTEMTIME start_system_time = {};
GetLocalTime(&start_system_time);
base::Time tomorrow(base::Time::NowFromSystemTime() +
base::TimeDelta::FromDays(1));
SYSTEMTIME end_system_time = {};
if (!UTCFileTimeToLocalSystemTime(tomorrow.ToFileTime(), &end_system_time))
return false;
DWORD num_run_times = 1;
SYSTEMTIME* raw_run_times = nullptr;
HRESULT hr = registered_task->GetRunTimes(
&start_system_time, &end_system_time, &num_run_times, &raw_run_times);
if (FAILED(hr)) {
PLOG(ERROR) << "Failed to GetRunTimes, " << std::hex << hr;
return false;
}
if (num_run_times == 0) {
LOG(WARNING) << "No more run times?";
return false;
}
base::win::ScopedCoMem<SYSTEMTIME> run_times;
run_times.Reset(raw_run_times);
// Again, although unclear from MSDN, IRegisteredTask::GetRunTimes returns
// local times.
FILETIME file_time = {};
if (!LocalSystemTimeToUTCFileTime(run_times[0], &file_time))
return false;
*next_run_time = base::Time::FromFileTime(file_time);
return true;
}
bool SetTaskEnabled(const wchar_t* task_name, bool enabled) override {
DCHECK(task_name);
if (!root_task_folder_)
return false;
Microsoft::WRL::ComPtr<IRegisteredTask> registered_task;
if (!GetTask(task_name, ®istered_task)) {
LOG(ERROR) << "Failed to find the task " << task_name
<< " to enable/disable";
return false;
}
HRESULT hr;
hr = registered_task->put_Enabled(enabled ? VARIANT_TRUE : VARIANT_FALSE);
if (FAILED(hr)) {
PLOG(ERROR) << "Failed to set enabled status of task named " << task_name
<< ". " << std::hex << hr;
return false;
}
return true;
}
bool IsTaskEnabled(const wchar_t* task_name) override {
DCHECK(task_name);
if (!root_task_folder_)
return false;
Microsoft::WRL::ComPtr<IRegisteredTask> registered_task;
if (!GetTask(task_name, ®istered_task))
return false;
HRESULT hr;
VARIANT_BOOL is_enabled;
hr = registered_task->get_Enabled(&is_enabled);
if (FAILED(hr)) {
LOG(ERROR) << "Failed to get enabled status for task named " << task_name
<< ". " << std::hex << hr << ": "
<< logging::SystemErrorCodeToString(hr);
return false;
}
return is_enabled == VARIANT_TRUE;
}
bool GetTaskNameList(std::vector<std::wstring>* task_names) override {
DCHECK(task_names);
if (!root_task_folder_)
return false;
for (TaskIterator it(root_task_folder_.Get()); !it.done(); it.Next())
task_names->push_back(it.name());
return true;
}
bool GetTaskInfo(const wchar_t* task_name, TaskInfo* info) override {
DCHECK(task_name);
DCHECK(info);
if (!root_task_folder_)
return false;
Microsoft::WRL::ComPtr<IRegisteredTask> registered_task;
if (!GetTask(task_name, ®istered_task)) {
LOG(ERROR) << "Failed to get task named " << task_name;
return false;
}
// Collect information into internal storage to ensure that we start with
// a clean slate and don't return partial results on error.
TaskInfo info_storage;
HRESULT hr =
GetTaskDescription(registered_task.Get(), &info_storage.description);
if (FAILED(hr)) {
LOG(ERROR) << "Failed to get description for task '" << task_name << "'. "
<< std::hex << hr << ": "
<< logging::SystemErrorCodeToString(hr);
return false;
}
if (!GetTaskExecActions(registered_task.Get(),
&info_storage.exec_actions)) {
LOG(ERROR) << "Failed to get actions for task '" << task_name << "'";
return false;
}
hr = GetTaskLogonType(registered_task.Get(), &info_storage.logon_type);
if (FAILED(hr)) {
LOG(ERROR) << "Failed to get logon type for task '" << task_name << "'. "
<< std::hex << hr << ": "
<< logging::SystemErrorCodeToString(hr);
return false;
}
info_storage.name = task_name;
std::swap(*info, info_storage);
return true;
}
bool DeleteTask(const wchar_t* task_name) override {
DCHECK(task_name);
if (!root_task_folder_)
return false;
LOG(INFO) << "Delete Task '" << task_name << "'.";
HRESULT hr = root_task_folder_->DeleteTask(
base::win::ScopedBstr(task_name).Get(), 0);
// This can happen, e.g., while running tests, when the file system stresses
// quite a lot. Give it a few more chances to succeed.
size_t num_retries_left = kNumDeleteTaskRetry;
if (FAILED(hr)) {
while ((hr == HRESULT_FROM_WIN32(ERROR_TRANSACTION_NOT_ACTIVE) ||
hr == HRESULT_FROM_WIN32(ERROR_TRANSACTION_ALREADY_ABORTED)) &&
--num_retries_left && IsTaskRegistered(task_name)) {
LOG(WARNING) << "Retrying delete task because transaction not active, "
<< std::hex << hr << ".";
hr = root_task_folder_->DeleteTask(
base::win::ScopedBstr(task_name).Get(), 0);
::Sleep(kDeleteRetryDelayInMs);
}
if (!IsTaskRegistered(task_name))
hr = S_OK;
}
if (FAILED(hr) && hr != HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND)) {
PLOG(ERROR) << "Can't delete task. " << std::hex << hr;
return false;
}
DCHECK(!IsTaskRegistered(task_name));
return true;
}
bool RegisterTask(const wchar_t* task_name,
const wchar_t* task_description,
const base::CommandLine& run_command,
TriggerType trigger_type,
bool hidden) override {
DCHECK(task_name);
DCHECK(task_description);
if (!DeleteTask(task_name))
return false;
// Create the task definition object to create the task.
Microsoft::WRL::ComPtr<ITaskDefinition> task;
DCHECK(task_service_);
HRESULT hr = task_service_->NewTask(0, &task);
if (FAILED(hr)) {
PLOG(ERROR) << "Can't create new task. " << std::hex << hr;
return false;
}
base::win::ScopedBstr user_name;
if (!GetCurrentUser(&user_name))
return false;
if (trigger_type != TRIGGER_TYPE_NOW) {
// Allow the task to run elevated on startup.
Microsoft::WRL::ComPtr<IPrincipal> principal;
hr = task->get_Principal(&principal);
if (FAILED(hr)) {
PLOG(ERROR) << "Can't get principal. " << std::hex << hr;
return false;
}
hr = principal->put_RunLevel(TASK_RUNLEVEL_HIGHEST);
if (FAILED(hr)) {
PLOG(ERROR) << "Can't set highest run level. " << std::hex << hr;
return false;
}
hr = principal->put_UserId(user_name.Get());
if (FAILED(hr)) {
PLOG(ERROR) << "Can't put user id. " << std::hex << hr;
return false;
}
hr = principal->put_LogonType(TASK_LOGON_INTERACTIVE_TOKEN);
if (FAILED(hr)) {
PLOG(ERROR) << "Can't put logon type. " << std::hex << hr;
return false;
}
}
Microsoft::WRL::ComPtr<IRegistrationInfo> registration_info;
hr = task->get_RegistrationInfo(®istration_info);
if (FAILED(hr)) {
PLOG(ERROR) << "Can't get registration info. " << std::hex << hr;
return false;
}
hr = registration_info->put_Author(user_name.Get());
if (FAILED(hr)) {
PLOG(ERROR) << "Can't set registration info author. " << std::hex << hr;
return false;
}
base::win::ScopedBstr description(task_description);
hr = registration_info->put_Description(description.Get());
if (FAILED(hr)) {
PLOG(ERROR) << "Can't set description. " << std::hex << hr;
return false;
}
Microsoft::WRL::ComPtr<ITaskSettings> task_settings;
hr = task->get_Settings(&task_settings);
if (FAILED(hr)) {
PLOG(ERROR) << "Can't get task settings. " << std::hex << hr;
return false;
}
hr = task_settings->put_StartWhenAvailable(VARIANT_TRUE);
if (FAILED(hr)) {
PLOG(ERROR) << "Can't put 'StartWhenAvailable' to true. " << std::hex
<< hr;
return false;
}
// TODO(csharp): Find a way to only set this for log upload retry.
hr = task_settings->put_DeleteExpiredTaskAfter(
base::win::ScopedBstr(kZeroMinuteText).Get());
if (FAILED(hr)) {
PLOG(ERROR) << "Can't put 'DeleteExpiredTaskAfter'. " << std::hex << hr;
return false;
}
hr = task_settings->put_DisallowStartIfOnBatteries(VARIANT_FALSE);
if (FAILED(hr)) {
PLOG(ERROR) << "Can't put 'DisallowStartIfOnBatteries' to false. "
<< std::hex << hr;
return false;
}
hr = task_settings->put_StopIfGoingOnBatteries(VARIANT_FALSE);
if (FAILED(hr)) {
PLOG(ERROR) << "Can't put 'StopIfGoingOnBatteries' to false. " << std::hex
<< hr;
return false;
}
if (hidden) {
hr = task_settings->put_Hidden(VARIANT_TRUE);
if (FAILED(hr)) {
PLOG(ERROR) << "Can't put 'Hidden' to true. " << std::hex << hr;
return false;
}
}
Microsoft::WRL::ComPtr<ITriggerCollection> trigger_collection;
hr = task->get_Triggers(&trigger_collection);
if (FAILED(hr)) {
PLOG(ERROR) << "Can't get trigger collection. " << std::hex << hr;
return false;
}
TASK_TRIGGER_TYPE2 task_trigger_type = TASK_TRIGGER_EVENT;
base::win::ScopedBstr repetition_interval;
switch (trigger_type) {
case TRIGGER_TYPE_POST_REBOOT:
task_trigger_type = TASK_TRIGGER_LOGON;
break;
case TRIGGER_TYPE_NOW:
task_trigger_type = TASK_TRIGGER_REGISTRATION;
break;
case TRIGGER_TYPE_HOURLY:
case TRIGGER_TYPE_EVERY_SIX_HOURS:
task_trigger_type = TASK_TRIGGER_DAILY;
if (base::CommandLine::ForCurrentProcess()->HasSwitch(
kLogUploadRetryIntervalSwitch)) {
// String format: PT%lsM
const std::wstring interval_switch = base::StrCat(
{L"PT",
base::CommandLine::ForCurrentProcess()->GetSwitchValueNative(
kLogUploadRetryIntervalSwitch),
L"M"});
LOG(WARNING) << "Command line switch overriding retry interval to: "
<< interval_switch;
repetition_interval.Reset(::SysAllocString(interval_switch.c_str()));
} else if (trigger_type == TRIGGER_TYPE_EVERY_SIX_HOURS) {
repetition_interval.Reset(::SysAllocString(kSixHoursText));
} else {
DCHECK_EQ(TRIGGER_TYPE_HOURLY, trigger_type);
repetition_interval.Reset(::SysAllocString(kOneHourText));
}
break;
default:
NOTREACHED() << "Unknown TriggerType?";
}
Microsoft::WRL::ComPtr<ITrigger> trigger;
hr = trigger_collection->Create(task_trigger_type, &trigger);
if (FAILED(hr)) {
PLOG(ERROR) << "Can't create trigger of type " << task_trigger_type
<< ". " << std::hex << hr;
return false;
}
if (trigger_type == TRIGGER_TYPE_HOURLY ||
trigger_type == TRIGGER_TYPE_EVERY_SIX_HOURS) {
Microsoft::WRL::ComPtr<IDailyTrigger> daily_trigger;
hr = trigger.As(&daily_trigger);
if (FAILED(hr)) {
PLOG(ERROR) << "Can't Query for registration trigger. " << std::hex
<< hr;
return false;
}
hr = daily_trigger->put_DaysInterval(1);
if (FAILED(hr)) {
PLOG(ERROR) << "Can't put 'DaysInterval' to 1, " << std::hex << hr;
return false;
}
Microsoft::WRL::ComPtr<IRepetitionPattern> repetition_pattern;
hr = trigger->get_Repetition(&repetition_pattern);
if (FAILED(hr)) {
PLOG(ERROR) << "Can't get 'Repetition'. " << std::hex << hr;
return false;
}
// The duration is the time to keep repeating until the next daily
// trigger.
hr = repetition_pattern->put_Duration(
base::win::ScopedBstr(kTwentyFourHoursText).Get());
if (FAILED(hr)) {
PLOG(ERROR) << "Can't put 'Duration' to " << kTwentyFourHoursText
<< ". " << std::hex << hr;
return false;
}
hr = repetition_pattern->put_Interval(repetition_interval.Get());
if (FAILED(hr)) {
PLOG(ERROR) << "Can't put 'Interval' to " << repetition_interval.Get()
<< ". " << std::hex << hr;
return false;
}
// Start now.
base::Time now(base::Time::NowFromSystemTime());
base::win::ScopedBstr start_boundary(GetTimestampString(now));
hr = trigger->put_StartBoundary(start_boundary.Get());
if (FAILED(hr)) {
PLOG(ERROR) << "Can't put 'StartBoundary' to " << start_boundary.Get()
<< ". " << std::hex << hr;
return false;
}
}
if (trigger_type == TRIGGER_TYPE_POST_REBOOT) {
Microsoft::WRL::ComPtr<ILogonTrigger> logon_trigger;
hr = trigger.As(&logon_trigger);
if (FAILED(hr)) {
PLOG(ERROR) << "Can't query trigger for 'ILogonTrigger'. " << std::hex
<< hr;
return false;
}
hr = logon_trigger->put_Delay(
base::win::ScopedBstr(kFifteenMinutesText).Get());
if (FAILED(hr)) {
PLOG(ERROR) << "Can't put 'Delay'. " << std::hex << hr;
return false;
}
}
// None of the triggers should go beyond kNumDaysBeforeExpiry.
base::Time expiry_date(base::Time::NowFromSystemTime() +
base::TimeDelta::FromDays(kNumDaysBeforeExpiry));
base::win::ScopedBstr end_boundary(GetTimestampString(expiry_date));
hr = trigger->put_EndBoundary(end_boundary.Get());
if (FAILED(hr)) {
PLOG(ERROR) << "Can't put 'EndBoundary' to " << end_boundary.Get() << ". "
<< std::hex << hr;
return false;
}
Microsoft::WRL::ComPtr<IActionCollection> actions;
hr = task->get_Actions(&actions);
if (FAILED(hr)) {
PLOG(ERROR) << "Can't get actions collection. " << std::hex << hr;
return false;
}
Microsoft::WRL::ComPtr<IAction> action;
hr = actions->Create(TASK_ACTION_EXEC, &action);
if (FAILED(hr)) {
PLOG(ERROR) << "Can't create exec action. " << std::hex << hr;
return false;
}
Microsoft::WRL::ComPtr<IExecAction> exec_action;
hr = action.As(&exec_action);
if (FAILED(hr)) {
PLOG(ERROR) << "Can't query for exec action. " << std::hex << hr;
return false;
}
base::win::ScopedBstr path(run_command.GetProgram().value());
hr = exec_action->put_Path(path.Get());
if (FAILED(hr)) {
PLOG(ERROR) << "Can't set path of exec action. " << std::hex << hr;
return false;
}
base::win::ScopedBstr args(run_command.GetArgumentsString());
hr = exec_action->put_Arguments(args.Get());
if (FAILED(hr)) {
PLOG(ERROR) << "Can't set arguments of exec action. " << std::hex << hr;
return false;
}
Microsoft::WRL::ComPtr<IRegisteredTask> registered_task;
base::win::ScopedVariant user(user_name.Get());
DCHECK(root_task_folder_);
hr = root_task_folder_->RegisterTaskDefinition(
base::win::ScopedBstr(task_name).Get(), task.Get(), TASK_CREATE,
*user.AsInput(), // Not really input, but API expect non-const.
base::win::ScopedVariant::kEmptyVariant, TASK_LOGON_NONE,
base::win::ScopedVariant::kEmptyVariant, ®istered_task);
if (FAILED(hr)) {
LOG(ERROR) << "RegisterTaskDefinition failed. " << std::hex << hr << ": "
<< logging::SystemErrorCodeToString(hr);
return false;
}
DCHECK(IsTaskRegistered(task_name));
LOG(INFO) << "Successfully registered: "
<< SanitizeCommandLine(run_command);
return true;
}
private:
// Helper class that lets us iterate over all registered tasks.
class TaskIterator {
public:
explicit TaskIterator(ITaskFolder* task_folder) {
DCHECK(task_folder);
HRESULT hr = task_folder->GetTasks(TASK_ENUM_HIDDEN, &tasks_);
if (FAILED(hr)) {
PLOG(ERROR) << "Failed to get registered tasks from folder. "
<< std::hex << hr;
done_ = true;
return;
}
hr = tasks_->get_Count(&num_tasks_);
if (FAILED(hr)) {
PLOG(ERROR) << "Failed to get registered tasks count. " << std::hex
<< hr;
done_ = true;
return;
}
Next();
}
// Increment to the next valid item in the task list. Skip entries for
// which we cannot retrieve a name.
void Next() {
DCHECK(!done_);
task_.Reset();
name_.clear();
if (++task_index_ >= num_tasks_) {
done_ = true;
return;
}
// Note: get_Item uses 1 based indices.
HRESULT hr =
tasks_->get_Item(base::win::ScopedVariant(task_index_ + 1), &task_);
if (FAILED(hr)) {
PLOG(ERROR) << "Failed to get task at index: " << task_index_ << ". "
<< std::hex << hr;
Next();
return;
}
base::win::ScopedBstr task_name_bstr;
hr = task_->get_Name(task_name_bstr.Receive());
if (FAILED(hr)) {
PLOG(ERROR) << "Failed to get name at index: " << task_index_ << ". "
<< std::hex << hr;
Next();
return;
}
name_ = std::wstring(task_name_bstr.Get() ? task_name_bstr.Get() : L"");
}
// Detach the currently active task and pass ownership to the caller.
// After this method has been called, the -> operator must no longer be
// used.
IRegisteredTask* Detach() { return task_.Detach(); }
// Provide access to the current task.
IRegisteredTask* operator->() const {
IRegisteredTask* result = task_.Get();
DCHECK(result);
return result;
}
const std::wstring& name() const { return name_; }
bool done() const { return done_; }
private:
Microsoft::WRL::ComPtr<IRegisteredTaskCollection> tasks_;
Microsoft::WRL::ComPtr<IRegisteredTask> task_;
std::wstring name_;
long task_index_ = -1; // NOLINT, API requires a long.
long num_tasks_ = 0; // NOLINT, API requires a long.
bool done_ = false;
};
// Return the task with |task_name| and false if not found. |task| can be null
// when only interested in task's existence.
bool GetTask(const wchar_t* task_name, IRegisteredTask** task) {
for (TaskIterator it(root_task_folder_.Get()); !it.done(); it.Next()) {
if (::_wcsicmp(it.name().c_str(), task_name) == 0) {
if (task)
*task = it.Detach();
return true;
}
}
return false;
}
// Return the description of the task.
HRESULT GetTaskDescription(IRegisteredTask* task, std::wstring* description) {
DCHECK(task);
DCHECK(description);
base::win::ScopedBstr task_name_bstr;
HRESULT hr = task->get_Name(task_name_bstr.Receive());
std::wstring task_name =
std::wstring(task_name_bstr.Get() ? task_name_bstr.Get() : L"");
if (FAILED(hr)) {
LOG(ERROR) << "Failed to get task name";
}
Microsoft::WRL::ComPtr<ITaskDefinition> task_info;
hr = task->get_Definition(&task_info);
if (FAILED(hr)) {
LOG(ERROR) << "Failed to get definition for task, " << task_name << ": "
<< logging::SystemErrorCodeToString(hr);
return hr;
}
Microsoft::WRL::ComPtr<IRegistrationInfo> reg_info;
hr = task_info->get_RegistrationInfo(®_info);
if (FAILED(hr)) {
LOG(ERROR) << "Failed to get registration info, " << task_name << ": "
<< logging::SystemErrorCodeToString(hr);
return hr;
}
base::win::ScopedBstr raw_description;
hr = reg_info->get_Description(raw_description.Receive());
if (FAILED(hr)) {
LOG(ERROR) << "Failed to get description, " << task_name << ": "
<< logging::SystemErrorCodeToString(hr);
return hr;
}
*description =
std::wstring(raw_description.Get() ? raw_description.Get() : L"");
return ERROR_SUCCESS;
}
// Return all executable actions associated with the given task. Non-exec
// actions are silently ignored.
bool GetTaskExecActions(IRegisteredTask* task,
std::vector<TaskExecAction>* actions) {
DCHECK(task);
DCHECK(actions);
Microsoft::WRL::ComPtr<ITaskDefinition> task_definition;
HRESULT hr = task->get_Definition(&task_definition);
if (FAILED(hr)) {
PLOG(ERROR) << "Failed to get definition of task, " << std::hex << hr;
return false;
}
Microsoft::WRL::ComPtr<IActionCollection> action_collection;
hr = task_definition->get_Actions(&action_collection);
if (FAILED(hr)) {
PLOG(ERROR) << "Failed to get action collection, " << std::hex << hr;
return false;
}
long actions_count = 0; // NOLINT, API requires a long.
hr = action_collection->get_Count(&actions_count);
if (FAILED(hr)) {
PLOG(ERROR) << "Failed to get number of actions, " << std::hex << hr;
return false;
}
// Find and return as many exec actions as possible in |actions| and return
// false if there were any errors on the way. Note that the indexing of
// actions is 1-based.
bool success = true;
for (long action_index = 1; // NOLINT
action_index <= actions_count; ++action_index) {
Microsoft::WRL::ComPtr<IAction> action;
hr = action_collection->get_Item(action_index, &action);
if (FAILED(hr)) {
PLOG(ERROR) << "Failed to get action at index " << action_index << ", "
<< std::hex << hr;
success = false;
continue;
}
::TASK_ACTION_TYPE action_type;
hr = action->get_Type(&action_type);
if (FAILED(hr)) {
PLOG(ERROR) << "Failed to get the type of action at index "
<< action_index << ", " << std::hex << hr;
success = false;
continue;
}
// We only care about exec actions for now. The other types are
// TASK_ACTION_COM_HANDLER, TASK_ACTION_SEND_EMAIL,
// TASK_ACTION_SHOW_MESSAGE. The latter two are marked as deprecated in
// the Task Scheduler's GUI.
if (action_type != ::TASK_ACTION_EXEC)
continue;
Microsoft::WRL::ComPtr<IExecAction> exec_action;
hr = action.As(&exec_action);
if (FAILED(hr)) {
PLOG(ERROR) << "Failed to query from action, " << std::hex << hr;
success = false;
continue;
}
base::win::ScopedBstr application_path;
hr = exec_action->get_Path(application_path.Receive());
if (FAILED(hr)) {
PLOG(ERROR) << "Failed to get path from action, " << std::hex << hr;
success = false;
continue;
}
base::win::ScopedBstr working_dir;
hr = exec_action->get_WorkingDirectory(working_dir.Receive());
if (FAILED(hr)) {
PLOG(ERROR) << "Failed to get working directory for action, "
<< std::hex << hr;
success = false;
continue;
}
base::win::ScopedBstr parameters;
hr = exec_action->get_Arguments(parameters.Receive());
if (FAILED(hr)) {
PLOG(ERROR) << "Failed to get arguments from action of task, "
<< std::hex << hr;
success = false;
continue;
}
actions->push_back(
{base::FilePath(application_path.Get() ? application_path.Get()
: L""),
base::FilePath(working_dir.Get() ? working_dir.Get() : L""),
std::wstring(parameters.Get() ? parameters.Get() : L"")});
}
return success;
}
// Return the log-on type required for the task's actions to be run.
HRESULT GetTaskLogonType(IRegisteredTask* task, uint32_t* logon_type) {
DCHECK(task);
DCHECK(logon_type);
Microsoft::WRL::ComPtr<ITaskDefinition> task_info;
HRESULT hr = task->get_Definition(&task_info);
if (FAILED(hr)) {
LOG(ERROR) << "Failed to get definition, " << std::hex << hr << ": "
<< logging::SystemErrorCodeToString(hr);
return hr;
}
Microsoft::WRL::ComPtr<IPrincipal> principal;
hr = task_info->get_Principal(&principal);
if (FAILED(hr)) {
LOG(ERROR) << "Failed to get principal info, " << std::hex << hr << ": "
<< logging::SystemErrorCodeToString(hr);
return hr;
}
TASK_LOGON_TYPE raw_logon_type;
hr = principal->get_LogonType(&raw_logon_type);
if (FAILED(hr)) {
LOG(ERROR) << "Failed to get logon type info, " << std::hex << hr << ": "
<< logging::SystemErrorCodeToString(hr);
return hr;
}
switch (raw_logon_type) {
case TASK_LOGON_INTERACTIVE_TOKEN:
*logon_type = LOGON_INTERACTIVE;
break;
case TASK_LOGON_GROUP: // fall-thru
case TASK_LOGON_PASSWORD: // fall-thru
case TASK_LOGON_SERVICE_ACCOUNT:
*logon_type = LOGON_SERVICE;
break;
case TASK_LOGON_S4U:
*logon_type = LOGON_SERVICE | LOGON_S4U;
break;
case TASK_LOGON_INTERACTIVE_TOKEN_OR_PASSWORD:
*logon_type = LOGON_INTERACTIVE | LOGON_SERVICE;
break;
default:
*logon_type = LOGON_UNKNOWN;
break;
}
return ERROR_SUCCESS;
}
static Microsoft::WRL::ComPtr<ITaskService> task_service_;
static Microsoft::WRL::ComPtr<ITaskFolder> root_task_folder_;
DISALLOW_COPY_AND_ASSIGN(TaskSchedulerV2);
};
Microsoft::WRL::ComPtr<ITaskService> TaskSchedulerV2::task_service_;
Microsoft::WRL::ComPtr<ITaskFolder> TaskSchedulerV2::root_task_folder_;
// This wrapper class is needed so that CreateInstance below can instantiate a
// new one on every call, transferring ownership to the caller, and yet, we need
// to always get the same delegate to be called. So the temporary instantiated
// TaskScheduler is this mocked wrapper class, and each instance will delegate
// to the same mock, passed to the constructor.
// TODO(csharp): Simplify this.
class TaskSchedulerMock : public TaskScheduler {
public:
explicit TaskSchedulerMock(TaskScheduler* delegate) : delegate_(delegate) {
DCHECK(delegate);
}
// TaskScheduler.
bool IsTaskRegistered(const wchar_t* task_name) override {
return delegate_->IsTaskRegistered(task_name);
}
bool GetNextTaskRunTime(const wchar_t* task_name,
base::Time* next_run_time) override {
return delegate_->GetNextTaskRunTime(task_name, next_run_time);
}
bool DeleteTask(const wchar_t* task_name) override {
return delegate_->DeleteTask(task_name);
}
bool SetTaskEnabled(const wchar_t* task_name, bool enabled) override {
return delegate_->SetTaskEnabled(task_name, enabled);
}
bool IsTaskEnabled(const wchar_t* task_name) override {
return delegate_->IsTaskEnabled(task_name);
}
bool GetTaskNameList(std::vector<std::wstring>* task_names) override {
return delegate_->GetTaskNameList(task_names);
}
bool GetTaskInfo(const wchar_t* task_name, TaskInfo* info) override {
return delegate_->GetTaskInfo(task_name, info);
}
bool RegisterTask(const wchar_t* task_name,
const wchar_t* task_description,
const base::CommandLine& run_command,
TriggerType trigger_type,
bool hidden) override {
return delegate_->RegisterTask(task_name, task_description, run_command,
trigger_type, hidden);
}
private:
TaskScheduler* delegate_;
};
} // namespace
TaskScheduler* TaskScheduler::mock_delegate_ = nullptr;
TaskScheduler::TaskInfo::TaskInfo() = default;
TaskScheduler::TaskInfo::TaskInfo(const TaskScheduler::TaskInfo&) = default;
TaskScheduler::TaskInfo::TaskInfo(TaskScheduler::TaskInfo&&) = default;
TaskScheduler::TaskInfo& TaskScheduler::TaskInfo::operator=(
const TaskScheduler::TaskInfo&) = default;
TaskScheduler::TaskInfo& TaskScheduler::TaskInfo::operator=(
TaskScheduler::TaskInfo&&) = default;
TaskScheduler::TaskInfo::~TaskInfo() = default;
// static.
bool TaskScheduler::Initialize() {
return TaskSchedulerV2::Initialize();
}
// static.
void TaskScheduler::Terminate() {
TaskSchedulerV2::Terminate();
}
// static.
TaskScheduler* TaskScheduler::CreateInstance() {
if (mock_delegate_)
return new TaskSchedulerMock(mock_delegate_);
return new TaskSchedulerV2();
}
TaskScheduler::TaskScheduler() = default;
} // namespace chrome_cleaner
| 15,194 |
679 | <filename>main/unoxml/source/dom/notation.cxx
/**************************************************************
*
* 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 <notation.hxx>
#include <string.h>
namespace DOM
{
CNotation::CNotation(CDocument const& rDocument, ::osl::Mutex const& rMutex,
xmlNotationPtr const pNotation)
: CNotation_Base(rDocument, rMutex,
NodeType_NOTATION_NODE, reinterpret_cast<xmlNodePtr>(pNotation))
, m_aNotationPtr(pNotation)
{
}
OUString SAL_CALL CNotation::getPublicId() throw (RuntimeException)
{
OSL_ENSURE(false,
"CNotation::getPublicId: not implemented (#i113683#)");
return OUString();
}
/**
The system identifier of this notation.
*/
OUString SAL_CALL CNotation::getSystemId() throw (RuntimeException)
{
OSL_ENSURE(false,
"CNotation::getSystemId: not implemented (#i113683#)");
return OUString();
}
OUString SAL_CALL CNotation::getNodeName()throw (RuntimeException)
{
::osl::MutexGuard const g(m_rMutex);
OUString aName;
if (m_aNodePtr != NULL)
{
const xmlChar* xName = m_aNodePtr->name;
aName = OUString((sal_Char*)xName, strlen((char*)xName), RTL_TEXTENCODING_UTF8);
}
return aName;
}
OUString SAL_CALL CNotation::getNodeValue() throw (RuntimeException)
{
return OUString();
}
}
| 835 |
2,443 | // Copyright (c) 2015-2019 The HomeKit ADK Contributors
//
// Licensed under the Apache License, Version 2.0 (the “License”);
// you may not use this file except in compliance with the License.
// See [CONTRIBUTORS.md] for the list of HomeKit ADK project authors.
#include "HAPPlatform.h"
HAP_RESULT_USE_CHECK
float HAPFloatFromBitPattern(uint32_t bitPattern) {
float value;
HAPAssert(sizeof value == sizeof bitPattern);
HAPRawBufferCopyBytes(&value, &bitPattern, sizeof value);
return value;
}
HAP_RESULT_USE_CHECK
uint32_t HAPFloatGetBitPattern(float value) {
uint32_t bitPattern;
HAPAssert(sizeof bitPattern == sizeof value);
HAPRawBufferCopyBytes(&bitPattern, &value, sizeof bitPattern);
return bitPattern;
}
//----------------------------- Bigint Implementation ------------------------------
#define kInt_NumberOfWords (6) // Number of words (total 168 bits).
#define kInt_BitsPerWord (28) // Bits per word.
#define kInt_BitMask ((1 << kInt_BitsPerWord) - 1)
typedef struct {
uint32_t w[kInt_NumberOfWords];
uint32_t len;
} Bigint;
// x = val
static void BigintInit(Bigint* x, uint64_t value) {
uint32_t n = 0;
while (value) {
x->w[n] = (uint32_t) value & kInt_BitMask;
value >>= kInt_BitsPerWord;
n++;
}
x->len = n;
}
// Returns 0 if x == y, <0 if x < y, >0 if x > y
static int32_t BigintComp(const Bigint* x, const Bigint* y) {
uint32_t nx = x->len, ny = y->len;
int32_t delta = (int32_t) nx - (int32_t) ny;
if (delta)
return delta;
while (nx > 0) {
nx--;
delta = (int32_t) x->w[nx] - (int32_t) y->w[nx];
if (delta)
return delta;
}
return 0;
}
// z = x + y
static void BigintAdd(const Bigint* x, const Bigint* y, Bigint* z) {
uint32_t c = 0, i = 0, nx = x->len, ny = y->len;
while (i < nx || i < ny || c != 0) {
c += (i < nx ? x->w[i] : 0) + (i < ny ? y->w[i] : 0);
z->w[i] = c & kInt_BitMask;
c >>= kInt_BitsPerWord;
i++;
}
z->len = i;
}
// x = x * n, 2 <= n <= 10
static void BigintMul(Bigint* x, uint32_t n) {
uint32_t c = 0, i = 0, nx = x->len;
while (i < nx) {
c += x->w[i] * n;
x->w[i] = c & kInt_BitMask;
c >>= kInt_BitsPerWord;
i++;
}
if (c) {
x->w[i] = c;
x->len = i + 1;
}
}
// x = x % y; returns x / y
// pre: x < 10 * y
static uint32_t BigintDivRem(Bigint* x, const Bigint* y) {
uint32_t q = 0, ny = y->len;
while (BigintComp(x, y) >= 0) {
uint32_t i = 0, nx = x->len, n = 0;
int32_t c = 0;
q++;
while (i < nx) {
// x = x - y
c += x->w[i];
if (i < ny)
c -= y->w[i];
x->w[i] = c & kInt_BitMask;
i++;
if (c != 0)
n = i; // Remember most significant word.
c >>= kInt_BitsPerWord;
}
x->len = n;
}
return q;
}
//-----------------------------------------------------------
HAP_RESULT_USE_CHECK
HAPError HAPFloatFromString(const char* string, float* value) {
HAPPrecondition(string);
HAPPrecondition(value);
// - We don't want to accept leading or trailing whitespace.
// - We don't want to accept hexadecimal floats for now.
// - We don't want to accept infinity / nan for now.
// - We only want to accept standalone values.
*value = 0.0F;
char c = string[0];
int i = 1;
// Read sign.
uint32_t sign = 0;
if (c == '-') {
sign = 0x80000000;
c = string[i++];
} else if (c == '+') {
c = string[i++];
}
// Read mantissa.
uint64_t mant = 0;
int dp = 0;
int digits = 0;
int exp10 = 0; // Base 10 exponent.
for (;;) {
if (c == '.' && !dp) {
dp = 1;
} else if (c >= '0' && c <= '9') {
if (!dp)
exp10++;
if (mant < 100000000000000000ll) { // 10^17
mant = mant * 10 + (uint64_t)(c - '0');
exp10--;
}
digits++;
} else {
break;
}
c = string[i++];
}
if (digits == 0) {
// No mantissa digits.
return kHAPError_InvalidData;
}
/* mantissa == mant * 10^exp10, mant < 10^18 */
// Read exponent.
if (c == 'e' || c == 'E') {
// Scan exponent.
c = string[i++];
int expSign = 1;
if (c == '-') {
expSign = -1;
c = string[i++];
} else if (c == '+') {
c = string[i++];
}
int exp = 0;
digits = 0;
while (c >= '0' && c <= '9') {
if (exp < 1000) {
exp = exp * 10 + c - '0';
}
c = string[i++];
digits = 1;
}
if (digits == 0) {
// No exponent digits.
return kHAPError_InvalidData;
}
exp10 += exp * expSign;
}
if (c != 0) {
// Illegal characters in string.
return kHAPError_InvalidData;
}
/* |value| == mant * 10^exp10 */
// Check zero and large exponents to avoid Bigint overflow.
// Values below 0.7*10-45 are rounded down to zero.
if (mant == 0 || exp10 < -(45 + 18)) {
*value = HAPFloatFromBitPattern(sign); // +/-0
return kHAPError_None;
// Values above 3.4*10^38 are converted to infinity.
} else if (exp10 > 38) {
*value = HAPFloatFromBitPattern(0x7F800000 + sign); // +/-inf
return kHAPError_None;
}
/* -63 <= exp10 <= 38 */
// Base change.
Bigint X, S;
BigintInit(&X, mant);
BigintInit(&S, 1);
int exp2 = 0; // Base 2 exponent.
/* |value| == X * 10^exp10 */
while (exp10 > 0) {
BigintMul(&X, 5); // * 10/2
exp10--;
exp2++;
}
while (exp10 < 0) {
BigintMul(&S, 5); // * 10/2
exp10++;
exp2--;
}
while (BigintComp(&X, &S) >= 0) {
BigintMul(&S, 2);
exp2++;
}
while (BigintComp(&X, &S) < 0) {
BigintMul(&X, 2);
exp2--;
}
/* |value| == X/S * 2^exp2, 1 <= X/S < 2, X,S < 2^150 */
// Assemble float bits.
uint32_t bits = 0; // Mantissa bits (1.23).
int numBits = 24; // Number of mantissa bits.
if (exp2 >= -150) {
// No underflow.
if (exp2 < -126) {
// Denormalized float.
numBits = 150 + exp2;
exp2 = -126;
}
for (i = 0; i < numBits; i++) {
bits = bits * 2 + BigintDivRem(&X, &S);
BigintMul(&X, 2);
}
// Round to even.
if (BigintComp(&X, &S) + (int32_t)(bits & 1) > 0) {
bits++;
}
if (bits >= 0x1000000) {
// Rounding overflow.
bits >>= 1;
exp2++;
}
if (exp2 > 127) {
// Exponent overflow.
bits = 0x7F800000; // inf
} else {
// Include exponent.
bits += ((uint32_t)(exp2 + 126) << 23);
}
}
*value = HAPFloatFromBitPattern(bits + sign);
return kHAPError_None;
}
HAP_RESULT_USE_CHECK
HAPError HAPFloatGetDescription(char* bytes, size_t maxBytes, float value) {
uint32_t bits = HAPFloatGetBitPattern(value);
uint32_t mant = bits & 0x7FFFFF; // Base 2 mantissa.
int exp2 = (bits >> 23) & 0xFF; // Base 2 exponent.
size_t i = 0;
if ((int32_t) bits < 0) {
if (i + 1 >= maxBytes) {
return kHAPError_OutOfResources;
}
bytes[i++] = '-';
}
if (exp2 == 0xFF) { // inf/nan
if (i + 3 >= maxBytes) {
return kHAPError_OutOfResources;
}
if (mant) {
// no sign
bytes[0] = 'n';
bytes[1] = 'a';
bytes[2] = 'n';
bytes[3] = 0;
} else {
bytes[i++] = 'i';
bytes[i++] = 'n';
bytes[i++] = 'f';
bytes[i] = 0;
}
return kHAPError_None;
} else if (exp2) { // normalized
mant |= 0x800000;
} else { // denormalized
exp2 = 1;
}
if (mant == 0) {
if (i + 1 >= maxBytes) {
return kHAPError_OutOfResources;
}
bytes[i++] = '0';
bytes[i] = 0;
return kHAPError_None;
}
// Base change.
Bigint X, D, S, T;
BigintInit(&X, mant * 2);
BigintInit(&D, 1);
BigintInit(&S, 0x800000 * 2); // Position of decimal point.
exp2 -= 127;
/* |value| == X/S * 2^exp2, delta == D/S * 2^exp2, X/S <= 2, 0 < X < 2^25, -127 <= exp2 <= 127 */
int exp10 = 0;
while (exp2 < 0) {
if (BigintComp(&X, &S) <= 0) { // X/S <= 1
BigintMul(&X, 5);
BigintMul(&D, 5);
exp10--;
} else { // X/S > 1
BigintMul(&S, 2);
}
exp2++;
}
while (exp2 > 0) {
if (BigintComp(&X, &S) <= 0) { // X/S <= 1
BigintMul(&X, 2);
BigintMul(&D, 2);
} else { // X/S > 1
BigintMul(&S, 5);
exp10++;
}
exp2--;
}
/* |value| == X/S * 10^exp10, delta == D/S * 10^exp10, 1/5 < X/S <= 5, X,S < 2^114 */
// Write digits.
int32_t odd = bits & 1; // Original mantissa is odd.
uint32_t digit; // Actual digit.
int32_t low; // low <= 0 => digit is in range.
int32_t high; // high <= 0 => (digit + 1) is in range.
int dpPos = 0; // Position of decimal point.
int numDig = 0; // Number of written digits.
for (;;) {
digit = BigintDivRem(&X, &S);
/* X/S is difference between generated digits and precise value, X/S < 1 */
if ((bits & 0x7FFFFF) == 0) { // Special case:
BigintAdd(&X, &X, &T); // Lower delta is delta/2.
low = BigintComp(&T, &D); // X/S < D/S/2
} else {
low = BigintComp(&X, &D) + odd; // X/S </<= D/S
}
BigintAdd(&D, &X, &T);
high = BigintComp(&S, &T) + odd; // 1 - X/S </<= D/S
if (numDig == 0 && digit == 0 && high > 0) {
exp10--; // Suppress leading zero.
} else {
if (numDig == 0 && exp10 >= -4 && exp10 <= 5) {
// Eliminate small exponents.
dpPos = exp10;
exp10 = 0;
if (dpPos < 0) {
// Write leading decimal point.
if (i + (size_t)(2 - dpPos) >= maxBytes) {
return kHAPError_OutOfResources;
}
bytes[i++] = '0';
bytes[i++] = '.';
while (dpPos < -1) {
bytes[i++] = '0';
dpPos++;
}
}
}
if ((low <= 0 || high <= 0) && numDig >= dpPos) {
// No more digits needed.
break;
}
if (i + 2 >= maxBytes) {
return kHAPError_OutOfResources;
}
bytes[i++] = (char) (digit + '0'); // Write digit.
if (numDig == dpPos) {
bytes[i++] = '.'; // Write decimal point.
}
numDig++;
}
BigintMul(&X, 10);
BigintMul(&D, 10);
}
// Handle last digit.
if (low > 0) { // Only digit+1 in range.
digit++; // Use digit+1.
} else if (high <= 0) { // digit and digit+1 in range.
// Round to even.
BigintAdd(&X, &X, &T);
if (BigintComp(&T, &S) + (int32_t)(digit & 1) > 0) { // X/S >=/> 1/2
digit++;
}
}
if (i + 1 >= maxBytes) {
return kHAPError_OutOfResources;
}
// Write last digit (no decimal point).
bytes[i++] = (char) (digit + '0');
// Write exponent.
if (exp10) {
if (i + 4 >= maxBytes) {
return kHAPError_OutOfResources;
}
bytes[i++] = 'e';
if (exp10 < 0) {
bytes[i++] = '-';
exp10 = -exp10;
} else {
bytes[i++] = '+';
}
bytes[i++] = (char) ('0' + exp10 / 10);
bytes[i++] = (char) ('0' + exp10 % 10);
}
bytes[i] = 0;
return kHAPError_None;
}
float HAPFloatGetFraction(float value) {
uint32_t bits = HAPFloatGetBitPattern(value);
int exp = ((bits >> 23) & 0xFF) - 127;
if (exp < 0) { // no integer part
return value;
} else if (exp >= 23) { // no fractional part
return value - value;
}
// Remove fractional bits.
bits &= (0xFFFFFFFF << (23 - exp));
// Subtract integer part.
return value - HAPFloatFromBitPattern(bits);
}
float HAPFloatGetAbsoluteValue(float value) {
return HAPFloatFromBitPattern(HAPFloatGetBitPattern(value) & 0x7FFFFFFF);
}
bool HAPFloatIsZero(float value) {
return (HAPFloatGetBitPattern(value) & 0x7FFFFFFF) == 0;
}
bool HAPFloatIsFinite(float value) {
return (HAPFloatGetBitPattern(value) & 0x7F800000) != 0x7F800000; // inf exponent
}
bool HAPFloatIsInfinite(float value) {
return (HAPFloatGetBitPattern(value) & 0x7FFFFFFF) == 0x7F800000; // inf
}
| 6,951 |
372 | /*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.spanner.v1.model;
/**
* A message representing information for a key range (possibly one key).
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Cloud Spanner API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class KeyRangeInfo extends com.google.api.client.json.GenericJson {
/**
* The list of context values for this key range.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<ContextValue> contextValues;
static {
// hack to force ProGuard to consider ContextValue used, since otherwise it would be stripped out
// see https://github.com/google/google-api-java-client/issues/543
com.google.api.client.util.Data.nullOf(ContextValue.class);
}
/**
* The index of the end key in indexed_keys.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Integer endKeyIndex;
/**
* Information about this key range, for all metrics.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private LocalizedString info;
/**
* The number of keys this range covers.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long keysCount;
/**
* The name of the metric. e.g. "latency".
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private LocalizedString metric;
/**
* The index of the start key in indexed_keys.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Integer startKeyIndex;
/**
* The time offset. This is the time since the start of the time interval.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private String timeOffset;
/**
* The unit of the metric. This is an unstructured field and will be mapped as is to the user.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private LocalizedString unit;
/**
* The value of the metric.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Float value;
/**
* The list of context values for this key range.
* @return value or {@code null} for none
*/
public java.util.List<ContextValue> getContextValues() {
return contextValues;
}
/**
* The list of context values for this key range.
* @param contextValues contextValues or {@code null} for none
*/
public KeyRangeInfo setContextValues(java.util.List<ContextValue> contextValues) {
this.contextValues = contextValues;
return this;
}
/**
* The index of the end key in indexed_keys.
* @return value or {@code null} for none
*/
public java.lang.Integer getEndKeyIndex() {
return endKeyIndex;
}
/**
* The index of the end key in indexed_keys.
* @param endKeyIndex endKeyIndex or {@code null} for none
*/
public KeyRangeInfo setEndKeyIndex(java.lang.Integer endKeyIndex) {
this.endKeyIndex = endKeyIndex;
return this;
}
/**
* Information about this key range, for all metrics.
* @return value or {@code null} for none
*/
public LocalizedString getInfo() {
return info;
}
/**
* Information about this key range, for all metrics.
* @param info info or {@code null} for none
*/
public KeyRangeInfo setInfo(LocalizedString info) {
this.info = info;
return this;
}
/**
* The number of keys this range covers.
* @return value or {@code null} for none
*/
public java.lang.Long getKeysCount() {
return keysCount;
}
/**
* The number of keys this range covers.
* @param keysCount keysCount or {@code null} for none
*/
public KeyRangeInfo setKeysCount(java.lang.Long keysCount) {
this.keysCount = keysCount;
return this;
}
/**
* The name of the metric. e.g. "latency".
* @return value or {@code null} for none
*/
public LocalizedString getMetric() {
return metric;
}
/**
* The name of the metric. e.g. "latency".
* @param metric metric or {@code null} for none
*/
public KeyRangeInfo setMetric(LocalizedString metric) {
this.metric = metric;
return this;
}
/**
* The index of the start key in indexed_keys.
* @return value or {@code null} for none
*/
public java.lang.Integer getStartKeyIndex() {
return startKeyIndex;
}
/**
* The index of the start key in indexed_keys.
* @param startKeyIndex startKeyIndex or {@code null} for none
*/
public KeyRangeInfo setStartKeyIndex(java.lang.Integer startKeyIndex) {
this.startKeyIndex = startKeyIndex;
return this;
}
/**
* The time offset. This is the time since the start of the time interval.
* @return value or {@code null} for none
*/
public String getTimeOffset() {
return timeOffset;
}
/**
* The time offset. This is the time since the start of the time interval.
* @param timeOffset timeOffset or {@code null} for none
*/
public KeyRangeInfo setTimeOffset(String timeOffset) {
this.timeOffset = timeOffset;
return this;
}
/**
* The unit of the metric. This is an unstructured field and will be mapped as is to the user.
* @return value or {@code null} for none
*/
public LocalizedString getUnit() {
return unit;
}
/**
* The unit of the metric. This is an unstructured field and will be mapped as is to the user.
* @param unit unit or {@code null} for none
*/
public KeyRangeInfo setUnit(LocalizedString unit) {
this.unit = unit;
return this;
}
/**
* The value of the metric.
* @return value or {@code null} for none
*/
public java.lang.Float getValue() {
return value;
}
/**
* The value of the metric.
* @param value value or {@code null} for none
*/
public KeyRangeInfo setValue(java.lang.Float value) {
this.value = value;
return this;
}
@Override
public KeyRangeInfo set(String fieldName, Object value) {
return (KeyRangeInfo) super.set(fieldName, value);
}
@Override
public KeyRangeInfo clone() {
return (KeyRangeInfo) super.clone();
}
}
| 2,358 |
4,813 | # Generated by Django 2.2.1 on 2019-05-29 20:37
import json
from django.db import migrations
def normalize_webhook_values(apps, schema_editor):
Channel = apps.get_model("api", "Channel")
for ch in Channel.objects.filter(kind="webhook").only("value"):
# The old format of url_down, url_up, post_data separated by newlines:
if not ch.value.startswith("{"):
parts = ch.value.split("\n")
url_down = parts[0]
url_up = parts[1] if len(parts) > 1 else ""
post_data = parts[2] if len(parts) > 2 else ""
ch.value = json.dumps(
{
"method_down": "POST" if post_data else "GET",
"url_down": url_down,
"body_down": post_data,
"headers_down": {},
"method_up": "POST" if post_data else "GET",
"url_up": url_up,
"body_up": post_data,
"headers_up": {},
}
)
ch.save()
continue
doc = json.loads(ch.value)
# Legacy "post_data" in doc -- use the legacy fields
if "post_data" in doc:
ch.value = json.dumps(
{
"method_down": "POST" if doc["post_data"] else "GET",
"url_down": doc["url_down"],
"body_down": doc["post_data"],
"headers_down": doc["headers"],
"method_up": "POST" if doc["post_data"] else "GET",
"url_up": doc["url_up"],
"body_up": doc["post_data"],
"headers_up": doc["headers"],
}
)
ch.save()
continue
class Migration(migrations.Migration):
dependencies = [("api", "0060_tokenbucket")]
operations = [
migrations.RunPython(normalize_webhook_values, migrations.RunPython.noop)
]
| 1,068 |
575 | <reponame>dark-richie/crashpad<filename>util/file/filesystem_posix.cc
// Copyright 2017 The Crashpad Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "util/file/filesystem.h"
#include <errno.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "base/logging.h"
#include "build/build_config.h"
namespace crashpad {
bool FileModificationTime(const base::FilePath& path, timespec* mtime) {
struct stat st;
if (lstat(path.value().c_str(), &st) != 0) {
PLOG(ERROR) << "lstat " << path.value();
return false;
}
#if defined(OS_APPLE)
*mtime = st.st_mtimespec;
#elif defined(OS_ANDROID)
// This is needed to compile with traditional NDK headers.
mtime->tv_sec = st.st_mtime;
mtime->tv_nsec = st.st_mtime_nsec;
#else
*mtime = st.st_mtim;
#endif
return true;
}
bool LoggingCreateDirectory(const base::FilePath& path,
FilePermissions permissions,
bool may_reuse) {
if (mkdir(path.value().c_str(),
permissions == FilePermissions::kWorldReadable ? 0755 : 0700) ==
0) {
return true;
}
if (may_reuse && errno == EEXIST) {
if (!IsDirectory(path, true)) {
LOG(ERROR) << path.value() << " not a directory";
return false;
}
return true;
}
PLOG(ERROR) << "mkdir " << path.value();
return false;
}
bool MoveFileOrDirectory(const base::FilePath& source,
const base::FilePath& dest) {
if (rename(source.value().c_str(), dest.value().c_str()) != 0) {
PLOG(ERROR) << "rename " << source.value().c_str() << ", "
<< dest.value().c_str();
return false;
}
return true;
}
bool IsRegularFile(const base::FilePath& path) {
struct stat st;
if (lstat(path.value().c_str(), &st) != 0) {
PLOG_IF(ERROR, errno != ENOENT) << "stat " << path.value();
return false;
}
return S_ISREG(st.st_mode);
}
bool IsDirectory(const base::FilePath& path, bool allow_symlinks) {
struct stat st;
if (allow_symlinks) {
if (stat(path.value().c_str(), &st) != 0) {
PLOG_IF(ERROR, errno != ENOENT) << "stat " << path.value();
return false;
}
} else if (lstat(path.value().c_str(), &st) != 0) {
PLOG_IF(ERROR, errno != ENOENT) << "lstat " << path.value();
return false;
}
return S_ISDIR(st.st_mode);
}
bool LoggingRemoveFile(const base::FilePath& path) {
if (unlink(path.value().c_str()) != 0) {
PLOG(ERROR) << "unlink " << path.value();
return false;
}
return true;
}
bool LoggingRemoveDirectory(const base::FilePath& path) {
if (rmdir(path.value().c_str()) != 0) {
PLOG(ERROR) << "rmdir " << path.value();
return false;
}
return true;
}
} // namespace crashpad
| 1,295 |
442 | <gh_stars>100-1000
from unittest import TestCase
from mock import MagicMock
from mock import patch
from mock import mock_open
import prepare
from prepare import Prepare
import config
import bitcoin
from mock import Mock
class TestPrepare(TestCase):
def setUp(self):
self.context = Mock()
self.prepare = Prepare(self.context)
bitcoin.SelectParams('regtest')
@patch('node.wait_until_height_reached', lambda node, height: None)
@patch('utils.sleep', lambda time: None)
@patch('prepare._calc_number_of_tx_chains', lambda txs_per_tick, block_per_tick, amount_of_nodes: 5)
def test_warmup_block_generation(self):
node_0 = MagicMock()
node_1 = MagicMock()
nodes = [node_0, node_1]
self.context.nodes.values.return_value = nodes
self.prepare._pool = MagicMock()
self.prepare._give_nodes_spendable_coins()
self.assertEqual(node_0.execute_rpc.call_count, 2)
self.assertEqual(node_1.execute_rpc.call_count, 2)
@patch('os.path.exists')
@patch('os.path.islink')
@patch('os.makedirs')
@patch('bash.check_output')
@patch('builtins.open', new_callable=mock_open)
def test_prepare_simulation_dir(self, m_open, m_check_output, m_makedirs, m_islink, m_exists):
m_exists.return_value = False
self.prepare._pool = MagicMock()
self.prepare._prepare_simulation_dir()
self.assertEqual(m_makedirs.call_count, 3)
self.assertEqual(m_check_output.call_count, 10)
@patch('bash.check_output')
def test_remove_old_containers_if_exists(self, m_check_output):
m_check_output.return_value = ['container1', 'container2']
prepare._remove_old_containers_if_exists()
self.assertEqual(m_check_output.call_count, 2)
@patch('bash.check_output')
def test_remove_old_containers_if_exists_no_old_containers(self, m_check_output):
m_check_output.return_value = []
prepare._remove_old_containers_if_exists()
self.assertEqual(m_check_output.call_count, 1)
@patch('utils.sleep', lambda t: None)
@patch('bash.call_silent')
@patch('bash.check_output')
def test_recreate_network(self, m_check_output, m_call_silent):
m_call_silent.return_value = 0
prepare._recreate_network()
self.assertEqual(m_check_output.call_count, 2)
self.assertEqual(m_call_silent.call_count, 1)
@patch('utils.sleep', lambda t: None)
@patch('bash.call_silent')
@patch('bash.check_output')
def test_recreate_network_no_network(self, m_check_output, m_call_silent):
m_call_silent.return_value = -1
prepare._recreate_network()
self.assertEqual(m_check_output.call_count, 1)
def test_calc_number_of_tx_chains(self):
config.max_in_mempool_ancestors = 25
amount = prepare._calc_number_of_tx_chains(2, 1 / 600, 10)
self.assertEqual(amount, 51)
| 1,242 |
349 | package com.ray3k.skincomposer.dialog.scenecomposer.undoables;
import com.ray3k.skincomposer.dialog.scenecomposer.DialogSceneComposer;
import com.ray3k.skincomposer.dialog.scenecomposer.DialogSceneComposerModel;
public class CellUniformUndoable implements SceneComposerUndoable {
private DialogSceneComposerModel.SimCell cell;
private DialogSceneComposer dialog;
private boolean uniformX;
private boolean uniformY;
private boolean previousUniformX;
private boolean previousUniformY;
public CellUniformUndoable(boolean uniformX, boolean uniformY) {
this.uniformX = uniformX;
this.uniformY = uniformY;
dialog = DialogSceneComposer.dialog;
cell = (DialogSceneComposerModel.SimCell) dialog.simActor;
previousUniformX = cell.uniformX;
previousUniformY = cell.uniformY;
}
@Override
public void undo() {
cell.uniformX = previousUniformX;
cell.uniformY = previousUniformY;
if (dialog.simActor != cell) {
dialog.simActor = cell;
dialog.populateProperties();
dialog.populatePath();
}
dialog.model.updatePreview();
}
@Override
public void redo() {
cell.uniformX = uniformX;
cell.uniformY = uniformY;
if (dialog.simActor != cell) {
dialog.simActor = cell;
dialog.populateProperties();
dialog.populatePath();
}
dialog.model.updatePreview();
}
@Override
public String getRedoString() {
return "Redo \"Cell Uniform\"";
}
@Override
public String getUndoString() {
return "Undo \"Cell Uniform\"";
}
}
| 757 |
350 | # (C) Copyright 2021 IBM 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.
import warnings
import pandas as pd
import numpy as np
from itertools import permutations, combinations
from collections import namedtuple, Counter
from sklearn.covariance import EmpiricalCovariance
from sklearn.neighbors import NearestNeighbors
from sklearn.exceptions import NotFittedError
from sklearn.base import clone as sk_clone
from .base_estimator import IndividualOutcomeEstimator
from scipy.optimize import linear_sum_assignment
from scipy.spatial import distance
KNN = namedtuple("KNN", "learner index")
# scipy distance routine requires matrix of valid numerical distances
# we use `VERY_LARGE_NUMBER` to represent an infinite distance
VERY_LARGE_NUMBER = np.finfo('d').max
def majority_rule(x):
return Counter(x).most_common(1)[0][0]
class Matching(IndividualOutcomeEstimator):
def __init__(
self,
propensity_transform=None,
caliper=None,
with_replacement=True,
n_neighbors=1,
matching_mode="both",
metric="mahalanobis",
knn_backend="sklearn",
estimate_observed_outcome=False,
):
"""Match treatment and control samples with similar covariates.
Args:
propensity_transform (causallib.transformers.PropensityTransformer):
an object for data preprocessing which adds the propensity
score as a feature (default: None)
caliper (float) : maximal distance for a match to be accepted. If
not defined, all matches will be accepted. If defined, some
samples may not be matched and their outcomes will not be
estimated. (default: None)
with_replacement (bool): whether samples can be used multiple times
for matching. If set to False, the matching process will optimize
the linear sum of distances between pairs of treatment and
control samples and only `min(N_treatment, N_control)` samples
will be estimated. Matching with no replacement does not make
use of the `fit` data and is therefore not implemented for
out-of-sample data (default: True)
n_neighbors (int) : number of nearest neighbors to include in match.
Must be 1 if `with_replacement` is `False.` If larger than 1, the
estimate is calculated using the `regress_agg_function` or
`classify_agg_function` across the `n_neighbors`. Note that when
the `caliper` variable is set, some samples will have fewer than
`n_neighbors` matches. (default: 1).
matching_mode (str) : Direction of matching: `treatment_to_control`,
`control_to_treatment` or `both` to indicate which set should
be matched to which. All sets are cross-matched in `match`
and when `with_replacement` is `False` all matching modes
coincide. With replacement there is a difference.
metric (str) : Distance metric string for calculating distance
between samples. Note: if an external built `knn_backend`
object with a different metric is supplied, `metric` needs to
be changed to reflect that, because `Matching` will set its
inverse covariance matrix if "mahalanobis" is set. (default:
"mahalanobis", also supported: "euclidean")
knn_backend (str or callable) : Backend to use for nearest neighbor
search. Options are "sklearn" or a callable which returns an
object implementing `fit`, `kneighbors` and `set_params`
like the sklearn `NearestNeighbors` object. (default: "sklearn").
estimate_observed_outcome (bool) : Whether to allow a match of a
sample to a sample other than itself when looking within its own
treatment value. If True, the estimated potential outcome for the
observed outcome may differ from the true observed outcome.
(default: False)
Attributes:
classify_agg_function (callable) : Aggregating function for outcome
estimation when classifying. (default: majority_rule)
Usage is determined by type of `y` during `fit`
regress_agg_function (callable) : Aggregating function for outcome
estimation when regressing or predicting prob_a. (default: np.mean)
Usage is determined by type of `y` during `fit`
treatments_ (pd.DataFrame) : DataFrame of treatments (created after `fit`)
outcomes_ (pd.DataFrame) : DataFrame of outcomes (created after `fit`)
match_df_ (pd.DataFrame) : Dataframe of most recently calculated
matches. For details, see `match`. (created after `match`)
samples_used_ (pd.Series) : Series with count of samples used
during most recent match. Series includes a count for each
treatment value. (created after `match`)
"""
self.propensity_transform = propensity_transform
self.covariance_conditioner = EmpiricalCovariance()
self.caliper = caliper
self.with_replacement = with_replacement
self.n_neighbors = n_neighbors
self.matching_mode = matching_mode
self.metric = metric
# if classify task, default aggregation function is majority
self.classify_agg_function = majority_rule
# if regress task, default aggregation function is mean
self.regress_agg_function = np.mean
self.knn_backend = knn_backend
self.estimate_observed_outcome = estimate_observed_outcome
def fit(self, X, a, y, sample_weight=None):
"""Load the treatments and outcomes and fit search trees.
Applies transform to covariates X, initializes search trees for each
treatment value for performing nearest neighbor searches.
Note: Running `fit` a second time overwrites any information from
previous `fit or `match` and re-fits the propensity_transform object.
Args:
X (pd.DataFrame): DataFrame of shape (n,m) containing m covariates
for n samples.
a (pd.Series): Series of shape (n,) containing discrete treatment
values for the n samples.
y (pd.Series): Series of shape (n,) containing outcomes for
the n samples.
sample_weight: IGNORED In signature for compatibility with other
estimators.
Note: `X`, `a` and `y` must share the same index.
Returns:
self (Matching) the fitted object
"""
self._clear_post_fit_variables()
self.outcome_ = y.copy()
self.treatments_ = a.copy()
if self.propensity_transform:
self.propensity_transform.fit(X, a)
X = self.propensity_transform.transform(X)
self.conditioned_covariance_ = self._calculate_covariance(X)
self.treatment_knns_ = {}
for a in self.treatments_.unique():
haystack = X[self.treatments_ == a]
self.treatment_knns_[a] = self._fit_sknn(haystack)
return self
def _execute_matching(self, X, a):
"""Execute matching of samples in X according to the treatment values in a.
Returns a DataFrame including all the results, which is also set as
the attribute `self.match_df_`. The arguments `X` and `a` define the
"needle" where the "haystack" is the data that was previously passed
to fit, for matching with replacement. As such, treatment and control
samples from within `X` will not be matched with each other, unless
the same `X` and `a` were passed to `fit`. For matching without
replacement, the `X` and `a` passed to `match` provide the "needle" and
the "haystack". If the attribute `caliper` is set, the matches are
limited to those with a distance less than `caliper`.
This function ignores the existing `match_df_` and will overwrite it.
It is thus useful for if you have changed the settings and need to
rematch the samples. For most applications, the `match` function is
more convenient.
Args:
X (pd.DataFrame): DataFrame of shape (n,m) containing m covariates
for n samples.
a (pd.Series): Series of shape (n,) containing discrete treatment
values for the n samples.
Note: The args are assumed to share the same index.
Returns:
match_df: The resulting matches DataFrame is indexed so that
` match_df.loc[treatment_value, sample_id]` has columns `matches`
and `distances` containing lists of indices to samples and the
respective distances for the matches discovered for `sample_id`
from within the fitted samples with the given `treatment_value`.
The indices in the `matches` column are from the fitted data,
not the X argument in `match`. If `sample_id` had no match,
`match_df.loc[treatment_value, sample_id].matches = []`.
The DataFrame has shape (n* len(a.unique()), 2 ).
Raises:
NotImplementedError: Raised when with_replacement is False and
n_neighbors is not 1.
"""
if self.n_neighbors != 1 and not self.with_replacement:
raise NotImplementedError(
"Matching more than one neighbor is only implemented for"
"no-replacement"
)
if self.propensity_transform:
X = self.propensity_transform.transform(X)
if self.with_replacement:
self.match_df_ = self._withreplacement_match(X, a)
else:
self.match_df_ = self._noreplacement_match(X, a)
sample_id_name = X.index.name if X.index.name is not None else "sample_id"
self.match_df_.index.set_names(
["match_to_treatment", sample_id_name], inplace=True
)
# we record the number of samples that were successfully matched of
# each treatment value
self.samples_used_ = self._count_samples_used_by_treatment_value(a)
return self.match_df_
def estimate_individual_outcome(
self, X, a, y=None, treatment_values=None, predict_proba=True, dropna=True
):
"""
Calculate the potential outcome for each sample and treatment value.
Execute match and calculate, for each treatment value and each sample,
the expected outcome.
Note: Out of sample estimation for matching without replacement requires
passing a `y` vector here. If no 'y' is passed here, the values received
by `fit` are used, and if the estimation indices are not a subset of the
fitted indices, the estimation will fail.
If the attribute `estimate_observed_outcome` is
`True`, estimates will be calculated for the observed outcomes as well.
If not, then the observed outcome will be passed through from the
corresponding element of `y` passed to `fit`.
Args:
X (pd.DataFrame): DataFrame of shape (n,m) containing m covariates
for n samples.
a (pd.Series): Series of shape (n,) containing discrete treatment
values for the n samples.
y (pd.Series): Series of shape (n,) containing outcome values for
n samples. This is only used when `with_replacemnt=False`.
Otherwise, the outcome values passed to `fit` are used.
predict_proba (bool) : whether to output classifications or
probabilties for a classification task. If set to False and
data is non-integer, a warning is issued. (default True)
dropna (bool) : For samples that were unmatched due to caliper
restrictions, drop from outcome_df leading to a potentially
smaller sized output, or include them as NaN. (default: True)
treatment_values : IGNORED
Note: The args are assumed to share the same index.
Returns:
outcome_df (pd.DataFrame)
"""
match_df = self.match(X, a, use_cached_result=True)
outcome_df = self._aggregate_match_df_to_generate_outcome_df(
match_df, a, predict_proba)
outcome_df = self._filter_outcome_df_by_matching_mode(outcome_df, a)
if outcome_df.isna().all(axis=None):
raise ValueError("Matching was not successful and no outcomes can"
"be estimated. Check caliper value.")
if dropna:
outcome_df = outcome_df.dropna()
return outcome_df
def match(self, X, a, use_cached_result=True, successful_matches_only=False):
"""Matching the samples in X according to the treatment values in a.
Returns a DataFrame including all the results, which is also set as
the attribute `self.match_df_`. The arguments `X` and `a` define the
"needle" where the "haystack" is the data that was previously passed
to fit, for matching with replacement. As such, treatment and control
samp les from within `X` will not be matched with each other, unless
the same `X` and `a` were passed to `fit`. For matching without
replacement, the `X` and `a` passed to `match` provide the "needle" and
the "haystack". If the attribute `caliper` is set, the matches are
limited to those with a distance less than `caliper`.
Args:
X (pd.DataFrame): DataFrame of shape (n,m) containing m covariates
for n samples.
a (pd.Series): Series of shape (n,) containing discrete treatment
values for the n samples.
use_cached_result (bool): Whether or not to return the `match_df`
from the most recent matching operation. The cached result will
only be used if the sample indices of `X` and those of `match_df`
are identical, otherwise it will rematch.
successful_matches_only (bool): Whether or not to filter the matches
to those which matched successfully. If set to `False`, the
resulting DataFrame will have shape (n* len(a.unique()), 2 ),
otherwise it may have a smaller shape due to unsuccessful matches.
Note: The args are assumed to share the same index.
Returns:
match_df: The resulting matches DataFrame is indexed so that
` match_df.loc[treatment_value, sample_id]` has columns `matches`
and `distances` containing lists of indices to samples and the
respective distances for the matches discovered for `sample_id`
from within the fitted samples with the given `treatment_value`.
The indices in the `matches` column are from the fitted data,
not the X argument in `match`. If `sample_id` had no match,
`match_df.loc[treatment_value, sample_id].matches = []`.
The DataFrame has shape (n* len(a.unique()), 2 ), if
`successful_matches_only` is set to `False.
Raises:
NotImplementedError: Raised when with_replacement is False and
n_neighbors is not 1.
"""
cached_result_available = (hasattr(self, "match_df_")
and X.index.equals(self.match_df_.loc[0].index))
if not (use_cached_result and cached_result_available):
self._execute_matching(X, a)
return self._get_match_df(successful_matches_only=successful_matches_only)
def matches_to_weights(self, match_df=None):
"""Calculate weights based on a given set of matches.
For each matching from one treatment value to another, a weight vector
is generated. The weights are calculated as the number of times a
sample was selected in a matching, with each occurrence weighted
according to the number of other samples in that matching. The weights
can be used to estimate outcomes or to check covariate balancing. The
function can only be called after `match` has been run.
Args:
match_df (pd.DataFrame) : a DataFrame of matches returned from
`match`. If not supplied, will use the `match_df_` attribute if
available, else raises ValueError. Will not execute `match` to
generate a `match_df`.
Returns:
weights_df (pd.DataFrame): DataFrame of shape (n,M) where M is the
number of permutations of `a.unique()`.
"""
if match_df is None:
match_df = self._get_match_df(successful_matches_only=False)
match_permutations = sorted(permutations(self.treatments_.unique()))
weights_df = pd.DataFrame([
self._matches_to_weights_single_matching(s, t, match_df)
for s, t in match_permutations],).T
return weights_df
def get_covariates_of_matches(self, s, t, covariates):
"""
Look up covariates of closest matches for a given matching.
Using `self.match_df_` and the supplied `covariates`, look up
the covariates of the last match. The function can only be called after
`match` has been run.
Args:
s (int) : source treatment value
t (int) : target treatment value
covariates (pd.DataFrame) : The same covariates which were
passed to `fit`.
Returns:
covariate_df (pd.DataFrame) : a DataFrame of size
(n_matched_samples, n_covariates * 3 + 2) with the covariate
values of the sample, covariates of its match, calculated
distance and number of neighbors found within the given
caliper (with no caliper this will equal self.n_neighbors )
"""
match_df = self._get_match_df()
subdf = match_df.loc[s][self.treatments_ == t]
sample_id_name = subdf.index.name
def get_covariate_difference_from_nearest_match(source_row_index):
j = subdf.loc[source_row_index].matches[0]
delta_series = pd.Series(
covariates.loc[source_row_index] - covariates.loc[j])
source_row = covariates.loc[j].copy()
source_row.at[sample_id_name] = j
target_row = covariates.loc[source_row_index].copy()
target_row = target_row
covariate_differences = pd.concat(
{
t: target_row,
s: source_row,
"delta": delta_series,
"outcomes": pd.Series(
{t: self.outcome_.loc[source_row_index],
s: self.outcome_.loc[j]}
),
"match": pd.Series(
dict(
n_neighbors=len(
subdf.loc[source_row_index].matches),
distance=subdf.loc[source_row_index].distances[0],
)
),
}
)
return covariate_differences
covdf = pd.DataFrame(
data=[get_covariate_difference_from_nearest_match(i)
for i in subdf.index], index=subdf.index
)
covdf = covdf.reset_index()
cols = covdf.columns
covdf.columns = pd.MultiIndex.from_tuples(
[(t, sample_id_name)] + list(cols[1:]))
return covdf
def _clear_post_fit_variables(self):
for var in list(vars(self)):
if var[-1] == "_":
self.__delattr__(var)
def _calculate_covariance(self, X):
if len(X.shape) > 1 and X.shape[1] > 1:
V_list = []
for a in self.treatments_.unique():
X_at_a = X[self.treatments_ == a].copy()
current_V = self.covariance_conditioner.fit(X_at_a).covariance_
V_list.append(current_V)
# following Imbens&Rubin, we average across treatment groups
V = np.mean(V_list, axis=0)
else:
# for 1d data revert to euclidean metric
V = np.array(1).reshape(1, 1)
return V
def _aggregate_match_df_to_generate_outcome_df(self, match_df, a, predict_proba):
agg_function = self._get_agg_function(predict_proba)
def outcome_from_matches_by_idx(x):
return agg_function(self.outcome_.loc[x])
outcomes = {}
for i in sorted(a.unique()):
outcomes[i] = match_df.loc[i].matches.apply(
outcome_from_matches_by_idx)
outcome_df = pd.DataFrame(outcomes)
return outcome_df
def _get_match_df(self, successful_matches_only=True):
if not hasattr(self, "match_df_") or self.match_df_ is None:
raise NotFittedError("You need to run `match` first")
match_df = self.match_df_.copy()
if successful_matches_only:
match_df = match_df[match_df.matches.apply(bool)]
if match_df.empty:
raise ValueError(
"Matching was not successful and no outcomes can be "
"estimated. Check caliper value."
)
return match_df
def _filter_outcome_df_by_matching_mode(self, outcome_df, a):
if self.matching_mode == "treatment_to_control":
outcome_df = outcome_df[a == 1]
elif self.matching_mode == "control_to_treatment":
outcome_df = outcome_df[a == 0]
elif self.matching_mode == "both":
pass
else:
raise NotImplementedError(
"Matching mode {} is not implemented. Please select one of "
"'treatment_to_control', 'control_to_treatment, "
"or 'both'.".format(self.matching_mode)
)
return outcome_df
def _get_agg_function(self, predict_proba):
if predict_proba:
agg_function = self.regress_agg_function
else:
agg_function = self.classify_agg_function
try:
isoutputinteger = np.allclose(
self.outcome_.apply(int), self.outcome_)
if not isoutputinteger:
warnings.warn(
"Classifying non-categorical outcomes. "
"This is probably a mistake."
)
except:
warnings.warn(
"Unable to detect whether outcome is integer-like. ")
return agg_function
def _instantiate_nearest_neighbors_object(self):
backend = self.knn_backend
if backend == "sklearn":
backend_instance = NearestNeighbors(algorithm="auto")
elif callable(backend):
backend_instance = backend()
self.metric = backend_instance.metric
elif hasattr(backend, "fit") and hasattr(backend, "kneighbors"):
backend_instance = sk_clone(backend)
self.metric = backend_instance.metric
else:
raise NotImplementedError(
"`knn_backend` must be either an NearestNeighbors-like object,"
" a callable returning such an object, or the string \"sklearn\"")
backend_instance.set_params(**self._get_metric_dict())
return backend_instance
def _fit_sknn(self, target_df):
"""
Fit scikit-learn NearestNeighbors object with samples in target_df.
Fits object, adds metric parameters and returns namedtuple which
also includes DataFrame indices so that identities can looked up.
Args:
target_df (pd.DataFrame) : DataFrame of covariates to fit
Returns:
KNN (namedtuple) : Namedtuple with members `learner` and `index`
containing the fitted sklearn object and an index lookup vector,
respectively.
"""
target_array = target_df.values
sknn = self._instantiate_nearest_neighbors_object()
target_array = self._ensure_array_columnlike(target_array)
sknn.fit(target_array)
return KNN(sknn, target_df.index)
@staticmethod
def _ensure_array_columnlike(target_array):
if len(target_array.shape) < 2 or target_array.shape[1] == 1:
target_array = target_array.reshape(-1, 1)
return target_array
def _get_metric_dict(
self,
VI_in_metric_params=True,
):
metric_dict = dict(metric=self.metric)
if self.metric == "mahalanobis":
VI = np.linalg.inv(self.conditioned_covariance_)
if VI_in_metric_params:
metric_dict["metric_params"] = {"VI": VI}
else:
metric_dict["VI"] = VI
return metric_dict
def _kneighbors(self, knn, source_df):
"""Lookup neighbors in knn object.
Args:
knn (namedtuple) : knn named tuple to look for neighbors in. The
object has `learner` and `index` attributes to reference the
original df index.
source_df (pd.DataFrame) : a DataFrame of source data points to use
as "needles" for the knn "haystack."
Returns:
match_df (pd.DataFrame) : a DataFrame of matches
"""
source_array = source_df.values
# 1d data must be in shape (-1, 1) for sklearn.knn
source_array = self._ensure_array_columnlike(source_array)
distances, neighbor_array_indices = knn.learner.kneighbors(
source_array, n_neighbors=self.n_neighbors
)
return self._generate_match_df(
source_df, knn.index, distances, neighbor_array_indices
)
def _generate_match_df(
self, source_df, target_df_index, distances, neighbor_array_indices
):
"""
Take results of matching and build into match_df DataFrame.
For clarity we'll call the samples that are being matched "needles" and
the set of samples that they looked for matches in the "haystack".
Args:
source_df (pd.DataFrame) : Covariate dataframe of N "needles"
target_df_index (np.array) : An array of M indices of the haystack
samples in their original dataframe.
distances (np.array) : An array of N arrays of floats of length K
where K is `self.n_neighbors`.
neighbor_array_indices (np.array) : An array of N arrays of ints of
length K where K is `self.n_neighbors`.
"""
# target is the haystack, source is the needle(s)
# translate array indices back to original indices
matches_dict = {}
for source_idx, distance_row, neighbor_array_index_row in zip(
source_df.index, distances, neighbor_array_indices
):
neighbor_df_indices = \
target_df_index[neighbor_array_index_row.flatten()]
if self.caliper is not None:
neighbor_df_indices = [
n
for i, n in enumerate(neighbor_df_indices)
if distance_row[i] < self.caliper
]
distance_row = [d for d in distance_row if d < self.caliper]
matches_dict[source_idx] = dict(
matches=list(neighbor_df_indices), distances=list(distance_row)
)
# convert dict of dicts like { 1: {'matches':[], 'distances':[]}} to df
return pd.DataFrame(matches_dict).T
def _matches_to_weights_single_matching(self, s, t, match_df):
"""
For a given match, calculate the resulting weight vector.
The weight vector adds a count each time a sample is used, weighted by
the number of other neighbors when it was used. This is necessary to
make the weighted sum return the correct effect estimate.
"""
weights = pd.Series(self.treatments_.copy() * 0)
name = {0: "control", 1: "treatment"}
weights.name = "{s}_to_{t}".format(s=name[s], t=name[t])
s_to_t_matches = match_df.loc[t][self.treatments_ == s].matches
for source_idx, matches_list in s_to_t_matches.iteritems():
if matches_list:
weights.loc[source_idx] += 1
for match in matches_list:
weights.loc[match] += 1 / len(matches_list)
return weights
def _get_distance_matrix(self, source_df, target_df):
"""
Create distance matrix for no replacement match.
Combines metric, caliper and source/target data into a
precalculated distance matrix which can be passed to
scipy.optimize.linear_sum_assignment.
"""
cdist_args = dict(
XA=self._ensure_array_columnlike(source_df.values),
XB=self._ensure_array_columnlike(target_df.values),
)
cdist_args.update(self._get_metric_dict(False))
distance_matrix = distance.cdist(**cdist_args)
if self.caliper is not None:
distance_matrix[distance_matrix > self.caliper] = VERY_LARGE_NUMBER
return distance_matrix
def _withreplacement_match(self, X, a):
matches = {} # maps treatment value to list of matches TO that value
for treatment_value, knn in self.treatment_knns_.items():
matches[treatment_value] = self._kneighbors(knn, X)
# when producing potential outcomes we may want to force the
# value of the observed outcome to be the actual observed
# outcome, and not an average of the k nearest samples.
if not self.estimate_observed_outcome:
def limit_within_treatment_matches_to_self_only(row):
if (
a.loc[row.name] == treatment_value
and row.name in row.matches
):
row.matches = [row.name]
row.distances = [0]
return row
matches[treatment_value] = matches[treatment_value].apply(
limit_within_treatment_matches_to_self_only, axis=1
)
return pd.concat(matches, sort=True)
def _noreplacement_match(self, X, a):
match_combinations = sorted(combinations(a.unique(), 2))
matches = {}
for s, t in match_combinations:
distance_matrix = self._get_distance_matrix(X[a == s], X[a == t])
source_array, neighbor_array_indices, distances = \
self._optimally_match_distance_matrix(distance_matrix)
source_df = X[a == s].iloc[np.array(source_array)]
target_df = X[a == t].iloc[np.array(neighbor_array_indices)]
if t in matches or s in matches:
warnings.warn(
"No-replacement matching for more than "
"2 treatment values is not supported"
)
matches[t] = self._create_match_df_for_no_replacement(
a, source_df, target_df, distances
)
matches[s] = self._create_match_df_for_no_replacement(
a, target_df, source_df, distances
)
match_df = pd.concat(matches, sort=True)
return match_df
def _optimally_match_distance_matrix(self, distance_matrix):
source_array, neighbor_array_indices = linear_sum_assignment(
distance_matrix
)
distances = [
[distance_matrix[s_idx, t_idx]]
for s_idx, t_idx in zip(source_array, neighbor_array_indices)
]
source_array, neighbor_array_indices, distances = \
self._filter_noreplacement_matches_using_caliper(
source_array, neighbor_array_indices, distances)
return source_array, neighbor_array_indices, distances
def _filter_noreplacement_matches_using_caliper(
self, source_array, neighbor_array_indices, distances):
if self.caliper is None:
return source_array, neighbor_array_indices, distances
keep_indices = [i for i, d in enumerate(
distances) if d[0] <= self.caliper]
source_array = source_array[keep_indices]
neighbor_array_indices = neighbor_array_indices[keep_indices]
distances = [distances[i] for i in keep_indices]
if not keep_indices:
warnings.warn("No matches found, check caliper."
"No estimation possible.")
return source_array, neighbor_array_indices, distances
@staticmethod
def _create_match_df_for_no_replacement(
base_series, source_df, target_df, distances
):
match_sub_df = pd.DataFrame(
index=base_series.index,
columns=[
"matches",
"distances",
],
data=base_series.apply(lambda x: pd.Series([[], []])).values,
dtype="object",
)
# matching from source to target: read distances
match_sub_df.loc[source_df.index] = pd.DataFrame(
data=dict(
matches=[[tidx] for tidx in target_df.index],
distances=distances,
),
index=source_df.index,
)
# matching from target to target: fill with zeros
match_sub_df.loc[target_df.index] = pd.DataFrame(
data=dict(
matches=[[tidx] for tidx in target_df.index],
distances=[[0]] * len(distances),
),
index=target_df.index,
)
return match_sub_df
def _count_samples_used_by_treatment_value(self, a):
# we record the number of samples that were successfully matched of
# each treatment value
samples_used = {
treatment_value:
self.match_df_.loc[treatment_value][a != treatment_value]
.matches.apply(bool).sum()
for treatment_value in sorted(a.unique(), reverse=True)
}
return pd.Series(samples_used)
class PropensityMatching(Matching):
def __init__(self, learner, **kwargs):
"""Matching on propensity score only.
This is a convenience class to execute the common task of propensity
score matching. It shares all of the methods of the `Matching` class
but offers a shortcut for initialization.
Args:
learner (sklearn.estimator) : a trainable propensity model that
implements `fit` and `predict_proba`. Will be passed to the
`PropensityTransformer` object.
**kwargs : see Matching.__init__ for supported kwargs.
"""
from causallib.preprocessing.transformers import PropensityTransformer
super().__init__(**kwargs)
self.learner = learner
self.propensity_transform = PropensityTransformer(
include_covariates=False, learner=self.learner
)
| 15,745 |
5,823 | // Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_LINUX_FL_BASIC_MESSAGE_CHANNEL_H_
#define FLUTTER_SHELL_PLATFORM_LINUX_FL_BASIC_MESSAGE_CHANNEL_H_
#if !defined(__FLUTTER_LINUX_INSIDE__) && !defined(FLUTTER_LINUX_COMPILATION)
#error "Only <flutter_linux/flutter_linux.h> can be included directly."
#endif
#include <gio/gio.h>
#include <glib-object.h>
#include "fl_binary_messenger.h"
#include "fl_message_codec.h"
G_BEGIN_DECLS
G_DECLARE_FINAL_TYPE(FlBasicMessageChannel,
fl_basic_message_channel,
FL,
BASIC_MESSAGE_CHANNEL,
GObject)
G_DECLARE_FINAL_TYPE(FlBasicMessageChannelResponseHandle,
fl_basic_message_channel_response_handle,
FL,
BASIC_MESSAGE_CHANNEL_RESPONSE_HANDLE,
GObject)
/**
* FlBasicMessageChannel:
*
* #FlBasicMessageChannel is an object that allows sending and receiving
* messages to/from Dart code over platform channels.
*
* The following example shows how to send messages on a channel:
*
* |[<!-- language="C" -->
* static FlBasicMessageChannel *channel = NULL;
*
* static void message_cb (FlBasicMessageChannel* channel,
* FlValue* message,
* FlBasicMessageChannelResponseHandle* response_handle,
* gpointer user_data) {
* g_autoptr(FlValue) response = handle_message (message);
* g_autoptr(GError) error = NULL;
* if (!fl_basic_message_channel_respond (channel, response_handle, response,
* &error))
* g_warning ("Failed to send channel response: %s", error->message);
* }
*
* static void message_response_cb (GObject *object,
* GAsyncResult *result,
* gpointer user_data) {
* g_autoptr(GError) error = NULL;
* g_autoptr(FlValue) response =
* fl_basic_message_channel_send_finish (FL_BASIC_MESSAGE_CHANNEL (object),
* result, &error);
* if (response == NULL) {
* g_warning ("Failed to send message: %s", error->message);
* return;
* }
*
* handle_response (response);
* }
*
* static void setup_channel () {
* g_autoptr(FlStandardMessageCodec) codec = fl_standard_message_codec_new ();
* channel = fl_basic_message_channel_new (messenger, "flutter/foo",
* FL_MESSAGE_CODEC (codec));
* fl_basic_message_channel_set_message_handler (channel, message_cb, NULL,
* NULL);
*
* g_autoptr(FlValue) message = fl_value_new_string ("Hello World");
* fl_basic_message_channel_send (channel, message, NULL,
* message_response_cb, NULL);
* }
* ]|
*
* #FlBasicMessageChannel matches the BasicMessageChannel class in the Flutter
* services library.
*/
/**
* FlBasicMessageChannelResponseHandle:
*
* #FlBasicMessageChannelResponseHandle is an object used to send responses
* with.
*/
/**
* FlBasicMessageChannelMessageHandler:
* @channel: an #FlBasicMessageChannel.
* @message: message received.
* @response_handle: a handle to respond to the message with.
* @user_data: (closure): data provided when registering this handler.
*
* Function called when a message is received. Call
* fl_basic_message_channel_respond() to respond to this message. If the
* response is not occurring in this callback take a reference to
* @response_handle and release that once it has been responded to. Failing to
* respond before the last reference to @response_handle is dropped is a
* programming error.
*/
typedef void (*FlBasicMessageChannelMessageHandler)(
FlBasicMessageChannel* channel,
FlValue* message,
FlBasicMessageChannelResponseHandle* response_handle,
gpointer user_data);
/**
* fl_basic_message_channel_new:
* @messenger: an #FlBinaryMessenger.
* @name: a channel name.
* @codec: the message codec.
*
* Creates a basic message channel. @codec must match the codec used on the Dart
* end of the channel.
*
* Returns: a new #FlBasicMessageChannel.
*/
FlBasicMessageChannel* fl_basic_message_channel_new(
FlBinaryMessenger* messenger,
const gchar* name,
FlMessageCodec* codec);
/**
* fl_basic_message_channel_set_message_handler:
* @channel: an #FlBasicMessageChannel.
* @handler: (allow-none): function to call when a message is received on this
* channel or %NULL to disable the handler.
* @user_data: (closure): user data to pass to @handler.
* @destroy_notify: (allow-none): a function which gets called to free
* @user_data, or %NULL.
*
* Sets the function called when a message is received from the Dart side of the
* channel. See #FlBasicMessageChannelMessageHandler for details on how to
* respond to messages.
*
* The handler is removed if the channel is closed or is replaced by another
* handler, set @destroy_notify if you want to detect this.
*/
void fl_basic_message_channel_set_message_handler(
FlBasicMessageChannel* channel,
FlBasicMessageChannelMessageHandler handler,
gpointer user_data,
GDestroyNotify destroy_notify);
/**
* fl_basic_message_channel_respond:
* @channel: an #FlBasicMessageChannel.
* @response_handle: handle that was provided in a
* #FlBasicMessageChannelMessageHandler.
* @message: (allow-none): message response to send or %NULL for an empty
* response.
* @error: (allow-none): #GError location to store the error occurring, or %NULL
* to ignore.
*
* Responds to a message.
*
* Returns: %TRUE on success.
*/
gboolean fl_basic_message_channel_respond(
FlBasicMessageChannel* channel,
FlBasicMessageChannelResponseHandle* response_handle,
FlValue* message,
GError** error);
/**
* fl_basic_message_channel_send:
* @channel: an #FlBasicMessageChannel.
* @message: message to send, must match what the #FlMessageCodec supports.
* @cancellable: (allow-none): a #GCancellable or %NULL.
* @callback: (scope async): (allow-none): a #GAsyncReadyCallback to call when
* the request is satisfied or %NULL to ignore the response.
* @user_data: (closure): user data to pass to @callback.
*
* Asynchronously sends a message.
*/
void fl_basic_message_channel_send(FlBasicMessageChannel* channel,
FlValue* message,
GCancellable* cancellable,
GAsyncReadyCallback callback,
gpointer user_data);
/**
* fl_basic_message_channel_send_finish:
* @channel: an #FlBasicMessageChannel.
* @result: a #GAsyncResult.
* @error: (allow-none): #GError location to store the error occurring, or %NULL
* to ignore.
*
* Completes request started with fl_basic_message_channel_send().
*
* Returns: message response on success or %NULL on error.
*/
FlValue* fl_basic_message_channel_send_finish(FlBasicMessageChannel* channel,
GAsyncResult* result,
GError** error);
G_END_DECLS
#endif // FLUTTER_SHELL_PLATFORM_LINUX_FL_BASIC_MESSAGE_CHANNEL_H_
| 2,819 |
375 | <reponame>obrienben/openwayback
/*
* This file is part of the Wayback archival access software
* (http://archive-access.sourceforge.net/projects/wayback/).
*
* Licensed to the Internet Archive (IA) by one or more individual
* contributors.
*
* The IA 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.archive.wayback.util.graph;
import java.awt.Graphics2D;
/**
* @author brad
*
*/
public class RegionGraphElement extends RectangularGraphElement {
private RegionData data = null;
private ValueGraphElements values = null;
private GraphConfiguration config = null;
/**
* @param x the x coordinate for the region, in the global coordinate space
* of the containing Graph
* @param y the y coordinate for the region, in the global coordinate space
* of the containing Graph
* @param width the width of this region, in pixels
* @param height the height of this region, in pixels
* @param data the data to use for this region
* @param config the GraphConfiguration for this Graph
*/
public RegionGraphElement(int x, int y, int width, int height,
RegionData data, GraphConfiguration config) {
super(x,y,width,height);
// System.err.format("Created region (%d,%d)-(%d,%d)\n",x,y,width,height);
this.data = data;
this.config = config;
// int labelHeight = config.regionFontSize + (config.fontPadY * 2);
int labelHeight = 0;
int valuesHeight = height - labelHeight;
this.values = new ValueGraphElements(x+1, y+1, width - 1, valuesHeight,
data.getHighlightedValue(), data.getValues(),
data.getMaxValue(), config);
}
/**
* @return the RegionData for this region
*/
public RegionData getData() {
return data;
}
public void draw(Graphics2D g2d) {
if(data.hasHighlightedValue()) {
g2d.setColor(config.regionHighlightColor);
g2d.fillRect(x + 1, y+1, width - 1, height-2);
}
g2d.setColor(config.regionBorderColor);
g2d.setStroke(config.regionBorderStroke);
g2d.drawLine(x, y, x, y + height);
// int fontY = (y + height) - config.fontPadY;
//
// g2d.setColor(config.regionLabelColor);
// g2d.setFont(config.getRegionLabelFont());
// g2d.drawString(data.getLabel(), x + config.fontPadX, fontY);
values.draw(g2d);
}
}
| 910 |
521 | //
// XApplication.h
//
// Created by <NAME> on January 6, 2001.
//
/*
* Copyright (c) 2001 <NAME>. All Rights Reserved.
*
* 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 ABOVE LISTED COPYRIGHT HOLDER(S) 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.
*
* Except as contained in this notice, the name(s) of the above copyright
* holders shall not be used in advertising or otherwise to promote the
* sale, use or other dealings in this Software without prior written
* authorization.
*/
/* $XFree86: $ */
#import <Cocoa/Cocoa.h>
#import "XServer.h"
#import "Preferences.h"
@interface XApplication : NSApplication {
IBOutlet XServer *xserver;
IBOutlet Preferences *preferences;
}
- (void)sendEvent:(NSEvent *)anEvent;
@end
| 477 |
567 | <reponame>sdepablos/bigquery-utils
package com.google.bigquery;
import static org.junit.Assert.*;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import org.apache.calcite.sql.parser.SqlParseException;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class CalciteParserTest {
CalciteParser parser;
@Before
public void initParser() {
parser = new CalciteParser();
}
@Test(expected= SqlParseException.class)
public void parseQueryFail() throws SqlParseException {
parser.parseQuery("BLAH SELECT");
}
@Test
public void parseQuerySuccess() throws SqlParseException {
ByteArrayOutputStream outContent = new ByteArrayOutputStream();
System.setOut(new PrintStream(outContent));
System.out.println(parser.parseQuery("SELECT a FROM A"));
assertEquals("(SELECT \"a\"\n" + "FROM \"A\")\n", outContent.toString());
}
@Test
public void parseQueryMultipleLineSuccess() throws SqlParseException {
ByteArrayOutputStream outContent = new ByteArrayOutputStream();
System.setOut(new PrintStream(outContent));
System.out.println(parser.parseQuery("SELECT a FROM A; SELECT b FROM B"));
assertEquals("(SELECT \"a\"\n" + "FROM \"A\"), (SELECT \"b\"\n" + "FROM \"B\")\n",
outContent.toString());
}
@Test(expected= SqlParseException.class)
public void parseQueryMultipleLineFail() throws SqlParseException {
parser.parseQuery("SELECT a FROM A; BLAH SELECT");
}
// the Calcite parser can handle trailing/leading spaces as well as spaces in the middle
@Test
public void parseQuerySpaceSuccess() throws SqlParseException {
Assert.assertEquals(parser.parseQuery("SELECT a FROM A"),
parser.parseQuery(" SELECT a FROM A "));
}
// tests for exception position retrieval
@Test
public void parseQueryExceptionCatchSingleLine() {
try {
parser.parseQuery("BLAH SELECT a FROM A");
}
catch (SqlParseException e){
assertEquals(1, e.getPos().getLineNum());
assertEquals(1, e.getPos().getEndLineNum());
assertEquals(1, e.getPos().getColumnNum());
assertEquals(4, e.getPos().getEndColumnNum());
}
}
@Test
public void parseQueryExceptionCatchMultipleLine() {
try {
parser.parseQuery("SELECT a FROM A; BLAH SELECT b FROM B");
}
catch (SqlParseException e){
assertEquals(1, e.getPos().getLineNum());
assertEquals(1, e.getPos().getEndLineNum());
assertEquals(18, e.getPos().getColumnNum());
assertEquals(21, e.getPos().getEndColumnNum());
}
}
@Test
public void parseQueryExceptionCatchNewLine() {
try {
parser.parseQuery("SELECT a FROM A; "
+ '\n' + "BLAH SELECT b FROM B");
}
catch (SqlParseException e){
assertEquals(2, e.getPos().getLineNum());
assertEquals(2, e.getPos().getEndLineNum());
assertEquals(1, e.getPos().getColumnNum());
assertEquals(4, e.getPos().getEndColumnNum());
}
}
} | 1,102 |
1,473 | <reponame>rd2281136306/pinpoint
package com.navercorp.pinpoint.plugin.resin.interceptor;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.servlet.ServletContext;
import com.navercorp.pinpoint.bootstrap.context.ServerMetaDataHolder;
import com.navercorp.pinpoint.bootstrap.context.TraceContext;
import com.navercorp.pinpoint.bootstrap.interceptor.AroundInterceptor;
import com.navercorp.pinpoint.bootstrap.logging.PLogger;
import com.navercorp.pinpoint.bootstrap.logging.PLoggerFactory;
import com.navercorp.pinpoint.common.util.StringUtils;
/**
* @author huangpeng<EMAIL>
*/
public class WebAppInterceptor implements AroundInterceptor {
private PLogger logger = PLoggerFactory.getLogger(this.getClass());
private final boolean isDebug = logger.isDebugEnabled();
private final TraceContext traceContext;
public WebAppInterceptor(TraceContext traceContext) {
this.traceContext = traceContext;
}
@Override
public void before(Object target, Object[] args) {
// DO nothing
}
@Override
public void after(Object target, Object[] args, Object result, Throwable throwable) {
if (isDebug) {
logger.afterInterceptor(target, args, result, throwable);
}
try {
if (target instanceof ServletContext) {
final ServletContext servletContext = (ServletContext) target;
final String contextKey = extractContextKey(servletContext);
final List<String> loadedJarNames = extractLibJars(servletContext);
if (isDebug) {
logger.debug("{} jars : {}", contextKey, Arrays.toString(loadedJarNames.toArray()));
}
dispatchLibJars(contextKey, loadedJarNames, servletContext);
} else {
logger.warn("Webapp loader is not an instance of javax.servlet.ServletContext , target={}", target);
}
} catch (Exception e) {
logger.warn("Failed to dispatch lib jars", e);
}
}
private String extractContextKey(ServletContext webapp) {
String context = webapp.getContextPath();
return StringUtils.isEmpty(context) ? "/ROOT" : context;
}
private List<String> extractLibJarNamesFromURLs(URL[] urls) {
if (urls == null) {
return Collections.emptyList();
}
List<String> libJarNames = new ArrayList<String>(urls.length);
for (URL url : urls) {
try {
URI uri = url.toURI();
String libJarName = extractLibJarName(uri);
if (libJarName.length() > 0) {
libJarNames.add(libJarName);
}
} catch (URISyntaxException e) {
// ignore invalid formats
logger.warn("Invalid library url found : [{}]", url, e);
} catch (Exception e) {
logger.warn("Error extracting library name", e);
}
}
return libJarNames;
}
private String extractLibJarName(URI uri) {
String jarName = uri.toString();
int lastIndexOfSeparator = jarName.lastIndexOf("/");
if (lastIndexOfSeparator < 0) {
return jarName;
} else {
int lastIndexOfExclamatory = jarName.lastIndexOf("!");
if (lastIndexOfExclamatory == lastIndexOfSeparator - 1) {
jarName = jarName.substring(0, lastIndexOfExclamatory);
return jarName.substring(jarName.lastIndexOf("/") + 1);
} else if (jarName.startsWith("jar:") || jarName.endsWith(".jar")) {
return jarName.substring(lastIndexOfSeparator + 1);
} else {
return "";
}
}
}
private void dispatchLibJars(String contextKey, List<String> libJars, ServletContext webapp) {
ServerMetaDataHolder holder = this.traceContext.getServerMetaDataHolder();
holder.addServiceInfo(contextKey, libJars);
holder.setServerName(webapp.getServerInfo());
holder.notifyListeners();
}
private List<String> extractLibJars(ServletContext webapp) {
ClassLoader classLoader = webapp.getClassLoader();
if (classLoader instanceof URLClassLoader) {
URL[] urls = ((URLClassLoader) classLoader).getURLs();
return extractLibJarNamesFromURLs(urls);
} else {
return Collections.emptyList();
}
}
} | 1,987 |
14,668 | <reponame>chromium/chromium<gh_stars>1000+
// 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 CHROMEOS_SERVICES_BLUETOOTH_CONFIG_INITIALIZER_H_
#define CHROMEOS_SERVICES_BLUETOOTH_CONFIG_INITIALIZER_H_
#include <memory>
#include "base/memory/ref_counted.h"
namespace device {
class BluetoothAdapter;
} // namespace device
namespace chromeos {
namespace bluetooth_config {
class AdapterStateController;
class BluetoothDeviceStatusNotifier;
class BluetoothPowerController;
class DeviceCache;
class DeviceNameManager;
class DeviceOperationHandler;
class DiscoveredDevicesProvider;
class DiscoverySessionManager;
// Responsible for initializing the classes needed by the CrosBluetoothConfig
// API.
class Initializer {
public:
Initializer(const Initializer&) = delete;
Initializer& operator=(const Initializer&) = delete;
virtual ~Initializer() = default;
virtual std::unique_ptr<AdapterStateController> CreateAdapterStateController(
scoped_refptr<device::BluetoothAdapter> bluetooth_adapter) = 0;
virtual std::unique_ptr<BluetoothDeviceStatusNotifier>
CreateBluetoothDeviceStatusNotifier(DeviceCache* device_cache) = 0;
virtual std::unique_ptr<BluetoothPowerController>
CreateBluetoothPowerController(
AdapterStateController* adapter_state_controller) = 0;
virtual std::unique_ptr<DeviceNameManager> CreateDeviceNameManager(
scoped_refptr<device::BluetoothAdapter> bluetooth_adapter) = 0;
virtual std::unique_ptr<DeviceCache> CreateDeviceCache(
AdapterStateController* adapter_state_controller,
scoped_refptr<device::BluetoothAdapter> bluetooth_adapter,
DeviceNameManager* device_name_manager) = 0;
virtual std::unique_ptr<DiscoveredDevicesProvider>
CreateDiscoveredDevicesProvider(DeviceCache* device_cache) = 0;
virtual std::unique_ptr<DiscoverySessionManager>
CreateDiscoverySessionManager(
AdapterStateController* adapter_state_controller,
scoped_refptr<device::BluetoothAdapter> bluetooth_adapter,
DiscoveredDevicesProvider* discovered_devices_provider) = 0;
virtual std::unique_ptr<DeviceOperationHandler> CreateDeviceOperationHandler(
AdapterStateController* adapter_state_controller,
scoped_refptr<device::BluetoothAdapter> bluetooth_adapter,
DeviceNameManager* device_name_manager) = 0;
protected:
Initializer() = default;
};
} // namespace bluetooth_config
} // namespace chromeos
#endif // CHROMEOS_SERVICES_BLUETOOTH_CONFIG_INITIALIZER_H_
| 790 |
862 | /*
* (c) Copyright 2019 Palantir Technologies Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.palantir.atlasdb.timelock;
import com.palantir.lock.LockService;
import com.palantir.logsafe.logger.SafeLogger;
import com.palantir.logsafe.logger.SafeLoggerFactory;
import com.palantir.timestamp.TimestampManagementService;
import com.palantir.timestamp.TimestampService;
import java.util.stream.Stream;
import org.immutables.value.Value;
@Value.Immutable
public interface TimeLockServices extends AutoCloseable {
SafeLogger log = SafeLoggerFactory.get(TimeLockServices.class);
static TimeLockServices create(
TimestampService timestampService,
LockService lockService,
AsyncTimelockService timelockService,
AsyncTimelockResource timelockResource,
TimestampManagementService timestampManagementService) {
return ImmutableTimeLockServices.builder()
.timestampService(timestampService)
.lockService(lockService)
.timestampManagementService(timestampManagementService)
.timelockService(timelockService)
.timelockResource(timelockResource)
.build();
}
TimestampService getTimestampService();
LockService getLockService();
// The Jersey endpoints
AsyncTimelockResource getTimelockResource();
// The RPC-independent leadership-enabled implementation of the timelock service
AsyncTimelockService getTimelockService();
TimestampManagementService getTimestampManagementService();
@Override
default void close() {
Stream.of(
getTimestampService(),
getLockService(),
getTimelockResource(),
getTimelockService(),
getTimestampManagementService())
.filter(service -> service instanceof AutoCloseable)
.distinct()
.forEach(service -> {
try {
((AutoCloseable) service).close();
} catch (Exception e) {
log.info("Exception occurred when closing a constituent of TimeLockServices", e);
}
});
}
}
| 1,114 |
2,210 | # import all APIs
from .webgear import WebGear
from .webgear_rtc import WebGear_RTC
from .netgear_async import NetGear_Async
__all__ = ["WebGear", "NetGear_Async", "WebGear_RTC"]
__author__ = "<NAME> (@abhiTronix) <<EMAIL>>"
| 92 |
580 | <gh_stars>100-1000
// Copyright 2016-2020 TriAxis Games L.L.C. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Kismet/BlueprintFunctionLibrary.h"
#include "RuntimeMeshRenderable.h"
#include "RuntimeMeshSlicer.generated.h"
/** Options for creating cap geometry when slicing */
UENUM()
enum class ERuntimeMeshSliceCapOption : uint8
{
/** Do not create cap geometry */
NoCap,
/** Add a new section to RuntimeMesh for cap */
CreateNewSectionForCap,
/** Add cap geometry to existing last section */
UseLastSectionForCap
};
UCLASS()
class RUNTIMEMESHCOMPONENT_API URuntimeMeshSlicer : public UBlueprintFunctionLibrary
{
GENERATED_BODY()
public:
/**
* Slice the RuntimeMeshComponent (including simple convex collision) using a plane. Optionally create 'cap' geometry.
* @param InRuntimeMesh RuntimeMeshComponent to slice
* @param PlanePosition Point on the plane to use for slicing, in world space
* @param PlaneNormal Normal of plane used for slicing. Geometry on the positive side of the plane will be kept.
* @param bCreateOtherHalf If true, an additional RuntimeMeshComponent (OutOtherHalfRuntimeMesh) will be created using the other half of the sliced geometry
* @param OutOtherHalfRuntimeMesh If bCreateOtherHalf is set, this is the new component created. Its owner will be the same as the supplied InRuntimeMesh.
* @param CapOption If and how to create 'cap' geometry on the slicing plane
* @param CapMaterial If creating a new section for the cap, assign this material to that section
*/
UFUNCTION(BlueprintCallable, Category = "Components|RuntimeMesh")
static void SliceRuntimeMesh(URuntimeMeshComponent* InRuntimeMesh, FVector PlanePosition, FVector PlaneNormal, bool bCreateOtherHalf,
URuntimeMeshComponent*& OutOtherHalfRuntimeMesh, ERuntimeMeshSliceCapOption CapOption, UMaterialInterface* CapMaterial);
/**
* Slice the RuntimeMeshData using a plane. Optionally create 'cap' geometry.
* @param SourceSection RuntimeMeshData to slice
* @param PlanePosition Point on the plane to use for slicing, in world space
* @param PlaneNormal Normal of plane used for slicing. Geometry on the positive side of the plane will be kept.
* @param CapOption If and how to create 'cap' geometry on the slicing plane
* @param NewSourceSection Resulting mesh data for origin section
* @param DestinationSection Mesh data sliced from source
*/
UFUNCTION(BlueprintCallable, Category = "Components|RuntimeMesh")
static bool SliceRuntimeMeshData(FRuntimeMeshRenderableMeshData& SourceSection, const FPlane& SlicePlane, ERuntimeMeshSliceCapOption CapOption, FRuntimeMeshRenderableMeshData& NewSourceSection,
FRuntimeMeshRenderableMeshData& NewSourceSectionCap, bool bCreateDestination, FRuntimeMeshRenderableMeshData& DestinationSection, FRuntimeMeshRenderableMeshData& NewDestinationSectionCap);
};
| 851 |
380 | <reponame>aviallon/waifu2x-converter-cpp<filename>src/modelHandler_simd_unroll4.hpp<gh_stars>100-1000
const unsigned char *w_cur = w_chunk_base;
unsigned char *output_base0 = output + ((x0+0)*nOutputPlanes + oi0*OP_BLOCK_SIZE)*sizeof(float);
unsigned char *output_base1 = output + ((x0+1)*nOutputPlanes + oi0*OP_BLOCK_SIZE)*sizeof(float);
unsigned char *output_base2 = output + ((x0+2)*nOutputPlanes + oi0*OP_BLOCK_SIZE)*sizeof(float);
unsigned char *output_base3 = output + ((x0+3)*nOutputPlanes + oi0*OP_BLOCK_SIZE)*sizeof(float);
vreg_t oreg00 = zero_vreg();
vreg_t oreg01 = zero_vreg();
vreg_t oreg10 = zero_vreg();
vreg_t oreg11 = zero_vreg();
vreg_t oreg20 = zero_vreg();
vreg_t oreg21 = zero_vreg();
vreg_t oreg30 = zero_vreg();
vreg_t oreg31 = zero_vreg();
for (int dposx=0; dposx<3; dposx++) {
int dposx2 = dposx-1;
int dposx2_le = dposx-1;
int dposx2_re = dposx-1;
if (x0 == 0 && dposx == 0) {
dposx2_le = 0;
}
if (x0 == width-4 && dposx == 2) {
dposx2_re = 0;
}
int off0 = ((dposy2*width + x0 + 0 + dposx2_le)*nInputPlanes+ii0*IP_BLOCK_SIZE)*sizeof(float);
int off1 = ((dposy2*width + x0 + 1 + dposx2)*nInputPlanes+ii0*IP_BLOCK_SIZE)*sizeof(float);
int off2 = ((dposy2*width + x0 + 2 + dposx2)*nInputPlanes+ii0*IP_BLOCK_SIZE)*sizeof(float);
int off3 = ((dposy2*width + x0 + 3 + dposx2_re)*nInputPlanes+ii0*IP_BLOCK_SIZE)*sizeof(float);
const unsigned char *input_cur_x0 = in + off0;
const unsigned char *input_cur_x1 = in + off1;
const unsigned char *input_cur_x2 = in + off2;
const unsigned char *input_cur_x3 = in + off3;
uintptr_t addr_off = 0;
#if (defined USE_SSE3)
for (int ii1=0; ii1<IP_BLOCK_SIZE; ii1+=4) {
#if defined __x86_64
/* ** silvermont(4cycle) **
*
* <decode>
* movss i0, mem
* shufps i0, i0
*
* mov i1, i0
* mul i0, wreg
*
* add o0, i0
* mul i1, wreg
*
* add o1, i1
*
*
* <issue>
* FP0 FP1 Mem
* shups mul0 load
* mov mul0
* add mul1
* mul1
*
*
* ** other(2cycle) **
* shuf, load, mul, add
* mul, add
*
*/
#define OP_0_0(OFF) "movss " #OFF "(%[PTR0],%[ADDR_OFF]), %%xmm0\n\t"
#define OP_0_1(OFF) "shufps $0, %%xmm0, %%xmm0\n\t"
#define OP_0_2(OFF) "movaps %%xmm0, %%xmm1\n\t"
#define OP_0_3(OFF) "mulps %%xmm2, %%xmm0\n\t"
#define OP_0_4(OFF) "addps %%xmm0, %[OREG00]\n\t"
#define OP_0_5(OFF) "mulps %%xmm3, %%xmm1\n\t"
#define OP_0_6(OFF) "addps %%xmm1, %[OREG01]\n\t"
#define OP_1_0(OFF) "movss " #OFF "(%[PTR1],%[ADDR_OFF]), %%xmm4\n\t"
#define OP_1_1(OFF) "shufps $0, %%xmm4, %%xmm4\n\t"
#define OP_1_2(OFF) "movaps %%xmm4, %%xmm5\n\t"
#define OP_1_3(OFF) "mulps %%xmm2, %%xmm4\n\t"
#define OP_1_4(OFF) "addps %%xmm4, %[OREG10]\n\t"
#define OP_1_5(OFF) "mulps %%xmm3, %%xmm5\n\t"
#define OP_1_6(OFF) "addps %%xmm5, %[OREG11]\n\t"
#define OP_2_0(OFF) "movss " #OFF "(%[PTR2],%[ADDR_OFF]), %%xmm0\n\t"
#define OP_2_1(OFF) "shufps $0, %%xmm0, %%xmm0\n\t"
#define OP_2_2(OFF) "movaps %%xmm0, %%xmm1\n\t"
#define OP_2_3(OFF) "mulps %%xmm2, %%xmm0\n\t"
#define OP_2_4(OFF) "addps %%xmm0, %[OREG20]\n\t"
#define OP_2_5(OFF) "mulps %%xmm3, %%xmm1\n\t"
#define OP_2_6(OFF) "addps %%xmm1, %[OREG21]\n\t"
#define OP_3_0(OFF) "movss " #OFF "(%[PTR3],%[ADDR_OFF]), %%xmm4\n\t"
#define OP_3_1(OFF) "shufps $0, %%xmm4, %%xmm4\n\t"
#define OP_3_2(OFF) "movaps %%xmm4, %%xmm5\n\t"
#define OP_3_3(OFF) "mulps %%xmm2, %%xmm4\n\t"
#define OP_3_4(OFF) "addps %%xmm4, %[OREG30]\n\t"
#define OP_3_5(OFF) "mulps %%xmm3, %%xmm5\n\t"
#define OP_3_6(OFF) "addps %%xmm5, %[OREG31]\n\t"
/* 0: mov ld-> 0 <1>
* 1: shuf 0 -> 0 <2,3>
* 2: mov 0 -> 1 <5>
* 3: mul 2,0 -> 0 <4>
* 4: add 0,D -> D D
* 5: mul 3,1 -> 1 <6>
* 6: add 1,D -> D D
*/
#define OP_BLOCK_0(OFF,NOFF) \
OP_0_0(OFF) \
OP_1_0(OFF) \
OP_0_1(OFF) \
OP_1_1(OFF) \
OP_0_2(OFF) \
OP_1_2(OFF) \
OP_0_3(OFF) \
OP_1_3(OFF) \
OP_0_4(OFF) \
OP_2_0(OFF) \
OP_1_4(OFF) \
OP_3_0(OFF) \
OP_0_5(OFF) \
OP_2_1(OFF) \
OP_1_5(OFF) \
OP_3_1(OFF) \
OP_0_6(OFF) \
OP_2_2(OFF) \
OP_1_6(OFF) \
OP_3_2(OFF) \
\
OP_2_3(OFF) \
OP_3_3(OFF) \
OP_2_4(OFF) \
OP_0_0(NOFF) \
OP_3_4(OFF) \
OP_1_0(NOFF) \
OP_2_5(OFF) \
OP_0_1(NOFF) \
OP_3_5(OFF) \
OP_1_1(NOFF) \
OP_2_6(OFF) \
OP_3_6(OFF)
#define OP_BLOCK(OFF,NOFF) \
OP_0_2(OFF) \
OP_1_2(OFF) \
OP_0_3(OFF) \
OP_1_3(OFF) \
OP_0_4(OFF) \
OP_2_0(OFF) \
OP_1_4(OFF) \
OP_3_0(OFF) \
OP_0_5(OFF) \
OP_2_1(OFF) \
OP_1_5(OFF) \
OP_3_1(OFF) \
OP_0_6(OFF) \
OP_2_2(OFF) \
OP_1_6(OFF) \
OP_3_2(OFF) \
\
OP_2_3(OFF) \
OP_3_3(OFF) \
OP_2_4(OFF) \
OP_0_0(NOFF) \
OP_3_4(OFF) \
OP_1_0(NOFF) \
OP_2_5(OFF) \
OP_0_1(NOFF) \
OP_3_5(OFF) \
OP_1_1(NOFF) \
OP_2_6(OFF) \
OP_3_6(OFF)
#define OP_BLOCK_LAST(OFF) \
OP_0_2(OFF) \
OP_1_2(OFF) \
OP_0_3(OFF) \
OP_1_3(OFF) \
OP_0_4(OFF) \
OP_2_0(OFF) \
OP_1_4(OFF) \
OP_3_0(OFF) \
OP_0_5(OFF) \
OP_2_1(OFF) \
OP_1_5(OFF) \
OP_3_1(OFF) \
OP_0_6(OFF) \
OP_2_2(OFF) \
OP_1_6(OFF) \
OP_3_2(OFF) \
\
OP_2_3(OFF) \
OP_3_3(OFF) \
OP_2_4(OFF) \
OP_3_4(OFF) \
OP_2_5(OFF) \
OP_3_5(OFF) \
OP_2_6(OFF) \
OP_3_6(OFF)
__asm__ __volatile__ ("movaps 16*0(%[W_CUR]), %%xmm2\n\t"
"movaps 16*1(%[W_CUR]), %%xmm3\n\t"
OP_BLOCK_0(0,4)
"movaps 16*2(%[W_CUR]), %%xmm2\n\t"
"movaps 16*3(%[W_CUR]), %%xmm3\n\t"
OP_BLOCK(4,8)
"movaps 16*4(%[W_CUR]), %%xmm2\n\t"
"movaps 16*5(%[W_CUR]), %%xmm3\n\t"
OP_BLOCK(8,12)
"movaps 16*6(%[W_CUR]), %%xmm2\n\t"
"movaps 16*7(%[W_CUR]), %%xmm3\n\t"
OP_BLOCK_LAST(12)
:[OREG00]"+x"(oreg00),
[OREG01]"+x"(oreg01),
[OREG10]"+x"(oreg10),
[OREG11]"+x"(oreg11),
[OREG20]"+x"(oreg20),
[OREG21]"+x"(oreg21),
[OREG30]"+x"(oreg30),
[OREG31]"+x"(oreg31)
:[PTR0]"r"(input_cur_x0),
[PTR1]"r"(input_cur_x1),
[PTR2]"r"(input_cur_x2),
[PTR3]"r"(input_cur_x3),
[W_CUR]"r"(w_cur),
[ADDR_OFF]"r"(addr_off)
:"xmm0","xmm1","xmm2","xmm3","xmm4","xmm5","xmm6","xmm7"
);
addr_off += 16;
w_cur += 128;
#else
__m128 i0 = _mm_load_ps((float*)input_cur_x0);
__m128 i1 = _mm_load_ps((float*)input_cur_x1);
__m128 i2 = _mm_load_ps((float*)input_cur_x2);
__m128 i3 = _mm_load_ps((float*)input_cur_x3);
__m128 ireg0, ireg1, ireg2, ireg3;
input_cur_x0 += 16;
input_cur_x1 += 16;
input_cur_x2 += 16;
input_cur_x3 += 16;
__m128 w0, w1;
#define ACCUMULATE(II) \
w0 = _mm_load_ps((float*)(w_cur)); \
w1 = _mm_load_ps((float*)(w_cur+16)); \
\
w_cur += 32; \
\
ireg0 = _mm_shuffle_ps(i0, i0, _MM_SHUFFLE(II,II,II,II)); \
oreg00 = madd_vreg(w0, ireg0, oreg00); \
oreg01 = madd_vreg(w1, ireg0, oreg01); \
\
ireg1 = _mm_shuffle_ps(i1, i1, _MM_SHUFFLE(II,II,II,II)); \
oreg10 = madd_vreg(w0, ireg1, oreg10); \
oreg11 = madd_vreg(w1, ireg1, oreg11); \
\
ireg2 = _mm_shuffle_ps(i2, i2, _MM_SHUFFLE(II,II,II,II)); \
oreg20 = madd_vreg(w0, ireg2, oreg20); \
oreg21 = madd_vreg(w1, ireg2, oreg21); \
\
ireg3 = _mm_shuffle_ps(i3, i3, _MM_SHUFFLE(II,II,II,II)); \
oreg30 = madd_vreg(w0, ireg3, oreg30); \
oreg31 = madd_vreg(w1, ireg3, oreg31);
ACCUMULATE(0);
ACCUMULATE(1);
ACCUMULATE(2);
ACCUMULATE(3);
#endif
}
#elif (defined __ARM_NEON && !defined __aarch64__)
for (int ii1=0; ii1<IP_BLOCK_SIZE; ii1+=16) {
/* q0-q3: ireg
* q4,q5 : wreg
*/
#define NEON_BODY(PLD_IN,PLD_W) \
__asm__ __volatile__("vld1.32 {q0}, [%[PTR0]:64]!\n\t" \
"vld1.32 {q1}, [%[PTR1]:64]!\n\t" \
"vld1.32 {q2}, [%[PTR2]:64]!\n\t" \
"vld1.32 {q3}, [%[PTR3]:64]!\n\t" \
"vld1.32 {q4}, [%[W_CUR]:64]!\n\t" \
"vld1.32 {q5}, [%[W_CUR]:64]!\n\t" \
\
"vmla.f32 %q[OREG00], q4, d0[0]\n\t" \
"vld1.32 {q6}, [%[W_CUR]:64]!\n\t" \
"vmla.f32 %q[OREG01], q5, d0[0]\n\t" \
"vld1.32 {q7}, [%[W_CUR]:64]!\n\t" \
"vmla.f32 %q[OREG10], q4, d2[0]\n\t" \
"vmla.f32 %q[OREG11], q5, d2[0]\n\t" \
"vmla.f32 %q[OREG20], q4, d4[0]\n\t" \
"vmla.f32 %q[OREG21], q5, d4[0]\n\t" \
"vmla.f32 %q[OREG30], q4, d6[0]\n\t" \
"vmla.f32 %q[OREG31], q5, d6[0]\n\t" \
\
"vmla.f32 %q[OREG00], q6, d0[1]\n\t" \
"vld1.32 {q4}, [%[W_CUR]:64]!\n\t" \
"vmla.f32 %q[OREG01], q7, d0[1]\n\t" \
"vld1.32 {q5}, [%[W_CUR]:64]!\n\t" \
"vmla.f32 %q[OREG10], q6, d2[1]\n\t" \
"vmla.f32 %q[OREG11], q7, d2[1]\n\t" \
"vmla.f32 %q[OREG20], q6, d4[1]\n\t" \
"vmla.f32 %q[OREG21], q7, d4[1]\n\t" \
"vmla.f32 %q[OREG30], q6, d6[1]\n\t" \
"vmla.f32 %q[OREG31], q7, d6[1]\n\t" \
\
"vmla.f32 %q[OREG00], q4, d1[0]\n\t" \
"vld1.32 {q6}, [%[W_CUR]:64]!\n\t" \
"vmla.f32 %q[OREG01], q5, d1[0]\n\t" \
"vld1.32 {q7}, [%[W_CUR]:64]!\n\t" \
"vmla.f32 %q[OREG10], q4, d3[0]\n\t" \
"vmla.f32 %q[OREG11], q5, d3[0]\n\t" \
"vmla.f32 %q[OREG20], q4, d5[0]\n\t" \
"vmla.f32 %q[OREG21], q5, d5[0]\n\t" \
PLD_IN \
"vmla.f32 %q[OREG30], q4, d7[0]\n\t" \
"vmla.f32 %q[OREG31], q5, d7[0]\n\t" \
\
"vmla.f32 %q[OREG00], q6, d1[1]\n\t" \
PLD_W \
"vmla.f32 %q[OREG01], q7, d1[1]\n\t" \
"vmla.f32 %q[OREG10], q6, d3[1]\n\t" \
"vmla.f32 %q[OREG11], q7, d3[1]\n\t" \
"vmla.f32 %q[OREG20], q6, d5[1]\n\t" \
"vmla.f32 %q[OREG21], q7, d5[1]\n\t" \
"vmla.f32 %q[OREG30], q6, d7[1]\n\t" \
"vmla.f32 %q[OREG31], q7, d7[1]\n\t" \
\
:[W_CUR]"+r"(w_cur), \
[OREG00]"+w"(oreg00), \
[OREG01]"+w"(oreg01), \
[OREG10]"+w"(oreg10), \
[OREG11]"+w"(oreg11), \
[OREG20]"+w"(oreg20), \
[OREG21]"+w"(oreg21), \
[OREG30]"+w"(oreg30), \
[OREG31]"+w"(oreg31), \
[PTR0]"+r"(input_cur_x0), \
[PTR1]"+r"(input_cur_x1), \
[PTR2]"+r"(input_cur_x2), \
[PTR3]"+r"(input_cur_x3) \
: \
:"q0","q1","q2","q3", \
"q4","q5","q6","q7","memory");
NEON_BODY("pld [%[PTR0], #256]\n\t", "pld [%[W_CUR], #192]\n\t");
NEON_BODY("","");
NEON_BODY("","");
NEON_BODY("","");
}
#else
#define accumulate(o0,o1,w0,w1,addr) { \
vreg_t ireg0 = load_vreg_broadcast(addr); \
o0 = madd_vreg(w0, ireg0, o0); \
o1 = madd_vreg(w1, ireg0, o1); \
}
#define MUL_W_IN(I) \
{ \
int I2 = I; \
vreg_t wreg0, wreg1; \
\
wreg0 = load_vreg(w_cur); \
wreg1 = load_vreg(w_cur + VEC_NELEM*sizeof(float)); \
\
accumulate(oreg00, oreg01, wreg0, wreg1, (input_cur_x0)); \
accumulate(oreg10, oreg11, wreg0, wreg1, (input_cur_x1)); \
accumulate(oreg20, oreg21, wreg0, wreg1, (input_cur_x2)); \
accumulate(oreg30, oreg31, wreg0, wreg1, (input_cur_x3)); \
\
w_cur += OP_BLOCK_SIZE * sizeof(float); \
input_cur_x0 += sizeof(float); \
input_cur_x1 += sizeof(float); \
input_cur_x2 += sizeof(float); \
input_cur_x3 += sizeof(float); \
}
for (int ii1=0; ii1<IP_BLOCK_SIZE; ii1+=4) {
MUL_W_IN(ii1+0);
MUL_W_IN(ii1+1);
MUL_W_IN(ii1+2);
MUL_W_IN(ii1+3);
}
#endif
}
if (dposy == 0 && ii0 == 0) {
store_vreg(output_base0 + ( 0)*sizeof(float), oreg00);
store_vreg(output_base0 + (VEC_NELEM)*sizeof(float), oreg01);
store_vreg(output_base1 + ( 0)*sizeof(float), oreg10);
store_vreg(output_base1 + (VEC_NELEM)*sizeof(float), oreg11);
store_vreg(output_base2 + ( 0)*sizeof(float), oreg20);
store_vreg(output_base2 + (VEC_NELEM)*sizeof(float), oreg21);
store_vreg(output_base3 + ( 0)*sizeof(float), oreg30);
store_vreg(output_base3 + (VEC_NELEM)*sizeof(float), oreg31);
} else if (last_iter) {
vreg_t tmp00, tmp01;
vreg_t tmp10, tmp11;
vreg_t tmp20, tmp21;
vreg_t tmp30, tmp31;
vreg_t mtz, ltz, bv0, bv1;
bv0 = load_vreg(biases + (oi0*OP_BLOCK_SIZE+ 0)*sizeof(float));
bv1 = load_vreg(biases + (oi0*OP_BLOCK_SIZE+VEC_NELEM)*sizeof(float));
#define ReLU(addr, bv, N) \
tmp##N = load_vreg(addr); \
tmp##N = add_vreg(tmp##N, oreg##N); \
tmp##N = add_vreg(tmp##N, bv); \
mtz = max_vreg(tmp##N, zero_vreg()); \
ltz = min_vreg(tmp##N, zero_vreg()); \
tmp##N = madd_vreg(ltz, set1_vreg(0.1f), mtz); \
ReLU(output_base0 + ( 0)*sizeof(float), bv0, 00);
ReLU(output_base0 + (VEC_NELEM)*sizeof(float), bv1, 01);
ReLU(output_base1 + ( 0)*sizeof(float), bv0, 10);
ReLU(output_base1 + (VEC_NELEM)*sizeof(float), bv1, 11);
ReLU(output_base2 + ( 0)*sizeof(float), bv0, 20);
ReLU(output_base2 + (VEC_NELEM)*sizeof(float), bv1, 21);
ReLU(output_base3 + ( 0)*sizeof(float), bv0, 30);
ReLU(output_base3 + (VEC_NELEM)*sizeof(float), bv1, 31);
store_vreg(output_base0 + ( 0)*sizeof(float), tmp00);
store_vreg(output_base0 + (VEC_NELEM)*sizeof(float), tmp01);
store_vreg(output_base1 + ( 0)*sizeof(float), tmp10);
store_vreg(output_base1 + (VEC_NELEM)*sizeof(float), tmp11);
store_vreg(output_base2 + ( 0)*sizeof(float), tmp20);
store_vreg(output_base2 + (VEC_NELEM)*sizeof(float), tmp21);
store_vreg(output_base3 + ( 0)*sizeof(float), tmp30);
store_vreg(output_base3 + (VEC_NELEM)*sizeof(float), tmp31);
} else {
vreg_t tmp;
#define ADD_TO_MEM(addr, val) \
tmp = load_vreg(addr); \
tmp = add_vreg(tmp, val); \
store_vreg(addr, tmp);
ADD_TO_MEM(output_base0 + ( 0)*sizeof(float), oreg00);
ADD_TO_MEM(output_base0 + (VEC_NELEM)*sizeof(float), oreg01);
ADD_TO_MEM(output_base1 + ( 0)*sizeof(float), oreg10);
ADD_TO_MEM(output_base1 + (VEC_NELEM)*sizeof(float), oreg11);
ADD_TO_MEM(output_base2 + ( 0)*sizeof(float), oreg20);
ADD_TO_MEM(output_base2 + (VEC_NELEM)*sizeof(float), oreg21);
ADD_TO_MEM(output_base3 + ( 0)*sizeof(float), oreg30);
ADD_TO_MEM(output_base3 + (VEC_NELEM)*sizeof(float), oreg31);
}
#undef MUL_W_IN
#ifdef accumulate
#undef accumulate
#endif
#undef ADD_TO_MEM
#undef ReLU
| 17,297 |
15,337 | <gh_stars>1000+
from typing import TYPE_CHECKING, Optional
from django_countries import countries
from .interface import ShippingMethodData
if TYPE_CHECKING:
from .models import ShippingMethod
def default_shipping_zone_exists(zone_pk=None):
from .models import ShippingZone
return ShippingZone.objects.exclude(pk=zone_pk).filter(default=True)
def get_countries_without_shipping_zone():
"""Return countries that are not assigned to any shipping zone."""
from .models import ShippingZone
covered_countries = set()
for zone in ShippingZone.objects.all():
covered_countries.update({c.code for c in zone.countries})
return (country[0] for country in countries if country[0] not in covered_countries)
def convert_to_shipping_method_data(
shipping_method: Optional["ShippingMethod"],
) -> Optional["ShippingMethodData"]:
if not shipping_method:
return None
return ShippingMethodData(
id=str(shipping_method.id),
name=shipping_method.name,
price=getattr(shipping_method, "price", None),
description=shipping_method.description,
type=shipping_method.type,
excluded_products=shipping_method.excluded_products,
channel_listings=shipping_method.channel_listings,
minimum_order_weight=shipping_method.minimum_order_weight,
maximum_order_weight=shipping_method.maximum_order_weight,
maximum_delivery_days=shipping_method.maximum_delivery_days,
minimum_delivery_days=shipping_method.minimum_delivery_days,
metadata=shipping_method.metadata,
private_metadata=shipping_method.private_metadata,
)
| 582 |
12,077 | <reponame>jacksmith15/faker<filename>faker/providers/currency/sv_SE/__init__.py<gh_stars>1000+
from .. import Provider as CurrencyProvider
# Names taken from https://www.iban.se/currency-codes
class Provider(CurrencyProvider):
# Format: (code, name)
currencies = (
("AED", "UAE Dirham"),
("AFN", "Afghani"),
("ALL", "Lek"),
("AMD", "Armenisk Dram"),
("ANG", "Gulden från Nederländska Antillerna"),
("AOA", "Kwanza"),
("ARS", "Argentinsk Peso"),
("AUD", "Australisk Dollar"),
("AWG", "Arubisk Florin"),
("AZN", "Azerbajdzjansk Manat"),
("BAM", "Konvertibel Mark"),
("BBD", "Barbadosdollar"),
("BDT", "Taka"),
("BGN", "Bulgarisk Lev"),
("BHD", "Bahraini Dinar"),
("BIF", "Burundi-franc"),
("BMD", "Bermuda-dollar"),
("BND", "Brunei-dollar"),
("BOB", "Boliviano"),
("BOV", "Mvdol"),
("BRL", "Brasilisk Real"),
("BSD", "Bahamasdollar"),
("BTN", "Ngultrum"),
("BWP", "Pula"),
("BYR", "Vitrysk Rubel"),
("BZD", "Belize-dollar"),
("CAD", "Kanadensisk Dollar"),
("CDF", "Kongolesisk Franc"),
("CHE", "WIR Euro"),
("CHF", "Schweizerfranc"),
("CHW", "WIR Franc"),
("CLF", "Unidad de Fomento"),
("CLP", "Chilensk Peso"),
("CNY", "Yuan Renminbi"),
("COP", "Colombiansk Peso"),
("COU", "Unidad de Valor Real"),
("CRC", "<NAME>"),
("CUC", "Peso Convertible"),
("CUP", "Kubansk Peso"),
("CVE", "Kap Verde Escudo"),
("CZK", "Tjeckisk Koruna"),
("DJF", "Djibouti-franc"),
("DKK", "Dansk Krone"),
("DOP", "Dominicansk Peso"),
("DZD", "Algerisk Dinar"),
("EGP", "Egyptiskt pund"),
("ERN", "Nakfa"),
("ETB", "Etiopisk Birr"),
("EUR", "Euro"),
("FJD", "Fiji Dollar"),
("FKP", "Pund från Falklandöarna"),
("GBP", "Pund Sterling"),
("GEL", "Lari"),
("GHS", "Ghana Cedi"),
("GIP", "Gibraltar-pund"),
("GMD", "Dalasi"),
("GNF", "Guinea-franc"),
("GTQ", "Quetzal"),
("GYD", "Guyana-dollar"),
("HKD", "Hong Kong-dollar"),
("HNL", "Lempira"),
("HRK", "Kuna"),
("HTG", "Gourde"),
("HUF", "Forint"),
("IDR", "Rupiah"),
("ILS", "Ny Israelisk Shekel"),
("INR", "Indisk Rupie"),
("IQD", "Irakisk Dinar"),
("IRR", "Iransk Rial"),
("ISK", "Isländsk Krona"),
("JMD", "Jamaica-dollar"),
("JOD", "Jordanisk Dinar"),
("JPY", "Yen"),
("KES", "Kenyansk Shilling"),
("KGS", "Som"),
("KHR", "Riel"),
("KMF", "Comoros-franc"),
("KPW", "Nordkoreansk Won"),
("KRW", "Won"),
("KWD", "Kuwaiti Dinar"),
("KYD", "Caymanöar-dollar"),
("KZT", "Tenge"),
("LAK", "Kip"),
("LBP", "Libanesiskt pund"),
("LKR", "Sri Lanka Rupie"),
("LRD", "Liberiansk Dollar"),
("LSL", "Loti"),
("LYD", "Libysk Dinar"),
("MAD", "<NAME>"),
("MDL", "<NAME>"),
("MGA", "<NAME>"),
("MKD", "Denar"),
("MMK", "Kyat"),
("MNT", "Tugrik"),
("MOP", "Pataca"),
("MRO", "Ouguiya"),
("MUR", "<NAME>"),
("MVR", "Rufiyaa"),
("MWK", "Kwacha"),
("MXN", "Mexikansk Peso"),
("MXV", "Mexikansk Unidad de Inversion (UDI)"),
("MYR", "Malaysisk Ringgit"),
("MZN", "Mozambique Metical"),
("NAD", "Namibia Dollar"),
("NGN", "Naira"),
("NIO", "Cordoba Oro"),
("NOK", "Norsk Krone"),
("NOK", "Norwegian Krone"),
("NPR", "Nepalesisk Rupie"),
("NZD", "Nya Zealand-dollar"),
("OMR", "Rial Omani"),
("PAB", "Balboa"),
("PEN", "Nuevo Sol"),
("PGK", "Kina"),
("PHP", "Filippinsk Peso"),
("PKR", "Pakistansk Rupie"),
("PLN", "Zloty"),
("PYG", "Guarani"),
("QAR", "Qatari Rial"),
("RON", "Rumänsk Leu"),
("RSD", "Serbisk Dinar"),
("RUB", "<NAME>"),
("RWF", "Rwanda Franc"),
("SAR", "Saudi Riyal"),
("SBD", "Dollar från Salomonöarna"),
("SCR", "Seychell-rupie"),
("SDG", "Sudanesiskt pund"),
("SEK", "Svensk Krona"),
("SGD", "Singapore Dollar"),
("SHP", "Saint Helena pund"),
("SLL", "Leone"),
("SOS", "Somalisk Shilling"),
("SRD", "Surinam Dollar"),
("SSP", "Sydsudanesiskt pund"),
("STD", "Dobra"),
("SVC", "El Salvador Colon"),
("SYP", "Syriskt pund"),
("SZL", "Lilangeni"),
("THB", "Baht"),
("TJS", "Somoni"),
("TMT", "Turkmenistansk Ny Manat"),
("TND", "Tunisisk Dinar"),
("TOP", "Pa’anga"),
("TRY", "Turkisk Lira"),
("TTD", "Trinidad och Tobago Dollar"),
("TWD", "Ny Taiwanesisk Dollar"),
("TZS", "Tanzanisk Shilling"),
("UAH", "Hryvnia"),
("UGX", "Uganda Shilling"),
("USD", "US Dollar"),
("USN", "US Dollar (Nästa dag)"),
("UYI", "Uruguay Peso en Unidades Indexadas (URUIURUI)"),
("UYU", "Peso Uruguayo"),
("UZS", "Uzbekistansk Sum"),
("VEF", "Bolivar"),
("VND", "Dong"),
("VUV", "Vatu"),
("WST", "Tala"),
("XAF", "CFA Franc BEAC"),
("XCD", "East Caribbean Dollar"),
("XDR", "SDR (Särskild dragningsrätt)"),
("XOF", "CFA Franc BCEAO"),
("XPF", "CFP Franc"),
("XSU", "Sucre"),
("XUA", "ADB Beräkningsenhet"),
("YER", "Yemeni Rial"),
("ZAR", "Rand"),
("ZMW", "Zambian Kwacha"),
("ZWL", "Zimbabwe Dollar"),
)
| 3,222 |
2,151 | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/events/ozone/evdev/touch_filter/edge_touch_filter.h"
#include <stddef.h>
#include <cmath>
#include "base/logging.h"
#include "base/macros.h"
#include "base/metrics/histogram_macros.h"
#include "base/strings/stringprintf.h"
#include "ui/gfx/geometry/insets.h"
namespace ui {
namespace {
// The maximum distance from the border to be considered for filtering
const int kMaxBorderDistance = 1;
bool IsNearBorder(const gfx::Point& point, gfx::Size touchscreen_size) {
gfx::Rect inner_bound = gfx::Rect(touchscreen_size);
inner_bound.Inset(gfx::Insets(kMaxBorderDistance));
return !inner_bound.Contains(point);
}
} // namespace
EdgeTouchFilter::EdgeTouchFilter(gfx::Size& touchscreen_size)
: touchscreen_size_(touchscreen_size) {
}
void EdgeTouchFilter::Filter(
const std::vector<InProgressTouchEvdev>& touches,
base::TimeTicks time,
std::bitset<kNumTouchEvdevSlots>* slots_should_delay) {
for (const InProgressTouchEvdev& touch : touches) {
size_t slot = touch.slot;
gfx::Point& tracked_tap = tracked_taps_[slot];
gfx::Point touch_pos = gfx::Point(touch.x, touch.y);
bool should_delay = false;
if (!touch.touching && !touch.was_touching)
continue; // Only look at slots with active touches.
if (!touch.was_touching && IsNearBorder(touch_pos, touchscreen_size_)) {
should_delay = true; // Delay new contact near border.
tracked_taps_[slot] = touch_pos;
}
if (slots_should_delay->test(slot) && touch_pos == tracked_tap) {
should_delay = true; // Continue delaying contacts that don't move.
}
slots_should_delay->set(slot, should_delay);
}
}
} // namespace ui
| 656 |
312 | package com.dfire.platform.alchemy.domain;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import javax.persistence.*;
import javax.validation.constraints.*;
import java.io.Serializable;
import java.time.Instant;
import java.util.HashSet;
import java.util.Set;
import java.util.Objects;
import com.dfire.platform.alchemy.domain.enumeration.ClusterType;
/**
* A Cluster.
*/
@Entity
@Table(name = "cluster")
public class Cluster implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@Column(name = "name", nullable = false)
private String name;
@NotNull
@Enumerated(EnumType.STRING)
@Column(name = "jhi_type", nullable = false)
private ClusterType type;
@Lob
@Column(name = "config", nullable = false)
private String config;
@NotNull
@Column(name = "remark", nullable = false)
private String remark;
@Column(name = "created_by")
private String createdBy;
@Column(name = "created_date")
private Instant createdDate;
@Column(name = "last_modified_by")
private String lastModifiedBy;
@Column(name = "last_modified_date")
private Instant lastModifiedDate;
@ManyToOne
@JsonIgnoreProperties("clusters")
private Business business;
@OneToMany(mappedBy = "cluster")
private Set<Job> jobs = new HashSet<>();
// jhipster-needle-entity-add-field - JHipster will add fields here, do not remove
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public Cluster name(String name) {
this.name = name;
return this;
}
public void setName(String name) {
this.name = name;
}
public ClusterType getType() {
return type;
}
public Cluster type(ClusterType type) {
this.type = type;
return this;
}
public void setType(ClusterType type) {
this.type = type;
}
public String getConfig() {
return config;
}
public Cluster config(String config) {
this.config = config;
return this;
}
public void setConfig(String config) {
this.config = config;
}
public String getRemark() {
return remark;
}
public Cluster remark(String remark) {
this.remark = remark;
return this;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getCreatedBy() {
return createdBy;
}
public Cluster createdBy(String createdBy) {
this.createdBy = createdBy;
return this;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public Instant getCreatedDate() {
return createdDate;
}
public Cluster createdDate(Instant createdDate) {
this.createdDate = createdDate;
return this;
}
public void setCreatedDate(Instant createdDate) {
this.createdDate = createdDate;
}
public String getLastModifiedBy() {
return lastModifiedBy;
}
public Cluster lastModifiedBy(String lastModifiedBy) {
this.lastModifiedBy = lastModifiedBy;
return this;
}
public void setLastModifiedBy(String lastModifiedBy) {
this.lastModifiedBy = lastModifiedBy;
}
public Instant getLastModifiedDate() {
return lastModifiedDate;
}
public Cluster lastModifiedDate(Instant lastModifiedDate) {
this.lastModifiedDate = lastModifiedDate;
return this;
}
public void setLastModifiedDate(Instant lastModifiedDate) {
this.lastModifiedDate = lastModifiedDate;
}
public Business getBusiness() {
return business;
}
public Cluster business(Business business) {
this.business = business;
return this;
}
public void setBusiness(Business business) {
this.business = business;
}
public Set<Job> getJobs() {
return jobs;
}
public Cluster jobs(Set<Job> jobs) {
this.jobs = jobs;
return this;
}
public Cluster addJob(Job job) {
this.jobs.add(job);
job.setCluster(this);
return this;
}
public Cluster removeJob(Job job) {
this.jobs.remove(job);
job.setCluster(null);
return this;
}
public void setJobs(Set<Job> jobs) {
this.jobs = jobs;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Cluster)) {
return false;
}
return id != null && id.equals(((Cluster) o).id);
}
@Override
public int hashCode() {
return 31;
}
@Override
public String toString() {
return "Cluster{" +
"id=" + getId() +
", name='" + getName() + "'" +
", type='" + getType() + "'" +
", config='" + getConfig() + "'" +
", remark='" + getRemark() + "'" +
", createdBy='" + getCreatedBy() + "'" +
", createdDate='" + getCreatedDate() + "'" +
", lastModifiedBy='" + getLastModifiedBy() + "'" +
", lastModifiedDate='" + getLastModifiedDate() + "'" +
"}";
}
}
| 2,334 |
1,582 | <filename>tests/test_oauth.py
# encoding: utf-8
from tests.base import TestCase
from webtest import TestApp
import app as M
from vilya.models.api_token import ApiToken
class OAuthTest(TestCase):
def test_login(self):
app = TestApp(M.app)
user_id = 'testuser'
apikey = self._add_api_key()
token = ApiToken.add(apikey.client_id, user_id)
app.get('/',
headers=dict(Authorization="Bearer %s" % token.token),
status=200)
def test_unauthorized_login(self):
app = TestApp(M.app)
r = app.get(
'/', headers=dict(Authorization="Bearer BAD"),
status=202)
| 312 |
2,787 | <filename>src/overview/src/NIOverviewLogger.h
//
// Copyright 2011-2014 NimbusKit
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
extern NSString* const NIOverviewLoggerDidAddDeviceLog;
extern NSString* const NIOverviewLoggerDidAddConsoleLog;
extern NSString* const NIOverviewLoggerDidAddEventLog;
@class NIOverviewDeviceLogEntry;
@class NIOverviewConsoleLogEntry;
@class NIOverviewEventLogEntry;
/**
* The Overview logger.
*
* @ingroup Overview-Logger
*
* This object stores all of the historical information used to draw the graphs in the
* Overview memory and disk pages, as well as the console log page.
*
* The primary log should be accessed by calling [NIOverview @link NIOverview::logger logger@endlink].
*/
@interface NIOverviewLogger : NSObject
#pragma mark Configuration Settings /** @name Configuration Settings */
/**
* The oldest age of a memory or disk log entry.
*
* Log entries older than this number of seconds will be pruned from the log.
*
* By default this is 1 minute.
*/
@property (nonatomic, assign) NSTimeInterval oldestLogAge;
+ (NIOverviewLogger*)sharedLogger;
#pragma mark Adding Log Entries /** @name Adding Log Entries */
/**
* Add a device log.
*
* This method will first prune expired entries and then add the new entry to the log.
*/
- (void)addDeviceLog:(NIOverviewDeviceLogEntry *)logEntry;
/**
* Add a console log.
*
* This method will not prune console log entries.
*/
- (void)addConsoleLog:(NIOverviewConsoleLogEntry *)logEntry;
/**
* Add a event log.
*
* This method will first prune expired entries and then add the new entry to the log.
*/
- (void)addEventLog:(NIOverviewEventLogEntry *)logEntry;
#pragma mark Accessing Logs /** @name Accessing Logs */
/**
* The linked list of device logs.
*
* Log entries are in increasing chronological order.
*/
@property (nonatomic, readonly, strong) NSMutableOrderedSet* deviceLogs;
/**
* The linked list of console logs.
*
* Log entries are in increasing chronological order.
*/
@property (nonatomic, readonly, strong) NSMutableOrderedSet* consoleLogs;
/**
* The linked list of events.
*
* Log entries are in increasing chronological order.
*/
@property (nonatomic, readonly, strong) NSMutableOrderedSet* eventLogs;
@end
/**
* The basic requirements for a log entry.
*
* @ingroup Overview-Logger-Entries
*
* A basic log entry need only define a timestamp in order to be particularly useful.
*/
@interface NIOverviewLogEntry : NSObject
#pragma mark Creating an Entry /** @name Creating an Entry */
/**
* Designated initializer.
*/
- (id)initWithTimestamp:(NSDate *)timestamp;
#pragma mark Entry Information /** @name Entry Information */
/**
* The timestamp for this log entry.
*/
@property (nonatomic, retain) NSDate* timestamp;
@end
/**
* A device log entry.
*
* @ingroup Overview-Logger-Entries
*/
@interface NIOverviewDeviceLogEntry : NIOverviewLogEntry
#pragma mark Entry Information /** @name Entry Information */
/**
* The number of bytes of free memory.
*/
@property (nonatomic, assign) unsigned long long bytesOfFreeMemory;
/**
* The number of bytes of total memory.
*/
@property (nonatomic, assign) unsigned long long bytesOfTotalMemory;
/**
* The number of bytes of free disk space.
*/
@property (nonatomic, assign) unsigned long long bytesOfFreeDiskSpace;
/**
* The number of bytes of total disk space.
*/
@property (nonatomic, assign) unsigned long long bytesOfTotalDiskSpace;
/**
* The battery level.
*/
@property (nonatomic, assign) CGFloat batteryLevel;
/**
* The state of the battery.
*/
@property (nonatomic, assign) UIDeviceBatteryState batteryState;
@end
/**
* A console log entry.
*
* @ingroup Overview-Logger-Entries
*/
@interface NIOverviewConsoleLogEntry : NIOverviewLogEntry
#pragma mark Creating an Entry /** @name Creating an Entry */
/**
* Designated initializer.
*/
- (id)initWithLog:(NSString *)log;
#pragma mark Entry Information /** @name Entry Information */
/**
* The text that was written to the console log.
*/
@property (nonatomic, copy) NSString* log;
@end
typedef enum {
NIOverviewEventDidReceiveMemoryWarning,
} NIOverviewEventType;
/**
* An event log entry.
*
* @ingroup Overview-Logger-Entries
*/
@interface NIOverviewEventLogEntry : NIOverviewLogEntry
#pragma mark Creating an Entry /** @name Creating an Entry */
/**
* Designated initializer.
*/
- (id)initWithType:(NSInteger)type;
#pragma mark Entry Information /** @name Entry Information */
/**
* The type of event.
*/
@property (nonatomic, assign) NSInteger type;
@end
| 1,480 |
1,993 | <filename>brave/src/main/java/brave/propagation/ExtraFieldCustomizer.java
/*
* Copyright 2013-2020 The OpenZipkin 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 brave.propagation;
import brave.baggage.BaggagePropagationCustomizer;
/**
* @since 5.7
* @deprecated Since 5.11 use {@link BaggagePropagationCustomizer}
*/
@Deprecated public interface ExtraFieldCustomizer {
/** Use to avoid comparing against null references */
ExtraFieldCustomizer NOOP = new ExtraFieldCustomizer() {
@Override public void customize(ExtraFieldPropagation.FactoryBuilder builder) {
}
@Override public String toString() {
return "NoopExtraFieldCustomizer{}";
}
};
void customize(ExtraFieldPropagation.FactoryBuilder builder);
}
| 352 |
4,695 | <filename>package.json<gh_stars>1000+
{
"name": "betwixt",
"version": "1.6.1",
"description": "Web Debugging Proxy based on Chrome DevTools Network panel",
"main": "src/main.js",
"scripts": {
"start": "electron src/main.js",
"test": "jshint src/lib/ src/*.js && jscs src/lib/ src/*.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/kdzwinel/betwixt.git"
},
"keywords": [
"traffic",
"proxy",
"mitm",
"devtools"
],
"author": "<NAME>",
"license": "MIT",
"bugs": {
"url": "https://github.com/kdzwinel/betwixt/issues"
},
"homepage": "https://github.com/kdzwinel/betwixt",
"dependencies": {
"chalk": "^1.1.1",
"http-mitm-proxy": "^0.5.0",
"istextorbinary": "^2.0.0",
"minimist": "^1.2.0"
},
"devDependencies": {
"electron-packager": "^6.0.0",
"electron-prebuilt": "^0.36.12",
"jscs": "^2.6.0",
"jshint": "^2.8.0"
}
}
| 457 |
1,467 | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.regions.providers;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.profiles.ProfileFileSystemSetting;
import software.amazon.awssdk.profiles.ProfileProperty;
import software.amazon.awssdk.regions.Region;
/**
* Loads region information from the {@link ProfileFile#defaultProfileFile()} using the default profile name.
*/
@SdkProtectedApi
public final class AwsProfileRegionProvider implements AwsRegionProvider {
private final Supplier<ProfileFile> profileFile;
private final String profileName;
public AwsProfileRegionProvider() {
this(null, null);
}
public AwsProfileRegionProvider(Supplier<ProfileFile> profileFile, String profileName) {
this.profileFile = profileFile != null ? profileFile : ProfileFile::defaultProfileFile;
this.profileName = profileName != null ? profileName : ProfileFileSystemSetting.AWS_PROFILE.getStringValueOrThrow();
}
@Override
public Region getRegion() {
return profileFile.get()
.profile(profileName)
.map(p -> p.properties().get(ProfileProperty.REGION))
.map(Region::of)
.orElseThrow(() -> SdkClientException.builder()
.message("No region provided in profile: " + profileName)
.build());
}
}
| 815 |
590 | <reponame>closeio/graphql-core
from graphql.pyutils import Path
def describe_path():
def add_path():
path = Path(None, 0, None)
assert path.prev is None
assert path.key == 0
prev, path = path, Path(path, 1, None)
assert path.prev is prev
assert path.key == 1
prev, path = path, Path(path, "two", None)
assert path.prev is prev
assert path.key == "two"
def add_key():
prev = Path(None, 0, None)
path = prev.add_key("one")
assert path.prev is prev
assert path.key == "one"
def as_list():
path = Path(None, 1, None)
assert path.as_list() == [1]
path = path.add_key("two")
assert path.as_list() == [1, "two"]
path = path.add_key(3)
assert path.as_list() == [1, "two", 3]
| 390 |
310 | /*
* Copyright (c) 2014-2020, <NAME>, <EMAIL>
* All rights reserved.
*
* Licensed under: MIT Licence
* See LICENSE.TXT included with this code to read the full license agreement.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package org.darisadesigns.polyglotlina.QuizEngine;
import org.darisadesigns.polyglotlina.DictCore;
import org.darisadesigns.polyglotlina.ManagersCollections.DictionaryCollection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map.Entry;
import java.util.Random;
/**
*
* @author draque.thompson
*/
public class Quiz extends DictionaryCollection<QuizQuestion> {
private final DictCore core;
private List<QuizQuestion> quizList = null;
private int quizPos = -1; // start at -1 because initial next() call bumps to 0
private QuizQuestion curQuestion;
public Quiz(DictCore _core) {
super(new QuizQuestion(_core));
core = _core;
}
public int getLength() {
if (quizList == null) {
quizList = new ArrayList<>(nodeMap.values());
}
return quizList.size();
}
/**
* Gets current position within quiz.
* Index begins at 0.
* @return current position
*/
public int getCurQuestion() {
return quizPos;
}
@Override
public void clear() {
bufferNode = new QuizQuestion(core);
}
/**
* Gets list of questions in randomized order
* @return
*/
public QuizQuestion[] getQuestions() {
long seed = System.nanoTime();
List<QuizQuestion> questions = new ArrayList<>(nodeMap.values());
Collections.shuffle(questions, new Random(seed));
return questions.toArray(new QuizQuestion[0]);
}
public int getQuizLength() {
return nodeMap.size();
}
/**
* Gets number of correctly answered questions (even if quiz is not completed)
* @return number of correct answers
*/
public int getNumCorrect() {
int ret = 0;
for (Object o : nodeMap.values().toArray()) {
QuizQuestion question = (QuizQuestion)o;
if (question.getAnswered() == QuizQuestion.Answered.Correct) {
ret++;
}
}
return ret;
}
/**
* Sets test back to non-taken, original status.
*/
public void resetQuiz() {
for (Object o : nodeMap.values().toArray()) {
QuizQuestion question = (QuizQuestion)o;
question.setAnswered(QuizQuestion.Answered.Unanswered);
question.setUserAnswer(null);
}
curQuestion = null;
quizPos = -1;
quizList = null;
}
public void trimQuiz() {
for (Entry<Integer, QuizQuestion> o : nodeMap.entrySet().toArray(new Entry[0])) {
QuizQuestion question = o.getValue();
if (question.getAnswered() == QuizQuestion.Answered.Correct) {
nodeMap.remove(o.getKey());
} else {
question.setAnswered(QuizQuestion.Answered.Unanswered);
question.setUserAnswer(null);
}
}
curQuestion = null;
quizPos = -1;
quizList = null;
}
/**
* Tests whether more questions exist in quiz
* @return true if more questions
*/
public boolean hasNext() {
if (quizList == null) {
quizList = new ArrayList<>(nodeMap.values());
}
int quizSize = quizList.size();
return quizSize > 0 && (quizSize - 1) > quizPos;
}
/**
* Gets next quiz question (if one exists)
* Will throw exception if no
* next question.
*
* @return next quiz question
* @throws java.lang.Exception
*/
public QuizQuestion next() throws Exception {
if (quizList == null) {
quizList = new ArrayList<>(nodeMap.values());
}
quizPos++;
try {
curQuestion = quizList.get(quizPos);
} catch (IndexOutOfBoundsException e) {
// force this to be handled explicitly
throw new Exception(e);
}
return curQuestion;
}
/**
* Gets previous question.Throws null exception if quizList not initialized. Throws out of bounds exception if called while on first question
* @return
* @throws java.lang.Exception
*/
public QuizQuestion prev() throws Exception {
if (quizPos == 0 || quizList == null) {
throw new Exception("You can't call this when on the first entry.");
}
quizPos--;
return quizList.get(quizPos);
}
@Override
public QuizQuestion notFoundNode() {
QuizQuestion emptyQuestion = new QuizQuestion(core);
emptyQuestion.setValue("QUESTION NOT FOUND");
return emptyQuestion;
}
}
| 2,630 |
333 | #ifndef __IRODS_POSTGRES_OBJECT_HPP__
#define __IRODS_POSTGRES_OBJECT_HPP__
// =-=-=-=-=-=-=-
// irods includes
#include "irods_database_object.hpp"
// =-=-=-=-=-=-=-
// boost includes
#include <boost/shared_ptr.hpp>
namespace irods {
// =-=-=-=-=-=-=-
// @brief
const std::string POSTGRES_DATABASE_PLUGIN( "postgres" );
// =-=-=-=-=-=-=-
// @brief postgres object class
class postgres_object : public database_object {
public:
// =-=-=-=-=-=-=-
// Constructors
postgres_object();
postgres_object( const postgres_object& );
// =-=-=-=-=-=-=-
// Destructors
virtual ~postgres_object();
// =-=-=-=-=-=-=-
// Operators
virtual postgres_object& operator=( const postgres_object& );
// =-=-=-=-=-=-=-
/// @brief Comparison operator
virtual bool operator==( const postgres_object& _rhs ) const;
// =-=-=-=-=-=-=-
// plugin resolution operation
virtual error resolve(
const std::string&, // plugin interface
plugin_ptr& ); // resolved plugin
// =-=-=-=-=-=-=-
// accessor for rule engine variables
virtual error get_re_vars( rule_engine_vars_t& );
// =-=-=-=-=-=-=-
// Accessors
// =-=-=-=-=-=-=-
// Mutators
private:
// =-=-=-=-=-=-=-
// Attributes
}; // postgres_object
// =-=-=-=-=-=-=-
// helpful typedef for sock comm interface & factory
typedef boost::shared_ptr< postgres_object > postgres_object_ptr;
}; // namespace irods
#endif // __IRODS_POSTGRES_OBJECT_HPP__
| 780 |
2,151 | <gh_stars>1000+
// Copyright 2018 The Feed Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.android.libraries.feed.piet;
import static com.google.android.libraries.feed.common.testing.RunnableSubject.assertThatRunnable;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
import android.app.Activity;
import android.content.Context;
import android.view.View;
import com.google.android.libraries.feed.piet.CustomElementAdapter.KeySupplier;
import com.google.android.libraries.feed.piet.host.CustomElementProvider;
import com.google.search.now.ui.piet.BindingRefsProto.CustomBindingRef;
import com.google.search.now.ui.piet.ElementsProto.BindingValue;
import com.google.search.now.ui.piet.ElementsProto.BindingValue.Visibility;
import com.google.search.now.ui.piet.ElementsProto.CustomElement;
import com.google.search.now.ui.piet.ElementsProto.CustomElementData;
import com.google.search.now.ui.piet.ElementsProto.Element;
import com.google.search.now.ui.piet.ElementsProto.TextElement;
import com.google.search.now.ui.piet.StylesProto.StyleIdsStack;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
/** Tests of the {@link CustomElementAdapter}. */
@RunWith(RobolectricTestRunner.class)
public class CustomElementAdapterTest {
private static final CustomElementData DUMMY_DATA = CustomElementData.getDefaultInstance();
private static final CustomElement DEFAULT_MODEL =
CustomElement.newBuilder().setCustomElementData(DUMMY_DATA).build();
@Mock private AdapterParameters adapterParameters;
@Mock private FrameContext frameContext;
@Mock private CustomElementProvider customElementProvider;
private Context context;
private View customView;
private CustomElementAdapter adapter;
@Before
public void setUp() throws Exception {
initMocks(this);
context = Robolectric.setupActivity(Activity.class);
customView = new View(context);
when(frameContext.getCustomElementProvider()).thenReturn(customElementProvider);
when(frameContext.bindNewStyle(any(StyleIdsStack.class))).thenReturn(frameContext);
when(frameContext.getCurrentStyle()).thenReturn(StyleProvider.DEFAULT_STYLE_PROVIDER);
when(customElementProvider.createCustomElement(DUMMY_DATA)).thenReturn(customView);
adapter = new KeySupplier().getAdapter(context, adapterParameters);
}
@Test
public void testCreate() {
assertThat(adapter).isNotNull();
}
@Test
public void testCreateAdapter_initializes() {
adapter.createAdapter(DEFAULT_MODEL, frameContext);
assertThat(adapter.getView()).isNotNull();
assertThat(adapter.getKey()).isNotNull();
}
@Test
public void testCreateAdapter_ignoresSubsequentCalls() {
adapter.createAdapter(DEFAULT_MODEL, frameContext);
View adapterView = adapter.getView();
RecyclerKey adapterKey = adapter.getKey();
adapter.createAdapter(DEFAULT_MODEL, frameContext);
assertThat(adapter.getView()).isSameAs(adapterView);
assertThat(adapter.getKey()).isSameAs(adapterKey);
}
@Test
public void testBindModel_data() {
adapter.createAdapter(DEFAULT_MODEL, frameContext);
adapter.bindModel(DEFAULT_MODEL, frameContext);
assertThat(adapter.getBaseView().getChildAt(0)).isEqualTo(customView);
}
@Test
public void testBindModel_binding() {
CustomBindingRef bindingRef = CustomBindingRef.newBuilder().setBindingId("CUSTOM!").build();
when(frameContext.getCustomElementBindingValue(bindingRef))
.thenReturn(BindingValue.newBuilder().setCustomElementData(DUMMY_DATA).build());
CustomElement model = CustomElement.newBuilder().setCustomBinding(bindingRef).build();
adapter.createAdapter(model, frameContext);
adapter.bindModel(model, frameContext);
assertThat(adapter.getBaseView().getChildAt(0)).isEqualTo(customView);
}
@Test
public void testBindModel_noContent() {
adapter.createAdapter(DEFAULT_MODEL, frameContext);
adapter.bindModel(CustomElement.getDefaultInstance(), frameContext);
verifyZeroInteractions(customElementProvider);
assertThat(adapter.getBaseView().getChildCount()).isEqualTo(0);
}
@Test
public void testBindModel_visibilityGone() {
CustomBindingRef bindingRef = CustomBindingRef.newBuilder().setBindingId("CUSTOM!").build();
when(frameContext.getCustomElementBindingValue(bindingRef))
.thenReturn(BindingValue.newBuilder().setVisibility(Visibility.GONE).build());
CustomElement model = CustomElement.newBuilder().setCustomBinding(bindingRef).build();
adapter.createAdapter(model, frameContext);
adapter.bindModel(model, frameContext);
assertThat(adapter.getBaseView().getVisibility()).isEqualTo(View.GONE);
}
@Test
public void testBindModel_optionalAbsent() {
CustomBindingRef bindingRef =
CustomBindingRef.newBuilder().setBindingId("CUSTOM!").setIsOptional(true).build();
when(frameContext.getCustomElementBindingValue(bindingRef))
.thenReturn(BindingValue.getDefaultInstance());
CustomElement model = CustomElement.newBuilder().setCustomBinding(bindingRef).build();
adapter.createAdapter(model, frameContext);
// This should not fail.
adapter.bindModel(model, frameContext);
assertThat(adapter.getView().getVisibility()).isEqualTo(View.GONE);
}
@Test
public void testBindModel_setsVisibility() {
CustomBindingRef customBindingRef =
CustomBindingRef.newBuilder().setBindingId("CUSTOM").build();
CustomElement customElement =
CustomElement.newBuilder().setCustomBinding(customBindingRef).build();
adapter.createAdapter(
CustomElement.newBuilder()
.setCustomElementData(CustomElementData.getDefaultInstance())
.build(),
frameContext);
// Sets visibility on bound value with content
when(frameContext.getCustomElementBindingValue(customBindingRef))
.thenReturn(
BindingValue.newBuilder()
.setCustomElementData(CustomElementData.getDefaultInstance())
.setVisibility(Visibility.INVISIBLE)
.build());
adapter.bindModel(customElement, frameContext);
assertThat(adapter.getBaseView().getVisibility()).isEqualTo(View.INVISIBLE);
adapter.unbindModel();
// Sets visibility for inline content
adapter.bindModel(
CustomElement.newBuilder()
.setCustomElementData(CustomElementData.getDefaultInstance())
.build(),
frameContext);
assertThat(adapter.getBaseView().getVisibility()).isEqualTo(View.VISIBLE);
adapter.unbindModel();
// Sets visibility on GONE binding with no content
when(frameContext.getCustomElementBindingValue(customBindingRef))
.thenReturn(BindingValue.newBuilder().setVisibility(Visibility.GONE).build());
adapter.bindModel(customElement, frameContext);
assertThat(adapter.getBaseView().getVisibility()).isEqualTo(View.GONE);
adapter.unbindModel();
// Sets visibility with VISIBLE binding
when(frameContext.getCustomElementBindingValue(customBindingRef))
.thenReturn(
BindingValue.newBuilder()
.setCustomElementData(CustomElementData.getDefaultInstance())
.setVisibility(Visibility.VISIBLE)
.build());
adapter.bindModel(customElement, frameContext);
assertThat(adapter.getBaseView().getVisibility()).isEqualTo(View.VISIBLE);
}
@Test
public void testBindModel_noContentInBinding() {
CustomBindingRef bindingRef = CustomBindingRef.newBuilder().setBindingId("CUSTOM").build();
when(frameContext.getCustomElementBindingValue(bindingRef))
.thenReturn(BindingValue.newBuilder().setBindingId("CUSTOM").build());
CustomElement model = CustomElement.newBuilder().setCustomBinding(bindingRef).build();
adapter.createAdapter(model, frameContext);
assertThatRunnable(() -> adapter.bindModel(model, frameContext))
.throwsAnExceptionOfType(IllegalArgumentException.class)
.that()
.hasMessageThat()
.contains("Custom element binding CUSTOM had no content");
}
@Test
public void testUnbindModel() {
adapter.createAdapter(DEFAULT_MODEL, frameContext);
adapter.bindModel(DEFAULT_MODEL, frameContext);
adapter.unbindModel();
verify(customElementProvider).releaseCustomView(customView);
assertThat(adapter.getBaseView().getChildCount()).isEqualTo(0);
}
@Test
public void testUnbindModel_noChildren() {
adapter.createAdapter(DEFAULT_MODEL, frameContext);
adapter.unbindModel();
verifyZeroInteractions(customElementProvider);
assertThat(adapter.getBaseView().getChildCount()).isEqualTo(0);
}
@Test
public void testUnbindModel_multipleChildren() {
View customView2 = new View(context);
when(customElementProvider.createCustomElement(DUMMY_DATA))
.thenReturn(customView)
.thenReturn(customView2);
adapter.createAdapter(DEFAULT_MODEL, frameContext);
adapter.bindModel(DEFAULT_MODEL, frameContext);
adapter.bindModel(DEFAULT_MODEL, frameContext);
adapter.unbindModel();
verify(customElementProvider).releaseCustomView(customView);
verify(customElementProvider).releaseCustomView(customView2);
assertThat(adapter.getBaseView().getChildCount()).isEqualTo(0);
}
@Test
public void testGetModelFromElement() {
CustomElement model =
CustomElement.newBuilder()
.setStyleReferences(StyleIdsStack.newBuilder().addStyleIds("custom"))
.build();
Element elementWithModel = Element.newBuilder().setCustomElement(model).build();
assertThat(adapter.getModelFromElement(elementWithModel)).isSameAs(model);
Element elementWithWrongModel =
Element.newBuilder().setTextElement(TextElement.getDefaultInstance()).build();
assertThatRunnable(() -> adapter.getModelFromElement(elementWithWrongModel))
.throwsAnExceptionOfType(IllegalArgumentException.class)
.that()
.hasMessageThat()
.contains("Missing CustomElement");
Element emptyElement = Element.getDefaultInstance();
assertThatRunnable(() -> adapter.getModelFromElement(emptyElement))
.throwsAnExceptionOfType(IllegalArgumentException.class)
.that()
.hasMessageThat()
.contains("Missing CustomElement");
}
}
| 3,732 |
1,570 | <reponame>tonyh-fff/swiftshader<filename>src/System/Memory.cpp<gh_stars>1000+
// Copyright 2016 The SwiftShader Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "Memory.hpp"
#include "Debug.hpp"
#include "Types.hpp"
#if defined(_WIN32)
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# endif
# include <windows.h>
# include <intrin.h>
#else
# include <errno.h>
# include <sys/mman.h>
# include <stdlib.h>
# include <unistd.h>
#endif
#include <cstdlib>
#include <cstring>
#undef allocate
#undef deallocate
#if(defined(__i386__) || defined(_M_IX86) || defined(__x86_64__) || defined(_M_X64)) && !defined(__x86__)
# define __x86__
#endif
// A Clang extension to determine compiler features.
// We use it to detect Sanitizer builds (e.g. -fsanitize=memory).
#ifndef __has_feature
# define __has_feature(x) 0
#endif
namespace sw {
namespace {
struct Allocation
{
// size_t bytes;
unsigned char *block;
};
} // anonymous namespace
size_t memoryPageSize()
{
static int pageSize = [] {
#if defined(_WIN32)
SYSTEM_INFO systemInfo;
GetSystemInfo(&systemInfo);
return systemInfo.dwPageSize;
#else
return sysconf(_SC_PAGESIZE);
#endif
}();
return pageSize;
}
static void *allocate(size_t bytes, size_t alignment, bool clearToZero)
{
ASSERT((alignment & (alignment - 1)) == 0); // Power of 2 alignment.
size_t size = bytes + sizeof(Allocation) + alignment;
unsigned char *block = (unsigned char *)malloc(size);
unsigned char *aligned = nullptr;
if(block)
{
if(clearToZero)
{
memset(block, 0, size);
}
aligned = (unsigned char *)((uintptr_t)(block + sizeof(Allocation) + alignment - 1) & -(intptr_t)alignment);
Allocation *allocation = (Allocation *)(aligned - sizeof(Allocation));
// allocation->bytes = bytes;
allocation->block = block;
}
return aligned;
}
// TODO(b/140991626): Rename to allocate().
void *allocateUninitialized(size_t bytes, size_t alignment)
{
return allocate(bytes, alignment, false);
}
void *allocateZero(size_t bytes, size_t alignment)
{
return allocate(bytes, alignment, true);
}
// This funtion allocates memory that is zero-initialized for security reasons
// only. In MemorySanitizer enabled builds it is left uninitialized.
void *allocateZeroOrPoison(size_t bytes, size_t alignment)
{
return allocate(bytes, alignment, !__has_feature(memory_sanitizer));
}
void freeMemory(void *memory)
{
if(memory)
{
unsigned char *aligned = (unsigned char *)memory;
Allocation *allocation = (Allocation *)(aligned - sizeof(Allocation));
free(allocation->block);
}
}
void clear(uint16_t *memory, uint16_t element, size_t count)
{
#if defined(_MSC_VER) && defined(__x86__) && !defined(MEMORY_SANITIZER)
__stosw(memory, element, count);
#elif defined(__GNUC__) && defined(__x86__) && !defined(MEMORY_SANITIZER)
__asm__ __volatile__("rep stosw"
: "+D"(memory), "+c"(count)
: "a"(element)
: "memory");
#else
for(size_t i = 0; i < count; i++)
{
memory[i] = element;
}
#endif
}
void clear(uint32_t *memory, uint32_t element, size_t count)
{
#if defined(_MSC_VER) && defined(__x86__) && !defined(MEMORY_SANITIZER)
__stosd((unsigned long *)memory, element, count);
#elif defined(__GNUC__) && defined(__x86__) && !defined(MEMORY_SANITIZER)
__asm__ __volatile__("rep stosl"
: "+D"(memory), "+c"(count)
: "a"(element)
: "memory");
#else
for(size_t i = 0; i < count; i++)
{
memory[i] = element;
}
#endif
}
} // namespace sw
| 1,562 |
334 | <reponame>raakasf/moderncpp
#include <algorithm>
#include <array>
#include <chrono>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <memory>
#include <random>
#include <string>
#include <vector>
using namespace std;
void sort_vector(vector<int> &v);
void sort_selection(vector<int> &v);
void sort_selection_std(vector<int> &v);
void sort_insertion(vector<int> &v);
void sort_insertion_std(vector<int> &v);
void sort_merge_sort_std(vector<int> &v);
void sort_quicksort_std(vector<int> &v);
int sort_vector_operations(vector<int> &v);
int search_sequential(const vector<int> &v, const int key);
int search_binary(const vector<int> &v, const int key);
pair<int, int> search_sequential_operations(const vector<int> &v,
const int key);
pair<int, int> search_binary_operations(const vector<int> &v, const int key);
int sort_selection_operations(vector<int> &v);
int sort_insertion_operations(vector<int> &v);
int random_number(int low, int high);
void shuffle_vector(vector<int> &v);
vector<int> create_vector(int n);
int main() {
std::ofstream fout("results.csv");
constexpr bool use_std = true;
// Measure real time
cout << "n\t\tstd\t\tselection_std\t\tinsertion_std\tmerge_sort_std\tquick_"
"sort_std"
<< endl;
fout << "n,std,seletion,insertion,mergesort,quicksort" << endl;
auto increment = [](int i) {
return pow(10, std::max(int(0), int(ceil(log10(i)) - 2)));
};
std::cout << "increment: " << increment(1) << std::endl;
for (int i = 2; i < 100000000; i += increment(i + 1)) {
cout << "n=" << i << "\t";
fout << i << ",";
if (i < 10) {
cout << "\t";
}
vector<int> v = create_vector(i);
vector<int> v1 = v;
auto start = chrono::steady_clock::now();
sort_vector(v1);
auto duration = std::chrono::duration_cast<std::chrono::microseconds>(
chrono::steady_clock::now() - start);
cout << duration.count() << "μs\t\t";
fout << duration.count() << ",";
vector<int> v4 = v;
start = chrono::steady_clock::now();
if constexpr (use_std) {
sort_selection_std(v4);
} else {
sort_selection(v4);
}
duration = std::chrono::duration_cast<std::chrono::microseconds>(
chrono::steady_clock::now() - start);
cout << duration.count() << "μs\t\t";
fout << duration.count() << ",";
vector<int> v5 = v;
start = chrono::steady_clock::now();
if constexpr (use_std) {
sort_insertion_std(v5);
} else {
sort_insertion(v5);
}
duration = std::chrono::duration_cast<std::chrono::microseconds>(
chrono::steady_clock::now() - start);
cout << duration.count() << "μs\t\t";
fout << duration.count() << ",";
vector<int> v6 = v;
start = chrono::steady_clock::now();
sort_merge_sort_std(v6);
duration = std::chrono::duration_cast<std::chrono::microseconds>(
chrono::steady_clock::now() - start);
cout << duration.count() << "μs\t\t";
fout << duration.count() << ",";
vector<int> v7 = v;
start = chrono::steady_clock::now();
sort_quicksort_std(v7);
duration = std::chrono::duration_cast<std::chrono::microseconds>(
chrono::steady_clock::now() - start);
cout << duration.count() << "μs\t\t";
fout << duration.count() << ",";
cout << endl;
fout << endl;
}
cout << "n\t\tstd\t\tselection\t\tinsertion" << endl;
for (int i = 2; i < 100000000; i *= 2) {
cout << "n=" << i << "\t";
if (i < 10) {
cout << "\t";
}
vector<int> v = create_vector(i);
vector<int> v1 = v;
int operations = sort_vector_operations(v1);
cout << operations << "\t\t";
vector<int> v2 = v;
operations = sort_selection_operations(v2);
cout << operations << "\t\t";
vector<int> v3 = v;
operations = sort_insertion_operations(v3);
cout << operations << "\t\t";
cout << endl;
}
return 0;
}
void shuffle_vector(vector<int> &v) {
static random_device r;
static default_random_engine generator(r());
shuffle(v.begin(), v.end(), generator);
}
void sort_vector(vector<int> &v) { sort(v.begin(), v.end()); }
void sort_selection(vector<int> &v) {
// índices para loops
size_t i, j, min;
// elemento para trocas
int x;
// para cada posição
for (i = 0; i < v.size() - 1; i++) {
// procuramos o menor entre i + 1 e n e colocamos em i
// mínimo é o i
min = i;
for (j = i + 1; j < v.size(); j++) {
if (v[j] < v[min]) {
// mínimo é o j
min = j;
}
}
// troca a[i] com a[min]
x = v[min];
v[min] = v[i];
v[i] = x;
}
}
void sort_insertion(vector<int> &v) {
// índices para loops
size_t i;
int j;
// elemento
int x;
// para cada posição a partir de i = 1
for (i = 1; i < v.size(); i++) {
// coloca o elemento a[i] na posição correta
x = v[i];
j = static_cast<int>(i) - 1;
// enquanto há posições válidas e
// elemento a colocar é menor que o corrente
while ((j >= 0) && (x < v[j])) {
v[j + 1] = v[j];
j--;
}
// pega elemento guardado e coloca na posição dele
v[j + 1] = x;
}
}
int sort_vector_operations(vector<int> &v) {
int operations = 0;
auto comp = [&operations](int a, int b) {
++operations;
return a < b;
};
sort(v.begin(), v.end(), comp);
return operations;
}
int sort_selection_operations(vector<int> &v) {
int operations = 0;
// índices para loops
size_t i, j, min;
// elemento para trocas
int x;
// para cada posição
for (i = 0; i < v.size() - 1; i++) {
// procuramos o menor entre i + 1 e n e colocamos em i
// mínimo é o i
min = i;
for (j = i + 1; j < v.size(); j++) {
++operations;
if (v[j] < v[min]) {
// mínimo é o j
min = j;
}
}
// troca a[i] com a[min]
x = v[min];
v[min] = v[i];
v[i] = x;
}
return operations;
}
int sort_insertion_operations(vector<int> &v) {
int operations = 0;
// índices para loops
size_t i;
int j;
// elemento
int x;
// para cada posição a partir de i = 1
for (i = 1; i < v.size(); i++) {
// coloca o elemento a[i] na posição correta
x = v[i];
j = static_cast<int>(i) - 1;
// enquanto há posições válidas e
// elemento a colocar é menor que o corrente
++operations;
while ((j >= 0) && (x < v[j])) {
v[j + 1] = v[j];
j--;
++operations;
}
// pega elemento guardado e coloca na posição dele
v[j + 1] = x;
}
return operations;
}
void sort_selection_std(vector<int> &v) {
for (auto i = v.begin(); i != v.end() - 1; ++i) {
iter_swap(i, min_element(i, v.end()));
}
}
void sort_insertion_std(vector<int> &v) {
for (auto i = v.begin(); i != v.end(); ++i) {
rotate(upper_bound(v.begin(), i, *i), i, i + 1);
}
}
template <typename Iterador> void merge_sort(Iterador start, Iterador fim) {
if (fim - start > 1) {
Iterador meio = start + (fim - start) / 2;
merge_sort(start, meio);
merge_sort(meio, fim);
std::vector<int> intercalado(fim - start);
merge(start, meio, meio, fim, intercalado.begin());
std::copy(intercalado.begin(), intercalado.end(), start);
}
}
void sort_merge_sort_std(vector<int> &v) { merge_sort(v.begin(), v.end()); }
template <typename Iterador>
void in_place_merge_sort(Iterador start, Iterador fim) {
if (fim - start > 1) {
Iterador meio = start + (fim - start) / 2;
in_place_merge_sort(start, meio);
in_place_merge_sort(meio, fim);
inplace_merge(start, meio, fim);
}
}
void sort_in_place_merge_sort_std(vector<int> &v) {
in_place_merge_sort(v.begin(), v.end());
}
// helper function for median of three
template <typename T> T median(T t1, T t2, T t3) {
if (t1 < t2) {
if (t2 < t3)
return t2;
else if (t1 < t3)
return t3;
else
return t1;
} else {
if (t1 < t3)
return t1;
else if (t2 < t3)
return t3;
else
return t2;
}
}
// Helper object to get <= from <
template <typename Order>
struct non_strict_op {
explicit non_strict_op(Order o) : order(o) {}
bool operator()(typename Order::second_argument_type arg1,
typename Order::first_argument_type arg2) const {
return !order(arg2, arg1);
}
private:
Order order;
};
template <typename Order> non_strict_op<Order> non_strict(Order o) {
return non_strict_op<Order>(o);
}
template <typename RandomAccessIterator, typename Order>
void quicksort(RandomAccessIterator first, RandomAccessIterator last,
Order order) {
if (first != last && first + 1 != last) {
typedef typename std::iterator_traits<RandomAccessIterator>::value_type
value_type;
RandomAccessIterator mid = first + (last - first) / 2;
value_type pivot = median(*first, *mid, *(last - 1));
RandomAccessIterator split1 = std::partition(
first, last, std::bind(order, std::placeholders::_1, pivot));
RandomAccessIterator split2 = std::partition(
split1, last,
std::bind(non_strict(order), std::placeholders::_1, pivot));
quicksort(first, split1, order);
quicksort(split2, last, order);
}
}
template <typename RandomAccessIterator>
void quicksort(RandomAccessIterator first, RandomAccessIterator last) {
quicksort(
first, last,
std::less<
typename std::iterator_traits<RandomAccessIterator>::value_type>());
}
void sort_quicksort_std(vector<int> &v) { quicksort(v.begin(), v.end()); }
int random_number(int low, int high) {
static random_device r;
static default_random_engine generator(r());
uniform_int_distribution<int> ud(low, high);
return ud(generator);
}
vector<int> create_vector(int n) {
vector<int> v(n);
for (int i = 0; i < n; ++i) {
v[i] = i;
}
shuffle_vector(v);
return v;
}
int search_sequential(const vector<int> &v, const int key) {
for (size_t i = 0; i < v.size(); ++i) {
if (v[i] == key) {
return i;
}
}
return -1;
}
int search_binary(const vector<int> &v, const int key) {
int left = 0;
int right = v.size() - 1;
int i;
do {
i = (left + right) / 2;
if (v[i] < key) {
left = i + 1;
} else {
right = i - 1;
}
} while (v[i] != key && left <= right);
if (v[i] == key) {
return i;
} else {
return -1;
}
}
pair<int, int> search_sequential_operations(const vector<int> &v,
const int key) {
int operations = 0;
for (size_t i = 0; i < v.size(); ++i) {
operations++;
if (v[i] == key) {
return {i, operations};
}
operations++;
}
return {-1, operations};
}
pair<int, int> search_binary_operations(const vector<int> &v, const int key) {
int left = 0;
int right = v.size() - 1;
int i;
int operations = 0;
do {
i = (left + right) / 2;
operations++;
if (v[i] < key) {
left = i + 1;
} else {
right = i - 1;
}
operations++;
} while (v[i] != key && left <= right);
operations++;
if (v[i] == key) {
return {i, operations};
} else {
return {-1, operations};
}
}
| 5,932 |
605 | <gh_stars>100-1000
#ifndef H7_H
#define H7_H
extern "C++" {
class A {};
}
class B : public A {};
#endif
| 54 |
310 | package com.propertycross.mgwt.properties;
import static com.google.gwt.safehtml.shared.UriUtils.fromString;
import com.google.gwt.safehtml.shared.SafeUri;
public final class Property {
private final String guid;
private final String title;
private final String price;
private final String formattedPrice;
private final String bedBathroomText;
private final String bedrooms;
private final String bathrooms;
private final String type;
private final SafeUri imgUrl;
private final String summary;
public Property(String guid, String title, String price, String bedrooms,
String bathrooms, String type, String imgUrl, String summary)
{
this.guid = guid;
this.title = title;
this.price = price;
formattedPrice = formatPrice(price);
bedBathroomText = createBedBathroomText(bedrooms, bathrooms);
this.bedrooms = bedrooms;
this.bathrooms = bathrooms;
this.type = type;
this.imgUrl = fromString(imgUrl);
this.summary = summary;
}
public String id()
{
return guid;
}
public String type()
{
return type;
}
public String bathrooms()
{
return bathrooms;
}
public String bedrooms()
{
return bedrooms;
}
public String bedBathroomText()
{
return bedBathroomText;
}
public String summary()
{
return summary;
}
public SafeUri imgUrl()
{
return imgUrl;
}
public String price()
{
return price;
}
public String formattedPrice()
{
return formattedPrice;
}
private String formatPrice(String price)
{
String[] s = price.split(" ");
return "£" + s[0];
}
private String createBedBathroomText(String bedrooms, String bathrooms) {
return bedrooms + " bed, " + bathrooms + " bathroom";
}
public String title()
{
return title;
}
@Override
public int hashCode()
{
int hash = 3;
hash = 83 * hash + (guid != null ? guid.hashCode() : 0);
hash = 83 * hash + (title != null ? title.hashCode() : 0);
hash = 83 * hash + (price != null ? price.hashCode() : 0);
hash = 83 * hash + (bedrooms != null ? bedrooms.hashCode() : 0);
hash = 83 * hash + (bathrooms != null ? bathrooms.hashCode() : 0);
hash = 83 * hash + (type != null ? type.hashCode() : 0);
hash = 83 * hash + (imgUrl != null ? imgUrl.hashCode() : 0);
hash = 83 * hash + (summary != null ? summary.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object obj)
{
if(obj == null) return false;
if(getClass() != obj.getClass()) return false;
Property o = (Property)obj;
if((guid == null) ? (o.guid != null) : !guid.equals(o.guid)) {
return false;
}
if((title == null) ? (o.title != null) : !title.equals(o.title)) {
return false;
}
if((price == null) ? (o.price != null) : !price.equals(o.price)) {
return false;
}
if((bedrooms == null) ? (o.bedrooms != null)
: !bedrooms.equals(o.bedrooms)) return false;
if((bathrooms == null) ? (o.bathrooms != null)
: !bathrooms.equals(o.bathrooms)) return false;
if((type == null) ? (o.type != null) : !type.equals(o.type)) {
return false;
}
if(imgUrl != o.imgUrl && (imgUrl == null || !imgUrl.equals(o.imgUrl))) {
return false;
}
if((summary == null) ? (o.summary != null)
: !summary.equals(o.summary)) return false;
return true;
}
@Override
public String toString()
{
return "Property{" + "guid=" + guid + ", title=" + title + ", price=" +
price + ", bedrooms=" + bedrooms + ", bathrooms=" + bathrooms +
", type=" + type + ", imgUrl=" + imgUrl + ", summary=" +
summary + '}';
}
}
| 1,761 |
17,085 | /* Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#ifdef PADDLE_WITH_XPU
#include "paddle/fluid/operators/load_op.h"
namespace ops = paddle::operators;
REGISTER_OP_XPU_KERNEL(
load, ops::LoadOpKernel<paddle::platform::XPUDeviceContext, float>,
ops::LoadOpKernel<paddle::platform::XPUDeviceContext, double>,
ops::LoadOpKernel<paddle::platform::XPUDeviceContext, int>,
ops::LoadOpKernel<paddle::platform::XPUDeviceContext, int8_t>,
ops::LoadOpKernel<paddle::platform::XPUDeviceContext, int64_t>);
#endif // PADDLE_WITH_XPU
| 349 |
348 | <reponame>chamberone/Leaflet.PixiOverlay
{"nom":"Villeneuve","circ":"11ème circonscription","dpt":"Gironde","inscrits":325,"abs":164,"votants":161,"blancs":13,"nuls":1,"exp":147,"res":[{"nuance":"REM","nom":"<NAME>","voix":81},{"nuance":"FN","nom":"<NAME>","voix":66}]} | 108 |
340 | <filename>include/eve/detail/function/simd/common/compress_store_swizzle_mask_num.hpp
//==================================================================================================
/*
EVE - Expressive Vector Engine
Copyright : EVE Contributors & Maintainers
SPDX-License-Identifier: MIT
*/
//==================================================================================================
#pragma once
#include <eve/detail/top_bits.hpp>
#include <eve/function/convert.hpp>
#include <eve/function/count_true.hpp>
#include <utility>
namespace eve::detail
{
template<eve::relative_conditional_expr C, typename T>
EVE_FORCEINLINE std::pair<int, int>
compress_store_swizzle_mask_num_(EVE_SUPPORTS(cpu_), C c, logical<wide<T, fixed<4>>> mask)
{
using w_t = wide<T, fixed<4>>;
using l_t = logical<wide<T>>;
// can only be for 64 bit numbers on 128 bit register
if constexpr (has_aggregated_abi_v<w_t>)
{
return compress_store_swizzle_mask_num(c, convert(mask, as<logical<std::uint32_t>>{}));
}
else
{
static_assert(top_bits<l_t>::bits_per_element == 1);
int mmask = top_bits{mask, c}.as_int();
return {(mmask & 7), std::popcount(static_cast<std::uint32_t>(mmask))};
}
}
template<typename T>
EVE_FORCEINLINE std::pair<int, int>
compress_store_swizzle_mask_num_(EVE_SUPPORTS(cpu_), logical<wide<T, fixed<8>>> mask)
{
int sum = 0;
sum += mask.get(0);
sum += mask.get(1);
sum += 3 * mask.get(2);
sum += 3 * mask.get(3);
sum += 9 * mask.get(4);
sum += 9 * mask.get(5);
return std::pair{sum, eve::count_true(mask)};
}
template<typename T>
EVE_FORCEINLINE auto
compress_store_swizzle_mask_num_(EVE_SUPPORTS(cpu_), logical<wide<T, fixed<16>>> mask)
{
auto [l, h] = mask.slice();
auto [l_num, l_count] = compress_store_swizzle_mask_num(l);
auto [h_num, h_count] = compress_store_swizzle_mask_num(h);
struct res {
int l_num;
int l_count;
int h_num;
int h_count;
};
return res{l_num, l_count, h_num, h_count};
}
}
| 827 |
1,204 | <filename>unit-tests/src/test/java/com/gs/collections/impl/collection/mutable/CollectionAdapterAsUnmodifiableTest.java
/*
* Copyright 2014 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gs.collections.impl.collection.mutable;
import java.util.ArrayList;
import java.util.List;
import com.gs.collections.api.collection.MutableCollection;
import com.gs.collections.api.partition.PartitionMutableCollection;
import com.gs.collections.impl.block.factory.Functions;
import com.gs.collections.impl.block.factory.Functions2;
import org.junit.Assert;
import org.junit.Test;
public class CollectionAdapterAsUnmodifiableTest extends UnmodifiableMutableCollectionTestCase<Integer>
{
@Override
protected MutableCollection<Integer> getCollection()
{
List<Integer> list = new ArrayList<>();
list.add(1);
return new CollectionAdapter<>(list).asUnmodifiable();
}
@Override
@Test
public void select()
{
Assert.assertEquals(this.getCollection().toList(), this.getCollection().select(ignored -> true));
Assert.assertNotEquals(this.getCollection().toList(), this.getCollection().select(ignored -> false));
}
@Override
@Test
public void selectWith()
{
Assert.assertEquals(this.getCollection().toList(), this.getCollection().selectWith((ignored1, ignored2) -> true, null));
Assert.assertNotEquals(this.getCollection().toList(), this.getCollection().selectWith((ignored1, ignored2) -> false, null));
}
@Override
@Test
public void reject()
{
Assert.assertEquals(this.getCollection().toList(), this.getCollection().reject(ignored1 -> false));
Assert.assertNotEquals(this.getCollection().toList(), this.getCollection().reject(ignored -> true));
}
@Override
@Test
public void rejectWith()
{
Assert.assertEquals(this.getCollection().toList(), this.getCollection().rejectWith((ignored11, ignored21) -> false, null));
Assert.assertNotEquals(this.getCollection().toList(), this.getCollection().rejectWith((ignored1, ignored2) -> true, null));
}
@Override
@Test
public void partition()
{
PartitionMutableCollection<?> partition = this.getCollection().partition(ignored -> true);
Assert.assertEquals(this.getCollection().toList(), partition.getSelected());
Assert.assertNotEquals(this.getCollection().toList(), partition.getRejected());
}
@Override
@Test
public void partitionWith()
{
PartitionMutableCollection<?> partition = this.getCollection().partitionWith((ignored1, ignored2) -> true, null);
Assert.assertEquals(this.getCollection().toList(), partition.getSelected());
Assert.assertNotEquals(this.getCollection().toList(), partition.getRejected());
}
@Override
@Test
public void collect()
{
Assert.assertEquals(this.getCollection().toList(), this.getCollection().collect(Functions.getPassThru()));
Assert.assertNotEquals(this.getCollection().toList(), this.getCollection().collect(Object::getClass));
}
@Override
@Test
public void collectWith()
{
Assert.assertEquals(this.getCollection().toList(), this.getCollection().collectWith(Functions2.fromFunction(Functions.getPassThru()), null));
Assert.assertNotEquals(this.getCollection().toList(), this.getCollection().collectWith(Functions2.fromFunction(Object::getClass), null));
}
@Override
@Test
public void collectIf()
{
Assert.assertEquals(this.getCollection().toList(), this.getCollection().collectIf(ignored -> true, Functions.getPassThru()));
Assert.assertNotEquals(this.getCollection().toList(), this.getCollection().collectIf(ignored -> false, Object::getClass));
}
}
| 1,471 |
1,056 | <filename>enterprise/web.core.syntax/src/org/netbeans/modules/web/core/syntax/completion/JspCompletionQuery.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.web.core.syntax.completion;
import java.io.File;
import java.net.URI;
import org.netbeans.modules.web.core.syntax.completion.api.JspCompletionItem;
import java.util.*;
import javax.swing.text.JTextComponent;
import javax.swing.text.BadLocationException;
import javax.servlet.jsp.tagext.TagInfo;
import javax.servlet.jsp.tagext.TagAttributeInfo;
import org.netbeans.api.jsp.lexer.JspTokenId;
import org.netbeans.api.lexer.Token;
import org.netbeans.api.lexer.TokenHierarchy;
import org.netbeans.api.lexer.TokenSequence;
import org.netbeans.editor.*;
import org.netbeans.lib.editor.util.CharSequenceUtilities;
import org.netbeans.modules.web.core.syntax.deprecated.JspTagTokenContext;
import org.netbeans.modules.web.core.syntax.*;
import org.netbeans.modules.web.core.syntax.tld.TldLibrary;
import org.netbeans.spi.editor.completion.CompletionItem;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.filesystems.JarFileSystem;
import org.openide.util.Exceptions;
/**
* JSP completion support finder
*
* @author <NAME>
* @author <NAME>
* @author <EMAIL>
*/
public class JspCompletionQuery {
private static final String JSP_COMMENT_END_DELIMITER = "--%>"; //NOI18N
private static final List<String> JSP_DELIMITERS = Arrays.asList(new String[]{"<%", "<%=", "<%!", "<%--"}); //NOI18N
private static final JspCompletionQuery JSP_COMPLETION_QUERY = new JspCompletionQuery();
static JspCompletionQuery instance() {
return JSP_COMPLETION_QUERY;
}
void query(CompletionResultSet<? extends CompletionItem> result,
JTextComponent component, int offset) {
BaseDocument doc = (BaseDocument)component.getDocument();
JspSyntaxSupport sup = JspSyntaxSupport.get(doc);
doc.readLock();
try {
SyntaxElement elem = sup.getElementChain( offset );
if (elem == null)
// this is a legal option, when I don't have anything to say just return null
return;
//do not use SyntaxElements for determining comments, it doesn't work well
TokenHierarchy<?> th = TokenHierarchy.get(doc);
TokenSequence<JspTokenId> ts = th.tokenSequence(JspTokenId.language());
ts.move(offset);
if (ts.moveNext() || ts.movePrevious()) {
if (ts.token().id() == JspTokenId.COMMENT ||
(ts.token().id() == JspTokenId.EOL && ts.movePrevious()
&& ts.token().id() == JspTokenId.COMMENT))
{
queryJspCommentContent(result, offset, doc);
}
}
switch (elem.getCompletionContext()) {
// TAG COMPLETION
case JspSyntaxSupport.TAG_COMPLETION_CONTEXT :
queryJspTag(result, component, offset, sup,
(SyntaxElement.Tag)elem);
break;
// ENDTAG COMPLETION
case JspSyntaxSupport.ENDTAG_COMPLETION_CONTEXT :
queryJspEndTag(result, component, offset, sup);
break;
//DIRECTIVE COMPLETION IN JSP SCRIPTLET (<%| should offer <%@taglib etc.)
case JspSyntaxSupport.SCRIPTINGL_COMPLETION_CONTEXT:
queryJspDirectiveInScriptlet(result, offset, sup);
//query for jsp delimiters
queryJspDelimitersInScriptlet(result, offset, sup);
break;
// DIRECTIVE COMPLETION
case JspSyntaxSupport.DIRECTIVE_COMPLETION_CONTEXT :
queryJspDirective(result, component, offset, sup,
(SyntaxElement.Directive)elem, doc);
break;
// CONTENT LANGUAGE
case JspSyntaxSupport.CONTENTL_COMPLETION_CONTEXT :
// JSP tags results
queryJspTagInContent(result, offset, sup, doc);
// JSP directive results
queryJspDirectiveInContent(result, component, offset, sup, doc);
//query for jsp delimiters
queryJspDelimitersInContent(result, offset, sup);
break;
}
} catch (BadLocationException e) {
Exceptions.printStackTrace(e);
} finally {
doc.readUnlock();
}
}
private void queryJspTag(CompletionResultSet result, JTextComponent component, int offset,
JspSyntaxSupport sup, SyntaxElement.Tag elem) throws BadLocationException {
// find the current item
TokenItem item = sup.getItemAtOrBefore(offset);
if (item == null) {
return ;
}
TokenID id = item.getTokenID();
String tokenPart = item.getImage().substring(0, offset - item.getOffset());
String token = item.getImage().trim();
int anchor = -1;
// SYMBOL
if (id == JspTagTokenContext.SYMBOL) {
if (tokenPart.equals("<")) { // NOI18N
// just after the beginning of the tag
anchor = offset;
addTagPrefixItems(result, anchor, sup, sup.getTagPrefixes("")); // NOI18N
}
if (tokenPart.endsWith("\"")) { // NOI18N
// try an attribute value
String attrName = findAttributeForValue(sup, item);
if (attrName != null) {
AttributeValueSupport attSup =
AttributeValueSupport.getSupport(true, elem.getName(), attrName);
if (attSup != null) {
attSup.result(result, component, offset, sup, elem, ""); // NOI18N
}
}
}
if(tokenPart.endsWith(">") && !tokenPart.endsWith("/>")) {
CompletionItem autocompletedEndTag = sup.getAutocompletedEndTag(offset);
if (autocompletedEndTag != null) {
result.addItem(autocompletedEndTag);
}
}
}
// TAG
if (id == JspTagTokenContext.TAG
|| id == JspTagTokenContext.WHITESPACE
|| id == JspTagTokenContext.EOL) {
// inside a JSP tag name
if (isBlank(tokenPart.charAt(tokenPart.length() - 1))
|| tokenPart.equals("\n")) {
// blank character - do attribute completion
anchor = offset;
addAttributeItems(result, anchor, sup, elem, sup.getTagAttributes(elem.getName(), ""), null); // NOI18N
} else {
int colonIndex = tokenPart.indexOf(":"); // NOI18N
anchor = offset - tokenPart.length();
if (colonIndex == -1) {
addTagPrefixItems(result, anchor, sup, sup.getTagPrefixes(tokenPart));
} else {
String prefix = tokenPart.substring(0, colonIndex);
addTagPrefixItems(result, anchor, sup, prefix, sup.getTags(tokenPart), elem);
}
}
}
// ATTRIBUTE
if (id == JspTagTokenContext.ATTRIBUTE) {
// inside or after an attribute
if (isBlank(tokenPart.charAt(tokenPart.length() - 1))) {
// blank character - do attribute completion
anchor = offset;
addAttributeItems(result, anchor, sup, elem, sup.getTagAttributes(elem.getName(), ""), null); // NOI18N
} else {
anchor = offset - tokenPart.length();
addAttributeItems(result, anchor , sup, elem, sup.getTagAttributes(elem.getName(), tokenPart), token);
}
}
// ATTRIBUTE VALUE
if (id == JspTagTokenContext.ATTR_VALUE) {
// inside or after an attribute
String valuePart = tokenPart.trim();
//return empty completion if the CC is not invoked inside a quotations
if(valuePart.length() == 0) {
return;
}
item = item.getPrevious();
while ((item != null) && (item.getTokenID() == JspTagTokenContext.ATTR_VALUE)) {
valuePart = item.getImage() + valuePart;
item = item.getPrevious();
}
// get rid of the first quote
valuePart = valuePart.substring(1);
String attrName = findAttributeForValue(sup, item);
if (attrName != null) {
AttributeValueSupport attSup =
AttributeValueSupport.getSupport(true, elem.getName(), attrName);
if (attSup != null) {
attSup.result(result, component, offset, sup, elem, valuePart);
}
}
}
if(anchor != -1) {
result.setAnchorOffset(anchor);
}
}
private void queryJspEndTag(CompletionResultSet result, JTextComponent component, int offset, JspSyntaxSupport sup) throws BadLocationException {
// find the current item
TokenItem item = sup.getItemAtOrBefore(offset);
if (item == null) {
return;
}
String tokenPart = item.getImage().substring(0, offset - item.getOffset());
int anchor = offset - tokenPart.length();
result.setAnchorOffset(anchor);
result.addAllItems(sup.getPossibleEndTags(offset, anchor, tokenPart));
}
/** Gets a list of JSP directives which can be completed just after <% in java scriptlet context */
private void queryJspDirectiveInScriptlet(CompletionResultSet result, int offset, JspSyntaxSupport sup) throws BadLocationException {
TokenItem item = sup.getItemAtOrBefore(offset);
if (item == null) {
return;
}
TokenID id = item.getTokenID();
String tokenPart = item.getImage().substring(0, offset - item.getOffset());
if(id == JspTagTokenContext.SYMBOL2 && tokenPart.equals("<%")) {
addDirectiveItems(result, offset - tokenPart.length(), (List<TagInfo>)sup.getDirectives("")); // NOI18N
}
}
private void queryJspDelimitersInScriptlet(CompletionResultSet result, int offset, JspSyntaxSupport sup) throws BadLocationException {
TokenItem item = sup.getItemAtOrBefore(offset);
if (item == null) {
return;
}
TokenID id = item.getTokenID();
String image = item.getImage();
int tokenPartLen = offset - item.getOffset();
String tokenPart = item.getImage().substring(0, tokenPartLen <= image.length() ? tokenPartLen : image.length());
if(id == JspTagTokenContext.SYMBOL2 && tokenPart.startsWith("<%")) {
addDelimiterItems(result, offset - tokenPart.length(), tokenPart); // NOI18N
}
}
private void queryJspDelimitersInContent(CompletionResultSet result, int offset, JspSyntaxSupport sup) throws BadLocationException {
TokenItem item = sup.getItemAtOrBefore(offset);
if (item == null) {
return;
}
String image = item.getImage();
int tokenPartLen = offset - item.getOffset();
String tokenPart = item.getImage().substring(0, tokenPartLen <= image.length() ? tokenPartLen : image.length());
if(tokenPart.startsWith("<")) {
addDelimiterItems(result, offset - tokenPart.length(), tokenPart); // NOI18N
}
}
private void queryJspDirective(CompletionResultSet result, JTextComponent component, int offset, JspSyntaxSupport sup,
SyntaxElement.Directive elem, BaseDocument doc) throws BadLocationException {
// find the current item
TokenItem item = sup.getItemAtOrBefore(offset);
if (item == null) {
return;
}
TokenID id = item.getTokenID();
String tokenPart = item.getImage().substring(0, offset - item.getOffset());
String token = item.getImage().trim();
// SYMBOL
if (id.getNumericID() == JspTagTokenContext.SYMBOL_ID) {
if (tokenPart.startsWith("<")) { // NOI18N
//calculate a position of the potential replacement
int removeLength = tokenPart.length();
addDirectiveItems(result, offset - removeLength, sup.getDirectives("")); // NOI18N
}
if (tokenPart.endsWith("\"")) { // NOI18N
// try an attribute value
String attrName = findAttributeForValue(sup, item);
if (attrName != null) {
AttributeValueSupport attSup =
AttributeValueSupport.getSupport(false, elem.getName(), attrName);
if (attSup != null) {
attSup.result(result, component, offset, sup, elem, ""); // NOI18N
}
}
}
}
// DIRECTIVE
if (id.getNumericID() == JspTagTokenContext.TAG_ID
|| id.getNumericID() == JspTagTokenContext.WHITESPACE_ID
|| id.getNumericID() == JspTagTokenContext.EOL_ID) {
// inside a JSP directive name or after a whitespace
if (isBlank(tokenPart.charAt(tokenPart.length() - 1))
|| tokenPart.equals("\n")) {
TokenItem prevItem = item.getPrevious();
TokenID prevId = prevItem.getTokenID();
String prevToken = prevItem.getImage().trim();
if (prevId.getNumericID() == JspTagTokenContext.TAG_ID
|| prevId.getNumericID() == JspTagTokenContext.ATTR_VALUE_ID
|| prevId.getNumericID() == JspTagTokenContext.WHITESPACE_ID
|| prevId.getNumericID() == JspTagTokenContext.EOL_ID) {
// blank character - do attribute completion
addAttributeItems(result, offset, sup, elem, sup.getDirectiveAttributes(elem.getName(), ""), null); // NOI18N
} else if (prevId.getNumericID() == JspTagTokenContext.SYMBOL_ID && prevToken.equals("<%@")) { // NOI18N
// just after the beginning of the directive
int removeLength = tokenPart.length() + "<%@".length(); //NOI18N
addDirectiveItems(result, offset - removeLength, sup.getDirectives("")); // NOI18N
}
} else {
boolean add = true;
//I need to get the whitespace token length before the tag name
int whitespaceLength = 0;
TokenItem prevItem = item.getPrevious();
TokenID prevId = prevItem.getTokenID();
//test whether there is a space before the currently completed tagname
if(prevId.getNumericID() == JspTagTokenContext.TAG_ID && "".equals(prevItem.getImage().trim())) //try to trim the token image - just for sure since I am not absolutely sure if the TAG_ID is only for whitespaces in this case.
whitespaceLength = prevItem.getImage().length();
List<TagInfo> list = (List<TagInfo>)sup.getDirectives(tokenPart);
if (list.size() == 1){
TagInfo directive = list.get(0);
//is the cc invoce just after the directive?
if (directive.getTagName().equalsIgnoreCase(tokenPart)) {
add = false;
}
}
if (add){
int removeLength = whitespaceLength + tokenPart.length() + "<%@".length();
addDirectiveItems(result, offset - removeLength, list);
}
}
}
// ATTRIBUTE
if (id.getNumericID() == JspTagTokenContext.ATTRIBUTE_ID) {
// inside or after an attribute
if (isBlank(tokenPart.charAt(tokenPart.length() - 1))) {
// blank character - do attribute completion
addAttributeItems(result, offset, sup, elem, sup.getDirectiveAttributes(elem.getName(), ""), null); // NOI18N
} else {
int removeLength = tokenPart.length();
addAttributeItems(result, offset - removeLength, sup, elem, sup.getDirectiveAttributes(elem.getName(), tokenPart), token);
}
}
// ATTRIBUTE VALUE
if (id.getNumericID() == JspTagTokenContext.ATTR_VALUE_ID) {
// inside or after an attribute
String valuePart = tokenPart;
item = item.getPrevious();
while ((item != null) && (item.getTokenID().getNumericID() == JspTagTokenContext.ATTR_VALUE_ID
|| item.getTokenID().getNumericID() == JspTagTokenContext.EOL_ID)) {
valuePart = item.getImage() + valuePart;
item = item.getPrevious();
}
// get rid of the first quote
valuePart = valuePart.substring(1);
String attrName = findAttributeForValue(sup, item);
if (attrName != null) {
AttributeValueSupport attSup =
AttributeValueSupport.getSupport(false, elem.getName(), attrName);
//we cannot set substitute offset for file cc items
if (attSup != null) {
attSup.result(result, component, offset, sup, elem, valuePart); // NOI18N
}
}
}
}
private void queryJspTagInContent(CompletionResultSet result, int offset, JspSyntaxSupport sup, final BaseDocument doc) throws BadLocationException {
// find the current item
TokenItem item = sup.getItemAtOrBefore(offset);
if (item == null) {
return;
}
String tokenPart = item.getImage().substring(0,
(offset - item.getOffset()) >= item.getImage().length() ? item.getImage().length() : offset - item.getOffset());
int ltIndex = tokenPart.lastIndexOf('<');
if (ltIndex != -1) {
tokenPart = tokenPart.substring(ltIndex + 1);
}
while (ltIndex == -1) {
item = item.getPrevious();
if (item == null) {
return;
}
String newImage = item.getImage();
ltIndex = newImage.lastIndexOf('<');
if (ltIndex != -1)
tokenPart = newImage.substring(ltIndex + 1) + tokenPart;
else {
tokenPart = newImage + tokenPart;
}
if (tokenPart.length() > 20) {
//huh, what the hell is that? I belive it should be > 42 ;-)
return;
}
}
// we found ltIndex, tokenPart is either the part of the token we are looking for
// or '/' + what we are looking for
int removeLength = tokenPart.length();
if (tokenPart.startsWith("/")) { // NOI18N
tokenPart = tokenPart.substring(1);
int anchor = offset - removeLength + 1;
result.setAnchorOffset(anchor);
result.addAllItems(sup.getPossibleEndTags(offset, anchor, tokenPart, true)); //get only first end tag
} else {
int semiColonPos = tokenPart.indexOf(':');
if (semiColonPos >= 0){
Map tagLibMappings = sup.getTagLibraryMappings();
if (tagLibMappings != null) {
int anchor = offset - tokenPart.length();
String prefix = tokenPart.substring(0, semiColonPos);
String tagNamePrefix = tokenPart.substring(semiColonPos + 1);
String uri = StandardTagLibraryPrefixes.get(prefix);
Object v = tagLibMappings.get(uri);
if (v instanceof String[]) {
String[] vals = (String[]) v;
String jarPath = vals[0];
String tldPath = vals[1];
String FILE_PREFIX = "file:/"; //NOI18N
File f;
if (jarPath.startsWith(FILE_PREFIX)) {
URI u = URI.create(jarPath);
f = new File(u);
} else {
f = new File(jarPath);
}
try {
JarFileSystem jfs = new JarFileSystem(FileUtil.normalizeFile(f));
FileObject tldFile = jfs.getRoot().getFileObject(tldPath);
TldLibrary tldLib = TldLibrary.create(tldFile);
for (String tagName : tldLib.getTags().keySet()) {
if (tagName.startsWith(tagNamePrefix)) {
result.addItem(new JspCompletionItem.UnresolvedPrefixTag(prefix + ":" + tagName,
anchor, uri, prefix));
}
}
} catch (Exception ex) {
Exceptions.printStackTrace(ex);
}
}
}
} else {
int anchor = offset - removeLength;
result.setAnchorOffset(anchor);
addTagPrefixItems(result, anchor, sup, sup.getTagPrefixes(tokenPart));
}
}
}
private void queryJspDirectiveInContent(CompletionResultSet result, JTextComponent component, int offset, JspSyntaxSupport sup, BaseDocument doc) throws BadLocationException {
// find the current item
TokenItem item = sup.getItemAtOrBefore(offset);
if (item == null) {
//return empty completion result
return;
}
String tokenPart = item.getImage().substring(0,
(offset - item.getOffset()) >= item.getImage().length() ? item.getImage().length() : offset - item.getOffset());
if(!tokenPart.equals("<") && !tokenPart.equals("<%")) { // NOI18N
//return empty completion result
return ;
}
addDirectiveItems(result, offset - tokenPart.length(), sup.getDirectives("")); // NOI18N
}
private void queryJspCommentContent(CompletionResultSet result, int offset, BaseDocument doc) throws BadLocationException {
// find the current item
TokenHierarchy th = TokenHierarchy.get(doc);
TokenSequence<JspTokenId> ts = th.tokenSequence(JspTokenId.language());
int diff = ts.move(offset);
boolean boundary = diff == 0 && ts.movePrevious();
if(boundary /* use previous token if on boundary */ || ts.moveNext() || ts.movePrevious()) {
Token t = ts.token();
if(boundary) {
diff = t.length();
}
assert t != null;
assert t.id() == JspTokenId.COMMENT || t.id() == JspTokenId.EOL;
CharSequence pretext = t.text().subSequence(Math.max(0, diff - 3), diff);
int match = postfixMatch(pretext, JSP_COMMENT_END_DELIMITER);
if(match > 0 && match < JSP_COMMENT_END_DELIMITER.length()) { //do not complete the end delimiter without any prefix
result.addItem(JspCompletionItem.createDelimiter(JSP_COMMENT_END_DELIMITER, offset - match));
}
}
}
/**
* Returns number of identical characters of the given postfix with the end of the source text
* postfixMatch("abc", "x") == 0;
* postfixMatch("abc", "a") == 0;
* postfixMatch("abc", "c") == 1;
* postfixMatch("abc", "bc") == 2;
* postfixMatch("abc", "abc") == 3;
*
* @param text source text
* @param postfix postfix we try to match
* @return length of the match
*/
int postfixMatch(CharSequence text, CharSequence postfix) {
if (text.length() > postfix.length()) {
//limit the searched text size according to the postfix
text = text.subSequence(text.length() - postfix.length(), text.length());
}
int match = 0;
for (int i = text.length() - 1; i >= 0; i--) {
CharSequence subtext = text.subSequence(i, text.length());
CharSequence subpattern = postfix.subSequence(0, subtext.length());
if (CharSequenceUtilities.equals(subtext, subpattern)) {
match = subtext.length();
}
}
return match;
}
private boolean isBlank(char c) {
return c == ' ';
}
/** Finds an attribute name, assuming that the item is either
* SYMBOL after the attribute name or ATTR_VALUE after this attribute name.
* May return null if nothing found.
*/
protected String findAttributeForValue(JspSyntaxSupport sup, TokenItem item) {
// get before any ATTR_VALUE
while ((item != null) && (item.getTokenID().getNumericID() == JspTagTokenContext.ATTR_VALUE_ID))
item = item.getPrevious();
// now collect the symbols
String symbols = ""; // NOI18N
while ((item != null) && (item.getTokenID().getNumericID() == JspTagTokenContext.SYMBOL_ID)) {
symbols = item.getImage() + symbols;
item = item.getPrevious();
}
// two quotes at the end are not allowed
if (!sup.isValueBeginning(symbols))
return null;
String attributeName = ""; // NOI18N
//there may be a whitespace before the equals sign - trace over the whitespace
//due to a bug in jsp tag syntax parser the whitespace has tag-directive tokenID
//so I need to use the token image to recognize whether it is a whitespace
while ((item != null) && (item.getImage().trim().length() == 0)) {
item = item.getPrevious();
}
//now there should be either tag name or attribute name
while ((item != null) && (item.getTokenID().getNumericID() == JspTagTokenContext.ATTRIBUTE_ID)) {
attributeName = item.getImage() + attributeName;
item = item.getPrevious();
}
if (attributeName.trim().length() > 0)
return attributeName.trim();
return null;
}
/** Adds to the list of items <code>compItemList</code> new TagPrefix items with prefix
* <code>prefix</code> for list of tag names <code>tagStringItems</code>.
* @param set - <code>SyntaxElement.Tag</code>
*/
private void addTagPrefixItems(CompletionResultSet result, int anchor, JspSyntaxSupport sup, String prefix, List tagStringItems, SyntaxElement.Tag set) {
for (int i = 0; i < tagStringItems.size(); i++) {
Object item = tagStringItems.get(i);
if (item instanceof TagInfo)
result.addItem(JspCompletionItem.createPrefixTag(prefix, anchor, (TagInfo)item, set));
else
result.addItem(JspCompletionItem.createPrefixTag(prefix + ":" + (String)item, anchor)); // NOI18N
}
}
/** Adds to the list of items <code>compItemList</code> new TagPrefix items for prefix list
* <code>prefixStringItems</code>, followed by all possible tags for the given prefixes.
*/
private void addTagPrefixItems(CompletionResultSet result, int anchor, JspSyntaxSupport sup, List<Object> prefixStringItems) {
for (int i = 0; i < prefixStringItems.size(); i++) {
String prefix = (String)prefixStringItems.get(i);
// now get tags for this prefix
List tags = sup.getTags(prefix, ""); // NOI18N
for (int j = 0; j < tags.size(); j++) {
Object item = tags.get(j);
if (item instanceof TagInfo)
result.addItem(JspCompletionItem.createPrefixTag(prefix, anchor, (TagInfo)item));
else
result.addItem(JspCompletionItem.createPrefixTag(prefix + ":" + (String)item, anchor)); // NOI18N
}
}
}
/** Adds to the list of items <code>compItemList</code> new TagPrefix items with prefix
* <code>prefix</code> for list of tag names <code>tagStringItems</code>.
*/
private void addDirectiveItems(CompletionResultSet result, int anchor, List<TagInfo> directiveStringItems) {
for (int i = 0; i < directiveStringItems.size(); i++) {
TagInfo item = directiveStringItems.get(i);
result.addItem(JspCompletionItem.createDirective( item.getTagName(), anchor, item));
}
}
private void addDelimiterItems(CompletionResultSet result, int anchor, String prefix) {
for(String delimiter : JSP_DELIMITERS) {
if(delimiter.startsWith(prefix)) {
result.addItem(JspCompletionItem.createDelimiter(delimiter, anchor));
}
}
}
/** Adds to the list of items <code>compItemList</code> new Attribute items.
* Only those which are not already in tagDir
* @param sup the syntax support
* @param compItemList list to add to
* @param tagDir tag or directive element
* @param attributeItems list of strings containing suitable values (String or TagAttributeInfo)
* @param currentAttr current attribute, may be null
*/
private void addAttributeItems(CompletionResultSet result, int offset, JspSyntaxSupport sup,
SyntaxElement.TagDirective tagDir, List attributeItems, String currentAttr) {
for (int i = 0; i < attributeItems.size(); i++) {
Object item = attributeItems.get(i);
String attr;
if (item instanceof TagAttributeInfo)
attr = ((TagAttributeInfo)item).getName();
else
attr = (String)item;
boolean isThere = tagDir.getAttributes().keySet().contains(attr);
if (!isThere || attr.equalsIgnoreCase(currentAttr) ||
(currentAttr != null && attr.startsWith(currentAttr) && attr.length()>currentAttr.length() && !isThere)) {
if (item instanceof TagAttributeInfo)
//XXX This is hack for fixing issue #45302 - CC is to aggressive.
//The definition of the tag and declaration doesn't allow
//define something like "prefix [uri | tagdir]". In the future
//it should be rewritten definition of declaration, which allow
//to do it.
if ("taglib".equalsIgnoreCase(tagDir.getName())){ //NOI18N
if (attr.equalsIgnoreCase("prefix") //NOI18N
|| (attr.equalsIgnoreCase("uri") && !tagDir.getAttributes().keySet().contains("tagdir")) //NOI18N
|| (attr.equalsIgnoreCase("tagdir") && !tagDir.getAttributes().keySet().contains("uri"))) //NOI18N
result.addItem(JspCompletionItem.createAttribute(offset, (TagAttributeInfo)item));
} else {
result.addItem(JspCompletionItem.createAttribute(offset, (TagAttributeInfo)item));
} else
result.addItem(JspCompletionItem.createAttribute((String)item, offset));
}
}
}
public static class CompletionResultSet<T extends CompletionItem> {
private List<T> items;
private int anchor;
public CompletionResultSet() {
items = new ArrayList<T>();
anchor = -1;
}
public int getAnchor() {
return anchor;
}
public List<? extends CompletionItem> getItems() {
return items;
}
public void setAnchorOffset(int anchor) {
this.anchor = anchor;
}
public void addItem(T item) {
items.add(item);
}
public void addAllItems(Collection<T> items) {
this.items.addAll(items);
}
}
}
| 15,645 |
401 | <filename>qmlfrontend/game_view.h
#ifndef GAMEVIEW_H
#define GAMEVIEW_H
#include <QQuickItem>
#include <QPointer>
#include <QScopedPointer>
#include <QtGui/QOpenGLFunctions>
#include <QtGui/QOpenGLShaderProgram>
#include "engine_instance.h"
class GameViewRenderer : public QObject, protected QOpenGLFunctions {
Q_OBJECT
public:
explicit GameViewRenderer();
~GameViewRenderer() override;
void tick(quint32 delta);
void setEngineInstance(EngineInstance* engineInstance);
public slots:
void paint();
void onViewportSizeChanged(QQuickWindow* window);
private:
quint32 m_delta;
QPointer<EngineInstance> m_engineInstance;
};
class GameView : public QQuickItem {
Q_OBJECT
Q_PROPERTY(EngineInstance* engineInstance READ engineInstance WRITE
setEngineInstance NOTIFY engineInstanceChanged)
public:
explicit GameView(QQuickItem* parent = nullptr);
Q_INVOKABLE void tick(quint32 delta);
EngineInstance* engineInstance() const;
signals:
void engineInstanceChanged(EngineInstance* engineInstance);
public slots:
void sync();
void cleanup();
void setEngineInstance(EngineInstance* engineInstance);
private slots:
void handleWindowChanged(QQuickWindow* win);
private:
quint32 m_delta;
QScopedPointer<GameViewRenderer> m_renderer;
bool m_windowChanged;
QPointer<EngineInstance> m_engineInstance;
QSize m_viewportSize;
QPoint m_centerPoint;
};
#endif // GAMEVIEW_H
| 474 |
5,607 | <reponame>kfowler/micronaut-core
/*
* Copyright 2017-2020 original authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.micronaut.http.server.cors;
import io.micronaut.core.convert.ArgumentConversionContext;
import io.micronaut.core.convert.ConversionContext;
import io.micronaut.core.convert.TypeConverter;
import io.micronaut.core.convert.value.ConvertibleValues;
import io.micronaut.core.convert.value.ConvertibleValuesMap;
import io.micronaut.core.type.Argument;
import io.micronaut.http.HttpMethod;
import jakarta.inject.Singleton;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* Responsible for converting a map of configuration to an instance of {@link CorsOriginConfiguration}.
*
* @author <NAME>
* @author <NAME>
* @since 1.0
*/
@Singleton
public class CorsOriginConverter implements TypeConverter<Map<String, Object>, CorsOriginConfiguration> {
private static final String ALLOWED_ORIGINS = "allowed-origins";
private static final String ALLOWED_METHODS = "allowed-methods";
private static final String ALLOWED_HEADERS = "allowed-headers";
private static final String EXPOSED_HEADERS = "exposed-headers";
private static final String ALLOW_CREDENTIALS = "allow-credentials";
private static final String MAX_AGE = "max-age";
private static final ArgumentConversionContext<List<HttpMethod>> CONVERSION_CONTEXT_LIST_OF_HTTP_METHOD = ConversionContext.of(Argument.listOf(HttpMethod.class));
@Override
public Optional<CorsOriginConfiguration> convert(Map<String, Object> object, Class<CorsOriginConfiguration> targetType, ConversionContext context) {
CorsOriginConfiguration configuration = new CorsOriginConfiguration();
ConvertibleValues<Object> convertibleValues = new ConvertibleValuesMap<>(object);
convertibleValues
.get(ALLOWED_ORIGINS, ConversionContext.LIST_OF_STRING)
.ifPresent(configuration::setAllowedOrigins);
convertibleValues
.get(ALLOWED_METHODS, CONVERSION_CONTEXT_LIST_OF_HTTP_METHOD)
.ifPresent(configuration::setAllowedMethods);
convertibleValues
.get(ALLOWED_HEADERS, ConversionContext.LIST_OF_STRING)
.ifPresent(configuration::setAllowedHeaders);
convertibleValues
.get(EXPOSED_HEADERS, ConversionContext.LIST_OF_STRING)
.ifPresent(configuration::setExposedHeaders);
convertibleValues
.get(ALLOW_CREDENTIALS, ConversionContext.BOOLEAN)
.ifPresent(configuration::setAllowCredentials);
convertibleValues
.get(MAX_AGE, ConversionContext.LONG)
.ifPresent(configuration::setMaxAge);
return Optional.of(configuration);
}
}
| 1,097 |
5,079 | from __future__ import absolute_import, unicode_literals
import pytest
from case import Mock, patch
from celery.bin.migrate import migrate
from celery.five import WhateverIO
class test_migrate:
@patch('celery.contrib.migrate.migrate_tasks')
def test_run(self, migrate_tasks):
out = WhateverIO()
m = migrate(app=self.app, stdout=out, stderr=WhateverIO())
with pytest.raises(TypeError):
m.run()
migrate_tasks.assert_not_called()
m.run('memory://foo', 'memory://bar')
migrate_tasks.assert_called()
state = Mock()
state.count = 10
state.strtotal = 30
m.on_migrate_task(state, {'task': 'tasks.add', 'id': 'ID'}, None)
assert '10/30' in out.getvalue()
| 325 |
370 | <gh_stars>100-1000
#!/usr/bin/python
import pcbmode.config as config
from . import messages as msg
from .module import Module
class Board():
"""
"""
def __init__(self):
self._module_dict = config.brd
self._module_routing = config.rte
module = Module(self._module_dict,
self._module_routing)
| 154 |
32,544 | <reponame>DBatOWL/tutorials<filename>persistence-modules/hibernate-exceptions/src/test/java/com/baeldung/hibernate/entitynotfoundexception/EntityNotFoundExceptionIntegrationTest.java
package com.baeldung.hibernate.entitynotfoundexception;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityNotFoundException;
import javax.persistence.Persistence;
import java.io.IOException;
public class EntityNotFoundExceptionIntegrationTest {
private static EntityManager entityManager;
@Before
public void setUp() throws IOException {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("com.baeldung.hibernate.entitynotfoundexception.h2_persistence_unit");
entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();
}
@Test(expected = EntityNotFoundException.class)
public void givenNonExistingUserId_whenGetReferenceIsUsed_thenExceptionIsThrown() {
User user = entityManager.getReference(User.class, 1L);
user.getName();
}
@Test(expected = EntityNotFoundException.class)
public void givenItem_whenManyToOneEntityIsMissing_thenExceptionIsThrown() {
entityManager.createNativeQuery("Insert into Item (category_id, name, id) values (1, 'test', 1)").executeUpdate();
entityManager.flush();
Item item = entityManager.find(Item.class, 1L);
item.getCategory().getName();
}
@After
public void tearDown() {
entityManager.close();
}
}
| 562 |
2,576 | <filename>eventsourcing/src/main/java/org/axonframework/eventsourcing/AbstractSnapshotTrigger.java
package org.axonframework.eventsourcing;
import java.io.Serializable;
import org.axonframework.eventhandling.DomainEventMessage;
import org.axonframework.eventhandling.EventMessage;
import org.axonframework.messaging.unitofwork.CurrentUnitOfWork;
/**
* Abstract implementation of the {@link org.axonframework.eventsourcing.SnapshotTrigger} that schedules snapshots on
* the Unit of Work. Actual logic when to schedule a snapshot should be provided by a subclass.
*
* @author <NAME>
* @since 4.4.4
*/
public abstract class AbstractSnapshotTrigger implements SnapshotTrigger, Serializable {
private static final long serialVersionUID = 4129616856823136473L;
private transient Snapshotter snapshotter;
private Class<?> aggregateType;
private boolean initialized;
/**
* Instantiate a {@link AbstractSnapshotTrigger} based on the {@link Snapshotter} and aggregateType {@link Class<?>}.
*
* @param snapshotter the {@link Snapshotter} for scheduling snapshots
* @param aggregateType the {@link Class<?> of the aggregate that is creating a snapshot}
*/
protected AbstractSnapshotTrigger(Snapshotter snapshotter, Class<?> aggregateType) {
this.snapshotter = snapshotter;
this.aggregateType = aggregateType;
this.initialized = false;
}
@Override
public void eventHandled(EventMessage<?> msg) {
if (msg instanceof DomainEventMessage && exceedsThreshold()) {
prepareSnapshotScheduling((DomainEventMessage<?>) msg);
reset();
}
}
@Override
public void initializationFinished() {
initialized = true;
}
private void prepareSnapshotScheduling(DomainEventMessage<?> eventMessage) {
if (CurrentUnitOfWork.isStarted()) {
if (initialized) {
CurrentUnitOfWork.get().onPrepareCommit(
u -> scheduleSnapshot(eventMessage));
} else {
CurrentUnitOfWork.get().onCleanup(
u -> scheduleSnapshot(eventMessage));
}
} else {
scheduleSnapshot(eventMessage);
}
}
private void scheduleSnapshot(DomainEventMessage<?> eventMessage) {
snapshotter.scheduleSnapshot(aggregateType, eventMessage.getAggregateIdentifier());
}
/**
* Sets the snapshotter
*
* @param snapshotter The {@link Snapshotter} for scheduling snapshots.
*/
public void setSnapshotter(Snapshotter snapshotter) {
this.snapshotter = snapshotter;
}
/**
* This method is used to determine if a new snapshot should be created
* @return true if the threshold has been exceeded
*/
protected abstract boolean exceedsThreshold();
/**
* This method is used to reset all the variables that are used to check if a threshold has been exceeded
*/
protected abstract void reset();
}
| 1,052 |
8,428 | # third party
from sqlalchemy import Column
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import String
# relative
from . import Base
class BinObjDataset(Base):
__tablename__ = "bin_obj_dataset"
id = Column(Integer(), primary_key=True, autoincrement=True)
name = Column(String(256))
obj = Column(String(256), ForeignKey("bin_object.id", ondelete="CASCADE"))
dataset = Column(String(256), ForeignKey("dataset.id", ondelete="CASCADE"))
dtype = Column(String(256))
shape = Column(String(256))
| 187 |
1,253 | <gh_stars>1000+
#include<stdio.h>
int a[1000000];
void merge(int low, int mid, int high){
int n1=mid-low+1;
int n2=high-mid;
int i,j,k;
int left[1000000],right[1000000];
for(i=0;i<n1;i++)
left[i]=a[low+i];
for(i=0;i<n2;i++)
right[i]=a[mid+1+i];
i=0,j=0,k=low;
while(i<n1 && j<n2){
if(left[i]<=right[j]){
a[k++]=left[i++];
}
else{
a[k++]=right[j++];
}
}
while(i<n1)
a[k++]=left[i++];
while(j<n2)
a[k++]=right[j++];
}
void sort(int low, int high){
int mid;
//mid = (low+high)/2;
if(low<high){
mid = (low+high)/2;
sort(low,mid);
sort(mid+1,high);
merge(low,mid,high);
}
}
int main(){
int n,len;
int i=0;
while(scanf("%d",&n)!=EOF){
a[i++]=n;
}
len=i;
//printf("%d\n",i);
//for(i=0;i<len;i++)
// printf("%d ", a[i]);
//printf("\n");
sort(0,len-1);
for(i=0;i<len;i++){
printf("%d ",a[i]);
}
printf("\n");
return 0;
}
| 517 |
356 | <reponame>majk1/netbeans-mmd-plugin
/*
* Copyright 2015-2018 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.igormaznitsa.mindmap.swing.panel;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.anyBoolean;
import static org.mockito.Mockito.anyDouble;
import static org.mockito.Mockito.anyFloat;
import static org.mockito.Mockito.anyInt;
import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.igormaznitsa.mindmap.swing.panel.utils.KeyShortcut;
import java.awt.Color;
import java.awt.Font;
import java.util.HashMap;
import java.util.Map;
import java.util.prefs.Preferences;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
public class MindMapPanelConfigTest {
@Test
public void testHasDifferenceInParameters_NoDifference() {
final MindMapPanelConfig one = new MindMapPanelConfig();
final MindMapPanelConfig two = new MindMapPanelConfig();
assertFalse(one.hasDifferenceInParameters(two));
}
@Test
public void testHasDifferenceInParameters_DifferenceInBoolean() {
final MindMapPanelConfig one = new MindMapPanelConfig();
final MindMapPanelConfig two = new MindMapPanelConfig();
one.setDropShadow(!two.isDropShadow());
assertTrue(one.hasDifferenceInParameters(two));
}
@Test
public void testHasDifferenceInParameters_DifferenceInKeyShortcuts() {
final MindMapPanelConfig one = new MindMapPanelConfig();
final MindMapPanelConfig two = new MindMapPanelConfig();
one.setKeyShortCut(new KeyShortcut(MindMapPanelConfig.KEY_ADD_CHILD_AND_START_EDIT, Integer.MAX_VALUE, Integer.MIN_VALUE));
assertTrue(one.hasDifferenceInParameters(two));
}
@Test
public void testHasDifferenceInParameters_DifferenceInFloat() {
final MindMapPanelConfig one = new MindMapPanelConfig();
final MindMapPanelConfig two = new MindMapPanelConfig();
one.setCollapsatorBorderWidth(two.getCollapsatorBorderWidth() + 0.001f);
assertTrue(one.hasDifferenceInParameters(two));
}
@Test
public void testHasDifferenceInParameters_DifferenceInInt() {
final MindMapPanelConfig one = new MindMapPanelConfig();
final MindMapPanelConfig two = new MindMapPanelConfig();
one.setCollapsatorSize(two.getCollapsatorSize() + 1);
assertTrue(one.hasDifferenceInParameters(two));
}
@Test
public void testHasDifferenceInParameters_DifferenceInColor() {
final MindMapPanelConfig one = new MindMapPanelConfig();
final MindMapPanelConfig two = new MindMapPanelConfig();
one.setCollapsatorBackgroundColor(new Color(two.getCollapsatorBackgroundColor().getRGB() ^ 0xFFFFFFFF));
assertTrue(one.hasDifferenceInParameters(two));
}
@Test
public void testHasDifferenceInParameters_DifferenceInFont() {
final MindMapPanelConfig one = new MindMapPanelConfig();
final MindMapPanelConfig two = new MindMapPanelConfig();
one.setFont(two.getFont().deriveFont(17));
assertTrue(one.hasDifferenceInParameters(two));
}
@Test
public void testHasDifferenceInParameters_DifferenceInDouble() {
final MindMapPanelConfig one = new MindMapPanelConfig();
final MindMapPanelConfig two = new MindMapPanelConfig();
one.setScale(two.getScale() + 0.00001d);
assertTrue(one.hasDifferenceInParameters(two));
}
@Test
public void testSaveRestoreState() {
final Map<String, Object> storage = new HashMap<>();
final Preferences prefs = mock(Preferences.class);
doAnswer(new Answer() {
@Override
public Object answer(final InvocationOnMock invocation) throws Throwable {
final String key = invocation.getArgument(0);
final String value = invocation.getArgument(1);
storage.put(key, value);
return null;
}
}).when(prefs).put(anyString(), anyString());
doAnswer(new Answer() {
@Override
public Object answer(final InvocationOnMock invocation) throws Throwable {
final String key = invocation.getArgument(0);
final Integer value = invocation.getArgument(1);
storage.put(key, value);
return null;
}
}).when(prefs).putInt(anyString(), anyInt());
doAnswer(new Answer() {
@Override
public Object answer(final InvocationOnMock invocation) throws Throwable {
final String key = invocation.getArgument(0);
final Boolean value = invocation.getArgument(1);
storage.put(key, value);
return null;
}
}).when(prefs).putBoolean(anyString(), anyBoolean());
doAnswer(new Answer() {
@Override
public Object answer(final InvocationOnMock invocation) throws Throwable {
final String key = invocation.getArgument(0);
final Float value = invocation.getArgument(1);
storage.put(key, value);
return null;
}
}).when(prefs).putFloat(anyString(), anyFloat());
doAnswer(new Answer() {
@Override
public Object answer(final InvocationOnMock invocation) throws Throwable {
final String key = invocation.getArgument(0);
final Double value = invocation.getArgument(1);
storage.put(key, value);
return null;
}
}).when(prefs).putDouble(anyString(), anyDouble());
when(prefs.get(anyString(), anyString())).thenAnswer(new Answer<String>() {
@Override
public String answer(InvocationOnMock invocation) throws Throwable {
final String key = invocation.getArgument(0);
final String def = invocation.getArgument(1);
return storage.containsKey(key) ? (String) storage.get(key) : def;
}
});
when(prefs.getBoolean(anyString(), anyBoolean())).thenAnswer(new Answer<Boolean>() {
@Override
public Boolean answer(InvocationOnMock invocation) throws Throwable {
final String key = invocation.getArgument(0);
final Boolean def = invocation.getArgument(1);
return storage.containsKey(key) ? (Boolean) storage.get(key) : def;
}
});
when(prefs.getInt(anyString(), anyInt())).thenAnswer(new Answer<Integer>() {
@Override
public Integer answer(InvocationOnMock invocation) throws Throwable {
final String key = invocation.getArgument(0);
final Integer def = invocation.getArgument(1);
return storage.containsKey(key) ? (Integer) storage.get(key) : def;
}
});
when(prefs.getFloat(anyString(), anyFloat())).thenAnswer(new Answer<Float>() {
@Override
public Float answer(InvocationOnMock invocation) throws Throwable {
final String key = invocation.getArgument(0);
final Float def = invocation.getArgument(1);
return storage.containsKey(key) ? (Float) storage.get(key) : def;
}
});
when(prefs.getDouble(anyString(), anyDouble())).thenAnswer(new Answer<Double>() {
@Override
public Double answer(InvocationOnMock invocation) throws Throwable {
final String key = invocation.getArgument(0);
final Double def = invocation.getArgument(1);
return storage.containsKey(key) ? (Double) storage.get(key) : def;
}
});
try {
when(prefs.keys()).thenAnswer(new Answer<String[]>() {
@Override
public String[] answer(final InvocationOnMock invocation) throws Throwable {
return storage.keySet().toArray(new String[0]);
}
});
} catch (Exception ex) {
fail("Unexpected exception");
}
final MindMapPanelConfig config = new MindMapPanelConfig();
config.setScale(100.5d);
config.setGridColor(Color.orange);
config.setShowGrid(false);
config.setFont(new Font("Helvetica", Font.ITALIC, 36));
config.setKeyShortCut(new KeyShortcut("testShortCut", 1234, 5678));
config.saveTo(prefs);
assertFalse(storage.isEmpty());
final MindMapPanelConfig newConfig = new MindMapPanelConfig();
newConfig.loadFrom(prefs);
assertFalse(newConfig.isShowGrid());
assertEquals(Color.orange, newConfig.getGridColor());
assertEquals(new Font("Helvetica", Font.ITALIC, 36), newConfig.getFont());
assertEquals(100.5d, newConfig.getScale(), 0.0d);
final KeyShortcut shortCut = newConfig.getKeyShortCut("testShortCut");
assertNotNull(shortCut);
assertEquals("testShortCut", shortCut.getID());
assertEquals(1234, shortCut.getKeyCode());
assertEquals(5678, shortCut.getModifiers());
storage.clear();
newConfig.loadFrom(prefs);
final MindMapPanelConfig etalon = new MindMapPanelConfig();
assertEquals(etalon.isShowGrid(), newConfig.isShowGrid());
assertEquals(etalon.getGridColor(), newConfig.getGridColor());
assertEquals(etalon.getFont(), newConfig.getFont());
assertEquals(etalon.getScale(), newConfig.getScale(), 0.0d);
assertNull(newConfig.getKeyShortCut("testShortCut"));
assertNotNull(newConfig.getKeyShortCut(MindMapPanelConfig.KEY_ADD_CHILD_AND_START_EDIT));
}
}
| 3,407 |
777 | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "extensions/browser/extension_registry_factory.h"
#include "extensions/browser/process_manager.h"
#include "extensions/browser/process_manager_factory.h"
using content::BrowserContext;
namespace extensions {
// static
ProcessManager* ProcessManagerFactory::GetForBrowserContext(
BrowserContext* context) {
return static_cast<ProcessManager*>(
GetInstance()->GetServiceForBrowserContext(context, true));
}
// static
ProcessManager* ProcessManagerFactory::GetForBrowserContextIfExists(
BrowserContext* context) {
return static_cast<ProcessManager*>(
GetInstance()->GetServiceForBrowserContext(context, false));
}
// static
ProcessManagerFactory* ProcessManagerFactory::GetInstance() {
return base::Singleton<ProcessManagerFactory>::get();
}
ProcessManagerFactory::ProcessManagerFactory()
: BrowserContextKeyedServiceFactory(
"ProcessManager",
BrowserContextDependencyManager::GetInstance()) {
DependsOn(extensions::ExtensionRegistryFactory::GetInstance());
}
ProcessManagerFactory::~ProcessManagerFactory() {
}
KeyedService* ProcessManagerFactory::BuildServiceInstanceFor(
BrowserContext* context) const {
return ProcessManager::Create(context);
}
BrowserContext* ProcessManagerFactory::GetBrowserContextToUse(
BrowserContext* context) const {
// ProcessManager::Create handles guest and incognito profiles, returning an
// IncognitoProcessManager in incognito mode.
return context;
}
} // namespace extensions
| 491 |
6,931 | import numpy as np
from statsmodels.base.model import Results
import statsmodels.base.wrapper as wrap
from statsmodels.tools.decorators import cache_readonly
"""
Elastic net regularization.
Routines for fitting regression models using elastic net
regularization. The elastic net minimizes the objective function
-llf / nobs + alpha((1 - L1_wt) * sum(params**2) / 2 +
L1_wt * sum(abs(params)))
The algorithm implemented here closely follows the implementation in
the R glmnet package, documented here:
http://cran.r-project.org/web/packages/glmnet/index.html
and here:
http://www.jstatsoft.org/v33/i01/paper
This routine should work for any regression model that implements
loglike, score, and hess.
"""
def _gen_npfuncs(k, L1_wt, alpha, loglike_kwds, score_kwds, hess_kwds):
"""
Negative penalized log-likelihood functions.
Returns the negative penalized log-likelihood, its derivative, and
its Hessian. The penalty only includes the smooth (L2) term.
All three functions have argument signature (x, model), where
``x`` is a point in the parameter space and ``model`` is an
arbitrary statsmodels regression model.
"""
def nploglike(params, model):
nobs = model.nobs
pen_llf = alpha[k] * (1 - L1_wt) * np.sum(params**2) / 2
llf = model.loglike(np.r_[params], **loglike_kwds)
return - llf / nobs + pen_llf
def npscore(params, model):
nobs = model.nobs
pen_grad = alpha[k] * (1 - L1_wt) * params
gr = -model.score(np.r_[params], **score_kwds)[0] / nobs
return gr + pen_grad
def nphess(params, model):
nobs = model.nobs
pen_hess = alpha[k] * (1 - L1_wt)
h = -model.hessian(np.r_[params], **hess_kwds)[0, 0] / nobs + pen_hess
return h
return nploglike, npscore, nphess
def fit_elasticnet(model, method="coord_descent", maxiter=100,
alpha=0., L1_wt=1., start_params=None, cnvrg_tol=1e-7,
zero_tol=1e-8, refit=False, check_step=True,
loglike_kwds=None, score_kwds=None, hess_kwds=None):
"""
Return an elastic net regularized fit to a regression model.
Parameters
----------
model : model object
A statsmodels object implementing ``loglike``, ``score``, and
``hessian``.
method : {'coord_descent'}
Only the coordinate descent algorithm is implemented.
maxiter : int
The maximum number of iteration cycles (an iteration cycle
involves running coordinate descent on all variables).
alpha : scalar or array_like
The penalty weight. If a scalar, the same penalty weight
applies to all variables in the model. If a vector, it
must have the same length as `params`, and contains a
penalty weight for each coefficient.
L1_wt : scalar
The fraction of the penalty given to the L1 penalty term.
Must be between 0 and 1 (inclusive). If 0, the fit is
a ridge fit, if 1 it is a lasso fit.
start_params : array_like
Starting values for `params`.
cnvrg_tol : scalar
If `params` changes by less than this amount (in sup-norm)
in one iteration cycle, the algorithm terminates with
convergence.
zero_tol : scalar
Any estimated coefficient smaller than this value is
replaced with zero.
refit : bool
If True, the model is refit using only the variables that have
non-zero coefficients in the regularized fit. The refitted
model is not regularized.
check_step : bool
If True, confirm that the first step is an improvement and search
further if it is not.
loglike_kwds : dict-like or None
Keyword arguments for the log-likelihood function.
score_kwds : dict-like or None
Keyword arguments for the score function.
hess_kwds : dict-like or None
Keyword arguments for the Hessian function.
Returns
-------
Results
A results object.
Notes
-----
The ``elastic net`` penalty is a combination of L1 and L2
penalties.
The function that is minimized is:
-loglike/n + alpha*((1-L1_wt)*|params|_2^2/2 + L1_wt*|params|_1)
where |*|_1 and |*|_2 are the L1 and L2 norms.
The computational approach used here is to obtain a quadratic
approximation to the smooth part of the target function:
-loglike/n + alpha*(1-L1_wt)*|params|_2^2/2
then repeatedly optimize the L1 penalized version of this function
along coordinate axes.
"""
k_exog = model.exog.shape[1]
loglike_kwds = {} if loglike_kwds is None else loglike_kwds
score_kwds = {} if score_kwds is None else score_kwds
hess_kwds = {} if hess_kwds is None else hess_kwds
if np.isscalar(alpha):
alpha = alpha * np.ones(k_exog)
# Define starting params
if start_params is None:
params = np.zeros(k_exog)
else:
params = start_params.copy()
btol = 1e-4
params_zero = np.zeros(len(params), dtype=bool)
init_args = model._get_init_kwds()
# we do not need a copy of init_args b/c get_init_kwds provides new dict
init_args['hasconst'] = False
model_offset = init_args.pop('offset', None)
if 'exposure' in init_args and init_args['exposure'] is not None:
if model_offset is None:
model_offset = np.log(init_args.pop('exposure'))
else:
model_offset += np.log(init_args.pop('exposure'))
fgh_list = [
_gen_npfuncs(k, L1_wt, alpha, loglike_kwds, score_kwds, hess_kwds)
for k in range(k_exog)]
converged = False
for itr in range(maxiter):
# Sweep through the parameters
params_save = params.copy()
for k in range(k_exog):
# Under the active set method, if a parameter becomes
# zero we do not try to change it again.
# TODO : give the user the option to switch this off
if params_zero[k]:
continue
# Set the offset to account for the variables that are
# being held fixed in the current coordinate
# optimization.
params0 = params.copy()
params0[k] = 0
offset = np.dot(model.exog, params0)
if model_offset is not None:
offset += model_offset
# Create a one-variable model for optimization.
model_1var = model.__class__(
model.endog, model.exog[:, k], offset=offset, **init_args)
# Do the one-dimensional optimization.
func, grad, hess = fgh_list[k]
params[k] = _opt_1d(
func, grad, hess, model_1var, params[k], alpha[k]*L1_wt,
tol=btol, check_step=check_step)
# Update the active set
if itr > 0 and np.abs(params[k]) < zero_tol:
params_zero[k] = True
params[k] = 0.
# Check for convergence
pchange = np.max(np.abs(params - params_save))
if pchange < cnvrg_tol:
converged = True
break
# Set approximate zero coefficients to be exactly zero
params[np.abs(params) < zero_tol] = 0
if not refit:
results = RegularizedResults(model, params)
results.converged = converged
return RegularizedResultsWrapper(results)
# Fit the reduced model to get standard errors and other
# post-estimation results.
ii = np.flatnonzero(params)
cov = np.zeros((k_exog, k_exog))
init_args = dict([(k, getattr(model, k, None)) for k in model._init_keys])
if len(ii) > 0:
model1 = model.__class__(
model.endog, model.exog[:, ii], **init_args)
rslt = model1.fit()
params[ii] = rslt.params
cov[np.ix_(ii, ii)] = rslt.normalized_cov_params
else:
# Hack: no variables were selected but we need to run fit in
# order to get the correct results class. So just fit a model
# with one variable.
model1 = model.__class__(model.endog, model.exog[:, 0], **init_args)
rslt = model1.fit(maxiter=0)
# fit may return a results or a results wrapper
if issubclass(rslt.__class__, wrap.ResultsWrapper):
klass = rslt._results.__class__
else:
klass = rslt.__class__
# Not all models have a scale
if hasattr(rslt, 'scale'):
scale = rslt.scale
else:
scale = 1.
# The degrees of freedom should reflect the number of parameters
# in the refit model, not including the zeros that are displayed
# to indicate which variables were dropped. See issue #1723 for
# discussion about setting df parameters in model and results
# classes.
p, q = model.df_model, model.df_resid
model.df_model = len(ii)
model.df_resid = model.nobs - model.df_model
# Assuming a standard signature for creating results classes.
refit = klass(model, params, cov, scale=scale)
refit.regularized = True
refit.converged = converged
refit.method = method
refit.fit_history = {'iteration': itr + 1}
# Restore df in model class, see issue #1723 for discussion.
model.df_model, model.df_resid = p, q
return refit
def _opt_1d(func, grad, hess, model, start, L1_wt, tol,
check_step=True):
"""
One-dimensional helper for elastic net.
Parameters
----------
func : function
A smooth function of a single variable to be optimized
with L1 penaty.
grad : function
The gradient of `func`.
hess : function
The Hessian of `func`.
model : statsmodels model
The model being fit.
start : real
A starting value for the function argument
L1_wt : non-negative real
The weight for the L1 penalty function.
tol : non-negative real
A convergence threshold.
check_step : bool
If True, check that the first step is an improvement and
use bisection if it is not. If False, return after the
first step regardless.
Notes
-----
``func``, ``grad``, and ``hess`` have argument signature (x,
model), where ``x`` is a point in the parameter space and
``model`` is the model being fit.
If the log-likelihood for the model is exactly quadratic, the
global minimum is returned in one step. Otherwise numerical
bisection is used.
Returns
-------
The argmin of the objective function.
"""
# Overview:
# We want to minimize L(x) + L1_wt*abs(x), where L() is a smooth
# loss function that includes the log-likelihood and L2 penalty.
# This is a 1-dimensional optimization. If L(x) is exactly
# quadratic we can solve for the argmin exactly. Otherwise we
# approximate L(x) with a quadratic function Q(x) and try to use
# the minimizer of Q(x) + L1_wt*abs(x). But if this yields an
# uphill step for the actual target function L(x) + L1_wt*abs(x),
# then we fall back to a expensive line search. The line search
# is never needed for OLS.
x = start
f = func(x, model)
b = grad(x, model)
c = hess(x, model)
d = b - c*x
# The optimum is achieved by hard thresholding to zero
if L1_wt > np.abs(d):
return 0.
# x + h is the minimizer of the Q(x) + L1_wt*abs(x)
if d >= 0:
h = (L1_wt - b) / c
elif d < 0:
h = -(L1_wt + b) / c
else:
return np.nan
# If the new point is not uphill for the target function, take it
# and return. This check is a bit expensive and un-necessary for
# OLS
if not check_step:
return x + h
f1 = func(x + h, model) + L1_wt*np.abs(x + h)
if f1 <= f + L1_wt*np.abs(x) + 1e-10:
return x + h
# Fallback for models where the loss is not quadratic
from scipy.optimize import brent
x_opt = brent(func, args=(model,), brack=(x-1, x+1), tol=tol)
return x_opt
class RegularizedResults(Results):
"""
Results for models estimated using regularization
Parameters
----------
model : Model
The model instance used to estimate the parameters.
params : ndarray
The estimated (regularized) parameters.
"""
def __init__(self, model, params):
super(RegularizedResults, self).__init__(model, params)
@cache_readonly
def fittedvalues(self):
"""
The predicted values from the model at the estimated parameters.
"""
return self.model.predict(self.params)
class RegularizedResultsWrapper(wrap.ResultsWrapper):
_attrs = {
'params': 'columns',
'resid': 'rows',
'fittedvalues': 'rows',
}
_wrap_attrs = _attrs
wrap.populate_wrapper(RegularizedResultsWrapper, # noqa:E305
RegularizedResults)
| 5,182 |
190,993 | /* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_FRAMEWORK_RUN_HANDLER_H_
#define TENSORFLOW_CORE_FRAMEWORK_RUN_HANDLER_H_
#include "tensorflow/core/lib/core/threadpool.h"
#include "tensorflow/core/lib/histogram/histogram.h"
#include "tensorflow/core/platform/context.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/thread_annotations.h"
#include "tensorflow/core/protobuf/config.pb.h"
namespace Eigen {
struct ThreadPoolDevice;
}
namespace tensorflow {
class RunHandler;
// RunHandlerPool is a fixed size pool of pre-allocated RunHandlers
// that can be used for tracking inter-op work for a given Session::Run().
// RunHandler(s) in the pool are initially 'inactive'. A RunHandler becomes
// 'active' when its unique_ptr is returned by Get() and is being used by a
// client. It becomes 'inactive' once more when its unique_ptr gets destroyed.
//
// Expected usage:
//
// * Create a single RunHandlerPool (say run_handler_pool_).
//
// * When a Session::Run() is invoked, obtain a handler by:
// auto handler = run_handler_pool_->Get();
//
// * Use handler for scheduling all inter-op work by:
// handler->ScheduleInterOpClosure(closure);
//
// This class is thread safe.
class RunHandlerPool {
public:
explicit RunHandlerPool(int num_inter_op_threads);
RunHandlerPool(int num_inter_op_threads, int num_intra_op_threads);
~RunHandlerPool();
// Returns an inactive RunHandler from the pool.
//
// RunHandlers in RunHandlerPool are initially 'inactive'.
// A RunHandler becomes 'active' when its unique_ptr its returned by Get()
// and is being used by a client. It becomes 'inactive' once more when the
// unique_ptr is destroyed.
//
// Will block unless there is an inactive handler.
std::unique_ptr<RunHandler> Get(
int64_t step_id = 0, int64_t timeout_in_ms = 0,
const RunOptions::Experimental::RunHandlerPoolOptions& options =
RunOptions::Experimental::RunHandlerPoolOptions());
// Get the priorities for active handlers. The return result is with the same
// order of the active handler list.
std::vector<int64_t> GetActiveHandlerPrioritiesForTesting() const;
private:
class Impl;
friend class RunHandler;
std::unique_ptr<Impl> impl_;
};
// RunHandler can be used to schedule inter/intra-op closures to run on a global
// pool shared across all Session::Run(s). The closures are enqueued to a
// handler specific queue, from which the work is stolen in a priority order
// (time of the Get() call).
//
// It can only be created via RunHandlerPool::Get().
//
// This class can be used instead of directly scheduling closures on a global
// pool since it maintains a global view across all sessions and optimizes pool
// scheduling to improve (median and tail) latency.
//
// This class is thread safe.
class RunHandler {
public:
void ScheduleInterOpClosure(std::function<void()> fn);
thread::ThreadPoolInterface* AsIntraThreadPoolInterface();
~RunHandler();
private:
class Impl;
friend class RunHandlerPool::Impl;
explicit RunHandler(Impl* impl);
Impl* impl_; // NOT OWNED.
};
namespace internal {
// TODO(azaks): Refactor with thread:ThreadPool
class RunHandlerEnvironment {
typedef Thread EnvThread;
struct TaskImpl {
std::function<void()> f;
Context context;
uint64 trace_id;
};
Env* const env_;
const ThreadOptions thread_options_;
const string name_;
public:
struct Task {
std::unique_ptr<TaskImpl> f;
};
RunHandlerEnvironment(Env* env, const ThreadOptions& thread_options,
const string& name);
EnvThread* CreateThread(std::function<void()> f,
const std::string& thread_name);
Task CreateTask(std::function<void()> f);
void ExecuteTask(const Task& t);
};
typedef typename RunHandlerEnvironment::Task Task;
typedef Eigen::RunQueue<Task, 1024> Queue;
// To reduce cache misses, we use a doubly-linked list of Waiter structs and
// queue them in LIFO order rather than the FIFO order used by a single
// condition variable.
struct Waiter {
Waiter() {
next = this;
prev = this;
}
condition_variable cv;
mutex mu;
Waiter* next;
Waiter* prev;
};
class ThreadWorkSource {
public:
ThreadWorkSource();
~ThreadWorkSource();
Task EnqueueTask(Task t, bool is_blocking);
Task PopBlockingTask();
Task PopNonBlockingTask(int start_index, bool search_from_all_queue);
void WaitForWork(int max_sleep_micros);
int TaskQueueSize(bool is_blocking);
int64_t GetTracemeId();
void SetTracemeId(int64_t value);
void SetWaiter(uint64 version, Waiter* waiter, mutex* mutex);
int64_t GetInflightTaskCount(bool is_blocking);
void IncrementInflightTaskCount(bool is_blocking);
void DecrementInflightTaskCount(bool is_blocking);
unsigned NonBlockingWorkShardingFactor();
std::string ToString();
private:
struct NonBlockingQueue {
mutex queue_op_mu;
char pad[128];
Queue queue;
};
int32 non_blocking_work_sharding_factor_;
Eigen::MaxSizeVector<NonBlockingQueue*> non_blocking_work_queues_;
std::atomic<int64_t> blocking_inflight_;
std::atomic<int64_t> non_blocking_inflight_;
Queue blocking_work_queue_;
mutex blocking_queue_op_mu_;
char pad_[128];
mutex waiters_mu_;
Waiter queue_waiters_ TF_GUARDED_BY(waiters_mu_);
std::atomic<int64_t> traceme_id_;
mutex run_handler_waiter_mu_;
uint64 version_ TF_GUARDED_BY(run_handler_waiter_mu_);
mutex* sub_thread_pool_waiter_mu_ TF_GUARDED_BY(run_handler_waiter_mu_);
Waiter* sub_thread_pool_waiter_ TF_GUARDED_BY(run_handler_waiter_mu_);
};
class RunHandlerThreadPool {
public:
struct PerThread {
constexpr PerThread() : pool(nullptr), thread_id(-1) {}
RunHandlerThreadPool* pool; // Parent pool, or null for normal threads.
int thread_id; // Worker thread index in pool.
};
RunHandlerThreadPool(int num_blocking_threads, int num_non_blocking_threads,
Env* env, const ThreadOptions& thread_options,
const string& name,
Eigen::MaxSizeVector<mutex>* waiters_mu,
Eigen::MaxSizeVector<Waiter>* queue_waiters);
~RunHandlerThreadPool();
void Start();
void StartOneThreadForTesting();
void AddWorkToQueue(ThreadWorkSource* tws, bool is_blocking,
std::function<void()> fn);
// Set work queues from which the thread 'tid' can steal its work.
// The request with start_request_idx will be attempted first. Other requests
// will be attempted in FIFO order based on their arrival time.
void SetThreadWorkSources(
int tid, int start_request_idx, uint64 version,
const Eigen::MaxSizeVector<ThreadWorkSource*>& thread_work_sources);
PerThread* GetPerThread();
int CurrentThreadId() const;
int NumThreads() const;
int NumBlockingThreads() const;
int NumNonBlockingThreads() const;
void WorkerLoop(int thread_id, bool may_steal_blocking_work);
// Search tasks from Requets range searching_range_start to
// searching_range_end. If there is no tasks in the search range and
// may_steal_blocking_work is true, then search from all requests.
Task FindTask(
int searching_range_start, int searching_range_end, int thread_id,
int sub_thread_pool_id, int max_blocking_inflight,
bool may_steal_blocking_work,
const Eigen::MaxSizeVector<ThreadWorkSource*>& thread_work_sources,
bool* task_from_blocking_queue, ThreadWorkSource** tws);
void WaitForWork(bool is_blocking, int thread_id,
int32_t max_blocking_inflight);
void WaitForWorkInSubThreadPool(bool is_blocking, int sub_thread_pool_id);
private:
struct ThreadData {
ThreadData();
mutex mu;
uint64 new_version;
condition_variable sources_not_empty;
std::unique_ptr<Thread> thread;
int current_index;
std::unique_ptr<Eigen::MaxSizeVector<ThreadWorkSource*>>
new_thread_work_sources TF_GUARDED_BY(mu);
uint64 current_version;
// Should only be accessed by one thread.
std::unique_ptr<Eigen::MaxSizeVector<ThreadWorkSource*>>
current_thread_work_sources;
int sub_thread_pool_id;
};
const int num_threads_;
const int num_blocking_threads_;
const int num_non_blocking_threads_;
Eigen::MaxSizeVector<ThreadData> thread_data_;
internal::RunHandlerEnvironment env_;
std::atomic<bool> cancelled_;
string name_;
Eigen::MaxSizeVector<mutex>* waiters_mu_;
Eigen::MaxSizeVector<Waiter>* queue_waiters_;
bool use_sub_thread_pool_;
std::vector<int> num_threads_in_sub_thread_pool_;
// Threads in each sub thread pool will search tasks from the given
// start_request_percentage to end_request_percentage in a round robin
// fashion.
std::vector<double> sub_thread_pool_start_request_percentage_;
std::vector<double> sub_thread_pool_end_request_percentage_;
};
} // namespace internal
} // end namespace tensorflow.
#endif // TENSORFLOW_CORE_FRAMEWORK_RUN_HANDLER_H_
| 3,253 |
1,104 | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2009, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Java is a trademark or registered trademark of Sun Microsystems, Inc.
* in the United States and other countries.]
*
* -----------------------
* StandardChartTheme.java
* -----------------------
* (C) Copyright 2008, 2009, by Object Refinery Limited.
*
* Original Author: <NAME> (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 14-Aug-2008 : Version 1 (DG);
* 10-Apr-2009 : Added getter/setter for smallFont (DG);
*
*/
package org.jfree.chart;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Paint;
import java.awt.Stroke;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Iterator;
import java.util.List;
import org.jfree.chart.annotations.XYAnnotation;
import org.jfree.chart.annotations.XYTextAnnotation;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.PeriodAxis;
import org.jfree.chart.axis.PeriodAxisLabelInfo;
import org.jfree.chart.axis.SubCategoryAxis;
import org.jfree.chart.axis.SymbolAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.block.Block;
import org.jfree.chart.block.BlockContainer;
import org.jfree.chart.block.LabelBlock;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.CombinedDomainCategoryPlot;
import org.jfree.chart.plot.CombinedDomainXYPlot;
import org.jfree.chart.plot.CombinedRangeCategoryPlot;
import org.jfree.chart.plot.CombinedRangeXYPlot;
import org.jfree.chart.plot.DefaultDrawingSupplier;
import org.jfree.chart.plot.DrawingSupplier;
import org.jfree.chart.plot.FastScatterPlot;
import org.jfree.chart.plot.MeterPlot;
import org.jfree.chart.plot.MultiplePiePlot;
import org.jfree.chart.plot.PieLabelLinkStyle;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.plot.Plot;
import org.jfree.chart.plot.PolarPlot;
import org.jfree.chart.plot.SpiderWebPlot;
import org.jfree.chart.plot.ThermometerPlot;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.AbstractRenderer;
import org.jfree.chart.renderer.category.BarPainter;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.BarRenderer3D;
import org.jfree.chart.renderer.category.CategoryItemRenderer;
import org.jfree.chart.renderer.category.GradientBarPainter;
import org.jfree.chart.renderer.category.LineRenderer3D;
import org.jfree.chart.renderer.category.MinMaxCategoryRenderer;
import org.jfree.chart.renderer.category.StatisticalBarRenderer;
import org.jfree.chart.renderer.xy.GradientXYBarPainter;
import org.jfree.chart.renderer.xy.XYBarPainter;
import org.jfree.chart.renderer.xy.XYBarRenderer;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.title.CompositeTitle;
import org.jfree.chart.title.LegendTitle;
import org.jfree.chart.title.PaintScaleLegend;
import org.jfree.chart.title.TextTitle;
import org.jfree.chart.title.Title;
import org.jfree.io.SerialUtilities;
import org.jfree.ui.RectangleInsets;
import org.jfree.util.PaintUtilities;
import org.jfree.util.PublicCloneable;
/**
* A default implementation of the {@link ChartTheme} interface. This
* implementation just collects a whole bunch of chart attributes and mimics
* the manual process of applying each attribute to the right sub-object
* within the JFreeChart instance. It's not elegant code, but it works.
*
* @since 1.0.11
*/
public class StandardChartTheme implements ChartTheme, Cloneable,
PublicCloneable, Serializable {
/** The name of this theme. */
private String name;
/**
* The largest font size. Use for the main chart title.
*/
private Font extraLargeFont;
/**
* A large font. Used for subtitles.
*/
private Font largeFont;
/**
* The regular font size. Used for axis tick labels, legend items etc.
*/
private Font regularFont;
/**
* The small font size.
*/
private Font smallFont;
/** The paint used to display the main chart title. */
private transient Paint titlePaint;
/** The paint used to display subtitles. */
private transient Paint subtitlePaint;
/** The background paint for the chart. */
private transient Paint chartBackgroundPaint;
/** The legend background paint. */
private transient Paint legendBackgroundPaint;
/** The legend item paint. */
private transient Paint legendItemPaint;
/** The drawing supplier. */
private DrawingSupplier drawingSupplier;
/** The background paint for the plot. */
private transient Paint plotBackgroundPaint;
/** The plot outline paint. */
private transient Paint plotOutlinePaint;
/** The label link style for pie charts. */
private PieLabelLinkStyle labelLinkStyle;
/** The label link paint for pie charts. */
private transient Paint labelLinkPaint;
/** The domain grid line paint. */
private transient Paint domainGridlinePaint;
/** The range grid line paint. */
private transient Paint rangeGridlinePaint;
/**
* The baseline paint (used for domain and range zero baselines)
*
* @since 1.0.13
*/
private transient Paint baselinePaint;
/** The crosshair paint. */
private transient Paint crosshairPaint;
/** The axis offsets. */
private RectangleInsets axisOffset;
/** The axis label paint. */
private transient Paint axisLabelPaint;
/** The tick label paint. */
private transient Paint tickLabelPaint;
/** The item label paint. */
private transient Paint itemLabelPaint;
/**
* A flag that controls whether or not shadows are visible (for example,
* in a bar renderer).
*/
private boolean shadowVisible;
/** The shadow paint. */
private transient Paint shadowPaint;
/** The bar painter. */
private BarPainter barPainter;
/** The XY bar painter. */
private XYBarPainter xyBarPainter;
/** The thermometer paint. */
private transient Paint thermometerPaint;
/**
* The paint used to fill the interior of the 'walls' in the background
* of a plot with a 3D effect. Applied to BarRenderer3D.
*/
private transient Paint wallPaint;
/** The error indicator paint for the {@link StatisticalBarRenderer}. */
private transient Paint errorIndicatorPaint;
/** The grid band paint for a {@link SymbolAxis}. */
private transient Paint gridBandPaint = SymbolAxis.DEFAULT_GRID_BAND_PAINT;
/** The grid band alternate paint for a {@link SymbolAxis}. */
private transient Paint gridBandAlternatePaint
= SymbolAxis.DEFAULT_GRID_BAND_ALTERNATE_PAINT;
/**
* Creates and returns the default 'JFree' chart theme.
*
* @return A chart theme.
*/
public static ChartTheme createJFreeTheme() {
return new StandardChartTheme("JFree");
}
/**
* Creates and returns a theme called "Darkness". In this theme, the
* charts have a black background.
*
* @return The "Darkness" theme.
*/
public static ChartTheme createDarknessTheme() {
StandardChartTheme theme = new StandardChartTheme("Darkness");
theme.titlePaint = Color.white;
theme.subtitlePaint = Color.white;
theme.legendBackgroundPaint = Color.black;
theme.legendItemPaint = Color.white;
theme.chartBackgroundPaint = Color.black;
theme.plotBackgroundPaint = Color.black;
theme.plotOutlinePaint = Color.yellow;
theme.baselinePaint = Color.white;
theme.crosshairPaint = Color.red;
theme.labelLinkPaint = Color.lightGray;
theme.tickLabelPaint = Color.white;
theme.axisLabelPaint = Color.white;
theme.shadowPaint = Color.darkGray;
theme.itemLabelPaint = Color.white;
theme.drawingSupplier = new DefaultDrawingSupplier(
new Paint[] {Color.decode("0xFFFF00"),
Color.decode("0x0036CC"), Color.decode("0xFF0000"),
Color.decode("0xFFFF7F"), Color.decode("0x6681CC"),
Color.decode("0xFF7F7F"), Color.decode("0xFFFFBF"),
Color.decode("0x99A6CC"), Color.decode("0xFFBFBF"),
Color.decode("0xA9A938"), Color.decode("0x2D4587")},
new Paint[] {Color.decode("0xFFFF00"),
Color.decode("0x0036CC")},
new Stroke[] {new BasicStroke(2.0f)},
new Stroke[] {new BasicStroke(0.5f)},
DefaultDrawingSupplier.DEFAULT_SHAPE_SEQUENCE);
theme.wallPaint = Color.darkGray;
theme.errorIndicatorPaint = Color.lightGray;
theme.gridBandPaint = new Color(255, 255, 255, 20);
theme.gridBandAlternatePaint = new Color(255, 255, 255, 40);
return theme;
}
/**
* Creates and returns a {@link ChartTheme} that doesn't apply any changes
* to the JFreeChart defaults. This produces the "legacy" look for
* JFreeChart.
*
* @return A legacy theme.
*/
public static ChartTheme createLegacyTheme() {
StandardChartTheme theme = new StandardChartTheme("Legacy") {
public void apply(JFreeChart chart) {
// do nothing at all
}
};
return theme;
}
/**
* Creates a new default instance.
*
* @param name the name of the theme (<code>null</code> not permitted).
*/
public StandardChartTheme(String name) {
if (name == null) {
throw new IllegalArgumentException("Null 'name' argument.");
}
this.name = name;
this.extraLargeFont = new Font("Tahoma", Font.BOLD, 20);
this.largeFont = new Font("Tahoma", Font.BOLD, 14);
this.regularFont = new Font("Tahoma", Font.PLAIN, 12);
this.smallFont = new Font("Tahoma", Font.PLAIN, 10);
this.titlePaint = Color.black;
this.subtitlePaint = Color.black;
this.legendBackgroundPaint = Color.white;
this.legendItemPaint = Color.darkGray;
this.chartBackgroundPaint = Color.white;
this.drawingSupplier = new DefaultDrawingSupplier();
this.plotBackgroundPaint = Color.lightGray;
this.plotOutlinePaint = Color.black;
this.labelLinkPaint = Color.black;
this.labelLinkStyle = PieLabelLinkStyle.CUBIC_CURVE;
this.axisOffset = new RectangleInsets(4, 4, 4, 4);
this.domainGridlinePaint = Color.white;
this.rangeGridlinePaint = Color.white;
this.baselinePaint = Color.black;
this.crosshairPaint = Color.blue;
this.axisLabelPaint = Color.darkGray;
this.tickLabelPaint = Color.darkGray;
this.barPainter = new GradientBarPainter();
this.xyBarPainter = new GradientXYBarPainter();
this.shadowVisible = true;
this.shadowPaint = Color.gray;
this.itemLabelPaint = Color.black;
this.thermometerPaint = Color.white;
this.wallPaint = BarRenderer3D.DEFAULT_WALL_PAINT;
this.errorIndicatorPaint = Color.black;
}
/**
* Returns the largest font for this theme.
*
* @return The largest font for this theme.
*
* @see #setExtraLargeFont(Font)
*/
public Font getExtraLargeFont() {
return this.extraLargeFont;
}
/**
* Sets the largest font for this theme.
*
* @param font the font (<code>null</code> not permitted).
*
* @see #getExtraLargeFont()
*/
public void setExtraLargeFont(Font font) {
if (font == null) {
throw new IllegalArgumentException("Null 'font' argument.");
}
this.extraLargeFont = font;
}
/**
* Returns the large font for this theme.
*
* @return The large font (never <code>null</code>).
*
* @see #setLargeFont(Font)
*/
public Font getLargeFont() {
return this.largeFont;
}
/**
* Sets the large font for this theme.
*
* @param font the font (<code>null</code> not permitted).
*
* @see #getLargeFont()
*/
public void setLargeFont(Font font) {
if (font == null) {
throw new IllegalArgumentException("Null 'font' argument.");
}
this.largeFont = font;
}
/**
* Returns the regular font.
*
* @return The regular font (never <code>null</code>).
*
* @see #setRegularFont(Font)
*/
public Font getRegularFont() {
return this.regularFont;
}
/**
* Sets the regular font for this theme.
*
* @param font the font (<code>null</code> not permitted).
*
* @see #getRegularFont()
*/
public void setRegularFont(Font font) {
if (font == null) {
throw new IllegalArgumentException("Null 'font' argument.");
}
this.regularFont = font;
}
/**
* Returns the small font.
*
* @return The small font (never <code>null</code>).
*
* @see #setSmallFont(Font)
*
* @since 1.0.13
*/
public Font getSmallFont() {
return this.smallFont;
}
/**
* Sets the small font for this theme.
*
* @param font the font (<code>null</code> not permitted).
*
* @see #getSmallFont()
*
* @since 1.0.13
*/
public void setSmallFont(Font font) {
if (font == null) {
throw new IllegalArgumentException("Null 'font' argument.");
}
this.smallFont = font;
}
/**
* Returns the title paint.
*
* @return The title paint (never <code>null</code>).
*
* @see #setTitlePaint(Paint)
*/
public Paint getTitlePaint() {
return this.titlePaint;
}
/**
* Sets the title paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getTitlePaint()
*/
public void setTitlePaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.titlePaint = paint;
}
/**
* Returns the subtitle paint.
*
* @return The subtitle paint (never <code>null</code>).
*
* @see #setSubtitlePaint(Paint)
*/
public Paint getSubtitlePaint() {
return this.subtitlePaint;
}
/**
* Sets the subtitle paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getSubtitlePaint()
*/
public void setSubtitlePaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.subtitlePaint = paint;
}
/**
* Returns the chart background paint.
*
* @return The chart background paint (never <code>null</code>).
*
* @see #setChartBackgroundPaint(Paint)
*/
public Paint getChartBackgroundPaint() {
return this.chartBackgroundPaint;
}
/**
* Sets the chart background paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getChartBackgroundPaint()
*/
public void setChartBackgroundPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.chartBackgroundPaint = paint;
}
/**
* Returns the legend background paint.
*
* @return The legend background paint (never <code>null</code>).
*
* @see #setLegendBackgroundPaint(Paint)
*/
public Paint getLegendBackgroundPaint() {
return this.legendBackgroundPaint;
}
/**
* Sets the legend background paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getLegendBackgroundPaint()
*/
public void setLegendBackgroundPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.legendBackgroundPaint = paint;
}
/**
* Returns the legend item paint.
*
* @return The legend item paint (never <code>null</code>).
*
* @see #setLegendItemPaint(Paint)
*/
public Paint getLegendItemPaint() {
return this.legendItemPaint;
}
/**
* Sets the legend item paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getLegendItemPaint()
*/
public void setLegendItemPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.legendItemPaint = paint;
}
/**
* Returns the plot background paint.
*
* @return The plot background paint (never <code>null</code>).
*
* @see #setPlotBackgroundPaint(Paint)
*/
public Paint getPlotBackgroundPaint() {
return this.plotBackgroundPaint;
}
/**
* Sets the plot background paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getPlotBackgroundPaint()
*/
public void setPlotBackgroundPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.plotBackgroundPaint = paint;
}
/**
* Returns the plot outline paint.
*
* @return The plot outline paint (never <code>null</code>).
*
* @see #setPlotOutlinePaint(Paint)
*/
public Paint getPlotOutlinePaint() {
return this.plotOutlinePaint;
}
/**
* Sets the plot outline paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getPlotOutlinePaint()
*/
public void setPlotOutlinePaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.plotOutlinePaint = paint;
}
/**
* Returns the label link style for pie charts.
*
* @return The label link style (never <code>null</code>).
*
* @see #setLabelLinkStyle(PieLabelLinkStyle)
*/
public PieLabelLinkStyle getLabelLinkStyle() {
return this.labelLinkStyle;
}
/**
* Sets the label link style for pie charts.
*
* @param style the style (<code>null</code> not permitted).
*
* @see #getLabelLinkStyle()
*/
public void setLabelLinkStyle(PieLabelLinkStyle style) {
if (style == null) {
throw new IllegalArgumentException("Null 'style' argument.");
}
this.labelLinkStyle = style;
}
/**
* Returns the label link paint for pie charts.
*
* @return The label link paint (never <code>null</code>).
*
* @see #setLabelLinkPaint(Paint)
*/
public Paint getLabelLinkPaint() {
return this.labelLinkPaint;
}
/**
* Sets the label link paint for pie charts.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getLabelLinkPaint()
*/
public void setLabelLinkPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.labelLinkPaint = paint;
}
/**
* Returns the domain grid line paint.
*
* @return The domain grid line paint (never <code>null<code>).
*
* @see #setDomainGridlinePaint(Paint)
*/
public Paint getDomainGridlinePaint() {
return this.domainGridlinePaint;
}
/**
* Sets the domain grid line paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getDomainGridlinePaint()
*/
public void setDomainGridlinePaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.domainGridlinePaint = paint;
}
/**
* Returns the range grid line paint.
*
* @return The range grid line paint (never <code>null</code>).
*
* @see #setRangeGridlinePaint(Paint)
*/
public Paint getRangeGridlinePaint() {
return this.rangeGridlinePaint;
}
/**
* Sets the range grid line paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getRangeGridlinePaint()
*/
public void setRangeGridlinePaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.rangeGridlinePaint = paint;
}
/**
* Returns the baseline paint.
*
* @return The baseline paint.
*
* @since 1.0.13
*/
public Paint getBaselinePaint() {
return this.baselinePaint;
}
/**
* Sets the baseline paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @since 1.0.13
*/
public void setBaselinePaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.baselinePaint = paint;
}
/**
* Returns the crosshair paint.
*
* @return The crosshair paint.
*/
public Paint getCrosshairPaint() {
return this.crosshairPaint;
}
/**
* Sets the crosshair paint.
*
* @param paint the paint (<code>null</code> not permitted).
*/
public void setCrosshairPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.crosshairPaint = paint;
}
/**
* Returns the axis offsets.
*
* @return The axis offsets (never <code>null</code>).
*
* @see #setAxisOffset(RectangleInsets)
*/
public RectangleInsets getAxisOffset() {
return this.axisOffset;
}
/**
* Sets the axis offset.
*
* @param offset the offset (<code>null</code> not permitted).
*
* @see #getAxisOffset()
*/
public void setAxisOffset(RectangleInsets offset) {
if (offset == null) {
throw new IllegalArgumentException("Null 'offset' argument.");
}
this.axisOffset = offset;
}
/**
* Returns the axis label paint.
*
* @return The axis label paint (never <code>null</code>).
*
* @see #setAxisLabelPaint(Paint)
*/
public Paint getAxisLabelPaint() {
return this.axisLabelPaint;
}
/**
* Sets the axis label paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getAxisLabelPaint()
*/
public void setAxisLabelPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.axisLabelPaint = paint;
}
/**
* Returns the tick label paint.
*
* @return The tick label paint (never <code>null</code>).
*
* @see #setTickLabelPaint(Paint)
*/
public Paint getTickLabelPaint() {
return this.tickLabelPaint;
}
/**
* Sets the tick label paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getTickLabelPaint()
*/
public void setTickLabelPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.tickLabelPaint = paint;
}
/**
* Returns the item label paint.
*
* @return The item label paint (never <code>null</code>).
*
* @see #setItemLabelPaint(Paint)
*/
public Paint getItemLabelPaint() {
return this.itemLabelPaint;
}
/**
* Sets the item label paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getItemLabelPaint()
*/
public void setItemLabelPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.itemLabelPaint = paint;
}
/**
* Returns the shadow visibility flag.
*
* @return The shadow visibility flag.
*
* @see #setShadowVisible(boolean)
*/
public boolean isShadowVisible() {
return this.shadowVisible;
}
/**
* Sets the shadow visibility flag.
*
* @param visible the flag.
*
* @see #isShadowVisible()
*/
public void setShadowVisible(boolean visible) {
this.shadowVisible = visible;
}
/**
* Returns the shadow paint.
*
* @return The shadow paint (never <code>null</code>).
*
* @see #setShadowPaint(Paint)
*/
public Paint getShadowPaint() {
return this.shadowPaint;
}
/**
* Sets the shadow paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getShadowPaint()
*/
public void setShadowPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.shadowPaint = paint;
}
/**
* Returns the bar painter.
*
* @return The bar painter (never <code>null</code>).
*
* @see #setBarPainter(BarPainter)
*/
public BarPainter getBarPainter() {
return this.barPainter;
}
/**
* Sets the bar painter.
*
* @param painter the painter (<code>null</code> not permitted).
*
* @see #getBarPainter()
*/
public void setBarPainter(BarPainter painter) {
if (painter == null) {
throw new IllegalArgumentException("Null 'painter' argument.");
}
this.barPainter = painter;
}
/**
* Returns the XY bar painter.
*
* @return The XY bar painter (never <code>null</code>).
*
* @see #setXYBarPainter(XYBarPainter)
*/
public XYBarPainter getXYBarPainter() {
return this.xyBarPainter;
}
/**
* Sets the XY bar painter.
*
* @param painter the painter (<code>null</code> not permitted).
*
* @see #getXYBarPainter()
*/
public void setXYBarPainter(XYBarPainter painter) {
if (painter == null) {
throw new IllegalArgumentException("Null 'painter' argument.");
}
this.xyBarPainter = painter;
}
/**
* Returns the thermometer paint.
*
* @return The thermometer paint (never <code>null</code>).
*
* @see #setThermometerPaint(Paint)
*/
public Paint getThermometerPaint() {
return this.thermometerPaint;
}
/**
* Sets the thermometer paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getThermometerPaint()
*/
public void setThermometerPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.thermometerPaint = paint;
}
/**
* Returns the wall paint for charts with a 3D effect.
*
* @return The wall paint (never <code>null</code>).
*
* @see #setWallPaint(Paint)
*/
public Paint getWallPaint() {
return this.wallPaint;
}
/**
* Sets the wall paint for charts with a 3D effect.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getWallPaint()
*/
public void setWallPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.wallPaint = paint;
}
/**
* Returns the error indicator paint.
*
* @return The error indicator paint (never <code>null</code>).
*
* @see #setErrorIndicatorPaint(Paint)
*/
public Paint getErrorIndicatorPaint() {
return this.errorIndicatorPaint;
}
/**
* Sets the error indicator paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getErrorIndicatorPaint()
*/
public void setErrorIndicatorPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.errorIndicatorPaint = paint;
}
/**
* Returns the grid band paint.
*
* @return The grid band paint (never <code>null</code>).
*
* @see #setGridBandPaint(Paint)
*/
public Paint getGridBandPaint() {
return this.gridBandPaint;
}
/**
* Sets the grid band paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getGridBandPaint()
*/
public void setGridBandPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.gridBandPaint = paint;
}
/**
* Returns the grid band alternate paint (used for a {@link SymbolAxis}).
*
* @return The paint (never <code>null</code>).
*
* @see #setGridBandAlternatePaint(Paint)
*/
public Paint getGridBandAlternatePaint() {
return this.gridBandAlternatePaint;
}
/**
* Sets the grid band alternate paint (used for a {@link SymbolAxis}).
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getGridBandAlternatePaint()
*/
public void setGridBandAlternatePaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.gridBandAlternatePaint = paint;
}
/**
* Returns the name of this theme.
*
* @return The name of this theme.
*/
public String getName() {
return this.name;
}
/**
* Returns a clone of the drawing supplier for this theme.
*
* @return A clone of the drawing supplier.
*/
public DrawingSupplier getDrawingSupplier() {
DrawingSupplier result = null;
if (this.drawingSupplier instanceof PublicCloneable) {
PublicCloneable pc = (PublicCloneable) this.drawingSupplier;
try {
result = (DrawingSupplier) pc.clone();
}
catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
return result;
}
/**
* Sets the drawing supplier for this theme.
*
* @param supplier the supplier (<code>null</code> not permitted).
*
* @see #getDrawingSupplier()
*/
public void setDrawingSupplier(DrawingSupplier supplier) {
if (supplier == null) {
throw new IllegalArgumentException("Null 'supplier' argument.");
}
this.drawingSupplier = supplier;
}
/**
* Applies this theme to the supplied chart.
*
* @param chart the chart (<code>null</code> not permitted).
*/
public void apply(JFreeChart chart) {
if (chart == null) {
throw new IllegalArgumentException("Null 'chart' argument.");
}
TextTitle title = chart.getTitle();
if (title != null) {
title.setFont(this.extraLargeFont);
title.setPaint(this.titlePaint);
}
int subtitleCount = chart.getSubtitleCount();
for (int i = 0; i < subtitleCount; i++) {
applyToTitle(chart.getSubtitle(i));
}
chart.setBackgroundPaint(this.chartBackgroundPaint);
// now process the plot if there is one
Plot plot = chart.getPlot();
if (plot != null) {
applyToPlot(plot);
}
}
/**
* Applies the attributes of this theme to the specified title.
*
* @param title the title.
*/
protected void applyToTitle(Title title) {
if (title instanceof TextTitle) {
TextTitle tt = (TextTitle) title;
tt.setFont(this.largeFont);
tt.setPaint(this.subtitlePaint);
}
else if (title instanceof LegendTitle) {
LegendTitle lt = (LegendTitle) title;
if (lt.getBackgroundPaint() != null) {
lt.setBackgroundPaint(this.legendBackgroundPaint);
}
lt.setItemFont(this.regularFont);
lt.setItemPaint(this.legendItemPaint);
if (lt.getWrapper() != null) {
applyToBlockContainer(lt.getWrapper());
}
}
else if (title instanceof PaintScaleLegend) {
PaintScaleLegend psl = (PaintScaleLegend) title;
psl.setBackgroundPaint(this.legendBackgroundPaint);
ValueAxis axis = psl.getAxis();
if (axis != null) {
applyToValueAxis(axis);
}
}
else if (title instanceof CompositeTitle) {
CompositeTitle ct = (CompositeTitle) title;
BlockContainer bc = ct.getContainer();
List blocks = bc.getBlocks();
Iterator iterator = blocks.iterator();
while (iterator.hasNext()) {
Block b = (Block) iterator.next();
if (b instanceof Title) {
applyToTitle((Title) b);
}
}
}
}
/**
* Applies the attributes of this theme to the specified container.
*
* @param bc a block container (<code>null</code> not permitted).
*/
protected void applyToBlockContainer(BlockContainer bc) {
Iterator iterator = bc.getBlocks().iterator();
while (iterator.hasNext()) {
Block b = (Block) iterator.next();
applyToBlock(b);
}
}
/**
* Applies the attributes of this theme to the specified block.
*
* @param b the block.
*/
protected void applyToBlock(Block b) {
if (b instanceof Title) {
applyToTitle((Title) b);
}
else if (b instanceof LabelBlock) {
LabelBlock lb = (LabelBlock) b;
lb.setFont(this.regularFont);
lb.setPaint(this.legendItemPaint);
}
}
/**
* Applies the attributes of this theme to a plot.
*
* @param plot the plot (<code>null</code>).
*/
protected void applyToPlot(Plot plot) {
if (plot == null) {
throw new IllegalArgumentException("Null 'plot' argument.");
}
if (plot.getDrawingSupplier() != null) {
plot.setDrawingSupplier(getDrawingSupplier());
}
if (plot.getBackgroundPaint() != null) {
plot.setBackgroundPaint(this.plotBackgroundPaint);
}
plot.setOutlinePaint(this.plotOutlinePaint);
// now handle specific plot types (and yes, I know this is some
// really ugly code that has to be manually updated any time a new
// plot type is added - I should have written something much cooler,
// but I didn't and neither did anyone else).
if (plot instanceof PiePlot) {
applyToPiePlot((PiePlot) plot);
}
else if (plot instanceof MultiplePiePlot) {
applyToMultiplePiePlot((MultiplePiePlot) plot);
}
else if (plot instanceof CategoryPlot) {
applyToCategoryPlot((CategoryPlot) plot);
}
else if (plot instanceof XYPlot) {
applyToXYPlot((XYPlot) plot);
}
else if (plot instanceof FastScatterPlot) {
applyToFastScatterPlot((FastScatterPlot) plot);
}
else if (plot instanceof MeterPlot) {
applyToMeterPlot((MeterPlot) plot);
}
else if (plot instanceof ThermometerPlot) {
applyToThermometerPlot((ThermometerPlot) plot);
}
else if (plot instanceof SpiderWebPlot) {
applyToSpiderWebPlot((SpiderWebPlot) plot);
}
else if (plot instanceof PolarPlot) {
applyToPolarPlot((PolarPlot) plot);
}
}
/**
* Applies the attributes of this theme to a {@link PiePlot} instance.
* This method also clears any set values for the section paint, outline
* etc, so that the theme's {@link DrawingSupplier} will be used.
*
* @param plot the plot (<code>null</code> not permitted).
*/
protected void applyToPiePlot(PiePlot plot) {
plot.setLabelLinkPaint(this.labelLinkPaint);
plot.setLabelLinkStyle(this.labelLinkStyle);
plot.setLabelFont(this.regularFont);
// clear the section attributes so that the theme's DrawingSupplier
// will be used
if (plot.getAutoPopulateSectionPaint()) {
plot.clearSectionPaints(false);
}
if (plot.getAutoPopulateSectionOutlinePaint()) {
plot.clearSectionOutlinePaints(false);
}
if (plot.getAutoPopulateSectionOutlineStroke()) {
plot.clearSectionOutlineStrokes(false);
}
}
/**
* Applies the attributes of this theme to a {@link MultiplePiePlot}.
*
* @param plot the plot (<code>null</code> not permitted).
*/
protected void applyToMultiplePiePlot(MultiplePiePlot plot) {
apply(plot.getPieChart());
}
/**
* Applies the attributes of this theme to a {@link CategoryPlot}.
*
* @param plot the plot (<code>null</code> not permitted).
*/
protected void applyToCategoryPlot(CategoryPlot plot) {
plot.setAxisOffset(this.axisOffset);
plot.setDomainGridlinePaint(this.domainGridlinePaint);
plot.setRangeGridlinePaint(this.rangeGridlinePaint);
plot.setRangeZeroBaselinePaint(this.baselinePaint);
// process all domain axes
int domainAxisCount = plot.getDomainAxisCount();
for (int i = 0; i < domainAxisCount; i++) {
CategoryAxis axis = plot.getDomainAxis(i);
if (axis != null) {
applyToCategoryAxis(axis);
}
}
// process all range axes
int rangeAxisCount = plot.getRangeAxisCount();
for (int i = 0; i < rangeAxisCount; i++) {
ValueAxis axis = (ValueAxis) plot.getRangeAxis(i);
if (axis != null) {
applyToValueAxis(axis);
}
}
// process all renderers
int rendererCount = plot.getRendererCount();
for (int i = 0; i < rendererCount; i++) {
CategoryItemRenderer r = plot.getRenderer(i);
if (r != null) {
applyToCategoryItemRenderer(r);
}
}
if (plot instanceof CombinedDomainCategoryPlot) {
CombinedDomainCategoryPlot cp = (CombinedDomainCategoryPlot) plot;
Iterator iterator = cp.getSubplots().iterator();
while (iterator.hasNext()) {
CategoryPlot subplot = (CategoryPlot) iterator.next();
if (subplot != null) {
applyToPlot(subplot);
}
}
}
if (plot instanceof CombinedRangeCategoryPlot) {
CombinedRangeCategoryPlot cp = (CombinedRangeCategoryPlot) plot;
Iterator iterator = cp.getSubplots().iterator();
while (iterator.hasNext()) {
CategoryPlot subplot = (CategoryPlot) iterator.next();
if (subplot != null) {
applyToPlot(subplot);
}
}
}
}
/**
* Applies the attributes of this theme to a {@link XYPlot}.
*
* @param plot the plot (<code>null</code> not permitted).
*/
protected void applyToXYPlot(XYPlot plot) {
plot.setAxisOffset(this.axisOffset);
plot.setDomainZeroBaselinePaint(this.baselinePaint);
plot.setRangeZeroBaselinePaint(this.baselinePaint);
plot.setDomainGridlinePaint(this.domainGridlinePaint);
plot.setRangeGridlinePaint(this.rangeGridlinePaint);
plot.setDomainCrosshairPaint(this.crosshairPaint);
plot.setRangeCrosshairPaint(this.crosshairPaint);
// process all domain axes
int domainAxisCount = plot.getDomainAxisCount();
for (int i = 0; i < domainAxisCount; i++) {
ValueAxis axis = plot.getDomainAxis(i);
if (axis != null) {
applyToValueAxis(axis);
}
}
// process all range axes
int rangeAxisCount = plot.getRangeAxisCount();
for (int i = 0; i < rangeAxisCount; i++) {
ValueAxis axis = (ValueAxis) plot.getRangeAxis(i);
if (axis != null) {
applyToValueAxis(axis);
}
}
// process all renderers
int rendererCount = plot.getRendererCount();
for (int i = 0; i < rendererCount; i++) {
XYItemRenderer r = plot.getRenderer(i);
if (r != null) {
applyToXYItemRenderer(r);
}
}
// process all annotations
Iterator iter = plot.getAnnotations().iterator();
while (iter.hasNext()) {
XYAnnotation a = (XYAnnotation) iter.next();
applyToXYAnnotation(a);
}
if (plot instanceof CombinedDomainXYPlot) {
CombinedDomainXYPlot cp = (CombinedDomainXYPlot) plot;
Iterator iterator = cp.getSubplots().iterator();
while (iterator.hasNext()) {
XYPlot subplot = (XYPlot) iterator.next();
if (subplot != null) {
applyToPlot(subplot);
}
}
}
if (plot instanceof CombinedRangeXYPlot) {
CombinedRangeXYPlot cp = (CombinedRangeXYPlot) plot;
Iterator iterator = cp.getSubplots().iterator();
while (iterator.hasNext()) {
XYPlot subplot = (XYPlot) iterator.next();
if (subplot != null) {
applyToPlot(subplot);
}
}
}
}
/**
* Applies the attributes of this theme to a {@link FastScatterPlot}.
* @param plot
*/
protected void applyToFastScatterPlot(FastScatterPlot plot) {
plot.setDomainGridlinePaint(this.domainGridlinePaint);
plot.setRangeGridlinePaint(this.rangeGridlinePaint);
ValueAxis xAxis = plot.getDomainAxis();
if (xAxis != null) {
applyToValueAxis(xAxis);
}
ValueAxis yAxis = plot.getRangeAxis();
if (yAxis != null) {
applyToValueAxis(yAxis);
}
}
/**
* Applies the attributes of this theme to a {@link PolarPlot}. This
* method is called from the {@link #applyToPlot(Plot)} method.
*
* @param plot the plot (<code>null</code> not permitted).
*/
protected void applyToPolarPlot(PolarPlot plot) {
plot.setAngleLabelFont(this.regularFont);
plot.setAngleLabelPaint(this.tickLabelPaint);
plot.setAngleGridlinePaint(this.domainGridlinePaint);
plot.setRadiusGridlinePaint(this.rangeGridlinePaint);
ValueAxis axis = plot.getAxis();
if (axis != null) {
applyToValueAxis(axis);
}
}
/**
* Applies the attributes of this theme to a {@link SpiderWebPlot}.
*
* @param plot the plot (<code>null</code> not permitted).
*/
protected void applyToSpiderWebPlot(SpiderWebPlot plot) {
plot.setLabelFont(this.regularFont);
plot.setLabelPaint(this.axisLabelPaint);
plot.setAxisLinePaint(this.axisLabelPaint);
}
/**
* Applies the attributes of this theme to a {@link MeterPlot}.
*
* @param plot the plot (<code>null</code> not permitted).
*/
protected void applyToMeterPlot(MeterPlot plot) {
plot.setDialBackgroundPaint(this.plotBackgroundPaint);
plot.setValueFont(this.largeFont);
plot.setValuePaint(this.axisLabelPaint);
plot.setDialOutlinePaint(this.plotOutlinePaint);
plot.setNeedlePaint(this.thermometerPaint);
plot.setTickLabelFont(this.regularFont);
plot.setTickLabelPaint(this.tickLabelPaint);
}
/**
* Applies the attributes for this theme to a {@link ThermometerPlot}.
* This method is called from the {@link #applyToPlot(Plot)} method.
*
* @param plot the plot.
*/
protected void applyToThermometerPlot(ThermometerPlot plot) {
plot.setValueFont(this.largeFont);
plot.setThermometerPaint(this.thermometerPaint);
ValueAxis axis = plot.getRangeAxis();
if (axis != null) {
applyToValueAxis(axis);
}
}
/**
* Applies the attributes for this theme to a {@link CategoryAxis}.
*
* @param axis the axis (<code>null</code> not permitted).
*/
protected void applyToCategoryAxis(CategoryAxis axis) {
axis.setLabelFont(this.largeFont);
axis.setLabelPaint(this.axisLabelPaint);
axis.setTickLabelFont(this.regularFont);
axis.setTickLabelPaint(this.tickLabelPaint);
if (axis instanceof SubCategoryAxis) {
SubCategoryAxis sca = (SubCategoryAxis) axis;
sca.setSubLabelFont(this.regularFont);
sca.setSubLabelPaint(this.tickLabelPaint);
}
}
/**
* Applies the attributes for this theme to a {@link ValueAxis}.
*
* @param axis the axis (<code>null</code> not permitted).
*/
protected void applyToValueAxis(ValueAxis axis) {
axis.setLabelFont(this.largeFont);
axis.setLabelPaint(this.axisLabelPaint);
axis.setTickLabelFont(this.regularFont);
axis.setTickLabelPaint(this.tickLabelPaint);
if (axis instanceof SymbolAxis) {
applyToSymbolAxis((SymbolAxis) axis);
}
if (axis instanceof PeriodAxis) {
applyToPeriodAxis((PeriodAxis) axis);
}
}
/**
* Applies the attributes for this theme to a {@link SymbolAxis}.
*
* @param axis the axis (<code>null</code> not permitted).
*/
protected void applyToSymbolAxis(SymbolAxis axis) {
axis.setGridBandPaint(this.gridBandPaint);
axis.setGridBandAlternatePaint(this.gridBandAlternatePaint);
}
/**
* Applies the attributes for this theme to a {@link PeriodAxis}.
*
* @param axis the axis (<code>null</code> not permitted).
*/
protected void applyToPeriodAxis(PeriodAxis axis) {
PeriodAxisLabelInfo[] info = axis.getLabelInfo();
for (int i = 0; i < info.length; i++) {
PeriodAxisLabelInfo e = info[i];
PeriodAxisLabelInfo n = new PeriodAxisLabelInfo(e.getPeriodClass(),
e.getDateFormat(), e.getPadding(), this.regularFont,
this.tickLabelPaint, e.getDrawDividers(),
e.getDividerStroke(), e.getDividerPaint());
info[i] = n;
}
axis.setLabelInfo(info);
}
/**
* Applies the attributes for this theme to an {@link AbstractRenderer}.
*
* @param renderer the renderer (<code>null</code> not permitted).
*/
protected void applyToAbstractRenderer(AbstractRenderer renderer) {
if (renderer.getAutoPopulateSeriesPaint()) {
renderer.clearSeriesPaints(false);
}
if (renderer.getAutoPopulateSeriesStroke()) {
renderer.clearSeriesStrokes(false);
}
}
/**
* Applies the settings of this theme to the specified renderer.
*
* @param renderer the renderer (<code>null</code> not permitted).
*/
protected void applyToCategoryItemRenderer(CategoryItemRenderer renderer) {
if (renderer == null) {
throw new IllegalArgumentException("Null 'renderer' argument.");
}
if (renderer instanceof AbstractRenderer) {
applyToAbstractRenderer((AbstractRenderer) renderer);
}
renderer.setBaseItemLabelFont(this.regularFont);
renderer.setBaseItemLabelPaint(this.itemLabelPaint);
// now we handle some special cases - yes, UGLY code alert!
// BarRenderer
if (renderer instanceof BarRenderer) {
BarRenderer br = (BarRenderer) renderer;
br.setBarPainter(this.barPainter);
br.setShadowVisible(this.shadowVisible);
br.setShadowPaint(this.shadowPaint);
}
// BarRenderer3D
if (renderer instanceof BarRenderer3D) {
BarRenderer3D br3d = (BarRenderer3D) renderer;
br3d.setWallPaint(this.wallPaint);
}
// LineRenderer3D
if (renderer instanceof LineRenderer3D) {
LineRenderer3D lr3d = (LineRenderer3D) renderer;
lr3d.setWallPaint(this.wallPaint);
}
// StatisticalBarRenderer
if (renderer instanceof StatisticalBarRenderer) {
StatisticalBarRenderer sbr = (StatisticalBarRenderer) renderer;
sbr.setErrorIndicatorPaint(this.errorIndicatorPaint);
}
// MinMaxCategoryRenderer
if (renderer instanceof MinMaxCategoryRenderer) {
MinMaxCategoryRenderer mmcr = (MinMaxCategoryRenderer) renderer;
mmcr.setGroupPaint(this.errorIndicatorPaint);
}
}
/**
* Applies the settings of this theme to the specified renderer.
*
* @param renderer the renderer (<code>null</code> not permitted).
*/
protected void applyToXYItemRenderer(XYItemRenderer renderer) {
if (renderer == null) {
throw new IllegalArgumentException("Null 'renderer' argument.");
}
if (renderer instanceof AbstractRenderer) {
applyToAbstractRenderer((AbstractRenderer) renderer);
}
renderer.setBaseItemLabelFont(this.regularFont);
renderer.setBaseItemLabelPaint(this.itemLabelPaint);
if (renderer instanceof XYBarRenderer) {
XYBarRenderer br = (XYBarRenderer) renderer;
br.setBarPainter(this.xyBarPainter);
br.setShadowVisible(this.shadowVisible);
}
}
/**
* Applies the settings of this theme to the specified annotation.
*
* @param annotation the annotation.
*/
protected void applyToXYAnnotation(XYAnnotation annotation) {
if (annotation == null) {
throw new IllegalArgumentException("Null 'annotation' argument.");
}
if (annotation instanceof XYTextAnnotation) {
XYTextAnnotation xyta = (XYTextAnnotation) annotation;
xyta.setFont(this.smallFont);
xyta.setPaint(this.itemLabelPaint);
}
}
/**
* Tests this theme for equality with an arbitrary object.
*
* @param obj the object (<code>null</code> permitted).
*
* @return A boolean.
*/
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof StandardChartTheme)) {
return false;
}
StandardChartTheme that = (StandardChartTheme) obj;
if (!this.name.equals(that.name)) {
return false;
}
if (!this.extraLargeFont.equals(that.extraLargeFont)) {
return false;
}
if (!this.largeFont.equals(that.largeFont)) {
return false;
}
if (!this.regularFont.equals(that.regularFont)) {
return false;
}
if (!this.smallFont.equals(that.smallFont)) {
return false;
}
if (!PaintUtilities.equal(this.titlePaint, that.titlePaint)) {
return false;
}
if (!PaintUtilities.equal(this.subtitlePaint, that.subtitlePaint)) {
return false;
}
if (!PaintUtilities.equal(this.chartBackgroundPaint,
that.chartBackgroundPaint)) {
return false;
}
if (!PaintUtilities.equal(this.legendBackgroundPaint,
that.legendBackgroundPaint)) {
return false;
}
if (!PaintUtilities.equal(this.legendItemPaint, that.legendItemPaint)) {
return false;
}
if (!this.drawingSupplier.equals(that.drawingSupplier)) {
return false;
}
if (!PaintUtilities.equal(this.plotBackgroundPaint,
that.plotBackgroundPaint)) {
return false;
}
if (!PaintUtilities.equal(this.plotOutlinePaint,
that.plotOutlinePaint)) {
return false;
}
if (!this.labelLinkStyle.equals(that.labelLinkStyle)) {
return false;
}
if (!PaintUtilities.equal(this.labelLinkPaint, that.labelLinkPaint)) {
return false;
}
if (!PaintUtilities.equal(this.domainGridlinePaint,
that.domainGridlinePaint)) {
return false;
}
if (!PaintUtilities.equal(this.rangeGridlinePaint,
that.rangeGridlinePaint)) {
return false;
}
if (!PaintUtilities.equal(this.crosshairPaint, that.crosshairPaint)) {
return false;
}
if (!this.axisOffset.equals(that.axisOffset)) {
return false;
}
if (!PaintUtilities.equal(this.axisLabelPaint, that.axisLabelPaint)) {
return false;
}
if (!PaintUtilities.equal(this.tickLabelPaint, that.tickLabelPaint)) {
return false;
}
if (!PaintUtilities.equal(this.itemLabelPaint, that.itemLabelPaint)) {
return false;
}
if (this.shadowVisible != that.shadowVisible) {
return false;
}
if (!PaintUtilities.equal(this.shadowPaint, that.shadowPaint)) {
return false;
}
if (!this.barPainter.equals(that.barPainter)) {
return false;
}
if (!this.xyBarPainter.equals(that.xyBarPainter)) {
return false;
}
if (!PaintUtilities.equal(this.thermometerPaint,
that.thermometerPaint)) {
return false;
}
if (!PaintUtilities.equal(this.wallPaint, that.wallPaint)) {
return false;
}
if (!PaintUtilities.equal(this.errorIndicatorPaint,
that.errorIndicatorPaint)) {
return false;
}
if (!PaintUtilities.equal(this.gridBandPaint, that.gridBandPaint)) {
return false;
}
if (!PaintUtilities.equal(this.gridBandAlternatePaint,
that.gridBandAlternatePaint)) {
return false;
}
return true;
}
/**
* Returns a clone of this theme.
*
* @return A clone.
*
* @throws CloneNotSupportedException if the theme cannot be cloned.
*/
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
/**
* Provides serialization support.
*
* @param stream the output stream (<code>null</code> not permitted).
*
* @throws IOException if there is an I/O error.
*/
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
SerialUtilities.writePaint(this.titlePaint, stream);
SerialUtilities.writePaint(this.subtitlePaint, stream);
SerialUtilities.writePaint(this.chartBackgroundPaint, stream);
SerialUtilities.writePaint(this.legendBackgroundPaint, stream);
SerialUtilities.writePaint(this.legendItemPaint, stream);
SerialUtilities.writePaint(this.plotBackgroundPaint, stream);
SerialUtilities.writePaint(this.plotOutlinePaint, stream);
SerialUtilities.writePaint(this.labelLinkPaint, stream);
SerialUtilities.writePaint(this.baselinePaint, stream);
SerialUtilities.writePaint(this.domainGridlinePaint, stream);
SerialUtilities.writePaint(this.rangeGridlinePaint, stream);
SerialUtilities.writePaint(this.crosshairPaint, stream);
SerialUtilities.writePaint(this.axisLabelPaint, stream);
SerialUtilities.writePaint(this.tickLabelPaint, stream);
SerialUtilities.writePaint(this.itemLabelPaint, stream);
SerialUtilities.writePaint(this.shadowPaint, stream);
SerialUtilities.writePaint(this.thermometerPaint, stream);
SerialUtilities.writePaint(this.wallPaint, stream);
SerialUtilities.writePaint(this.errorIndicatorPaint, stream);
SerialUtilities.writePaint(this.gridBandPaint, stream);
SerialUtilities.writePaint(this.gridBandAlternatePaint, stream);
}
/**
* Provides serialization support.
*
* @param stream the input stream (<code>null</code> not permitted).
*
* @throws IOException if there is an I/O error.
* @throws ClassNotFoundException if there is a classpath problem.
*/
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
this.titlePaint = SerialUtilities.readPaint(stream);
this.subtitlePaint = SerialUtilities.readPaint(stream);
this.chartBackgroundPaint = SerialUtilities.readPaint(stream);
this.legendBackgroundPaint = SerialUtilities.readPaint(stream);
this.legendItemPaint = SerialUtilities.readPaint(stream);
this.plotBackgroundPaint = SerialUtilities.readPaint(stream);
this.plotOutlinePaint = SerialUtilities.readPaint(stream);
this.labelLinkPaint = SerialUtilities.readPaint(stream);
this.baselinePaint = SerialUtilities.readPaint(stream);
this.domainGridlinePaint = SerialUtilities.readPaint(stream);
this.rangeGridlinePaint = SerialUtilities.readPaint(stream);
this.crosshairPaint = SerialUtilities.readPaint(stream);
this.axisLabelPaint = SerialUtilities.readPaint(stream);
this.tickLabelPaint = SerialUtilities.readPaint(stream);
this.itemLabelPaint = SerialUtilities.readPaint(stream);
this.shadowPaint = SerialUtilities.readPaint(stream);
this.thermometerPaint = SerialUtilities.readPaint(stream);
this.wallPaint = SerialUtilities.readPaint(stream);
this.errorIndicatorPaint = SerialUtilities.readPaint(stream);
this.gridBandPaint = SerialUtilities.readPaint(stream);
this.gridBandAlternatePaint = SerialUtilities.readPaint(stream);
}
}
| 27,402 |
446 | import numpy as np
import pandas as pd
def get_time_decay(uniq_weight, last=1.):
"""Calculate time decay weight
Params
------
uniq_weight: pd.Series
Sampling weight calculated label uniqueness
last: float, default 1, no decay
Parameter to detemine the slope and constant
Returns
-------
pd.Series
"""
weight = uniq_weight.sort_index().cumsum()
if last > 0:
slope = (1 - last) / weight.iloc[-1]
else:
slope = 1 / ((1 + last) * weight.iloc[-1])
const = 1. - slope * weight.iloc[-1]
weight = const + slope * weight
weight[weight < 0] = 0
return weight | 276 |
5,730 | <filename>src/main/java/org/ansj/app/extracting/domain/Token.java<gh_stars>1000+
package org.ansj.app.extracting.domain;
import org.ansj.app.extracting.exception.RuleFormatException;
import java.util.*;
/**
* Created by Ansj on 29/08/2017.
*/
public class Token {
public static final String ALL = ":*" ;
private int index;
private Set<String> terms = new HashSet<String>();
private List<String> regexs;//正则限定
private int[] range;//范围限定
private Token prev ;
private Token next ;
public Token(int index, String termsStr) {
this.index = index;
String[] split = termsStr.substring(1, termsStr.length() - 1).split("\\|");
for (String str : split) {
terms.add(str);
}
}
public void addAttr(String str) throws RuleFormatException {
char head = str.charAt(0);
str = str.substring(1, str.length() - 1);
if (head == '[') {
if (regexs == null) {
regexs = new ArrayList<String>();
}
regexs.add(str);
} else if (head == '{') {
String[] split = str.split(",");
if (range == null) {
range = new int[2];
}
if (split.length >= 2) {
range[0] = Integer.parseInt(split[0].trim());
range[1] = Integer.parseInt(split[1].trim());
} else {
range[0] = Integer.parseInt(split[0].trim());
range[1] = Integer.parseInt(split[0].trim());
}
} else {
throw new RuleFormatException("err format attr by " + str);
}
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public Set<String> getTerms() {
return terms;
}
public void setTerms(Set<String> terms) {
this.terms = terms;
}
public List<String> getRegexs() {
if(regexs==null){
return Collections.emptyList() ;
}
return regexs;
}
public void setRegexs(List<String> regexs) {
this.regexs = regexs;
}
public int[] getRange() {
return range;
}
public void setRange(int[] range) {
this.range = range;
}
public Token getPrev() {
return prev;
}
public Token getNext() {
return next;
}
public void setNext(Token next) {
this.next = next;
next.prev = this;
}
@Override
public String toString() {
return "index="+index+",terms="+terms+",regexs="+regexs+",range="+ Arrays.toString(range);
}
}
| 903 |
1,724 | #pragma once
#include <libio/Reader.h>
#include <libio/Scanner.h>
#include <libutils/String.h>
#include <libxml/Decl.h>
#include <libxml/Node.h>
namespace Xml
{
struct Doc
{
private:
Node _root;
Decl _decl;
public:
Decl &decl() { return _decl; }
void decl(Decl decl) { _decl = decl; }
Node &root() { return _root; }
void root(Node node) { _root = node; }
};
} // namespace Xml | 170 |
11,533 | <gh_stars>1000+
"""
Sane List Extension for Python-Markdown
=======================================
Modify the behavior of Lists in Python-Markdown to act in a sane manor.
See <https://pythonhosted.org/Markdown/extensions/sane_lists.html>
for documentation.
Original code Copyright 2011 [<NAME>](http://achinghead.com)
All changes Copyright 2011-2014 The Python Markdown Project
License: [BSD](http://www.opensource.org/licenses/bsd-license.php)
"""
from __future__ import absolute_import
from __future__ import unicode_literals
from . import Extension
from ..blockprocessors import OListProcessor, UListProcessor
import re
class SaneOListProcessor(OListProcessor):
SIBLING_TAGS = ['ol']
def __init__(self, parser):
super(SaneOListProcessor, self).__init__(parser)
self.CHILD_RE = re.compile(r'^[ ]{0,%d}((\d+\.))[ ]+(.*)' %
(self.tab_length - 1))
class SaneUListProcessor(UListProcessor):
SIBLING_TAGS = ['ul']
def __init__(self, parser):
super(SaneUListProcessor, self).__init__(parser)
self.CHILD_RE = re.compile(r'^[ ]{0,%d}(([*+-]))[ ]+(.*)' %
(self.tab_length - 1))
class SaneListExtension(Extension):
""" Add sane lists to Markdown. """
def extendMarkdown(self, md, md_globals):
""" Override existing Processors. """
md.parser.blockprocessors['olist'] = SaneOListProcessor(md.parser)
md.parser.blockprocessors['ulist'] = SaneUListProcessor(md.parser)
def makeExtension(*args, **kwargs):
return SaneListExtension(*args, **kwargs)
| 640 |
454 | """
Tests for the Hotjar template tags.
"""
import pytest
from django.http import HttpRequest
from django.template import Context, Template, TemplateSyntaxError
from django.test import override_settings
from utils import TagTestCase
from analytical.templatetags.analytical import _load_template_nodes
from analytical.templatetags.hotjar import HotjarNode
from analytical.utils import AnalyticalException
expected_html = """\
<script>
(function(h,o,t,j,a,r){
h.hj=h.hj||function(){(h.hj.q=h.hj.q||[]).push(arguments)};
h._hjSettings={hjid:123456789,hjsv:6};
a=o.getElementsByTagName('head')[0];
r=o.createElement('script');r.async=1;
r.src=t+h._hjSettings.hjid+j+h._hjSettings.hjsv;
a.appendChild(r);
})(window,document,'https://static.hotjar.com/c/hotjar-','.js?sv=');
</script>
"""
@override_settings(HOTJAR_SITE_ID='123456789')
class HotjarTagTestCase(TagTestCase):
maxDiff = None
def test_tag(self):
html = self.render_tag('hotjar', 'hotjar')
assert expected_html == html
def test_node(self):
html = HotjarNode().render(Context({}))
assert expected_html == html
def test_tags_take_no_args(self):
with pytest.raises(TemplateSyntaxError, match="'hotjar' takes no arguments"):
Template('{% load hotjar %}{% hotjar "arg" %}').render(Context({}))
@override_settings(HOTJAR_SITE_ID=None)
def test_no_id(self):
with pytest.raises(AnalyticalException, match="HOTJAR_SITE_ID setting is not set"):
HotjarNode()
@override_settings(HOTJAR_SITE_ID='invalid')
def test_invalid_id(self):
expected_pattern = (
r"^HOTJAR_SITE_ID setting: must be \(a string containing\) a number: 'invalid'$")
with pytest.raises(AnalyticalException, match=expected_pattern):
HotjarNode()
@override_settings(ANALYTICAL_INTERNAL_IPS=['1.1.1.1'])
def test_render_internal_ip(self):
request = HttpRequest()
request.META['REMOTE_ADDR'] = '1.1.1.1'
context = Context({'request': request})
actual_html = HotjarNode().render(context)
disabled_html = '\n'.join([
'<!-- Hotjar disabled on internal IP address',
expected_html,
'-->',
])
assert disabled_html == actual_html
def test_contribute_to_analytical(self):
"""
`hotjar.contribute_to_analytical` registers the head and body nodes.
"""
template_nodes = _load_template_nodes()
assert template_nodes == {
'head_top': [],
'head_bottom': [HotjarNode],
'body_top': [],
'body_bottom': [],
}
| 1,182 |
1,551 | <filename>src/DBusObjectPath.h
// Copyright 2017-2019 <NAME>
//
// This file is part of Gobbledegook.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file in the root of the source tree.
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// >>
// >>> INSIDE THIS FILE
// >>
//
// This represents a custom string type for a D-Bus object path.
//
// >>
// >>> DISCUSSION
// >>
//
// A D-Bus object path is normal string in the form "/com/example/foo/bar". This class provides a set of methods for building
// these paths safely in such a way that they are guaranteed to always provide a valid path.
//
// In addition to this functionality, our DBusObjectPath is its own distinct type requiring explicit conversion, providing a level
// of protection against accidentally using an arbitrary string as an object path.
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#pragma once
#include <string>
#include <ostream>
namespace ggk {
struct DBusObjectPath
{
// Default constructor (creates a root path)
inline DBusObjectPath() { path = "/"; }
// Copy constructor
inline DBusObjectPath(const DBusObjectPath &path) : path(path.path) {}
// Constructor that accepts a C string
//
// Note: explicit because we don't want accidental conversion. Creating a DBusObjectPath must be intentional.
inline explicit DBusObjectPath(const char *pPath) : path(pPath) {}
// Constructor that accepts a std::string
//
// Note: explicit because we don't want accidental conversion. Creating a DBusObjectPath must be intentional.
inline explicit DBusObjectPath(const std::string &path) : path(path) {}
// Explicit conversion to std::string
inline const std::string &toString() const { return path; }
// Explicit conversion to a C string
inline const char *c_str() const { return path.c_str(); }
// Assignment
inline DBusObjectPath &operator =(const DBusObjectPath &rhs)
{
if (this == &rhs) return *this;
path = rhs.path;
return *this;
}
// Concatenation
inline const DBusObjectPath &append(const char *rhs)
{
if (nullptr == rhs || !*rhs) { return *this; }
if (path.empty()) { path = rhs; return *this; }
bool ls = path.back() == '/';
bool rs = *rhs == '/';
if (ls && rs) { path.erase(path.length()-1); }
if (!ls && !rs) { path += "/"; }
path += rhs;
return *this;
}
// Adds a path node (in the form of an std::string) to the end of the path
inline const DBusObjectPath &append(const std::string &rhs)
{
return append(rhs.c_str());
}
// Adds a path node (in the form of a DBusObjectPath) to the end of the path
inline const DBusObjectPath &append(const DBusObjectPath &rhs)
{
return append(rhs.path.c_str());
}
// Adds a path node (in the form of a DBusObjectPath) to the end of the path
inline void operator +=(const DBusObjectPath &rhs)
{
append(rhs);
}
// Adds a path node (in the form of a C string) to the end of the path
inline void operator +=(const char *rhs)
{
append(rhs);
}
// Adds a path node (in the form of an std::string) to the end of the path
inline void operator +=(const std::string &rhs)
{
append(rhs);
}
// Concats two DBusObjectPaths into one, returning the resulting path
inline DBusObjectPath operator +(const DBusObjectPath &rhs) const
{
DBusObjectPath result(*this);
result += rhs;
return result;
}
// Concats a C string onto a DBusObjectPath, returning the resulting path
inline DBusObjectPath operator +(const char *rhs) const
{
DBusObjectPath result(*this);
result += rhs;
return result;
}
// Concats a std::string onto a DBusObjectPath, returning the resulting path
inline DBusObjectPath operator +(const std::string &rhs) const
{
DBusObjectPath result(*this);
result += rhs;
return result;
}
// Tests two DBusObjectPaths for equality, returning true of the two strings are identical
inline bool operator ==(const DBusObjectPath &rhs) const
{
return path == rhs.path;
}
private:
std::string path;
};
// Mixed-mode override for adding a DBusObjectPath to a C string, returning a new DBusObjectPath result
inline DBusObjectPath operator +(const char *lhs, const DBusObjectPath &rhs) { return DBusObjectPath(lhs) + rhs; }
// Mixed-mode override for adding a DBusObjectPath to a std::string, returning a new DBusObjectPath result
inline DBusObjectPath operator +(const std::string &lhs, const DBusObjectPath &rhs) { return DBusObjectPath(lhs) + rhs; }
// Streaming support for our DBusObjectPath (useful for our logging mechanism)
inline std::ostream& operator<<(std::ostream &os, const DBusObjectPath &path)
{
os << path.toString();
return os;
}
// Streaming support for our DBusObjectPath (useful for our logging mechanism)
inline std::ostream& operator +(std::ostream &os, const DBusObjectPath &path)
{
os << path.toString();
return os;
}
}; // namespace ggk | 1,552 |
608 | // -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
/*
* Copyright 2012 ZXing 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.
*
* 2012-09-19 HFN translation from Java into C++
*/
#include <zxing/pdf417/decoder/ec/ModulusGF.h>
#include <zxing/pdf417/decoder/ec/ModulusPoly.h>
using zxing::Ref;
using zxing::pdf417::decoder::ec::ModulusGF;
using zxing::pdf417::decoder::ec::ModulusPoly;
/**
* The central Modulus Galois Field for PDF417 with prime number 929
* and generator 3.
*/
ModulusGF ModulusGF::PDF417_GF(929,3);
/**
* <p>A field based on powers of a generator integer, modulo some modulus.</p>
*
* @author <NAME>
* @see com.google.zxing.common.reedsolomon.GenericGF
*/
ModulusGF::ModulusGF(int modulus, int generator)
: modulus_(modulus) {
expTable_ = new Array<int>(modulus_);
logTable_ = new Array<int>(modulus_);
int x = 1,i;
for (i = 0; i < modulus_; i++) {
expTable_[i] = x;
x = (x * generator) % modulus_;
}
for (i = 0; i < modulus_-1; i++) {
logTable_[expTable_[i]] = i;
}
// logTable[0] == 0 but this should never be used
ArrayRef<int>aZero(new Array<int>(1)),aOne(new Array<int>(1));
aZero[0]=0;aOne[0]=1;
zero_ = new ModulusPoly(*this, aZero);
one_ = new ModulusPoly(*this, aOne);
}
Ref<ModulusPoly> ModulusGF::getZero() {
return zero_;
}
Ref<ModulusPoly> ModulusGF::getOne() {
return one_;
}
Ref<ModulusPoly> ModulusGF::buildMonomial(int degree, int coefficient)
{
if (degree < 0) {
throw IllegalArgumentException("monomial: degree < 0!");
}
if (coefficient == 0) {
return zero_;
}
int nCoefficients = degree + 1;
ArrayRef<int> coefficients (new Array<int>(nCoefficients));
coefficients[0] = coefficient;
Ref<ModulusPoly> result(new ModulusPoly(*this,coefficients));
return result;
}
int ModulusGF::add(int a, int b) {
return (a + b) % modulus_;
}
int ModulusGF::subtract(int a, int b) {
return (modulus_ + a - b) % modulus_;
}
int ModulusGF::exp(int a) {
return expTable_[a];
}
int ModulusGF::log(int a) {
if (a == 0) {
throw IllegalArgumentException("log of zero!");
}
return logTable_[a];
}
int ModulusGF::inverse(int a) {
if (a == 0) {
throw IllegalArgumentException("inverse of zero!");;
}
return expTable_[modulus_ - logTable_[a] - 1];
}
int ModulusGF::multiply(int a, int b) {
if (a == 0 || b == 0) {
return 0;
}
return expTable_[(logTable_[a] + logTable_[b]) % (modulus_ - 1)];
}
int ModulusGF::getSize() {
return modulus_;
}
| 1,141 |
1,875 | /*
* Copyright 2020 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright (c) 2007-present, <NAME> & <NAME>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of JSR-310 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.
*/
package org.teavm.classlib.java.time;
import static java.time.temporal.ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH;
import static java.time.temporal.ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR;
import static java.time.temporal.ChronoField.ALIGNED_WEEK_OF_MONTH;
import static java.time.temporal.ChronoField.ALIGNED_WEEK_OF_YEAR;
import static java.time.temporal.ChronoField.AMPM_OF_DAY;
import static java.time.temporal.ChronoField.CLOCK_HOUR_OF_AMPM;
import static java.time.temporal.ChronoField.CLOCK_HOUR_OF_DAY;
import static java.time.temporal.ChronoField.DAY_OF_MONTH;
import static java.time.temporal.ChronoField.DAY_OF_WEEK;
import static java.time.temporal.ChronoField.DAY_OF_YEAR;
import static java.time.temporal.ChronoField.EPOCH_DAY;
import static java.time.temporal.ChronoField.ERA;
import static java.time.temporal.ChronoField.HOUR_OF_AMPM;
import static java.time.temporal.ChronoField.HOUR_OF_DAY;
import static java.time.temporal.ChronoField.MICRO_OF_DAY;
import static java.time.temporal.ChronoField.MICRO_OF_SECOND;
import static java.time.temporal.ChronoField.MILLI_OF_DAY;
import static java.time.temporal.ChronoField.MILLI_OF_SECOND;
import static java.time.temporal.ChronoField.MINUTE_OF_DAY;
import static java.time.temporal.ChronoField.MINUTE_OF_HOUR;
import static java.time.temporal.ChronoField.MONTH_OF_YEAR;
import static java.time.temporal.ChronoField.NANO_OF_DAY;
import static java.time.temporal.ChronoField.NANO_OF_SECOND;
import static java.time.temporal.ChronoField.PROLEPTIC_MONTH;
import static java.time.temporal.ChronoField.SECOND_OF_DAY;
import static java.time.temporal.ChronoField.SECOND_OF_MINUTE;
import static java.time.temporal.ChronoField.YEAR;
import static java.time.temporal.ChronoField.YEAR_OF_ERA;
import static java.time.temporal.ChronoUnit.HALF_DAYS;
import static java.time.temporal.ChronoUnit.HOURS;
import static java.time.temporal.ChronoUnit.MICROS;
import static java.time.temporal.ChronoUnit.MILLIS;
import static java.time.temporal.ChronoUnit.MINUTES;
import static java.time.temporal.ChronoUnit.NANOS;
import static java.time.temporal.ChronoUnit.SECONDS;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertSame;
import static org.testng.Assert.assertTrue;
import java.time.Clock;
import java.time.DateTimeException;
import java.time.DayOfWeek;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import java.time.Year;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.chrono.IsoChronology;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;
import java.time.temporal.JulianFields;
import java.time.temporal.TemporalAccessor;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalField;
import java.time.temporal.TemporalQueries;
import java.time.temporal.TemporalUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import org.junit.runner.RunWith;
import org.teavm.classlib.java.time.temporal.MockFieldNoValue;
import org.teavm.junit.TeaVMTestRunner;
import org.teavm.junit.WholeClassCompilation;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
/**
* Test LocalDateTime.
*/
@Test
@RunWith(TeaVMTestRunner.class)
@WholeClassCompilation
public class TestLocalDateTime extends AbstractDateTimeTest {
private static final ZoneOffset OFFSET_PONE = ZoneOffset.ofHours(1);
private static final ZoneOffset OFFSET_PTWO = ZoneOffset.ofHours(2);
private static final ZoneOffset OFFSET_MTWO = ZoneOffset.ofHours(-2);
private static final ZoneId ZONE_PARIS = ZoneId.of("Europe/Paris");
private static final ZoneId ZONE_GAZA = ZoneId.of("Asia/Gaza");
private LocalDateTime test2007x07x15x12x30x40x987654321 = LocalDateTime.of(2007, 7, 15, 12, 30, 40, 987654321);
private LocalDateTime maxDateTime;
private LocalDateTime minDateTime;
private Instant maxInstant;
private Instant minInstant;
@BeforeMethod
public void setUp() {
maxDateTime = LocalDateTime.MAX;
minDateTime = LocalDateTime.MIN;
maxInstant = maxDateTime.atZone(ZoneOffset.UTC).toInstant();
minInstant = minDateTime.atZone(ZoneOffset.UTC).toInstant();
}
//-----------------------------------------------------------------------
@Override
protected List<TemporalAccessor> samples() {
TemporalAccessor[] array = { test2007x07x15x12x30x40x987654321, LocalDateTime.MAX, LocalDateTime.MIN, };
return Arrays.asList(array);
}
@Override
protected List<TemporalField> validFields() {
TemporalField[] array = {
NANO_OF_SECOND,
NANO_OF_DAY,
MICRO_OF_SECOND,
MICRO_OF_DAY,
MILLI_OF_SECOND,
MILLI_OF_DAY,
SECOND_OF_MINUTE,
SECOND_OF_DAY,
MINUTE_OF_HOUR,
MINUTE_OF_DAY,
CLOCK_HOUR_OF_AMPM,
HOUR_OF_AMPM,
CLOCK_HOUR_OF_DAY,
HOUR_OF_DAY,
AMPM_OF_DAY,
DAY_OF_WEEK,
ALIGNED_DAY_OF_WEEK_IN_MONTH,
ALIGNED_DAY_OF_WEEK_IN_YEAR,
DAY_OF_MONTH,
DAY_OF_YEAR,
EPOCH_DAY,
ALIGNED_WEEK_OF_MONTH,
ALIGNED_WEEK_OF_YEAR,
MONTH_OF_YEAR,
PROLEPTIC_MONTH,
YEAR_OF_ERA,
YEAR,
ERA,
JulianFields.JULIAN_DAY,
JulianFields.MODIFIED_JULIAN_DAY,
JulianFields.RATA_DIE,
};
return Arrays.asList(array);
}
@Override
protected List<TemporalField> invalidFields() {
List<TemporalField> list = new ArrayList<>(Arrays.asList(ChronoField.values()));
list.removeAll(validFields());
return list;
}
//-----------------------------------------------------------------------
private void check(LocalDateTime dateTime, int y, int m, int d, int h, int mi, int s, int n) {
assertEquals(dateTime.getYear(), y);
assertEquals(dateTime.getMonth().getValue(), m);
assertEquals(dateTime.getDayOfMonth(), d);
assertEquals(dateTime.getHour(), h);
assertEquals(dateTime.getMinute(), mi);
assertEquals(dateTime.getSecond(), s);
assertEquals(dateTime.getNano(), n);
}
private LocalDateTime createDateMidnight(int year, int month, int day) {
return LocalDateTime.of(year, month, day, 0, 0);
}
//-----------------------------------------------------------------------
// now()
//-----------------------------------------------------------------------
@Test
public void now() {
LocalDateTime expected = LocalDateTime.now(Clock.systemDefaultZone());
LocalDateTime test = LocalDateTime.now();
long diff = Math.abs(test.toLocalTime().toNanoOfDay() - expected.toLocalTime().toNanoOfDay());
if (diff >= 100000000) {
// may be date change
expected = LocalDateTime.now(Clock.systemDefaultZone());
test = LocalDateTime.now();
diff = Math.abs(test.toLocalTime().toNanoOfDay() - expected.toLocalTime().toNanoOfDay());
}
assertTrue(diff < 100000000); // less than 0.1 secs
}
//-----------------------------------------------------------------------
// now(ZoneId)
//-----------------------------------------------------------------------
@Test(expectedExceptions = NullPointerException.class)
public void now_ZoneId_nullZoneId() {
LocalDateTime.now((ZoneId) null);
}
@Test
public void now_ZoneId() {
ZoneId zone = ZoneId.of("UTC+01:02:03");
LocalDateTime expected = LocalDateTime.now(Clock.system(zone));
LocalDateTime test = LocalDateTime.now(zone);
for (int i = 0; i < 100; i++) {
if (expected.equals(test)) {
return;
}
expected = LocalDateTime.now(Clock.system(zone));
test = LocalDateTime.now(zone);
}
assertEquals(test, expected);
}
//-----------------------------------------------------------------------
// now(Clock)
//-----------------------------------------------------------------------
@Test(expectedExceptions = NullPointerException.class)
public void now_Clock_nullClock() {
LocalDateTime.now((Clock) null);
}
@Test
public void now_Clock_allSecsInDay_utc() {
for (int i = 0; i < (2 * 24 * 60 * 60); i++) {
Instant instant = Instant.ofEpochSecond(i).plusNanos(123456789L);
Clock clock = Clock.fixed(instant, ZoneOffset.UTC);
LocalDateTime test = LocalDateTime.now(clock);
assertEquals(test.getYear(), 1970);
assertEquals(test.getMonth(), Month.JANUARY);
assertEquals(test.getDayOfMonth(), i < 24 * 60 * 60 ? 1 : 2);
assertEquals(test.getHour(), (i / (60 * 60)) % 24);
assertEquals(test.getMinute(), (i / 60) % 60);
assertEquals(test.getSecond(), i % 60);
assertEquals(test.getNano(), 123456789);
}
}
@Test
public void now_Clock_allSecsInDay_offset() {
for (int i = 0; i < (2 * 24 * 60 * 60); i++) {
Instant instant = Instant.ofEpochSecond(i).plusNanos(123456789L);
Clock clock = Clock.fixed(instant.minusSeconds(OFFSET_PONE.getTotalSeconds()), OFFSET_PONE);
LocalDateTime test = LocalDateTime.now(clock);
assertEquals(test.getYear(), 1970);
assertEquals(test.getMonth(), Month.JANUARY);
assertEquals(test.getDayOfMonth(), (i < 24 * 60 * 60) ? 1 : 2);
assertEquals(test.getHour(), (i / (60 * 60)) % 24);
assertEquals(test.getMinute(), (i / 60) % 60);
assertEquals(test.getSecond(), i % 60);
assertEquals(test.getNano(), 123456789);
}
}
@Test
public void now_Clock_allSecsInDay_beforeEpoch() {
LocalTime expected = LocalTime.MIDNIGHT.plusNanos(123456789L);
for (int i = -1; i >= -(24 * 60 * 60); i--) {
Instant instant = Instant.ofEpochSecond(i).plusNanos(123456789L);
Clock clock = Clock.fixed(instant, ZoneOffset.UTC);
LocalDateTime test = LocalDateTime.now(clock);
assertEquals(test.getYear(), 1969);
assertEquals(test.getMonth(), Month.DECEMBER);
assertEquals(test.getDayOfMonth(), 31);
expected = expected.minusSeconds(1);
assertEquals(test.toLocalTime(), expected);
}
}
//-----------------------------------------------------------------------
@Test
public void now_Clock_maxYear() {
Clock clock = Clock.fixed(maxInstant, ZoneOffset.UTC);
LocalDateTime test = LocalDateTime.now(clock);
assertEquals(test, maxDateTime);
}
@Test(expectedExceptions = DateTimeException.class)
public void now_Clock_tooBig() {
Clock clock = Clock.fixed(maxInstant.plusSeconds(24 * 60 * 60), ZoneOffset.UTC);
LocalDateTime.now(clock);
}
@Test
public void now_Clock_minYear() {
Clock clock = Clock.fixed(minInstant, ZoneOffset.UTC);
LocalDateTime test = LocalDateTime.now(clock);
assertEquals(test, minDateTime);
}
@Test(expectedExceptions = DateTimeException.class)
public void now_Clock_tooLow() {
Clock clock = Clock.fixed(minInstant.minusNanos(1), ZoneOffset.UTC);
LocalDateTime.now(clock);
}
//-----------------------------------------------------------------------
// of() factories
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
@Test
public void factory_of_4intsMonth() {
LocalDateTime dateTime = LocalDateTime.of(2007, Month.JULY, 15, 12, 30);
check(dateTime, 2007, 7, 15, 12, 30, 0, 0);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_4intsMonth_yearTooLow() {
LocalDateTime.of(Integer.MIN_VALUE, Month.JULY, 15, 12, 30);
}
@Test(expectedExceptions = NullPointerException.class)
public void factory_of_4intsMonth_nullMonth() {
LocalDateTime.of(2007, null, 15, 12, 30);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_4intsMonth_dayTooLow() {
LocalDateTime.of(2007, Month.JULY, -1, 12, 30);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_4intsMonth_dayTooHigh() {
LocalDateTime.of(2007, Month.JULY, 32, 12, 30);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_4intsMonth_hourTooLow() {
LocalDateTime.of(2007, Month.JULY, 15, -1, 30);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_4intsMonth_hourTooHigh() {
LocalDateTime.of(2007, Month.JULY, 15, 24, 30);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_4intsMonth_minuteTooLow() {
LocalDateTime.of(2007, Month.JULY, 15, 12, -1);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_4intsMonth_minuteTooHigh() {
LocalDateTime.of(2007, Month.JULY, 15, 12, 60);
}
//-----------------------------------------------------------------------
@Test
public void factory_of_5intsMonth() {
LocalDateTime dateTime = LocalDateTime.of(2007, Month.JULY, 15, 12, 30, 40);
check(dateTime, 2007, 7, 15, 12, 30, 40, 0);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_5intsMonth_yearTooLow() {
LocalDateTime.of(Integer.MIN_VALUE, Month.JULY, 15, 12, 30, 40);
}
@Test(expectedExceptions = NullPointerException.class)
public void factory_of_5intsMonth_nullMonth() {
LocalDateTime.of(2007, null, 15, 12, 30, 40);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_5intsMonth_dayTooLow() {
LocalDateTime.of(2007, Month.JULY, -1, 12, 30, 40);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_5intsMonth_dayTooHigh() {
LocalDateTime.of(2007, Month.JULY, 32, 12, 30, 40);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_5intsMonth_hourTooLow() {
LocalDateTime.of(2007, Month.JULY, 15, -1, 30, 40);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_5intsMonth_hourTooHigh() {
LocalDateTime.of(2007, Month.JULY, 15, 24, 30, 40);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_5intsMonth_minuteTooLow() {
LocalDateTime.of(2007, Month.JULY, 15, 12, -1, 40);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_5intsMonth_minuteTooHigh() {
LocalDateTime.of(2007, Month.JULY, 15, 12, 60, 40);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_5intsMonth_secondTooLow() {
LocalDateTime.of(2007, Month.JULY, 15, 12, 30, -1);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_5intsMonth_secondTooHigh() {
LocalDateTime.of(2007, Month.JULY, 15, 12, 30, 60);
}
//-----------------------------------------------------------------------
@Test
public void factory_of_6intsMonth() {
LocalDateTime dateTime = LocalDateTime.of(2007, Month.JULY, 15, 12, 30, 40, 987654321);
check(dateTime, 2007, 7, 15, 12, 30, 40, 987654321);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_6intsMonth_yearTooLow() {
LocalDateTime.of(Integer.MIN_VALUE, Month.JULY, 15, 12, 30, 40, 987654321);
}
@Test(expectedExceptions = NullPointerException.class)
public void factory_of_6intsMonth_nullMonth() {
LocalDateTime.of(2007, null, 15, 12, 30, 40, 987654321);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_6intsMonth_dayTooLow() {
LocalDateTime.of(2007, Month.JULY, -1, 12, 30, 40, 987654321);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_6intsMonth_dayTooHigh() {
LocalDateTime.of(2007, Month.JULY, 32, 12, 30, 40, 987654321);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_6intsMonth_hourTooLow() {
LocalDateTime.of(2007, Month.JULY, 15, -1, 30, 40, 987654321);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_6intsMonth_hourTooHigh() {
LocalDateTime.of(2007, Month.JULY, 15, 24, 30, 40, 987654321);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_6intsMonth_minuteTooLow() {
LocalDateTime.of(2007, Month.JULY, 15, 12, -1, 40, 987654321);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_6intsMonth_minuteTooHigh() {
LocalDateTime.of(2007, Month.JULY, 15, 12, 60, 40, 987654321);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_6intsMonth_secondTooLow() {
LocalDateTime.of(2007, Month.JULY, 15, 12, 30, -1, 987654321);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_6intsMonth_secondTooHigh() {
LocalDateTime.of(2007, Month.JULY, 15, 12, 30, 60, 987654321);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_6intsMonth_nanoTooLow() {
LocalDateTime.of(2007, Month.JULY, 15, 12, 30, 40, -1);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_6intsMonth_nanoTooHigh() {
LocalDateTime.of(2007, Month.JULY, 15, 12, 30, 40, 1000000000);
}
//-----------------------------------------------------------------------
@Test
public void factory_of_5ints() {
LocalDateTime dateTime = LocalDateTime.of(2007, 7, 15, 12, 30);
check(dateTime, 2007, 7, 15, 12, 30, 0, 0);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_5ints_yearTooLow() {
LocalDateTime.of(Integer.MIN_VALUE, 7, 15, 12, 30);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_5ints_monthTooLow() {
LocalDateTime.of(2007, 0, 15, 12, 30);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_5ints_monthTooHigh() {
LocalDateTime.of(2007, 13, 15, 12, 30);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_5ints_dayTooLow() {
LocalDateTime.of(2007, 7, -1, 12, 30);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_5ints_dayTooHigh() {
LocalDateTime.of(2007, 7, 32, 12, 30);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_5ints_hourTooLow() {
LocalDateTime.of(2007, 7, 15, -1, 30);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_5ints_hourTooHigh() {
LocalDateTime.of(2007, 7, 15, 24, 30);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_5ints_minuteTooLow() {
LocalDateTime.of(2007, 7, 15, 12, -1);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_5ints_minuteTooHigh() {
LocalDateTime.of(2007, 7, 15, 12, 60);
}
//-----------------------------------------------------------------------
@Test
public void factory_of_6ints() {
LocalDateTime dateTime = LocalDateTime.of(2007, 7, 15, 12, 30, 40);
check(dateTime, 2007, 7, 15, 12, 30, 40, 0);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_6ints_yearTooLow() {
LocalDateTime.of(Integer.MIN_VALUE, 7, 15, 12, 30, 40);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_6ints_monthTooLow() {
LocalDateTime.of(2007, 0, 15, 12, 30, 40);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_6ints_monthTooHigh() {
LocalDateTime.of(2007, 13, 15, 12, 30, 40);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_6ints_dayTooLow() {
LocalDateTime.of(2007, 7, -1, 12, 30, 40);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_6ints_dayTooHigh() {
LocalDateTime.of(2007, 7, 32, 12, 30, 40);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_6ints_hourTooLow() {
LocalDateTime.of(2007, 7, 15, -1, 30, 40);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_6ints_hourTooHigh() {
LocalDateTime.of(2007, 7, 15, 24, 30, 40);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_6ints_minuteTooLow() {
LocalDateTime.of(2007, 7, 15, 12, -1, 40);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_6ints_minuteTooHigh() {
LocalDateTime.of(2007, 7, 15, 12, 60, 40);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_6ints_secondTooLow() {
LocalDateTime.of(2007, 7, 15, 12, 30, -1);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_6ints_secondTooHigh() {
LocalDateTime.of(2007, 7, 15, 12, 30, 60);
}
//-----------------------------------------------------------------------
@Test
public void factory_of_7ints() {
LocalDateTime dateTime = LocalDateTime.of(2007, 7, 15, 12, 30, 40, 987654321);
check(dateTime, 2007, 7, 15, 12, 30, 40, 987654321);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_7ints_yearTooLow() {
LocalDateTime.of(Integer.MIN_VALUE, 7, 15, 12, 30, 40, 987654321);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_7ints_monthTooLow() {
LocalDateTime.of(2007, 0, 15, 12, 30, 40, 987654321);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_7ints_monthTooHigh() {
LocalDateTime.of(2007, 13, 15, 12, 30, 40, 987654321);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_7ints_dayTooLow() {
LocalDateTime.of(2007, 7, -1, 12, 30, 40, 987654321);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_7ints_dayTooHigh() {
LocalDateTime.of(2007, 7, 32, 12, 30, 40, 987654321);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_7ints_hourTooLow() {
LocalDateTime.of(2007, 7, 15, -1, 30, 40, 987654321);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_7ints_hourTooHigh() {
LocalDateTime.of(2007, 7, 15, 24, 30, 40, 987654321);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_7ints_minuteTooLow() {
LocalDateTime.of(2007, 7, 15, 12, -1, 40, 987654321);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_7ints_minuteTooHigh() {
LocalDateTime.of(2007, 7, 15, 12, 60, 40, 987654321);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_7ints_secondTooLow() {
LocalDateTime.of(2007, 7, 15, 12, 30, -1, 987654321);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_7ints_secondTooHigh() {
LocalDateTime.of(2007, 7, 15, 12, 30, 60, 987654321);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_7ints_nanoTooLow() {
LocalDateTime.of(2007, 7, 15, 12, 30, 40, -1);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_of_7ints_nanoTooHigh() {
LocalDateTime.of(2007, 7, 15, 12, 30, 40, 1000000000);
}
//-----------------------------------------------------------------------
@Test
public void factory_of_LocalDate_LocalTime() {
LocalDateTime dateTime = LocalDateTime.of(LocalDate.of(2007, 7, 15), LocalTime.of(12, 30, 40, 987654321));
check(dateTime, 2007, 7, 15, 12, 30, 40, 987654321);
}
@Test(expectedExceptions = NullPointerException.class)
public void factory_of_LocalDate_LocalTime_nullLocalDate() {
LocalDateTime.of(null, LocalTime.of(12, 30, 40, 987654321));
}
@Test(expectedExceptions = NullPointerException.class)
public void factory_of_LocalDate_LocalTime_nullLocalTime() {
LocalDateTime.of(LocalDate.of(2007, 7, 15), null);
}
//-----------------------------------------------------------------------
// ofInstant()
//-----------------------------------------------------------------------
@Test
public void factory_ofInstant_zone() {
LocalDateTime test = LocalDateTime.ofInstant(Instant.ofEpochSecond(86400 + 3600 + 120 + 4, 500), ZONE_PARIS);
assertEquals(test, LocalDateTime.of(1970, 1, 2, 2, 2, 4, 500)); // offset +01:00
}
@Test
public void factory_ofInstant_offset() {
LocalDateTime test = LocalDateTime.ofInstant(Instant.ofEpochSecond(86400 + 3600 + 120 + 4, 500), OFFSET_MTWO);
assertEquals(test, LocalDateTime.of(1970, 1, 1, 23, 2, 4, 500));
}
@Test
public void factory_ofInstant_offsetBeforeEpoch() {
LocalDateTime test = LocalDateTime.ofInstant(Instant.ofEpochSecond(-86400 + 4, 500), OFFSET_PTWO);
assertEquals(test, LocalDateTime.of(1969, 12, 31, 2, 0, 4, 500));
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_ofInstant_instantTooBig() {
LocalDateTime.ofInstant(Instant.ofEpochSecond(Long.MAX_VALUE), OFFSET_PONE);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_ofInstant_instantTooSmall() {
LocalDateTime.ofInstant(Instant.ofEpochSecond(Long.MIN_VALUE), OFFSET_PONE);
}
@Test(expectedExceptions = NullPointerException.class)
public void factory_ofInstant_nullInstant() {
LocalDateTime.ofInstant(null, ZONE_GAZA);
}
@Test(expectedExceptions = NullPointerException.class)
public void factory_ofInstant_nullZone() {
LocalDateTime.ofInstant(Instant.EPOCH, null);
}
//-----------------------------------------------------------------------
// ofEpochSecond()
//-----------------------------------------------------------------------
@Test
public void factory_ofEpochSecond_longOffset_afterEpoch() {
LocalDateTime base = LocalDateTime.of(1970, 1, 1, 2, 0, 0, 500);
for (int i = 0; i < 100000; i++) {
LocalDateTime test = LocalDateTime.ofEpochSecond(i, 500, OFFSET_PTWO);
assertEquals(test, base.plusSeconds(i));
}
}
@Test
public void factory_ofEpochSecond_longOffset_beforeEpoch() {
LocalDateTime base = LocalDateTime.of(1970, 1, 1, 2, 0, 0, 500);
for (int i = 0; i < 100000; i++) {
LocalDateTime test = LocalDateTime.ofEpochSecond(-i, 500, OFFSET_PTWO);
assertEquals(test, base.minusSeconds(i));
}
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_ofEpochSecond_longOffset_tooBig() {
LocalDateTime.ofEpochSecond(Long.MAX_VALUE, 500, OFFSET_PONE); // TODO: better test
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_ofEpochSecond_longOffset_tooSmall() {
LocalDateTime.ofEpochSecond(Long.MIN_VALUE, 500, OFFSET_PONE); // TODO: better test
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_ofEpochSecond_badNanos_toBig() {
LocalDateTime.ofEpochSecond(0, 1000000000, OFFSET_PONE);
}
@Test(expectedExceptions = DateTimeException.class)
public void factory_ofEpochSecond_badNanos_toSmall() {
LocalDateTime.ofEpochSecond(0, -1, OFFSET_PONE);
}
@Test(expectedExceptions = NullPointerException.class)
public void factory_ofEpochSecond_longOffset_nullOffset() {
LocalDateTime.ofEpochSecond(0L, 500, null);
}
//-----------------------------------------------------------------------
// from()
//-----------------------------------------------------------------------
@Test
public void test_from_Accessor() {
LocalDateTime base = LocalDateTime.of(2007, 7, 15, 17, 30);
assertEquals(LocalDateTime.from(base), base);
assertEquals(LocalDateTime.from(ZonedDateTime.of(base, ZoneOffset.ofHours(2))), base);
}
@Test(expectedExceptions = DateTimeException.class)
public void test_from_Accessor_invalid_noDerive() {
LocalDateTime.from(LocalTime.of(12, 30));
}
@Test(expectedExceptions = NullPointerException.class)
public void test_from_Accessor_null() {
LocalDateTime.from(null);
}
//-----------------------------------------------------------------------
// parse()
//-----------------------------------------------------------------------
@Test(dataProvider = "sampleToString")
public void test_parse(int y, int month, int d, int h, int m, int s, int n, String text) {
LocalDateTime t = LocalDateTime.parse(text);
assertEquals(t.getYear(), y);
assertEquals(t.getMonth().getValue(), month);
assertEquals(t.getDayOfMonth(), d);
assertEquals(t.getHour(), h);
assertEquals(t.getMinute(), m);
assertEquals(t.getSecond(), s);
assertEquals(t.getNano(), n);
}
@Test(expectedExceptions = DateTimeParseException.class)
public void factory_parse_illegalValue() {
LocalDateTime.parse("2008-06-32T11:15");
}
@Test(expectedExceptions = DateTimeParseException.class)
public void factory_parse_invalidValue() {
LocalDateTime.parse("2008-06-31T11:15");
}
@Test(expectedExceptions = NullPointerException.class)
public void factory_parse_nullText() {
LocalDateTime.parse(null);
}
//-----------------------------------------------------------------------
// parse(DateTimeFormatter)
//-----------------------------------------------------------------------
@Test
public void factory_parse_formatter() {
DateTimeFormatter f = DateTimeFormatter.ofPattern("u M d H m s");
LocalDateTime test = LocalDateTime.parse("2010 12 3 11 30 45", f);
assertEquals(test, LocalDateTime.of(2010, 12, 3, 11, 30, 45));
}
@Test(expectedExceptions = NullPointerException.class)
public void factory_parse_formatter_nullText() {
DateTimeFormatter f = DateTimeFormatter.ofPattern("u M d H m s");
LocalDateTime.parse(null, f);
}
@Test(expectedExceptions = NullPointerException.class)
public void factory_parse_formatter_nullFormatter() {
LocalDateTime.parse("ANY", null);
}
//-----------------------------------------------------------------------
// get(DateTimeField)
//-----------------------------------------------------------------------
@Test
public void test_get_DateTimeField() {
LocalDateTime test = LocalDateTime.of(2008, 6, 30, 12, 30, 40, 987654321);
assertEquals(test.getLong(ChronoField.YEAR), 2008);
assertEquals(test.getLong(ChronoField.MONTH_OF_YEAR), 6);
assertEquals(test.getLong(ChronoField.DAY_OF_MONTH), 30);
assertEquals(test.getLong(ChronoField.DAY_OF_WEEK), 1);
assertEquals(test.getLong(ChronoField.DAY_OF_YEAR), 182);
assertEquals(test.getLong(ChronoField.HOUR_OF_DAY), 12);
assertEquals(test.getLong(ChronoField.MINUTE_OF_HOUR), 30);
assertEquals(test.getLong(ChronoField.SECOND_OF_MINUTE), 40);
assertEquals(test.getLong(ChronoField.NANO_OF_SECOND), 987654321);
assertEquals(test.getLong(ChronoField.HOUR_OF_AMPM), 0);
assertEquals(test.getLong(ChronoField.AMPM_OF_DAY), 1);
}
@Test(expectedExceptions = NullPointerException.class)
public void test_get_DateTimeField_null() {
LocalDateTime test = LocalDateTime.of(2008, 6, 30, 12, 30, 40, 987654321);
test.getLong(null);
}
@Test(expectedExceptions = DateTimeException.class)
public void test_get_DateTimeField_invalidField() {
test2007x07x15x12x30x40x987654321.getLong(MockFieldNoValue.INSTANCE);
}
//-----------------------------------------------------------------------
// query(TemporalQuery)
//-----------------------------------------------------------------------
@Test
public void test_query() {
assertEquals(test2007x07x15x12x30x40x987654321.query(TemporalQueries.chronology()), IsoChronology.INSTANCE);
assertEquals(test2007x07x15x12x30x40x987654321.query(TemporalQueries.localDate()),
test2007x07x15x12x30x40x987654321 .toLocalDate());
assertEquals(test2007x07x15x12x30x40x987654321.query(TemporalQueries.localTime()),
test2007x07x15x12x30x40x987654321.toLocalTime());
assertEquals(test2007x07x15x12x30x40x987654321.query(TemporalQueries.offset()), null);
assertEquals(test2007x07x15x12x30x40x987654321.query(TemporalQueries.precision()), ChronoUnit.NANOS);
assertEquals(test2007x07x15x12x30x40x987654321.query(TemporalQueries.zone()), null);
assertEquals(test2007x07x15x12x30x40x987654321.query(TemporalQueries.zoneId()), null);
}
@Test(expectedExceptions = NullPointerException.class)
public void test_query_null() {
test2007x07x15x12x30x40x987654321.query(null);
}
//-----------------------------------------------------------------------
@DataProvider(name = "sampleDates")
Object[][] provider_sampleDates() {
return new Object[][] {
{2008, 7, 5},
{2007, 7, 5},
{2006, 7, 5},
{2005, 7, 5},
{2004, 1, 1},
{-1, 1, 2},
};
}
@DataProvider(name = "sampleTimes")
Object[][] provider_sampleTimes() {
return new Object[][] {
{0, 0, 0, 0},
{0, 0, 0, 1},
{0, 0, 1, 0},
{0, 0, 1, 1},
{0, 1, 0, 0},
{0, 1, 0, 1},
{0, 1, 1, 0},
{0, 1, 1, 1},
{1, 0, 0, 0},
{1, 0, 0, 1},
{1, 0, 1, 0},
{1, 0, 1, 1},
{1, 1, 0, 0},
{1, 1, 0, 1},
{1, 1, 1, 0},
{1, 1, 1, 1},
};
}
//-----------------------------------------------------------------------
// get*()
//-----------------------------------------------------------------------
@Test(dataProvider = "sampleDates")
public void test_get_dates(int y, int m, int d) {
LocalDateTime a = LocalDateTime.of(y, m, d, 12, 30);
assertEquals(a.getYear(), y);
assertEquals(a.getMonth(), Month.of(m));
assertEquals(a.getDayOfMonth(), d);
}
@Test(dataProvider = "sampleDates")
public void test_getDOY(int y, int m, int d) {
LocalDateTime a = LocalDateTime.of(y, m, d, 12, 30);
int total = 0;
for (int i = 1; i < m; i++) {
total += Month.of(i).length(isIsoLeap(y));
}
int doy = total + d;
assertEquals(a.getDayOfYear(), doy);
}
@Test(dataProvider = "sampleTimes")
public void test_get_times(int h, int m, int s, int ns) {
LocalDateTime a = LocalDateTime.of(test2007x07x15x12x30x40x987654321.toLocalDate(), LocalTime.of(h, m, s, ns));
assertEquals(a.getHour(), h);
assertEquals(a.getMinute(), m);
assertEquals(a.getSecond(), s);
assertEquals(a.getNano(), ns);
}
//-----------------------------------------------------------------------
// getDayOfWeek()
//-----------------------------------------------------------------------
@Test
public void test_getDayOfWeek() {
DayOfWeek dow = DayOfWeek.MONDAY;
for (Month month : Month.values()) {
int length = month.length(false);
for (int i = 1; i <= length; i++) {
LocalDateTime d = LocalDateTime.of(LocalDate.of(2007, month, i),
test2007x07x15x12x30x40x987654321.toLocalTime());
assertSame(d.getDayOfWeek(), dow);
dow = dow.plus(1);
}
}
}
//-----------------------------------------------------------------------
// with()
//-----------------------------------------------------------------------
@Test
public void test_with_adjustment() {
final LocalDateTime sample = LocalDateTime.of(2012, 3, 4, 23, 5);
TemporalAdjuster adjuster = dateTime -> sample;
assertEquals(test2007x07x15x12x30x40x987654321.with(adjuster), sample);
}
@Test(expectedExceptions = NullPointerException.class)
public void test_with_adjustment_null() {
test2007x07x15x12x30x40x987654321.with(null);
}
//-----------------------------------------------------------------------
// withYear()
//-----------------------------------------------------------------------
@Test
public void test_withYear_int_normal() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.withYear(2008);
check(t, 2008, 7, 15, 12, 30, 40, 987654321);
}
@Test(expectedExceptions = DateTimeException.class)
public void test_withYear_int_invalid() {
test2007x07x15x12x30x40x987654321.withYear(Year.MIN_VALUE - 1);
}
@Test
public void test_withYear_int_adjustDay() {
LocalDateTime t = LocalDateTime.of(2008, 2, 29, 12, 30).withYear(2007);
LocalDateTime expected = LocalDateTime.of(2007, 2, 28, 12, 30);
assertEquals(t, expected);
}
//-----------------------------------------------------------------------
// withMonth()
//-----------------------------------------------------------------------
@Test
public void test_withMonth_int_normal() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.withMonth(1);
check(t, 2007, 1, 15, 12, 30, 40, 987654321);
}
@Test(expectedExceptions = DateTimeException.class)
public void test_withMonth_int_invalid() {
test2007x07x15x12x30x40x987654321.withMonth(13);
}
@Test
public void test_withMonth_int_adjustDay() {
LocalDateTime t = LocalDateTime.of(2007, 12, 31, 12, 30).withMonth(11);
LocalDateTime expected = LocalDateTime.of(2007, 11, 30, 12, 30);
assertEquals(t, expected);
}
//-----------------------------------------------------------------------
// withDayOfMonth()
//-----------------------------------------------------------------------
@Test
public void test_withDayOfMonth_normal() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.withDayOfMonth(1);
check(t, 2007, 7, 1, 12, 30, 40, 987654321);
}
@Test(expectedExceptions = DateTimeException.class)
public void test_withDayOfMonth_invalid() {
LocalDateTime.of(2007, 11, 30, 12, 30).withDayOfMonth(32);
}
@Test(expectedExceptions = DateTimeException.class)
public void test_withDayOfMonth_invalidCombination() {
LocalDateTime.of(2007, 11, 30, 12, 30).withDayOfMonth(31);
}
//-----------------------------------------------------------------------
// withDayOfYear(int)
//-----------------------------------------------------------------------
@Test
public void test_withDayOfYear_normal() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.withDayOfYear(33);
assertEquals(t, LocalDateTime.of(2007, 2, 2, 12, 30, 40, 987654321));
}
@Test(expectedExceptions = DateTimeException.class)
public void test_withDayOfYear_illegal() {
test2007x07x15x12x30x40x987654321.withDayOfYear(367);
}
@Test(expectedExceptions = DateTimeException.class)
public void test_withDayOfYear_invalid() {
test2007x07x15x12x30x40x987654321.withDayOfYear(366);
}
//-----------------------------------------------------------------------
// withHour()
//-----------------------------------------------------------------------
@Test
public void test_withHour_normal() {
LocalDateTime t = test2007x07x15x12x30x40x987654321;
for (int i = 0; i < 24; i++) {
t = t.withHour(i);
assertEquals(t.getHour(), i);
}
}
@Test(expectedExceptions = DateTimeException.class)
public void test_withHour_hourTooLow() {
test2007x07x15x12x30x40x987654321.withHour(-1);
}
@Test(expectedExceptions = DateTimeException.class)
public void test_withHour_hourTooHigh() {
test2007x07x15x12x30x40x987654321.withHour(24);
}
//-----------------------------------------------------------------------
// withMinute()
//-----------------------------------------------------------------------
@Test
public void test_withMinute_normal() {
LocalDateTime t = test2007x07x15x12x30x40x987654321;
for (int i = 0; i < 60; i++) {
t = t.withMinute(i);
assertEquals(t.getMinute(), i);
}
}
@Test(expectedExceptions = DateTimeException.class)
public void test_withMinute_minuteTooLow() {
test2007x07x15x12x30x40x987654321.withMinute(-1);
}
@Test(expectedExceptions = DateTimeException.class)
public void test_withMinute_minuteTooHigh() {
test2007x07x15x12x30x40x987654321.withMinute(60);
}
//-----------------------------------------------------------------------
// withSecond()
//-----------------------------------------------------------------------
@Test
public void test_withSecond_normal() {
LocalDateTime t = test2007x07x15x12x30x40x987654321;
for (int i = 0; i < 60; i++) {
t = t.withSecond(i);
assertEquals(t.getSecond(), i);
}
}
@Test(expectedExceptions = DateTimeException.class)
public void test_withSecond_secondTooLow() {
test2007x07x15x12x30x40x987654321.withSecond(-1);
}
@Test(expectedExceptions = DateTimeException.class)
public void test_withSecond_secondTooHigh() {
test2007x07x15x12x30x40x987654321.withSecond(60);
}
//-----------------------------------------------------------------------
// withNano()
//-----------------------------------------------------------------------
@Test
public void test_withNanoOfSecond_normal() {
LocalDateTime t = test2007x07x15x12x30x40x987654321;
t = t.withNano(1);
assertEquals(t.getNano(), 1);
t = t.withNano(10);
assertEquals(t.getNano(), 10);
t = t.withNano(100);
assertEquals(t.getNano(), 100);
t = t.withNano(999999999);
assertEquals(t.getNano(), 999999999);
}
@Test(expectedExceptions = DateTimeException.class)
public void test_withNanoOfSecond_nanoTooLow() {
test2007x07x15x12x30x40x987654321.withNano(-1);
}
@Test(expectedExceptions = DateTimeException.class)
public void test_withNanoOfSecond_nanoTooHigh() {
test2007x07x15x12x30x40x987654321.withNano(1000000000);
}
//-----------------------------------------------------------------------
// plus(adjuster)
//-----------------------------------------------------------------------
@Test
public void test_plus_adjuster() {
Duration p = Duration.ofSeconds(62, 3);
LocalDateTime t = test2007x07x15x12x30x40x987654321.plus(p);
assertEquals(t, LocalDateTime.of(2007, 7, 15, 12, 31, 42, 987654324));
}
@Test(expectedExceptions = NullPointerException.class)
public void test_plus_adjuster_null() {
test2007x07x15x12x30x40x987654321.plus(null);
}
//-----------------------------------------------------------------------
// plus(Period)
//-----------------------------------------------------------------------
@Test
public void test_plus_Period_positiveMonths() {
MockSimplePeriod period = MockSimplePeriod.of(7, ChronoUnit.MONTHS);
LocalDateTime t = test2007x07x15x12x30x40x987654321.plus(period);
assertEquals(t, LocalDateTime.of(2008, 2, 15, 12, 30, 40, 987654321));
}
@Test
public void test_plus_Period_negativeDays() {
MockSimplePeriod period = MockSimplePeriod.of(-25, ChronoUnit.DAYS);
LocalDateTime t = test2007x07x15x12x30x40x987654321.plus(period);
assertEquals(t, LocalDateTime.of(2007, 6, 20, 12, 30, 40, 987654321));
}
@Test(expectedExceptions = NullPointerException.class)
public void test_plus_Period_null() {
test2007x07x15x12x30x40x987654321.plus(null);
}
@Test(expectedExceptions = DateTimeException.class)
public void test_plus_Period_invalidTooLarge() {
MockSimplePeriod period = MockSimplePeriod.of(1, ChronoUnit.YEARS);
LocalDateTime.of(Year.MAX_VALUE, 1, 1, 0, 0).plus(period);
}
@Test(expectedExceptions = DateTimeException.class)
public void test_plus_Period_invalidTooSmall() {
MockSimplePeriod period = MockSimplePeriod.of(-1, ChronoUnit.YEARS);
LocalDateTime.of(Year.MIN_VALUE, 1, 1, 0, 0).plus(period);
}
//-----------------------------------------------------------------------
// plus(long,PeriodUnit)
//-----------------------------------------------------------------------
@Test
public void test_plus_longPeriodUnit_positiveMonths() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.plus(7, ChronoUnit.MONTHS);
assertEquals(t, LocalDateTime.of(2008, 2, 15, 12, 30, 40, 987654321));
}
@Test
public void test_plus_longPeriodUnit_negativeDays() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.plus(-25, ChronoUnit.DAYS);
assertEquals(t, LocalDateTime.of(2007, 6, 20, 12, 30, 40, 987654321));
}
@Test(expectedExceptions = NullPointerException.class)
public void test_plus_longPeriodUnit_null() {
test2007x07x15x12x30x40x987654321.plus(1, null);
}
@Test(expectedExceptions = DateTimeException.class)
public void test_plus_longPeriodUnit_invalidTooLarge() {
LocalDateTime.of(Year.MAX_VALUE, 1, 1, 0, 0).plus(1, ChronoUnit.YEARS);
}
@Test(expectedExceptions = DateTimeException.class)
public void test_plus_longPeriodUnit_invalidTooSmall() {
LocalDateTime.of(Year.MIN_VALUE, 1, 1, 0, 0).plus(-1, ChronoUnit.YEARS);
}
//-----------------------------------------------------------------------
// plusYears()
//-----------------------------------------------------------------------
@Test
public void test_plusYears_int_normal() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.plusYears(1);
check(t, 2008, 7, 15, 12, 30, 40, 987654321);
}
@Test
public void test_plusYears_int_negative() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.plusYears(-1);
check(t, 2006, 7, 15, 12, 30, 40, 987654321);
}
@Test
public void test_plusYears_int_adjustDay() {
LocalDateTime t = createDateMidnight(2008, 2, 29).plusYears(1);
check(t, 2009, 2, 28, 0, 0, 0, 0);
}
@Test(expectedExceptions = DateTimeException.class)
public void test_plusYears_int_invalidTooLarge() {
createDateMidnight(Year.MAX_VALUE, 1, 1).plusYears(1);
}
@Test(expectedExceptions = DateTimeException.class)
public void test_plusYears_int_invalidTooSmall() {
LocalDate.of(Year.MIN_VALUE, 1, 1).plusYears(-1);
}
//-----------------------------------------------------------------------
// plusMonths()
//-----------------------------------------------------------------------
@Test
public void test_plusMonths_int_normal() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.plusMonths(1);
check(t, 2007, 8, 15, 12, 30, 40, 987654321);
}
@Test
public void test_plusMonths_int_overYears() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.plusMonths(25);
check(t, 2009, 8, 15, 12, 30, 40, 987654321);
}
@Test
public void test_plusMonths_int_negative() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.plusMonths(-1);
check(t, 2007, 6, 15, 12, 30, 40, 987654321);
}
@Test
public void test_plusMonths_int_negativeAcrossYear() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.plusMonths(-7);
check(t, 2006, 12, 15, 12, 30, 40, 987654321);
}
@Test
public void test_plusMonths_int_negativeOverYears() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.plusMonths(-31);
check(t, 2004, 12, 15, 12, 30, 40, 987654321);
}
@Test
public void test_plusMonths_int_adjustDayFromLeapYear() {
LocalDateTime t = createDateMidnight(2008, 2, 29).plusMonths(12);
check(t, 2009, 2, 28, 0, 0, 0, 0);
}
@Test
public void test_plusMonths_int_adjustDayFromMonthLength() {
LocalDateTime t = createDateMidnight(2007, 3, 31).plusMonths(1);
check(t, 2007, 4, 30, 0, 0, 0, 0);
}
@Test(expectedExceptions = DateTimeException.class)
public void test_plusMonths_int_invalidTooLarge() {
createDateMidnight(Year.MAX_VALUE, 12, 1).plusMonths(1);
}
@Test(expectedExceptions = DateTimeException.class)
public void test_plusMonths_int_invalidTooSmall() {
createDateMidnight(Year.MIN_VALUE, 1, 1).plusMonths(-1);
}
//-----------------------------------------------------------------------
// plusWeeks()
//-----------------------------------------------------------------------
@DataProvider(name = "samplePlusWeeksSymmetry")
Object[][] provider_samplePlusWeeksSymmetry() {
return new Object[][] {
{createDateMidnight(-1, 1, 1)},
{createDateMidnight(-1, 2, 28)},
{createDateMidnight(-1, 3, 1)},
{createDateMidnight(-1, 12, 31)},
{createDateMidnight(0, 1, 1)},
{createDateMidnight(0, 2, 28)},
{createDateMidnight(0, 2, 29)},
{createDateMidnight(0, 3, 1)},
{createDateMidnight(0, 12, 31)},
{createDateMidnight(2007, 1, 1)},
{createDateMidnight(2007, 2, 28)},
{createDateMidnight(2007, 3, 1)},
{createDateMidnight(2007, 12, 31)},
{createDateMidnight(2008, 1, 1)},
{createDateMidnight(2008, 2, 28)},
{createDateMidnight(2008, 2, 29)},
{createDateMidnight(2008, 3, 1)},
{createDateMidnight(2008, 12, 31)},
{createDateMidnight(2099, 1, 1)},
{createDateMidnight(2099, 2, 28)},
{createDateMidnight(2099, 3, 1)},
{createDateMidnight(2099, 12, 31)},
{createDateMidnight(2100, 1, 1)},
{createDateMidnight(2100, 2, 28)},
{createDateMidnight(2100, 3, 1)},
{createDateMidnight(2100, 12, 31)},
};
}
@Test(dataProvider = "samplePlusWeeksSymmetry")
public void test_plusWeeks_symmetry(LocalDateTime reference) {
for (int weeks = 0; weeks < 52 * 8; weeks++) {
LocalDateTime t = reference.plusWeeks(weeks).plusWeeks(-weeks);
assertEquals(t, reference);
t = reference.plusWeeks(-weeks).plusWeeks(weeks);
assertEquals(t, reference);
}
}
@Test
public void test_plusWeeks_normal() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.plusWeeks(1);
check(t, 2007, 7, 22, 12, 30, 40, 987654321);
}
@Test
public void test_plusWeeks_overMonths() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.plusWeeks(9);
check(t, 2007, 9, 16, 12, 30, 40, 987654321);
}
@Test
public void test_plusWeeks_overYears() {
LocalDateTime t = LocalDateTime.of(2006, 7, 16, 12, 30, 40, 987654321).plusWeeks(52);
assertEquals(t, test2007x07x15x12x30x40x987654321);
}
@Test
public void test_plusWeeks_overLeapYears() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.plusYears(-1).plusWeeks(104);
check(t, 2008, 7, 12, 12, 30, 40, 987654321);
}
@Test
public void test_plusWeeks_negative() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.plusWeeks(-1);
check(t, 2007, 7, 8, 12, 30, 40, 987654321);
}
@Test
public void test_plusWeeks_negativeAcrossYear() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.plusWeeks(-28);
check(t, 2006, 12, 31, 12, 30, 40, 987654321);
}
@Test
public void test_plusWeeks_negativeOverYears() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.plusWeeks(-104);
check(t, 2005, 7, 17, 12, 30, 40, 987654321);
}
@Test
public void test_plusWeeks_maximum() {
LocalDateTime t = createDateMidnight(Year.MAX_VALUE, 12, 24).plusWeeks(1);
check(t, Year.MAX_VALUE, 12, 31, 0, 0, 0, 0);
}
@Test
public void test_plusWeeks_minimum() {
LocalDateTime t = createDateMidnight(Year.MIN_VALUE, 1, 8).plusWeeks(-1);
check(t, Year.MIN_VALUE, 1, 1, 0, 0, 0, 0);
}
@Test(expectedExceptions = DateTimeException.class)
public void test_plusWeeks_invalidTooLarge() {
createDateMidnight(Year.MAX_VALUE, 12, 25).plusWeeks(1);
}
@Test(expectedExceptions = DateTimeException.class)
public void test_plusWeeks_invalidTooSmall() {
createDateMidnight(Year.MIN_VALUE, 1, 7).plusWeeks(-1);
}
//-----------------------------------------------------------------------
// plusDays()
//-----------------------------------------------------------------------
@DataProvider(name = "samplePlusDaysSymmetry")
Object[][] provider_samplePlusDaysSymmetry() {
return new Object[][] {
{createDateMidnight(-1, 1, 1)},
{createDateMidnight(-1, 2, 28)},
{createDateMidnight(-1, 3, 1)},
{createDateMidnight(-1, 12, 31)},
{createDateMidnight(0, 1, 1)},
{createDateMidnight(0, 2, 28)},
{createDateMidnight(0, 2, 29)},
{createDateMidnight(0, 3, 1)},
{createDateMidnight(0, 12, 31)},
{createDateMidnight(2007, 1, 1)},
{createDateMidnight(2007, 2, 28)},
{createDateMidnight(2007, 3, 1)},
{createDateMidnight(2007, 12, 31)},
{createDateMidnight(2008, 1, 1)},
{createDateMidnight(2008, 2, 28)},
{createDateMidnight(2008, 2, 29)},
{createDateMidnight(2008, 3, 1)},
{createDateMidnight(2008, 12, 31)},
{createDateMidnight(2099, 1, 1)},
{createDateMidnight(2099, 2, 28)},
{createDateMidnight(2099, 3, 1)},
{createDateMidnight(2099, 12, 31)},
{createDateMidnight(2100, 1, 1)},
{createDateMidnight(2100, 2, 28)},
{createDateMidnight(2100, 3, 1)},
{createDateMidnight(2100, 12, 31)},
};
}
@Test(dataProvider = "samplePlusDaysSymmetry")
public void test_plusDays_symmetry(LocalDateTime reference) {
for (int days = 0; days < 365 * 8; days++) {
LocalDateTime t = reference.plusDays(days).plusDays(-days);
assertEquals(t, reference);
t = reference.plusDays(-days).plusDays(days);
assertEquals(t, reference);
}
}
@Test
public void test_plusDays_normal() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.plusDays(1);
check(t, 2007, 7, 16, 12, 30, 40, 987654321);
}
@Test
public void test_plusDays_overMonths() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.plusDays(62);
check(t, 2007, 9, 15, 12, 30, 40, 987654321);
}
@Test
public void test_plusDays_overYears() {
LocalDateTime t = LocalDateTime.of(2006, 7, 14, 12, 30, 40, 987654321).plusDays(366);
assertEquals(t, test2007x07x15x12x30x40x987654321);
}
@Test
public void test_plusDays_overLeapYears() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.plusYears(-1).plusDays(365 + 366);
check(t, 2008, 7, 15, 12, 30, 40, 987654321);
}
@Test
public void test_plusDays_negative() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.plusDays(-1);
check(t, 2007, 7, 14, 12, 30, 40, 987654321);
}
@Test
public void test_plusDays_negativeAcrossYear() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.plusDays(-196);
check(t, 2006, 12, 31, 12, 30, 40, 987654321);
}
@Test
public void test_plusDays_negativeOverYears() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.plusDays(-730);
check(t, 2005, 7, 15, 12, 30, 40, 987654321);
}
@Test
public void test_plusDays_maximum() {
LocalDateTime t = createDateMidnight(Year.MAX_VALUE, 12, 30).plusDays(1);
check(t, Year.MAX_VALUE, 12, 31, 0, 0, 0, 0);
}
@Test
public void test_plusDays_minimum() {
LocalDateTime t = createDateMidnight(Year.MIN_VALUE, 1, 2).plusDays(-1);
check(t, Year.MIN_VALUE, 1, 1, 0, 0, 0, 0);
}
@Test(expectedExceptions = DateTimeException.class)
public void test_plusDays_invalidTooLarge() {
createDateMidnight(Year.MAX_VALUE, 12, 31).plusDays(1);
}
@Test(expectedExceptions = DateTimeException.class)
public void test_plusDays_invalidTooSmall() {
createDateMidnight(Year.MIN_VALUE, 1, 1).plusDays(-1);
}
@Test(expectedExceptions = ArithmeticException.class)
public void test_plusDays_overflowTooLarge() {
createDateMidnight(Year.MAX_VALUE, 12, 31).plusDays(Long.MAX_VALUE);
}
@Test(expectedExceptions = ArithmeticException.class)
public void test_plusDays_overflowTooSmall() {
createDateMidnight(Year.MIN_VALUE, 1, 1).plusDays(Long.MIN_VALUE);
}
//-----------------------------------------------------------------------
// plusHours()
//-----------------------------------------------------------------------
@Test
public void test_plusHours_one() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.with(LocalTime.MIDNIGHT);
LocalDate d = t.toLocalDate();
for (int i = 0; i < 50; i++) {
t = t.plusHours(1);
if ((i + 1) % 24 == 0) {
d = d.plusDays(1);
}
assertEquals(t.toLocalDate(), d);
assertEquals(t.getHour(), (i + 1) % 24);
}
}
@Test
public void test_plusHours_fromZero() {
LocalDateTime base = test2007x07x15x12x30x40x987654321.with(LocalTime.MIDNIGHT);
LocalDate d = base.toLocalDate().minusDays(3);
LocalTime t = LocalTime.of(21, 0);
for (int i = -50; i < 50; i++) {
LocalDateTime dt = base.plusHours(i);
t = t.plusHours(1);
if (t.getHour() == 0) {
d = d.plusDays(1);
}
assertEquals(dt.toLocalDate(), d);
assertEquals(dt.toLocalTime(), t);
}
}
@Test
public void test_plusHours_fromOne() {
LocalDateTime base = test2007x07x15x12x30x40x987654321.with(LocalTime.of(1, 0));
LocalDate d = base.toLocalDate().minusDays(3);
LocalTime t = LocalTime.of(22, 0);
for (int i = -50; i < 50; i++) {
LocalDateTime dt = base.plusHours(i);
t = t.plusHours(1);
if (t.getHour() == 0) {
d = d.plusDays(1);
}
assertEquals(dt.toLocalDate(), d);
assertEquals(dt.toLocalTime(), t);
}
}
//-----------------------------------------------------------------------
// plusMinutes()
//-----------------------------------------------------------------------
@Test
public void test_plusMinutes_one() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.with(LocalTime.MIDNIGHT);
LocalDate d = t.toLocalDate();
int hour = 0;
int min = 0;
for (int i = 0; i < 70; i++) {
t = t.plusMinutes(1);
min++;
if (min == 60) {
hour++;
min = 0;
}
assertEquals(t.toLocalDate(), d);
assertEquals(t.getHour(), hour);
assertEquals(t.getMinute(), min);
}
}
@Test
public void test_plusMinutes_fromZero() {
LocalDateTime base = test2007x07x15x12x30x40x987654321.with(LocalTime.MIDNIGHT);
LocalDate d = base.toLocalDate().minusDays(1);
LocalTime t = LocalTime.of(22, 49);
for (int i = -70; i < 70; i++) {
LocalDateTime dt = base.plusMinutes(i);
t = t.plusMinutes(1);
if (t == LocalTime.MIDNIGHT) {
d = d.plusDays(1);
}
assertEquals(dt.toLocalDate(), d, String.valueOf(i));
assertEquals(dt.toLocalTime(), t, String.valueOf(i));
}
}
@Test
public void test_plusMinutes_noChange_oneDay() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.plusMinutes(24 * 60);
assertEquals(t.toLocalDate(), test2007x07x15x12x30x40x987654321.toLocalDate().plusDays(1));
}
//-----------------------------------------------------------------------
// plusSeconds()
//-----------------------------------------------------------------------
@Test
public void test_plusSeconds_one() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.with(LocalTime.MIDNIGHT);
LocalDate d = t.toLocalDate();
int hour = 0;
int min = 0;
int sec = 0;
for (int i = 0; i < 3700; i++) {
t = t.plusSeconds(1);
sec++;
if (sec == 60) {
min++;
sec = 0;
}
if (min == 60) {
hour++;
min = 0;
}
assertEquals(t.toLocalDate(), d);
assertEquals(t.getHour(), hour);
assertEquals(t.getMinute(), min);
assertEquals(t.getSecond(), sec);
}
}
@DataProvider(name = "plusSeconds_fromZero")
Iterator<Object[]> plusSeconds_fromZero() {
return new Iterator<Object[]>() {
int delta = 30;
int i = -3660;
LocalDate date = test2007x07x15x12x30x40x987654321.toLocalDate().minusDays(1);
int hour = 22;
int min = 59;
int sec;
@Override
public boolean hasNext() {
return i <= 3660;
}
@Override
public Object[] next() {
final Object[] ret = new Object[] {i, date, hour, min, sec};
i += delta;
sec += delta;
if (sec >= 60) {
min++;
sec -= 60;
if (min == 60) {
hour++;
min = 0;
if (hour == 24) {
hour = 0;
}
}
}
if (i == 0) {
date = date.plusDays(1);
}
return ret;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
@Test(dataProvider = "plusSeconds_fromZero")
public void test_plusSeconds_fromZero(int seconds, LocalDate date, int hour, int min, int sec) {
LocalDateTime base = test2007x07x15x12x30x40x987654321.with(LocalTime.MIDNIGHT);
LocalDateTime t = base.plusSeconds(seconds);
assertEquals(date, t.toLocalDate());
assertEquals(hour, t.getHour());
assertEquals(min, t.getMinute());
assertEquals(sec, t.getSecond());
}
@Test
public void test_plusSeconds_noChange_oneDay() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.plusSeconds(24 * 60 * 60);
assertEquals(t.toLocalDate(), test2007x07x15x12x30x40x987654321.toLocalDate().plusDays(1));
}
//-----------------------------------------------------------------------
// plusNanos()
//-----------------------------------------------------------------------
@Test
public void test_plusNanos_halfABillion() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.with(LocalTime.MIDNIGHT);
LocalDate d = t.toLocalDate();
int hour = 0;
int min = 0;
int sec = 0;
int nanos = 0;
for (long i = 0; i < 3700 * 1000000000L; i += 500000000) {
t = t.plusNanos(500000000);
nanos += 500000000;
if (nanos == 1000000000) {
sec++;
nanos = 0;
}
if (sec == 60) {
min++;
sec = 0;
}
if (min == 60) {
hour++;
min = 0;
}
assertEquals(t.toLocalDate(), d, String.valueOf(i));
assertEquals(t.getHour(), hour);
assertEquals(t.getMinute(), min);
assertEquals(t.getSecond(), sec);
assertEquals(t.getNano(), nanos);
}
}
@DataProvider(name = "plusNanos_fromZero")
Iterator<Object[]> plusNanos_fromZero() {
return new Iterator<Object[]>() {
long delta = 7500000000L;
long i = -3660 * 1000000000L;
LocalDate date = test2007x07x15x12x30x40x987654321.toLocalDate().minusDays(1);
int hour = 22;
int min = 59;
int sec;
long nanos;
@Override
public boolean hasNext() {
return i <= 3660 * 1000000000L;
}
@Override
public Object[] next() {
final Object[] ret = new Object[] {i, date, hour, min, sec, (int) nanos};
i += delta;
nanos += delta;
if (nanos >= 1000000000L) {
sec += nanos / 1000000000L;
nanos %= 1000000000L;
if (sec >= 60) {
min++;
sec %= 60;
if (min == 60) {
hour++;
min = 0;
if (hour == 24) {
hour = 0;
date = date.plusDays(1);
}
}
}
}
return ret;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
@Test(dataProvider = "plusNanos_fromZero")
public void test_plusNanos_fromZero(long nanoseconds, LocalDate date, int hour, int min, int sec, int nanos) {
LocalDateTime base = test2007x07x15x12x30x40x987654321.with(LocalTime.MIDNIGHT);
LocalDateTime t = base.plusNanos(nanoseconds);
assertEquals(date, t.toLocalDate());
assertEquals(hour, t.getHour());
assertEquals(min, t.getMinute());
assertEquals(sec, t.getSecond());
assertEquals(nanos, t.getNano());
}
@Test
public void test_plusNanos_noChange_oneDay() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.plusNanos(24 * 60 * 60 * 1000000000L);
assertEquals(t.toLocalDate(), test2007x07x15x12x30x40x987654321.toLocalDate().plusDays(1));
}
//-----------------------------------------------------------------------
// minus(adjuster)
//-----------------------------------------------------------------------
@Test
public void test_minus_adjuster() {
Duration p = Duration.ofSeconds(62, 3);
LocalDateTime t = test2007x07x15x12x30x40x987654321.minus(p);
assertEquals(t, LocalDateTime.of(2007, 7, 15, 12, 29, 38, 987654318));
}
@Test(expectedExceptions = NullPointerException.class)
public void test_minus_adjuster_null() {
test2007x07x15x12x30x40x987654321.minus(null);
}
//-----------------------------------------------------------------------
// minus(Period)
//-----------------------------------------------------------------------
@Test
public void test_minus_Period_positiveMonths() {
MockSimplePeriod period = MockSimplePeriod.of(7, ChronoUnit.MONTHS);
LocalDateTime t = test2007x07x15x12x30x40x987654321.minus(period);
assertEquals(t, LocalDateTime.of(2006, 12, 15, 12, 30, 40, 987654321));
}
@Test
public void test_minus_Period_negativeDays() {
MockSimplePeriod period = MockSimplePeriod.of(-25, ChronoUnit.DAYS);
LocalDateTime t = test2007x07x15x12x30x40x987654321.minus(period);
assertEquals(t, LocalDateTime.of(2007, 8, 9, 12, 30, 40, 987654321));
}
@Test(expectedExceptions = NullPointerException.class)
public void test_minus_Period_null() {
test2007x07x15x12x30x40x987654321.minus(null);
}
@Test(expectedExceptions = DateTimeException.class)
public void test_minus_Period_invalidTooLarge() {
MockSimplePeriod period = MockSimplePeriod.of(-1, ChronoUnit.YEARS);
LocalDateTime.of(Year.MAX_VALUE, 1, 1, 0, 0).minus(period);
}
@Test(expectedExceptions = DateTimeException.class)
public void test_minus_Period_invalidTooSmall() {
MockSimplePeriod period = MockSimplePeriod.of(1, ChronoUnit.YEARS);
LocalDateTime.of(Year.MIN_VALUE, 1, 1, 0, 0).minus(period);
}
//-----------------------------------------------------------------------
// minus(long,PeriodUnit)
//-----------------------------------------------------------------------
@Test
public void test_minus_longPeriodUnit_positiveMonths() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.minus(7, ChronoUnit.MONTHS);
assertEquals(t, LocalDateTime.of(2006, 12, 15, 12, 30, 40, 987654321));
}
@Test
public void test_minus_longPeriodUnit_negativeDays() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.minus(-25, ChronoUnit.DAYS);
assertEquals(t, LocalDateTime.of(2007, 8, 9, 12, 30, 40, 987654321));
}
@Test(expectedExceptions = NullPointerException.class)
public void test_minus_longPeriodUnit_null() {
test2007x07x15x12x30x40x987654321.minus(1, null);
}
@Test(expectedExceptions = DateTimeException.class)
public void test_minus_longPeriodUnit_invalidTooLarge() {
LocalDateTime.of(Year.MAX_VALUE, 1, 1, 0, 0).minus(-1, ChronoUnit.YEARS);
}
@Test(expectedExceptions = DateTimeException.class)
public void test_minus_longPeriodUnit_invalidTooSmall() {
LocalDateTime.of(Year.MIN_VALUE, 1, 1, 0, 0).minus(1, ChronoUnit.YEARS);
}
//-----------------------------------------------------------------------
// minusYears()
//-----------------------------------------------------------------------
@Test
public void test_minusYears_int_normal() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.minusYears(1);
check(t, 2006, 7, 15, 12, 30, 40, 987654321);
}
@Test
public void test_minusYears_int_negative() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.minusYears(-1);
check(t, 2008, 7, 15, 12, 30, 40, 987654321);
}
@Test
public void test_minusYears_int_adjustDay() {
LocalDateTime t = createDateMidnight(2008, 2, 29).minusYears(1);
check(t, 2007, 2, 28, 0, 0, 0, 0);
}
@Test(expectedExceptions = DateTimeException.class)
public void test_minusYears_int_invalidTooLarge() {
createDateMidnight(Year.MAX_VALUE, 1, 1).minusYears(-1);
}
@Test(expectedExceptions = DateTimeException.class)
public void test_minusYears_int_invalidTooSmall() {
createDateMidnight(Year.MIN_VALUE, 1, 1).minusYears(1);
}
//-----------------------------------------------------------------------
// minusMonths()
//-----------------------------------------------------------------------
@Test
public void test_minusMonths_int_normal() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.minusMonths(1);
check(t, 2007, 6, 15, 12, 30, 40, 987654321);
}
@Test
public void test_minusMonths_int_overYears() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.minusMonths(25);
check(t, 2005, 6, 15, 12, 30, 40, 987654321);
}
@Test
public void test_minusMonths_int_negative() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.minusMonths(-1);
check(t, 2007, 8, 15, 12, 30, 40, 987654321);
}
@Test
public void test_minusMonths_int_negativeAcrossYear() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.minusMonths(-7);
check(t, 2008, 2, 15, 12, 30, 40, 987654321);
}
@Test
public void test_minusMonths_int_negativeOverYears() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.minusMonths(-31);
check(t, 2010, 2, 15, 12, 30, 40, 987654321);
}
@Test
public void test_minusMonths_int_adjustDayFromLeapYear() {
LocalDateTime t = createDateMidnight(2008, 2, 29).minusMonths(12);
check(t, 2007, 2, 28, 0, 0, 0, 0);
}
@Test
public void test_minusMonths_int_adjustDayFromMonthLength() {
LocalDateTime t = createDateMidnight(2007, 3, 31).minusMonths(1);
check(t, 2007, 2, 28, 0, 0, 0, 0);
}
@Test(expectedExceptions = DateTimeException.class)
public void test_minusMonths_int_invalidTooLarge() {
createDateMidnight(Year.MAX_VALUE, 12, 1).minusMonths(-1);
}
@Test(expectedExceptions = DateTimeException.class)
public void test_minusMonths_int_invalidTooSmall() {
createDateMidnight(Year.MIN_VALUE, 1, 1).minusMonths(1);
}
//-----------------------------------------------------------------------
// minusWeeks()
//-----------------------------------------------------------------------
@DataProvider(name = "sampleMinusWeeksSymmetry")
Object[][] provider_sampleMinusWeeksSymmetry() {
return new Object[][] {
{createDateMidnight(-1, 1, 1)},
{createDateMidnight(-1, 2, 28)},
{createDateMidnight(-1, 3, 1)},
{createDateMidnight(-1, 12, 31)},
{createDateMidnight(0, 1, 1)},
{createDateMidnight(0, 2, 28)},
{createDateMidnight(0, 2, 29)},
{createDateMidnight(0, 3, 1)},
{createDateMidnight(0, 12, 31)},
{createDateMidnight(2007, 1, 1)},
{createDateMidnight(2007, 2, 28)},
{createDateMidnight(2007, 3, 1)},
{createDateMidnight(2007, 12, 31)},
{createDateMidnight(2008, 1, 1)},
{createDateMidnight(2008, 2, 28)},
{createDateMidnight(2008, 2, 29)},
{createDateMidnight(2008, 3, 1)},
{createDateMidnight(2008, 12, 31)},
{createDateMidnight(2099, 1, 1)},
{createDateMidnight(2099, 2, 28)},
{createDateMidnight(2099, 3, 1)},
{createDateMidnight(2099, 12, 31)},
{createDateMidnight(2100, 1, 1)},
{createDateMidnight(2100, 2, 28)},
{createDateMidnight(2100, 3, 1)},
{createDateMidnight(2100, 12, 31)},
};
}
@Test(dataProvider = "sampleMinusWeeksSymmetry")
public void test_minusWeeks_symmetry(LocalDateTime reference) {
for (int weeks = 0; weeks < 52 * 8; weeks++) {
LocalDateTime t = reference.minusWeeks(weeks).minusWeeks(-weeks);
assertEquals(t, reference);
t = reference.minusWeeks(-weeks).minusWeeks(weeks);
assertEquals(t, reference);
}
}
@Test
public void test_minusWeeks_normal() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.minusWeeks(1);
check(t, 2007, 7, 8, 12, 30, 40, 987654321);
}
@Test
public void test_minusWeeks_overMonths() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.minusWeeks(9);
check(t, 2007, 5, 13, 12, 30, 40, 987654321);
}
@Test
public void test_minusWeeks_overYears() {
LocalDateTime t = LocalDateTime.of(2008, 7, 13, 12, 30, 40, 987654321).minusWeeks(52);
assertEquals(t, test2007x07x15x12x30x40x987654321);
}
@Test
public void test_minusWeeks_overLeapYears() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.minusYears(-1).minusWeeks(104);
check(t, 2006, 7, 18, 12, 30, 40, 987654321);
}
@Test
public void test_minusWeeks_negative() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.minusWeeks(-1);
check(t, 2007, 7, 22, 12, 30, 40, 987654321);
}
@Test
public void test_minusWeeks_negativeAcrossYear() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.minusWeeks(-28);
check(t, 2008, 1, 27, 12, 30, 40, 987654321);
}
@Test
public void test_minusWeeks_negativeOverYears() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.minusWeeks(-104);
check(t, 2009, 7, 12, 12, 30, 40, 987654321);
}
@Test
public void test_minusWeeks_maximum() {
LocalDateTime t = createDateMidnight(Year.MAX_VALUE, 12, 24).minusWeeks(-1);
check(t, Year.MAX_VALUE, 12, 31, 0, 0, 0, 0);
}
@Test
public void test_minusWeeks_minimum() {
LocalDateTime t = createDateMidnight(Year.MIN_VALUE, 1, 8).minusWeeks(1);
check(t, Year.MIN_VALUE, 1, 1, 0, 0, 0, 0);
}
@Test(expectedExceptions = DateTimeException.class)
public void test_minusWeeks_invalidTooLarge() {
createDateMidnight(Year.MAX_VALUE, 12, 25).minusWeeks(-1);
}
@Test(expectedExceptions = DateTimeException.class)
public void test_minusWeeks_invalidTooSmall() {
createDateMidnight(Year.MIN_VALUE, 1, 7).minusWeeks(1);
}
//-----------------------------------------------------------------------
// minusDays()
//-----------------------------------------------------------------------
@DataProvider(name = "sampleMinusDaysSymmetry")
Object[][] provider_sampleMinusDaysSymmetry() {
return new Object[][] {
{createDateMidnight(-1, 1, 1)},
{createDateMidnight(-1, 2, 28)},
{createDateMidnight(-1, 3, 1)},
{createDateMidnight(-1, 12, 31)},
{createDateMidnight(0, 1, 1)},
{createDateMidnight(0, 2, 28)},
{createDateMidnight(0, 2, 29)},
{createDateMidnight(0, 3, 1)},
{createDateMidnight(0, 12, 31)},
{createDateMidnight(2007, 1, 1)},
{createDateMidnight(2007, 2, 28)},
{createDateMidnight(2007, 3, 1)},
{createDateMidnight(2007, 12, 31)},
{createDateMidnight(2008, 1, 1)},
{createDateMidnight(2008, 2, 28)},
{createDateMidnight(2008, 2, 29)},
{createDateMidnight(2008, 3, 1)},
{createDateMidnight(2008, 12, 31)},
{createDateMidnight(2099, 1, 1)},
{createDateMidnight(2099, 2, 28)},
{createDateMidnight(2099, 3, 1)},
{createDateMidnight(2099, 12, 31)},
{createDateMidnight(2100, 1, 1)},
{createDateMidnight(2100, 2, 28)},
{createDateMidnight(2100, 3, 1)},
{createDateMidnight(2100, 12, 31)},
};
}
@Test(dataProvider = "sampleMinusDaysSymmetry")
public void test_minusDays_symmetry(LocalDateTime reference) {
for (int days = 0; days < 365 * 8; days++) {
LocalDateTime t = reference.minusDays(days).minusDays(-days);
assertEquals(t, reference);
t = reference.minusDays(-days).minusDays(days);
assertEquals(t, reference);
}
}
@Test
public void test_minusDays_normal() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.minusDays(1);
check(t, 2007, 7, 14, 12, 30, 40, 987654321);
}
@Test
public void test_minusDays_overMonths() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.minusDays(62);
check(t, 2007, 5, 14, 12, 30, 40, 987654321);
}
@Test
public void test_minusDays_overYears() {
LocalDateTime t = LocalDateTime.of(2008, 7, 16, 12, 30, 40, 987654321).minusDays(367);
assertEquals(t, test2007x07x15x12x30x40x987654321);
}
@Test
public void test_minusDays_overLeapYears() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.plusYears(2).minusDays(365 + 366);
assertEquals(t, test2007x07x15x12x30x40x987654321);
}
@Test
public void test_minusDays_negative() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.minusDays(-1);
check(t, 2007, 7, 16, 12, 30, 40, 987654321);
}
@Test
public void test_minusDays_negativeAcrossYear() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.minusDays(-169);
check(t, 2007, 12, 31, 12, 30, 40, 987654321);
}
@Test
public void test_minusDays_negativeOverYears() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.minusDays(-731);
check(t, 2009, 7, 15, 12, 30, 40, 987654321);
}
@Test
public void test_minusDays_maximum() {
LocalDateTime t = createDateMidnight(Year.MAX_VALUE, 12, 30).minusDays(-1);
check(t, Year.MAX_VALUE, 12, 31, 0, 0, 0, 0);
}
@Test
public void test_minusDays_minimum() {
LocalDateTime t = createDateMidnight(Year.MIN_VALUE, 1, 2).minusDays(1);
check(t, Year.MIN_VALUE, 1, 1, 0, 0, 0, 0);
}
@Test(expectedExceptions = DateTimeException.class)
public void test_minusDays_invalidTooLarge() {
createDateMidnight(Year.MAX_VALUE, 12, 31).minusDays(-1);
}
@Test(expectedExceptions = DateTimeException.class)
public void test_minusDays_invalidTooSmall() {
createDateMidnight(Year.MIN_VALUE, 1, 1).minusDays(1);
}
@Test(expectedExceptions = ArithmeticException.class)
public void test_minusDays_overflowTooLarge() {
createDateMidnight(Year.MAX_VALUE, 12, 31).minusDays(Long.MIN_VALUE);
}
@Test(expectedExceptions = ArithmeticException.class)
public void test_minusDays_overflowTooSmall() {
createDateMidnight(Year.MIN_VALUE, 1, 1).minusDays(Long.MAX_VALUE);
}
//-----------------------------------------------------------------------
// minusHours()
//-----------------------------------------------------------------------
@Test
public void test_minusHours_one() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.with(LocalTime.MIDNIGHT);
LocalDate d = t.toLocalDate();
for (int i = 0; i < 50; i++) {
t = t.minusHours(1);
if (i % 24 == 0) {
d = d.minusDays(1);
}
assertEquals(t.toLocalDate(), d);
assertEquals(t.getHour(), (((-i + 23) % 24) + 24) % 24);
}
}
@Test
public void test_minusHours_fromZero() {
LocalDateTime base = test2007x07x15x12x30x40x987654321.with(LocalTime.MIDNIGHT);
LocalDate d = base.toLocalDate().plusDays(2);
LocalTime t = LocalTime.of(3, 0);
for (int i = -50; i < 50; i++) {
LocalDateTime dt = base.minusHours(i);
t = t.minusHours(1);
if (t.getHour() == 23) {
d = d.minusDays(1);
}
assertEquals(dt.toLocalDate(), d, String.valueOf(i));
assertEquals(dt.toLocalTime(), t);
}
}
@Test
public void test_minusHours_fromOne() {
LocalDateTime base = test2007x07x15x12x30x40x987654321.with(LocalTime.of(1, 0));
LocalDate d = base.toLocalDate().plusDays(2);
LocalTime t = LocalTime.of(4, 0);
for (int i = -50; i < 50; i++) {
LocalDateTime dt = base.minusHours(i);
t = t.minusHours(1);
if (t.getHour() == 23) {
d = d.minusDays(1);
}
assertEquals(dt.toLocalDate(), d, String.valueOf(i));
assertEquals(dt.toLocalTime(), t);
}
}
//-----------------------------------------------------------------------
// minusMinutes()
//-----------------------------------------------------------------------
@Test
public void test_minusMinutes_one() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.with(LocalTime.MIDNIGHT);
LocalDate d = t.toLocalDate().minusDays(1);
int hour = 0;
int min = 0;
for (int i = 0; i < 70; i++) {
t = t.minusMinutes(1);
min--;
if (min == -1) {
hour--;
min = 59;
if (hour == -1) {
hour = 23;
}
}
assertEquals(t.toLocalDate(), d);
assertEquals(t.getHour(), hour);
assertEquals(t.getMinute(), min);
}
}
@Test
public void test_minusMinutes_fromZero() {
LocalDateTime base = test2007x07x15x12x30x40x987654321.with(LocalTime.MIDNIGHT);
LocalDate d = base.toLocalDate().minusDays(1);
LocalTime t = LocalTime.of(22, 49);
for (int i = 70; i > -70; i--) {
LocalDateTime dt = base.minusMinutes(i);
t = t.plusMinutes(1);
if (t == LocalTime.MIDNIGHT) {
d = d.plusDays(1);
}
assertEquals(dt.toLocalDate(), d);
assertEquals(dt.toLocalTime(), t);
}
}
@Test
public void test_minusMinutes_noChange_oneDay() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.minusMinutes(24 * 60);
assertEquals(t.toLocalDate(), test2007x07x15x12x30x40x987654321.toLocalDate().minusDays(1));
}
//-----------------------------------------------------------------------
// minusSeconds()
//-----------------------------------------------------------------------
@Test
public void test_minusSeconds_one() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.with(LocalTime.MIDNIGHT);
LocalDate d = t.toLocalDate().minusDays(1);
int hour = 0;
int min = 0;
int sec = 0;
for (int i = 0; i < 3700; i++) {
t = t.minusSeconds(1);
sec--;
if (sec == -1) {
min--;
sec = 59;
if (min == -1) {
hour--;
min = 59;
if (hour == -1) {
hour = 23;
}
}
}
assertEquals(t.toLocalDate(), d);
assertEquals(t.getHour(), hour);
assertEquals(t.getMinute(), min);
assertEquals(t.getSecond(), sec);
}
}
@DataProvider(name = "minusSeconds_fromZero")
Iterator<Object[]> minusSeconds_fromZero() {
return new Iterator<Object[]>() {
int delta = 30;
int i = 3660;
LocalDate date = test2007x07x15x12x30x40x987654321.toLocalDate().minusDays(1);
int hour = 22;
int min = 59;
int sec;
@Override
public boolean hasNext() {
return i >= -3660;
}
@Override
public Object[] next() {
final Object[] ret = new Object[] {i, date, hour, min, sec};
i -= delta;
sec += delta;
if (sec >= 60) {
min++;
sec -= 60;
if (min == 60) {
hour++;
min = 0;
if (hour == 24) {
hour = 0;
}
}
}
if (i == 0) {
date = date.plusDays(1);
}
return ret;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
@Test(dataProvider = "minusSeconds_fromZero")
public void test_minusSeconds_fromZero(int seconds, LocalDate date, int hour, int min, int sec) {
LocalDateTime base = test2007x07x15x12x30x40x987654321.with(LocalTime.MIDNIGHT);
LocalDateTime t = base.minusSeconds(seconds);
assertEquals(date, t.toLocalDate());
assertEquals(hour, t.getHour());
assertEquals(min, t.getMinute());
assertEquals(sec, t.getSecond());
}
//-----------------------------------------------------------------------
// minusNanos()
//-----------------------------------------------------------------------
@Test
public void test_minusNanos_halfABillion() {
LocalDateTime t = test2007x07x15x12x30x40x987654321.with(LocalTime.MIDNIGHT);
LocalDate d = t.toLocalDate().minusDays(1);
int hour = 0;
int min = 0;
int sec = 0;
int nanos = 0;
for (long i = 0; i < 3700 * 1000000000L; i += 500000000) {
t = t.minusNanos(500000000);
nanos -= 500000000;
if (nanos < 0) {
sec--;
nanos += 1000000000;
if (sec == -1) {
min--;
sec += 60;
if (min == -1) {
hour--;
min += 60;
if (hour == -1) {
hour += 24;
}
}
}
}
assertEquals(t.toLocalDate(), d);
assertEquals(t.getHour(), hour);
assertEquals(t.getMinute(), min);
assertEquals(t.getSecond(), sec);
assertEquals(t.getNano(), nanos);
}
}
@DataProvider(name = "minusNanos_fromZero")
Iterator<Object[]> minusNanos_fromZero() {
return new Iterator<Object[]>() {
long delta = 7500000000L;
long i = 3660 * 1000000000L;
LocalDate date = test2007x07x15x12x30x40x987654321.toLocalDate().minusDays(1);
int hour = 22;
int min = 59;
int sec;
long nanos;
@Override
public boolean hasNext() {
return i >= -3660 * 1000000000L;
}
@Override
public Object[] next() {
final Object[] ret = new Object[] {i, date, hour, min, sec, (int) nanos};
i -= delta;
nanos += delta;
if (nanos >= 1000000000L) {
sec += nanos / 1000000000L;
nanos %= 1000000000L;
if (sec >= 60) {
min++;
sec %= 60;
if (min == 60) {
hour++;
min = 0;
if (hour == 24) {
hour = 0;
date = date.plusDays(1);
}
}
}
}
return ret;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
@Test(dataProvider = "minusNanos_fromZero")
public void test_minusNanos_fromZero(long nanoseconds, LocalDate date, int hour, int min, int sec, int nanos) {
LocalDateTime base = test2007x07x15x12x30x40x987654321.with(LocalTime.MIDNIGHT);
LocalDateTime t = base.minusNanos(nanoseconds);
assertEquals(date, t.toLocalDate());
assertEquals(hour, t.getHour());
assertEquals(min, t.getMinute());
assertEquals(sec, t.getSecond());
assertEquals(nanos, t.getNano());
}
//-----------------------------------------------------------------------
// until()
//-----------------------------------------------------------------------
@DataProvider(name = "until")
Object[][] provider_until() {
return new Object[][]{
{"2012-06-15T00:00", "2012-06-15T00:00", NANOS, 0},
{"2012-06-15T00:00", "2012-06-15T00:00", MICROS, 0},
{"2012-06-15T00:00", "2012-06-15T00:00", MILLIS, 0},
{"2012-06-15T00:00", "2012-06-15T00:00", SECONDS, 0},
{"2012-06-15T00:00", "2012-06-15T00:00", MINUTES, 0},
{"2012-06-15T00:00", "2012-06-15T00:00", HOURS, 0},
{"2012-06-15T00:00", "2012-06-15T00:00", HALF_DAYS, 0},
{"2012-06-15T00:00", "2012-06-15T00:00:01", NANOS, 1000000000},
{"2012-06-15T00:00", "2012-06-15T00:00:01", MICROS, 1000000},
{"2012-06-15T00:00", "2012-06-15T00:00:01", MILLIS, 1000},
{"2012-06-15T00:00", "2012-06-15T00:00:01", SECONDS, 1},
{"2012-06-15T00:00", "2012-06-15T00:00:01", MINUTES, 0},
{"2012-06-15T00:00", "2012-06-15T00:00:01", HOURS, 0},
{"2012-06-15T00:00", "2012-06-15T00:00:01", HALF_DAYS, 0},
{"2012-06-15T00:00", "2012-06-15T00:01", NANOS, 60000000000L},
{"2012-06-15T00:00", "2012-06-15T00:01", MICROS, 60000000},
{"2012-06-15T00:00", "2012-06-15T00:01", MILLIS, 60000},
{"2012-06-15T00:00", "2012-06-15T00:01", SECONDS, 60},
{"2012-06-15T00:00", "2012-06-15T00:01", MINUTES, 1},
{"2012-06-15T00:00", "2012-06-15T00:01", HOURS, 0},
{"2012-06-15T00:00", "2012-06-15T00:01", HALF_DAYS, 0},
{"2012-06-15T12:30:40.500", "2012-06-15T12:30:39.499", SECONDS, -1},
{"2012-06-15T12:30:40.500", "2012-06-15T12:30:39.500", SECONDS, -1},
{"2012-06-15T12:30:40.500", "2012-06-15T12:30:39.501", SECONDS, 0},
{"2012-06-15T12:30:40.500", "2012-06-15T12:30:40.499", SECONDS, 0},
{"2012-06-15T12:30:40.500", "2012-06-15T12:30:40.500", SECONDS, 0},
{"2012-06-15T12:30:40.500", "2012-06-15T12:30:40.501", SECONDS, 0},
{"2012-06-15T12:30:40.500", "2012-06-15T12:30:41.499", SECONDS, 0},
{"2012-06-15T12:30:40.500", "2012-06-15T12:30:41.500", SECONDS, 1},
{"2012-06-15T12:30:40.500", "2012-06-15T12:30:41.501", SECONDS, 1},
{"2012-06-15T12:30:40.500", "2012-06-16T12:30:39.499", SECONDS, 86400 - 2},
{"2012-06-15T12:30:40.500", "2012-06-16T12:30:39.500", SECONDS, 86400 - 1},
{"2012-06-15T12:30:40.500", "2012-06-16T12:30:39.501", SECONDS, 86400 - 1},
{"2012-06-15T12:30:40.500", "2012-06-16T12:30:40.499", SECONDS, 86400 - 1},
{"2012-06-15T12:30:40.500", "2012-06-16T12:30:40.500", SECONDS, 86400 + 0},
{"2012-06-15T12:30:40.500", "2012-06-16T12:30:40.501", SECONDS, 86400 + 0},
{"2012-06-15T12:30:40.500", "2012-06-16T12:30:41.499", SECONDS, 86400 + 0},
{"2012-06-15T12:30:40.500", "2012-06-16T12:30:41.500", SECONDS, 86400 + 1},
{"2012-06-15T12:30:40.500", "2012-06-16T12:30:41.501", SECONDS, 86400 + 1},
};
}
@Test(dataProvider = "until")
public void test_until(String startStr, String endStr, TemporalUnit unit, long expected) {
LocalDateTime start = LocalDateTime.parse(startStr);
LocalDateTime end = LocalDateTime.parse(endStr);
assertEquals(start.until(end, unit), expected);
}
@Test(dataProvider = "until")
public void test_until_reveresed(String startStr, String endStr, TemporalUnit unit, long expected) {
LocalDateTime start = LocalDateTime.parse(startStr);
LocalDateTime end = LocalDateTime.parse(endStr);
assertEquals(end.until(start, unit), -expected);
}
//-----------------------------------------------------------------------
// atZone()
//-----------------------------------------------------------------------
@Test
public void test_atZone() {
LocalDateTime t = LocalDateTime.of(2008, 6, 30, 11, 30);
assertEquals(t.atZone(ZONE_PARIS),
ZonedDateTime.of(LocalDateTime.of(2008, 6, 30, 11, 30), ZONE_PARIS));
}
@Test
public void test_atZone_Offset() {
LocalDateTime t = LocalDateTime.of(2008, 6, 30, 11, 30);
assertEquals(t.atZone(OFFSET_PTWO), ZonedDateTime.of(LocalDateTime.of(2008, 6, 30, 11, 30), OFFSET_PTWO));
}
@Test
public void test_atZone_dstGap() {
LocalDateTime t = LocalDateTime.of(2007, 4, 1, 0, 0);
assertEquals(t.atZone(ZONE_GAZA),
ZonedDateTime.of(LocalDateTime.of(2007, 4, 1, 1, 0), ZONE_GAZA));
}
@Test
public void test_atZone_dstOverlap() {
LocalDateTime t = LocalDateTime.of(2007, 10, 28, 2, 30);
assertEquals(t.atZone(ZONE_PARIS),
ZonedDateTime.ofStrict(LocalDateTime.of(2007, 10, 28, 2, 30), OFFSET_PTWO, ZONE_PARIS));
}
@Test(expectedExceptions = NullPointerException.class)
public void test_atZone_nullTimeZone() {
LocalDateTime t = LocalDateTime.of(2008, 6, 30, 11, 30);
t.atZone(null);
}
//-----------------------------------------------------------------------
// toEpochSecond()
//-----------------------------------------------------------------------
@Test
public void test_toEpochSecond_afterEpoch() {
for (int i = -5; i < 5; i++) {
ZoneOffset offset = ZoneOffset.ofHours(i);
for (int j = 0; j < 1000; j++) {
LocalDateTime a = LocalDateTime.of(1970, 1, 1, 0, 0).plusSeconds(j);
assertEquals(a.toEpochSecond(offset), j - i * 3600);
}
}
}
@Test
public void test_toEpochSecond_beforeEpoch() {
for (int i = 0; i < 1000; i++) {
LocalDateTime a = LocalDateTime.of(1970, 1, 1, 0, 0).minusSeconds(i);
assertEquals(a.toEpochSecond(ZoneOffset.UTC), -i);
}
}
//-----------------------------------------------------------------------
// compareTo()
//-----------------------------------------------------------------------
@Test
public void test_comparisons() {
test_comparisons_LocalDateTime(
LocalDate.of(Year.MIN_VALUE, 1, 1),
LocalDate.of(Year.MIN_VALUE, 12, 31),
LocalDate.of(-1, 1, 1),
LocalDate.of(-1, 12, 31),
LocalDate.of(0, 1, 1),
LocalDate.of(0, 12, 31),
LocalDate.of(1, 1, 1),
LocalDate.of(1, 12, 31),
LocalDate.of(2008, 1, 1),
LocalDate.of(2008, 2, 29),
LocalDate.of(2008, 12, 31),
LocalDate.of(Year.MAX_VALUE, 1, 1),
LocalDate.of(Year.MAX_VALUE, 12, 31)
);
}
void test_comparisons_LocalDateTime(LocalDate... localDates) {
test_comparisons_LocalDateTime(
localDates,
LocalTime.MIDNIGHT,
LocalTime.of(0, 0, 0, 999999999),
LocalTime.of(0, 0, 59, 0),
LocalTime.of(0, 0, 59, 999999999),
LocalTime.of(0, 59, 0, 0),
LocalTime.of(0, 59, 59, 999999999),
LocalTime.NOON,
LocalTime.of(12, 0, 0, 999999999),
LocalTime.of(12, 0, 59, 0),
LocalTime.of(12, 0, 59, 999999999),
LocalTime.of(12, 59, 0, 0),
LocalTime.of(12, 59, 59, 999999999),
LocalTime.of(23, 0, 0, 0),
LocalTime.of(23, 0, 0, 999999999),
LocalTime.of(23, 0, 59, 0),
LocalTime.of(23, 0, 59, 999999999),
LocalTime.of(23, 59, 0, 0),
LocalTime.of(23, 59, 59, 999999999)
);
}
void test_comparisons_LocalDateTime(LocalDate[] localDates, LocalTime... localTimes) {
LocalDateTime[] localDateTimes = new LocalDateTime[localDates.length * localTimes.length];
int i = 0;
for (LocalDate localDate : localDates) {
for (LocalTime localTime : localTimes) {
localDateTimes[i++] = LocalDateTime.of(localDate, localTime);
}
}
doTest_comparisons_LocalDateTime(localDateTimes);
}
void doTest_comparisons_LocalDateTime(LocalDateTime[] localDateTimes) {
for (int i = 0; i < localDateTimes.length; i++) {
LocalDateTime a = localDateTimes[i];
for (int j = 0; j < localDateTimes.length; j++) {
LocalDateTime b = localDateTimes[j];
if (i < j) {
assertTrue(a.compareTo(b) < 0);
assertTrue(a.isBefore(b));
assertFalse(a.isAfter(b));
assertFalse(a.equals(b));
} else if (i > j) {
assertTrue(a.compareTo(b) > 0);
assertFalse(a.isBefore(b));
assertTrue(a.isAfter(b));
assertFalse(a.equals(b));
} else {
assertEquals(a.compareTo(b), 0);
assertFalse(a.isBefore(b));
assertFalse(a.isAfter(b));
assertTrue(a.equals(b));
}
}
}
}
@Test(expectedExceptions = NullPointerException.class)
public void test_compareTo_ObjectNull() {
test2007x07x15x12x30x40x987654321.compareTo(null);
}
@Test(expectedExceptions = NullPointerException.class)
public void test_isBefore_ObjectNull() {
test2007x07x15x12x30x40x987654321.isBefore(null);
}
@Test(expectedExceptions = NullPointerException.class)
public void test_isAfter_ObjectNull() {
test2007x07x15x12x30x40x987654321.isAfter(null);
}
@Test(expectedExceptions = ClassCastException.class)
@SuppressWarnings({"unchecked", "rawtypes"})
public void compareToNonLocalDateTime() {
Comparable c = test2007x07x15x12x30x40x987654321;
c.compareTo(new Object());
}
//-----------------------------------------------------------------------
// equals()
//-----------------------------------------------------------------------
@DataProvider(name = "sampleDateTimes")
Iterator<Object[]> provider_sampleDateTimes() {
return new Iterator<Object[]>() {
Object[][] sampleDates = provider_sampleDates();
Object[][] sampleTimes = provider_sampleTimes();
int datesIndex;
int timesIndex;
@Override
public boolean hasNext() {
return datesIndex < sampleDates.length;
}
@Override
public Object[] next() {
Object[] sampleDate = sampleDates[datesIndex];
Object[] sampleTime = sampleTimes[timesIndex];
Object[] ret = new Object[sampleDate.length + sampleTime.length];
System.arraycopy(sampleDate, 0, ret, 0, sampleDate.length);
System.arraycopy(sampleTime, 0, ret, sampleDate.length, sampleTime.length);
if (++timesIndex == sampleTimes.length) {
datesIndex++;
timesIndex = 0;
}
return ret;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
@Test(dataProvider = "sampleDateTimes")
public void test_equals_true(int y, int m, int d, int h, int mi, int s, int n) {
LocalDateTime a = LocalDateTime.of(y, m, d, h, mi, s, n);
LocalDateTime b = LocalDateTime.of(y, m, d, h, mi, s, n);
assertTrue(a.equals(b));
}
@Test(dataProvider = "sampleDateTimes")
public void test_equals_false_year_differs(int y, int m, int d, int h, int mi, int s, int n) {
LocalDateTime a = LocalDateTime.of(y, m, d, h, mi, s, n);
LocalDateTime b = LocalDateTime.of(y + 1, m, d, h, mi, s, n);
assertFalse(a.equals(b));
}
@Test(dataProvider = "sampleDateTimes")
public void test_equals_false_month_differs(int y, int m, int d, int h, int mi, int s, int n) {
LocalDateTime a = LocalDateTime.of(y, m, d, h, mi, s, n);
LocalDateTime b = LocalDateTime.of(y, m + 1, d, h, mi, s, n);
assertFalse(a.equals(b));
}
@Test(dataProvider = "sampleDateTimes")
public void test_equals_false_day_differs(int y, int m, int d, int h, int mi, int s, int n) {
LocalDateTime a = LocalDateTime.of(y, m, d, h, mi, s, n);
LocalDateTime b = LocalDateTime.of(y, m, d + 1, h, mi, s, n);
assertFalse(a.equals(b));
}
@Test(dataProvider = "sampleDateTimes")
public void test_equals_false_hour_differs(int y, int m, int d, int h, int mi, int s, int n) {
LocalDateTime a = LocalDateTime.of(y, m, d, h, mi, s, n);
LocalDateTime b = LocalDateTime.of(y, m, d, h + 1, mi, s, n);
assertFalse(a.equals(b));
}
@Test(dataProvider = "sampleDateTimes")
public void test_equals_false_minute_differs(int y, int m, int d, int h, int mi, int s, int n) {
LocalDateTime a = LocalDateTime.of(y, m, d, h, mi, s, n);
LocalDateTime b = LocalDateTime.of(y, m, d, h, mi + 1, s, n);
assertFalse(a.equals(b));
}
@Test(dataProvider = "sampleDateTimes")
public void test_equals_false_second_differs(int y, int m, int d, int h, int mi, int s, int n) {
LocalDateTime a = LocalDateTime.of(y, m, d, h, mi, s, n);
LocalDateTime b = LocalDateTime.of(y, m, d, h, mi, s + 1, n);
assertFalse(a.equals(b));
}
@Test(dataProvider = "sampleDateTimes")
public void test_equals_false_nano_differs(int y, int m, int d, int h, int mi, int s, int n) {
LocalDateTime a = LocalDateTime.of(y, m, d, h, mi, s, n);
LocalDateTime b = LocalDateTime.of(y, m, d, h, mi, s, n + 1);
assertFalse(a.equals(b));
}
@Test
public void test_equals_itself_true() {
assertEquals(test2007x07x15x12x30x40x987654321.equals(test2007x07x15x12x30x40x987654321), true);
}
@Test
public void test_equals_string_false() {
assertEquals(test2007x07x15x12x30x40x987654321.equals("2007-07-15T12:30:40.987654321"), false);
}
@Test
public void test_equals_null_false() {
assertEquals(test2007x07x15x12x30x40x987654321.equals(null), false);
}
//-----------------------------------------------------------------------
// hashCode()
//-----------------------------------------------------------------------
@Test(dataProvider = "sampleDateTimes")
public void test_hashCode(int y, int m, int d, int h, int mi, int s, int n) {
LocalDateTime a = LocalDateTime.of(y, m, d, h, mi, s, n);
assertEquals(a.hashCode(), a.hashCode());
LocalDateTime b = LocalDateTime.of(y, m, d, h, mi, s, n);
assertEquals(a.hashCode(), b.hashCode());
}
//-----------------------------------------------------------------------
// toString()
//-----------------------------------------------------------------------
@DataProvider(name = "sampleToString")
Object[][] provider_sampleToString() {
return new Object[][] {
{2008, 7, 5, 2, 1, 0, 0, "2008-07-05T02:01"},
{2007, 12, 31, 23, 59, 1, 0, "2007-12-31T23:59:01"},
{999, 12, 31, 23, 59, 59, 990000000, "0999-12-31T23:59:59.990"},
{-1, 1, 2, 23, 59, 59, 999990000, "-0001-01-02T23:59:59.999990"},
{-2008, 1, 2, 23, 59, 59, 999999990, "-2008-01-02T23:59:59.999999990"},
};
}
@Test(dataProvider = "sampleToString")
public void test_toString(int y, int m, int d, int h, int mi, int s, int n, String expected) {
LocalDateTime t = LocalDateTime.of(y, m, d, h, mi, s, n);
String str = t.toString();
assertEquals(str, expected);
}
//-----------------------------------------------------------------------
// format(DateTimeFormatter)
//-----------------------------------------------------------------------
@Test
public void test_format_formatter() {
DateTimeFormatter f = DateTimeFormatter.ofPattern("y M d H m s");
String t = LocalDateTime.of(2010, 12, 3, 11, 30, 45).format(f);
assertEquals(t, "2010 12 3 11 30 45");
}
@Test(expectedExceptions = NullPointerException.class)
public void test_format_formatter_null() {
LocalDateTime.of(2010, 12, 3, 11, 30, 45).format(null);
}
}
| 49,492 |
411 | <filename>giraph-block-app/src/main/java/org/apache/giraph/block_app/framework/piece/global_comm/ReduceUtilsObject.java<gh_stars>100-1000
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.giraph.block_app.framework.piece.global_comm;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.FloatWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
/**
* Utility object with common primitive reduce operations,
* without need to create reusable objects within the piece.
*/
public class ReduceUtilsObject {
private final DoubleWritable reusableDouble = new DoubleWritable();
private final FloatWritable reusableFloat = new FloatWritable();
private final LongWritable reusableLong = new LongWritable();
private final IntWritable reusableInt = new IntWritable();
// utility functions:
public void reduceDouble(
ReducerHandle<DoubleWritable, ?> reduceHandle, double value) {
DoubleWritable tmp = reusableDouble;
tmp.set(value);
reduceHandle.reduce(tmp);
}
public void reduceFloat(
ReducerHandle<FloatWritable, ?> reduceHandle, float value) {
FloatWritable tmp = reusableFloat;
tmp.set(value);
reduceHandle.reduce(tmp);
}
public void reduceLong(
ReducerHandle<LongWritable, ?> reduceHandle, long value) {
LongWritable tmp = reusableLong;
tmp.set(value);
reduceHandle.reduce(tmp);
}
public void reduceInt(ReducerHandle<IntWritable, ?> reduceHandle, int value) {
IntWritable tmp = reusableInt;
tmp.set(value);
reduceHandle.reduce(tmp);
}
}
| 700 |
696 | /*
* Copyright (C) 2015 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.strata.product.swap;
import java.io.Serializable;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.Map;
import java.util.NoSuchElementException;
import org.joda.beans.Bean;
import org.joda.beans.ImmutableBean;
import org.joda.beans.JodaBeanUtils;
import org.joda.beans.MetaBean;
import org.joda.beans.MetaProperty;
import org.joda.beans.gen.BeanDefinition;
import org.joda.beans.gen.ImmutableDefaults;
import org.joda.beans.gen.PropertyDefinition;
import org.joda.beans.impl.direct.DirectFieldsBeanBuilder;
import org.joda.beans.impl.direct.DirectMetaBean;
import org.joda.beans.impl.direct.DirectMetaProperty;
import org.joda.beans.impl.direct.DirectMetaPropertyMap;
import com.opengamma.strata.product.swap.type.FixedIborSwapTemplate;
/**
* A swap index implementation based on an immutable set of rules.
* <p>
* A standard immutable implementation of {@link SwapIndex} that defines the swap trade template,
* including the swap convention and tenor.
* <p>
* In most cases, applications should refer to indices by name, using {@link SwapIndex#of(String)}.
* The named index will typically be resolved to an instance of this class.
* As such, it is recommended to use the {@code SwapIndex} interface in application
* code rather than directly referring to this class.
*/
@BeanDefinition
public final class ImmutableSwapIndex
implements SwapIndex, ImmutableBean, Serializable {
/**
* The index name.
*/
@PropertyDefinition(validate = "notEmpty", overrideGet = true)
private final String name;
/**
* Whether the index is active, defaulted to true.
* <p>
* Over time some indices become inactive and are no longer produced.
* If this occurs, this flag will be set to false.
*/
@PropertyDefinition(overrideGet = true)
private final boolean active;
/**
* The fixing time.
*/
@PropertyDefinition(validate = "notNull", overrideGet = true)
private final LocalTime fixingTime;
/**
* The time-zone of the fixing time.
*/
@PropertyDefinition(validate = "notNull", overrideGet = true)
private final ZoneId fixingZone;
/**
* The template for creating Fixed-Ibor swap.
*/
@PropertyDefinition(validate = "notNull", overrideGet = true)
private final FixedIborSwapTemplate template;
//-------------------------------------------------------------------------
/**
* Obtains an instance from the specified name, time and template.
*
* @param name the index name
* @param fixingTime the fixing time
* @param fixingZone the time-zone of the fixing time
* @param template the swap template
* @return the index
*/
public static ImmutableSwapIndex of(
String name,
LocalTime fixingTime,
ZoneId fixingZone,
FixedIborSwapTemplate template) {
return new ImmutableSwapIndex(name, true, fixingTime, fixingZone, template);
}
//-------------------------------------------------------------------------
@ImmutableDefaults
private static void applyDefaults(Builder builder) {
builder.active = true;
}
//-------------------------------------------------------------------------
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof ImmutableSwapIndex) {
return name.equals(((ImmutableSwapIndex) obj).name);
}
return false;
}
@Override
public int hashCode() {
return name.hashCode();
}
//-------------------------------------------------------------------------
/**
* Returns the name of the index.
*
* @return the name of the index
*/
@Override
public String toString() {
return getName();
}
//------------------------- AUTOGENERATED START -------------------------
/**
* The meta-bean for {@code ImmutableSwapIndex}.
* @return the meta-bean, not null
*/
public static ImmutableSwapIndex.Meta meta() {
return ImmutableSwapIndex.Meta.INSTANCE;
}
static {
MetaBean.register(ImmutableSwapIndex.Meta.INSTANCE);
}
/**
* The serialization version id.
*/
private static final long serialVersionUID = 1L;
/**
* Returns a builder used to create an instance of the bean.
* @return the builder, not null
*/
public static ImmutableSwapIndex.Builder builder() {
return new ImmutableSwapIndex.Builder();
}
private ImmutableSwapIndex(
String name,
boolean active,
LocalTime fixingTime,
ZoneId fixingZone,
FixedIborSwapTemplate template) {
JodaBeanUtils.notEmpty(name, "name");
JodaBeanUtils.notNull(fixingTime, "fixingTime");
JodaBeanUtils.notNull(fixingZone, "fixingZone");
JodaBeanUtils.notNull(template, "template");
this.name = name;
this.active = active;
this.fixingTime = fixingTime;
this.fixingZone = fixingZone;
this.template = template;
}
@Override
public ImmutableSwapIndex.Meta metaBean() {
return ImmutableSwapIndex.Meta.INSTANCE;
}
//-----------------------------------------------------------------------
/**
* Gets the index name.
* @return the value of the property, not empty
*/
@Override
public String getName() {
return name;
}
//-----------------------------------------------------------------------
/**
* Gets whether the index is active, defaulted to true.
* <p>
* Over time some indices become inactive and are no longer produced.
* If this occurs, this flag will be set to false.
* @return the value of the property
*/
@Override
public boolean isActive() {
return active;
}
//-----------------------------------------------------------------------
/**
* Gets the fixing time.
* @return the value of the property, not null
*/
@Override
public LocalTime getFixingTime() {
return fixingTime;
}
//-----------------------------------------------------------------------
/**
* Gets the time-zone of the fixing time.
* @return the value of the property, not null
*/
@Override
public ZoneId getFixingZone() {
return fixingZone;
}
//-----------------------------------------------------------------------
/**
* Gets the template for creating Fixed-Ibor swap.
* @return the value of the property, not null
*/
@Override
public FixedIborSwapTemplate getTemplate() {
return template;
}
//-----------------------------------------------------------------------
/**
* Returns a builder that allows this bean to be mutated.
* @return the mutable builder, not null
*/
public Builder toBuilder() {
return new Builder(this);
}
//-----------------------------------------------------------------------
/**
* The meta-bean for {@code ImmutableSwapIndex}.
*/
public static final class Meta extends DirectMetaBean {
/**
* The singleton instance of the meta-bean.
*/
static final Meta INSTANCE = new Meta();
/**
* The meta-property for the {@code name} property.
*/
private final MetaProperty<String> name = DirectMetaProperty.ofImmutable(
this, "name", ImmutableSwapIndex.class, String.class);
/**
* The meta-property for the {@code active} property.
*/
private final MetaProperty<Boolean> active = DirectMetaProperty.ofImmutable(
this, "active", ImmutableSwapIndex.class, Boolean.TYPE);
/**
* The meta-property for the {@code fixingTime} property.
*/
private final MetaProperty<LocalTime> fixingTime = DirectMetaProperty.ofImmutable(
this, "fixingTime", ImmutableSwapIndex.class, LocalTime.class);
/**
* The meta-property for the {@code fixingZone} property.
*/
private final MetaProperty<ZoneId> fixingZone = DirectMetaProperty.ofImmutable(
this, "fixingZone", ImmutableSwapIndex.class, ZoneId.class);
/**
* The meta-property for the {@code template} property.
*/
private final MetaProperty<FixedIborSwapTemplate> template = DirectMetaProperty.ofImmutable(
this, "template", ImmutableSwapIndex.class, FixedIborSwapTemplate.class);
/**
* The meta-properties.
*/
private final Map<String, MetaProperty<?>> metaPropertyMap$ = new DirectMetaPropertyMap(
this, null,
"name",
"active",
"fixingTime",
"fixingZone",
"template");
/**
* Restricted constructor.
*/
private Meta() {
}
@Override
protected MetaProperty<?> metaPropertyGet(String propertyName) {
switch (propertyName.hashCode()) {
case 3373707: // name
return name;
case -1422950650: // active
return active;
case 1255686170: // fixingTime
return fixingTime;
case 1255870713: // fixingZone
return fixingZone;
case -1321546630: // template
return template;
}
return super.metaPropertyGet(propertyName);
}
@Override
public ImmutableSwapIndex.Builder builder() {
return new ImmutableSwapIndex.Builder();
}
@Override
public Class<? extends ImmutableSwapIndex> beanType() {
return ImmutableSwapIndex.class;
}
@Override
public Map<String, MetaProperty<?>> metaPropertyMap() {
return metaPropertyMap$;
}
//-----------------------------------------------------------------------
/**
* The meta-property for the {@code name} property.
* @return the meta-property, not null
*/
public MetaProperty<String> name() {
return name;
}
/**
* The meta-property for the {@code active} property.
* @return the meta-property, not null
*/
public MetaProperty<Boolean> active() {
return active;
}
/**
* The meta-property for the {@code fixingTime} property.
* @return the meta-property, not null
*/
public MetaProperty<LocalTime> fixingTime() {
return fixingTime;
}
/**
* The meta-property for the {@code fixingZone} property.
* @return the meta-property, not null
*/
public MetaProperty<ZoneId> fixingZone() {
return fixingZone;
}
/**
* The meta-property for the {@code template} property.
* @return the meta-property, not null
*/
public MetaProperty<FixedIborSwapTemplate> template() {
return template;
}
//-----------------------------------------------------------------------
@Override
protected Object propertyGet(Bean bean, String propertyName, boolean quiet) {
switch (propertyName.hashCode()) {
case 3373707: // name
return ((ImmutableSwapIndex) bean).getName();
case -1422950650: // active
return ((ImmutableSwapIndex) bean).isActive();
case 1255686170: // fixingTime
return ((ImmutableSwapIndex) bean).getFixingTime();
case 1255870713: // fixingZone
return ((ImmutableSwapIndex) bean).getFixingZone();
case -1321546630: // template
return ((ImmutableSwapIndex) bean).getTemplate();
}
return super.propertyGet(bean, propertyName, quiet);
}
@Override
protected void propertySet(Bean bean, String propertyName, Object newValue, boolean quiet) {
metaProperty(propertyName);
if (quiet) {
return;
}
throw new UnsupportedOperationException("Property cannot be written: " + propertyName);
}
}
//-----------------------------------------------------------------------
/**
* The bean-builder for {@code ImmutableSwapIndex}.
*/
public static final class Builder extends DirectFieldsBeanBuilder<ImmutableSwapIndex> {
private String name;
private boolean active;
private LocalTime fixingTime;
private ZoneId fixingZone;
private FixedIborSwapTemplate template;
/**
* Restricted constructor.
*/
private Builder() {
applyDefaults(this);
}
/**
* Restricted copy constructor.
* @param beanToCopy the bean to copy from, not null
*/
private Builder(ImmutableSwapIndex beanToCopy) {
this.name = beanToCopy.getName();
this.active = beanToCopy.isActive();
this.fixingTime = beanToCopy.getFixingTime();
this.fixingZone = beanToCopy.getFixingZone();
this.template = beanToCopy.getTemplate();
}
//-----------------------------------------------------------------------
@Override
public Object get(String propertyName) {
switch (propertyName.hashCode()) {
case 3373707: // name
return name;
case -1422950650: // active
return active;
case 1255686170: // fixingTime
return fixingTime;
case 1255870713: // fixingZone
return fixingZone;
case -1321546630: // template
return template;
default:
throw new NoSuchElementException("Unknown property: " + propertyName);
}
}
@Override
public Builder set(String propertyName, Object newValue) {
switch (propertyName.hashCode()) {
case 3373707: // name
this.name = (String) newValue;
break;
case -1422950650: // active
this.active = (Boolean) newValue;
break;
case 1255686170: // fixingTime
this.fixingTime = (LocalTime) newValue;
break;
case 1255870713: // fixingZone
this.fixingZone = (ZoneId) newValue;
break;
case -1321546630: // template
this.template = (FixedIborSwapTemplate) newValue;
break;
default:
throw new NoSuchElementException("Unknown property: " + propertyName);
}
return this;
}
@Override
public Builder set(MetaProperty<?> property, Object value) {
super.set(property, value);
return this;
}
@Override
public ImmutableSwapIndex build() {
return new ImmutableSwapIndex(
name,
active,
fixingTime,
fixingZone,
template);
}
//-----------------------------------------------------------------------
/**
* Sets the index name.
* @param name the new value, not empty
* @return this, for chaining, not null
*/
public Builder name(String name) {
JodaBeanUtils.notEmpty(name, "name");
this.name = name;
return this;
}
/**
* Sets whether the index is active, defaulted to true.
* <p>
* Over time some indices become inactive and are no longer produced.
* If this occurs, this flag will be set to false.
* @param active the new value
* @return this, for chaining, not null
*/
public Builder active(boolean active) {
this.active = active;
return this;
}
/**
* Sets the fixing time.
* @param fixingTime the new value, not null
* @return this, for chaining, not null
*/
public Builder fixingTime(LocalTime fixingTime) {
JodaBeanUtils.notNull(fixingTime, "fixingTime");
this.fixingTime = fixingTime;
return this;
}
/**
* Sets the time-zone of the fixing time.
* @param fixingZone the new value, not null
* @return this, for chaining, not null
*/
public Builder fixingZone(ZoneId fixingZone) {
JodaBeanUtils.notNull(fixingZone, "fixingZone");
this.fixingZone = fixingZone;
return this;
}
/**
* Sets the template for creating Fixed-Ibor swap.
* @param template the new value, not null
* @return this, for chaining, not null
*/
public Builder template(FixedIborSwapTemplate template) {
JodaBeanUtils.notNull(template, "template");
this.template = template;
return this;
}
//-----------------------------------------------------------------------
@Override
public String toString() {
StringBuilder buf = new StringBuilder(192);
buf.append("ImmutableSwapIndex.Builder{");
buf.append("name").append('=').append(JodaBeanUtils.toString(name)).append(',').append(' ');
buf.append("active").append('=').append(JodaBeanUtils.toString(active)).append(',').append(' ');
buf.append("fixingTime").append('=').append(JodaBeanUtils.toString(fixingTime)).append(',').append(' ');
buf.append("fixingZone").append('=').append(JodaBeanUtils.toString(fixingZone)).append(',').append(' ');
buf.append("template").append('=').append(JodaBeanUtils.toString(template));
buf.append('}');
return buf.toString();
}
}
//-------------------------- AUTOGENERATED END --------------------------
}
| 5,747 |
540 | <reponame>JoinCAD/CPP-Reflection
/* ----------------------------------------------------------------------------
** Copyright (c) 2016 <NAME>, All Rights Reserved.
**
** TypeInfo.hpp
** --------------------------------------------------------------------------*/
#pragma once
#include "../Common/Compiler.h"
#include "../TypeData.h"
#include "../TypeID.h"
#if defined(COMPILER_MSVC)
#pragma warning(push)
// unused template parameters
#pragma warning(disable : 4544)
#endif
namespace ursine
{
namespace meta
{
template<typename T>
bool TypeInfo<T>::Defined = false;
template<typename T>
void TypeInfo<T>::Register(
TypeID id,
TypeData &data,
bool beingDefined
)
{
// already defined
if (id == Type::Invalid( ).GetID( ))
return;
TypeIDs<T>::ID = id;
typedef typename std::remove_pointer< typename std::decay<T>::type >::type Decayed;
data.isClass = std::is_class< Decayed >::value;
data.isEnum = std::is_enum< Decayed >::value;
data.isPointer = std::is_pointer< T >::value;
data.isPrimitive = std::is_arithmetic< Decayed >::value;
data.isFloatingPoint = std::is_floating_point< Decayed >::value;
data.isSigned = std::is_signed< Decayed >::value;
if (beingDefined)
{
addDefaultConstructor( data );
applyTrivialAttributes( data );
}
}
template<typename T>
template<typename U>
void TypeInfo<T>::addDefaultConstructor(
TypeData &data,
typename std::enable_if<
!IsTriviallyDefaultConstructible(U)
>::type*
)
{
// do nothing
}
template<typename T>
template<typename U>
void TypeInfo<T>::addDefaultConstructor(
TypeData &data,
typename std::enable_if<
IsTriviallyDefaultConstructible(U)
>::type*
)
{
// add the good 'ol default constructor
data.AddConstructor<T, false, false>( { } );
// add the good 'ol dynamic default constructor
data.AddConstructor<T, true, false>( { } );
}
template<typename T>
template<typename U>
void TypeInfo<T>::applyTrivialAttributes(
TypeData &data,
typename std::enable_if<
!std::is_trivial<U>::value
>::type*
)
{
// do nothing
}
template<typename T>
template<typename U>
void TypeInfo<T>::applyTrivialAttributes(
TypeData &data,
typename std::enable_if<
std::is_trivial<U>::value
>::type*
)
{
data.SetDestructor<T>( );
}
}
}
#if defined(COMPILER_MSVC)
#pragma warning(pop)
#endif
| 1,533 |
5,279 | /*
* 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.beam.sdk.io.range;
/**
* A {@code RangeTracker} is a thread-safe helper object for implementing dynamic work rebalancing
* in position-based {@link org.apache.beam.sdk.io.BoundedSource.BoundedReader} subclasses.
*
* <h3>Usage of the RangeTracker class hierarchy</h3>
*
* The abstract {@code RangeTracker} interface should not be used per se - all users should use its
* subclasses directly. We declare it here because all subclasses have roughly the same interface
* and the same properties, to centralize the documentation. Currently we provide one implementation
* - {@link OffsetRangeTracker}.
*
* <h3>Position-based sources</h3>
*
* A position-based source is one where the source can be described by a range of positions of an
* ordered type and the records returned by the reader can be described by positions of the same
* type.
*
* <p>In case a record occupies a range of positions in the source, the most important thing about
* the record is the position where it starts.
*
* <p>Defining the semantics of positions for a source is entirely up to the source class, however
* the chosen definitions have to obey certain properties in order to make it possible to correctly
* split the source into parts, including dynamic splitting. Two main aspects need to be defined:
*
* <ul>
* <li>How to assign starting positions to records.
* <li>Which records should be read by a source with a range {@code [A, B)}.
* </ul>
*
* Moreover, reading a range must be <i>efficient</i>, i.e., the performance of reading a range
* should not significantly depend on the location of the range. For example, reading the range
* {@code [A, B)} should not require reading all data before {@code A}.
*
* <p>The sections below explain exactly what properties these definitions must satisfy, and how to
* use a {@code RangeTracker} with a properly defined source.
*
* <h3>Properties of position-based sources</h3>
*
* The main requirement for position-based sources is <i>associativity</i>: reading records from
* {@code [A, B)} and records from {@code [B, C)} should give the same records as reading from
* {@code [A, C)}, where {@code A <= B <= C}. This property ensures that no matter how a range of
* positions is split into arbitrarily many sub-ranges, the total set of records described by them
* stays the same.
*
* <p>The other important property is how the source's range relates to positions of records in the
* source. In many sources each record can be identified by a unique starting position. In this
* case:
*
* <ul>
* <li>All records returned by a source {@code [A, B)} must have starting positions in this range.
* <li>All but the last record should end within this range. The last record may or may not extend
* past the end of the range.
* <li>Records should not overlap.
* </ul>
*
* Such sources should define "read {@code [A, B)}" as "read from the first record starting at or
* after A, up to but not including the first record starting at or after B".
*
* <p>Some examples of such sources include reading lines or CSV from a text file, reading keys and
* values from a BigTable, etc.
*
* <p>The concept of <i>split points</i> allows to extend the definitions for dealing with sources
* where some records cannot be identified by a unique starting position.
*
* <p>In all cases, all records returned by a source {@code [A, B)} must <i>start</i> at or after
* {@code A}.
*
* <h3>Split points</h3>
*
* <p>Some sources may have records that are not directly addressable. For example, imagine a file
* format consisting of a sequence of compressed blocks. Each block can be assigned an offset, but
* records within the block cannot be directly addressed without decompressing the block. Let us
* refer to this hypothetical format as <i>CBF (Compressed Blocks Format)</i>.
*
* <p>Many such formats can still satisfy the associativity property. For example, in CBF, reading
* {@code [A, B)} can mean "read all the records in all blocks whose starting offset is in {@code
* [A, B)}".
*
* <p>To support such complex formats, we introduce the notion of <i>split points</i>. We say that a
* record is a split point if there exists a position {@code A} such that the record is the first
* one to be returned when reading the range {@code [A, infinity)}. In CBF, the only split points
* would be the first records in each block.
*
* <p>Split points allow us to define the meaning of a record's position and a source's range in all
* cases:
*
* <ul>
* <li>For a record that is at a split point, its position is defined to be the largest {@code A}
* such that reading a source with the range {@code [A, infinity)} returns this record;
* <li>Positions of other records are only required to be non-decreasing;
* <li>Reading the source {@code [A, B)} must return records starting from the first split point
* at or after {@code A}, up to but not including the first split point at or after {@code B}.
* In particular, this means that the first record returned by a source MUST always be a split
* point.
* <li>Positions of split points must be unique.
* </ul>
*
* As a result, for any decomposition of the full range of the source into position ranges, the
* total set of records will be the full set of records in the source, and each record will be read
* exactly once.
*
* <h3>Consumed positions</h3>
*
* As the source is being read, and records read from it are being passed to the downstream
* transforms in the pipeline, we say that positions in the source are being <i>consumed</i>. When a
* reader has read a record (or promised to a caller that a record will be returned), positions up
* to and including the record's start position are considered <i>consumed</i>.
*
* <p>Dynamic splitting can happen only at <i>unconsumed</i> positions. If the reader just returned
* a record at offset 42 in a file, dynamic splitting can happen only at offset 43 or beyond, as
* otherwise that record could be read twice (by the current reader and by a reader of the task
* starting at 43).
*
* <h3>Example</h3>
*
* The following example uses an {@link OffsetRangeTracker} to support dynamically splitting a
* source with integer positions (offsets).
*
* <pre>{@code
* class MyReader implements BoundedReader<Foo> {
* private MySource currentSource;
* private final OffsetRangeTracker tracker = new OffsetRangeTracker();
* ...
* MyReader(MySource source) {
* this.currentSource = source;
* this.tracker = new MyRangeTracker<>(source.getStartOffset(), source.getEndOffset())
* }
* ...
* boolean start() {
* ... (general logic for locating the first record) ...
* if (!tracker.tryReturnRecordAt(true, recordStartOffset)) return false;
* ... (any logic that depends on the record being returned, e.g. counting returned records)
* return true;
* }
* boolean advance() {
* ... (general logic for locating the next record) ...
* if (!tracker.tryReturnRecordAt(isAtSplitPoint, recordStartOffset)) return false;
* ... (any logic that depends on the record being returned, e.g. counting returned records)
* return true;
* }
*
* double getFractionConsumed() {
* return tracker.getFractionConsumed();
* }
* }
* }</pre>
*
* <h3>Usage with different models of iteration</h3>
*
* When using this class to protect a {@link org.apache.beam.sdk.io.BoundedSource.BoundedReader},
* follow the pattern described above.
*
* <p>When using this class to protect iteration in the {@code hasNext()/next()} model, consider the
* record consumed when {@code hasNext()} is about to return true, rather than when {@code next()}
* is called, because {@code hasNext()} returning true is promising the caller that {@code next()}
* will have an element to return - so {@link #trySplitAtPosition} must not split the range in a way
* that would make the record promised by {@code hasNext()} belong to a different range.
*
* <p>Also note that implementations of {@code hasNext()} need to ensure that they call {@link
* #tryReturnRecordAt} only once even if {@code hasNext()} is called repeatedly, due to the
* requirement on uniqueness of split point positions.
*
* @param <PositionT> Type of positions used by the source to define ranges and identify records.
*/
public interface RangeTracker<PositionT> {
/** Returns the starting position of the current range, inclusive. */
PositionT getStartPosition();
/** Returns the ending position of the current range, exclusive. */
PositionT getStopPosition();
/**
* Atomically determines whether a record at the given position can be returned and updates
* internal state. In particular:
*
* <ul>
* <li>If {@code isAtSplitPoint} is {@code true}, and {@code recordStart} is outside the current
* range, returns {@code false};
* <li>Otherwise, updates the last-consumed position to {@code recordStart} and returns {@code
* true}.
* </ul>
*
* <p>This method MUST be called on all split point records. It may be called on every record.
*/
boolean tryReturnRecordAt(boolean isAtSplitPoint, PositionT recordStart);
/**
* Atomically splits the current range [{@link #getStartPosition}, {@link #getStopPosition}) into
* a "primary" part [{@link #getStartPosition}, {@code splitPosition}) and a "residual" part
* [{@code splitPosition}, {@link #getStopPosition}), assuming the current last-consumed position
* is within [{@link #getStartPosition}, splitPosition) (i.e., {@code splitPosition} has not been
* consumed yet).
*
* <p>Updates the current range to be the primary and returns {@code true}. This means that all
* further calls on the current object will interpret their arguments relative to the primary
* range.
*
* <p>If the split position has already been consumed, or if no {@link #tryReturnRecordAt} call
* was made yet, returns {@code false}. The second condition is to prevent dynamic splitting
* during reader start-up.
*/
boolean trySplitAtPosition(PositionT splitPosition);
/**
* Returns the approximate fraction of positions in the source that have been consumed by
* successful {@link #tryReturnRecordAt} calls, or 0.0 if no such calls have happened.
*/
double getFractionConsumed();
}
| 3,105 |
2,637 | <gh_stars>1000+
/** @file usbc_reg.h
*
* @brief Automatically generated register structure
*
* (C) Copyright 2008-2019 Marvell International Ltd. All Rights Reserved
*
* MARVELL CONFIDENTIAL
* The source code contained or described herein and all documents related to
* the source code ("Material") are owned by Marvell International Ltd or its
* suppliers or licensors. Title to the Material remains with Marvell
* International Ltd or its suppliers and licensors. The Material contains
* trade secrets and proprietary and confidential information of Marvell or its
* suppliers and licensors. The Material is protected by worldwide copyright
* and trade secret laws and treaty provisions. No part of the Material may be
* used, copied, reproduced, modified, published, uploaded, posted,
* transmitted, distributed, or disclosed in any way without Marvell's prior
* express written permission.
*
* No license under any patent, copyright, trade secret or other intellectual
* property right is granted to or conferred upon you by disclosure or delivery
* of the Materials, either expressly, by implication, inducement, estoppel or
* otherwise. Any license under such intellectual property rights must be
* express and approved by Marvell in writing.
*
*/
/****************************************************************************//**
* @file usbc_reg.h
* @brief Automatically generated register structure.
* @version V1.0.0
* @date 12-Aug-2013
* @author CE Application Team
*
*******************************************************************************/
#ifndef _USBC_REG_H
#define _USBC_REG_H
struct usbc_reg {
/* 0x000: The ID register identifies the USB-HS 2.0 core and its revision. */
union {
struct {
uint32_t ID : 6; /* [5:0] r/o */
uint32_t RESERVED_7_6 : 2; /* [7:6] rsvd */
uint32_t NID : 6; /* [13:8] r/o */
uint32_t RESERVED_15_14 : 2; /* [15:14] rsvd */
uint32_t TAG : 5; /* [20:16] r/o */
uint32_t REVISION : 4; /* [24:21] r/o */
uint32_t VERSION : 4; /* [28:25] r/o */
uint32_t CIVERSION : 3; /* [31:29] r/o */
} BF;
uint32_t WORDVAL;
} ID;
/* 0x004: General hardware parameters as defined */
union {
struct {
uint32_t RT : 1; /* [0] r/o */
uint32_t CLKC : 2; /* [2:1] r/o */
uint32_t BWT : 1; /* [3] r/o */
uint32_t PHYW : 2; /* [5:4] r/o */
uint32_t PHYM : 4; /* [9:6] r/o */
uint32_t SM : 2; /* [11:10] r/o */
uint32_t RESERVED_31_12 : 20; /* [31:12] rsvd */
} BF;
uint32_t WORDVAL;
} HWGENERAL;
/* 0x008: Host hardware parameters as defined */
union {
struct {
uint32_t HC : 1; /* [0] r/o */
uint32_t NPORT : 3; /* [3:1] r/o */
uint32_t RESERVED_15_4 : 12; /* [15:4] rsvd */
uint32_t TTASY : 8; /* [23:16] r/o */
uint32_t TTPER : 8; /* [31:24] r/o */
} BF;
uint32_t WORDVAL;
} HWHOST;
/* 0x00c: Device hardware parameters as defined */
union {
struct {
uint32_t DC : 1; /* [0] r/o */
uint32_t DEVEP : 5; /* [5:1] r/o */
uint32_t RESERVED_31_6 : 26; /* [31:6] rsvd */
} BF;
uint32_t WORDVAL;
} HWDEVICE;
/* 0x010: TX buffer hardware parameters */
union {
struct {
uint32_t TXBURST : 8; /* [7:0] r/o */
uint32_t TXADD : 8; /* [15:8] r/o */
uint32_t TXCHANADD : 8; /* [23:16] r/o */
uint32_t RESERVED_31_24 : 8; /* [31:24] rsvd */
} BF;
uint32_t WORDVAL;
} HWTXBUF;
/* 0x014: RX buffer hardware parameters */
union {
struct {
uint32_t RXBURST : 8; /* [7:0] r/o */
uint32_t RXADD : 8; /* [15:8] r/o */
uint32_t RESERVED_31_16 : 16; /* [31:16] rsvd */
} BF;
uint32_t WORDVAL;
} HWRXBUF;
uint8_t zReserved0x018[104]; /* pad 0x018 - 0x07f */
/* 0x080: */
union {
struct {
uint32_t GPTLD : 24; /* [23:0] r/w */
uint32_t RESERVED_31_24 : 8; /* [31:24] rsvd */
} BF;
uint32_t WORDVAL;
} GPTIMER0LD;
/* 0x084: */
union {
struct {
uint32_t GPTCNT : 24; /* [23:0] r/o */
uint32_t GPTMODE : 1; /* [24] r/w */
uint32_t RESERVED_29_25 : 5; /* [29:25] rsvd */
uint32_t GPTRST : 1; /* [30] r/o */
uint32_t GPTRUN : 1; /* [31] r/w */
} BF;
uint32_t WORDVAL;
} GPTIMER0CTRL;
/* 0x088: */
union {
struct {
uint32_t GPTLD : 24; /* [23:0] r/w */
uint32_t RESERVED_31_24 : 8; /* [31:24] rsvd */
} BF;
uint32_t WORDVAL;
} GPTTIMER1LD;
/* 0x08c: */
union {
struct {
uint32_t GPTCNT : 24; /* [23:0] r/o */
uint32_t GPTMODE : 1; /* [24] r/w */
uint32_t RESERVED_29_25 : 5; /* [29:25] rsvd */
uint32_t GPTRST : 1; /* [30] r/o */
uint32_t GPTRUN : 1; /* [31] r/w */
} BF;
uint32_t WORDVAL;
} GPTIMER1CTRL;
/* 0x090: This register contains the control for the system bus interface */
union {
struct {
uint32_t AHBBRST : 3; /* [2:0] r/w */
uint32_t RESERVED_31_3 : 29; /* [31:3] rsvd */
} BF;
uint32_t WORDVAL;
} SBUSCFG;
uint8_t zReserved0x094[108]; /* pad 0x094 - 0x0ff */
/* 0x100: indicate which offset to add to the register base address */
union {
struct {
uint32_t CAPLENGTH : 8; /* [7:0] r/o */
uint32_t RESERVED_15_8 : 8; /* [15:8] rsvd */
uint32_t HCIVERSION : 16; /* [31:16] r/o */
} BF;
uint32_t WORDVAL;
} CAPLENGTH_HCIVERSION;
/* 0x104: Port steering logic capabilities */
union {
struct {
uint32_t N_PORTS : 4; /* [3:0] r/o */
uint32_t PPC : 1; /* [4] r/o */
uint32_t RESERVED_7_5 : 3; /* [7:5] rsvd */
uint32_t N_PCC : 4; /* [11:8] r/o */
uint32_t N_CC : 4; /* [15:12] r/o */
uint32_t PI : 1; /* [16] r/o */
uint32_t RESERVED_19_17 : 3; /* [19:17] rsvd */
uint32_t N_PTT : 4; /* [23:20] r/o */
uint32_t N_TT : 4; /* [27:24] r/o */
uint32_t RESERVED_31_28 : 4; /* [31:28] rsvd */
} BF;
uint32_t WORDVAL;
} HCSPARAMS;
/* 0x108: identifies multiple mode control */
union {
struct {
uint32_t ADC : 1; /* [0] r/o */
uint32_t PFL : 1; /* [1] r/o */
uint32_t ASP : 1; /* [2] r/o */
uint32_t RESERVED_3 : 1; /* [3] rsvd */
uint32_t IST : 4; /* [7:4] r/o */
uint32_t EECP : 8; /* [15:8] r/o */
uint32_t RESERVED_31_16 : 16; /* [31:16] rsvd */
} BF;
uint32_t WORDVAL;
} HCCPARAMS;
uint8_t zReserved0x10c[20]; /* pad 0x10c - 0x11f */
/* 0x120: */
union {
struct {
uint32_t DCIVERSION : 16; /* [15:0] r/o */
uint32_t RESERVED_31_16 : 16; /* [31:16] rsvd */
} BF;
uint32_t WORDVAL;
} DCIVERSION;
/* 0x124: describe the overall host/device capability of the controller. */
union {
struct {
uint32_t DEN : 5; /* [4:0] r/o */
uint32_t RESERVED_6_5 : 2; /* [6:5] rsvd */
uint32_t DC : 1; /* [7] r/o */
uint32_t HC : 1; /* [8] r/o */
uint32_t RESERVED_31_9 : 23; /* [31:9] rsvd */
} BF;
uint32_t WORDVAL;
} DCCPARAMS;
uint8_t zReserved0x128[24]; /* pad 0x128 - 0x13f */
/* 0x140: The serial bus host/device controller executes the command */
/* indicated in this register. */
union {
struct {
uint32_t RS : 1; /* [0] r/w */
uint32_t RST : 1; /* [1] r/w */
uint32_t FS0 : 1; /* [2] r/w */
uint32_t FS1 : 1; /* [3] r/w */
uint32_t PSE : 1; /* [4] r/w */
uint32_t ASE : 1; /* [5] r/w */
uint32_t IAA : 1; /* [6] r/w */
uint32_t LR : 1; /* [7] r/o */
uint32_t ASP0 : 1; /* [8] r/w */
uint32_t ASP1 : 1; /* [9] r/w */
uint32_t RESERVED_10 : 1; /* [10] rsvd */
uint32_t ASPE : 1; /* [11] r/w */
uint32_t RESERVED_12 : 1; /* [12] rsvd */
uint32_t SUTW : 1; /* [13] r/w */
uint32_t ATDTW : 1; /* [14] r/w */
uint32_t FS2 : 1; /* [15] r/w */
uint32_t ITC : 8; /* [23:16] r/w */
uint32_t RESERVED_31_24 : 8; /* [31:24] rsvd */
} BF;
uint32_t WORDVAL;
} USBCMD;
/* 0x144: indicates various states of the Controller and any pending */
/* interrupts */
union {
struct {
uint32_t UI : 1; /* [0] r/w */
uint32_t UEI : 1; /* [1] r/w */
uint32_t PCI : 1; /* [2] r/w */
uint32_t FRI : 1; /* [3] r/w */
uint32_t SEI : 1; /* [4] r/w */
uint32_t AAI : 1; /* [5] r/w */
uint32_t URI : 1; /* [6] r/w */
uint32_t SRI : 1; /* [7] r/w */
uint32_t SLI : 1; /* [8] r/w */
uint32_t RESERVED_9 : 1; /* [9] rsvd */
uint32_t ULPII : 1; /* [10] r/w */
uint32_t UALTI : 1; /* [11] r/o */
uint32_t HCH : 1; /* [12] r/o */
uint32_t RCL : 1; /* [13] r/o */
uint32_t PS : 1; /* [14] r/o */
uint32_t AS : 1; /* [15] r/o */
uint32_t NAKI : 1; /* [16] r/o */
uint32_t RESERVED_17 : 1; /* [17] rsvd */
uint32_t UAI : 1; /* [18] r/w */
uint32_t UPI : 1; /* [19] r/w */
uint32_t RESERVED_23_20 : 4; /* [23:20] rsvd */
uint32_t TI0 : 1; /* [24] r/w */
uint32_t TI1 : 1; /* [25] r/w */
uint32_t RESERVED_31_26 : 6; /* [31:26] rsvd */
} BF;
uint32_t WORDVAL;
} USBSTS;
/* 0x148: interrupt sources */
union {
struct {
uint32_t UE : 1; /* [0] r/w */
uint32_t UEE : 1; /* [1] r/w */
uint32_t PCE : 1; /* [2] r/w */
uint32_t FRE : 1; /* [3] r/w */
uint32_t SEE : 1; /* [4] r/w */
uint32_t AAE : 1; /* [5] r/w */
uint32_t URE : 1; /* [6] r/w */
uint32_t SRE : 1; /* [7] r/w */
uint32_t SLE : 1; /* [8] r/w */
uint32_t RESERVED_9 : 1; /* [9] rsvd */
uint32_t ULPIE : 1; /* [10] r/w */
uint32_t UALTIE : 1; /* [11] r/w */
uint32_t RESERVED_15_12 : 4; /* [15:12] rsvd */
uint32_t NAKE : 1; /* [16] r/o */
uint32_t RESERVED_17 : 1; /* [17] rsvd */
uint32_t UAIE : 1; /* [18] r/w */
uint32_t UPIE : 1; /* [19] r/w */
uint32_t RESERVED_23_20 : 4; /* [23:20] rsvd */
uint32_t TIE0 : 1; /* [24] r/w */
uint32_t TIE1 : 1; /* [25] r/w */
uint32_t RESERVED_31_26 : 6; /* [31:26] rsvd */
} BF;
uint32_t WORDVAL;
} USBINTR;
/* 0x14c: used by the host controller to index the periodic frame list */
union {
struct {
uint32_t FRINDEX : 14; /* [13:0] r/w */
uint32_t RESERVED_31_14 : 18; /* [31:14] rsvd */
} BF;
uint32_t WORDVAL;
} FRINDEX;
uint8_t zReserved0x150[4]; /* pad 0x150 - 0x153 */
/* 0x154: host controller frame list base address */
/* 0x154: device controller usb device address */
union {
struct {
uint32_t RESERVED_11_0 : 12; /* [11:0] rsvd */
uint32_t PERBASE : 20; /* [31:12] r/w */
} BF_PERIODICLISTBASE_HOST;
struct {
uint32_t RESERVED_23_0 : 24; /* [23:0] rsvd */
uint32_t USBADRA : 1; /* [24] r/w */
uint32_t USBADR : 7; /* [31:25] r/w */
} BF_PERIODICLISTBASE_DEVICE;
uint32_t WORDVAL;
} HOST_PERIODICLISTBASE_DEVICE;
/* 0x158: contains the address of the top of the endpoint list in system */
/* memory */
/* 0x158: contains the address of the top of the endpoint list in system */
/* memory */
union {
struct {
uint32_t RESERVED_4_0 : 5; /* [4:0] rsvd */
uint32_t ASYBASE : 27; /* [31:5] r/w */
} BF_ASYNCLISTADDR_HOST;
struct {
uint32_t RESERVED_10_0 : 11; /* [10:0] rsvd */
uint32_t EPBASE : 21; /* [31:11] r/w */
} BF_ASYNCLISTADDR_DEVICE;
uint32_t WORDVAL;
} HOST_ASYNCLISTADDR_DEVICE;
/* 0x15c: contains parameters needed for internal TT operations. */
union {
struct {
uint32_t TTAS : 1; /* [0] r/o */
uint32_t TTAC : 1; /* [1] r/w */
uint32_t RESERVED_23_2 : 22; /* [23:2] rsvd */
uint32_t TTHA : 7; /* [30:24] r/w */
uint32_t RESERVED_31 : 1; /* [31] rsvd */
} BF;
uint32_t WORDVAL;
} TTCTRL;
/* 0x160: controls the burst size used during data movement */
union {
struct {
uint32_t RXPBURST : 8; /* [7:0] r/w */
uint32_t TXPBURST : 8; /* [15:8] r/w */
uint32_t RESERVED_31_16 : 16; /* [31:16] rsvd */
} BF;
uint32_t WORDVAL;
} BURSTSIZE;
/* 0x164: */
union {
struct {
uint32_t TXSCHOH : 7; /* [6:0] r/w */
uint32_t RESERVED_7 : 1; /* [7] rsvd */
uint32_t TXSCHHEALTH : 5; /* [12:8] r/w */
uint32_t RESERVED_15_13 : 3; /* [15:13] rsvd */
uint32_t TXFIFOTHRES : 6; /* [21:16] r/w */
uint32_t RESERVED_31_22 : 10; /* [31:22] rsvd */
} BF;
uint32_t WORDVAL;
} TXFILLTUNING;
/* 0x168: */
union {
struct {
uint32_t TXTTSCHOH : 5; /* [4:0] r/w */
uint32_t RESERVED_7_5 : 3; /* [7:5] rsvd */
uint32_t TXTTSCHHEALTJ : 5; /* [12:8] r/w */
uint32_t RESERVED_31_13 : 19; /* [31:13] rsvd */
} BF;
uint32_t WORDVAL;
} TXTTFILLTUNING;
/* 0x16c: enable and controls the IC_USB FS/LS transceiver. */
union {
struct {
uint32_t IC_VDD1 : 3; /* [2:0] r/w */
uint32_t IC1 : 1; /* [3] r/w */
uint32_t IC_VDD2 : 3; /* [6:4] r/w */
uint32_t IC2 : 1; /* [7] r/w */
uint32_t IC_VDD3 : 3; /* [10:8] r/w */
uint32_t IC3 : 1; /* [11] r/w */
uint32_t IC_VDD4 : 3; /* [14:12] r/w */
uint32_t IC4 : 1; /* [15] r/w */
uint32_t IC_VDD5 : 3; /* [18:16] r/w */
uint32_t IC5 : 1; /* [19] r/w */
uint32_t IC_VDD6 : 3; /* [22:20] r/w */
uint32_t IC6 : 1; /* [23] r/w */
uint32_t IC_VDD7 : 3; /* [26:24] r/w */
uint32_t IC7 : 1; /* [27] r/w */
uint32_t IC_VDD8 : 3; /* [30:28] r/w */
uint32_t IC8 : 1; /* [31] r/w */
} BF;
uint32_t WORDVAL;
} IC_USB;
/* 0x170: provides indirect access to the ULPI PHY register set. */
union {
struct {
uint32_t ULPIDATWR : 8; /* [7:0] r/w */
uint32_t ULPIDATRD : 8; /* [15:8] r/o */
uint32_t ULPIADDR : 8; /* [23:16] r/w */
uint32_t ULPIPORT : 3; /* [26:24] r/w */
uint32_t ULPISS : 1; /* [27] r/w */
uint32_t RESERVED_28 : 1; /* [28] rsvd */
uint32_t ULPIRW : 1; /* [29] r/w */
uint32_t ULPIRUN : 1; /* [30] r/w */
uint32_t ULPIWU : 1; /* [31] r/w */
} BF;
uint32_t WORDVAL;
} ULPI_VIEWPORT;
uint8_t zReserved0x174[4]; /* pad 0x174 - 0x177 */
/* 0x178: */
union {
struct {
uint32_t EPRN : 16; /* [15:0] r/w */
uint32_t EPTN : 16; /* [31:16] r/w */
} BF;
uint32_t WORDVAL;
} ENDPTNAK;
/* 0x17c: */
union {
struct {
uint32_t EPRNE : 16; /* [15:0] r/w */
uint32_t EPTNE : 16; /* [31:16] r/w */
} BF;
uint32_t WORDVAL;
} ENDPTNAKEN;
uint8_t zReserved0x180[4]; /* pad 0x180 - 0x183 */
/* 0x184: */
union {
struct {
uint32_t CCS : 1; /* [0] r/o */
uint32_t CSC : 1; /* [1] r/w */
uint32_t PE : 1; /* [2] r/w */
uint32_t PEC : 1; /* [3] r/w */
uint32_t OCA : 1; /* [4] r/o */
uint32_t OCC : 1; /* [5] r/w */
uint32_t FPR : 1; /* [6] r/w */
uint32_t SUSP : 1; /* [7] r/w */
uint32_t PR : 1; /* [8] r/w */
uint32_t HSP : 1; /* [9] r/o */
uint32_t LS : 2; /* [11:10] r/o */
uint32_t PP : 1; /* [12] r/w */
uint32_t PO : 1; /* [13] r/o */
uint32_t PIC : 2; /* [15:14] r/w */
uint32_t PTC : 4; /* [19:16] r/w */
uint32_t WKCN : 1; /* [20] r/w */
uint32_t WKDS : 1; /* [21] r/w */
uint32_t WKOC : 1; /* [22] r/w */
uint32_t PHCD : 1; /* [23] r/w */
uint32_t PFSC : 1; /* [24] r/w */
uint32_t PTS2 : 1; /* [25] r/w */
uint32_t PSPD : 2; /* [27:26] r/o */
uint32_t PTW : 1; /* [28] r/w */
uint32_t STS : 1; /* [29] r/w */
uint32_t PTS : 2; /* [31:30] r/w */
} BF;
uint32_t WORDVAL;
} PORTSC1;
uint8_t zReserved0x188[28]; /* pad 0x188 - 0x1a3 */
/* 0x1a4: This register only exists in a OTG implementation. */
union {
struct {
uint32_t VD : 1; /* [0] r/w */
uint32_t VC : 1; /* [1] r/w */
uint32_t HAAR : 1; /* [2] r/w */
uint32_t OT : 1; /* [3] r/w */
uint32_t DP : 1; /* [4] r/w */
uint32_t IDPU : 1; /* [5] r/w */
uint32_t HADP : 1; /* [6] r/w */
uint32_t HABA : 1; /* [7] r/w */
uint32_t ID : 1; /* [8] r/o */
uint32_t AVV : 1; /* [9] r/o */
uint32_t ASV : 1; /* [10] r/o */
uint32_t BSV : 1; /* [11] r/o */
uint32_t BSE : 1; /* [12] r/o */
uint32_t _1MST : 1; /* [13] r/o */
uint32_t DPS : 1; /* [14] r/o */
uint32_t RESERVED_15 : 1; /* [15] rsvd */
uint32_t IDIS : 1; /* [16] r/w */
uint32_t AVVIS : 1; /* [17] r/w */
uint32_t ASVIS : 1; /* [18] r/w */
uint32_t BSVIS : 1; /* [19] r/w */
uint32_t BSEIS : 1; /* [20] r/w */
uint32_t _1MSS : 1; /* [21] r/w */
uint32_t DPIS : 1; /* [22] r/w */
uint32_t RESERVED_23 : 1; /* [23] rsvd */
uint32_t IDIE : 1; /* [24] r/w */
uint32_t AVVIE : 1; /* [25] r/w */
uint32_t ASVIE : 1; /* [26] r/w */
uint32_t BSVIE : 1; /* [27] r/w */
uint32_t BSEIE : 1; /* [28] r/w */
uint32_t _1MSE : 1; /* [29] r/w */
uint32_t DPIE : 1; /* [30] r/w */
uint32_t RESERVED_31 : 1; /* [31] rsvd */
} BF;
uint32_t WORDVAL;
} OTGSC;
/* 0x1a8: */
union {
struct {
uint32_t CM : 2; /* [1:0] r/w */
uint32_t ES : 1; /* [2] r/w */
uint32_t SLOM : 1; /* [3] r/w */
uint32_t SDIS : 1; /* [4] r/w */
uint32_t VBPS : 1; /* [5] r/w */
uint32_t RESERVED_14_6 : 9; /* [14:6] rsvd */
uint32_t SRT : 1; /* [15] r/w */
uint32_t RESERVED_31_16 : 16; /* [31:16] rsvd */
} BF;
uint32_t WORDVAL;
} USBMODE;
/* 0x1ac: Setup Endpoint Status */
union {
struct {
uint32_t ENDPTSETUPSTAT : 16; /* [15:0] r/w */
uint32_t RESERVED_31_16 : 16; /* [31:16] rsvd */
} BF;
uint32_t WORDVAL;
} ENDPTSETUPSTAT;
/* 0x1b0: */
union {
struct {
uint32_t PERB : 16; /* [15:0] r/w */
uint32_t PETB : 16; /* [31:16] r/w */
} BF;
uint32_t WORDVAL;
} ENDPTPRIME;
/* 0x1b4: */
union {
struct {
uint32_t FERB : 16; /* [15:0] r/w */
uint32_t FETB : 16; /* [31:16] r/w */
} BF;
uint32_t WORDVAL;
} ENDPTFLUSH;
/* 0x1b8: */
union {
struct {
uint32_t ERBR : 16; /* [15:0] r/o */
uint32_t ETBR : 16; /* [31:16] r/o */
} BF;
uint32_t WORDVAL;
} ENDPTSTAT;
/* 0x1bc: */
union {
struct {
uint32_t ERCE : 16; /* [15:0] r/w */
uint32_t ETCE : 16; /* [31:16] r/w */
} BF;
uint32_t WORDVAL;
} ENDPTCOMPLETE;
/* 0x1c0: Every device will implement Endpoint0 as a control endpoint. */
union {
struct {
uint32_t RXS : 1; /* [0] r/w */
uint32_t RESERVED_1 : 1; /* [1] rsvd */
uint32_t RXT : 2; /* [3:2] r/o */
uint32_t RESERVED_6_4 : 3; /* [6:4] rsvd */
uint32_t RXE : 1; /* [7] r/o */
uint32_t RESERVED_15_8 : 8; /* [15:8] rsvd */
uint32_t TXS : 1; /* [16] r/w */
uint32_t RESERVED_17 : 1; /* [17] rsvd */
uint32_t TXT : 2; /* [19:18] r/o */
uint32_t RESERVED_22_20 : 3; /* [22:20] rsvd */
uint32_t TXE : 1; /* [23] r/o */
uint32_t RESERVED_31_24 : 8; /* [31:24] rsvd */
} BF;
uint32_t WORDVAL;
} ENDPTCTRL0;
/* 0x1c4--0x1e0: */
union {
struct {
uint32_t RXS : 1; /* [0] r/w */
uint32_t RXD : 1; /* [1] r/w */
uint32_t RXT : 2; /* [3:2] r/w */
uint32_t RESERVED_4 : 1; /* [4] rsvd */
uint32_t RXI : 1; /* [5] r/w */
uint32_t RXR : 1; /* [6] r/w */
uint32_t RXE : 1; /* [7] r/w */
uint32_t RESERVED_15_8 : 8; /* [15:8] rsvd */
uint32_t TXS : 1; /* [16] r/w */
uint32_t TXD : 1; /* [17] r/w */
uint32_t TXT : 2; /* [19:18] r/w */
uint32_t RESERVED_20 : 1; /* [20] rsvd */
uint32_t TXI : 1; /* [21] r/w */
uint32_t TXR : 1; /* [22] r/w */
uint32_t TXE : 1; /* [23] r/w */
uint32_t RESERVED_31_24 : 8; /* [31:24] rsvd */
} BF;
uint32_t WORDVAL;
} ENDPTCTRL[7];
uint8_t zReserved0x1e0[32]; /* pad 0x1e0 - 0x1ff */
/* 0x200: */
union {
struct {
uint32_t CID0 : 8; /* [7:0] r/o */
uint32_t CID1 : 8; /* [15:8] r/o */
uint32_t RESERVED_31_16 : 16; /* [31:16] rsvd */
} BF;
uint32_t WORDVAL;
} PHY_ID;
/* 0x204: */
union {
struct {
uint32_t FBDIV : 9; /* [8:0] r/w */
uint32_t REFDIV : 5; /* [13:9] r/w */
uint32_t PLLVDD18 : 2; /* [15:14] r/w */
uint32_t RESERVED_31_16 : 16; /* [31:16] rsvd */
} BF;
uint32_t WORDVAL;
} PLL_CONTROL_0;
/* 0x208: */
union {
struct {
uint32_t PLLCAL12 : 2; /* [1:0] r/w */
uint32_t VCOCAL_START : 1; /* [2] r/w */
uint32_t CLK_BLK_EN : 1; /* [3] r/w */
uint32_t KVCO : 3; /* [6:4] r/w */
uint32_t KVCO_EXT : 1; /* [7] r/w */
uint32_t ICP : 3; /* [10:8] r/w */
uint32_t DLL_RESET_BLK : 1; /* [11] r/w */
uint32_t PLL_LOCK_BYPASS : 1; /* [12] r/w */
uint32_t PU_PLL : 1; /* [13] r/w */
uint32_t PLL_CONTRL_BY_PIN : 1; /* [14] r/w */
uint32_t PLL_READY : 1; /* [15] r/o */
uint32_t RESERVED_31_16 : 16; /* [31:16] rsvd */
} BF;
uint32_t WORDVAL;
} PLL_CONTROL_1;
/* 0x20c: */
union {
struct {
uint32_t RESERVED_BIT_15_0 : 16; /* [15:0] r/o */
uint32_t RESERVED_31_16 : 16; /* [31:16] rsvd */
} BF;
uint32_t WORDVAL;
} RESERVED_ADDR3;
/* 0x210: */
union {
struct {
uint32_t EXT_FS_RCAL : 4; /* [3:0] r/w */
uint32_t EXT_HS_RCAL : 4; /* [7:4] r/w */
uint32_t IMPCAL_VTH : 3; /* [10:8] r/w */
uint32_t EXT_FS_RCAL_EN : 1; /* [11] r/w */
uint32_t EXT_HS_RCAL_EN : 1; /* [12] r/w */
uint32_t RCAL_START : 1; /* [13] r/w */
uint32_t TXDATA_BLOCK_EN : 1; /* [14] r/w */
uint32_t ND : 1; /* [15] r/o */
uint32_t RESERVED_31_16 : 16; /* [31:16] rsvd */
} BF;
uint32_t WORDVAL;
} TX_CHANNEL_CONTRL_0;
/* 0x214: */
union {
struct {
uint32_t CK60_PHSEL : 4; /* [3:0] r/w */
uint32_t AMP : 3; /* [6:4] r/w */
uint32_t LOWVDD_EN : 1; /* [7] r/w */
uint32_t TXVDD12 : 2; /* [9:8] r/w */
uint32_t TXVDD15 : 2; /* [11:10] r/w */
uint32_t ND : 4; /* [15:12] r/o */
uint32_t RESERVED_31_16 : 16; /* [31:16] rsvd */
} BF;
uint32_t WORDVAL;
} TX_CHANNEL_CONTRL_1;
/* 0x218: */
union {
struct {
uint32_t HSDRV_EN : 4; /* [3:0] r/w */
uint32_t FSDRV_EN : 4; /* [7:4] r/w */
uint32_t IMP_CAL_DLY : 2; /* [9:8] r/w */
uint32_t DRV_SLEWRATE : 2; /* [11:10] r/w */
uint32_t ND : 4; /* [15:12] r/o */
uint32_t RESERVED_31_16 : 16; /* [31:16] rsvd */
} BF;
uint32_t WORDVAL;
} TX_CHANNEL_CONTRL_2;
/* 0x21c: */
union {
struct {
uint32_t RESERVED_BIT_15_0 : 16; /* [15:0] r/o */
uint32_t RESERVED_31_16 : 16; /* [31:16] rsvd */
} BF;
uint32_t WORDVAL;
} RESERVED_ADDR7;
/* 0x220: */
union {
struct {
uint32_t INTPI : 2; /* [1:0] r/w */
uint32_t LPF_COEF : 2; /* [3:2] r/w */
uint32_t SQ_THRESH : 4; /* [7:4] r/w */
uint32_t DISCON_THRESH : 2; /* [9:8] r/w */
uint32_t SQ_LENGTH : 2; /* [11:10] r/w */
uint32_t ACQ_LENGTH : 2; /* [13:12] r/w */
uint32_t USQ_LENGTH : 1; /* [14] r/w */
uint32_t PHASE_FREEZE_DLY : 1; /* [15] r/w */
uint32_t RESERVED_31_16 : 16; /* [31:16] rsvd */
} BF;
uint32_t WORDVAL;
} RX_CHANNEL_CONTRL_0;
/* 0x224: */
union {
struct {
uint32_t S2TO3_DLY_SEL : 2; /* [1:0] r/w */
uint32_t CDR_FASTLOCK_EN : 1; /* [2] r/w */
uint32_t CDR_COEF_SEL : 1; /* [3] r/w */
uint32_t EDGE_DET_SEL : 2; /* [5:4] r/w */
uint32_t RXDATA_BLOCK_LENGTH : 2; /* [7:6] r/w */
uint32_t CAP_SEL : 3; /* [10:8] r/w */
uint32_t EDGE_DET_EN : 1; /* [11] r/w */
uint32_t RXDATA_BLOCK_EN : 1; /* [12] r/w */
uint32_t EARLY_VOS_ON_EN : 1; /* [13] r/w */
uint32_t ND : 2; /* [15:14] r/o */
uint32_t RESERVED_31_16 : 16; /* [31:16] rsvd */
} BF;
uint32_t WORDVAL;
} RX_CHANNEL_CONTRL_1;
/* 0x228: */
union {
struct {
uint32_t RXVDD12 : 2; /* [1:0] r/w */
uint32_t RXVDD18 : 2; /* [3:2] r/w */
uint32_t SQ_ALWAYS_ON : 1; /* [4] r/w */
uint32_t SQ_BUFFER_EN : 1; /* [5] r/w */
uint32_t SAMPLER_CTRL : 1; /* [6] r/w */
uint32_t SQ_CM_SEL : 1; /* [7] r/w */
uint32_t USQ_FILTER : 1; /* [8] r/w */
uint32_t ND : 7; /* [15:9] r/o */
uint32_t RESERVED_31_16 : 16; /* [31:16] rsvd */
} BF;
uint32_t WORDVAL;
} RX_CHANNEL_CONTRL_2;
uint8_t zReserved0x22c[4]; /* pad 0x22c - 0x22f */
/* 0x230: */
union {
struct {
uint32_t IPTAT_SEL : 3; /* [2:0] r/w */
uint32_t VDD_USB2_DIG_TOP_SEL : 1; /* [3] r/w */
uint32_t TOPVDD18 : 2; /* [5:4] r/w */
uint32_t DIG_SEL : 2; /* [7:6] r/w */
uint32_t BG_VSEL : 2; /* [9:8] r/w */
uint32_t ND : 6; /* [15:10] r/o */
uint32_t RESERVED_31_16 : 16; /* [31:16] rsvd */
} BF;
uint32_t WORDVAL;
} ANA_CONTRL_0;
/* 0x234: */
union {
struct {
uint32_t TESTMON_ANA : 6; /* [5:0] r/w */
uint32_t STRESS_TEST_MODE : 1; /* [6] r/w */
uint32_t R_ROTATE_SEL : 1; /* [7] r/w */
uint32_t V2I : 3; /* [10:8] r/w */
uint32_t V2I_EXT : 1; /* [11] r/w */
uint32_t SEL_LPFR : 1; /* [12] r/w */
uint32_t ANA_CONTRL_BY_PIN : 1; /* [13] r/w */
uint32_t PU_ANA : 1; /* [14] r/w */
uint32_t ND : 1; /* [15] r/o */
uint32_t RESERVED_31_16 : 16; /* [31:16] rsvd */
} BF;
uint32_t WORDVAL;
} ANA_CONTRL_1;
/* 0x238: */
union {
struct {
uint32_t RESERVED_BIT_15_0 : 16; /* [15:0] r/w */
uint32_t RESERVED_31_16 : 16; /* [31:16] rsvd */
} BF;
uint32_t WORDVAL;
} RESERVED_ADDR_C;
/* 0x23c: */
union {
struct {
uint32_t FIFO_FILL_NUM : 4; /* [3:0] r/w */
uint32_t SYNC_NUM : 2; /* [5:4] r/w */
uint32_t HS_DRIBBLE_EN : 1; /* [6] r/w */
uint32_t CLK_SUSPEND_EN : 1; /* [7] r/w */
uint32_t SYNCDET_WINDOW_EN : 1; /* [8] r/w */
uint32_t EARLY_TX_EN : 1; /* [9] r/w */
uint32_t FORCE_END_EN : 1; /* [10] r/w */
uint32_t HOST_DISCON_SEL0 : 1; /* [11] r/w */
uint32_t HOST_DISCON_SEL1 : 1; /* [12] r/w */
uint32_t FS_EOP_MODE : 1; /* [13] r/w */
uint32_t FIFO_OV : 1; /* [14] r/o */
uint32_t FIFO_UF : 1; /* [15] r/o */
uint32_t RESERVED_31_16 : 16; /* [31:16] rsvd */
} BF;
uint32_t WORDVAL;
} DIGITAL_CONTROL_0;
/* 0x240: */
union {
struct {
uint32_t MON_SEL : 6; /* [5:0] r/w */
uint32_t SQ_RST_RX : 1; /* [6] r/w */
uint32_t SYNC_IGNORE_SQ : 1; /* [7] r/w */
uint32_t DM_PULLDOWN : 1; /* [8] r/w */
uint32_t DP_PULLDOWN : 1; /* [9] r/w */
uint32_t ARC_DPDM_MODE : 1; /* [10] r/w */
uint32_t EXT_TX_CLK_SEL : 1; /* [11] r/w */
uint32_t CLK_OUT_SEL : 1; /* [12] r/w */
uint32_t FS_RX_ERROR_MODE : 1; /* [13] r/w */
uint32_t FS_RX_ERROR_MODE1 : 1; /* [14] r/w */
uint32_t FS_RX_ERROR_MODE2 : 1; /* [15] r/w */
uint32_t RESERVED_31_16 : 16; /* [31:16] rsvd */
} BF;
uint32_t WORDVAL;
} DIGITAL_CONTROL_1;
/* 0x244: */
union {
struct {
uint32_t FS_HDL_OPMD : 1; /* [0] r/w */
uint32_t HS_HDL_SYNC : 1; /* [1] r/w */
uint32_t ALIGN_FS_OUTEN : 1; /* [2] r/w */
uint32_t DISABLE_EL16 : 1; /* [3] r/w */
uint32_t NOVBUS_DPDM00 : 1; /* [4] r/w */
uint32_t LONG_EOP : 1; /* [5] r/w */
uint32_t ND : 2; /* [7:6] r/o */
uint32_t PAD_STRENGTH : 5; /* [12:8] r/w */
uint32_t ND_15_13 : 3; /* [15:13] r/o */
uint32_t RESERVED_31_16 : 16; /* [31:16] rsvd */
} BF;
uint32_t WORDVAL;
} DIGITAL_CONTROL_2;
/* 0x248: */
union {
struct {
uint32_t RESERVED_BIT_15_0 : 16; /* [15:0] r/o */
uint32_t RESERVED_31_16 : 16; /* [31:16] rsvd */
} BF;
uint32_t WORDVAL;
} RESERVED_ADDR_12H;
/* 0x24c: */
union {
struct {
uint32_t TEST_TX_PATTERN : 8; /* [7:0] r/w */
uint32_t TEST_MODE_2_0 : 3; /* [10:8] r/w */
uint32_t TEST_BYPASS : 1; /* [11] r/w */
uint32_t TEST_LENGTH_1_0 : 2; /* [13:12] r/w */
uint32_t TEST_ANA_LPBK : 1; /* [14] r/w */
uint32_t TEST_DIG_LPBK : 1; /* [15] r/w */
uint32_t RESERVED_31_16 : 16; /* [31:16] rsvd */
} BF;
uint32_t WORDVAL;
} TEST_CONTRL_AND_STATUS_0;
/* 0x250: */
union {
struct {
uint32_t TEST_XCVR_SELECT : 2; /* [1:0] r/w */
uint32_t TEST_OP_MODE : 2; /* [3:2] r/w */
uint32_t TEST_TERM_SELECT : 1; /* [4] r/w */
uint32_t TEST_TX_BITSTUFF_EN : 1; /* [5] r/w */
uint32_t TEST_SUSPENDM : 1; /* [6] r/w */
uint32_t TEST_UTMI_SEL : 1; /* [7] r/w */
uint32_t TEST_SKIP_2_0 : 3; /* [10:8] r/w */
uint32_t ND : 1; /* [11] r/w */
uint32_t TEST_RESET : 1; /* [12] r/w */
uint32_t TEST_EN : 1; /* [13] r/w */
uint32_t TEST_FLAG : 1; /* [14] r/o */
uint32_t TEST_DONE : 1; /* [15] r/o */
uint32_t RESERVED_31_16 : 16; /* [31:16] rsvd */
} BF;
uint32_t WORDVAL;
} TEST_CONTRL_AND_STATUS_1;
/* 0x254: */
union {
struct {
uint32_t RESERVED_BIT_15_0 : 16; /* [15:0] r/o */
uint32_t RESERVED_31_16 : 16; /* [31:16] rsvd */
} BF;
uint32_t WORDVAL;
} RESERVED_ADDR_15H;
/* 0x258: */
union {
struct {
uint32_t TESTMON_CHRGDTC : 2; /* [1:0] r/w */
uint32_t PU_CHRG_DTC : 1; /* [2] r/w */
uint32_t ENABLE_SWITCH : 1; /* [3] r/w */
uint32_t ND : 12; /* [15:4] r/o */
uint32_t RESERVED_31_16 : 16; /* [31:16] rsvd */
} BF;
uint32_t WORDVAL;
} PHY_REG_CHGDTC_CONTRL;
/* 0x25c: */
union {
struct {
uint32_t TESTMON_OTG_2_0 : 3; /* [2:0] r/w */
uint32_t PU_OTG : 1; /* [3] r/w */
uint32_t OTG_CONTROL_BY_PIN : 1; /* [4] r/w */
uint32_t ND : 11; /* [15:5] r/o */
uint32_t RESERVED_31_16 : 16; /* [31:16] rsvd */
} BF;
uint32_t WORDVAL;
} PHY_REG_OTG_CONTROL;
/* 0x260: */
union {
struct {
uint32_t PHY_MON : 16; /* [15:0] r/w */
uint32_t RESERVED_31_16 : 16; /* [31:16] rsvd */
} BF;
uint32_t WORDVAL;
} USB2_PHY_MON0;
/* 0x264: */
union {
struct {
uint32_t RESERVED_0 : 2; /* [1:0] r/o */
uint32_t CDP_EN : 1; /* [2] r/w */
uint32_t DCP_EN : 1; /* [3] r/w */
uint32_t PD_EN : 1; /* [4] r/w */
uint32_t CDP_DM_AUTO_SWITCH : 1; /* [5] r/w */
uint32_t ENABLE_SWITCH_DM : 1; /* [6] r/w */
uint32_t ENABLE_SWITCH_DP : 1; /* [7] r/w */
uint32_t VDAT_CHARGE : 2; /* [9:8] r/w */
uint32_t VSRC_CHARGE : 2; /* [11:10] r/w */
uint32_t PLLVDD12 : 2; /* [13:12] r/w */
uint32_t RESERVED_14 : 1; /* [14] r/o */
uint32_t DP_DM_SWAP_CTRL : 1; /* [15] r/w */
uint32_t RESERVED_31_16 : 16; /* [31:16] rsvd */
} BF;
uint32_t WORDVAL;
} PHY_REG_CHGDTC_CONTRL_1;
/* 0x268: */
union {
struct {
uint32_t RESERVED_BIT_15_0 : 16; /* [15:0] r/o */
uint32_t RESERVED_31_16 : 16; /* [31:16] rsvd */
} BF;
uint32_t WORDVAL;
} RESERVED_ADDR_1AH;
/* 0x26c: */
union {
struct {
uint32_t RESERVED_BIT_15_0 : 16; /* [15:0] r/o */
uint32_t RESERVED_31_16 : 16; /* [31:16] rsvd */
} BF;
uint32_t WORDVAL;
} RESERVED_ADDR_1BH;
/* 0x270: */
union {
struct {
uint32_t RESERVED_BIT_15_0 : 16; /* [15:0] r/o */
uint32_t RESERVED_31_16 : 16; /* [31:16] rsvd */
} BF;
uint32_t WORDVAL;
} RESERVED_ADDR_1CH;
/* 0x274: */
union {
struct {
uint32_t RESERVED_BIT_15_0 : 16; /* [15:0] r/o */
uint32_t RESERVED_31_16 : 16; /* [31:16] rsvd */
} BF;
uint32_t WORDVAL;
} RESERVED_ADDR_1DH;
/* 0x278: */
union {
struct {
uint32_t ICID1 : 8; /* [7:0] r/o */
uint32_t ICID0 : 8; /* [15:8] r/o */
uint32_t RESERVED_31_16 : 16; /* [31:16] rsvd */
} BF;
uint32_t WORDVAL;
} INTERNAL_CID;
/* 0x27c: */
union {
struct {
uint32_t PHY_MULTIPORT : 1; /* [0] r/o */
uint32_t ND : 2; /* [2:1] r/o */
uint32_t DIG_REGULATOR : 1; /* [3] r/o */
uint32_t PHY_ULPI : 1; /* [4] r/o */
uint32_t PHY_HSIC : 1; /* [5] r/o */
uint32_t PHY_CHG_DTC : 1; /* [6] r/o */
uint32_t PHY_OTG : 1; /* [7] r/o */
uint32_t ICID2 : 8; /* [15:8] r/o */
uint32_t RESERVED_31_16 : 16; /* [31:16] rsvd */
} BF;
uint32_t WORDVAL;
} USB2_ICID_REG1;
};
typedef volatile struct usbc_reg usbc_reg_t;
#ifdef USBC_IMPL
BEGIN_REG_SECTION(usbc_registers)
usbc_reg_t USBCREG;
END_REG_SECTION(usbc_registers)
#else
extern usbc_reg_t USBCREG;
#endif
#endif /* _USBC_REG_H */
| 28,022 |
7,863 | <gh_stars>1000+
/* vi:set ts=8 sts=4 sw=4 ft=objc:
*
* VIM - Vi IMproved by <NAME>
* MacVim GUI port by <NAME>
*
* Do ":help uganda" in Vim to read copying and usage conditions.
* Do ":help credits" in Vim to see a list of people who contributed.
* See README.txt for an overview of the Vim source code.
*/
#import "MacVim.h"
#define MM_USE_ROW_CACHE 1
#if MM_USE_ROW_CACHE
typedef struct {
unsigned length; // length of row in unichars
int col; // last column accessed (in this row)
unsigned colOffset; // offset of 'col' from start of row (in unichars)
} MMRowCacheEntry;
#endif
@interface MMTextStorage : NSTextStorage {
NSTextStorage *backingStore;
int maxRows, maxColumns;
int actualRows, actualColumns;
NSAttributedString *emptyRowString;
NSFont *font;
NSFont *boldFont;
NSFont *italicFont;
NSFont *boldItalicFont;
NSFont *fontWide;
NSFont *boldFontWide;
NSFont *italicFontWide;
NSFont *boldItalicFontWide;
NSColor *defaultBackgroundColor;
NSColor *defaultForegroundColor;
NSSize cellSize;
float linespace;
float columnspace;
#if MM_USE_ROW_CACHE
MMRowCacheEntry *rowCache;
#endif
BOOL characterEqualsColumn;
}
- (NSString *)string;
- (NSDictionary *)attributesAtIndex:(NSUInteger)index
effectiveRange:(NSRangePointer)aRange;
- (void)replaceCharactersInRange:(NSRange)aRange
withString:(NSString *)aString;
- (void)setAttributes:(NSDictionary *)attributes range:(NSRange)aRange;
- (int)maxRows;
- (int)maxColumns;
- (int)actualRows;
- (int)actualColumns;
- (float)linespace;
- (float)columnspace;
- (void)setLinespace:(float)newLinespace;
- (void)setColumnspace:(float)newColumnspace;
- (void)getMaxRows:(int*)rows columns:(int*)cols;
- (void)setMaxRows:(int)rows columns:(int)cols;
- (void)drawString:(NSString *)string atRow:(int)row column:(int)col
cells:(int)cells withFlags:(int)flags
foregroundColor:(NSColor *)fg backgroundColor:(NSColor *)bg
specialColor:(NSColor *)sp;
- (void)deleteLinesFromRow:(int)row lineCount:(int)count
scrollBottom:(int)bottom left:(int)left right:(int)right
color:(NSColor *)color;
- (void)insertLinesAtRow:(int)row lineCount:(int)count
scrollBottom:(int)bottom left:(int)left right:(int)right
color:(NSColor *)color;
- (void)clearBlockFromRow:(int)row1 column:(int)col1 toRow:(int)row2
column:(int)col2 color:(NSColor *)color;
- (void)clearAll;
- (void)setDefaultColorsBackground:(NSColor *)bgColor
foreground:(NSColor *)fgColor;
- (void)setFont:(NSFont *)newFont;
- (void)setWideFont:(NSFont *)newFont;
- (NSFont *)font;
- (NSFont *)fontWide;
- (NSColor *)defaultBackgroundColor;
- (NSColor *)defaultForegroundColor;
- (NSSize)size;
- (NSSize)cellSize;
- (NSRect)rectForRowsInRange:(NSRange)range;
- (NSRect)rectForColumnsInRange:(NSRange)range;
- (NSUInteger)characterIndexForRow:(int)row column:(int)col;
- (BOOL)resizeToFitSize:(NSSize)size;
- (NSSize)fitToSize:(NSSize)size;
- (NSSize)fitToSize:(NSSize)size rows:(int *)rows columns:(int *)columns;
- (NSRect)boundingRectForCharacterAtRow:(int)row column:(int)col;
#if MM_USE_ROW_CACHE
- (MMRowCacheEntry *)rowCache;
#endif
@end
| 1,736 |
772 | {
"key": "rotationSpeed",
"name": "rotationSpeed",
"category": "Sprites",
"syntax": "rotationSpeed"
} | 43 |
984 | // Copyright (C) Microsoft Corporation. All rights reserved.
#pragma once
#pragma region Desktop Family or OneCore Family
#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP | WINAPI_PARTITION_SYSTEM)
EXTERN_C_START
typedef enum _NET_PACKET_TX_CHECKSUM_ACTION
{
NetPacketTxChecksumActionPassthrough = 0,
NetPacketTxChecksumActionRequired = 2,
} NET_PACKET_TX_CHECKSUM_ACTION;
typedef enum _NET_PACKET_RX_CHECKSUM_EVALUATION
{
NetPacketRxChecksumEvaluationNotChecked = 0,
NetPacketRxChecksumEvaluationValid = 1,
NetPacketRxChecksumEvaluationInvalid = 2,
} NET_PACKET_RX_CHECKSUM_EVALUATION;
#pragma warning(push)
#pragma warning(default:4820) // warn if the compiler inserted padding
typedef struct _NET_PACKET_CHECKSUM
{
// One of NET_PACKET_TX_CHECKSUM_ACTION or NET_PACKET_RX_CHECKSUM_EVALUATION
UINT8
Layer2 : 2;
// One of NET_PACKET_TX_CHECKSUM_ACTION or NET_PACKET_RX_CHECKSUM_EVALUATION
UINT8
Layer3 : 2;
// One of NET_PACKET_TX_CHECKSUM_ACTION or NET_PACKET_RX_CHECKSUM_EVALUATION
UINT8
Layer4 : 2;
UINT8
Reserved : 2;
} NET_PACKET_CHECKSUM;
C_ASSERT(sizeof(NET_PACKET_CHECKSUM) == 1);
#pragma warning(pop)
EXTERN_C_END
#define NET_PACKET_EXTENSION_CHECKSUM_NAME L"ms_packet_checksum"
#define NET_PACKET_EXTENSION_CHECKSUM_VERSION_1 1U
#endif // WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP | WINAPI_PARTITION_SYSTEM)
#pragma endregion
| 638 |
375 | /*
* Copyright (C) 2014 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.aniruddhc.acemusic.player.AsyncTasks;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.jaudiotagger.audio.AudioFile;
import org.jaudiotagger.audio.AudioFileIO;
import org.jaudiotagger.audio.exceptions.CannotReadException;
import org.jaudiotagger.audio.exceptions.CannotWriteException;
import org.jaudiotagger.audio.exceptions.InvalidAudioFrameException;
import org.jaudiotagger.audio.exceptions.ReadOnlyFileException;
import org.jaudiotagger.tag.FieldKey;
import org.jaudiotagger.tag.Tag;
import org.jaudiotagger.tag.TagException;
import org.jaudiotagger.tag.images.Artwork;
import org.jaudiotagger.tag.images.ArtworkFactory;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Environment;
import android.widget.Toast;
import com.aniruddhc.acemusic.player.R;
import com.aniruddhc.acemusic.player.DBHelpers.DBAccessHelper;
import com.aniruddhc.acemusic.player.Services.AutoFetchAlbumArtService;
import com.aniruddhc.acemusic.player.Utils.Common;
/*********************************************************************
* This class is different from AsyncGetAlbumArtTask. It includes an
* additional search functionality that scans the ENTIRE library,
* checks for missing art, and then downloads them.
*********************************************************************/
public class AsyncAutoGetAlbumArtTask extends AsyncTask<String, String, Void> {
private Context mContext;
private Common mApp;
private Activity mActivity;
private SharedPreferences sharedPreferences;
private AsyncTask<String, String, Void> task;
private String artworkURL;
private Bitmap artworkBitmap;
private byte[] buffer;
private AudioFile audioFile;
private File file;
private DBAccessHelper dbHelper;
private ProgressDialog pd;
private int currentProgress = 0;
private boolean DIALOG_VISIBLE = true;
public static ArrayList<String> dataURIsList = new ArrayList<String>();
public static ArrayList<String> artistsList = new ArrayList<String>();
public static ArrayList<String> albumsList = new ArrayList<String>();
public AsyncAutoGetAlbumArtTask(Context context, Activity activity) {
mContext = context;
mApp = (Common) context.getApplicationContext();
mActivity = activity;
sharedPreferences = mContext.getSharedPreferences("com.aniruddhc.acemusic.player", Context.MODE_PRIVATE);
task = this;
dbHelper = new DBAccessHelper(mContext);
}
public void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(mActivity);
pd.setTitle(R.string.downloading_album_art);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setCancelable(false);
pd.setCanceledOnTouchOutside(false);
pd.setMessage(mContext.getResources().getString(R.string.scanning_for_missing_art));
pd.setButton(DialogInterface.BUTTON_NEGATIVE,
mContext.getResources().getString(R.string.cancel),
new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
task.cancel(true);
}
});
pd.show();
}
@Override
protected Void doInBackground(String... params) {
//First, we'll go through all the songs in the music library DB and get their attributes.
dbHelper = new DBAccessHelper(mContext);
String selection = DBAccessHelper.SONG_SOURCE + "<>" + "'GOOGLE_PLAY_MUSIC'";
String[] projection = { DBAccessHelper._ID,
DBAccessHelper.SONG_FILE_PATH,
DBAccessHelper.SONG_ALBUM,
DBAccessHelper.SONG_ARTIST,
DBAccessHelper.SONG_TITLE };
Cursor cursor = dbHelper.getWritableDatabase().query(DBAccessHelper.MUSIC_LIBRARY_TABLE,
projection,
selection,
null,
null,
null,
null);
if (cursor.getCount()!=0) {
cursor.moveToFirst();
dataURIsList.add(cursor.getString(1));
albumsList.add(cursor.getString(2));
artistsList.add(cursor.getString(3));
while(cursor.moveToNext()) {
dataURIsList.add(cursor.getString(1));
albumsList.add(cursor.getString(2));
artistsList.add(cursor.getString(3));
}
} else {
//The user doesn't have any music so let's get outta here.
return null;
}
pd.setMax(dataURIsList.size());
//Now that we have the attributes of the songs, we'll go through them each and check for missing covers.
for (int i=0; i < dataURIsList.size(); i++) {
try {
file = new File(dataURIsList.get(i));
} catch (Exception e) {
continue;
}
audioFile = null;
try {
audioFile = AudioFileIO.read(file);
} catch (CannotReadException e2) {
// TODO Auto-generated catch block
continue;
} catch (IOException e2) {
// TODO Auto-generated catch block
continue;
} catch (TagException e2) {
// TODO Auto-generated catch block
continue;
} catch (ReadOnlyFileException e2) {
// TODO Auto-generated catch block
continue;
} catch (InvalidAudioFrameException e2) {
// TODO Auto-generated catch block
continue;
}
Tag tag = audioFile.getTag();
//Set the destination directory for the xml file.
File SDCardRoot = Environment.getExternalStorageDirectory();
File xmlFile = new File(SDCardRoot,"albumArt.xml");
if (tag!=null) {
String title = tag.getFirst(FieldKey.TITLE);
String checkingMessage = mContext.getResources().getString(R.string.checking_if)
+ " "
+ title
+ " "
+ mContext.getResources().getString(R.string.has_album_art)
+ ".";
currentProgress = currentProgress + 1;
String[] checkingProgressParams = { checkingMessage, "" + currentProgress };
publishProgress(checkingProgressParams);
List<Artwork> artworkList = tag.getArtworkList();
if (artworkList.size()==0) {
//Since the file doesn't have any album artwork, we'll have to download it.
//Get the artist and album name of the file we're working with.
String artist = tag.getFirst(FieldKey.ARTIST);
String album = tag.getFirst(FieldKey.ALBUM);
//Update the progress dialog.
String message = mContext.getResources().getString(R.string.downloading_artwork_for) + " " + title;
String[] progressParams = { message, "" + currentProgress };
publishProgress(progressParams);
//Remove any unacceptable characters.
if (artist.contains("#")) {
artist = artist.replace("#", "");
}
if (artist.contains("$")) {
artist = artist.replace("$", "");
}
if (artist.contains("@")) {
artist = artist.replace("@", "");
}
if (album.contains("#")) {
album = album.replace("#", "");
}
if (album.contains("$")) {
album = album.replace("$", "");
}
if (album.contains("@")) {
album = album.replace("@", "");
}
//Replace any spaces in the artist and album fields with "%20".
if (artist.contains(" ")) {
artist = artist.replace(" ", "%20");
}
if (album.contains(" ")) {
album = album.replace(" ", "%20");
}
//Construct the url for the HTTP request.
URL url = null;
try {
url = new URL("http://itunes.apple.com/search?term=" + artist + "+" + album + "&entity=album");
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
continue;
}
String xml = null;
try {
//Create a new HTTP connection.
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
//Check if albumArt.xml already exists and delete it.
if (xmlFile.exists()) {
xmlFile.delete();
}
//Create the OuputStream that will be used to store the downloaded data into the file.
FileOutputStream fileOutput = new FileOutputStream(xmlFile);
//Create the InputStream that will read the data from the HTTP connection.
InputStream inputStream = urlConnection.getInputStream();
//Total size of target file.
int totalSize = urlConnection.getContentLength();
//Temp variable that stores the number of downloaded bytes.
int downloadedSize = 0;
//Create a buffer to store the downloaded bytes.
buffer = new byte[1024];
int bufferLength = 0;
//Now read through the buffer and write the contents to the file.
while((bufferLength = inputStream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
}
//Close the File Output Stream.
fileOutput.close();
} catch (MalformedURLException e) {
//TODO Auto-generated method stub
continue;
} catch (IOException e) {
// TODO Auto-generated method stub
continue;
}
//Load the XML file into a String variable for local use.
String xmlAsString = null;
try {
xmlAsString = FileUtils.readFileToString(xmlFile);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Extract the albumArt parameter from the XML file.
artworkURL = StringUtils.substringBetween(xmlAsString, "\"artworkUrl100\":\"", "\",");
if (artworkURL==null) {
//Check and see if a lower resolution image available.
artworkURL = StringUtils.substringBetween(xmlAsString, "\"artworkUrl60\":\"", "\",");
if (artworkURL==null) {
//Can't do anything about that here.
} else {
//Replace "100x100" with "600x600" to retrieve larger album art images.
artworkURL = artworkURL.replace("100x100", "600x600");
}
} else {
//Replace "100x100" with "600x600" to retrieve larger album art images.
artworkURL = artworkURL.replace("100x100", "600x600");
}
//If no URL has been found, there's no point in continuing.
if (artworkURL!=null) {
artworkBitmap = null;
artworkBitmap = mApp.getImageLoader().loadImageSync(artworkURL);
File artworkFile = new File(Environment.getExternalStorageDirectory() + "/artwork.jpg");
//Save the artwork.
try {
FileOutputStream out = new FileOutputStream(artworkFile);
artworkBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
Artwork artwork = null;
try {
artwork = ArtworkFactory.createArtworkFromFile(artworkFile);
} catch (IOException e) {
// TODO Auto-generated catch block
setArtworkAsFile(artworkFile, dataURIsList.get(i));
continue;
} catch (ArrayIndexOutOfBoundsException e) {
// TODO Auto-generated catch block
setArtworkAsFile(artworkFile, dataURIsList.get(i));
continue;
} catch (Exception e) {
e.printStackTrace();
setArtworkAsFile(artworkFile, dataURIsList.get(i));
continue;
} catch (Error e) {
e.printStackTrace();
setArtworkAsFile(artworkFile, dataURIsList.get(i));
continue;
}
if (artwork!=null) {
try {
//Remove the current artwork field and recreate it.
tag.deleteArtworkField();
tag.addField(artwork);
} catch (Exception e) {
// TODO Auto-generated catch block
setArtworkAsFile(artworkFile, dataURIsList.get(i));
continue;
} catch (Error e) {
e.printStackTrace();
setArtworkAsFile(artworkFile, dataURIsList.get(i));
continue;
}
try {
audioFile.commit();
} catch (CannotWriteException e) {
// TODO Auto-generated catch block
setArtworkAsFile(artworkFile, dataURIsList.get(i));
continue;
} catch (Error e) {
e.printStackTrace();
setArtworkAsFile(artworkFile, dataURIsList.get(i));
continue;
}
}
//Delete the temporary files that we stored during the fetching process.
if (artworkFile.exists()) {
artworkFile.delete();
}
if (xmlFile.exists()) {
xmlFile.delete();
}
//Set the files to null to help clean up memory.
artworkBitmap = null;
audioFile = null;
tag = null;
xmlFile = null;
artworkFile = null;
}
}
}
}
}
audioFile = null;
file = null;
//System.gc();
return null;
}
//Saves the artwork as a JPEG file in the song's parent folder.
public void setArtworkAsFile(File artworkFile, String songFilePath) {
File songFile = new File(songFilePath);
String songTitle = songFile.getName();
int lastDotSlash = songTitle.lastIndexOf(".");
String albumArtFileName = songTitle.substring(0, lastDotSlash);
if (songFile.exists()) {
int lastSlashIndex = songFilePath.lastIndexOf("/");
String folderPath = songFilePath.substring(0, lastSlashIndex);
File destFile = new File(folderPath + "/" + albumArtFileName + ".jpg");
try {
FileUtils.copyFile(artworkFile, destFile);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return;
}
//Update the album art tag in Jams' database.
ContentValues values = new ContentValues();
songFilePath = songFilePath.replace("'", "''");
String where = DBAccessHelper.SONG_FILE_PATH + "=" + "'" + songFilePath + "'";
values.put(DBAccessHelper.SONG_ALBUM_ART_PATH, folderPath + "/" + albumArtFileName + ".jpg");
dbHelper.getWritableDatabase().update(DBAccessHelper.MUSIC_LIBRARY_TABLE, values, where, null);
}
}
@Override
public void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
if (DIALOG_VISIBLE==true) {
pd.setProgress(Integer.parseInt(values[1]));
pd.setMessage(values[0]);
}
//Update the notification.
AutoFetchAlbumArtService.builder.setContentTitle(mContext.getResources().getString(R.string.downloading_missing_cover_art));
AutoFetchAlbumArtService.builder.setSmallIcon(R.drawable.notif_icon);
AutoFetchAlbumArtService.builder.setContentInfo(null);
AutoFetchAlbumArtService.builder.setContentText(null);
AutoFetchAlbumArtService.builder.setProgress(dataURIsList.size(), currentProgress, false);
AutoFetchAlbumArtService.notification = AutoFetchAlbumArtService.builder.build();
NotificationManager notifyManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
notifyManager.notify(AutoFetchAlbumArtService.NOTIFICATION_ID, AutoFetchAlbumArtService.notification);
}
@Override
protected void onPostExecute(Void arg0) {
Intent intent = new Intent(mContext, AutoFetchAlbumArtService.class);
mContext.stopService(intent);
if (pd.isShowing() && DIALOG_VISIBLE==true) {
pd.dismiss();
}
//Dismiss the notification.
AutoFetchAlbumArtService.builder.setTicker(mContext.getResources().getString(R.string.done_downloading_art));
AutoFetchAlbumArtService.builder.setContentTitle(mContext.getResources().getString(R.string.done_downloading_art));
AutoFetchAlbumArtService.builder.setSmallIcon(R.drawable.notif_icon);
AutoFetchAlbumArtService.builder.setContentInfo(null);
AutoFetchAlbumArtService.builder.setContentText(null);
AutoFetchAlbumArtService.builder.setProgress(0, 0, false);
AutoFetchAlbumArtService.notification = AutoFetchAlbumArtService.builder.build();
AutoFetchAlbumArtService.notification.flags = Notification.FLAG_AUTO_CANCEL;
NotificationManager notifyManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
notifyManager.notify(AutoFetchAlbumArtService.NOTIFICATION_ID, AutoFetchAlbumArtService.notification);
Toast.makeText(mContext, R.string.done_downloading_art, Toast.LENGTH_LONG).show();
//Rescan for album art.
//Seting the "RESCAN_ALBUM_ART" flag to true will force MainActivity to rescan the folders.
sharedPreferences.edit().putBoolean("RESCAN_ALBUM_ART", true).commit();
//Restart the app.
final Intent i = mActivity.getBaseContext()
.getPackageManager()
.getLaunchIntentForPackage(mActivity.getBaseContext().getPackageName());
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
mActivity.startActivity(i);
mActivity.finish();
}
}
| 8,773 |
770 | // Copyright (C) 2016 The Regents of the University of California (Regents).
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// * Neither the name of The Regents or University of California 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 HOLDERS 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.
//
// Please contact the author of this library if you have any questions.
// Author: <NAME> (<EMAIL>)
#ifndef THEIA_SFM_GPS_CONVERTER_H_
#define THEIA_SFM_GPS_CONVERTER_H_
#include <Eigen/Core>
namespace theia {
// This helper class contains static methods to convert between Geodetic
// coordinates (latitude, longitude, and altitude) and Earth-Center-Earth-Fixed
// (ECEF) coordinates. The method used is very fast, does not require special
// treatment at the poles or equator, and is extremely accurate. In tests by
// csweeney with randomly generated points, the maximum error of lat/lon is
// roughly 4e-16 and the maximum altitude error is roughly 3e-9 meters. These
// errors are smaller than the wavelength of visible light!!
//
// The original method was presenting in this paper:
// <NAME>. "Converting earth-Centered, Earth-Fixed Coordinates to Geodetic
// Coordinates," IEEE Transactions on Aerospace and Electronic Systems, Vol. 32,
// No. 1, January 1996, pp. 473-476.
class GPSConverter {
public:
GPSConverter() {}
// Converts ECEF coordinates to GPS latitude, longitude, and altitude. ECEF
// coordinates should be in meters. The returned latitude and longitude are in
// degrees, and the altitude will be in meters.
static Eigen::Vector3d ECEFToLLA(const Eigen::Vector3d& ecef);
// Converts GPS latitude, longitude, and altitude to ECEF coordinates. The
// latitude and longitude should be in degrees and the altitude in meters. The
// returned ECEF coordinates will be in meters.
static Eigen::Vector3d LLAToECEF(const Eigen::Vector3d& lla);
};
} // namespace theia
#endif // THEIA_SFM_GPS_CONVERTER_H_
| 962 |
1,174 | <reponame>lijunru-hub/esp-iot-solution<gh_stars>1000+
// Copyright 2015-2016 Espressif Systems (Shanghai) PTE 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.
#ifndef _BME280_H_
#define _BME280_H_
#include "driver/i2c.h"
#include "i2c_bus.h"
#define BME280_I2C_ADDRESS_DEFAULT (0x76) /*The device's I2C address is either 0x76 or 0x77.*/
#define BME280_DEFAULT_CHIPID (0x60)
#define WRITE_BIT I2C_MASTER_WRITE /*!< I2C master write */
#define READ_BIT I2C_MASTER_READ /*!< I2C master read */
#define ACK_CHECK_EN 0x1 /*!< I2C master will check ack from slave*/
#define ACK_CHECK_DIS 0x0 /*!< I2C master will not check ack from slave */
#define ACK_VAL 0x0 /*!< I2C ack value */
#define NACK_VAL 0x1 /*!< I2C nack value */
#define BME280_REGISTER_DIG_T1 0x88
#define BME280_REGISTER_DIG_T2 0x8A
#define BME280_REGISTER_DIG_T3 0x8C
#define BME280_REGISTER_DIG_P1 0x8E
#define BME280_REGISTER_DIG_P2 0x90
#define BME280_REGISTER_DIG_P3 0x92
#define BME280_REGISTER_DIG_P4 0x94
#define BME280_REGISTER_DIG_P5 0x96
#define BME280_REGISTER_DIG_P6 0x98
#define BME280_REGISTER_DIG_P7 0x9A
#define BME280_REGISTER_DIG_P8 0x9C
#define BME280_REGISTER_DIG_P9 0x9E
#define BME280_REGISTER_DIG_H1 0xA1
#define BME280_REGISTER_DIG_H2 0xE1
#define BME280_REGISTER_DIG_H3 0xE3
#define BME280_REGISTER_DIG_H4 0xE4
#define BME280_REGISTER_DIG_H5 0xE5
#define BME280_REGISTER_DIG_H6 0xE7
#define BME280_REGISTER_CHIPID 0xD0
#define BME280_REGISTER_VERSION 0xD1
#define BME280_REGISTER_SOFTRESET 0xE0
#define BME280_REGISTER_CAL26 0xE1 // R calibration stored in 0xE1-0xF0
#define BME280_REGISTER_CONTROLHUMID 0xF2
#define BME280_REGISTER_STATUS 0XF3
#define BME280_REGISTER_CONTROL 0xF4
#define BME280_REGISTER_CONFIG 0xF5
#define BME280_REGISTER_PRESSUREDATA 0xF7
#define BME280_REGISTER_TEMPDATA 0xFA
#define BME280_REGISTER_HUMIDDATA 0xFD
typedef struct {
uint16_t dig_t1;
int16_t dig_t2;
int16_t dig_t3;
uint16_t dig_p1;
int16_t dig_p2;
int16_t dig_p3;
int16_t dig_p4;
int16_t dig_p5;
int16_t dig_p6;
int16_t dig_p7;
int16_t dig_p8;
int16_t dig_p9;
uint8_t dig_h1;
int16_t dig_h2;
uint8_t dig_h3;
int16_t dig_h4;
int16_t dig_h5;
int8_t dig_h6;
} bme280_data_t;
typedef enum {
BME280_SAMPLING_NONE = 0b000,
BME280_SAMPLING_X1 = 0b001,
BME280_SAMPLING_X2 = 0b010,
BME280_SAMPLING_X4 = 0b011,
BME280_SAMPLING_X8 = 0b100,
BME280_SAMPLING_X16 = 0b101
} bme280_sensor_sampling;
typedef enum {
BME280_MODE_SLEEP = 0b00,
BME280_MODE_FORCED = 0b01,
BME280_MODE_NORMAL = 0b11
} bme280_sensor_mode;
typedef enum {
BME280_FILTER_OFF = 0b000,
BME280_FILTER_X2 = 0b001,
BME280_FILTER_X4 = 0b010,
BME280_FILTER_X8 = 0b011,
BME280_FILTER_X16 = 0b100
} bme280_sensor_filter;
// standby durations in ms
typedef enum {
BME280_STANDBY_MS_0_5 = 0b000,
BME280_STANDBY_MS_10 = 0b110,
BME280_STANDBY_MS_20 = 0b111,
BME280_STANDBY_MS_62_5 = 0b001,
BME280_STANDBY_MS_125 = 0b010,
BME280_STANDBY_MS_250 = 0b011,
BME280_STANDBY_MS_500 = 0b100,
BME280_STANDBY_MS_1000 = 0b101
} bme280_standby_duration;
// The config register
typedef struct config {
// inactive duration (standby time) in normal mode
// 000 = 0.5 ms
// 001 = 62.5 ms
// 010 = 125 ms
// 011 = 250 ms
// 100 = 500 ms
// 101 = 1000 ms
// 110 = 10 ms
// 111 = 20 ms
unsigned int t_sb : 3;
// filter settings
// 000 = filter off
// 001 = 2x filter
// 010 = 4x filter
// 011 = 8x filter
// 100 and above = 16x filter
unsigned int filter : 3;
// unused - don't set
unsigned int none : 1;
unsigned int spi3w_en : 1;
} bme280_config_t;
// The ctrl_meas register
typedef struct ctrl_meas {
// temperature oversampling
// 000 = skipped
// 001 = x1
// 010 = x2
// 011 = x4
// 100 = x8
// 101 and above = x16
unsigned int osrs_t : 3;
// pressure oversampling
// 000 = skipped
// 001 = x1
// 010 = x2
// 011 = x4
// 100 = x8
// 101 and above = x16
unsigned int osrs_p : 3;
// device mode
// 00 = sleep
// 01 or 10 = forced
// 11 = normal
unsigned int mode : 2;
} bme280_ctrl_meas_t;
// The ctrl_hum register
typedef struct ctrl_hum {
// unused - don't set
unsigned int none : 5;
// pressure oversampling
// 000 = skipped
// 001 = x1
// 010 = x2
// 011 = x4
// 100 = x8
// 101 and above = x16
unsigned int osrs_h : 3;
} bme280_ctrl_hum_t;
typedef struct {
i2c_bus_device_handle_t i2c_dev;
uint8_t dev_addr;
bme280_data_t data_t;
bme280_config_t config_t;
bme280_ctrl_meas_t ctrl_meas_t;
bme280_ctrl_hum_t ctrl_hum_t;
int32_t t_fine;
} bme280_dev_t;
typedef void *bme280_handle_t; /*handle of bme280*/
#ifdef __cplusplus
extern "C"
{
#endif
/**
* @brief Create bme280 handle_t
*
* @param object handle of I2C
* @param decice address
*
* @return
* - bme280_handle_t
*/
bme280_handle_t bme280_create(i2c_bus_handle_t bus, uint8_t dev_addr);
/**
* @brief delete bme280 handle_t
*
* @param point to object handle of bme280
* @param whether delete i2c bus
*
* @return
* - ESP_OK Success
* - ESP_FAIL Fail
*/
esp_err_t bme280_delete(bme280_handle_t *sensor);
/**
* @brief Get the value of BME280_REGISTER_CONFIG register
*
* @param sensor object handle of bme280
*
* @return
* - unsigned int: the value of BME280_REGISTER_CONFIG register
*/
unsigned int bme280_getconfig(bme280_handle_t sensor);
/**
* @brief Get the value of BME280_REGISTER_CONTROL measure register
*
* @param sensor object handle of bme280
*
* @return
* - unsigned int the value of BME280_REGISTER_CONTROL register
*/
unsigned int bme280_getctrl_meas(bme280_handle_t sensor);
/**
* @brief Get the value of BME280_REGISTER_CONTROLHUMID measure register
*
* @param sensor object handle of bme280
*
* @return
* - unsigned int the value of BME280_REGISTER_CONTROLHUMID register
*/
unsigned int bme280_getctrl_hum(bme280_handle_t sensor);
/**
* @brief return true if chip is busy reading cal data
*
* @param sensor object handle of bme280
*
* @return
* - true chip is busy
* - false chip is idle or wrong
*/
bool bme280_is_reading_calibration(bme280_handle_t sensor);
/**
* @brief Reads the factory-set coefficients
*
* @param sensor object handle of bme280
*
* @return
* - ESP_OK Success
* - ESP_FAIL Fail
*/
esp_err_t bme280_read_coefficients(bme280_handle_t sensor);
/**
* @brief setup sensor with given parameters / settings
*
* @param sensor object handle of bme280
* @param Sensor working mode
* @param the sample of temperature measure
* @param the sample of pressure measure
* @param the sample of humidity measure
* @param Sensor filter multiples
* @param standby duration of sensor
*
* @return
* - ESP_OK Success
* - ESP_FAIL Fail
*/
esp_err_t bme280_set_sampling(bme280_handle_t sensor, bme280_sensor_mode mode,
bme280_sensor_sampling tempsampling,
bme280_sensor_sampling presssampling,
bme280_sensor_sampling humsampling, bme280_sensor_filter filter,
bme280_standby_duration duration);
/**
* @brief init bme280 device
*
* @param sensor object handle of bme280
*
* @return
* - ESP_OK Success
* - ESP_FAIL Fail
*/
esp_err_t bme280_default_init(bme280_handle_t sensor);
/**
* @brief Take a new measurement (only possible in forced mode)
* If we are in forced mode, the BME sensor goes back to sleep after each
* measurement and we need to set it to forced mode once at this point, so
* it will take the next measurement and then return to sleep again.
* In normal mode simply does new measurements periodically.
*
* @param sensor object handle of bme280
*
* @return
* - ESP_OK Success
* - ESP_FAIL Fail
*/
esp_err_t bme280_take_forced_measurement(bme280_handle_t sensor);
/**
* @brief Returns the temperature from the sensor
*
* @param sensor object handle of bme280
* @param temperature pointer to temperature
* @return esp_err_t
*/
esp_err_t bme280_read_temperature(bme280_handle_t sensor, float *temperature);
/**
* @brief Returns the temperature from the sensor
*
* @param sensor object handle of bme280
* @param pressure pointer to pressure value
* @return esp_err_t
*/
esp_err_t bme280_read_pressure(bme280_handle_t sensor, float *pressure);
/**
* @brief Returns the humidity from the sensor
*
* @param sensor object handle of bme280
* @param humidity pointer to humidity value
* @return esp_err_t
*/
esp_err_t bme280_read_humidity(bme280_handle_t sensor, float *humidity);
/**
* @brief Calculates the altitude (in meters) from the specified atmospheric
* pressure (in hPa), and sea-level pressure (in hPa).
*
* @param sensor object handle of bme280
* @param seaLevel: Sea-level pressure in hPa
* @param altitude pointer to altitude value
* @return esp_err_t
*/
esp_err_t bme280_read_altitude(bme280_handle_t sensor, float seaLevel, float *altitude);
/**
* Calculates the pressure at sea level (in hPa) from the specified altitude
* (in meters), and atmospheric pressure (in hPa).
*
* @param sensor object handle of bme280
* @param altitude Altitude in meters
* @param atmospheric Atmospheric pressure in hPa
* @param pressure pointer to pressure value
* @return esp_err_t
*/
esp_err_t bme280_calculates_pressure(bme280_handle_t sensor, float altitude,
float atmospheric, float *pressure);
#ifdef __cplusplus
}
#endif
#endif
| 4,758 |
2,504 | <reponame>nefeithu/behaviac
// ---------------------------------------------------------------------
// THIS FILE IS AUTO-GENERATED BY BEHAVIAC DESIGNER, SO PLEASE DON'T MODIFY IT BY YOURSELF!
// ---------------------------------------------------------------------
#include "behaviac_generated_behaviors_7.h"
namespace behaviac
{
// Source file: node_test/selector_loop_ut_1
class Action_bt_node_test_selector_loop_ut_1_node5 : public Action
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Action_bt_node_test_selector_loop_ut_1_node5, Action);
Action_bt_node_test_selector_loop_ut_1_node5()
{
method_p0 = 0;
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
((AgentNodeTest*)pAgent)->_Execute_Method_<METHOD_TYPE_AgentNodeTest_setTestVar_0, void, int >(method_p0);
return BT_FAILURE;
}
int method_p0;
};
class Action_bt_node_test_selector_loop_ut_1_node6 : public Action
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Action_bt_node_test_selector_loop_ut_1_node6, Action);
Action_bt_node_test_selector_loop_ut_1_node6()
{
method_p0 = 1;
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
((AgentNodeTest*)pAgent)->_Execute_Method_<METHOD_TYPE_AgentNodeTest_setTestVar_0, void, int >(method_p0);
return BT_SUCCESS;
}
int method_p0;
};
bool bt_node_test_selector_loop_ut_1::Create(BehaviorTree* pBT)
{
pBT->SetClassNameString("BehaviorTree");
pBT->SetId((uint16_t)-1);
pBT->SetName("node_test/selector_loop_ut_1");
pBT->SetIsFSM(false);
#if !BEHAVIAC_RELEASE
pBT->SetAgentType("AgentNodeTest");
#endif
// children
{
SelectorLoop* node0 = BEHAVIAC_NEW SelectorLoop;
node0->SetClassNameString("SelectorLoop");
node0->SetId(0);
#if !BEHAVIAC_RELEASE
node0->SetAgentType("AgentNodeTest");
#endif
pBT->AddChild(node0);
{
WithPrecondition* node1 = BEHAVIAC_NEW WithPrecondition;
node1->SetClassNameString("WithPrecondition");
node1->SetId(1);
#if !BEHAVIAC_RELEASE
node1->SetAgentType("AgentNodeTest");
#endif
node0->AddChild(node1);
{
True* node4 = BEHAVIAC_NEW True;
node4->SetClassNameString("True");
node4->SetId(4);
#if !BEHAVIAC_RELEASE
node4->SetAgentType("AgentNodeTest");
#endif
node1->AddChild(node4);
node1->SetHasEvents(node1->HasEvents() | node4->HasEvents());
}
{
Action_bt_node_test_selector_loop_ut_1_node5* node5 = BEHAVIAC_NEW Action_bt_node_test_selector_loop_ut_1_node5;
node5->SetClassNameString("Action");
node5->SetId(5);
#if !BEHAVIAC_RELEASE
node5->SetAgentType("AgentNodeTest");
#endif
node1->AddChild(node5);
node1->SetHasEvents(node1->HasEvents() | node5->HasEvents());
}
node0->SetHasEvents(node0->HasEvents() | node1->HasEvents());
}
{
WithPrecondition* node2 = BEHAVIAC_NEW WithPrecondition;
node2->SetClassNameString("WithPrecondition");
node2->SetId(2);
#if !BEHAVIAC_RELEASE
node2->SetAgentType("AgentNodeTest");
#endif
node0->AddChild(node2);
{
True* node3 = BEHAVIAC_NEW True;
node3->SetClassNameString("True");
node3->SetId(3);
#if !BEHAVIAC_RELEASE
node3->SetAgentType("AgentNodeTest");
#endif
node2->AddChild(node3);
node2->SetHasEvents(node2->HasEvents() | node3->HasEvents());
}
{
Action_bt_node_test_selector_loop_ut_1_node6* node6 = BEHAVIAC_NEW Action_bt_node_test_selector_loop_ut_1_node6;
node6->SetClassNameString("Action");
node6->SetId(6);
#if !BEHAVIAC_RELEASE
node6->SetAgentType("AgentNodeTest");
#endif
node2->AddChild(node6);
node2->SetHasEvents(node2->HasEvents() | node6->HasEvents());
}
node0->SetHasEvents(node0->HasEvents() | node2->HasEvents());
}
pBT->SetHasEvents(pBT->HasEvents() | node0->HasEvents());
}
return true;
}
// Source file: node_test/selector_loop_ut_2
class Action_bt_node_test_selector_loop_ut_2_node5 : public Action
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Action_bt_node_test_selector_loop_ut_2_node5, Action);
Action_bt_node_test_selector_loop_ut_2_node5()
{
method_p0 = 0;
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
((AgentNodeTest*)pAgent)->_Execute_Method_<METHOD_TYPE_AgentNodeTest_setTestVar_0, void, int >(method_p0);
return BT_FAILURE;
}
int method_p0;
};
class Action_bt_node_test_selector_loop_ut_2_node6 : public Action
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Action_bt_node_test_selector_loop_ut_2_node6, Action);
Action_bt_node_test_selector_loop_ut_2_node6()
{
method_p0 = 1;
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
((AgentNodeTest*)pAgent)->_Execute_Method_<METHOD_TYPE_AgentNodeTest_setTestVar_0, void, int >(method_p0);
return BT_SUCCESS;
}
int method_p0;
};
bool bt_node_test_selector_loop_ut_2::Create(BehaviorTree* pBT)
{
pBT->SetClassNameString("BehaviorTree");
pBT->SetId((uint16_t)-1);
pBT->SetName("node_test/selector_loop_ut_2");
pBT->SetIsFSM(false);
#if !BEHAVIAC_RELEASE
pBT->SetAgentType("AgentNodeTest");
#endif
// children
{
SelectorLoop* node0 = BEHAVIAC_NEW SelectorLoop;
node0->SetClassNameString("SelectorLoop");
node0->SetId(0);
#if !BEHAVIAC_RELEASE
node0->SetAgentType("AgentNodeTest");
#endif
pBT->AddChild(node0);
{
WithPrecondition* node1 = BEHAVIAC_NEW WithPrecondition;
node1->SetClassNameString("WithPrecondition");
node1->SetId(1);
#if !BEHAVIAC_RELEASE
node1->SetAgentType("AgentNodeTest");
#endif
node0->AddChild(node1);
{
True* node4 = BEHAVIAC_NEW True;
node4->SetClassNameString("True");
node4->SetId(4);
#if !BEHAVIAC_RELEASE
node4->SetAgentType("AgentNodeTest");
#endif
node1->AddChild(node4);
node1->SetHasEvents(node1->HasEvents() | node4->HasEvents());
}
{
Action_bt_node_test_selector_loop_ut_2_node5* node5 = BEHAVIAC_NEW Action_bt_node_test_selector_loop_ut_2_node5;
node5->SetClassNameString("Action");
node5->SetId(5);
#if !BEHAVIAC_RELEASE
node5->SetAgentType("AgentNodeTest");
#endif
node1->AddChild(node5);
node1->SetHasEvents(node1->HasEvents() | node5->HasEvents());
}
node0->SetHasEvents(node0->HasEvents() | node1->HasEvents());
}
{
WithPrecondition* node2 = BEHAVIAC_NEW WithPrecondition;
node2->SetClassNameString("WithPrecondition");
node2->SetId(2);
#if !BEHAVIAC_RELEASE
node2->SetAgentType("AgentNodeTest");
#endif
node0->AddChild(node2);
{
False* node3 = BEHAVIAC_NEW False;
node3->SetClassNameString("False");
node3->SetId(3);
#if !BEHAVIAC_RELEASE
node3->SetAgentType("AgentNodeTest");
#endif
node2->AddChild(node3);
node2->SetHasEvents(node2->HasEvents() | node3->HasEvents());
}
{
Action_bt_node_test_selector_loop_ut_2_node6* node6 = BEHAVIAC_NEW Action_bt_node_test_selector_loop_ut_2_node6;
node6->SetClassNameString("Action");
node6->SetId(6);
#if !BEHAVIAC_RELEASE
node6->SetAgentType("AgentNodeTest");
#endif
node2->AddChild(node6);
node2->SetHasEvents(node2->HasEvents() | node6->HasEvents());
}
node0->SetHasEvents(node0->HasEvents() | node2->HasEvents());
}
pBT->SetHasEvents(pBT->HasEvents() | node0->HasEvents());
}
return true;
}
// Source file: node_test/selector_loop_ut_3
class Action_bt_node_test_selector_loop_ut_3_node5 : public Action
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Action_bt_node_test_selector_loop_ut_3_node5, Action);
Action_bt_node_test_selector_loop_ut_3_node5()
{
method_p0 = 0;
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
((AgentNodeTest*)pAgent)->_Execute_Method_<METHOD_TYPE_AgentNodeTest_setTestVar_0, void, int >(method_p0);
return BT_RUNNING;
}
int method_p0;
};
class Action_bt_node_test_selector_loop_ut_3_node6 : public Action
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Action_bt_node_test_selector_loop_ut_3_node6, Action);
Action_bt_node_test_selector_loop_ut_3_node6()
{
method_p0 = 1;
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
((AgentNodeTest*)pAgent)->_Execute_Method_<METHOD_TYPE_AgentNodeTest_setTestVar_0, void, int >(method_p0);
return BT_SUCCESS;
}
int method_p0;
};
bool bt_node_test_selector_loop_ut_3::Create(BehaviorTree* pBT)
{
pBT->SetClassNameString("BehaviorTree");
pBT->SetId((uint16_t)-1);
pBT->SetName("node_test/selector_loop_ut_3");
pBT->SetIsFSM(false);
#if !BEHAVIAC_RELEASE
pBT->SetAgentType("AgentNodeTest");
#endif
// children
{
SelectorLoop* node0 = BEHAVIAC_NEW SelectorLoop;
node0->SetClassNameString("SelectorLoop");
node0->SetId(0);
#if !BEHAVIAC_RELEASE
node0->SetAgentType("AgentNodeTest");
#endif
pBT->AddChild(node0);
{
WithPrecondition* node1 = BEHAVIAC_NEW WithPrecondition;
node1->SetClassNameString("WithPrecondition");
node1->SetId(1);
#if !BEHAVIAC_RELEASE
node1->SetAgentType("AgentNodeTest");
#endif
node0->AddChild(node1);
{
False* node4 = BEHAVIAC_NEW False;
node4->SetClassNameString("False");
node4->SetId(4);
#if !BEHAVIAC_RELEASE
node4->SetAgentType("AgentNodeTest");
#endif
node1->AddChild(node4);
node1->SetHasEvents(node1->HasEvents() | node4->HasEvents());
}
{
Action_bt_node_test_selector_loop_ut_3_node5* node5 = BEHAVIAC_NEW Action_bt_node_test_selector_loop_ut_3_node5;
node5->SetClassNameString("Action");
node5->SetId(5);
#if !BEHAVIAC_RELEASE
node5->SetAgentType("AgentNodeTest");
#endif
node1->AddChild(node5);
node1->SetHasEvents(node1->HasEvents() | node5->HasEvents());
}
node0->SetHasEvents(node0->HasEvents() | node1->HasEvents());
}
{
WithPrecondition* node2 = BEHAVIAC_NEW WithPrecondition;
node2->SetClassNameString("WithPrecondition");
node2->SetId(2);
#if !BEHAVIAC_RELEASE
node2->SetAgentType("AgentNodeTest");
#endif
node0->AddChild(node2);
{
False* node3 = BEHAVIAC_NEW False;
node3->SetClassNameString("False");
node3->SetId(3);
#if !BEHAVIAC_RELEASE
node3->SetAgentType("AgentNodeTest");
#endif
node2->AddChild(node3);
node2->SetHasEvents(node2->HasEvents() | node3->HasEvents());
}
{
Action_bt_node_test_selector_loop_ut_3_node6* node6 = BEHAVIAC_NEW Action_bt_node_test_selector_loop_ut_3_node6;
node6->SetClassNameString("Action");
node6->SetId(6);
#if !BEHAVIAC_RELEASE
node6->SetAgentType("AgentNodeTest");
#endif
node2->AddChild(node6);
node2->SetHasEvents(node2->HasEvents() | node6->HasEvents());
}
node0->SetHasEvents(node0->HasEvents() | node2->HasEvents());
}
pBT->SetHasEvents(pBT->HasEvents() | node0->HasEvents());
}
return true;
}
// Source file: node_test/selector_loop_ut_4
class Action_bt_node_test_selector_loop_ut_4_node5 : public Action
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Action_bt_node_test_selector_loop_ut_4_node5, Action);
Action_bt_node_test_selector_loop_ut_4_node5()
{
method_p0 = 0;
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
((AgentNodeTest*)pAgent)->_Execute_Method_<METHOD_TYPE_AgentNodeTest_setTestVar_1, void, int >(method_p0);
return BT_FAILURE;
}
int method_p0;
};
class Action_bt_node_test_selector_loop_ut_4_node6 : public Action
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Action_bt_node_test_selector_loop_ut_4_node6, Action);
Action_bt_node_test_selector_loop_ut_4_node6()
{
method_p0 = 1;
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
((AgentNodeTest*)pAgent)->_Execute_Method_<METHOD_TYPE_AgentNodeTest_setTestVar_0, void, int >(method_p0);
return BT_RUNNING;
}
int method_p0;
};
bool bt_node_test_selector_loop_ut_4::Create(BehaviorTree* pBT)
{
pBT->SetClassNameString("BehaviorTree");
pBT->SetId((uint16_t)-1);
pBT->SetName("node_test/selector_loop_ut_4");
pBT->SetIsFSM(false);
#if !BEHAVIAC_RELEASE
pBT->SetAgentType("AgentNodeTest");
#endif
// children
{
SelectorLoop* node0 = BEHAVIAC_NEW SelectorLoop;
node0->SetClassNameString("SelectorLoop");
node0->SetId(0);
#if !BEHAVIAC_RELEASE
node0->SetAgentType("AgentNodeTest");
#endif
pBT->AddChild(node0);
{
WithPrecondition* node1 = BEHAVIAC_NEW WithPrecondition;
node1->SetClassNameString("WithPrecondition");
node1->SetId(1);
#if !BEHAVIAC_RELEASE
node1->SetAgentType("AgentNodeTest");
#endif
node0->AddChild(node1);
{
True* node4 = BEHAVIAC_NEW True;
node4->SetClassNameString("True");
node4->SetId(4);
#if !BEHAVIAC_RELEASE
node4->SetAgentType("AgentNodeTest");
#endif
node1->AddChild(node4);
node1->SetHasEvents(node1->HasEvents() | node4->HasEvents());
}
{
Action_bt_node_test_selector_loop_ut_4_node5* node5 = BEHAVIAC_NEW Action_bt_node_test_selector_loop_ut_4_node5;
node5->SetClassNameString("Action");
node5->SetId(5);
#if !BEHAVIAC_RELEASE
node5->SetAgentType("AgentNodeTest");
#endif
node1->AddChild(node5);
node1->SetHasEvents(node1->HasEvents() | node5->HasEvents());
}
node0->SetHasEvents(node0->HasEvents() | node1->HasEvents());
}
{
WithPrecondition* node2 = BEHAVIAC_NEW WithPrecondition;
node2->SetClassNameString("WithPrecondition");
node2->SetId(2);
#if !BEHAVIAC_RELEASE
node2->SetAgentType("AgentNodeTest");
#endif
node0->AddChild(node2);
{
True* node3 = BEHAVIAC_NEW True;
node3->SetClassNameString("True");
node3->SetId(3);
#if !BEHAVIAC_RELEASE
node3->SetAgentType("AgentNodeTest");
#endif
node2->AddChild(node3);
node2->SetHasEvents(node2->HasEvents() | node3->HasEvents());
}
{
Action_bt_node_test_selector_loop_ut_4_node6* node6 = BEHAVIAC_NEW Action_bt_node_test_selector_loop_ut_4_node6;
node6->SetClassNameString("Action");
node6->SetId(6);
#if !BEHAVIAC_RELEASE
node6->SetAgentType("AgentNodeTest");
#endif
node2->AddChild(node6);
node2->SetHasEvents(node2->HasEvents() | node6->HasEvents());
}
node0->SetHasEvents(node0->HasEvents() | node2->HasEvents());
}
pBT->SetHasEvents(pBT->HasEvents() | node0->HasEvents());
}
return true;
}
// Source file: node_test/selector_loop_ut_5
class Action_bt_node_test_selector_loop_ut_5_node5 : public Action
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Action_bt_node_test_selector_loop_ut_5_node5, Action);
Action_bt_node_test_selector_loop_ut_5_node5()
{
method_p0 = 0;
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
((AgentNodeTest*)pAgent)->_Execute_Method_<METHOD_TYPE_AgentNodeTest_setTestVar_0, void, int >(method_p0);
return BT_RUNNING;
}
int method_p0;
};
class Action_bt_node_test_selector_loop_ut_5_node6 : public Action
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Action_bt_node_test_selector_loop_ut_5_node6, Action);
Action_bt_node_test_selector_loop_ut_5_node6()
{
method_p0 = (char*)("node_test/reference_sub_1");
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
behaviac::EBTStatus result = ((AgentNodeTest*)pAgent)->_Execute_Method_<METHOD_TYPE_AgentNodeTest_switchRef, behaviac::EBTStatus, behaviac::string& >(method_p0);
return result;
}
behaviac::string method_p0;
};
class Action_bt_node_test_selector_loop_ut_5_node9 : public Action
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Action_bt_node_test_selector_loop_ut_5_node9, Action);
Action_bt_node_test_selector_loop_ut_5_node9()
{
method_p0 = 1;
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
((AgentNodeTest*)pAgent)->_Execute_Method_<METHOD_TYPE_AgentNodeTest_setTestVar_0, void, int >(method_p0);
return BT_SUCCESS;
}
int method_p0;
};
bool bt_node_test_selector_loop_ut_5::Create(BehaviorTree* pBT)
{
pBT->SetClassNameString("BehaviorTree");
pBT->SetId((uint16_t)-1);
pBT->SetName("node_test/selector_loop_ut_5");
pBT->SetIsFSM(false);
#if !BEHAVIAC_RELEASE
pBT->SetAgentType("AgentNodeTest");
#endif
// children
{
SelectorLoop* node0 = BEHAVIAC_NEW SelectorLoop;
node0->SetClassNameString("SelectorLoop");
node0->SetId(0);
#if !BEHAVIAC_RELEASE
node0->SetAgentType("AgentNodeTest");
#endif
pBT->AddChild(node0);
{
WithPrecondition* node1 = BEHAVIAC_NEW WithPrecondition;
node1->SetClassNameString("WithPrecondition");
node1->SetId(1);
#if !BEHAVIAC_RELEASE
node1->SetAgentType("AgentNodeTest");
#endif
node0->AddChild(node1);
{
False* node4 = BEHAVIAC_NEW False;
node4->SetClassNameString("False");
node4->SetId(4);
#if !BEHAVIAC_RELEASE
node4->SetAgentType("AgentNodeTest");
#endif
node1->AddChild(node4);
node1->SetHasEvents(node1->HasEvents() | node4->HasEvents());
}
{
Action_bt_node_test_selector_loop_ut_5_node5* node5 = BEHAVIAC_NEW Action_bt_node_test_selector_loop_ut_5_node5;
node5->SetClassNameString("Action");
node5->SetId(5);
#if !BEHAVIAC_RELEASE
node5->SetAgentType("AgentNodeTest");
#endif
node1->AddChild(node5);
node1->SetHasEvents(node1->HasEvents() | node5->HasEvents());
}
node0->SetHasEvents(node0->HasEvents() | node1->HasEvents());
}
{
WithPrecondition* node2 = BEHAVIAC_NEW WithPrecondition;
node2->SetClassNameString("WithPrecondition");
node2->SetId(2);
#if !BEHAVIAC_RELEASE
node2->SetAgentType("AgentNodeTest");
#endif
node0->AddChild(node2);
{
True* node3 = BEHAVIAC_NEW True;
node3->SetClassNameString("True");
node3->SetId(3);
#if !BEHAVIAC_RELEASE
node3->SetAgentType("AgentNodeTest");
#endif
node2->AddChild(node3);
node2->SetHasEvents(node2->HasEvents() | node3->HasEvents());
}
{
Action_bt_node_test_selector_loop_ut_5_node6* node6 = BEHAVIAC_NEW Action_bt_node_test_selector_loop_ut_5_node6;
node6->SetClassNameString("Action");
node6->SetId(6);
#if !BEHAVIAC_RELEASE
node6->SetAgentType("AgentNodeTest");
#endif
node2->AddChild(node6);
node2->SetHasEvents(node2->HasEvents() | node6->HasEvents());
}
node0->SetHasEvents(node0->HasEvents() | node2->HasEvents());
}
{
WithPrecondition* node7 = BEHAVIAC_NEW WithPrecondition;
node7->SetClassNameString("WithPrecondition");
node7->SetId(7);
#if !BEHAVIAC_RELEASE
node7->SetAgentType("AgentNodeTest");
#endif
node0->AddChild(node7);
{
True* node8 = BEHAVIAC_NEW True;
node8->SetClassNameString("True");
node8->SetId(8);
#if !BEHAVIAC_RELEASE
node8->SetAgentType("AgentNodeTest");
#endif
node7->AddChild(node8);
node7->SetHasEvents(node7->HasEvents() | node8->HasEvents());
}
{
Action_bt_node_test_selector_loop_ut_5_node9* node9 = BEHAVIAC_NEW Action_bt_node_test_selector_loop_ut_5_node9;
node9->SetClassNameString("Action");
node9->SetId(9);
#if !BEHAVIAC_RELEASE
node9->SetAgentType("AgentNodeTest");
#endif
node7->AddChild(node9);
node7->SetHasEvents(node7->HasEvents() | node9->HasEvents());
}
node0->SetHasEvents(node0->HasEvents() | node7->HasEvents());
}
pBT->SetHasEvents(pBT->HasEvents() | node0->HasEvents());
}
return true;
}
// Source file: node_test/selector_loop_ut_6
class DecoratorLoop_bt_node_test_selector_loop_ut_6_node9 : public DecoratorLoop
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(DecoratorLoop_bt_node_test_selector_loop_ut_6_node9, DecoratorLoop);
DecoratorLoop_bt_node_test_selector_loop_ut_6_node9()
{
m_bDecorateWhenChildEnds = false;
m_bDoneWithinFrame = false;
}
protected:
virtual int GetCount(Agent* pAgent) const
{
BEHAVIAC_UNUSED_VAR(pAgent);
return 10;
}
};
class Condition_bt_node_test_selector_loop_ut_6_node4 : public Condition
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Condition_bt_node_test_selector_loop_ut_6_node4, Condition);
Condition_bt_node_test_selector_loop_ut_6_node4()
{
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
bool opl = ((AgentNodeTest*)pAgent)->_Execute_Method_<METHOD_TYPE_AgentNodeTest_CanSeeEnemy, bool >();
bool opr = true;
bool op = PrivateDetails::Equal(opl, opr);
return op ? BT_SUCCESS : BT_FAILURE;
}
};
class Action_bt_node_test_selector_loop_ut_6_node5 : public Action
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Action_bt_node_test_selector_loop_ut_6_node5, Action);
Action_bt_node_test_selector_loop_ut_6_node5()
{
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
behaviac::EBTStatus result = ((AgentNodeTest*)pAgent)->_Execute_Method_<METHOD_TYPE_AgentNodeTest_Move, behaviac::EBTStatus >();
return result;
}
};
class Precondition_bt_node_test_selector_loop_ut_6_attach7 : public Precondition
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Precondition_bt_node_test_selector_loop_ut_6_attach7, Precondition);
Precondition_bt_node_test_selector_loop_ut_6_attach7()
{
this->SetPhase(Precondition::E_UPDATE);
this->SetIsAnd(true);
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
EBTStatus result = BT_SUCCESS;
int opr2 = 1;
((AgentNodeTest*)pAgent)->_Get_Property_<PROPERTY_TYPE_AgentNodeTest_testVar_0, int >() = opr2;
return result;
}
};
class Action_bt_node_test_selector_loop_ut_6_node6 : public Action
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Action_bt_node_test_selector_loop_ut_6_node6, Action);
Action_bt_node_test_selector_loop_ut_6_node6()
{
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
behaviac::EBTStatus result = ((AgentNodeTest*)pAgent)->_Execute_Method_<METHOD_TYPE_AgentNodeTest_MoveToTarget, behaviac::EBTStatus >();
return result;
}
};
class Precondition_bt_node_test_selector_loop_ut_6_attach8 : public Precondition
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Precondition_bt_node_test_selector_loop_ut_6_attach8, Precondition);
Precondition_bt_node_test_selector_loop_ut_6_attach8()
{
this->SetPhase(Precondition::E_UPDATE);
this->SetIsAnd(true);
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
EBTStatus result = BT_SUCCESS;
int opr2 = 2;
((AgentNodeTest*)pAgent)->_Get_Property_<PROPERTY_TYPE_AgentNodeTest_testVar_0, int >() = opr2;
return result;
}
};
bool bt_node_test_selector_loop_ut_6::Create(BehaviorTree* pBT)
{
pBT->SetClassNameString("BehaviorTree");
pBT->SetId((uint16_t)-1);
pBT->SetName("node_test/selector_loop_ut_6");
pBT->SetIsFSM(false);
#if !BEHAVIAC_RELEASE
pBT->SetAgentType("AgentNodeTest");
#endif
// children
{
DecoratorLoop_bt_node_test_selector_loop_ut_6_node9* node9 = BEHAVIAC_NEW DecoratorLoop_bt_node_test_selector_loop_ut_6_node9;
node9->SetClassNameString("DecoratorLoop");
node9->SetId(9);
#if !BEHAVIAC_RELEASE
node9->SetAgentType("AgentNodeTest");
#endif
pBT->AddChild(node9);
{
SelectorLoop* node0 = BEHAVIAC_NEW SelectorLoop;
node0->SetClassNameString("SelectorLoop");
node0->SetId(0);
#if !BEHAVIAC_RELEASE
node0->SetAgentType("AgentNodeTest");
#endif
node9->AddChild(node0);
{
WithPrecondition* node1 = BEHAVIAC_NEW WithPrecondition;
node1->SetClassNameString("WithPrecondition");
node1->SetId(1);
#if !BEHAVIAC_RELEASE
node1->SetAgentType("AgentNodeTest");
#endif
node0->AddChild(node1);
{
Condition_bt_node_test_selector_loop_ut_6_node4* node4 = BEHAVIAC_NEW Condition_bt_node_test_selector_loop_ut_6_node4;
node4->SetClassNameString("Condition");
node4->SetId(4);
#if !BEHAVIAC_RELEASE
node4->SetAgentType("AgentNodeTest");
#endif
node1->AddChild(node4);
node1->SetHasEvents(node1->HasEvents() | node4->HasEvents());
}
{
Action_bt_node_test_selector_loop_ut_6_node5* node5 = BEHAVIAC_NEW Action_bt_node_test_selector_loop_ut_6_node5;
node5->SetClassNameString("Action");
node5->SetId(5);
#if !BEHAVIAC_RELEASE
node5->SetAgentType("AgentNodeTest");
#endif
// attachments
{
Precondition_bt_node_test_selector_loop_ut_6_attach7* attach7 = BEHAVIAC_NEW Precondition_bt_node_test_selector_loop_ut_6_attach7;
attach7->SetClassNameString("Precondition");
attach7->SetId(7);
#if !BEHAVIAC_RELEASE
attach7->SetAgentType("AgentNodeTest");
#endif
node5->Attach(attach7, true, false, false);
node5->SetHasEvents(node5->HasEvents() | (Event::DynamicCast(attach7) != 0));
}
node1->AddChild(node5);
node1->SetHasEvents(node1->HasEvents() | node5->HasEvents());
}
node0->SetHasEvents(node0->HasEvents() | node1->HasEvents());
}
{
WithPrecondition* node2 = BEHAVIAC_NEW WithPrecondition;
node2->SetClassNameString("WithPrecondition");
node2->SetId(2);
#if !BEHAVIAC_RELEASE
node2->SetAgentType("AgentNodeTest");
#endif
node0->AddChild(node2);
{
True* node3 = BEHAVIAC_NEW True;
node3->SetClassNameString("True");
node3->SetId(3);
#if !BEHAVIAC_RELEASE
node3->SetAgentType("AgentNodeTest");
#endif
node2->AddChild(node3);
node2->SetHasEvents(node2->HasEvents() | node3->HasEvents());
}
{
Action_bt_node_test_selector_loop_ut_6_node6* node6 = BEHAVIAC_NEW Action_bt_node_test_selector_loop_ut_6_node6;
node6->SetClassNameString("Action");
node6->SetId(6);
#if !BEHAVIAC_RELEASE
node6->SetAgentType("AgentNodeTest");
#endif
// attachments
{
Precondition_bt_node_test_selector_loop_ut_6_attach8* attach8 = BEHAVIAC_NEW Precondition_bt_node_test_selector_loop_ut_6_attach8;
attach8->SetClassNameString("Precondition");
attach8->SetId(8);
#if !BEHAVIAC_RELEASE
attach8->SetAgentType("AgentNodeTest");
#endif
node6->Attach(attach8, true, false, false);
node6->SetHasEvents(node6->HasEvents() | (Event::DynamicCast(attach8) != 0));
}
node2->AddChild(node6);
node2->SetHasEvents(node2->HasEvents() | node6->HasEvents());
}
node0->SetHasEvents(node0->HasEvents() | node2->HasEvents());
}
node9->SetHasEvents(node9->HasEvents() | node0->HasEvents());
}
pBT->SetHasEvents(pBT->HasEvents() | node9->HasEvents());
}
return true;
}
// Source file: node_test/selector_loop_ut_7
class Action_bt_node_test_selector_loop_ut_7_node16 : public Action
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Action_bt_node_test_selector_loop_ut_7_node16, Action);
Action_bt_node_test_selector_loop_ut_7_node16()
{
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
((AgentNodeTest*)pAgent)->_Execute_Method_<METHOD_TYPE_AgentNodeTest_SelectTarget, void >();
return BT_SUCCESS;
}
};
class Assignment_bt_node_test_selector_loop_ut_7_node21 : public Assignment
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Assignment_bt_node_test_selector_loop_ut_7_node21, Assignment);
Assignment_bt_node_test_selector_loop_ut_7_node21()
{
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
EBTStatus result = BT_SUCCESS;
int opr = 0;
((AgentNodeTest*)pAgent)->_Get_Property_<PROPERTY_TYPE_AgentNodeTest_testVar_1, int >() = opr;
return result;
}
};
class DecoratorLoop_bt_node_test_selector_loop_ut_7_node9 : public DecoratorLoop
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(DecoratorLoop_bt_node_test_selector_loop_ut_7_node9, DecoratorLoop);
DecoratorLoop_bt_node_test_selector_loop_ut_7_node9()
{
m_bDecorateWhenChildEnds = false;
m_bDoneWithinFrame = false;
}
protected:
virtual int GetCount(Agent* pAgent) const
{
BEHAVIAC_UNUSED_VAR(pAgent);
return -1;
}
};
class Precondition_bt_node_test_selector_loop_ut_7_attach14 : public Precondition
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Precondition_bt_node_test_selector_loop_ut_7_attach14, Precondition);
Precondition_bt_node_test_selector_loop_ut_7_attach14()
{
this->SetPhase(Precondition::E_BOTH);
this->SetIsAnd(true);
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
EBTStatus result = BT_SUCCESS;
bool opl = ((AgentNodeTest*)pAgent)->_Execute_Method_<METHOD_TYPE_AgentNodeTest_IsTargetValid, bool >();
bool opr2 = true;
bool op = PrivateDetails::Equal(opl, opr2);
if (!op)
result = BT_FAILURE;
return result;
}
};
class Precondition_bt_node_test_selector_loop_ut_7_attach17 : public Precondition
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Precondition_bt_node_test_selector_loop_ut_7_attach17, Precondition);
Precondition_bt_node_test_selector_loop_ut_7_attach17()
{
this->SetPhase(Precondition::E_UPDATE);
this->SetIsAnd(true);
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
EBTStatus result = BT_SUCCESS;
int opr1 = ((AgentNodeTest*)pAgent)->_Get_Property_<PROPERTY_TYPE_AgentNodeTest_testVar_1, int >();
int opr2 = 1;
((AgentNodeTest*)pAgent)->_Get_Property_<PROPERTY_TYPE_AgentNodeTest_testVar_1, int >() = (int)(opr1 + opr2);
return result;
}
};
class Effector_bt_node_test_selector_loop_ut_7_attach18 : public Effector
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Effector_bt_node_test_selector_loop_ut_7_attach18, Effector);
Effector_bt_node_test_selector_loop_ut_7_attach18()
{
this->SetPhase(Effector::E_SUCCESS);
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
EBTStatus result = BT_SUCCESS;
int opr2 = 0;
((AgentNodeTest*)pAgent)->_Get_Property_<PROPERTY_TYPE_AgentNodeTest_testVar_1, int >() = opr2;
return result;
}
};
class Condition_bt_node_test_selector_loop_ut_7_node4 : public Condition
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Condition_bt_node_test_selector_loop_ut_7_node4, Condition);
Condition_bt_node_test_selector_loop_ut_7_node4()
{
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
bool opl = ((AgentNodeTest*)pAgent)->_Execute_Method_<METHOD_TYPE_AgentNodeTest_CanSeeEnemy, bool >();
bool opr = true;
bool op = PrivateDetails::Equal(opl, opr);
return op ? BT_SUCCESS : BT_FAILURE;
}
};
class Action_bt_node_test_selector_loop_ut_7_node5 : public Action
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Action_bt_node_test_selector_loop_ut_7_node5, Action);
Action_bt_node_test_selector_loop_ut_7_node5()
{
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
behaviac::EBTStatus result = ((AgentNodeTest*)pAgent)->_Execute_Method_<METHOD_TYPE_AgentNodeTest_Move, behaviac::EBTStatus >();
return result;
}
};
class Precondition_bt_node_test_selector_loop_ut_7_attach7 : public Precondition
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Precondition_bt_node_test_selector_loop_ut_7_attach7, Precondition);
Precondition_bt_node_test_selector_loop_ut_7_attach7()
{
this->SetPhase(Precondition::E_UPDATE);
this->SetIsAnd(true);
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
EBTStatus result = BT_SUCCESS;
int opr2 = 1;
((AgentNodeTest*)pAgent)->_Get_Property_<PROPERTY_TYPE_AgentNodeTest_testVar_0, int >() = opr2;
return result;
}
};
class Action_bt_node_test_selector_loop_ut_7_node6 : public Action
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Action_bt_node_test_selector_loop_ut_7_node6, Action);
Action_bt_node_test_selector_loop_ut_7_node6()
{
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
behaviac::EBTStatus result = ((AgentNodeTest*)pAgent)->_Execute_Method_<METHOD_TYPE_AgentNodeTest_MoveToTarget, behaviac::EBTStatus >();
return result;
}
};
class Precondition_bt_node_test_selector_loop_ut_7_attach8 : public Precondition
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Precondition_bt_node_test_selector_loop_ut_7_attach8, Precondition);
Precondition_bt_node_test_selector_loop_ut_7_attach8()
{
this->SetPhase(Precondition::E_UPDATE);
this->SetIsAnd(true);
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
EBTStatus result = BT_SUCCESS;
int opr2 = 2;
((AgentNodeTest*)pAgent)->_Get_Property_<PROPERTY_TYPE_AgentNodeTest_testVar_0, int >() = opr2;
return result;
}
};
class Precondition_bt_node_test_selector_loop_ut_7_attach19 : public Precondition
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Precondition_bt_node_test_selector_loop_ut_7_attach19, Precondition);
Precondition_bt_node_test_selector_loop_ut_7_attach19()
{
this->SetPhase(Precondition::E_ENTER);
this->SetIsAnd(true);
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
EBTStatus result = BT_SUCCESS;
int opr2 = 1;
((AgentNodeTest*)pAgent)->_Get_Property_<PROPERTY_TYPE_AgentNodeTest_testVar_1, int >() = opr2;
return result;
}
};
class Action_bt_node_test_selector_loop_ut_7_node12 : public Action
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Action_bt_node_test_selector_loop_ut_7_node12, Action);
Action_bt_node_test_selector_loop_ut_7_node12()
{
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
((AgentNodeTest*)pAgent)->_Execute_Method_<METHOD_TYPE_AgentNodeTest_Stop, void >();
return BT_SUCCESS;
}
};
class Precondition_bt_node_test_selector_loop_ut_7_attach20 : public Precondition
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Precondition_bt_node_test_selector_loop_ut_7_attach20, Precondition);
Precondition_bt_node_test_selector_loop_ut_7_attach20()
{
this->SetPhase(Precondition::E_ENTER);
this->SetIsAnd(true);
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
EBTStatus result = BT_SUCCESS;
int opr1 = ((AgentNodeTest*)pAgent)->_Get_Property_<PROPERTY_TYPE_AgentNodeTest_testVar_1, int >();
int opr2 = 1;
((AgentNodeTest*)pAgent)->_Get_Property_<PROPERTY_TYPE_AgentNodeTest_testVar_1, int >() = (int)(opr1 + opr2);
return result;
}
};
class Action_bt_node_test_selector_loop_ut_7_node13 : public Action
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Action_bt_node_test_selector_loop_ut_7_node13, Action);
Action_bt_node_test_selector_loop_ut_7_node13()
{
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
((AgentNodeTest*)pAgent)->_Execute_Method_<METHOD_TYPE_AgentNodeTest_SelectTarget, void >();
return BT_SUCCESS;
}
};
class Precondition_bt_node_test_selector_loop_ut_7_attach22 : public Precondition
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Precondition_bt_node_test_selector_loop_ut_7_attach22, Precondition);
Precondition_bt_node_test_selector_loop_ut_7_attach22()
{
this->SetPhase(Precondition::E_ENTER);
this->SetIsAnd(true);
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
EBTStatus result = BT_SUCCESS;
int opr1 = ((AgentNodeTest*)pAgent)->_Get_Property_<PROPERTY_TYPE_AgentNodeTest_testVar_1, int >();
int opr2 = 1;
((AgentNodeTest*)pAgent)->_Get_Property_<PROPERTY_TYPE_AgentNodeTest_testVar_1, int >() = (int)(opr1 + opr2);
return result;
}
};
bool bt_node_test_selector_loop_ut_7::Create(BehaviorTree* pBT)
{
pBT->SetClassNameString("BehaviorTree");
pBT->SetId((uint16_t)-1);
pBT->SetName("node_test/selector_loop_ut_7");
pBT->SetIsFSM(false);
#if !BEHAVIAC_RELEASE
pBT->SetAgentType("AgentNodeTest");
#endif
// children
{
Sequence* node15 = BEHAVIAC_NEW Sequence;
node15->SetClassNameString("Sequence");
node15->SetId(15);
#if !BEHAVIAC_RELEASE
node15->SetAgentType("AgentNodeTest");
#endif
pBT->AddChild(node15);
{
Action_bt_node_test_selector_loop_ut_7_node16* node16 = BEHAVIAC_NEW Action_bt_node_test_selector_loop_ut_7_node16;
node16->SetClassNameString("Action");
node16->SetId(16);
#if !BEHAVIAC_RELEASE
node16->SetAgentType("AgentNodeTest");
#endif
node15->AddChild(node16);
node15->SetHasEvents(node15->HasEvents() | node16->HasEvents());
}
{
Assignment_bt_node_test_selector_loop_ut_7_node21* node21 = BEHAVIAC_NEW Assignment_bt_node_test_selector_loop_ut_7_node21;
node21->SetClassNameString("Assignment");
node21->SetId(21);
#if !BEHAVIAC_RELEASE
node21->SetAgentType("AgentNodeTest");
#endif
node15->AddChild(node21);
node15->SetHasEvents(node15->HasEvents() | node21->HasEvents());
}
{
Selector* node10 = BEHAVIAC_NEW Selector;
node10->SetClassNameString("Selector");
node10->SetId(10);
#if !BEHAVIAC_RELEASE
node10->SetAgentType("AgentNodeTest");
#endif
node15->AddChild(node10);
{
DecoratorLoop_bt_node_test_selector_loop_ut_7_node9* node9 = BEHAVIAC_NEW DecoratorLoop_bt_node_test_selector_loop_ut_7_node9;
node9->SetClassNameString("DecoratorLoop");
node9->SetId(9);
#if !BEHAVIAC_RELEASE
node9->SetAgentType("AgentNodeTest");
#endif
// attachments
{
Precondition_bt_node_test_selector_loop_ut_7_attach14* attach14 = BEHAVIAC_NEW Precondition_bt_node_test_selector_loop_ut_7_attach14;
attach14->SetClassNameString("Precondition");
attach14->SetId(14);
#if !BEHAVIAC_RELEASE
attach14->SetAgentType("AgentNodeTest");
#endif
node9->Attach(attach14, true, false, false);
node9->SetHasEvents(node9->HasEvents() | (Event::DynamicCast(attach14) != 0));
}
{
Precondition_bt_node_test_selector_loop_ut_7_attach17* attach17 = BEHAVIAC_NEW Precondition_bt_node_test_selector_loop_ut_7_attach17;
attach17->SetClassNameString("Precondition");
attach17->SetId(17);
#if !BEHAVIAC_RELEASE
attach17->SetAgentType("AgentNodeTest");
#endif
node9->Attach(attach17, true, false, false);
node9->SetHasEvents(node9->HasEvents() | (Event::DynamicCast(attach17) != 0));
}
{
Effector_bt_node_test_selector_loop_ut_7_attach18* attach18 = BEHAVIAC_NEW Effector_bt_node_test_selector_loop_ut_7_attach18;
attach18->SetClassNameString("Effector");
attach18->SetId(18);
#if !BEHAVIAC_RELEASE
attach18->SetAgentType("AgentNodeTest");
#endif
node9->Attach(attach18, false, true, false);
node9->SetHasEvents(node9->HasEvents() | (Event::DynamicCast(attach18) != 0));
}
node10->AddChild(node9);
{
SelectorLoop* node0 = BEHAVIAC_NEW SelectorLoop;
node0->SetClassNameString("SelectorLoop");
node0->SetId(0);
#if !BEHAVIAC_RELEASE
node0->SetAgentType("AgentNodeTest");
#endif
node9->AddChild(node0);
{
WithPrecondition* node1 = BEHAVIAC_NEW WithPrecondition;
node1->SetClassNameString("WithPrecondition");
node1->SetId(1);
#if !BEHAVIAC_RELEASE
node1->SetAgentType("AgentNodeTest");
#endif
node0->AddChild(node1);
{
Condition_bt_node_test_selector_loop_ut_7_node4* node4 = BEHAVIAC_NEW Condition_bt_node_test_selector_loop_ut_7_node4;
node4->SetClassNameString("Condition");
node4->SetId(4);
#if !BEHAVIAC_RELEASE
node4->SetAgentType("AgentNodeTest");
#endif
node1->AddChild(node4);
node1->SetHasEvents(node1->HasEvents() | node4->HasEvents());
}
{
Action_bt_node_test_selector_loop_ut_7_node5* node5 = BEHAVIAC_NEW Action_bt_node_test_selector_loop_ut_7_node5;
node5->SetClassNameString("Action");
node5->SetId(5);
#if !BEHAVIAC_RELEASE
node5->SetAgentType("AgentNodeTest");
#endif
// attachments
{
Precondition_bt_node_test_selector_loop_ut_7_attach7* attach7 = BEHAVIAC_NEW Precondition_bt_node_test_selector_loop_ut_7_attach7;
attach7->SetClassNameString("Precondition");
attach7->SetId(7);
#if !BEHAVIAC_RELEASE
attach7->SetAgentType("AgentNodeTest");
#endif
node5->Attach(attach7, true, false, false);
node5->SetHasEvents(node5->HasEvents() | (Event::DynamicCast(attach7) != 0));
}
node1->AddChild(node5);
node1->SetHasEvents(node1->HasEvents() | node5->HasEvents());
}
node0->SetHasEvents(node0->HasEvents() | node1->HasEvents());
}
{
WithPrecondition* node2 = BEHAVIAC_NEW WithPrecondition;
node2->SetClassNameString("WithPrecondition");
node2->SetId(2);
#if !BEHAVIAC_RELEASE
node2->SetAgentType("AgentNodeTest");
#endif
node0->AddChild(node2);
{
True* node3 = BEHAVIAC_NEW True;
node3->SetClassNameString("True");
node3->SetId(3);
#if !BEHAVIAC_RELEASE
node3->SetAgentType("AgentNodeTest");
#endif
node2->AddChild(node3);
node2->SetHasEvents(node2->HasEvents() | node3->HasEvents());
}
{
Action_bt_node_test_selector_loop_ut_7_node6* node6 = BEHAVIAC_NEW Action_bt_node_test_selector_loop_ut_7_node6;
node6->SetClassNameString("Action");
node6->SetId(6);
#if !BEHAVIAC_RELEASE
node6->SetAgentType("AgentNodeTest");
#endif
// attachments
{
Precondition_bt_node_test_selector_loop_ut_7_attach8* attach8 = BEHAVIAC_NEW Precondition_bt_node_test_selector_loop_ut_7_attach8;
attach8->SetClassNameString("Precondition");
attach8->SetId(8);
#if !BEHAVIAC_RELEASE
attach8->SetAgentType("AgentNodeTest");
#endif
node6->Attach(attach8, true, false, false);
node6->SetHasEvents(node6->HasEvents() | (Event::DynamicCast(attach8) != 0));
}
node2->AddChild(node6);
node2->SetHasEvents(node2->HasEvents() | node6->HasEvents());
}
node0->SetHasEvents(node0->HasEvents() | node2->HasEvents());
}
node9->SetHasEvents(node9->HasEvents() | node0->HasEvents());
}
node10->SetHasEvents(node10->HasEvents() | node9->HasEvents());
}
{
Sequence* node11 = BEHAVIAC_NEW Sequence;
node11->SetClassNameString("Sequence");
node11->SetId(11);
#if !BEHAVIAC_RELEASE
node11->SetAgentType("AgentNodeTest");
#endif
// attachments
{
Precondition_bt_node_test_selector_loop_ut_7_attach19* attach19 = BEHAVIAC_NEW Precondition_bt_node_test_selector_loop_ut_7_attach19;
attach19->SetClassNameString("Precondition");
attach19->SetId(19);
#if !BEHAVIAC_RELEASE
attach19->SetAgentType("AgentNodeTest");
#endif
node11->Attach(attach19, true, false, false);
node11->SetHasEvents(node11->HasEvents() | (Event::DynamicCast(attach19) != 0));
}
node10->AddChild(node11);
{
Action_bt_node_test_selector_loop_ut_7_node12* node12 = BEHAVIAC_NEW Action_bt_node_test_selector_loop_ut_7_node12;
node12->SetClassNameString("Action");
node12->SetId(12);
#if !BEHAVIAC_RELEASE
node12->SetAgentType("AgentNodeTest");
#endif
// attachments
{
Precondition_bt_node_test_selector_loop_ut_7_attach20* attach20 = BEHAVIAC_NEW Precondition_bt_node_test_selector_loop_ut_7_attach20;
attach20->SetClassNameString("Precondition");
attach20->SetId(20);
#if !BEHAVIAC_RELEASE
attach20->SetAgentType("AgentNodeTest");
#endif
node12->Attach(attach20, true, false, false);
node12->SetHasEvents(node12->HasEvents() | (Event::DynamicCast(attach20) != 0));
}
node11->AddChild(node12);
node11->SetHasEvents(node11->HasEvents() | node12->HasEvents());
}
{
Action_bt_node_test_selector_loop_ut_7_node13* node13 = BEHAVIAC_NEW Action_bt_node_test_selector_loop_ut_7_node13;
node13->SetClassNameString("Action");
node13->SetId(13);
#if !BEHAVIAC_RELEASE
node13->SetAgentType("AgentNodeTest");
#endif
// attachments
{
Precondition_bt_node_test_selector_loop_ut_7_attach22* attach22 = BEHAVIAC_NEW Precondition_bt_node_test_selector_loop_ut_7_attach22;
attach22->SetClassNameString("Precondition");
attach22->SetId(22);
#if !BEHAVIAC_RELEASE
attach22->SetAgentType("AgentNodeTest");
#endif
node13->Attach(attach22, true, false, false);
node13->SetHasEvents(node13->HasEvents() | (Event::DynamicCast(attach22) != 0));
}
node11->AddChild(node13);
node11->SetHasEvents(node11->HasEvents() | node13->HasEvents());
}
node10->SetHasEvents(node10->HasEvents() | node11->HasEvents());
}
node15->SetHasEvents(node15->HasEvents() | node10->HasEvents());
}
pBT->SetHasEvents(pBT->HasEvents() | node15->HasEvents());
}
return true;
}
// Source file: node_test/selector_loop_ut_8
class Action_bt_node_test_selector_loop_ut_8_node16 : public Action
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Action_bt_node_test_selector_loop_ut_8_node16, Action);
Action_bt_node_test_selector_loop_ut_8_node16()
{
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
((AgentNodeTest*)pAgent)->_Execute_Method_<METHOD_TYPE_AgentNodeTest_SelectTarget, void >();
return BT_SUCCESS;
}
};
class Assignment_bt_node_test_selector_loop_ut_8_node21 : public Assignment
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Assignment_bt_node_test_selector_loop_ut_8_node21, Assignment);
Assignment_bt_node_test_selector_loop_ut_8_node21()
{
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
EBTStatus result = BT_SUCCESS;
int opr = 0;
((AgentNodeTest*)pAgent)->_Get_Property_<PROPERTY_TYPE_AgentNodeTest_testVar_1, int >() = opr;
return result;
}
};
class Precondition_bt_node_test_selector_loop_ut_8_attach24 : public Precondition
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Precondition_bt_node_test_selector_loop_ut_8_attach24, Precondition);
Precondition_bt_node_test_selector_loop_ut_8_attach24()
{
this->SetPhase(Precondition::E_BOTH);
this->SetIsAnd(true);
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
EBTStatus result = BT_SUCCESS;
int& opl = ((AgentNodeTest*)pAgent)->_Get_Property_<PROPERTY_TYPE_AgentNodeTest_testVar_0, int >();
int opr2 = 10;
bool op = PrivateDetails::GreaterEqual(opl, opr2);
if (!op)
result = BT_FAILURE;
return result;
}
};
class DecoratorLoop_bt_node_test_selector_loop_ut_8_node9 : public DecoratorLoop
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(DecoratorLoop_bt_node_test_selector_loop_ut_8_node9, DecoratorLoop);
DecoratorLoop_bt_node_test_selector_loop_ut_8_node9()
{
m_bDecorateWhenChildEnds = false;
m_bDoneWithinFrame = false;
}
protected:
virtual int GetCount(Agent* pAgent) const
{
BEHAVIAC_UNUSED_VAR(pAgent);
return -1;
}
};
class Precondition_bt_node_test_selector_loop_ut_8_attach14 : public Precondition
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Precondition_bt_node_test_selector_loop_ut_8_attach14, Precondition);
Precondition_bt_node_test_selector_loop_ut_8_attach14()
{
this->SetPhase(Precondition::E_BOTH);
this->SetIsAnd(true);
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
EBTStatus result = BT_SUCCESS;
bool opl = ((AgentNodeTest*)pAgent)->_Execute_Method_<METHOD_TYPE_AgentNodeTest_IsTargetValid, bool >();
bool opr2 = true;
bool op = PrivateDetails::Equal(opl, opr2);
if (!op)
result = BT_FAILURE;
return result;
}
};
class Precondition_bt_node_test_selector_loop_ut_8_attach17 : public Precondition
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Precondition_bt_node_test_selector_loop_ut_8_attach17, Precondition);
Precondition_bt_node_test_selector_loop_ut_8_attach17()
{
this->SetPhase(Precondition::E_UPDATE);
this->SetIsAnd(true);
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
EBTStatus result = BT_SUCCESS;
int opr1 = ((AgentNodeTest*)pAgent)->_Get_Property_<PROPERTY_TYPE_AgentNodeTest_testVar_1, int >();
int opr2 = 1;
((AgentNodeTest*)pAgent)->_Get_Property_<PROPERTY_TYPE_AgentNodeTest_testVar_1, int >() = (int)(opr1 + opr2);
return result;
}
};
class Effector_bt_node_test_selector_loop_ut_8_attach18 : public Effector
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Effector_bt_node_test_selector_loop_ut_8_attach18, Effector);
Effector_bt_node_test_selector_loop_ut_8_attach18()
{
this->SetPhase(Effector::E_SUCCESS);
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
EBTStatus result = BT_SUCCESS;
int opr2 = 0;
((AgentNodeTest*)pAgent)->_Get_Property_<PROPERTY_TYPE_AgentNodeTest_testVar_1, int >() = opr2;
return result;
}
};
class Condition_bt_node_test_selector_loop_ut_8_node4 : public Condition
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Condition_bt_node_test_selector_loop_ut_8_node4, Condition);
Condition_bt_node_test_selector_loop_ut_8_node4()
{
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
bool opl = ((AgentNodeTest*)pAgent)->_Execute_Method_<METHOD_TYPE_AgentNodeTest_CanSeeEnemy, bool >();
bool opr = true;
bool op = PrivateDetails::Equal(opl, opr);
return op ? BT_SUCCESS : BT_FAILURE;
}
};
class Action_bt_node_test_selector_loop_ut_8_node5 : public Action
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Action_bt_node_test_selector_loop_ut_8_node5, Action);
Action_bt_node_test_selector_loop_ut_8_node5()
{
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
behaviac::EBTStatus result = ((AgentNodeTest*)pAgent)->_Execute_Method_<METHOD_TYPE_AgentNodeTest_Move, behaviac::EBTStatus >();
return result;
}
};
class Precondition_bt_node_test_selector_loop_ut_8_attach7 : public Precondition
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Precondition_bt_node_test_selector_loop_ut_8_attach7, Precondition);
Precondition_bt_node_test_selector_loop_ut_8_attach7()
{
this->SetPhase(Precondition::E_UPDATE);
this->SetIsAnd(true);
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
EBTStatus result = BT_SUCCESS;
int opr2 = 1;
((AgentNodeTest*)pAgent)->_Get_Property_<PROPERTY_TYPE_AgentNodeTest_testVar_0, int >() = opr2;
return result;
}
};
class Action_bt_node_test_selector_loop_ut_8_node6 : public Action
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Action_bt_node_test_selector_loop_ut_8_node6, Action);
Action_bt_node_test_selector_loop_ut_8_node6()
{
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
behaviac::EBTStatus result = ((AgentNodeTest*)pAgent)->_Execute_Method_<METHOD_TYPE_AgentNodeTest_MoveToTarget, behaviac::EBTStatus >();
return result;
}
};
class Precondition_bt_node_test_selector_loop_ut_8_attach8 : public Precondition
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Precondition_bt_node_test_selector_loop_ut_8_attach8, Precondition);
Precondition_bt_node_test_selector_loop_ut_8_attach8()
{
this->SetPhase(Precondition::E_UPDATE);
this->SetIsAnd(true);
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
EBTStatus result = BT_SUCCESS;
int opr2 = 2;
((AgentNodeTest*)pAgent)->_Get_Property_<PROPERTY_TYPE_AgentNodeTest_testVar_0, int >() = opr2;
return result;
}
};
class Precondition_bt_node_test_selector_loop_ut_8_attach19 : public Precondition
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Precondition_bt_node_test_selector_loop_ut_8_attach19, Precondition);
Precondition_bt_node_test_selector_loop_ut_8_attach19()
{
this->SetPhase(Precondition::E_ENTER);
this->SetIsAnd(true);
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
EBTStatus result = BT_SUCCESS;
int opr2 = 1;
((AgentNodeTest*)pAgent)->_Get_Property_<PROPERTY_TYPE_AgentNodeTest_testVar_1, int >() = opr2;
return result;
}
};
class Action_bt_node_test_selector_loop_ut_8_node12 : public Action
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Action_bt_node_test_selector_loop_ut_8_node12, Action);
Action_bt_node_test_selector_loop_ut_8_node12()
{
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
((AgentNodeTest*)pAgent)->_Execute_Method_<METHOD_TYPE_AgentNodeTest_Stop, void >();
return BT_SUCCESS;
}
};
class Precondition_bt_node_test_selector_loop_ut_8_attach20 : public Precondition
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Precondition_bt_node_test_selector_loop_ut_8_attach20, Precondition);
Precondition_bt_node_test_selector_loop_ut_8_attach20()
{
this->SetPhase(Precondition::E_ENTER);
this->SetIsAnd(true);
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
EBTStatus result = BT_SUCCESS;
int opr1 = ((AgentNodeTest*)pAgent)->_Get_Property_<PROPERTY_TYPE_AgentNodeTest_testVar_1, int >();
int opr2 = 1;
((AgentNodeTest*)pAgent)->_Get_Property_<PROPERTY_TYPE_AgentNodeTest_testVar_1, int >() = (int)(opr1 + opr2);
return result;
}
};
class Action_bt_node_test_selector_loop_ut_8_node13 : public Action
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Action_bt_node_test_selector_loop_ut_8_node13, Action);
Action_bt_node_test_selector_loop_ut_8_node13()
{
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
((AgentNodeTest*)pAgent)->_Execute_Method_<METHOD_TYPE_AgentNodeTest_SelectTarget, void >();
return BT_SUCCESS;
}
};
class Precondition_bt_node_test_selector_loop_ut_8_attach22 : public Precondition
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Precondition_bt_node_test_selector_loop_ut_8_attach22, Precondition);
Precondition_bt_node_test_selector_loop_ut_8_attach22()
{
this->SetPhase(Precondition::E_ENTER);
this->SetIsAnd(true);
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
EBTStatus result = BT_SUCCESS;
int opr1 = ((AgentNodeTest*)pAgent)->_Get_Property_<PROPERTY_TYPE_AgentNodeTest_testVar_1, int >();
int opr2 = 1;
((AgentNodeTest*)pAgent)->_Get_Property_<PROPERTY_TYPE_AgentNodeTest_testVar_1, int >() = (int)(opr1 + opr2);
return result;
}
};
class Assignment_bt_node_test_selector_loop_ut_8_node25 : public Assignment
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Assignment_bt_node_test_selector_loop_ut_8_node25, Assignment);
Assignment_bt_node_test_selector_loop_ut_8_node25()
{
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
EBTStatus result = BT_SUCCESS;
int opr = 100;
((AgentNodeTest*)pAgent)->_Get_Property_<PROPERTY_TYPE_AgentNodeTest_testVar_1, int >() = opr;
return result;
}
};
class Compute_bt_node_test_selector_loop_ut_8_node26 : public Compute
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Compute_bt_node_test_selector_loop_ut_8_node26, Compute);
Compute_bt_node_test_selector_loop_ut_8_node26()
{
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
EBTStatus result = BT_SUCCESS;
int opr1 = ((AgentNodeTest*)pAgent)->_Get_Property_<PROPERTY_TYPE_AgentNodeTest_testVar_1, int >();
int opr2 = 1;
((AgentNodeTest*)pAgent)->_Get_Property_<PROPERTY_TYPE_AgentNodeTest_testVar_1, int >() = (int)(opr1 + opr2);
return result;
}
};
bool bt_node_test_selector_loop_ut_8::Create(BehaviorTree* pBT)
{
pBT->SetClassNameString("BehaviorTree");
pBT->SetId((uint16_t)-1);
pBT->SetName("node_test/selector_loop_ut_8");
pBT->SetIsFSM(false);
#if !BEHAVIAC_RELEASE
pBT->SetAgentType("AgentNodeTest");
#endif
// children
{
Sequence* node15 = BEHAVIAC_NEW Sequence;
node15->SetClassNameString("Sequence");
node15->SetId(15);
#if !BEHAVIAC_RELEASE
node15->SetAgentType("AgentNodeTest");
#endif
pBT->AddChild(node15);
{
Action_bt_node_test_selector_loop_ut_8_node16* node16 = BEHAVIAC_NEW Action_bt_node_test_selector_loop_ut_8_node16;
node16->SetClassNameString("Action");
node16->SetId(16);
#if !BEHAVIAC_RELEASE
node16->SetAgentType("AgentNodeTest");
#endif
node15->AddChild(node16);
node15->SetHasEvents(node15->HasEvents() | node16->HasEvents());
}
{
Assignment_bt_node_test_selector_loop_ut_8_node21* node21 = BEHAVIAC_NEW Assignment_bt_node_test_selector_loop_ut_8_node21;
node21->SetClassNameString("Assignment");
node21->SetId(21);
#if !BEHAVIAC_RELEASE
node21->SetAgentType("AgentNodeTest");
#endif
node15->AddChild(node21);
node15->SetHasEvents(node15->HasEvents() | node21->HasEvents());
}
{
Selector* node23 = BEHAVIAC_NEW Selector;
node23->SetClassNameString("Selector");
node23->SetId(23);
#if !BEHAVIAC_RELEASE
node23->SetAgentType("AgentNodeTest");
#endif
node15->AddChild(node23);
{
Selector* node10 = BEHAVIAC_NEW Selector;
node10->SetClassNameString("Selector");
node10->SetId(10);
#if !BEHAVIAC_RELEASE
node10->SetAgentType("AgentNodeTest");
#endif
// attachments
{
Precondition_bt_node_test_selector_loop_ut_8_attach24* attach24 = BEHAVIAC_NEW Precondition_bt_node_test_selector_loop_ut_8_attach24;
attach24->SetClassNameString("Precondition");
attach24->SetId(24);
#if !BEHAVIAC_RELEASE
attach24->SetAgentType("AgentNodeTest");
#endif
node10->Attach(attach24, true, false, false);
node10->SetHasEvents(node10->HasEvents() | (Event::DynamicCast(attach24) != 0));
}
node23->AddChild(node10);
{
DecoratorLoop_bt_node_test_selector_loop_ut_8_node9* node9 = BEHAVIAC_NEW DecoratorLoop_bt_node_test_selector_loop_ut_8_node9;
node9->SetClassNameString("DecoratorLoop");
node9->SetId(9);
#if !BEHAVIAC_RELEASE
node9->SetAgentType("AgentNodeTest");
#endif
// attachments
{
Precondition_bt_node_test_selector_loop_ut_8_attach14* attach14 = BEHAVIAC_NEW Precondition_bt_node_test_selector_loop_ut_8_attach14;
attach14->SetClassNameString("Precondition");
attach14->SetId(14);
#if !BEHAVIAC_RELEASE
attach14->SetAgentType("AgentNodeTest");
#endif
node9->Attach(attach14, true, false, false);
node9->SetHasEvents(node9->HasEvents() | (Event::DynamicCast(attach14) != 0));
}
{
Precondition_bt_node_test_selector_loop_ut_8_attach17* attach17 = BEHAVIAC_NEW Precondition_bt_node_test_selector_loop_ut_8_attach17;
attach17->SetClassNameString("Precondition");
attach17->SetId(17);
#if !BEHAVIAC_RELEASE
attach17->SetAgentType("AgentNodeTest");
#endif
node9->Attach(attach17, true, false, false);
node9->SetHasEvents(node9->HasEvents() | (Event::DynamicCast(attach17) != 0));
}
{
Effector_bt_node_test_selector_loop_ut_8_attach18* attach18 = BEHAVIAC_NEW Effector_bt_node_test_selector_loop_ut_8_attach18;
attach18->SetClassNameString("Effector");
attach18->SetId(18);
#if !BEHAVIAC_RELEASE
attach18->SetAgentType("AgentNodeTest");
#endif
node9->Attach(attach18, false, true, false);
node9->SetHasEvents(node9->HasEvents() | (Event::DynamicCast(attach18) != 0));
}
node10->AddChild(node9);
{
SelectorLoop* node0 = BEHAVIAC_NEW SelectorLoop;
node0->SetClassNameString("SelectorLoop");
node0->SetId(0);
#if !BEHAVIAC_RELEASE
node0->SetAgentType("AgentNodeTest");
#endif
node9->AddChild(node0);
{
WithPrecondition* node1 = BEHAVIAC_NEW WithPrecondition;
node1->SetClassNameString("WithPrecondition");
node1->SetId(1);
#if !BEHAVIAC_RELEASE
node1->SetAgentType("AgentNodeTest");
#endif
node0->AddChild(node1);
{
Condition_bt_node_test_selector_loop_ut_8_node4* node4 = BEHAVIAC_NEW Condition_bt_node_test_selector_loop_ut_8_node4;
node4->SetClassNameString("Condition");
node4->SetId(4);
#if !BEHAVIAC_RELEASE
node4->SetAgentType("AgentNodeTest");
#endif
node1->AddChild(node4);
node1->SetHasEvents(node1->HasEvents() | node4->HasEvents());
}
{
Action_bt_node_test_selector_loop_ut_8_node5* node5 = BEHAVIAC_NEW Action_bt_node_test_selector_loop_ut_8_node5;
node5->SetClassNameString("Action");
node5->SetId(5);
#if !BEHAVIAC_RELEASE
node5->SetAgentType("AgentNodeTest");
#endif
// attachments
{
Precondition_bt_node_test_selector_loop_ut_8_attach7* attach7 = BEHAVIAC_NEW Precondition_bt_node_test_selector_loop_ut_8_attach7;
attach7->SetClassNameString("Precondition");
attach7->SetId(7);
#if !BEHAVIAC_RELEASE
attach7->SetAgentType("AgentNodeTest");
#endif
node5->Attach(attach7, true, false, false);
node5->SetHasEvents(node5->HasEvents() | (Event::DynamicCast(attach7) != 0));
}
node1->AddChild(node5);
node1->SetHasEvents(node1->HasEvents() | node5->HasEvents());
}
node0->SetHasEvents(node0->HasEvents() | node1->HasEvents());
}
{
WithPrecondition* node2 = BEHAVIAC_NEW WithPrecondition;
node2->SetClassNameString("WithPrecondition");
node2->SetId(2);
#if !BEHAVIAC_RELEASE
node2->SetAgentType("AgentNodeTest");
#endif
node0->AddChild(node2);
{
True* node3 = BEHAVIAC_NEW True;
node3->SetClassNameString("True");
node3->SetId(3);
#if !BEHAVIAC_RELEASE
node3->SetAgentType("AgentNodeTest");
#endif
node2->AddChild(node3);
node2->SetHasEvents(node2->HasEvents() | node3->HasEvents());
}
{
Action_bt_node_test_selector_loop_ut_8_node6* node6 = BEHAVIAC_NEW Action_bt_node_test_selector_loop_ut_8_node6;
node6->SetClassNameString("Action");
node6->SetId(6);
#if !BEHAVIAC_RELEASE
node6->SetAgentType("AgentNodeTest");
#endif
// attachments
{
Precondition_bt_node_test_selector_loop_ut_8_attach8* attach8 = BEHAVIAC_NEW Precondition_bt_node_test_selector_loop_ut_8_attach8;
attach8->SetClassNameString("Precondition");
attach8->SetId(8);
#if !BEHAVIAC_RELEASE
attach8->SetAgentType("AgentNodeTest");
#endif
node6->Attach(attach8, true, false, false);
node6->SetHasEvents(node6->HasEvents() | (Event::DynamicCast(attach8) != 0));
}
node2->AddChild(node6);
node2->SetHasEvents(node2->HasEvents() | node6->HasEvents());
}
node0->SetHasEvents(node0->HasEvents() | node2->HasEvents());
}
node9->SetHasEvents(node9->HasEvents() | node0->HasEvents());
}
node10->SetHasEvents(node10->HasEvents() | node9->HasEvents());
}
{
Sequence* node11 = BEHAVIAC_NEW Sequence;
node11->SetClassNameString("Sequence");
node11->SetId(11);
#if !BEHAVIAC_RELEASE
node11->SetAgentType("AgentNodeTest");
#endif
// attachments
{
Precondition_bt_node_test_selector_loop_ut_8_attach19* attach19 = BEHAVIAC_NEW Precondition_bt_node_test_selector_loop_ut_8_attach19;
attach19->SetClassNameString("Precondition");
attach19->SetId(19);
#if !BEHAVIAC_RELEASE
attach19->SetAgentType("AgentNodeTest");
#endif
node11->Attach(attach19, true, false, false);
node11->SetHasEvents(node11->HasEvents() | (Event::DynamicCast(attach19) != 0));
}
node10->AddChild(node11);
{
Action_bt_node_test_selector_loop_ut_8_node12* node12 = BEHAVIAC_NEW Action_bt_node_test_selector_loop_ut_8_node12;
node12->SetClassNameString("Action");
node12->SetId(12);
#if !BEHAVIAC_RELEASE
node12->SetAgentType("AgentNodeTest");
#endif
// attachments
{
Precondition_bt_node_test_selector_loop_ut_8_attach20* attach20 = BEHAVIAC_NEW Precondition_bt_node_test_selector_loop_ut_8_attach20;
attach20->SetClassNameString("Precondition");
attach20->SetId(20);
#if !BEHAVIAC_RELEASE
attach20->SetAgentType("AgentNodeTest");
#endif
node12->Attach(attach20, true, false, false);
node12->SetHasEvents(node12->HasEvents() | (Event::DynamicCast(attach20) != 0));
}
node11->AddChild(node12);
node11->SetHasEvents(node11->HasEvents() | node12->HasEvents());
}
{
Action_bt_node_test_selector_loop_ut_8_node13* node13 = BEHAVIAC_NEW Action_bt_node_test_selector_loop_ut_8_node13;
node13->SetClassNameString("Action");
node13->SetId(13);
#if !BEHAVIAC_RELEASE
node13->SetAgentType("AgentNodeTest");
#endif
// attachments
{
Precondition_bt_node_test_selector_loop_ut_8_attach22* attach22 = BEHAVIAC_NEW Precondition_bt_node_test_selector_loop_ut_8_attach22;
attach22->SetClassNameString("Precondition");
attach22->SetId(22);
#if !BEHAVIAC_RELEASE
attach22->SetAgentType("AgentNodeTest");
#endif
node13->Attach(attach22, true, false, false);
node13->SetHasEvents(node13->HasEvents() | (Event::DynamicCast(attach22) != 0));
}
node11->AddChild(node13);
node11->SetHasEvents(node11->HasEvents() | node13->HasEvents());
}
node10->SetHasEvents(node10->HasEvents() | node11->HasEvents());
}
node23->SetHasEvents(node23->HasEvents() | node10->HasEvents());
}
{
Assignment_bt_node_test_selector_loop_ut_8_node25* node25 = BEHAVIAC_NEW Assignment_bt_node_test_selector_loop_ut_8_node25;
node25->SetClassNameString("Assignment");
node25->SetId(25);
#if !BEHAVIAC_RELEASE
node25->SetAgentType("AgentNodeTest");
#endif
node23->AddChild(node25);
node23->SetHasEvents(node23->HasEvents() | node25->HasEvents());
}
node15->SetHasEvents(node15->HasEvents() | node23->HasEvents());
}
{
Compute_bt_node_test_selector_loop_ut_8_node26* node26 = BEHAVIAC_NEW Compute_bt_node_test_selector_loop_ut_8_node26;
node26->SetClassNameString("Compute");
node26->SetId(26);
#if !BEHAVIAC_RELEASE
node26->SetAgentType("AgentNodeTest");
#endif
node15->AddChild(node26);
node15->SetHasEvents(node15->HasEvents() | node26->HasEvents());
}
pBT->SetHasEvents(pBT->HasEvents() | node15->HasEvents());
}
return true;
}
// Source file: node_test/selector_probability_ut_0
class SelectorProbability_bt_node_test_selector_probability_ut_0_node0 : public SelectorProbability
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(SelectorProbability_bt_node_test_selector_probability_ut_0_node0, SelectorProbability);
SelectorProbability_bt_node_test_selector_probability_ut_0_node0()
{
}
public:
void Initialize(const char* method)
{
this->m_method = AgentMeta::ParseMethod(method);
}
};
class DecoratorWeight_bt_node_test_selector_probability_ut_0_node3 : public DecoratorWeight
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(DecoratorWeight_bt_node_test_selector_probability_ut_0_node3, DecoratorWeight);
DecoratorWeight_bt_node_test_selector_probability_ut_0_node3()
{
m_bDecorateWhenChildEnds = false;
}
protected:
virtual int GetWeight(Agent* pAgent) const
{
BEHAVIAC_UNUSED_VAR(pAgent);
return 20;
}
};
class Action_bt_node_test_selector_probability_ut_0_node1 : public Action
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Action_bt_node_test_selector_probability_ut_0_node1, Action);
Action_bt_node_test_selector_probability_ut_0_node1()
{
method_p0 = 0;
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
((AgentNodeTest*)pAgent)->_Execute_Method_<METHOD_TYPE_AgentNodeTest_setTestVar_0, void, int >(method_p0);
return BT_SUCCESS;
}
int method_p0;
};
class DecoratorWeight_bt_node_test_selector_probability_ut_0_node5 : public DecoratorWeight
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(DecoratorWeight_bt_node_test_selector_probability_ut_0_node5, DecoratorWeight);
DecoratorWeight_bt_node_test_selector_probability_ut_0_node5()
{
m_bDecorateWhenChildEnds = false;
}
protected:
virtual int GetWeight(Agent* pAgent) const
{
BEHAVIAC_UNUSED_VAR(pAgent);
return 30;
}
};
class Action_bt_node_test_selector_probability_ut_0_node2 : public Action
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Action_bt_node_test_selector_probability_ut_0_node2, Action);
Action_bt_node_test_selector_probability_ut_0_node2()
{
method_p0 = 1;
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
((AgentNodeTest*)pAgent)->_Execute_Method_<METHOD_TYPE_AgentNodeTest_setTestVar_0, void, int >(method_p0);
return BT_SUCCESS;
}
int method_p0;
};
class DecoratorWeight_bt_node_test_selector_probability_ut_0_node6 : public DecoratorWeight
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(DecoratorWeight_bt_node_test_selector_probability_ut_0_node6, DecoratorWeight);
DecoratorWeight_bt_node_test_selector_probability_ut_0_node6()
{
m_bDecorateWhenChildEnds = false;
}
protected:
virtual int GetWeight(Agent* pAgent) const
{
BEHAVIAC_UNUSED_VAR(pAgent);
return 50;
}
};
class Action_bt_node_test_selector_probability_ut_0_node4 : public Action
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Action_bt_node_test_selector_probability_ut_0_node4, Action);
Action_bt_node_test_selector_probability_ut_0_node4()
{
method_p0 = 2;
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
((AgentNodeTest*)pAgent)->_Execute_Method_<METHOD_TYPE_AgentNodeTest_setTestVar_0, void, int >(method_p0);
return BT_SUCCESS;
}
int method_p0;
};
bool bt_node_test_selector_probability_ut_0::Create(BehaviorTree* pBT)
{
pBT->SetClassNameString("BehaviorTree");
pBT->SetId((uint16_t)-1);
pBT->SetName("node_test/selector_probability_ut_0");
pBT->SetIsFSM(false);
#if !BEHAVIAC_RELEASE
pBT->SetAgentType("AgentNodeTest");
#endif
// children
{
SelectorProbability_bt_node_test_selector_probability_ut_0_node0* node0 = BEHAVIAC_NEW SelectorProbability_bt_node_test_selector_probability_ut_0_node0;
node0->SetClassNameString("SelectorProbability");
node0->SetId(0);
#if !BEHAVIAC_RELEASE
node0->SetAgentType("AgentNodeTest");
#endif
pBT->AddChild(node0);
{
DecoratorWeight_bt_node_test_selector_probability_ut_0_node3* node3 = BEHAVIAC_NEW DecoratorWeight_bt_node_test_selector_probability_ut_0_node3;
node3->SetClassNameString("DecoratorWeight");
node3->SetId(3);
#if !BEHAVIAC_RELEASE
node3->SetAgentType("AgentNodeTest");
#endif
node0->AddChild(node3);
{
Action_bt_node_test_selector_probability_ut_0_node1* node1 = BEHAVIAC_NEW Action_bt_node_test_selector_probability_ut_0_node1;
node1->SetClassNameString("Action");
node1->SetId(1);
#if !BEHAVIAC_RELEASE
node1->SetAgentType("AgentNodeTest");
#endif
node3->AddChild(node1);
node3->SetHasEvents(node3->HasEvents() | node1->HasEvents());
}
node0->SetHasEvents(node0->HasEvents() | node3->HasEvents());
}
{
DecoratorWeight_bt_node_test_selector_probability_ut_0_node5* node5 = BEHAVIAC_NEW DecoratorWeight_bt_node_test_selector_probability_ut_0_node5;
node5->SetClassNameString("DecoratorWeight");
node5->SetId(5);
#if !BEHAVIAC_RELEASE
node5->SetAgentType("AgentNodeTest");
#endif
node0->AddChild(node5);
{
Action_bt_node_test_selector_probability_ut_0_node2* node2 = BEHAVIAC_NEW Action_bt_node_test_selector_probability_ut_0_node2;
node2->SetClassNameString("Action");
node2->SetId(2);
#if !BEHAVIAC_RELEASE
node2->SetAgentType("AgentNodeTest");
#endif
node5->AddChild(node2);
node5->SetHasEvents(node5->HasEvents() | node2->HasEvents());
}
node0->SetHasEvents(node0->HasEvents() | node5->HasEvents());
}
{
DecoratorWeight_bt_node_test_selector_probability_ut_0_node6* node6 = BEHAVIAC_NEW DecoratorWeight_bt_node_test_selector_probability_ut_0_node6;
node6->SetClassNameString("DecoratorWeight");
node6->SetId(6);
#if !BEHAVIAC_RELEASE
node6->SetAgentType("AgentNodeTest");
#endif
node0->AddChild(node6);
{
Action_bt_node_test_selector_probability_ut_0_node4* node4 = BEHAVIAC_NEW Action_bt_node_test_selector_probability_ut_0_node4;
node4->SetClassNameString("Action");
node4->SetId(4);
#if !BEHAVIAC_RELEASE
node4->SetAgentType("AgentNodeTest");
#endif
node6->AddChild(node4);
node6->SetHasEvents(node6->HasEvents() | node4->HasEvents());
}
node0->SetHasEvents(node0->HasEvents() | node6->HasEvents());
}
pBT->SetHasEvents(pBT->HasEvents() | node0->HasEvents());
}
return true;
}
// Source file: node_test/selector_probability_ut_1
class SelectorProbability_bt_node_test_selector_probability_ut_1_node0 : public SelectorProbability
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(SelectorProbability_bt_node_test_selector_probability_ut_1_node0, SelectorProbability);
SelectorProbability_bt_node_test_selector_probability_ut_1_node0()
{
}
public:
void Initialize(const char* method)
{
this->m_method = AgentMeta::ParseMethod(method);
}
};
class DecoratorWeight_bt_node_test_selector_probability_ut_1_node4 : public DecoratorWeight
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(DecoratorWeight_bt_node_test_selector_probability_ut_1_node4, DecoratorWeight);
DecoratorWeight_bt_node_test_selector_probability_ut_1_node4()
{
m_bDecorateWhenChildEnds = false;
}
protected:
virtual int GetWeight(Agent* pAgent) const
{
BEHAVIAC_UNUSED_VAR(pAgent);
return 0;
}
};
class Action_bt_node_test_selector_probability_ut_1_node1 : public Action
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Action_bt_node_test_selector_probability_ut_1_node1, Action);
Action_bt_node_test_selector_probability_ut_1_node1()
{
method_p0 = 0;
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
((AgentNodeTest*)pAgent)->_Execute_Method_<METHOD_TYPE_AgentNodeTest_setTestVar_0, void, int >(method_p0);
return BT_FAILURE;
}
int method_p0;
};
class DecoratorWeight_bt_node_test_selector_probability_ut_1_node5 : public DecoratorWeight
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(DecoratorWeight_bt_node_test_selector_probability_ut_1_node5, DecoratorWeight);
DecoratorWeight_bt_node_test_selector_probability_ut_1_node5()
{
m_bDecorateWhenChildEnds = false;
}
protected:
virtual int GetWeight(Agent* pAgent) const
{
BEHAVIAC_UNUSED_VAR(pAgent);
return 1;
}
};
class Action_bt_node_test_selector_probability_ut_1_node2 : public Action
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Action_bt_node_test_selector_probability_ut_1_node2, Action);
Action_bt_node_test_selector_probability_ut_1_node2()
{
method_p0 = 1;
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
((AgentNodeTest*)pAgent)->_Execute_Method_<METHOD_TYPE_AgentNodeTest_setTestVar_0, void, int >(method_p0);
return BT_FAILURE;
}
int method_p0;
};
class DecoratorWeight_bt_node_test_selector_probability_ut_1_node6 : public DecoratorWeight
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(DecoratorWeight_bt_node_test_selector_probability_ut_1_node6, DecoratorWeight);
DecoratorWeight_bt_node_test_selector_probability_ut_1_node6()
{
m_bDecorateWhenChildEnds = false;
}
protected:
virtual int GetWeight(Agent* pAgent) const
{
BEHAVIAC_UNUSED_VAR(pAgent);
return 1;
}
};
class Action_bt_node_test_selector_probability_ut_1_node3 : public Action
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Action_bt_node_test_selector_probability_ut_1_node3, Action);
Action_bt_node_test_selector_probability_ut_1_node3()
{
method_p0 = 2;
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
((AgentNodeTest*)pAgent)->_Execute_Method_<METHOD_TYPE_AgentNodeTest_setTestVar_0, void, int >(method_p0);
return BT_SUCCESS;
}
int method_p0;
};
bool bt_node_test_selector_probability_ut_1::Create(BehaviorTree* pBT)
{
pBT->SetClassNameString("BehaviorTree");
pBT->SetId((uint16_t)-1);
pBT->SetName("node_test/selector_probability_ut_1");
pBT->SetIsFSM(false);
#if !BEHAVIAC_RELEASE
pBT->SetAgentType("AgentNodeTest");
#endif
// children
{
SelectorProbability_bt_node_test_selector_probability_ut_1_node0* node0 = BEHAVIAC_NEW SelectorProbability_bt_node_test_selector_probability_ut_1_node0;
node0->SetClassNameString("SelectorProbability");
node0->SetId(0);
#if !BEHAVIAC_RELEASE
node0->SetAgentType("AgentNodeTest");
#endif
pBT->AddChild(node0);
{
DecoratorWeight_bt_node_test_selector_probability_ut_1_node4* node4 = BEHAVIAC_NEW DecoratorWeight_bt_node_test_selector_probability_ut_1_node4;
node4->SetClassNameString("DecoratorWeight");
node4->SetId(4);
#if !BEHAVIAC_RELEASE
node4->SetAgentType("AgentNodeTest");
#endif
node0->AddChild(node4);
{
Action_bt_node_test_selector_probability_ut_1_node1* node1 = BEHAVIAC_NEW Action_bt_node_test_selector_probability_ut_1_node1;
node1->SetClassNameString("Action");
node1->SetId(1);
#if !BEHAVIAC_RELEASE
node1->SetAgentType("AgentNodeTest");
#endif
node4->AddChild(node1);
node4->SetHasEvents(node4->HasEvents() | node1->HasEvents());
}
node0->SetHasEvents(node0->HasEvents() | node4->HasEvents());
}
{
DecoratorWeight_bt_node_test_selector_probability_ut_1_node5* node5 = BEHAVIAC_NEW DecoratorWeight_bt_node_test_selector_probability_ut_1_node5;
node5->SetClassNameString("DecoratorWeight");
node5->SetId(5);
#if !BEHAVIAC_RELEASE
node5->SetAgentType("AgentNodeTest");
#endif
node0->AddChild(node5);
{
Action_bt_node_test_selector_probability_ut_1_node2* node2 = BEHAVIAC_NEW Action_bt_node_test_selector_probability_ut_1_node2;
node2->SetClassNameString("Action");
node2->SetId(2);
#if !BEHAVIAC_RELEASE
node2->SetAgentType("AgentNodeTest");
#endif
node5->AddChild(node2);
node5->SetHasEvents(node5->HasEvents() | node2->HasEvents());
}
node0->SetHasEvents(node0->HasEvents() | node5->HasEvents());
}
{
DecoratorWeight_bt_node_test_selector_probability_ut_1_node6* node6 = BEHAVIAC_NEW DecoratorWeight_bt_node_test_selector_probability_ut_1_node6;
node6->SetClassNameString("DecoratorWeight");
node6->SetId(6);
#if !BEHAVIAC_RELEASE
node6->SetAgentType("AgentNodeTest");
#endif
node0->AddChild(node6);
{
Action_bt_node_test_selector_probability_ut_1_node3* node3 = BEHAVIAC_NEW Action_bt_node_test_selector_probability_ut_1_node3;
node3->SetClassNameString("Action");
node3->SetId(3);
#if !BEHAVIAC_RELEASE
node3->SetAgentType("AgentNodeTest");
#endif
node6->AddChild(node3);
node6->SetHasEvents(node6->HasEvents() | node3->HasEvents());
}
node0->SetHasEvents(node0->HasEvents() | node6->HasEvents());
}
pBT->SetHasEvents(pBT->HasEvents() | node0->HasEvents());
}
return true;
}
// Source file: node_test/selector_probability_ut_2
class SelectorProbability_bt_node_test_selector_probability_ut_2_node0 : public SelectorProbability
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(SelectorProbability_bt_node_test_selector_probability_ut_2_node0, SelectorProbability);
SelectorProbability_bt_node_test_selector_probability_ut_2_node0()
{
}
public:
void Initialize(const char* method)
{
this->m_method = AgentMeta::ParseMethod(method);
}
};
class DecoratorWeight_bt_node_test_selector_probability_ut_2_node4 : public DecoratorWeight
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(DecoratorWeight_bt_node_test_selector_probability_ut_2_node4, DecoratorWeight);
DecoratorWeight_bt_node_test_selector_probability_ut_2_node4()
{
m_bDecorateWhenChildEnds = false;
}
protected:
virtual int GetWeight(Agent* pAgent) const
{
BEHAVIAC_UNUSED_VAR(pAgent);
return 0;
}
};
class Action_bt_node_test_selector_probability_ut_2_node1 : public Action
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Action_bt_node_test_selector_probability_ut_2_node1, Action);
Action_bt_node_test_selector_probability_ut_2_node1()
{
method_p0 = 0;
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
((AgentNodeTest*)pAgent)->_Execute_Method_<METHOD_TYPE_AgentNodeTest_setTestVar_0, void, int >(method_p0);
return BT_SUCCESS;
}
int method_p0;
};
class DecoratorWeight_bt_node_test_selector_probability_ut_2_node5 : public DecoratorWeight
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(DecoratorWeight_bt_node_test_selector_probability_ut_2_node5, DecoratorWeight);
DecoratorWeight_bt_node_test_selector_probability_ut_2_node5()
{
m_bDecorateWhenChildEnds = false;
}
protected:
virtual int GetWeight(Agent* pAgent) const
{
BEHAVIAC_UNUSED_VAR(pAgent);
return 0;
}
};
class Action_bt_node_test_selector_probability_ut_2_node2 : public Action
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Action_bt_node_test_selector_probability_ut_2_node2, Action);
Action_bt_node_test_selector_probability_ut_2_node2()
{
method_p0 = 1;
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
((AgentNodeTest*)pAgent)->_Execute_Method_<METHOD_TYPE_AgentNodeTest_setTestVar_0, void, int >(method_p0);
return BT_SUCCESS;
}
int method_p0;
};
class DecoratorWeight_bt_node_test_selector_probability_ut_2_node6 : public DecoratorWeight
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(DecoratorWeight_bt_node_test_selector_probability_ut_2_node6, DecoratorWeight);
DecoratorWeight_bt_node_test_selector_probability_ut_2_node6()
{
m_bDecorateWhenChildEnds = false;
}
protected:
virtual int GetWeight(Agent* pAgent) const
{
BEHAVIAC_UNUSED_VAR(pAgent);
return 0;
}
};
class Action_bt_node_test_selector_probability_ut_2_node3 : public Action
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Action_bt_node_test_selector_probability_ut_2_node3, Action);
Action_bt_node_test_selector_probability_ut_2_node3()
{
method_p0 = 2;
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
((AgentNodeTest*)pAgent)->_Execute_Method_<METHOD_TYPE_AgentNodeTest_setTestVar_0, void, int >(method_p0);
return BT_SUCCESS;
}
int method_p0;
};
bool bt_node_test_selector_probability_ut_2::Create(BehaviorTree* pBT)
{
pBT->SetClassNameString("BehaviorTree");
pBT->SetId((uint16_t)-1);
pBT->SetName("node_test/selector_probability_ut_2");
pBT->SetIsFSM(false);
#if !BEHAVIAC_RELEASE
pBT->SetAgentType("AgentNodeTest");
#endif
// children
{
SelectorProbability_bt_node_test_selector_probability_ut_2_node0* node0 = BEHAVIAC_NEW SelectorProbability_bt_node_test_selector_probability_ut_2_node0;
node0->SetClassNameString("SelectorProbability");
node0->SetId(0);
#if !BEHAVIAC_RELEASE
node0->SetAgentType("AgentNodeTest");
#endif
pBT->AddChild(node0);
{
DecoratorWeight_bt_node_test_selector_probability_ut_2_node4* node4 = BEHAVIAC_NEW DecoratorWeight_bt_node_test_selector_probability_ut_2_node4;
node4->SetClassNameString("DecoratorWeight");
node4->SetId(4);
#if !BEHAVIAC_RELEASE
node4->SetAgentType("AgentNodeTest");
#endif
node0->AddChild(node4);
{
Action_bt_node_test_selector_probability_ut_2_node1* node1 = BEHAVIAC_NEW Action_bt_node_test_selector_probability_ut_2_node1;
node1->SetClassNameString("Action");
node1->SetId(1);
#if !BEHAVIAC_RELEASE
node1->SetAgentType("AgentNodeTest");
#endif
node4->AddChild(node1);
node4->SetHasEvents(node4->HasEvents() | node1->HasEvents());
}
node0->SetHasEvents(node0->HasEvents() | node4->HasEvents());
}
{
DecoratorWeight_bt_node_test_selector_probability_ut_2_node5* node5 = BEHAVIAC_NEW DecoratorWeight_bt_node_test_selector_probability_ut_2_node5;
node5->SetClassNameString("DecoratorWeight");
node5->SetId(5);
#if !BEHAVIAC_RELEASE
node5->SetAgentType("AgentNodeTest");
#endif
node0->AddChild(node5);
{
Action_bt_node_test_selector_probability_ut_2_node2* node2 = BEHAVIAC_NEW Action_bt_node_test_selector_probability_ut_2_node2;
node2->SetClassNameString("Action");
node2->SetId(2);
#if !BEHAVIAC_RELEASE
node2->SetAgentType("AgentNodeTest");
#endif
node5->AddChild(node2);
node5->SetHasEvents(node5->HasEvents() | node2->HasEvents());
}
node0->SetHasEvents(node0->HasEvents() | node5->HasEvents());
}
{
DecoratorWeight_bt_node_test_selector_probability_ut_2_node6* node6 = BEHAVIAC_NEW DecoratorWeight_bt_node_test_selector_probability_ut_2_node6;
node6->SetClassNameString("DecoratorWeight");
node6->SetId(6);
#if !BEHAVIAC_RELEASE
node6->SetAgentType("AgentNodeTest");
#endif
node0->AddChild(node6);
{
Action_bt_node_test_selector_probability_ut_2_node3* node3 = BEHAVIAC_NEW Action_bt_node_test_selector_probability_ut_2_node3;
node3->SetClassNameString("Action");
node3->SetId(3);
#if !BEHAVIAC_RELEASE
node3->SetAgentType("AgentNodeTest");
#endif
node6->AddChild(node3);
node6->SetHasEvents(node6->HasEvents() | node3->HasEvents());
}
node0->SetHasEvents(node0->HasEvents() | node6->HasEvents());
}
pBT->SetHasEvents(pBT->HasEvents() | node0->HasEvents());
}
return true;
}
// Source file: node_test/selector_probability_ut_3
class DecoratorLoop_bt_node_test_selector_probability_ut_3_node4 : public DecoratorLoop
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(DecoratorLoop_bt_node_test_selector_probability_ut_3_node4, DecoratorLoop);
DecoratorLoop_bt_node_test_selector_probability_ut_3_node4()
{
m_bDecorateWhenChildEnds = true;
m_bDoneWithinFrame = false;
}
protected:
virtual int GetCount(Agent* pAgent) const
{
BEHAVIAC_UNUSED_VAR(pAgent);
return 1;
}
};
class SelectorProbability_bt_node_test_selector_probability_ut_3_node0 : public SelectorProbability
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(SelectorProbability_bt_node_test_selector_probability_ut_3_node0, SelectorProbability);
SelectorProbability_bt_node_test_selector_probability_ut_3_node0()
{
}
public:
void Initialize(const char* method)
{
this->m_method = AgentMeta::ParseMethod(method);
}
};
class DecoratorWeight_bt_node_test_selector_probability_ut_3_node5 : public DecoratorWeight
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(DecoratorWeight_bt_node_test_selector_probability_ut_3_node5, DecoratorWeight);
DecoratorWeight_bt_node_test_selector_probability_ut_3_node5()
{
m_bDecorateWhenChildEnds = false;
}
protected:
virtual int GetWeight(Agent* pAgent) const
{
BEHAVIAC_UNUSED_VAR(pAgent);
return 10;
}
};
class Compute_bt_node_test_selector_probability_ut_3_node2 : public Compute
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Compute_bt_node_test_selector_probability_ut_3_node2, Compute);
Compute_bt_node_test_selector_probability_ut_3_node2()
{
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
EBTStatus result = BT_SUCCESS;
int opr1 = ((AgentNodeTest*)pAgent)->_Get_Property_<PROPERTY_TYPE_AgentNodeTest_testVar_0, int >();
int opr2 = 1;
((AgentNodeTest*)pAgent)->_Get_Property_<PROPERTY_TYPE_AgentNodeTest_testVar_0, int >() = (int)(opr1 + opr2);
return result;
}
};
class WaitFrames_bt_node_test_selector_probability_ut_3_node10 : public WaitFrames
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(WaitFrames_bt_node_test_selector_probability_ut_3_node10, WaitFrames);
WaitFrames_bt_node_test_selector_probability_ut_3_node10()
{
}
protected:
virtual int GetFrames(Agent* pAgent) const
{
BEHAVIAC_UNUSED_VAR(pAgent);
return 3;
}
};
class Compute_bt_node_test_selector_probability_ut_3_node11 : public Compute
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Compute_bt_node_test_selector_probability_ut_3_node11, Compute);
Compute_bt_node_test_selector_probability_ut_3_node11()
{
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
EBTStatus result = BT_SUCCESS;
int opr1 = ((AgentNodeTest*)pAgent)->_Get_Property_<PROPERTY_TYPE_AgentNodeTest_testVar_0, int >();
int opr2 = 1;
((AgentNodeTest*)pAgent)->_Get_Property_<PROPERTY_TYPE_AgentNodeTest_testVar_0, int >() = (int)(opr1 - opr2);
return result;
}
};
class DecoratorWeight_bt_node_test_selector_probability_ut_3_node6 : public DecoratorWeight
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(DecoratorWeight_bt_node_test_selector_probability_ut_3_node6, DecoratorWeight);
DecoratorWeight_bt_node_test_selector_probability_ut_3_node6()
{
m_bDecorateWhenChildEnds = false;
}
protected:
virtual int GetWeight(Agent* pAgent) const
{
BEHAVIAC_UNUSED_VAR(pAgent);
return 10;
}
};
class Compute_bt_node_test_selector_probability_ut_3_node3 : public Compute
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Compute_bt_node_test_selector_probability_ut_3_node3, Compute);
Compute_bt_node_test_selector_probability_ut_3_node3()
{
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
EBTStatus result = BT_SUCCESS;
int opr1 = ((AgentNodeTest*)pAgent)->_Get_Property_<PROPERTY_TYPE_AgentNodeTest_testVar_1, int >();
int opr2 = 1;
((AgentNodeTest*)pAgent)->_Get_Property_<PROPERTY_TYPE_AgentNodeTest_testVar_1, int >() = (int)(opr1 + opr2);
return result;
}
};
class WaitFrames_bt_node_test_selector_probability_ut_3_node9 : public WaitFrames
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(WaitFrames_bt_node_test_selector_probability_ut_3_node9, WaitFrames);
WaitFrames_bt_node_test_selector_probability_ut_3_node9()
{
}
protected:
virtual int GetFrames(Agent* pAgent) const
{
BEHAVIAC_UNUSED_VAR(pAgent);
return 3;
}
};
class Compute_bt_node_test_selector_probability_ut_3_node1 : public Compute
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Compute_bt_node_test_selector_probability_ut_3_node1, Compute);
Compute_bt_node_test_selector_probability_ut_3_node1()
{
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
EBTStatus result = BT_SUCCESS;
int opr1 = ((AgentNodeTest*)pAgent)->_Get_Property_<PROPERTY_TYPE_AgentNodeTest_testVar_1, int >();
int opr2 = 1;
((AgentNodeTest*)pAgent)->_Get_Property_<PROPERTY_TYPE_AgentNodeTest_testVar_1, int >() = (int)(opr1 - opr2);
return result;
}
};
bool bt_node_test_selector_probability_ut_3::Create(BehaviorTree* pBT)
{
pBT->SetClassNameString("BehaviorTree");
pBT->SetId((uint16_t)-1);
pBT->SetName("node_test/selector_probability_ut_3");
pBT->SetIsFSM(false);
#if !BEHAVIAC_RELEASE
pBT->SetAgentType("AgentNodeTest");
#endif
// children
{
DecoratorLoop_bt_node_test_selector_probability_ut_3_node4* node4 = BEHAVIAC_NEW DecoratorLoop_bt_node_test_selector_probability_ut_3_node4;
node4->SetClassNameString("DecoratorLoop");
node4->SetId(4);
#if !BEHAVIAC_RELEASE
node4->SetAgentType("AgentNodeTest");
#endif
pBT->AddChild(node4);
{
SelectorProbability_bt_node_test_selector_probability_ut_3_node0* node0 = BEHAVIAC_NEW SelectorProbability_bt_node_test_selector_probability_ut_3_node0;
node0->SetClassNameString("SelectorProbability");
node0->SetId(0);
#if !BEHAVIAC_RELEASE
node0->SetAgentType("AgentNodeTest");
#endif
node4->AddChild(node0);
{
DecoratorWeight_bt_node_test_selector_probability_ut_3_node5* node5 = BEHAVIAC_NEW DecoratorWeight_bt_node_test_selector_probability_ut_3_node5;
node5->SetClassNameString("DecoratorWeight");
node5->SetId(5);
#if !BEHAVIAC_RELEASE
node5->SetAgentType("AgentNodeTest");
#endif
node0->AddChild(node5);
{
Sequence* node7 = BEHAVIAC_NEW Sequence;
node7->SetClassNameString("Sequence");
node7->SetId(7);
#if !BEHAVIAC_RELEASE
node7->SetAgentType("AgentNodeTest");
#endif
node5->AddChild(node7);
{
Compute_bt_node_test_selector_probability_ut_3_node2* node2 = BEHAVIAC_NEW Compute_bt_node_test_selector_probability_ut_3_node2;
node2->SetClassNameString("Compute");
node2->SetId(2);
#if !BEHAVIAC_RELEASE
node2->SetAgentType("AgentNodeTest");
#endif
node7->AddChild(node2);
node7->SetHasEvents(node7->HasEvents() | node2->HasEvents());
}
{
WaitFrames_bt_node_test_selector_probability_ut_3_node10* node10 = BEHAVIAC_NEW WaitFrames_bt_node_test_selector_probability_ut_3_node10;
node10->SetClassNameString("WaitFrames");
node10->SetId(10);
#if !BEHAVIAC_RELEASE
node10->SetAgentType("AgentNodeTest");
#endif
node7->AddChild(node10);
node7->SetHasEvents(node7->HasEvents() | node10->HasEvents());
}
{
Compute_bt_node_test_selector_probability_ut_3_node11* node11 = BEHAVIAC_NEW Compute_bt_node_test_selector_probability_ut_3_node11;
node11->SetClassNameString("Compute");
node11->SetId(11);
#if !BEHAVIAC_RELEASE
node11->SetAgentType("AgentNodeTest");
#endif
node7->AddChild(node11);
node7->SetHasEvents(node7->HasEvents() | node11->HasEvents());
}
node5->SetHasEvents(node5->HasEvents() | node7->HasEvents());
}
node0->SetHasEvents(node0->HasEvents() | node5->HasEvents());
}
{
DecoratorWeight_bt_node_test_selector_probability_ut_3_node6* node6 = BEHAVIAC_NEW DecoratorWeight_bt_node_test_selector_probability_ut_3_node6;
node6->SetClassNameString("DecoratorWeight");
node6->SetId(6);
#if !BEHAVIAC_RELEASE
node6->SetAgentType("AgentNodeTest");
#endif
node0->AddChild(node6);
{
Sequence* node8 = BEHAVIAC_NEW Sequence;
node8->SetClassNameString("Sequence");
node8->SetId(8);
#if !BEHAVIAC_RELEASE
node8->SetAgentType("AgentNodeTest");
#endif
node6->AddChild(node8);
{
Compute_bt_node_test_selector_probability_ut_3_node3* node3 = BEHAVIAC_NEW Compute_bt_node_test_selector_probability_ut_3_node3;
node3->SetClassNameString("Compute");
node3->SetId(3);
#if !BEHAVIAC_RELEASE
node3->SetAgentType("AgentNodeTest");
#endif
node8->AddChild(node3);
node8->SetHasEvents(node8->HasEvents() | node3->HasEvents());
}
{
WaitFrames_bt_node_test_selector_probability_ut_3_node9* node9 = BEHAVIAC_NEW WaitFrames_bt_node_test_selector_probability_ut_3_node9;
node9->SetClassNameString("WaitFrames");
node9->SetId(9);
#if !BEHAVIAC_RELEASE
node9->SetAgentType("AgentNodeTest");
#endif
node8->AddChild(node9);
node8->SetHasEvents(node8->HasEvents() | node9->HasEvents());
}
{
Compute_bt_node_test_selector_probability_ut_3_node1* node1 = BEHAVIAC_NEW Compute_bt_node_test_selector_probability_ut_3_node1;
node1->SetClassNameString("Compute");
node1->SetId(1);
#if !BEHAVIAC_RELEASE
node1->SetAgentType("AgentNodeTest");
#endif
node8->AddChild(node1);
node8->SetHasEvents(node8->HasEvents() | node1->HasEvents());
}
node6->SetHasEvents(node6->HasEvents() | node8->HasEvents());
}
node0->SetHasEvents(node0->HasEvents() | node6->HasEvents());
}
node4->SetHasEvents(node4->HasEvents() | node0->HasEvents());
}
pBT->SetHasEvents(pBT->HasEvents() | node4->HasEvents());
}
return true;
}
// Source file: node_test/selector_probability_ut_4
class DecoratorLoop_bt_node_test_selector_probability_ut_4_node15 : public DecoratorLoop
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(DecoratorLoop_bt_node_test_selector_probability_ut_4_node15, DecoratorLoop);
DecoratorLoop_bt_node_test_selector_probability_ut_4_node15()
{
m_bDecorateWhenChildEnds = true;
m_bDoneWithinFrame = false;
}
protected:
virtual int GetCount(Agent* pAgent) const
{
BEHAVIAC_UNUSED_VAR(pAgent);
return 1;
}
};
class SelectorProbability_bt_node_test_selector_probability_ut_4_node0 : public SelectorProbability
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(SelectorProbability_bt_node_test_selector_probability_ut_4_node0, SelectorProbability);
SelectorProbability_bt_node_test_selector_probability_ut_4_node0()
{
}
public:
void Initialize(const char* method)
{
this->m_method = AgentMeta::ParseMethod(method);
}
};
class DecoratorWeight_bt_node_test_selector_probability_ut_4_node5 : public DecoratorWeight
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(DecoratorWeight_bt_node_test_selector_probability_ut_4_node5, DecoratorWeight);
DecoratorWeight_bt_node_test_selector_probability_ut_4_node5()
{
m_bDecorateWhenChildEnds = false;
}
protected:
virtual int GetWeight(Agent* pAgent) const
{
BEHAVIAC_UNUSED_VAR(pAgent);
return 10;
}
};
class Parallel_bt_node_test_selector_probability_ut_4_node10 : public Parallel
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Parallel_bt_node_test_selector_probability_ut_4_node10, Parallel);
Parallel_bt_node_test_selector_probability_ut_4_node10()
{
m_failPolicy = FAIL_ON_ONE;
m_succeedPolicy = SUCCEED_ON_ALL;
m_exitPolicy = EXIT_ABORT_RUNNINGSIBLINGS;
m_childFinishPolicy = CHILDFINISH_LOOP;
}
protected:
};
class Compute_bt_node_test_selector_probability_ut_4_node2 : public Compute
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Compute_bt_node_test_selector_probability_ut_4_node2, Compute);
Compute_bt_node_test_selector_probability_ut_4_node2()
{
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
EBTStatus result = BT_SUCCESS;
int opr1 = ((AgentNodeTest*)pAgent)->_Get_Property_<PROPERTY_TYPE_AgentNodeTest_testVar_0, int >();
int opr2 = 1;
((AgentNodeTest*)pAgent)->_Get_Property_<PROPERTY_TYPE_AgentNodeTest_testVar_0, int >() = (int)(opr1 + opr2);
return result;
}
};
class Compute_bt_node_test_selector_probability_ut_4_node13 : public Compute
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Compute_bt_node_test_selector_probability_ut_4_node13, Compute);
Compute_bt_node_test_selector_probability_ut_4_node13()
{
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
EBTStatus result = BT_SUCCESS;
float opr1 = ((AgentNodeTest*)pAgent)->_Get_Property_<PROPERTY_TYPE_AgentNodeTest_testVar_2, float >();
float opr2 = 1;
((AgentNodeTest*)pAgent)->_Get_Property_<PROPERTY_TYPE_AgentNodeTest_testVar_2, float >() = (float)(opr1 + opr2);
return result;
}
};
class Wait_bt_node_test_selector_probability_ut_4_node4 : public Wait
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Wait_bt_node_test_selector_probability_ut_4_node4, Wait);
Wait_bt_node_test_selector_probability_ut_4_node4()
{
}
protected:
virtual double GetTime(Agent* pAgent) const
{
BEHAVIAC_UNUSED_VAR(pAgent);
return 1000;
}
};
class Compute_bt_node_test_selector_probability_ut_4_node11 : public Compute
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Compute_bt_node_test_selector_probability_ut_4_node11, Compute);
Compute_bt_node_test_selector_probability_ut_4_node11()
{
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
EBTStatus result = BT_SUCCESS;
int opr1 = ((AgentNodeTest*)pAgent)->_Get_Property_<PROPERTY_TYPE_AgentNodeTest_testVar_0, int >();
int opr2 = 1;
((AgentNodeTest*)pAgent)->_Get_Property_<PROPERTY_TYPE_AgentNodeTest_testVar_0, int >() = (int)(opr1 - opr2);
return result;
}
};
class DecoratorWeight_bt_node_test_selector_probability_ut_4_node6 : public DecoratorWeight
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(DecoratorWeight_bt_node_test_selector_probability_ut_4_node6, DecoratorWeight);
DecoratorWeight_bt_node_test_selector_probability_ut_4_node6()
{
m_bDecorateWhenChildEnds = false;
}
protected:
virtual int GetWeight(Agent* pAgent) const
{
BEHAVIAC_UNUSED_VAR(pAgent);
return 10;
}
};
class Parallel_bt_node_test_selector_probability_ut_4_node12 : public Parallel
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Parallel_bt_node_test_selector_probability_ut_4_node12, Parallel);
Parallel_bt_node_test_selector_probability_ut_4_node12()
{
m_failPolicy = FAIL_ON_ONE;
m_succeedPolicy = SUCCEED_ON_ALL;
m_exitPolicy = EXIT_ABORT_RUNNINGSIBLINGS;
m_childFinishPolicy = CHILDFINISH_LOOP;
}
protected:
};
class Compute_bt_node_test_selector_probability_ut_4_node3 : public Compute
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Compute_bt_node_test_selector_probability_ut_4_node3, Compute);
Compute_bt_node_test_selector_probability_ut_4_node3()
{
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
EBTStatus result = BT_SUCCESS;
int opr1 = ((AgentNodeTest*)pAgent)->_Get_Property_<PROPERTY_TYPE_AgentNodeTest_testVar_1, int >();
int opr2 = 1;
((AgentNodeTest*)pAgent)->_Get_Property_<PROPERTY_TYPE_AgentNodeTest_testVar_1, int >() = (int)(opr1 + opr2);
return result;
}
};
class Compute_bt_node_test_selector_probability_ut_4_node14 : public Compute
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Compute_bt_node_test_selector_probability_ut_4_node14, Compute);
Compute_bt_node_test_selector_probability_ut_4_node14()
{
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
EBTStatus result = BT_SUCCESS;
float opr1 = ((AgentNodeTest*)pAgent)->_Get_Property_<PROPERTY_TYPE_AgentNodeTest_testVar_3, float >();
float opr2 = 1;
((AgentNodeTest*)pAgent)->_Get_Property_<PROPERTY_TYPE_AgentNodeTest_testVar_3, float >() = (float)(opr1 + opr2);
return result;
}
};
class Wait_bt_node_test_selector_probability_ut_4_node9 : public Wait
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Wait_bt_node_test_selector_probability_ut_4_node9, Wait);
Wait_bt_node_test_selector_probability_ut_4_node9()
{
}
protected:
virtual double GetTime(Agent* pAgent) const
{
BEHAVIAC_UNUSED_VAR(pAgent);
return 1000;
}
};
class Compute_bt_node_test_selector_probability_ut_4_node1 : public Compute
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Compute_bt_node_test_selector_probability_ut_4_node1, Compute);
Compute_bt_node_test_selector_probability_ut_4_node1()
{
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
EBTStatus result = BT_SUCCESS;
int opr1 = ((AgentNodeTest*)pAgent)->_Get_Property_<PROPERTY_TYPE_AgentNodeTest_testVar_1, int >();
int opr2 = 1;
((AgentNodeTest*)pAgent)->_Get_Property_<PROPERTY_TYPE_AgentNodeTest_testVar_1, int >() = (int)(opr1 - opr2);
return result;
}
};
bool bt_node_test_selector_probability_ut_4::Create(BehaviorTree* pBT)
{
pBT->SetClassNameString("BehaviorTree");
pBT->SetId((uint16_t)-1);
pBT->SetName("node_test/selector_probability_ut_4");
pBT->SetIsFSM(false);
#if !BEHAVIAC_RELEASE
pBT->SetAgentType("AgentNodeTest");
#endif
// children
{
DecoratorLoop_bt_node_test_selector_probability_ut_4_node15* node15 = BEHAVIAC_NEW DecoratorLoop_bt_node_test_selector_probability_ut_4_node15;
node15->SetClassNameString("DecoratorLoop");
node15->SetId(15);
#if !BEHAVIAC_RELEASE
node15->SetAgentType("AgentNodeTest");
#endif
pBT->AddChild(node15);
{
SelectorProbability_bt_node_test_selector_probability_ut_4_node0* node0 = BEHAVIAC_NEW SelectorProbability_bt_node_test_selector_probability_ut_4_node0;
node0->SetClassNameString("SelectorProbability");
node0->SetId(0);
#if !BEHAVIAC_RELEASE
node0->SetAgentType("AgentNodeTest");
#endif
node15->AddChild(node0);
{
DecoratorWeight_bt_node_test_selector_probability_ut_4_node5* node5 = BEHAVIAC_NEW DecoratorWeight_bt_node_test_selector_probability_ut_4_node5;
node5->SetClassNameString("DecoratorWeight");
node5->SetId(5);
#if !BEHAVIAC_RELEASE
node5->SetAgentType("AgentNodeTest");
#endif
node0->AddChild(node5);
{
Sequence* node7 = BEHAVIAC_NEW Sequence;
node7->SetClassNameString("Sequence");
node7->SetId(7);
#if !BEHAVIAC_RELEASE
node7->SetAgentType("AgentNodeTest");
#endif
node5->AddChild(node7);
{
Parallel_bt_node_test_selector_probability_ut_4_node10* node10 = BEHAVIAC_NEW Parallel_bt_node_test_selector_probability_ut_4_node10;
node10->SetClassNameString("Parallel");
node10->SetId(10);
#if !BEHAVIAC_RELEASE
node10->SetAgentType("AgentNodeTest");
#endif
node7->AddChild(node10);
{
Compute_bt_node_test_selector_probability_ut_4_node2* node2 = BEHAVIAC_NEW Compute_bt_node_test_selector_probability_ut_4_node2;
node2->SetClassNameString("Compute");
node2->SetId(2);
#if !BEHAVIAC_RELEASE
node2->SetAgentType("AgentNodeTest");
#endif
node10->AddChild(node2);
node10->SetHasEvents(node10->HasEvents() | node2->HasEvents());
}
{
Compute_bt_node_test_selector_probability_ut_4_node13* node13 = BEHAVIAC_NEW Compute_bt_node_test_selector_probability_ut_4_node13;
node13->SetClassNameString("Compute");
node13->SetId(13);
#if !BEHAVIAC_RELEASE
node13->SetAgentType("AgentNodeTest");
#endif
node10->AddChild(node13);
node10->SetHasEvents(node10->HasEvents() | node13->HasEvents());
}
node7->SetHasEvents(node7->HasEvents() | node10->HasEvents());
}
{
Wait_bt_node_test_selector_probability_ut_4_node4* node4 = BEHAVIAC_NEW Wait_bt_node_test_selector_probability_ut_4_node4;
node4->SetClassNameString("Wait");
node4->SetId(4);
#if !BEHAVIAC_RELEASE
node4->SetAgentType("AgentNodeTest");
#endif
node7->AddChild(node4);
node7->SetHasEvents(node7->HasEvents() | node4->HasEvents());
}
{
Compute_bt_node_test_selector_probability_ut_4_node11* node11 = BEHAVIAC_NEW Compute_bt_node_test_selector_probability_ut_4_node11;
node11->SetClassNameString("Compute");
node11->SetId(11);
#if !BEHAVIAC_RELEASE
node11->SetAgentType("AgentNodeTest");
#endif
node7->AddChild(node11);
node7->SetHasEvents(node7->HasEvents() | node11->HasEvents());
}
node5->SetHasEvents(node5->HasEvents() | node7->HasEvents());
}
node0->SetHasEvents(node0->HasEvents() | node5->HasEvents());
}
{
DecoratorWeight_bt_node_test_selector_probability_ut_4_node6* node6 = BEHAVIAC_NEW DecoratorWeight_bt_node_test_selector_probability_ut_4_node6;
node6->SetClassNameString("DecoratorWeight");
node6->SetId(6);
#if !BEHAVIAC_RELEASE
node6->SetAgentType("AgentNodeTest");
#endif
node0->AddChild(node6);
{
Sequence* node8 = BEHAVIAC_NEW Sequence;
node8->SetClassNameString("Sequence");
node8->SetId(8);
#if !BEHAVIAC_RELEASE
node8->SetAgentType("AgentNodeTest");
#endif
node6->AddChild(node8);
{
Parallel_bt_node_test_selector_probability_ut_4_node12* node12 = BEHAVIAC_NEW Parallel_bt_node_test_selector_probability_ut_4_node12;
node12->SetClassNameString("Parallel");
node12->SetId(12);
#if !BEHAVIAC_RELEASE
node12->SetAgentType("AgentNodeTest");
#endif
node8->AddChild(node12);
{
Compute_bt_node_test_selector_probability_ut_4_node3* node3 = BEHAVIAC_NEW Compute_bt_node_test_selector_probability_ut_4_node3;
node3->SetClassNameString("Compute");
node3->SetId(3);
#if !BEHAVIAC_RELEASE
node3->SetAgentType("AgentNodeTest");
#endif
node12->AddChild(node3);
node12->SetHasEvents(node12->HasEvents() | node3->HasEvents());
}
{
Compute_bt_node_test_selector_probability_ut_4_node14* node14 = BEHAVIAC_NEW Compute_bt_node_test_selector_probability_ut_4_node14;
node14->SetClassNameString("Compute");
node14->SetId(14);
#if !BEHAVIAC_RELEASE
node14->SetAgentType("AgentNodeTest");
#endif
node12->AddChild(node14);
node12->SetHasEvents(node12->HasEvents() | node14->HasEvents());
}
node8->SetHasEvents(node8->HasEvents() | node12->HasEvents());
}
{
Wait_bt_node_test_selector_probability_ut_4_node9* node9 = BEHAVIAC_NEW Wait_bt_node_test_selector_probability_ut_4_node9;
node9->SetClassNameString("Wait");
node9->SetId(9);
#if !BEHAVIAC_RELEASE
node9->SetAgentType("AgentNodeTest");
#endif
node8->AddChild(node9);
node8->SetHasEvents(node8->HasEvents() | node9->HasEvents());
}
{
Compute_bt_node_test_selector_probability_ut_4_node1* node1 = BEHAVIAC_NEW Compute_bt_node_test_selector_probability_ut_4_node1;
node1->SetClassNameString("Compute");
node1->SetId(1);
#if !BEHAVIAC_RELEASE
node1->SetAgentType("AgentNodeTest");
#endif
node8->AddChild(node1);
node8->SetHasEvents(node8->HasEvents() | node1->HasEvents());
}
node6->SetHasEvents(node6->HasEvents() | node8->HasEvents());
}
node0->SetHasEvents(node0->HasEvents() | node6->HasEvents());
}
node15->SetHasEvents(node15->HasEvents() | node0->HasEvents());
}
pBT->SetHasEvents(pBT->HasEvents() | node15->HasEvents());
}
return true;
}
// Source file: node_test/selector_stochastic_ut_0
class SelectorStochastic_bt_node_test_selector_stochastic_ut_0_node0 : public SelectorStochastic
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(SelectorStochastic_bt_node_test_selector_stochastic_ut_0_node0, SelectorStochastic);
SelectorStochastic_bt_node_test_selector_stochastic_ut_0_node0()
{
}
public:
void Initialize(const char* method)
{
this->m_method = AgentMeta::ParseMethod(method);
}
};
class Action_bt_node_test_selector_stochastic_ut_0_node1 : public Action
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Action_bt_node_test_selector_stochastic_ut_0_node1, Action);
Action_bt_node_test_selector_stochastic_ut_0_node1()
{
method_p0 = 0;
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
((AgentNodeTest*)pAgent)->_Execute_Method_<METHOD_TYPE_AgentNodeTest_setTestVar_0, void, int >(method_p0);
return BT_SUCCESS;
}
int method_p0;
};
class Action_bt_node_test_selector_stochastic_ut_0_node2 : public Action
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Action_bt_node_test_selector_stochastic_ut_0_node2, Action);
Action_bt_node_test_selector_stochastic_ut_0_node2()
{
method_p0 = 1;
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
((AgentNodeTest*)pAgent)->_Execute_Method_<METHOD_TYPE_AgentNodeTest_setTestVar_0, void, int >(method_p0);
return BT_SUCCESS;
}
int method_p0;
};
class Action_bt_node_test_selector_stochastic_ut_0_node3 : public Action
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Action_bt_node_test_selector_stochastic_ut_0_node3, Action);
Action_bt_node_test_selector_stochastic_ut_0_node3()
{
method_p0 = 2;
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
((AgentNodeTest*)pAgent)->_Execute_Method_<METHOD_TYPE_AgentNodeTest_setTestVar_0, void, int >(method_p0);
return BT_SUCCESS;
}
int method_p0;
};
bool bt_node_test_selector_stochastic_ut_0::Create(BehaviorTree* pBT)
{
pBT->SetClassNameString("BehaviorTree");
pBT->SetId((uint16_t)-1);
pBT->SetName("node_test/selector_stochastic_ut_0");
pBT->SetIsFSM(false);
#if !BEHAVIAC_RELEASE
pBT->SetAgentType("AgentNodeTest");
#endif
// children
{
SelectorStochastic_bt_node_test_selector_stochastic_ut_0_node0* node0 = BEHAVIAC_NEW SelectorStochastic_bt_node_test_selector_stochastic_ut_0_node0;
node0->SetClassNameString("SelectorStochastic");
node0->SetId(0);
#if !BEHAVIAC_RELEASE
node0->SetAgentType("AgentNodeTest");
#endif
pBT->AddChild(node0);
{
Action_bt_node_test_selector_stochastic_ut_0_node1* node1 = BEHAVIAC_NEW Action_bt_node_test_selector_stochastic_ut_0_node1;
node1->SetClassNameString("Action");
node1->SetId(1);
#if !BEHAVIAC_RELEASE
node1->SetAgentType("AgentNodeTest");
#endif
node0->AddChild(node1);
node0->SetHasEvents(node0->HasEvents() | node1->HasEvents());
}
{
Action_bt_node_test_selector_stochastic_ut_0_node2* node2 = BEHAVIAC_NEW Action_bt_node_test_selector_stochastic_ut_0_node2;
node2->SetClassNameString("Action");
node2->SetId(2);
#if !BEHAVIAC_RELEASE
node2->SetAgentType("AgentNodeTest");
#endif
node0->AddChild(node2);
node0->SetHasEvents(node0->HasEvents() | node2->HasEvents());
}
{
Action_bt_node_test_selector_stochastic_ut_0_node3* node3 = BEHAVIAC_NEW Action_bt_node_test_selector_stochastic_ut_0_node3;
node3->SetClassNameString("Action");
node3->SetId(3);
#if !BEHAVIAC_RELEASE
node3->SetAgentType("AgentNodeTest");
#endif
node0->AddChild(node3);
node0->SetHasEvents(node0->HasEvents() | node3->HasEvents());
}
pBT->SetHasEvents(pBT->HasEvents() | node0->HasEvents());
}
return true;
}
// Source file: node_test/selector_stochastic_ut_1
class SelectorStochastic_bt_node_test_selector_stochastic_ut_1_node0 : public SelectorStochastic
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(SelectorStochastic_bt_node_test_selector_stochastic_ut_1_node0, SelectorStochastic);
SelectorStochastic_bt_node_test_selector_stochastic_ut_1_node0()
{
}
public:
void Initialize(const char* method)
{
this->m_method = AgentMeta::ParseMethod(method);
}
};
class Action_bt_node_test_selector_stochastic_ut_1_node1 : public Action
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Action_bt_node_test_selector_stochastic_ut_1_node1, Action);
Action_bt_node_test_selector_stochastic_ut_1_node1()
{
method_p0 = 0;
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
((AgentNodeTest*)pAgent)->_Execute_Method_<METHOD_TYPE_AgentNodeTest_setTestVar_0, void, int >(method_p0);
return BT_SUCCESS;
}
int method_p0;
};
bool bt_node_test_selector_stochastic_ut_1::Create(BehaviorTree* pBT)
{
pBT->SetClassNameString("BehaviorTree");
pBT->SetId((uint16_t)-1);
pBT->SetName("node_test/selector_stochastic_ut_1");
pBT->SetIsFSM(false);
#if !BEHAVIAC_RELEASE
pBT->SetAgentType("AgentNodeTest");
#endif
// children
{
SelectorStochastic_bt_node_test_selector_stochastic_ut_1_node0* node0 = BEHAVIAC_NEW SelectorStochastic_bt_node_test_selector_stochastic_ut_1_node0;
node0->SetClassNameString("SelectorStochastic");
node0->SetId(0);
#if !BEHAVIAC_RELEASE
node0->SetAgentType("AgentNodeTest");
#endif
pBT->AddChild(node0);
{
Action_bt_node_test_selector_stochastic_ut_1_node1* node1 = BEHAVIAC_NEW Action_bt_node_test_selector_stochastic_ut_1_node1;
node1->SetClassNameString("Action");
node1->SetId(1);
#if !BEHAVIAC_RELEASE
node1->SetAgentType("AgentNodeTest");
#endif
node0->AddChild(node1);
node0->SetHasEvents(node0->HasEvents() | node1->HasEvents());
}
{
True* node2 = BEHAVIAC_NEW True;
node2->SetClassNameString("True");
node2->SetId(2);
#if !BEHAVIAC_RELEASE
node2->SetAgentType("AgentNodeTest");
#endif
node0->AddChild(node2);
node0->SetHasEvents(node0->HasEvents() | node2->HasEvents());
}
{
True* node3 = BEHAVIAC_NEW True;
node3->SetClassNameString("True");
node3->SetId(3);
#if !BEHAVIAC_RELEASE
node3->SetAgentType("AgentNodeTest");
#endif
node0->AddChild(node3);
node0->SetHasEvents(node0->HasEvents() | node3->HasEvents());
}
pBT->SetHasEvents(pBT->HasEvents() | node0->HasEvents());
}
return true;
}
}
| 54,829 |
743 | <filename>hermes-management/src/main/java/pl/allegro/tech/hermes/management/api/auth/ManagementRights.java
package pl.allegro.tech.hermes.management.api.auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import pl.allegro.tech.hermes.api.Group;
import pl.allegro.tech.hermes.api.Subscription;
import pl.allegro.tech.hermes.api.Topic;
import pl.allegro.tech.hermes.domain.topic.TopicRepository;
import pl.allegro.tech.hermes.management.config.GroupProperties;
import javax.ws.rs.container.ContainerRequestContext;
/**
* Make sure these implementations conform to what is configured via RolesAllowed annotations in endpoints.
*/
@Component
public class ManagementRights {
private final TopicRepository topicRepository;
private final GroupProperties groupProperties;
@Autowired
public ManagementRights(TopicRepository topicRepository, GroupProperties groupProperties) {
this.topicRepository = topicRepository;
this.groupProperties = groupProperties;
}
public boolean isUserAllowedToManageTopic(Topic topic, ContainerRequestContext requestContext) {
return isAdmin(requestContext) ||
getOwnershipResolver(requestContext).isUserAnOwner(topic.getOwner());
}
public boolean isUserAllowedToCreateSubscription(Subscription subscription, ContainerRequestContext requestContext) {
return !topicRepository.isSubscribingRestricted(subscription.getTopicName()) ||
isAdmin(requestContext) || isTopicOwner(subscription, requestContext);
}
public boolean isUserAllowedToCreateGroup(ContainerRequestContext requestContext) {
return isAdmin(requestContext) || groupProperties.isNonAdminCreationEnabled();
}
private boolean isUserAllowedToManageGroup(ContainerRequestContext requestContext) {
return isAdmin(requestContext);
}
public boolean isUserAllowedToManageSubscription(Subscription subscription, ContainerRequestContext requestContext) {
return isAdmin(requestContext) || isTopicOwner(subscription, requestContext) ||
isSubscriptionOwner(subscription, requestContext);
}
private boolean isTopicOwner(Subscription subscription, ContainerRequestContext requestContext) {
return getOwnershipResolver(requestContext).isUserAnOwner(topicRepository.getTopicDetails(subscription.getTopicName()).getOwner());
}
private boolean isSubscriptionOwner(Subscription subscription, ContainerRequestContext requestContext) {
return getOwnershipResolver(requestContext).isUserAnOwner(subscription.getOwner());
}
private boolean isAdmin(ContainerRequestContext requestContext) {
return requestContext.getSecurityContext().isUserInRole(Roles.ADMIN);
}
private SecurityProvider.OwnershipResolver getOwnershipResolver(ContainerRequestContext requestContext) {
return (SecurityProvider.OwnershipResolver) requestContext.getProperty(AuthorizationFilter.OWNERSHIP_RESOLVER);
}
public CreatorRights<Subscription> getSubscriptionCreatorRights(ContainerRequestContext requestContext) {
return new SubscriptionCreatorRights(requestContext);
}
public CreatorRights<Group> getGroupCreatorRights(ContainerRequestContext requestContext) {
return new GroupCreatorRights(requestContext);
}
class SubscriptionCreatorRights implements CreatorRights<Subscription> {
private ContainerRequestContext requestContext;
SubscriptionCreatorRights(ContainerRequestContext requestContext) {
this.requestContext = requestContext;
}
@Override
public boolean allowedToManage(Subscription subscription) {
return ManagementRights.this.isUserAllowedToManageSubscription(subscription, requestContext);
}
@Override
public boolean allowedToCreate(Subscription subscription) {
return ManagementRights.this.isUserAllowedToCreateSubscription(subscription, requestContext);
}
}
class GroupCreatorRights implements CreatorRights<Group> {
private ContainerRequestContext requestContext;
GroupCreatorRights(ContainerRequestContext requestContext) {
this.requestContext = requestContext;
}
@Override
public boolean allowedToManage(Group group) {
return ManagementRights.this.isUserAllowedToManageGroup(requestContext);
}
@Override
public boolean allowedToCreate(Group group) {
return ManagementRights.this.isUserAllowedToCreateGroup(requestContext);
}
}
}
| 1,493 |
1,272 | <reponame>AndersSpringborg/avs-device-sdk<filename>AVSCommon/AVS/include/AVSCommon/AVS/Initialization/InitializationParameters.h
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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 ALEXA_CLIENT_SDK_AVSCOMMON_AVS_INCLUDE_AVSCOMMON_AVS_INITIALIZATION_INITIALIZATIONPARAMETERS_H_
#define ALEXA_CLIENT_SDK_AVSCOMMON_AVS_INCLUDE_AVSCOMMON_AVS_INITIALIZATION_INITIALIZATIONPARAMETERS_H_
#include <iostream>
#include <memory>
#include <vector>
#include <AVSCommon/SDKInterfaces/PowerResourceManagerInterface.h>
#include <AVSCommon/SDKInterfaces/Timing/TimerDelegateFactoryInterface.h>
#include <AVSCommon/Utils/Timing/TimerDelegateFactory.h>
namespace alexaClientSDK {
namespace avsCommon {
namespace avs {
namespace initialization {
/**
* A struct to contain the various parameters that are needed to initialize @c AlexaClientSDKInit.
*/
struct InitializationParameters {
/**
* Vector of @c istreams containing JSON documents from which
* to parse configuration parameters. Streams are processed in the order they appear in the vector. When a
* value appears in more than one JSON stream the last processed stream's value overwrites the previous value
* (and a debug log entry will be created). This allows for specifying default settings (by providing them
* first) and specifying the configuration from multiple sources (e.g. a separate stream for each component).
* Documentation of the JSON configuration format and methods to access the resulting global configuration
* can be found here: avsCommon::utils::configuration::ConfigurationNode.
*/
std::shared_ptr<std::vector<std::shared_ptr<std::istream>>> jsonStreams;
/// The @c PowerResourceManagerInterface. This will be used for power management.
std::shared_ptr<sdkInterfaces::PowerResourceManagerInterface> powerResourceManager;
/// The @c TimerDelegateFactoryInterface. This will be used to inject custom implementations of @c
/// TimerDelegateInterface.
std::shared_ptr<sdkInterfaces::timing::TimerDelegateFactoryInterface> timerDelegateFactory;
};
} // namespace initialization
} // namespace avs
} // namespace avsCommon
} // namespace alexaClientSDK
#endif // ALEXA_CLIENT_SDK_AVSCOMMON_AVS_INCLUDE_AVSCOMMON_AVS_INITIALIZATION_INITIALIZATIONPARAMETERS_H_
| 865 |
2,092 | <filename>app/src/main/java/com/demo/widget/meis/MeiFireflyActivity.java
package com.demo.widget.meis;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import com.demo.widget.R;
import com.demo.widget.utils.Eyes;
import com.meis.widget.particle.FireflyView;
/**
* Created by wenshi on 2018/7/5.
* Description 浮动粒子界面
*/
public class MeiFireflyActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mei_fire_fly_activity);
Eyes.translucentStatusBar(this, true);
}
}
| 283 |
14,668 | // 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_WEBUI_DIAGNOSTICS_UI_BACKEND_INPUT_DATA_PROVIDER_KEYBOARD_H_
#define ASH_WEBUI_DIAGNOSTICS_UI_BACKEND_INPUT_DATA_PROVIDER_KEYBOARD_H_
#include "ash/webui/diagnostics_ui/mojom/input_data_provider.mojom.h"
#include "base/memory/weak_ptr.h"
#include "ui/chromeos/events/event_rewriter_chromeos.h"
#include "ui/events/ozone/evdev/event_device_info.h"
#include "ui/events/ozone/layout/xkb/xkb_evdev_codes.h"
#include "ui/events/ozone/layout/xkb/xkb_keyboard_layout_engine.h"
namespace ash {
namespace diagnostics {
class InputDeviceInformation;
// Helper to provide InputDataProvider diagnostic interface with
// keyboard-specific logic.
class InputDataProviderKeyboard {
public:
InputDataProviderKeyboard();
InputDataProviderKeyboard(const InputDataProviderKeyboard&) = delete;
InputDataProviderKeyboard& operator=(const InputDataProviderKeyboard&) =
delete;
~InputDataProviderKeyboard();
void GetKeyboardVisualLayout(
mojom::KeyboardInfoPtr keyboard,
mojom::InputDataProvider::GetKeyboardVisualLayoutCallback callback);
mojom::KeyboardInfoPtr ConstructKeyboard(
const InputDeviceInformation* device_info);
private:
void ProcessXkbLayout(
mojom::InputDataProvider::GetKeyboardVisualLayoutCallback callback);
mojom::KeyGlyphSetPtr LookupGlyphSet(uint32_t evdev_code);
void ProcessKeyboardTopRowLayout(
const InputDeviceInformation* device_info,
ui::EventRewriterChromeOS::KeyboardTopRowLayout* out_top_row_layout,
std::vector<mojom::TopRowKey>* out_top_row_keys);
ui::XkbEvdevCodes xkb_evdev_codes_;
ui::XkbKeyboardLayoutEngine xkb_layout_engine_;
base::WeakPtrFactory<InputDataProviderKeyboard> weak_factory_{this};
};
} // namespace diagnostics
} // namespace ash
#endif // ASH_WEBUI_DIAGNOSTICS_UI_BACKEND_INPUT_DATA_PROVIDER_KEYBOARD_H_
| 703 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.