max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
2,332 | {"atlas_mist_7": "MIST atlas scale 7", "atlas_mist_36": "MIST atlas scale 36", "atlas_mist_12": "MIST atlas scale 12", "atlas_yeo17": "Yeo 17 network atlas", "atlas_harvard": "Harvard-Oxford atlas", "atlas_yeo7": "Yeo 7 network atlas", "atlas_mist_20": "MIST atlas scale 20", "atlas_mist_64": "MIST atlas scale 64"} | 128 |
1,752 | <reponame>chonty/napalm1
import json
from lxml import etree
def test_build_payload(mock_pynxos_device):
"""
Payload format should be as follows:
[
{
'id': 1,
'jsonrpc': '2.0',
'method': 'cli',
'params': {'cmd': 'show hostname', 'version': 1.0}
}
]
"""
mock_device = mock_pynxos_device
payload = mock_device.api._build_payload(["show hostname"], method="cli")
payload = json.loads(payload)
assert isinstance(payload, list)
payload_dict = payload[0]
assert payload_dict["id"] == 1
assert payload_dict["jsonrpc"] == "2.0"
assert payload_dict["method"] == "cli"
assert payload_dict["params"]["cmd"] == "show hostname"
assert payload_dict["params"]["version"] == 1.0
def test_build_payload_list(mock_pynxos_device):
"""Payload with list of commands (jsonrpc)"""
mock_device = mock_pynxos_device
payload = mock_device.api._build_payload(
["show hostname", "show version"], method="cli"
)
payload = json.loads(payload)
assert len(payload) == 2
payload_dict = payload[0]
assert payload_dict["id"] == 1
assert payload_dict["jsonrpc"] == "2.0"
assert payload_dict["method"] == "cli"
assert payload_dict["params"]["cmd"] == "show hostname"
assert payload_dict["params"]["version"] == 1.0
payload_dict = payload[1]
assert payload_dict["id"] == 2
assert payload_dict["jsonrpc"] == "2.0"
assert payload_dict["method"] == "cli"
assert payload_dict["params"]["cmd"] == "show version"
assert payload_dict["params"]["version"] == 1.0
def test_build_payload_xml(mock_pynxos_device_xml):
"""
Payload format should be as follows:
<?xml version="1.0"?>
<ins_api>
<version>1.2</version>
<type>cli_show</type>
<chunk>0</chunk>
<sid>sid</sid>
<input>show hostname</input>
<output_format>xml</output_format>
</ins_api>
"""
mock_device = mock_pynxos_device_xml
payload = mock_device.api._build_payload(["show hostname"], method="cli_show")
xml_root = etree.fromstring(payload)
assert xml_root.tag == "ins_api"
version = xml_root.find("./version")
api_method = xml_root.find("./type")
sid = xml_root.find("./sid")
api_cmd = xml_root.find("./input")
output_format = xml_root.find("./output_format")
assert version.tag == "version"
assert version.text == "1.0"
assert api_method.tag == "type"
assert api_method.text == "cli_show"
assert sid.tag == "sid"
assert sid.text == "sid"
assert api_cmd.tag == "input"
assert api_cmd.text == "show hostname"
assert output_format.tag == "output_format"
assert output_format.text == "xml"
def test_build_payload_xml_list(mock_pynxos_device_xml):
"""Build payload with list of commands (XML)."""
mock_device = mock_pynxos_device_xml
payload = mock_device.api._build_payload(
["show hostname", "show version"], method="cli_show"
)
xml_root = etree.fromstring(payload)
assert xml_root.tag == "ins_api"
version = xml_root.find("./version")
api_method = xml_root.find("./type")
sid = xml_root.find("./sid") # noqa
api_cmd = xml_root.find("./input")
output_format = xml_root.find("./output_format")
assert api_cmd.text == "show hostname ;show version"
assert version.tag == "version"
assert version.text == "1.0"
assert api_method.text == "cli_show"
assert output_format.text == "xml"
def test_build_payload_xml_config(mock_pynxos_device_xml):
"""Build payload with list of commands (XML)."""
mock_device = mock_pynxos_device_xml
payload = mock_device.api._build_payload(
["logging history size 200"], method="cli_conf"
)
xml_root = etree.fromstring(payload)
api_method = xml_root.find("./type")
api_cmd = xml_root.find("./input")
assert xml_root.tag == "ins_api"
assert api_cmd.text == "logging history size 200"
assert api_method.text == "cli_conf"
| 1,655 |
1,293 | /*
* Copyright (c) 2020 - Manifold Systems LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package manifold.xml.rt;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import manifold.rt.api.Bindings;
import manifold.json.rt.api.DataBindings;
import manifold.json.rt.parser.Token;
import manifold.json.rt.parser.TokenType;
import manifold.rt.api.util.Pair;
import manifold.xml.rt.parser.XmlAttribute;
import manifold.xml.rt.parser.XmlParser;
import manifold.xml.rt.parser.XmlTerminal;
import manifold.xml.rt.parser.XmlElement;
import static manifold.json.rt.Json.indent;
import static manifold.json.rt.Json.toBindings;
public class Xml
{
public static final String XML_DEFAULT_ROOT = "root_object";
public static final String XML_ELEM_CONTENT = "textContent";
public static String toXml( Object jsonValue )
{
StringBuilder sb = new StringBuilder();
jsonValue = toBindings( jsonValue );
if( jsonValue instanceof Map )
{
toXml( jsonValue, null, sb, 0 );
}
else if( jsonValue instanceof Iterable )
{
toXml( jsonValue, "list", sb, 0 );
}
else
{
toXml( jsonValue, "item", sb, 0 );
}
return sb.toString();
}
public static void toXml( Object jsonValue, String name, StringBuilder target, int indent )
{
jsonValue = toBindings( jsonValue );
if( jsonValue instanceof Map )
{
if( name == null )
{
Map map = (Map)jsonValue;
if( map.size() == 1 )
{
// single entry with no name implies root, defer to the root
Object rootKey = map.keySet().iterator().next();
Object rootValue = map.get( rootKey );
if( rootValue instanceof Pair )
{
rootValue = ((Pair)rootValue).getSecond();
}
toXml( rootValue, rootKey.toString(), target, indent );
return;
}
else
{
//todo: factor out Xml.XML_DEFAULT_ROOT
name = "root_object";
}
}
toXml( (Map)jsonValue, name, target, indent );
}
else if( jsonValue instanceof Iterable )
{
toXml( (Iterable)jsonValue, name, target, indent );
}
else
{
toXml( String.valueOf( jsonValue ), name, target, indent );
}
}
/**
* Serializes this {@link Map} instance into an XML formatted StringBuilder {@code target}
* with the specified {@code indent} of spaces.
*
* @param name The name of the root element to nest the Map XML
* @param target A {@link StringBuilder} to write the XML in
* @param indent The margin of spaces to indent the XML
*/
private static void toXml( Map bindings, String name, StringBuilder target, int indent )
{
indent( target, indent );
target.append( '<' ).append( name );
if( bindings.size() > 0 )
{
for( Object key: bindings.keySet() )
{
Object value = bindings.get( key );
if( value instanceof Pair )
{
value = ((Pair)value).getSecond();
}
value = toBindings( value );
if( !(value instanceof Map) && !(value instanceof Iterable) && !key.equals( XML_ELEM_CONTENT ) )
{
target.append( " " ).append( key ).append( "=\"" ).append( value ).append( '"' );
}
}
int count = 0;
for( Object key: bindings.keySet() )
{
Object value = bindings.get( key );
if( value instanceof Pair )
{
value = ((Pair)value).getSecond();
}
value = toBindings( value );
if( value instanceof Map )
{
if( count == 0 )
{
target.append( ">\n" );
}
toXml( (Map)value, key.toString(), target, indent + 2 );
count++;
}
else if( value instanceof Iterable )
{
if( count == 0 )
{
target.append( ">\n" );
}
toXml( (Iterable)value, key.toString(), target, indent + 2 );
count++;
}
else if( value instanceof String && key.equals( XML_ELEM_CONTENT ) )
{
if( count == 0 )
{
target.append( ">\n" );
}
indent( target, indent + 2 );
target.append( value ).append( "\n" );
count++;
}
}
if( count == 0 )
{
target.append( "/>\n" );
}
else
{
indent( target, indent );
target.append( "</" ).append( name ).append( ">\n" );
}
}
else
{
target.append( "/>\n" );
}
}
private static void toXml( Iterable value, String name, StringBuilder target, int indent )
{
for( Object comp: value )
{
if( comp instanceof Pair )
{
comp = ((Pair)comp).getSecond();
}
comp = toBindings( comp );
if( comp instanceof Map )
{
toXml( (Map)comp, name, target, indent );
}
else if( comp instanceof Iterable )
{
toXml( (Iterable)comp, name, target, indent );
}
else
{
toXml( String.valueOf( comp ), name, target, indent );
}
}
}
private static void toXml( String value, String name, StringBuilder target, int indent )
{
indent( target, indent );
target.append( '<' ).append( name ).append( ">" );
target.append( value );
target.append( "</" ).append( name ).append( ">\n" );
}
public static Bindings fromXml( String xml )
{
return fromXml( xml, false );
}
public static Bindings fromXml( String xml, boolean withTokens )
{
try( InputStream inputStream = new BufferedInputStream( new ByteArrayInputStream( xml.getBytes() ) ) )
{
XmlElement elem = XmlParser.parse( inputStream );
DataBindings bindings = transform( new DataBindings(), elem, withTokens );
if( bindings.size() == 1 )
{
Object root = bindings.get( XML_DEFAULT_ROOT );
if( root instanceof DataBindings )
{
bindings = (DataBindings)bindings.get( XML_DEFAULT_ROOT );
}
}
return bindings;
}
catch( IOException e )
{
throw new RuntimeException( e );
}
}
private static DataBindings transform( DataBindings parent, XmlElement elem, boolean withTokens )
{
// Add to parent
DataBindings children = new DataBindings();
parent.put( elem.getName().getRawText(), withTokens ? makeTokensValue( elem, children ) : children );
// Attributes
for( Map.Entry<String, XmlAttribute> entry: elem.getAttributes().entrySet() )
{
children.put( entry.getKey(), withTokens ? makeTokensValue( entry.getValue() ) : entry.getValue().getValue() );
}
// Element text
if( elem.getRawContent() != null )
{
children.put( XML_ELEM_CONTENT, elem.getRawContent().getRawText().trim() );
}
// Child Elements
Map<String, List<DataBindings>> map = new LinkedHashMap<>();
for( XmlElement child: elem.getChildren() )
{
map.computeIfAbsent( child.getName().getRawText(), k -> new ArrayList<>() )
.add( transform( new DataBindings(), child, withTokens ) );
}
for( Map.Entry<String, List<DataBindings>> entry: map.entrySet() )
{
List<DataBindings> list = entry.getValue();
if( list.size() == 1 )
{
children.putAll( list.get( 0 ) );
}
else
{
// Duplicates are put into a list and indirectly exposed through it
List<Object> listValues = list.stream().map( e -> e.get( entry.getKey() ) ).collect( Collectors.toList() );
children.put( entry.getKey(), withTokens ? makeTokensValue( listValues ) : listValues );
}
}
return parent;
}
private static Object makeTokensValue( XmlElement elem, Bindings value )
{
Token keyToken = makeToken( elem.getName() );
return new Pair<>( new Token[]{keyToken, null}, value );
}
private static Object makeTokensValue( List<Object> value )
{
Object item = value.get( 0 );
if( item instanceof Pair )
{
// Use the location of the first occurrence
return new Pair<>( ((Pair)item).getFirst(), value );
}
return value;
}
private static Object makeTokensValue( XmlAttribute attr )
{
Token keyToken = makeToken( attr.getName() );
XmlTerminal rawValue = attr.getRawValue();
Token valueToken = rawValue == null ? null : makeToken( rawValue );
return new Pair<>( new Token[]{keyToken, valueToken}, attr.getValue() );
}
private static Token makeToken( XmlTerminal value )
{
return new Token( TokenType.STRING, value.getRawText(), value.getOffset(), value.getLine(), -1 );
}
}
| 3,784 |
677 | package org.caffinitas.ohc.linked;
import org.caffinitas.ohc.Eviction;
import org.caffinitas.ohc.HashAlgorithm;
import org.caffinitas.ohc.OHCache;
import org.caffinitas.ohc.OHCacheStats;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.io.IOException;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
public class CrossCheckCapacityTest extends CrossCheckTestBase {
@Test(dataProvider = "types")
public void testFreeCapacity(Eviction eviction, HashAlgorithm hashAlgorithm) throws Exception
{
try (OHCache<Integer, String> cache = cache(eviction, hashAlgorithm))
{
long cap = cache.capacity();
cache.put(42, "foo");
long free1 = cache.freeCapacity();
assertTrue(cap > free1);
cache.put(11, "bar baz");
long free2 = cache.freeCapacity();
assertTrue(free1 > free2);
assertTrue(cap > free2);
cache.put(11, "bar baz dog mud forest");
long free3 = cache.freeCapacity();
assertTrue(free2 > free3);
assertTrue(cap > free3);
cache.remove(11);
long free4 = cache.freeCapacity();
Assert.assertEquals(free1, free4);
assertTrue(cap > free4);
cache.remove(42);
long free5 = cache.freeCapacity();
Assert.assertEquals(free5, cap);
}
}
@Test(dataProvider = "types")
public void testSetCapacity(Eviction eviction, HashAlgorithm hashAlgorithm) throws Exception
{
try (OHCache<Integer, String> cache = cache(eviction, hashAlgorithm))
{
long cap = cache.capacity();
cache.put(42, "foo");
long free = cache.freeCapacity();
cache.setCapacity(cap + TestUtils.ONE_MB);
Assert.assertEquals(cache.capacity(), cap + TestUtils.ONE_MB);
Assert.assertEquals(cache.freeCapacity(), free + TestUtils.ONE_MB);
cache.setCapacity(cap - TestUtils.ONE_MB);
Assert.assertEquals(cache.capacity(), cap - TestUtils.ONE_MB);
Assert.assertEquals(cache.freeCapacity(), free - TestUtils.ONE_MB);
cache.setCapacity(0L);
Assert.assertEquals(cache.capacity(), 0L);
assertTrue(cache.freeCapacity() < 0L);
Assert.assertEquals(cache.size(), 1);
cache.put(42, "bar");
Assert.assertEquals(cache.size(), 0);
Assert.assertEquals(cache.freeCapacity(), 0L);
}
}
@Test(dataProvider = "types")
public void testResetStatistics(Eviction eviction, HashAlgorithm hashAlgorithm) throws IOException
{
try (OHCache<Integer, String> cache = cache(eviction, hashAlgorithm))
{
for (int i = 0; i < 100; i++)
cache.put(i, Integer.toString(i));
for (int i = 0; i < 30; i++)
cache.put(i, Integer.toString(i));
for (int i = 0; i < 50; i++)
cache.get(i);
for (int i = 100; i < 120; i++)
cache.get(i);
for (int i = 0; i < 25; i++)
cache.remove(i);
OHCacheStats stats = cache.stats();
Assert.assertEquals(stats.getPutAddCount(), 100);
Assert.assertEquals(stats.getPutReplaceCount(), 30);
Assert.assertEquals(stats.getHitCount(), 50);
Assert.assertEquals(stats.getMissCount(), 20);
Assert.assertEquals(stats.getRemoveCount(), 25);
cache.resetStatistics();
stats = cache.stats();
Assert.assertEquals(stats.getPutAddCount(), 0);
Assert.assertEquals(stats.getPutReplaceCount(), 0);
Assert.assertEquals(stats.getHitCount(), 0);
Assert.assertEquals(stats.getMissCount(), 0);
Assert.assertEquals(stats.getRemoveCount(), 0);
}
}
@Test(dataProvider = "types")
public void testTooBigEntryOnPut(Eviction eviction, HashAlgorithm hashAlgorithm) throws IOException
{
try (OHCache<Integer, String> cache = cache(eviction, hashAlgorithm, 8, -1, -1, Util.roundUpTo8(TestUtils.intSerializer.serializedSize(1)) + Util.ENTRY_OFF_DATA + 5))
{
cache.put(1, new String(new byte[100]));
Assert.assertEquals(cache.size(), 0);
cache.putIfAbsent(1, new String(new byte[100]));
Assert.assertEquals(cache.size(), 0);
cache.addOrReplace(1, "foo", new String(new byte[100]));
Assert.assertEquals(cache.size(), 0);
cache.addOrReplace(1, "bar", "foo");
Assert.assertEquals(cache.size(), 1);
Assert.assertEquals(cache.get(1), "foo");
cache.addOrReplace(1, "foo", new String(new byte[100]));
Assert.assertEquals(cache.size(), 0);
Assert.assertEquals(cache.get(1), null);
}
}
@Test(dataProvider = "none")
public void testEvictionNone(Eviction eviction, HashAlgorithm hashAlgorithm) throws IOException
{
try (OHCache<Integer, String> cache = cache(eviction, hashAlgorithm, 1, -1, 1, -1))
{
String v = longString();
int i = 0;
for (; cache.freeCapacity() >= 1000; i++)
assertTrue(cache.put(i++, v));
assertFalse(cache.put(i++, v));
cache.remove(0);
assertTrue(cache.put(i++, v));
assertFalse(cache.put(i++, v));
}
}
}
| 2,599 |
2,542 | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#pragma once
namespace LoggingReplicatorTests
{
class TestStateStream final
: public TxnReplicator::OperationDataStream
{
K_FORCE_SHARED(TestStateStream)
public:
static TestStateStream::SPtr Create(__in KAllocator & allocator, __in ULONG32 successfulOperationCount);
ktl::Awaitable<NTSTATUS> GetNextAsync(
__in ktl::CancellationToken const & cancellationToken,
__out Data::Utilities::OperationData::CSPtr & result) noexcept override;
void Dispose() override;
private:
TestStateStream(__in ULONG32 successfulOperationCount);
ULONG32 successfulOperationCount_;
ULONG32 currentOperationCount_;
};
}
| 323 |
2,219 | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef QUICHE_QUIC_PLATFORM_API_QUIC_MEM_SLICE_STORAGE_H_
#define QUICHE_QUIC_PLATFORM_API_QUIC_MEM_SLICE_STORAGE_H_
#include "quic/platform/api/quic_export.h"
#include "net/quic/platform/impl/quic_mem_slice_storage_impl.h"
namespace quic {
// QuicMemSliceStorage is a container class that store QuicMemSlices for further
// use cases such as turning into QuicMemSliceSpan.
class QUIC_EXPORT_PRIVATE QuicMemSliceStorage {
public:
QuicMemSliceStorage(const struct iovec* iov,
int iov_count,
QuicBufferAllocator* allocator,
const QuicByteCount max_slice_len)
: impl_(iov, iov_count, allocator, max_slice_len) {}
QuicMemSliceStorage(const QuicMemSliceStorage& other) = default;
QuicMemSliceStorage& operator=(const QuicMemSliceStorage& other) = default;
QuicMemSliceStorage(QuicMemSliceStorage&& other) = default;
QuicMemSliceStorage& operator=(QuicMemSliceStorage&& other) = default;
~QuicMemSliceStorage() = default;
// Return a QuicMemSliceSpan form of the storage.
QuicMemSliceSpan ToSpan() { return impl_.ToSpan(); }
void Append(QuicMemSlice slice) { impl_.Append(std::move(*slice.impl())); }
private:
QuicMemSliceStorageImpl impl_;
};
} // namespace quic
#endif // QUICHE_QUIC_PLATFORM_API_QUIC_MEM_SLICE_STORAGE_H_
| 585 |
357 | <reponame>sgravrock/cedar
#import <Foundation/Foundation.h>
#import "CDRNullabilityCompat.h"
#import "CDRFake.h"
#import "CedarDouble.h"
NS_ASSUME_NONNULL_BEGIN
#ifdef __cplusplus
@interface CDRClassFake : CDRFake
@end
id CDR_fake_for(BOOL require_explicit_stubs, Class klass, ...);
#endif // __cplusplus
NS_ASSUME_NONNULL_END
| 141 |
988 | /*
* The contents of this file are subject to the Interbase Public
* License Version 1.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.Inprise.com/IPL.html
*
* Software distributed under the License is distributed on an
* "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express
* or implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code was created by Inprise Corporation
* and its predecessors. Portions created by Inprise Corporation are
* Copyright (C) Inprise Corporation.
*
* All Rights Reserved.
* Contributor(s): ______________________________________.
*
*/
// contains the main() and not shared routines for fbguard
#include "firebird.h"
#include <stdio.h>
#ifdef HAVE_STRING_H
#include <string.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#ifdef HAVE_SYS_STAT_H
#include <sys/stat.h>
#endif
#ifdef HAVE_ERRNO_H
#include <errno.h>
#else
int errno = -1;
#endif
#include <time.h>
#include "../common/os/divorce.h"
#include "../common/os/os_utils.h"
#include "../common/isc_proto.h"
#include "../yvalve/gds_proto.h"
#include "../common/file_params.h"
#include "../utilities/guard/util_proto.h"
#include "../common/classes/fb_string.h"
const USHORT FOREVER = 1;
const USHORT ONETIME = 2;
const USHORT IGNORE = 3;
const USHORT NORMAL_EXIT= 0;
const char* const SERVER_BINARY = "firebird";
const char* const GUARD_FILE = "fb_guard";
volatile sig_atomic_t shutting_down;
void shutdown_handler(int)
{
shutting_down = 1;
}
int CLIB_ROUTINE main( int argc, char **argv)
{
/**************************************
*
* m a i n
*
**************************************
*
* Functional description
* The main for fbguard. This process is used to start
* the standalone server and keep it running after an abnormal termination.
*
**************************************/
USHORT option = FOREVER; // holds FOREVER or ONETIME or IGNORE
bool done = true;
bool daemon = false;
const TEXT* prog_name = argv[0];
const TEXT* pidfilename = 0;
int guard_exit_code = 0;
const TEXT* const* const end = argc + argv;
argv++;
while (argv < end)
{
const TEXT* p = *argv++;
if (*p++ == '-')
switch (UPPER(*p))
{
case 'D':
daemon = true;
break;
case 'F':
option = FOREVER;
break;
case 'O':
option = ONETIME;
break;
case 'S':
option = IGNORE;
break;
case 'P':
pidfilename = *argv++;
break;
default:
fprintf(stderr,
"Usage: %s [-signore | -onetime | -forever (default)] [-daemon] [-pidfile filename]\n",
prog_name);
exit(-1);
break;
}
} // while
// get and set the umask for the current process
const ULONG new_mask = 0007;
const ULONG old_mask = umask(new_mask);
// exclusive lock the file
int fd_guard;
if ((fd_guard = UTIL_ex_lock(GUARD_FILE)) < 0)
{
// could not get exclusive lock -- some other guardian is running
if (fd_guard == -2)
fprintf(stderr, "%s: Program is already running.\n", prog_name);
exit(-3);
}
// the umask back to orignal donot want to carry this to child process
umask(old_mask);
// move the server name into the argument to be passed
TEXT process_name[1024];
process_name[0] = '\0';
TEXT* server_args[2];
server_args[0] = process_name;
server_args[1] = NULL;
shutting_down = 0;
if (UTIL_set_handler(SIGTERM, shutdown_handler, false) < 0)
{
fprintf(stderr, "%s: Cannot set signal handler (error %d).\n", prog_name, errno);
exit(-5);
}
if (UTIL_set_handler(SIGINT, shutdown_handler, false) < 0)
{
fprintf(stderr, "%s: Cannot set signal handler (error %d).\n", prog_name, errno);
exit(-5);
}
// detach from controlling tty
if (daemon && fork()) {
exit(0);
}
// Keep stdout and stderr opened and let server emit output
// or redirect stdout/stderr to /dev/null or file by user choice
// If we want to daemonize - close all fds and let child to reopen it.
int mask = 0; // FD_ZERO(&mask);
mask |= daemon ? 0 : (1 << 1 | 1 << 2); // FD_SET(1, &mask); FD_SET(2, &mask);
divorce_terminal(mask);
time_t timer = 0;
do {
int ret_code;
if (shutting_down)
{
// don't start a child
break;
}
if (timer == time(0))
{
// don't let server restart too often - avoid log overflow
sleep(1);
continue;
}
timer = time(0);
pid_t child_pid =
UTIL_start_process(SERVER_BINARY, server_args, prog_name);
if (child_pid == -1)
{
// could not fork the server
gds__log("%s: guardian could not start server\n", prog_name/*, process_name*/);
fprintf(stderr, "%s: Could not start server\n", prog_name/*, process_name*/);
UTIL_ex_unlock(fd_guard);
exit(-4);
}
if (pidfilename)
{
FILE *pf = os_utils::fopen(pidfilename, "w");
if (pf)
{
fprintf(pf, "%d", child_pid);
fclose(pf);
}
else
{
gds__log("%s: guardian could not open %s for writing, error %d\n",
prog_name, pidfilename, errno);
}
}
// wait for child to die, and evaluate exit status
bool shutdown_child = true;
if (!shutting_down)
{
ret_code = UTIL_wait_for_child(child_pid, shutting_down);
shutdown_child = (ret_code == -2);
}
if (shutting_down)
{
if (shutdown_child)
{
ret_code = UTIL_shutdown_child(child_pid, 3, 1);
if (ret_code < 0)
{
gds__log("%s: error while shutting down %s (%d)\n",
prog_name, process_name, errno);
guard_exit_code = -6;
}
else if (ret_code == 1) {
gds__log("%s: %s killed (did not terminate)\n", prog_name, process_name);
}
else if (ret_code == 2) {
gds__log("%s: unable to shutdown %s\n", prog_name, process_name);
}
else {
gds__log("%s: %s terminated\n", prog_name, process_name);
}
}
break;
}
if (ret_code != NORMAL_EXIT)
{
// check for startup error
if (ret_code == STARTUP_ERROR)
{
gds__log("%s: %s terminated due to startup error (%d)\n",
prog_name, process_name, ret_code);
if (option == IGNORE)
{
gds__log("%s: %s terminated due to startup error (%d)\n Trying again\n",
prog_name, process_name, ret_code);
done = false; // Try it again, Sam (even if it is a startup error) FSG 8.11.2000
}
else
{
gds__log("%s: %s terminated due to startup error (%d)\n",
prog_name, process_name, ret_code);
done = true; // do not restart we have a startup problem
}
}
else
{
gds__log("%s: %s terminated abnormally (%d)\n", prog_name, process_name, ret_code);
if (option == FOREVER || option == IGNORE)
done = false;
}
}
else
{
// Normal shutdown - don't restart the server
gds__log("%s: %s normal shutdown.\n", prog_name, process_name);
done = true;
}
} while (!done);
if (pidfilename) {
remove(pidfilename);
}
UTIL_ex_unlock(fd_guard);
exit(guard_exit_code);
} // main
| 2,869 |
3,702 | /*
* 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 app.metatron.discovery.domain.activities.spec;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.joda.time.DateTime;
/**
* https://www.w3.org/TR/activitystreams-core
*/
public class ActivityStreamV2 {
/**
*
*/
@JsonProperty("@context")
String context;
/**
*
*/
String id;
/**
*
*/
String type;
/**
*
*/
String name;
/**
*
*/
Actor actor;
/**
*
*/
ActivityObject object;
/**
*
*/
ActivityObject target;
/**
*
*/
ActivityGenerator generator;
/**
*
*/
DateTime published;
@JsonCreator
public ActivityStreamV2(@JsonProperty("@context") String context,
@JsonProperty("id") String id,
@JsonProperty(value = "type", required = true) String type,
@JsonProperty("name") String name,
@JsonProperty("actor") Actor actor,
@JsonProperty("object") ActivityObject object,
@JsonProperty("target") ActivityObject target,
@JsonProperty("generator") ActivityGenerator generator,
@JsonProperty("published") DateTime published) {
this.context = context;
this.id = id;
this.type = type;
this.name = name;
this.actor = actor;
this.object = object;
this.target = target;
this.generator = generator;
this.published = published;
}
public String getContext() {
return context;
}
public String getId() {
return id;
}
public String getType() {
return type;
}
public String getName() {
return name;
}
public Actor getActor() {
return actor;
}
public ActivityObject getObject() {
return object;
}
public ActivityObject getTarget() {
return target;
}
public ActivityGenerator getGenerator() {
return generator;
}
public DateTime getPublished() {
return published;
}
}
| 996 |
1,016 | package com.thinkbiganalytics.spark.dataprofiler.testcases;
/*-
* #%L
* thinkbig-spark-job-profiler-app
* %%
* Copyright (C) 2017 ThinkBig Analytics
* %%
* 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.
* #L%
*/
import com.thinkbiganalytics.spark.dataprofiler.ProfilerConfiguration;
import com.thinkbiganalytics.spark.dataprofiler.columns.TimestampColumnStatistics;
import com.thinkbiganalytics.spark.dataprofiler.core.ProfilerTest;
import com.thinkbiganalytics.spark.dataprofiler.output.OutputRow;
import org.apache.spark.sql.types.DataTypes;
import org.joda.time.DateTime;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import java.sql.Timestamp;
import java.util.List;
/**
* Timestamp Column Statistics Test Case
*/
public class TimestampColumnCase2Test extends ProfilerTest {
@BeforeClass
public static void setUpClass() {
System.out.println("\t*** Starting run for TimestampColumnCase2Test ***");
}
@AfterClass
public static void tearDownClass() {
System.out.println("\t*** Completed run for TimestampColumnCase2Test ***");
}
/**
* Verify accommodating column values.
*/
@Test
public void accomodate() {
final ProfilerConfiguration profilerConfiguration = new ProfilerConfiguration();
profilerConfiguration.setNumberOfTopNValues(3);
// Test with a null value
TimestampColumnStatistics stats = new TimestampColumnStatistics(DataTypes.createStructField("ts", DataTypes.TimestampType, true), profilerConfiguration);
stats.accomodate(null, 1L);
Assert.assertNull(stats.getMaxTimestamp());
Assert.assertNull(stats.getMinTimestamp());
// Test with uninitialized max & min
stats.accomodate("2016-06-27 14:04:30", 1L);
Timestamp ts1 = new Timestamp(new DateTime(2016, 6, 27, 14, 4, 30).getMillis());
Assert.assertEquals(ts1, stats.getMaxTimestamp());
Assert.assertEquals(ts1, stats.getMinTimestamp());
// Test with a later timestamp
stats.accomodate("2016-06-27 14:04:31", 1L);
Timestamp ts2 = new Timestamp(new DateTime(2016, 6, 27, 14, 4, 31).getMillis());
Assert.assertEquals(ts2, stats.getMaxTimestamp());
Assert.assertEquals(ts1, stats.getMinTimestamp());
// Test with an earlier timestamp
stats.accomodate("2016-06-27 14:04:29", 1L);
Timestamp ts3 = new Timestamp(new DateTime(2016, 6, 27, 14, 4, 29).getMillis());
Assert.assertEquals(ts2, stats.getMaxTimestamp());
Assert.assertEquals(ts3, stats.getMinTimestamp());
}
/**
* Verify combining statistics.
*/
@Test
public void combine() {
final ProfilerConfiguration profilerConfiguration = new ProfilerConfiguration();
profilerConfiguration.setNumberOfTopNValues(3);
// Test when 'this' is empty
TimestampColumnStatistics other = new TimestampColumnStatistics(DataTypes.createStructField("ts", DataTypes.TimestampType, true), profilerConfiguration);
TimestampColumnStatistics stats = new TimestampColumnStatistics(DataTypes.createStructField("ts", DataTypes.TimestampType, true), profilerConfiguration);
other.accomodate("2016-06-27 14:04:30", 1L);
stats.combine(other);
Timestamp ts1 = new Timestamp(new DateTime(2016, 6, 27, 14, 4, 30).getMillis());
Assert.assertEquals(ts1, stats.getMaxTimestamp());
Assert.assertEquals(ts1, stats.getMinTimestamp());
// Test when other is empty
other = new TimestampColumnStatistics(DataTypes.createStructField("ts", DataTypes.TimestampType, true), profilerConfiguration);
stats.combine(other);
Assert.assertEquals(ts1, stats.getMaxTimestamp());
Assert.assertEquals(ts1, stats.getMinTimestamp());
// Test when other has later timestamp
other.accomodate("2016-06-27 14:04:31", 1L);
stats.combine(other);
Timestamp ts2 = new Timestamp(new DateTime(2016, 6, 27, 14, 4, 31).getMillis());
Assert.assertEquals(ts2, stats.getMaxTimestamp());
Assert.assertEquals(ts1, stats.getMinTimestamp());
// Test when other has earlier timestamp
other.accomodate("2016-06-27 14:04:29", 1L);
stats.combine(other);
Timestamp ts3 = new Timestamp(new DateTime(2016, 6, 27, 14, 4, 29).getMillis());
Assert.assertEquals(ts2, stats.getMaxTimestamp());
Assert.assertEquals(ts3, stats.getMinTimestamp());
}
/**
* Verify statistics string.
*/
@Test
public void getVerboseStatistics() {
final ProfilerConfiguration profilerConfiguration = new ProfilerConfiguration();
profilerConfiguration.setNumberOfTopNValues(3);
// Test when empty
TimestampColumnStatistics stats = new TimestampColumnStatistics(DataTypes.createStructField("ts", DataTypes.TimestampType, true), profilerConfiguration);
String expected = "{\nColumnInfo [name=ts, datatype=timestamp, nullable=true, metadata={}]\n"
+ "CommonStatistics [nullCount=0, totalCount=0, uniqueCount=0, percNullValues=0, percUniqueValues=0, percDuplicateValues=0]\n"
+ "Top 3 values [\n]\n"
+ "TimestampColumnStatistics [maxTimestamp=, minTimestamp=]\n}";
Assert.assertEquals(expected, stats.getVerboseStatistics());
// Test with multiple values
stats.accomodate("", 1L);
stats.accomodate("2016-06-27 14:04:29", 1L);
stats.accomodate("2016-06-27 14:04:30", 1L);
stats.accomodate("2016-06-27 14:04:31", 1L);
stats.accomodate(null, 1L);
expected = "{\nColumnInfo [name=ts, datatype=timestamp, nullable=true, metadata={}]\n"
+ "CommonStatistics [nullCount=1, totalCount=5, uniqueCount=5, percNullValues=20, percUniqueValues=100, percDuplicateValues=0]\n"
+ "Top 3 values [\n1^A^A1^B2^A2016-06-27 14:04:29^A1^B3^A2016-06-27 14:04:30^A1^B]\n"
+ "TimestampColumnStatistics [maxTimestamp=2016-06-27 14:04:31.0, minTimestamp=2016-06-27 14:04:29.0]\n}";
Assert.assertEquals(expected, stats.getVerboseStatistics());
}
/**
* Verify writing statistics.
*/
@Test
public void writeStatistics() {
final ProfilerConfiguration profilerConfiguration = new ProfilerConfiguration();
profilerConfiguration.setNumberOfTopNValues(3);
// Test when empty
TimestampColumnStatistics stats = new TimestampColumnStatistics(DataTypes.createStructField("ts", DataTypes.TimestampType, true), profilerConfiguration);
List<OutputRow> rows = stats.getStatistics();
Assert.assertEquals(12, rows.size());
Assert.assertEquals("OutputRow [columnName=ts, metricType=COLUMN_DATATYPE, metricValue=TimestampType]", rows.get(0).toString());
Assert.assertEquals("OutputRow [columnName=ts, metricType=COLUMN_NULLABLE, metricValue=true]", rows.get(1).toString());
Assert.assertEquals("OutputRow [columnName=ts, metricType=COLUMN_METADATA, metricValue={}]", rows.get(2).toString());
Assert.assertEquals("OutputRow [columnName=ts, metricType=NULL_COUNT, metricValue=0]", rows.get(3).toString());
Assert.assertEquals("OutputRow [columnName=ts, metricType=TOTAL_COUNT, metricValue=0]", rows.get(4).toString());
Assert.assertEquals("OutputRow [columnName=ts, metricType=UNIQUE_COUNT, metricValue=0]", rows.get(5).toString());
Assert.assertEquals("OutputRow [columnName=ts, metricType=PERC_NULL_VALUES, metricValue=0]", rows.get(6).toString());
Assert.assertEquals("OutputRow [columnName=ts, metricType=PERC_UNIQUE_VALUES, metricValue=0]", rows.get(7).toString());
Assert.assertEquals("OutputRow [columnName=ts, metricType=PERC_DUPLICATE_VALUES, metricValue=0]", rows.get(8).toString());
Assert.assertEquals("OutputRow [columnName=ts, metricType=TOP_N_VALUES, metricValue=]", rows.get(9).toString());
Assert.assertEquals("OutputRow [columnName=ts, metricType=MAX_TIMESTAMP, metricValue=]", rows.get(10).toString());
Assert.assertEquals("OutputRow [columnName=ts, metricType=MIN_TIMESTAMP, metricValue=]", rows.get(11).toString());
// Test with multiple values
stats = new TimestampColumnStatistics(DataTypes.createStructField("ts", DataTypes.TimestampType, true), profilerConfiguration);
stats.accomodate("", 1L);
stats.accomodate("2016-06-27 14:04:29", 1L);
stats.accomodate("2016-06-27 14:04:30", 1L);
stats.accomodate("2016-06-27 14:04:31", 1L);
stats.accomodate(null, 1L);
rows = stats.getStatistics();
Assert.assertEquals(12, rows.size());
Assert.assertEquals("OutputRow [columnName=ts, metricType=COLUMN_DATATYPE, metricValue=TimestampType]", rows.get(0).toString());
Assert.assertEquals("OutputRow [columnName=ts, metricType=COLUMN_NULLABLE, metricValue=true]", rows.get(1).toString());
Assert.assertEquals("OutputRow [columnName=ts, metricType=COLUMN_METADATA, metricValue={}]", rows.get(2).toString());
Assert.assertEquals("OutputRow [columnName=ts, metricType=NULL_COUNT, metricValue=1]", rows.get(3).toString());
Assert.assertEquals("OutputRow [columnName=ts, metricType=TOTAL_COUNT, metricValue=5]", rows.get(4).toString());
Assert.assertEquals("OutputRow [columnName=ts, metricType=UNIQUE_COUNT, metricValue=5]", rows.get(5).toString());
Assert.assertEquals("OutputRow [columnName=ts, metricType=PERC_NULL_VALUES, metricValue=20]", rows.get(6).toString());
Assert.assertEquals("OutputRow [columnName=ts, metricType=PERC_UNIQUE_VALUES, metricValue=100]", rows.get(7).toString());
Assert.assertEquals("OutputRow [columnName=ts, metricType=PERC_DUPLICATE_VALUES, metricValue=0]", rows.get(8).toString());
Assert.assertEquals("OutputRow [columnName=ts, metricType=TOP_N_VALUES, metricValue=1^A^A1^B2^A2016-06-27 14:04:29^A1^B3^A2016-06-27 14:04:30^A1^B]", rows.get(9).toString());
Assert.assertEquals("OutputRow [columnName=ts, metricType=MAX_TIMESTAMP, metricValue=2016-06-27 14:04:31.0]", rows.get(10).toString());
Assert.assertEquals("OutputRow [columnName=ts, metricType=MIN_TIMESTAMP, metricValue=2016-06-27 14:04:29.0]", rows.get(11).toString());
}
}
| 4,243 |
496 | <filename>apm-agent-plugins/apm-okhttp-plugin/src/test/java/co/elastic/apm/agent/okhttp/OkHttp3ClientInstrumentationTest.java
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. 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 co.elastic.apm.agent.okhttp;
import co.elastic.apm.agent.httpclient.AbstractHttpClientInstrumentationTest;
import co.elastic.apm.agent.util.Version;
import co.elastic.apm.agent.util.VersionUtils;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import org.junit.Before;
import java.util.Objects;
public class OkHttp3ClientInstrumentationTest extends AbstractHttpClientInstrumentationTest {
private Version okhttpVersion;
private OkHttpClient client;
@Before
public void setUp() {
client = new OkHttpClient();
String versionString = VersionUtils.getVersion(OkHttpClient.class, "com.squareup.okhttp3", "okhttp");
okhttpVersion = Version.of(Objects.requireNonNullElse(versionString, "4.0.0"));
}
@Override
protected boolean isErrorOnCircularRedirectSupported() {
return okhttpVersion.compareTo(Version.of("3.6.0")) > -1;
}
@Override
protected boolean isIpv6Supported() {
return okhttpVersion.compareTo(Version.of("3.3.0")) > -1;
}
@Override
protected void performGet(String path) throws Exception {
Request request = new Request.Builder()
.url(path)
.build();
client.newCall(request).execute().body().close();
}
}
| 715 |
325 | package com.box.l10n.mojito.aspect;
import com.google.common.base.Stopwatch;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Simple aspect to log time spent in a function.
*
* @author jeanaurambault
*/
@Aspect
public class StopWatchAspect {
/**
* logger
*/
static Logger logger = LoggerFactory.getLogger(StopWatchAspect.class);
@Around("methods()")
public Object mesureTime(ProceedingJoinPoint pjp) throws Throwable {
Stopwatch stopwatch = Stopwatch.createStarted();
Object res = pjp.proceed();
stopwatch.stop();
logger.debug("{}#{} took: {}", pjp.getSignature().getDeclaringTypeName(), pjp.getSignature().getName(), stopwatch.toString());
return res;
}
@Pointcut("execution(@com.box.l10n.mojito.aspect.StopWatch * *(..))")
private void methods() {
}
}
| 438 |
14,668 | <gh_stars>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.
#ifndef REMOTING_HOST_WIN_EVALUATE_D3D_H_
#define REMOTING_HOST_WIN_EVALUATE_D3D_H_
#include <string>
#include <vector>
namespace remoting {
// Evaluates the D3D capability of the system and sends the results to stdout.
// DO NOT call this method within the host process. Only call in an isolated
// child process. I.e. from EvaluateCapabilityLocally().
int EvaluateD3D();
// Evaluates the D3D capability of the system in a separate process. Returns
// true if the process succeeded. The capabilities will be stored in |result|.
// Note, this is not a cheap call, it uses EvaluateCapability() internally to
// spawn a new process, which may take a noticeable amount of time.
bool GetD3DCapabilities(std::vector<std::string>* result);
// Used to ensure that pulling in the DirectX dependencies and creating a D3D
// Device does not result in a crash or system instability.
// Note: This is an expensive call as it creates a new process and blocks on it.
bool IsD3DAvailable();
} // namespace remoting
#endif // REMOTING_HOST_WIN_EVALUATE_D3D_H_
| 368 |
388 | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates.
* 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 AMAZON_KINESIS_PRODUCER_PROCESSING_STATISTICS_LOGGER_H
#define AMAZON_KINESIS_PRODUCER_PROCESSING_STATISTICS_LOGGER_H
#include <string>
#include <ostream>
#include <atomic>
#include <thread>
#include <aws/kinesis/core/put_records_context.h>
namespace aws {
namespace utils {
/**
* \brief Provides tracking of the reason a single occurred.
*
* This provides a simple way for the reducer to indicate the reason, or reasons, that a flush was triggered.
* The result of this class is consumed by flush_statistics_aggregator::merge to create the couting statistics
*/
class flush_statistics_context {
private:
bool is_manual_ = false; /** Set when the flush was manually triggered */
bool is_for_record_count_ = false; /** Set when the flush was triggered by the number of records in the container */
bool is_for_data_size_ = false; /** Set when the flush was triggered by the number of bytes in the container */
bool is_for_predicate_match_ = false; /** Set when the predicate was matched */
bool is_timed_ = false; /** Set when the flush is triggered by elapsed timer */
public:
bool manual() { return is_manual_; }
flush_statistics_context& manual(bool value);
bool record_count() { return is_for_record_count_; }
flush_statistics_context& record_count(bool value);
bool data_size() { return is_for_data_size_; }
flush_statistics_context& data_size(bool value);
bool predicate_match() { return is_for_predicate_match_; }
flush_statistics_context& predicate_match(bool value);
bool timed() { return is_timed_; }
flush_statistics_context& timed(bool value);
bool flush_required() {
return is_manual_ || is_for_record_count_ || is_for_data_size_ || is_for_predicate_match_ || is_timed_;
}
};
/**
* \brief Stores the counts for each flush reason.
*
* This stores the counts provided by individual flush activities, and handles reporting on the flush processes.
*/
class flush_statistics_aggregator {
public:
flush_statistics_aggregator(const std::string &stream_name, const std::string &input_type, const std::string &output_type);
void merge(flush_statistics_context &flush_reason, std::uint64_t input_records);
void reset();
flush_statistics_aggregator(const flush_statistics_aggregator &) = delete;
flush_statistics_aggregator(flush_statistics_aggregator &&) = delete;
private:
std::string stream_name_;
std::string input_type_;
std::string output_type_;
std::atomic<std::uint64_t> manual_;
std::atomic<std::uint64_t> record_count_;
std::atomic<std::uint64_t> data_size_;
std::atomic<std::uint64_t> predicate_match_;
std::atomic<std::uint64_t> timed_;
std::atomic<std::uint64_t> input_records_;
std::atomic<std::uint64_t> output_records_;
friend std::ostream &operator<<(std::ostream &os, const flush_statistics_aggregator &fs);
};
/**
* \brief Provides the display string for a flush_statistics_aggregator
*
* This provides a user readable display string the flush_statistics_aggregator. This is used by the
* processing_statistics_logger to display a flush_statistics_aggregator to the logging system.
*
* @param os
* @param fs
* @return os
*/
std::ostream &operator<<(std::ostream &os, const flush_statistics_aggregator &fs);
/**
* \brief Provides logging of flush statistics and request latency.
*
* This provides logging of for flush_statistics_aggregator, and for request latency. This tracks how long it
* takes from a PutRecordsRequest to be enqueued for processing, until it has been completed.
*/
class processing_statistics_logger {
public:
flush_statistics_aggregator &stage1() { return stage1_; }
flush_statistics_aggregator &stage2() { return stage2_; }
processing_statistics_logger(std::string& stream, const std::uint64_t max_buffer_time);
void request_complete(std::shared_ptr<aws::kinesis::core::PutRecordsContext> context);
private:
const std::string stream_;
flush_statistics_aggregator stage1_;
flush_statistics_aggregator stage2_;
const std::uint64_t max_buffer_time_;
std::atomic<std::uint64_t> total_time_;
std::atomic<std::uint64_t> total_requests_;
std::thread reporting_thread_;
std::atomic<bool> is_running_;
void reporting_loop();
};
}
}
#endif //AMAZON_KINESIS_PRODUCER_PROCESSING_STATISTICS_LOGGER_H
| 1,872 |
634 | <filename>modules/base/core-api/src/main/java/consulo/extensions/LocalizeValueConverter.java
/*
* Copyright 2013-2020 consulo.io
*
* 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 consulo.extensions;
import com.intellij.util.xmlb.Converter;
import consulo.localize.LocalizeManager;
import consulo.localize.LocalizeValue;
import javax.annotation.Nonnull;
/**
* @author VISTALL
* @since 2020-05-29
*/
public final class LocalizeValueConverter extends Converter<LocalizeValue> {
@Override
public LocalizeValue fromString(@Nonnull String value) {
return LocalizeManager.get().fromStringKey(value);
}
@Nonnull
@Override
public String toString(@Nonnull LocalizeValue localizeValue) {
throw new UnsupportedOperationException("We can't write localize value");
}
}
| 378 |
318 | <reponame>kangzai228/learning-power<filename>inside/Task/Mitmdump/Intercept/Weekly.py
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Author : lisztomania
# @Date : 2021/2/6
# @Software : Pycharm
# @Version : Python 3.8.5
# @File : Weekly.py
# @Function :
import base64
import json
import re
from random import randint
from typing import Dict
from inside.Task.Mitmdump.Intercept.ABC_Answer import ABC_ANSWER
__all__ = ['WEEKLY']
class WEEKLY(ABC_ANSWER):
"""每周答题拦截体"""
def Url_Put(self, url: str) -> bool:
"""
Url_Put(url: str) -> bool
提交判断
:param url: url
:return: bool
"""
return "https://pc-proxy-api.xuexi.cn/api/exam/service/practice" \
"/weekPracticeSubmitV3" == url
def Url_Res(self, url: str) -> bool:
"""
Url_Res(url: str) -> bool
答案判断
:param url: url
:return: bool
"""
res = "https://pc-proxy-api.xuexi.cn/api/exam/service/detail/queryV3" \
"\\?type=2&id=.*&forced=true"
if re.match(res, url):
return True
return False
def Extract(self, data: bytes) -> Dict:
"""
Extract(data: bytes) -> Dict
提取答案
:param data: 包含答案的字节数据
:return: Dict
"""
data = data.decode('utf-8')
data = json.loads(data)['data_str']
return json.loads(base64.b64decode(data).decode('utf-8'))
def Inject(self, data: bytes, res: Dict) -> bytes:
"""
Inject(data: bytes, res: Dict) -> bytes
注入答案
:param data: 原始提交数据
:param res: 包含答案数据
:return: 修改后的提交数据
"""
data = json.loads(data.decode('utf-8'))
data['uniqueId'] = res['uniqueId']
data['questions'].clear()
data['usedTime'] = randint(20, 50)
for question in res['questions']:
data['questions'].append(
{
'questionId': question['questionId'],
'answers': question['correct'],
'correct': True
}
)
return json.dumps(data).encode('utf-8')
| 1,193 |
2,151 | <gh_stars>1000+
// 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.
#ifndef ASH_STICKY_KEYS_STICKY_KEYS_OVERLAY_H_
#define ASH_STICKY_KEYS_STICKY_KEYS_OVERLAY_H_
#include <memory>
#include "ash/ash_export.h"
#include "ash/sticky_keys/sticky_keys_state.h"
#include "ui/compositor/layer_animation_observer.h"
#include "ui/events/event_constants.h"
#include "ui/gfx/geometry/size.h"
namespace gfx {
class Rect;
}
namespace views {
class Widget;
}
namespace ash {
class StickyKeysOverlayView;
// Controls the overlay UI for sticky keys, an accessibility feature allowing
// use of modifier keys without holding them down. This overlay will appear as
// a transparent window on the top left of the screen, showing the state of
// each sticky key modifier.
class ASH_EXPORT StickyKeysOverlay : public ui::ImplicitAnimationObserver {
public:
StickyKeysOverlay();
~StickyKeysOverlay() override;
// Shows or hides the overlay.
void Show(bool visible);
void SetModifierVisible(ui::EventFlags modifier, bool visible);
bool GetModifierVisible(ui::EventFlags modifier);
// Updates the overlay with the current state of a sticky key modifier.
void SetModifierKeyState(ui::EventFlags modifier, StickyKeyState state);
// Get the current state of the sticky key modifier in the overlay.
StickyKeyState GetModifierKeyState(ui::EventFlags modifier);
// Returns true if the overlay is currently visible. If the overlay is
// animating, the returned value is the target of the animation.
bool is_visible() { return is_visible_; }
// Returns the underlying views::Widget for testing purposes. The returned
// widget is owned by StickyKeysOverlay.
views::Widget* GetWidgetForTesting();
private:
// Returns the current bounds of the overlay, which is based on visibility.
gfx::Rect CalculateOverlayBounds();
// ui::ImplicitAnimationObserver:
void OnImplicitAnimationsCompleted() override;
bool is_visible_;
std::unique_ptr<views::Widget> overlay_widget_;
std::unique_ptr<StickyKeysOverlayView> overlay_view_;
gfx::Size widget_size_;
};
} // namespace ash
#endif // ASH_STICKY_KEYS_STICKY_KEYS_OVERLAY_H_
| 695 |
1,396 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jdbi.v3.core;
import java.util.concurrent.Callable;
import org.jdbi.v3.core.config.ConfigRegistry;
import org.jdbi.v3.core.extension.ExtensionMethod;
import org.jdbi.v3.core.extension.HandleSupplier;
import static org.jdbi.v3.core.internal.Invocations.invokeWith;
class ConstantHandleSupplier implements HandleSupplier {
private final Handle handle;
static HandleSupplier of(Handle handle) {
return new ConstantHandleSupplier(handle);
}
ConstantHandleSupplier(Handle handle) {
this.handle = handle;
}
@Override
public Jdbi getJdbi() {
return handle.getJdbi();
}
@Override
public ConfigRegistry getConfig() {
return handle.getConfig();
}
@Override
public Handle getHandle() {
return handle;
}
@Override
public <V> V invokeInContext(ExtensionMethod extensionMethod, ConfigRegistry config, Callable<V> task) throws Exception {
return invokeWith(
handle::getExtensionMethod,
handle::setExtensionMethod,
extensionMethod,
() -> invokeWith(
handle::getConfig,
handle::setConfig,
config,
task
)
);
}
}
| 677 |
562 | <reponame>rockandsalt/conan-center-index
#include <opengv/math/roots.hpp>
#include <vector>
#include <iostream>
int main() {
std::vector<double> poly {1.0, -2.0, -5.0, 6.0};
std::vector<double> computed_roots = opengv::math::o3_roots(poly);
std::vector<double> expected_roots {-2.0, 3.0, 1.0};
std::cout << "Computed roots: ";
for (auto i = computed_roots.begin(); i != computed_roots.end(); ++i)
std::cout << *i << ' ';
std::cout << std::endl;
std::cout << "Expected roots: ";
for (auto i = expected_roots.begin(); i != expected_roots.end(); ++i)
std::cout << *i << ' ';
std::cout << std::endl;
if (computed_roots != expected_roots) {
std::cout << "The calculated roots do not match the expected ones" << std::endl;
return 1;
}
std::cout << "Success" << std::endl;
return 0;
}
| 378 |
1,968 | <gh_stars>1000+
//
// Copyright (c) 2002-2011 The ANGLE Project 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 CROSSCOMPILERGLSL_OUTPUTGLSLBASE_H_
#define CROSSCOMPILERGLSL_OUTPUTGLSLBASE_H_
#include <set>
#include "compiler/ForLoopUnroll.h"
#include "compiler/intermediate.h"
#include "compiler/ParseHelper.h"
class TOutputGLSLBase : public TIntermTraverser
{
public:
TOutputGLSLBase(TInfoSinkBase& objSink,
ShArrayIndexClampingStrategy clampingStrategy,
ShHashFunction64 hashFunction,
NameMap& nameMap,
TSymbolTable& symbolTable);
protected:
TInfoSinkBase& objSink() { return mObjSink; }
void writeTriplet(Visit visit, const char* preStr, const char* inStr, const char* postStr);
void writeVariableType(const TType& type);
virtual bool writeVariablePrecision(TPrecision precision) = 0;
void writeFunctionParameters(const TIntermSequence& args);
const ConstantUnion* writeConstantUnion(const TType& type, const ConstantUnion* pConstUnion);
TString getTypeName(const TType& type);
virtual void visitSymbol(TIntermSymbol* node);
virtual void visitConstantUnion(TIntermConstantUnion* node);
virtual bool visitBinary(Visit visit, TIntermBinary* node);
virtual bool visitUnary(Visit visit, TIntermUnary* node);
virtual bool visitSelection(Visit visit, TIntermSelection* node);
virtual bool visitAggregate(Visit visit, TIntermAggregate* node);
virtual bool visitLoop(Visit visit, TIntermLoop* node);
virtual bool visitBranch(Visit visit, TIntermBranch* node);
void visitCodeBlock(TIntermNode* node);
// Return the original name if hash function pointer is NULL;
// otherwise return the hashed name.
TString hashName(const TString& name);
// Same as hashName(), but without hashing built-in variables.
TString hashVariableName(const TString& name);
// Same as hashName(), but without hashing built-in functions.
TString hashFunctionName(const TString& mangled_name);
private:
bool structDeclared(const TStructure* structure) const;
void declareStruct(const TStructure* structure);
TInfoSinkBase& mObjSink;
bool mDeclaringVariables;
// Structs are declared as the tree is traversed. This set contains all
// the structs already declared. It is maintained so that a struct is
// declared only once.
typedef std::set<TString> DeclaredStructs;
DeclaredStructs mDeclaredStructs;
ForLoopUnroll mLoopUnroll;
ShArrayIndexClampingStrategy mClampingStrategy;
// name hashing.
ShHashFunction64 mHashFunction;
NameMap& mNameMap;
TSymbolTable& mSymbolTable;
};
#endif // CROSSCOMPILERGLSL_OUTPUTGLSLBASE_H_
| 1,003 |
524 | #include "stdafx.h"
#include "../../corelib/collection_helper.h"
#include "../utils/utils.h"
#include "LoadPixmapFromDataTask.h"
namespace Utils
{
LoadPixmapFromDataTask::LoadPixmapFromDataTask(core::istream *stream, const QSize& _maxSize)
: Stream_(stream)
, maxSize_(_maxSize)
{
assert(Stream_);
Stream_->addref();
}
LoadPixmapFromDataTask::~LoadPixmapFromDataTask()
{
Stream_->release();
}
void LoadPixmapFromDataTask::run()
{
const auto size = Stream_->size();
assert(size > 0);
auto data = QByteArray::fromRawData((const char *)Stream_->read(size), (int)size);
QPixmap preview;
QSize originalSize;
Utils::loadPixmapScaled(data, maxSize_, Out preview, Out originalSize);
if (preview.isNull())
{
emit loadedSignal(QPixmap());
return;
}
emit loadedSignal(preview);
}
}
| 494 |
1,408 | <gh_stars>1000+
/* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (c) 2020, Linaro Limited and Contributors. All rights reserved.
*/
#include <libfdt.h>
#include <bl31/ehf.h>
#include <common/debug.h>
#include <common/fdt_fixup.h>
#include <common/fdt_wrappers.h>
#include <lib/xlat_tables/xlat_tables_compat.h>
#include <services/spm_mm_partition.h>
#include <platform_def.h>
/* Region equivalent to MAP_DEVICE1 suitable for mapping at EL0 */
#define MAP_DEVICE1_EL0 MAP_REGION_FLAT(DEVICE1_BASE, \
DEVICE1_SIZE, \
MT_DEVICE | MT_RW | MT_SECURE | MT_USER)
mmap_region_t plat_qemu_secure_partition_mmap[] = {
QEMU_SP_IMAGE_NS_BUF_MMAP, /* must be placed at first entry */
MAP_DEVICE1_EL0, /* for the UART */
QEMU_SP_IMAGE_MMAP,
QEMU_SPM_BUF_EL0_MMAP,
QEMU_SP_IMAGE_RW_MMAP,
MAP_SECURE_VARSTORE,
{0}
};
/* Boot information passed to a secure partition during initialisation. */
static spm_mm_mp_info_t sp_mp_info[PLATFORM_CORE_COUNT];
spm_mm_boot_info_t plat_qemu_secure_partition_boot_info = {
.h.type = PARAM_SP_IMAGE_BOOT_INFO,
.h.version = VERSION_1,
.h.size = sizeof(spm_mm_boot_info_t),
.h.attr = 0,
.sp_mem_base = PLAT_QEMU_SP_IMAGE_BASE,
.sp_mem_limit = BL32_LIMIT,
.sp_image_base = PLAT_QEMU_SP_IMAGE_BASE,
.sp_stack_base = PLAT_SP_IMAGE_STACK_BASE,
.sp_heap_base = PLAT_QEMU_SP_IMAGE_HEAP_BASE,
.sp_ns_comm_buf_base = PLAT_QEMU_SP_IMAGE_NS_BUF_BASE,
.sp_shared_buf_base = PLAT_SPM_BUF_BASE,
.sp_image_size = PLAT_QEMU_SP_IMAGE_SIZE,
.sp_pcpu_stack_size = PLAT_SP_IMAGE_STACK_PCPU_SIZE,
.sp_heap_size = PLAT_QEMU_SP_IMAGE_HEAP_SIZE,
.sp_ns_comm_buf_size = PLAT_QEMU_SP_IMAGE_NS_BUF_SIZE,
.sp_shared_buf_size = PLAT_SPM_BUF_SIZE,
.num_sp_mem_regions = PLAT_QEMU_SP_IMAGE_NUM_MEM_REGIONS,
.num_cpus = PLATFORM_CORE_COUNT,
.mp_info = sp_mp_info
};
/* Enumeration of priority levels on QEMU platforms. */
ehf_pri_desc_t qemu_exceptions[] = {
EHF_PRI_DESC(QEMU_PRI_BITS, PLAT_SP_PRI)
};
static void qemu_initialize_mp_info(spm_mm_mp_info_t *mp_info)
{
unsigned int i, j;
spm_mm_mp_info_t *tmp = mp_info;
for (i = 0; i < PLATFORM_CLUSTER_COUNT; i++) {
for (j = 0; j < PLATFORM_MAX_CPUS_PER_CLUSTER; j++) {
tmp->mpidr = (0x80000000 | (i << MPIDR_AFF1_SHIFT)) + j;
/*
* Linear indices and flags will be filled
* in the spm_mm service.
*/
tmp->linear_id = 0;
tmp->flags = 0;
tmp++;
}
}
}
int dt_add_ns_buf_node(uintptr_t *base)
{
uintptr_t addr;
size_t size;
uintptr_t ns_buf_addr;
int node;
int err;
void *fdt = (void *)ARM_PRELOADED_DTB_BASE;
err = fdt_open_into(fdt, fdt, PLAT_QEMU_DT_MAX_SIZE);
if (err < 0) {
ERROR("Invalid Device Tree at %p: error %d\n", fdt, err);
return err;
}
/*
* reserved-memory for standaloneMM non-secure buffer
* is allocated at the top of the first system memory region.
*/
node = fdt_path_offset(fdt, "/memory");
err = fdt_get_reg_props_by_index(fdt, node, 0, &addr, &size);
if (err < 0) {
ERROR("Failed to get the memory node information\n");
return err;
}
INFO("System RAM @ 0x%lx - 0x%lx\n", addr, addr + size - 1);
ns_buf_addr = addr + (size - PLAT_QEMU_SP_IMAGE_NS_BUF_SIZE);
INFO("reserved-memory for spm-mm @ 0x%lx - 0x%llx\n", ns_buf_addr,
ns_buf_addr + PLAT_QEMU_SP_IMAGE_NS_BUF_SIZE - 1);
err = fdt_add_reserved_memory(fdt, "ns-buf-spm-mm", ns_buf_addr,
PLAT_QEMU_SP_IMAGE_NS_BUF_SIZE);
if (err < 0) {
ERROR("Failed to add the reserved-memory node\n");
return err;
}
*base = ns_buf_addr;
return 0;
}
/* Plug in QEMU exceptions to Exception Handling Framework. */
EHF_REGISTER_PRIORITIES(qemu_exceptions, ARRAY_SIZE(qemu_exceptions),
QEMU_PRI_BITS);
const mmap_region_t *plat_get_secure_partition_mmap(void *cookie)
{
uintptr_t ns_buf_base;
dt_add_ns_buf_node(&ns_buf_base);
plat_qemu_secure_partition_mmap[0].base_pa = ns_buf_base;
plat_qemu_secure_partition_mmap[0].base_va = ns_buf_base;
plat_qemu_secure_partition_boot_info.sp_ns_comm_buf_base = ns_buf_base;
return plat_qemu_secure_partition_mmap;
}
const spm_mm_boot_info_t *
plat_get_secure_partition_boot_info(void *cookie)
{
qemu_initialize_mp_info(sp_mp_info);
return &plat_qemu_secure_partition_boot_info;
}
| 2,109 |
1,331 | <filename>java/meterpreter/stdapi/src/main/java/com/metasploit/meterpreter/stdapi/stdapi_sys_config_getenv.java
package com.metasploit.meterpreter.stdapi;
import com.metasploit.meterpreter.Meterpreter;
import com.metasploit.meterpreter.TLVPacket;
import com.metasploit.meterpreter.TLVType;
import com.metasploit.meterpreter.command.Command;
import java.util.List;
import java.util.Map;
public class stdapi_sys_config_getenv implements Command {
public int execute(Meterpreter meterpreter, TLVPacket request, TLVPacket response) throws Exception {
try {
List envVars = request.getValues(TLVType.TLV_TYPE_ENV_VARIABLE);
for (int i = 0; i < envVars.size(); ++i) {
String envVar = (String) envVars.get(i);
if (envVar.startsWith("$") || envVar.startsWith("%")) {
envVar = envVar.substring(1);
}
if (envVar.endsWith("$") || envVar.endsWith("%")) {
envVar = envVar.substring(0, envVar.length() - 1);
}
String envVal = System.getenv(envVar);
TLVPacket grp = new TLVPacket();
grp.add(TLVType.TLV_TYPE_ENV_VARIABLE, envVar);
grp.add(TLVType.TLV_TYPE_ENV_VALUE, envVal);
response.addOverflow(TLVType.TLV_TYPE_ENV_GROUP, grp);
}
} catch (IllegalArgumentException e) {
Map<String,String> envVals = System.getenv();
for (Map.Entry<String, String> entry : envVals.entrySet()) {
TLVPacket grp = new TLVPacket();
grp.add(TLVType.TLV_TYPE_ENV_VARIABLE, entry.getKey());
grp.add(TLVType.TLV_TYPE_ENV_VALUE, entry.getValue());
response.addOverflow(TLVType.TLV_TYPE_ENV_GROUP, grp);
}
}
return ERROR_SUCCESS;
}
}
| 938 |
357 | <filename>vmidentity/idm/server/src/main/java/com/vmware/identity/idm/server/provider/BaseLdapSchemaMapping.java
/*
*
* Copyright (c) 2012-2015 VMware, 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.vmware.identity.idm.server.provider;
import java.util.Collection;
import java.util.Map;
import com.vmware.identity.diagnostics.DiagnosticsLoggerFactory;
import com.vmware.identity.diagnostics.IDiagnosticsLogger;
import com.vmware.identity.idm.IdentityStoreAttributeMapping;
import com.vmware.identity.idm.IdentityStoreObjectMapping;
import com.vmware.identity.idm.IdentityStoreSchemaMapping;
import com.vmware.identity.idm.ValidateUtil;
import com.vmware.identity.idm.server.ServerUtils;
import com.vmware.identity.interop.ldap.LdapFilterString;
public abstract class BaseLdapSchemaMapping implements ILdapSchemaMapping
{
private static final IDiagnosticsLogger log = DiagnosticsLoggerFactory.getLogger(BaseLdapSchemaMapping.class);
private IdentityStoreSchemaMapping _schemaMapping;
private Map<String, String> _defaultAttributes;
private String _userQueryByAccountNameOrUpn;
private String _userQueryByUpn;
private String _userQueryByAccountName;
private String _userQueryByObjectUniqueId;
private String _userQueryByCriteria;
private String _userQueryByCriteriaForName;
private String _allUsersQuery;
private String _allDisabledUsersQuery;
private String _groupQueryByCriteria;
private String _groupQueryByCriteriaForName;
private String _allGroupsQuery;
private String _directParentGroupsQuery;
private String _nestedParentGroupsQuery;
private String _groupQueryByObjectUniqueId;
private String _groupQueryByAccountName;
private String _userOrGroupQueryByAccountNameOrUpn;
private String _userOrGroupQueryByAccountName;
private String _passwordSettingsQuery;
private String _domainObjectQuery;
private Boolean _builtPasswordSettingsQuery;
private Boolean _builtDomainObjectQuery;
protected static final String DN_ATTRIBUTE = "dn";
protected BaseLdapSchemaMapping( IdentityStoreSchemaMapping schemaMapping, Map<String, String> defaultAttributes )
{
ValidateUtil.validateNotNull(defaultAttributes, "defaultAttributes");
this._schemaMapping = schemaMapping;
this._defaultAttributes = defaultAttributes;
this._userQueryByAccountNameOrUpn = null;
this._userQueryByAccountName = null;
this._userQueryByUpn = null;
this._userQueryByObjectUniqueId = null;
this._userQueryByCriteria = null;
this._userQueryByCriteriaForName = null;
this._allUsersQuery = null;
this._allDisabledUsersQuery = null;
this._groupQueryByCriteria = null;
this._groupQueryByCriteriaForName = null;
this._allGroupsQuery = null;
this._directParentGroupsQuery = null;
this._nestedParentGroupsQuery = null;
this._groupQueryByObjectUniqueId = null;
this._groupQueryByAccountName = null;
this._userOrGroupQueryByAccountNameOrUpn = null;
this._userOrGroupQueryByAccountName = null;
this._passwordSettingsQuery = null;
this._domainObjectQuery = null;
this._builtPasswordSettingsQuery = false;
this._builtDomainObjectQuery = false;
}
@Override
public String getUserQueryByAccountNameOrUpn()
{
if(ServerUtils.isNullOrEmpty(this._userQueryByAccountNameOrUpn))
{
this._userQueryByAccountNameOrUpn = buildUserQueryByAccountNameOrUpn();
log.debug(
String.format("Built UserQueryByAccountNameOrUpn: [%s]", this._userQueryByAccountNameOrUpn)
);
}
return this._userQueryByAccountNameOrUpn;
}
@Override
public String getUserQueryByUpn()
{
if(ServerUtils.isNullOrEmpty(this._userQueryByUpn))
{
this._userQueryByUpn = buildUserQueryByUpn();
log.debug(
String.format("Built UserQueryByUpn: [%s]", this._userQueryByUpn)
);
}
return this._userQueryByUpn;
}
@Override
public String getUserQueryByAccountName()
{
if(ServerUtils.isNullOrEmpty(this._userQueryByAccountName))
{
this._userQueryByAccountName = buildUserQueryByAccountName();
log.debug(
String.format("Built UserQueryByAccountName: [%s]", this._userQueryByAccountName)
);
}
return this._userQueryByAccountName;
}
@Override
public String getUserQueryByObjectUniqueId()
{
if(ServerUtils.isNullOrEmpty(this._userQueryByObjectUniqueId))
{
this._userQueryByObjectUniqueId = buildUserQueryByObjectUniqueId();
log.debug(
String.format("Built UserQueryByObjectUniqueId: [%s]", this._userQueryByObjectUniqueId)
);
}
return this._userQueryByObjectUniqueId;
}
@Override
public String getUserQueryByCriteria()
{
if(ServerUtils.isNullOrEmpty(this._userQueryByCriteria))
{
this._userQueryByCriteria = buildUserQueryByCriteria();
log.debug(
String.format("Built UserQueryByCriteria: [%s]", this._userQueryByCriteria)
);
}
return this._userQueryByCriteria;
}
@Override
public String getUserQueryByCriteriaForName()
{
if(ServerUtils.isNullOrEmpty(this._userQueryByCriteriaForName))
{
this._userQueryByCriteriaForName = buildUserQueryByCriteriaForName();
log.debug(
String.format("Built UserQueryByCriteriaForName: [%s]", this._userQueryByCriteriaForName)
);
}
return this._userQueryByCriteriaForName;
}
@Override
public String getAllUsersQuery()
{
if(ServerUtils.isNullOrEmpty(this._allUsersQuery))
{
this._allUsersQuery = buildAllUsersQuery();
log.debug(
String.format("Built AllUsersQuery: [%s]", this._allUsersQuery)
);
}
return this._allUsersQuery;
}
@Override
public String getAllDisabledUsersQuery()
{
if(ServerUtils.isNullOrEmpty(this._allDisabledUsersQuery))
{
this._allDisabledUsersQuery = buildAllDisabledUsersQuery();
log.debug(
String.format("Built AllDisabledUsersQuery: [%s]", this._allDisabledUsersQuery)
);
}
return this._allDisabledUsersQuery;
}
@Override
public String getGroupQueryByCriteria()
{
if(ServerUtils.isNullOrEmpty(this._groupQueryByCriteria))
{
this._groupQueryByCriteria = buildGroupQueryByCriteria();
log.debug(
String.format("Built GroupQueryByCriteria: [%s]", this._groupQueryByCriteria)
);
}
return this._groupQueryByCriteria;
}
@Override
public String getGroupQueryByCriteriaForName()
{
if(ServerUtils.isNullOrEmpty(this._groupQueryByCriteriaForName))
{
this._groupQueryByCriteriaForName = buildGroupQueryByCriteriaForName();
log.debug(
String.format("Built GroupQueryByCriteriaForName: [%s]", this._groupQueryByCriteriaForName)
);
}
return this._groupQueryByCriteriaForName;
}
@Override
public String getAllGroupsQuery()
{
if(ServerUtils.isNullOrEmpty(this._allGroupsQuery))
{
this._allGroupsQuery = buildAllGroupsQuery();
log.debug(
String.format("Built AllGroupsQuery: [%s]", this._allGroupsQuery)
);
}
return this._allGroupsQuery;
}
@Override
public String getDirectParentGroupsQuery()
{
if(ServerUtils.isNullOrEmpty(this._directParentGroupsQuery))
{
this._directParentGroupsQuery = buildDirectParentGroupsQuery();
log.debug(
String.format("Built DirectParentGroupsQuery: [%s]", this._directParentGroupsQuery)
);
}
return this._directParentGroupsQuery;
}
@Override
public String getNestedParentGroupsQuery()
{
if(ServerUtils.isNullOrEmpty(this._nestedParentGroupsQuery))
{
this._nestedParentGroupsQuery = buildNestedParentGroupsQuery();
log.debug(
String.format("Built NestedParentGroupsQuery: [%s]", this._nestedParentGroupsQuery)
);
}
return this._nestedParentGroupsQuery;
}
@Override
public String getGroupQueryByObjectUniqueId()
{
if(ServerUtils.isNullOrEmpty(this._groupQueryByObjectUniqueId))
{
this._groupQueryByObjectUniqueId = buildGroupQueryByObjectUniqueId();
log.debug(
String.format("Built GroupQueryByObjectUniqueId: [%s]", this._groupQueryByObjectUniqueId)
);
}
return this._groupQueryByObjectUniqueId;
}
@Override
public String getGroupQueryByAccountName()
{
if(ServerUtils.isNullOrEmpty(this._groupQueryByAccountName))
{
this._groupQueryByAccountName = buildGroupQueryByAccountName();
log.debug(
String.format("Built GroupQueryByAccountName: [%s]", this._groupQueryByAccountName)
);
}
return this._groupQueryByAccountName;
}
@Override
public String getUserOrGroupQueryByAccountNameOrUpn()
{
if(ServerUtils.isNullOrEmpty(this._userOrGroupQueryByAccountNameOrUpn))
{
this._userOrGroupQueryByAccountNameOrUpn = buildUserOrGroupQueryByAccountNameOrUpn();
log.debug(
String.format("Built UserOrGroupQueryByAccountNameOrUpn: [%s]", this._userOrGroupQueryByAccountNameOrUpn)
);
}
return this._userOrGroupQueryByAccountNameOrUpn;
}
@Override
public String getUserOrGroupQueryByAccountName()
{
if(ServerUtils.isNullOrEmpty(this._userOrGroupQueryByAccountName))
{
this._userOrGroupQueryByAccountName = buildUserOrGroupQueryByAccountName();
log.debug(
String.format("Built UserOrGroupQueryByAccountName: [%s]", this._userOrGroupQueryByAccountName)
);
}
return this._userOrGroupQueryByAccountName;
}
@Override
public String getPasswordSettingsQuery()
{
if( this._builtPasswordSettingsQuery == false)
{
this._passwordSettingsQuery = buildPasswordSettingsQuery();
this._builtPasswordSettingsQuery = true;
log.debug(
String.format("Built PasswordSettingsQuery: [%s]", this._passwordSettingsQuery)
);
}
return this._passwordSettingsQuery;
}
@Override
public String getDomainObjectQuery()
{
if( this._builtDomainObjectQuery == false)
{
this._domainObjectQuery = buildDomainObjectQuery();
this._builtDomainObjectQuery = true;
log.debug(
String.format("Built DomainObjectQuery: [%s]", this._domainObjectQuery)
);
}
return this._domainObjectQuery;
}
@Override
public String getUserAttribute( String attribute )
{
return this.getAttribute(IdentityStoreObjectMapping.ObjectIds.ObjectIdUser, attribute);
}
@Override
public String getGroupAttribute( String attribute )
{
return this.getAttribute(IdentityStoreObjectMapping.ObjectIds.ObjectIdGroup, attribute);
}
@Override
public String getPwdObjectAttribute( String attribute )
{
return this.getAttribute(IdentityStoreObjectMapping.ObjectIds.ObjectIdPasswordSettings, attribute);
}
@Override
public String getDomainObjectAttribute( String attribute )
{
return this.getAttribute(IdentityStoreObjectMapping.ObjectIds.ObjectIdDomain, attribute);
}
@Override
public String getDNFilter( String filter, Collection<String> memberDNs )
{
StringBuilder dnListFilter = new StringBuilder();
dnListFilter.append("(&");
dnListFilter.append(filter);
dnListFilter.append("(|");
for (String memberDn : memberDNs)
{
dnListFilter.append("(distinguishedName=");
dnListFilter.append(LdapFilterString.encode(memberDn));
dnListFilter.append(")");
}
dnListFilter.append("))");
return dnListFilter.toString();
}
@Override
public boolean doesLinkExist(String mappedAttributeName)
{
return ((IdentityStoreAttributeMapping.NO_LINK_ATTRIBUTE_MAPPING.equalsIgnoreCase(mappedAttributeName)) == false);
}
@Override
public boolean isDnAttribute(String attributeName)
{
return DN_ATTRIBUTE.equalsIgnoreCase(attributeName);
}
protected String getUserObjectClassValue()
{
return this.getObjectClassValue(IdentityStoreObjectMapping.ObjectIds.ObjectIdUser);
}
protected String getGroupObjectClassValue()
{
return this.getObjectClassValue(IdentityStoreObjectMapping.ObjectIds.ObjectIdGroup);
}
protected String getPasswordSettingsObjectClassValue()
{
return this.getObjectClassValue(IdentityStoreObjectMapping.ObjectIds.ObjectIdPasswordSettings);
}
protected String getDomainObjectClassValue()
{
return this.getObjectClassValue(IdentityStoreObjectMapping.ObjectIds.ObjectIdDomain);
}
protected abstract String buildUserQueryByAccountNameOrUpn();
protected abstract String buildUserQueryByUpn();
protected abstract String buildUserQueryByAccountName();
protected abstract String buildUserQueryByObjectUniqueId( );
protected abstract String buildUserQueryByCriteria();
protected abstract String buildUserQueryByCriteriaForName();
protected abstract String buildAllUsersQuery();
protected abstract String buildAllDisabledUsersQuery();
protected abstract String buildGroupQueryByCriteria();
protected abstract String buildGroupQueryByCriteriaForName();
protected abstract String buildAllGroupsQuery();
protected abstract String buildDirectParentGroupsQuery();
protected abstract String buildNestedParentGroupsQuery();
protected abstract String buildGroupQueryByObjectUniqueId( );
protected abstract String buildGroupQueryByAccountName();
protected abstract String buildUserOrGroupQueryByAccountNameOrUpn();
protected abstract String buildUserOrGroupQueryByAccountName();
protected abstract String buildPasswordSettingsQuery();
protected abstract String buildDomainObjectQuery();
private String getObjectClassValue(String objectCl)
{
String objectClass = null;
if(this._schemaMapping != null)
{
IdentityStoreObjectMapping objectMapping = this._schemaMapping.getObjectMapping(objectCl);
if(objectMapping != null)
{
objectClass = objectMapping.getObjectClass();
}
}
if( ServerUtils.isNullOrEmpty(objectClass) )
{
objectClass = this._defaultAttributes.get(objectCl);
}
return objectClass;
}
private String getAttribute( String objectClass, String attributeName )
{
String attribute = null;
if( this._schemaMapping != null)
{
IdentityStoreObjectMapping objectMapping = this._schemaMapping.getObjectMapping(objectClass);
if( objectMapping != null )
{
IdentityStoreAttributeMapping attributeMapping = objectMapping.getAttributeMapping(attributeName);
if( attributeMapping != null )
{
attribute = attributeMapping.getAttributeName();
}
}
}
if( ServerUtils.isNullOrEmpty(attribute) )
{
attribute = this._defaultAttributes.get(attributeName);
}
return attribute;
}
}
| 6,682 |
834 | #using <System.Data.dll>
#using <System.Windows.Forms.dll>
#using <System.dll>
#using <System.Drawing.dll>
using namespace System;
using namespace System::Drawing;
using namespace System::Collections;
using namespace System::ComponentModel;
using namespace System::Windows::Forms;
using namespace System::Data;
/// <summary>
/// Summary description for Form1.
/// </summary>
public ref class Form1: public System::Windows::Forms::Form
{
private:
System::Windows::Forms::ListBox^ listBox1;
System::Windows::Forms::Button^ button1;
/// <summary>
/// Required designer variable.
/// </summary>
System::ComponentModel::Container^ components;
public:
Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
}
public:
/// <summary>
/// Clean up any resources being used.
/// </summary>
~Form1()
{
if ( components != nullptr )
{
delete components;
}
}
private:
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
void InitializeComponent()
{
this->listBox1 = gcnew System::Windows::Forms::ListBox;
this->button1 = gcnew System::Windows::Forms::Button;
this->SuspendLayout();
//
// listBox1
//
array<Object^>^temp0 = {"Alpha","Bravo","Charlie","Delta","Echo","Foxtro","Golf","Hotel","Igloo","Java","Koala","Lima","Mama"};
this->listBox1->Items->AddRange( temp0 );
this->listBox1->Location = System::Drawing::Point( 56, 40 );
this->listBox1->Name = "listBox1";
this->listBox1->SelectionMode = System::Windows::Forms::SelectionMode::None;
this->listBox1->Size = System::Drawing::Size( 200, 82 );
this->listBox1->TabIndex = 0;
this->listBox1->MouseDown += gcnew System::Windows::Forms::MouseEventHandler( this, &Form1::listBox1_MouseDown );
//
// button1
//
this->button1->Location = System::Drawing::Point( 264, 72 );
this->button1->Name = "button1";
this->button1->TabIndex = 1;
this->button1->Text = "button1";
this->button1->Click += gcnew System::EventHandler( this, &Form1::button1_Click );
//
// Form1
//
this->ClientSize = System::Drawing::Size( 376, 254 );
array<System::Windows::Forms::Control^>^temp1 = {this->button1,this->listBox1};
this->Controls->AddRange( temp1 );
this->Name = "Form1";
this->Text = "Form1";
this->Load += gcnew System::EventHandler( this, &Form1::Form1_Load );
this->ResumeLayout( false );
}
//<Snippet1>
private:
void InitializeMyListBox()
{
// Add items to the ListBox.
listBox1->Items->Add( "A" );
listBox1->Items->Add( "C" );
listBox1->Items->Add( "E" );
listBox1->Items->Add( "F" );
listBox1->Items->Add( "G" );
listBox1->Items->Add( "D" );
listBox1->Items->Add( "B" );
// Sort all items added previously.
listBox1->Sorted = true;
// Set the SelectionMode to select multiple items.
listBox1->SelectionMode = SelectionMode::MultiExtended;
// Select three initial items from the list.
listBox1->SetSelected( 0, true );
listBox1->SetSelected( 2, true );
listBox1->SetSelected( 4, true );
// Force the ListBox to scroll back to the top of the list.
listBox1->TopIndex = 0;
}
void InvertMySelection()
{
// Loop through all items the ListBox.
for ( int x = 0; x < listBox1->Items->Count; x++ )
{
// Select all items that are not selected,
// deselect all items that are selected.
listBox1->SetSelected( x, !listBox1->GetSelected( x ) );
}
listBox1->TopIndex = 0;
}
//</Snippet1>
void button1_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ )
{
InvertMySelection();
}
void listBox1_MouseDown( Object^ /*sender*/, System::Windows::Forms::MouseEventArgs^ /*e*/ ){}
void Form1_Load( Object^ /*sender*/, System::EventArgs^ /*e*/ )
{
listBox1->Items->Clear();
this->InitializeMyListBox();
}
};
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
int main()
{
Application::Run( gcnew Form1 );
}
| 1,713 |
439 | <reponame>stoLem/GyverLibs
#include <GyverBME280.h>
/* ============ Utilities ============ */
float pressureToAltitude(float pressure)
{
if(!pressure) return 0; // If the pressure module has been disabled return '0'
pressure /= 100.0F; // Convert [Pa] to [hPa]
return 44330.0 * (1.0 - pow(pressure / 1013.25, 0.1903)); // Сalculate altitude
}
float pressureToMmHg(float pressure)
{
return (float)(pressure * 0.00750061683f); // Convert [Pa] to [mm Hg]
}
/* ============ Setup & begin ============ */
bool GyverBME280::begin(void)
{
return GyverBME280::begin(0x76);
}
bool GyverBME280::begin(uint8_t address)
{
_i2c_address = address;
/* === Start I2C bus & check BME280 === */
Wire.begin(); // Start I2C bus
if(!GyverBME280::reset()) return false; // BME280 software reset & ack check
if(GyverBME280::readRegister(0xD0) != 0x60) return false; // Check chip ID
GyverBME280::readCalibrationData(); // Read all calibration values
/* === Load settings to BME280 === */
GyverBME280::writeRegister(0xF2 , _hum_oversampl); // write hum oversampling value
GyverBME280::writeRegister(0xF2 , GyverBME280::readRegister(0xF2)); // rewrite hum oversampling register
GyverBME280::writeRegister(0xF4 , ((_temp_oversampl << 5) | (_press_oversampl << 2) | _operating_mode)); // write temp & press oversampling value , normal mode
GyverBME280::writeRegister(0xF5 , ((_standby_time << 5) | (_filter_coef << 2))); // write standby time & filter coef
return true;
}
void GyverBME280::setMode(uint8_t mode)
{
_operating_mode = mode;
}
void GyverBME280::setFilter(uint8_t mode)
{
_filter_coef = mode;
}
void GyverBME280::setStandbyTime(uint8_t mode)
{
_standby_time = mode;
}
void GyverBME280::setHumOversampling(uint8_t mode)
{
_hum_oversampl = mode;
}
void GyverBME280::setTempOversampling(uint8_t mode)
{
_temp_oversampl = mode;
}
void GyverBME280::setPressOversampling(uint8_t mode)
{
_press_oversampl = mode;
}
/* ============ Reading ============ */
int32_t GyverBME280::readTempInt(void)
{
int32_t temp_raw = GyverBME280::readRegister24(0xFA); // Read 24-bit value
if (temp_raw == 0x800000) return 0; // If the temperature module has been disabled return '0'
temp_raw >>= 4; // Start temperature reading in integers
int32_t value_1 = ((((temp_raw >> 3) - ((int32_t)CalibrationData._T1 << 1))) *
((int32_t)CalibrationData._T2)) >> 11;
int32_t value_2 = (((((temp_raw >> 4) - ((int32_t)CalibrationData._T1)) *
((temp_raw >> 4) - ((int32_t)CalibrationData._T1))) >> 12) * ((int32_t)CalibrationData._T3)) >> 14;
return ((int32_t)value_1 + value_2); // Return temperature in integers
}
float GyverBME280::readTemperature(void)
{
int32_t temp_raw = GyverBME280::readTempInt();
float T = (temp_raw * 5 + 128) >> 8;
return T / 100; // Return temperature in float
}
float GyverBME280::readPressure(void)
{
uint32_t press_raw = GyverBME280::readRegister24(0xF7); // Read 24-bit value
if (press_raw == 0x800000) return 0; // If the pressure module has been disabled return '0'
press_raw >>= 4; // Start pressure converting
int64_t value_1 = ((int64_t)GyverBME280::readTempInt()) - 128000;
int64_t value_2 = value_1 * value_1 * (int64_t)CalibrationData._P6;
value_2 = value_2 + ((value_1 * (int64_t)CalibrationData._P5) << 17);
value_2 = value_2 + (((int64_t)CalibrationData._P4) << 35);
value_1 = ((value_1 * value_1 * (int64_t)CalibrationData._P3) >> 8) + ((value_1 * (int64_t)CalibrationData._P2) << 12);
value_1 = (((((int64_t)1) << 47) + value_1)) * ((int64_t)CalibrationData._P1) >> 33;
if (!value_1) return 0; // Avoid division by zero
int64_t p = 1048576 - press_raw;
p = (((p << 31) - value_2) * 3125) / value_1;
value_1 = (((int64_t)CalibrationData._P9) * (p >> 13) * (p >> 13)) >> 25;
value_2 = (((int64_t)CalibrationData._P8) * p) >> 19;
p = ((p + value_1 + value_2) >> 8) + (((int64_t)CalibrationData._P7) << 4);
return (float)p / 256; // Return pressure in float
}
float GyverBME280::readHumidity(void)
{
Wire.beginTransmission(_i2c_address); // Start I2C transmission
Wire.write(0xFD); // Request humidity data register
if(Wire.endTransmission() != 0) return 0;
Wire.requestFrom(_i2c_address, 2); // Request humidity data
int32_t hum_raw = ((uint16_t)Wire.read() << 8) | (uint16_t)Wire.read(); // Read humidity data
if (hum_raw == 0x8000) return 0; // If the humidity module has been disabled return '0'
int32_t value = (GyverBME280::readTempInt() - ((int32_t)76800)); // Start humidity converting
value = (((((hum_raw << 14) - (((int32_t)CalibrationData._H4) << 20) -
(((int32_t)CalibrationData._H5) * value)) +((int32_t)16384)) >> 15) *
(((((((value * ((int32_t)CalibrationData._H6)) >> 10) *(((value *
((int32_t)CalibrationData._H3)) >> 11) + ((int32_t)32768))) >> 10) +
((int32_t)2097152)) * ((int32_t)CalibrationData._H2) + 8192) >> 14));
value = (value - (((((value >> 15) * (value >> 15)) >> 7) * ((int32_t)CalibrationData._H1)) >> 4));
value = (value < 0) ? 0 : value;
value = (value > 419430400) ? 419430400 : value;
float h = (value >> 12);
return h / 1024.0; // Return humidity in float
}
/* ============ Misc ============ */
bool GyverBME280::isMeasuring(void) // Returns 'true' while the measurement is in progress
{
return (bool)((GyverBME280::readRegister(0xF3) & 0x08) >> 3); // Read status register & mask bit "measuring"
}
void GyverBME280::oneMeasurement(void)
{
GyverBME280::writeRegister(0xF4 , ((GyverBME280::readRegister(0xF4) & 0xFC) | 0x02)); // Set the operating mode to FORCED_MODE
}
GyverBME280::GyverBME280() {}
/* ============ Private ============ */
/* = BME280 software reset = */
bool GyverBME280::reset(void)
{
if(!GyverBME280::writeRegister(0x0E , 0xB6)) return false;
delay(10);
return true;
}
/* = Read and combine three BME280 registers = */
uint32_t GyverBME280::readRegister24(uint8_t address)
{
Wire.beginTransmission(_i2c_address);
Wire.write(address);
if(Wire.endTransmission() != 0) return 0x800000;
Wire.requestFrom(_i2c_address, 3);
return (((uint32_t)Wire.read() << 16) | ((uint32_t)Wire.read() << 8) | (uint32_t)Wire.read());
}
/* = Write one 8-bit BME280 register = */
bool GyverBME280::writeRegister(uint8_t address , uint8_t data)
{
Wire.beginTransmission(_i2c_address);
Wire.write(address);
Wire.write(data);
if(Wire.endTransmission() != 0) return false;
return true;
}
/* = Read one 8-bit BME280 register = */
uint8_t GyverBME280::readRegister(uint8_t address)
{
Wire.beginTransmission(_i2c_address);
Wire.write(address);
if(Wire.endTransmission() != 0) return 0;
Wire.requestFrom(_i2c_address , 1);
return Wire.read();
}
/* = Structure to store all calibration values = */
void GyverBME280::readCalibrationData(void)
{
/* first part request*/
Wire.beginTransmission(_i2c_address);
Wire.write(0x88);
if(Wire.endTransmission() != 0) return;
Wire.requestFrom(_i2c_address , 25);
/* reading */
CalibrationData._T1 = (Wire.read() | (Wire.read() << 8));
CalibrationData._T2 = (Wire.read() | (Wire.read() << 8));
CalibrationData._T3 = (Wire.read() | (Wire.read() << 8));
CalibrationData._P1 = (Wire.read() | (Wire.read() << 8));
CalibrationData._P2 = (Wire.read() | (Wire.read() << 8));
CalibrationData._P3 = (Wire.read() | (Wire.read() << 8));
CalibrationData._P4 = (Wire.read() | (Wire.read() << 8));
CalibrationData._P5 = (Wire.read() | (Wire.read() << 8));
CalibrationData._P6 = (Wire.read() | (Wire.read() << 8));
CalibrationData._P7 = (Wire.read() | (Wire.read() << 8));
CalibrationData._P8 = (Wire.read() | (Wire.read() << 8));
CalibrationData._P9 = (Wire.read() | (Wire.read() << 8));
CalibrationData._H1 = Wire.read();
/* second part request*/
Wire.beginTransmission(_i2c_address);
Wire.write(0xE1);
Wire.endTransmission();
Wire.requestFrom(_i2c_address , 8);
/* reading */
CalibrationData._H2 = (Wire.read() | (Wire.read() << 8));
CalibrationData._H3 = Wire.read();
CalibrationData._H4 = (Wire.read() << 4);
uint8_t interVal = Wire.read();
CalibrationData._H4 |= (interVal & 0xF);
CalibrationData._H5 = (((interVal & 0xF0) >> 4) | (Wire.read() << 4));
CalibrationData._H6 = Wire.read();
} | 3,597 |
1,273 | package org.broadinstitute.hellbender.utils;
import htsjdk.tribble.util.ParsingUtils;
import org.broadinstitute.hellbender.GATKBaseTest;
import org.testng.annotations.Test;
import java.util.*;
import java.util.stream.Collectors;
/**
* A class to test the speed of different string.split implementations.
* This test is disabled by default because it takes 3.5 minutes to complete and we already have the information it provides.
* Created by jonn on 11/1/17.
*/
public class StringSplitSpeedUnitTest extends GATKBaseTest {
private static final String stringToSplit =
"Arma virumque cano, Troiae qui primus ab oris " +
"Italiam, fato profugus, Laviniaque venit " +
"litora, multum ille et terris iactatus et alto " +
"vi superum saevae memorem Iunonis ob iram; " +
"multa quoque et bello passus, dum conderet urbem, " +
"inferretque deos Latio, genus unde Latinum, " +
"Albanique patres, atque altae moenia Romae. " +
"Musa, mihi causas memora, quo numine laeso, " +
"quidve dolens, regina deum tot volvere casus " +
"insignem pietate virum, tot adire labores " +
"impulerit. Tantaene animis caelestibus irae? " +
"Urbs antiqua fuit, Tyrii tenuere coloni, " +
"Karthago, Italiam contra Tiberinaque longe " +
"ostia, dives opum studiisque asperrima belli; " +
"quam Iuno fertur terris magis omnibus unam " +
"posthabita coluisse Samo; hic illius arma, " +
"hic currus fuit; hoc regnum dea gentibus esse, " +
"si qua fata sinant, iam tum tenditque fovetque. " +
"Progeniem sed enim Troiano a sanguine duci " +
"audierat, Tyrias olim quae verteret arces; " +
"hinc populum late regem belloque superbum " +
"venturum excidio Libyae: sic volvere Parcas. " +
"Id metuens, veterisque memor Saturnia belli, " +
"prima quod ad Troiam pro caris gesserat Argis- " +
"necdum etiam causae irarum saevique dolores " +
"exciderant animo: manet alta mente repostum " +
"iudicium Paridis spretaeque iniuria formae, " +
"et genus invisum, et rapti Ganymedis honores. " +
"His accensa super, iactatos aequore toto " +
"Troas, reliquias Danaum atque immitis Achilli, " +
"arcebat longe Latio, multosque per annos " +
"errabant, acti fatis, maria omnia circum. " +
"Tantae molis erat Romanam condere gentem!";
private static final List<String> wordsToSplitOn = new ArrayList<>( Arrays.asList(stringToSplit.split(" ")) );
private static final Set<String> singleCharStringsToSplitOn =
Arrays.stream(stringToSplit.split(""))
.map(s -> (s.equals("?")) ? "\\?" : s)
.collect(Collectors.toSet());
private static final int numIterations = 100000;
private static final double MS_TO_NS = 1000000.0;
private static final double S_TO_MS = 1000.0;
//=========================================================================
private static void printTimingString(final String decorator,
final long time_ns,
final int numSplits) {
final double time_ms = time_ns / MS_TO_NS;
final double timePerSplit_ns = ((double)time_ns) / ((double)numSplits) / ((double)numIterations);
final double timePerSplit_ms = timePerSplit_ns / MS_TO_NS;
System.out.println("\t" + decorator + " Total Time:\t" + time_ns + "ns\t" + time_ms +
"ms\tPer Split:\t" + timePerSplit_ns + "ns\t\t" + timePerSplit_ms + "ms");
}
private static void printTimingTable(final long javaSplitWordTotalTime_ns,
final long javaSplitSingleCharStringTotalTime_ns,
final long htsjdkSplitSingleCharTotalTime_ns,
final long gatkSplitWordTotalTime_ns,
final long gatkSplitSingleCharStringTotalTime_ns,
final long overallElapsedTime_ns,
final double overallElapsedTime_ms) {
System.out.println("================================================================================");
System.out.println("Timing Results:");
System.out.println("--------------------------------------------------------------------------------");
System.out.println("Overall Elapsed Time: " + overallElapsedTime_ns + "ns, " + overallElapsedTime_ms + "ms");
System.out.println("--------------------------------------------------------------------------------");
System.out.println("Java Split String:");
printTimingString("Words", javaSplitWordTotalTime_ns, wordsToSplitOn.size());
printTimingString("\"Chars\"", javaSplitSingleCharStringTotalTime_ns, singleCharStringsToSplitOn.size());
System.out.println("HTSJDK ParsingUtils::split");
printTimingString("\"Chars\"", htsjdkSplitSingleCharTotalTime_ns, singleCharStringsToSplitOn.size());
System.out.println("GATK Utils::split");
printTimingString("Words", gatkSplitWordTotalTime_ns, wordsToSplitOn.size());
printTimingString("\"Chars\"", gatkSplitSingleCharStringTotalTime_ns, singleCharStringsToSplitOn.size());
System.out.println("================================================================================");
}
private static void printTimingTableMarkdown(final long javaSplitWordTotalTime_ns,
final long javaSplitSingleCharStringTotalTime_ns,
final long htsjdkSplitSingleCharTotalTime_ns,
final long gatkSplitWordTotalTime_ns,
final long gatkSplitSingleCharStringTotalTime_ns ) {
System.out.println( "| Method | Benchmark | Total Time (ns) | Total Time (ms) | Time Per Split Operation (ns) | Time Per Split Operation (ms) |" );
System.out.println( "| --- | --- | --- | --- | --- | --- |" );
printTimingMarkdownLine( "| Java String::split | Split on Words | ", javaSplitWordTotalTime_ns, wordsToSplitOn.size() );
printTimingMarkdownLine( "| Java String::split | Split on Chars | ", javaSplitSingleCharStringTotalTime_ns, singleCharStringsToSplitOn.size() );
System.out.println( "| HTSJDK ParsingUtils::split | Split on Words | NA | NA | NA | NA |" );
printTimingMarkdownLine( "| HTSJDK ParsingUtils::split | Split on Chars | ", htsjdkSplitSingleCharTotalTime_ns, singleCharStringsToSplitOn.size() );
printTimingMarkdownLine( "| GATK Utils::split | Split on Words | ", gatkSplitWordTotalTime_ns, wordsToSplitOn.size() );
printTimingMarkdownLine( "| GATK Utils::split | Split on Chars | ", gatkSplitSingleCharStringTotalTime_ns, singleCharStringsToSplitOn.size() );
}
private static void printTimingMarkdownLine(final String rowHeader,
final long time_ns,
final int numSplits) {
final double time_ms = time_ns / MS_TO_NS;
final double timePerSplit_ns = ((double)time_ns) / ((double)numSplits) / ((double)numIterations);
final double timePerSplit_ms = timePerSplit_ns / MS_TO_NS;
System.out.println( rowHeader + time_ns + " | " + time_ms + " | " + timePerSplit_ns + " | " + timePerSplit_ms + " |" );
}
//==================================================================================================================
// Disabled so that we don't waste time.
// Cached results here:
//--------------------------------------------------------------------------------
// Overall Elapsed Time: 194969742609ns, 194969.742609ms, 3.25min
//--------------------------------------------------------------------------------
// Java Split String:
// Words Total Time: 123581339505ns 123581.339505ms Per Split: 5668.868784633028ns 0.0056688687846330275ms
// "Chars" Total Time: 13324148242ns 13324.148242ms Per Split: 3098.6391260465116ns 0.0030986391260465116ms
// HTSJDK ParsingUtils::split
// "Chars" Total Time: 6054845269ns 6054.845269ms Per Split: 1408.1035509302328ns 0.0014081035509302328ms
// GATK Utils::split
// Words Total Time: 45913524687ns 45913.524687ms Per Split: 2106.124985642202ns 0.002106124985642202ms
// "Chars" Total Time: 6095292091ns 6095.292091ms Per Split: 1417.509788604651ns 0.001417509788604651ms
//================================================================================
@Test(enabled = false)
void compareTimingForSplitString() {
final long overallStartTime = System.nanoTime();
//------------------------------------------------------------------------------------------------------------------
// Baseline Java String.split:
//-------------------------------------------------
// First we do words:
System.out.print("Testing Java String.split on words..."); System.out.flush();
final long javaSplitWordStartTime = System.nanoTime();
for ( int i = 0; i < numIterations; ++i ) {
for ( final String word : wordsToSplitOn ) {
stringToSplit.split(word);
}
}
final long javaSplitWordStopTime = System.nanoTime();
final long javaSplitWordTotalTime_ns = javaSplitWordStopTime - javaSplitWordStartTime;
System.out.println( " Done! (" + (javaSplitWordTotalTime_ns / MS_TO_NS / S_TO_MS) + "s)" );
//-------------------------------------------------
// Now we do single char words:
System.out.print("Testing Java String.split on single characters..."); System.out.flush();
final long javaSplitSingleCharStringStartTime = System.nanoTime();
for ( int i = 0; i < numIterations; ++i ) {
for ( final String word : singleCharStringsToSplitOn ) {
stringToSplit.split(word);
}
}
final long javaSplitSingleCharStringStopTime = System.nanoTime();
final long javaSplitSingleCharStringTotalTime_ns = javaSplitSingleCharStringStopTime - javaSplitSingleCharStringStartTime;
System.out.println( " Done! (" + (javaSplitSingleCharStringTotalTime_ns / MS_TO_NS / S_TO_MS) + "s)" );
//------------------------------------------------------------------------------------------------------------------
// HTSJDK's ParsingUtils::split:
//-------------------------------------------------
// First we do words:
// NOT APPLICABLE FOR HTSJDK's ParsingUtils::split!
//-------------------------------------------------
// Now we do single char words:
System.out.print("Testing HTSJDK's ParsingUtils::split on single characters..."); System.out.flush();
final long htsjdkSplitSingleCharStringStartTime = System.nanoTime();
for ( int i = 0; i < numIterations; ++i ) {
for ( final String word : singleCharStringsToSplitOn ) {
ParsingUtils.split( stringToSplit, word.charAt(0) );
}
}
final long htsjdkSplitSingleCharStringStopTime = System.nanoTime();
final long htsjdkSplitSingleCharTotalTime_ns = htsjdkSplitSingleCharStringStopTime - htsjdkSplitSingleCharStringStartTime;
System.out.println( " Done! (" + (htsjdkSplitSingleCharTotalTime_ns / MS_TO_NS / S_TO_MS) + "s)" );
//------------------------------------------------------------------------------------------------------------------
// GATK's Utils::split:
//-------------------------------------------------
// First we do words:
System.out.print("Testing GATK's Utils::split: on words..."); System.out.flush();
final long gatkSplitWordStartTime = System.nanoTime();
for ( int i = 0; i < numIterations; ++i ) {
for ( final String word : wordsToSplitOn ) {
Utils.split( stringToSplit, word );
}
}
final long gatkSplitWordStopTime = System.nanoTime();
final long gatkSplitWordTotalTime_ns = gatkSplitWordStopTime - gatkSplitWordStartTime;
System.out.println( " Done! (" + (gatkSplitWordTotalTime_ns / MS_TO_NS / S_TO_MS) + "s)" );
//-------------------------------------------------
// Now we do single char words:
System.out.print("Testing GATK's Utils::split: on single characters..."); System.out.flush();
final long gatkSplitSingleCharStringStartTime = System.nanoTime();
for ( int i = 0; i < numIterations; ++i ) {
for ( final String word : singleCharStringsToSplitOn ) {
Utils.split( stringToSplit, word );
}
}
final long gatkSplitSingleCharStringStopTime = System.nanoTime();
final long gatkSplitSingleCharStringTotalTime_ns = gatkSplitSingleCharStringStopTime - gatkSplitSingleCharStringStartTime;
System.out.println( " Done! (" + (gatkSplitSingleCharStringTotalTime_ns / MS_TO_NS / S_TO_MS) + "s)" );
//------------------------------------------------------------------------------------------------------------------
final long overallEndTime = System.nanoTime();
final long overallElapsedTime_ns = overallEndTime - overallStartTime;
final double overallElapsedTime_ms = overallElapsedTime_ns / MS_TO_NS;
//------------------------------------------------------------------------------------------------------------------
// Print results:
printTimingTable(javaSplitWordTotalTime_ns, javaSplitSingleCharStringTotalTime_ns, htsjdkSplitSingleCharTotalTime_ns, gatkSplitWordTotalTime_ns, gatkSplitSingleCharStringTotalTime_ns, overallElapsedTime_ns, overallElapsedTime_ms);
System.out.println("");
System.out.println("====");
System.out.println("");
printTimingTableMarkdown(javaSplitWordTotalTime_ns, javaSplitSingleCharStringTotalTime_ns, htsjdkSplitSingleCharTotalTime_ns, gatkSplitWordTotalTime_ns, gatkSplitSingleCharStringTotalTime_ns );
}
}
| 5,709 |
9,402 | <gh_stars>1000+
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
// File: CORDB-ASSEMBLY.H
//
#ifndef __MONO_DEBUGGER_CORDB_ASSEMBLY_H__
#define __MONO_DEBUGGER_CORDB_ASSEMBLY_H__
#include <cordb.h>
class CLiteWeightStgdbRW;
class CordbModule : public CordbBaseMono,
public ICorDebugModule,
public ICorDebugModule2,
public ICorDebugModule3,
public ICorDebugModule4
{
int m_debuggerId; // id on mono side;
CordbProcess* m_pProcess;
RegMeta* m_pRegMeta;
CordbAssembly* m_pAssembly;
CLiteWeightStgdbRW* m_pStgdbRW;
CORDB_ADDRESS m_pPeImage;
int32_t m_nPeImageSize;
unsigned long dwFlags;
char * m_pAssemblyName;
int m_nAssemblyNameLen;
public:
CordbModule(Connection* conn, CordbProcess* process, CordbAssembly* assembly, int id_assembly);
ULONG STDMETHODCALLTYPE AddRef(void)
{
return (BaseAddRef());
}
ULONG STDMETHODCALLTYPE Release(void)
{
return (BaseRelease());
}
const char* GetClassName()
{
return "CordbModule";
}
~CordbModule();
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID id, void** pInterface);
HRESULT STDMETHODCALLTYPE IsMappedLayout(BOOL* pIsMapped);
HRESULT STDMETHODCALLTYPE CreateReaderForInMemorySymbols(REFIID riid, void** ppObj);
HRESULT STDMETHODCALLTYPE SetJMCStatus(BOOL bIsJustMyCode, ULONG32 cTokens, mdToken pTokens[]);
HRESULT STDMETHODCALLTYPE ApplyChanges(ULONG cbMetadata, BYTE pbMetadata[], ULONG cbIL, BYTE pbIL[]);
HRESULT STDMETHODCALLTYPE SetJITCompilerFlags(DWORD dwFlags);
HRESULT STDMETHODCALLTYPE GetJITCompilerFlags(DWORD* pdwFlags);
HRESULT STDMETHODCALLTYPE ResolveAssembly(mdToken tkAssemblyRef, ICorDebugAssembly** ppAssembly);
HRESULT STDMETHODCALLTYPE GetProcess(ICorDebugProcess** ppProcess);
HRESULT STDMETHODCALLTYPE GetBaseAddress(CORDB_ADDRESS* pAddress);
HRESULT STDMETHODCALLTYPE GetAssembly(ICorDebugAssembly** ppAssembly);
HRESULT STDMETHODCALLTYPE GetName(ULONG32 cchName, ULONG32* pcchName, WCHAR szName[]);
HRESULT STDMETHODCALLTYPE EnableJITDebugging(BOOL bTrackJITInfo, BOOL bAllowJitOpts);
HRESULT STDMETHODCALLTYPE EnableClassLoadCallbacks(BOOL bClassLoadCallbacks);
HRESULT STDMETHODCALLTYPE GetFunctionFromToken(mdMethodDef methodDef, ICorDebugFunction** ppFunction);
HRESULT STDMETHODCALLTYPE GetFunctionFromRVA(CORDB_ADDRESS rva, ICorDebugFunction** ppFunction);
HRESULT STDMETHODCALLTYPE GetClassFromToken(mdTypeDef typeDef, ICorDebugClass** ppClass);
HRESULT STDMETHODCALLTYPE CreateBreakpoint(ICorDebugModuleBreakpoint** ppBreakpoint);
HRESULT STDMETHODCALLTYPE GetEditAndContinueSnapshot(ICorDebugEditAndContinueSnapshot** ppEditAndContinueSnapshot);
HRESULT STDMETHODCALLTYPE GetMetaDataInterface(REFIID riid, IUnknown** ppObj);
HRESULT STDMETHODCALLTYPE GetToken(mdModule* pToken);
HRESULT STDMETHODCALLTYPE IsDynamic(BOOL* pDynamic);
HRESULT STDMETHODCALLTYPE GetGlobalVariableValue(mdFieldDef fieldDef, ICorDebugValue** ppValue);
HRESULT STDMETHODCALLTYPE GetSize(ULONG32* pcBytes);
HRESULT STDMETHODCALLTYPE IsInMemory(BOOL* pInMemory);
int GetDebuggerId() const
{
return m_debuggerId;
}
};
class CordbAssembly : public CordbBaseMono, public ICorDebugAssembly, public ICorDebugAssembly2
{
CordbProcess* m_pProcess;
CordbAppDomain* m_pAppDomain;
int m_debuggerId;
char* m_pAssemblyName;
int m_nAssemblyNameLen;
public:
CordbAssembly(Connection* conn, CordbProcess* process, CordbAppDomain* appDomain, int id_assembly);
ULONG STDMETHODCALLTYPE AddRef(void)
{
return (BaseAddRef());
}
ULONG STDMETHODCALLTYPE Release(void)
{
return (BaseRelease());
}
const char* GetClassName()
{
return "CordbAssembly";
}
~CordbAssembly();
HRESULT STDMETHODCALLTYPE IsFullyTrusted(BOOL* pbFullyTrusted);
HRESULT STDMETHODCALLTYPE GetProcess(ICorDebugProcess** ppProcess);
HRESULT STDMETHODCALLTYPE GetAppDomain(ICorDebugAppDomain** ppAppDomain);
HRESULT STDMETHODCALLTYPE EnumerateModules(ICorDebugModuleEnum** ppModules);
HRESULT STDMETHODCALLTYPE GetCodeBase(ULONG32 cchName, ULONG32* pcchName, WCHAR szName[]);
HRESULT STDMETHODCALLTYPE GetName(ULONG32 cchName, ULONG32* pcchName, WCHAR szName[]);
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID id, _COM_Outptr_ void __RPC_FAR* __RPC_FAR* ppInterface);
};
#endif
| 1,947 |
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.plugins.importers;
import static com.igormaznitsa.mindmap.swing.panel.StandardTopicAttribute.ATTR_FILL_COLOR;
import static com.igormaznitsa.mindmap.swing.panel.StandardTopicAttribute.ATTR_TEXT_COLOR;
import com.igormaznitsa.meta.common.utils.Assertions;
import com.igormaznitsa.mindmap.model.Extra;
import com.igormaznitsa.mindmap.model.ExtraFile;
import com.igormaznitsa.mindmap.model.ExtraLink;
import com.igormaznitsa.mindmap.model.ExtraNote;
import com.igormaznitsa.mindmap.model.ExtraTopic;
import com.igormaznitsa.mindmap.model.MMapURI;
import com.igormaznitsa.mindmap.model.MindMap;
import com.igormaznitsa.mindmap.model.Topic;
import com.igormaznitsa.mindmap.model.logger.Logger;
import com.igormaznitsa.mindmap.model.logger.LoggerFactory;
import com.igormaznitsa.mindmap.plugins.api.AbstractImporter;
import com.igormaznitsa.mindmap.plugins.api.PluginContext;
import com.igormaznitsa.mindmap.plugins.attributes.images.ImageVisualAttributePlugin;
import com.igormaznitsa.mindmap.swing.panel.MindMapPanel;
import com.igormaznitsa.mindmap.swing.panel.Texts;
import com.igormaznitsa.mindmap.swing.panel.ui.AbstractCollapsableElement;
import com.igormaznitsa.mindmap.swing.panel.utils.Utils;
import com.igormaznitsa.mindmap.swing.services.IconID;
import com.igormaznitsa.mindmap.swing.services.ImageIconServiceProvider;
import java.awt.Color;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.swing.Icon;
import org.apache.commons.io.FileUtils;
import org.json.JSONArray;
import org.json.JSONObject;
public class Mindmup2MindMapImporter extends AbstractImporter {
private static final Icon ICO = ImageIconServiceProvider.findInstance().getIconForId(IconID.POPUP_EXPORT_MINDMUP);
private static final Logger LOGGER = LoggerFactory.getLogger(Mindmup2MindMapImporter.class);
@Override
@Nullable
public MindMap doImport(@Nonnull final PluginContext context) throws Exception {
final File file = this.selectFileForExtension(context, Texts.getString("MMDImporters.Mindmup2MindMap.openDialogTitle"), null, "mup", "Mindmup files (.MUP)", Texts.getString("MMDImporters.ApproveImport"));
if (file == null) {
return null;
}
final JSONObject parsedJson;
parsedJson = new JSONObject(FileUtils.readFileToString(file, "UTF-8"));
MindMap resultedMap = null;
final Number formatVersion = parsedJson.getNumber("formatVersion");
if (formatVersion == null) {
context.getDialogProvider().msgError(null, Texts.getString("MMDImporters.Mindmup2MindMap.Error.WrongFormat"));
} else {
resultedMap = new MindMap(true);
resultedMap.setAttribute(MindMapPanel.ATTR_SHOW_JUMPS, "true");
final Topic mindMapRoot = Assertions.assertNotNull(resultedMap.getRoot());
final Map<Long, Topic> mapTopicId = new HashMap<>();
parseTopic(resultedMap, null, mindMapRoot, parsedJson, mapTopicId);
if (!mindMapRoot.getExtras().containsKey(Extra.ExtraType.FILE)) {
mindMapRoot.setExtra(new ExtraFile(new MMapURI(null, file, null)));
}
if (parsedJson.has("links")) {
final JSONArray links = parsedJson.getJSONArray("links");
processLinks(resultedMap, links, mapTopicId);
}
}
return resultedMap;
}
private void processLinks(@Nonnull final MindMap map, @Nonnull final JSONArray links, @Nonnull final Map<Long, Topic> topics) {
for (int i = 0; i < links.length(); i++) {
try {
final JSONObject linkObject = links.getJSONObject(i);
final Topic fromTopic = topics.get(linkObject.optLong("ideaIdFrom", Long.MIN_VALUE));
final Topic toTopic = topics.get(linkObject.optLong("ideaIdTo", Long.MIN_VALUE));
if (fromTopic != null && toTopic != null) {
fromTopic.setExtra(ExtraTopic.makeLinkTo(map, toTopic));
}
} catch (final Exception ex) {
LOGGER.error("Can't parse link", ex);
}
}
}
private void parseTopic(@Nonnull MindMap map, @Nullable final Topic parentTopic, @Nullable final Topic pregeneratedTopic, @Nonnull final JSONObject json, @Nonnull final Map<Long, Topic> idTopicMap) {
final JSONObject ideas = json.optJSONObject("ideas");
if (ideas != null) {
final List<OrderableIdea> sortedIdeas = new ArrayList<>();
for (final String key : ideas.keySet()) {
final JSONObject idea = ideas.optJSONObject(key);
if (idea == null) {
continue;
}
double order = 0.0d;
try {
order = Double.parseDouble(key.trim());
} catch (final NumberFormatException ex) {
LOGGER.error("Detected unexpected number format in order", ex);
}
sortedIdeas.add(new OrderableIdea(order, idea));
}
Collections.sort(sortedIdeas);
for (final OrderableIdea i : sortedIdeas) {
final JSONObject ideaObject = i.getIdea();
final String title = ideaObject.optString("title", "");
final long id = ideaObject.optLong("id", Long.MIN_VALUE);
final Topic topicToProcess;
if (pregeneratedTopic == null) {
topicToProcess = Assertions.assertNotNull(parentTopic).makeChild(title.trim(), parentTopic);
if (Assertions.assertNotNull(topicToProcess.getParent()).isRoot()) {
if (i.isLeftBranch()) {
AbstractCollapsableElement.makeTopicLeftSided(topicToProcess, true);
final Topic firstSibling = Assertions.assertNotNull(parentTopic).getFirst();
if (firstSibling != null && firstSibling != topicToProcess) {
topicToProcess.moveBefore(firstSibling);
}
}
}
} else {
topicToProcess = pregeneratedTopic;
topicToProcess.setText(title.trim());
}
if (id != Long.MIN_VALUE) {
idTopicMap.put(id, topicToProcess);
}
final JSONObject attributes = ideaObject.optJSONObject("attr");
if (attributes != null) {
for (final String key : attributes.keySet()) {
final JSONObject attrJson = attributes.optJSONObject(key);
if (attrJson != null) {
if ("note".equals(key)) {
processAttrNote(attrJson, topicToProcess);
} else if ("icon".equals(key)) {
processAttrIcon(attrJson, topicToProcess);
} else if ("style".equals(key)) {
processAttrStyle(attrJson, topicToProcess);
} else {
LOGGER.warn("Detected unsupported attribute '" + key + '\'');
}
}
}
}
if (id >= 0L) {
idTopicMap.put(id, topicToProcess);
}
parseTopic(map, topicToProcess, null, ideaObject, idTopicMap);
if (parentTopic == null && pregeneratedTopic != null) {
// process only root
break;
}
}
}
}
private void processAttrNote(@Nonnull final JSONObject note, @Nonnull final Topic topic) {
topic.setExtra(new ExtraNote(note.optString("text", "")));
}
private void processAttrIcon(@Nonnull final JSONObject icon, @Nonnull final Topic topic) {
final String iconUrl = icon.getString("url");
if (iconUrl.startsWith("data:")) {
final String[] data = iconUrl.split("\\,");
if (data.length == 2 && data[0].startsWith("data:image/") && data[0].endsWith("base64")) {
try {
final String encoded = Utils.rescaleImageAndEncodeAsBase64(new ByteArrayInputStream(Utils.base64decode(data[1].trim())), -1);
if (encoded == null) {
LOGGER.warn("Can't convert image : " + iconUrl);
} else {
topic.setAttribute(ImageVisualAttributePlugin.ATTR_KEY, encoded);
}
} catch (final Exception ex) {
LOGGER.error("Can't load image : " + iconUrl, ex);
}
}
} else {
try {
topic.setExtra(new ExtraLink(iconUrl));
} catch (final URISyntaxException ex) {
LOGGER.error("Can't parse URI : " + iconUrl);
}
}
}
private void processAttrStyle(@Nonnull final JSONObject style, @Nonnull final Topic topic) {
final String background = style.getString("background");
if (background != null) {
final Color color = Utils.html2color(background, false);
if (color != null) {
topic.setAttribute(ATTR_FILL_COLOR.getText(), Utils.color2html(color, false));
topic.setAttribute(ATTR_TEXT_COLOR.getText(), Utils.color2html(Utils.makeContrastColor(color), false));
}
}
}
@Override
@Nullable
public String getMnemonic() {
return "mindmup";
}
@Override
@Nonnull
public String getName(@Nonnull final PluginContext context) {
return Texts.getString("MMDImporters.Mindmup2MindMap.Name");
}
@Override
@Nonnull
public String getReference(@Nonnull final PluginContext context) {
return Texts.getString("MMDImporters.Mindmup2MindMap.Reference");
}
@Override
@Nonnull
public Icon getIcon(@Nonnull final PluginContext context) {
return ICO;
}
@Override
public int getOrder() {
return 2;
}
@Override
public boolean isCompatibleWithFullScreenMode() {
return false;
}
private static final class OrderableIdea implements Comparable<OrderableIdea> {
private final double order;
private final JSONObject idea;
private OrderableIdea(final double order, @Nonnull final JSONObject idea) {
this.order = order;
this.idea = idea;
}
private boolean isLeftBranch() {
return this.order < 0.0d;
}
@Nonnull
private JSONObject getIdea() {
return this.idea;
}
@Override
public int compareTo(@Nonnull final OrderableIdea that) {
return Double.compare(this.order, that.order);
}
}
}
| 4,128 |
13,566 | <reponame>Priya098098/appsmith
package com.appsmith.server.repositories;
import com.appsmith.server.domains.Config;
import org.springframework.data.mongodb.core.ReactiveMongoOperations;
import org.springframework.data.mongodb.core.convert.MongoConverter;
import org.springframework.stereotype.Component;
@Component
public class CustomConfigRepositoryImpl extends BaseAppsmithRepositoryImpl<Config> implements CustomConfigRepository {
public CustomConfigRepositoryImpl(ReactiveMongoOperations mongoOperations, MongoConverter mongoConverter) {
super(mongoOperations, mongoConverter);
}
}
| 192 |
455 | /*
* 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.cassandra.db.compaction;
import java.util.*;
import java.util.function.LongPredicate;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Ordering;
import org.apache.cassandra.io.sstable.format.SSTableReader;
import org.apache.cassandra.schema.TableMetadata;
import org.apache.cassandra.db.*;
import org.apache.cassandra.db.filter.ColumnFilter;
import org.apache.cassandra.db.partitions.PurgeFunction;
import org.apache.cassandra.db.partitions.UnfilteredPartitionIterator;
import org.apache.cassandra.db.partitions.UnfilteredPartitionIterators;
import org.apache.cassandra.db.rows.*;
import org.apache.cassandra.db.transform.Transformation;
import org.apache.cassandra.index.transactions.CompactionTransaction;
import org.apache.cassandra.io.sstable.ISSTableScanner;
import org.apache.cassandra.schema.CompactionParams.TombstoneOption;
/**
* Merge multiple iterators over the content of sstable into a "compacted" iterator.
* <p>
* On top of the actual merging the source iterators, this class:
* <ul>
* <li>purge gc-able tombstones if possible (see PurgeIterator below).</li>
* <li>update 2ndary indexes if necessary (as we don't read-before-write on index updates, index entries are
* not deleted on deletion of the base table data, which is ok because we'll fix index inconsistency
* on reads. This however mean that potentially obsolete index entries could be kept a long time for
* data that is not read often, so compaction "pro-actively" fix such index entries. This is mainly
* an optimization).</li>
* <li>invalidate cached partitions that are empty post-compaction. This avoids keeping partitions with
* only purgable tombstones in the row cache.</li>
* <li>keep tracks of the compaction progress.</li>
* </ul>
*/
public class CompactionIterator extends CompactionInfo.Holder implements UnfilteredPartitionIterator
{
private static final long UNFILTERED_TO_UPDATE_PROGRESS = 100;
private final OperationType type;
private final CompactionController controller;
private final List<ISSTableScanner> scanners;
private final ImmutableSet<SSTableReader> sstables;
private final int nowInSec;
private final UUID compactionId;
private final long totalBytes;
private long bytesRead;
private long totalSourceCQLRows;
/*
* counters for merged rows.
* array index represents (number of merged rows - 1), so index 0 is counter for no merge (1 row),
* index 1 is counter for 2 rows merged, and so on.
*/
private final long[] mergeCounters;
private final UnfilteredPartitionIterator compacted;
private final ActiveCompactionsTracker activeCompactions;
public CompactionIterator(OperationType type, List<ISSTableScanner> scanners, CompactionController controller, int nowInSec, UUID compactionId)
{
this(type, scanners, controller, nowInSec, compactionId, ActiveCompactionsTracker.NOOP);
}
@SuppressWarnings("resource") // We make sure to close mergedIterator in close() and CompactionIterator is itself an AutoCloseable
public CompactionIterator(OperationType type, List<ISSTableScanner> scanners, CompactionController controller, int nowInSec, UUID compactionId, ActiveCompactionsTracker activeCompactions)
{
this.controller = controller;
this.type = type;
this.scanners = scanners;
this.nowInSec = nowInSec;
this.compactionId = compactionId;
this.bytesRead = 0;
long bytes = 0;
for (ISSTableScanner scanner : scanners)
bytes += scanner.getLengthInBytes();
this.totalBytes = bytes;
this.mergeCounters = new long[scanners.size()];
this.activeCompactions = activeCompactions == null ? ActiveCompactionsTracker.NOOP : activeCompactions;
this.activeCompactions.beginCompaction(this); // note that CompactionTask also calls this, but CT only creates CompactionIterator with a NOOP ActiveCompactions
UnfilteredPartitionIterator merged = scanners.isEmpty()
? EmptyIterators.unfilteredPartition(controller.cfs.metadata())
: UnfilteredPartitionIterators.merge(scanners, listener());
merged = Transformation.apply(merged, new GarbageSkipper(controller));
merged = Transformation.apply(merged, new Purger(controller, nowInSec));
compacted = Transformation.apply(merged, new AbortableUnfilteredPartitionTransformation(this));
sstables = scanners.stream().map(ISSTableScanner::getBackingSSTables).flatMap(Collection::stream).collect(ImmutableSet.toImmutableSet());
}
public TableMetadata metadata()
{
return controller.cfs.metadata();
}
public CompactionInfo getCompactionInfo()
{
return new CompactionInfo(controller.cfs.metadata(),
type,
bytesRead,
totalBytes,
compactionId,
sstables);
}
private void updateCounterFor(int rows)
{
assert rows > 0 && rows - 1 < mergeCounters.length;
mergeCounters[rows - 1] += 1;
}
public long[] getMergedRowCounts()
{
return mergeCounters;
}
public long getTotalSourceCQLRows()
{
return totalSourceCQLRows;
}
private UnfilteredPartitionIterators.MergeListener listener()
{
return new UnfilteredPartitionIterators.MergeListener()
{
public UnfilteredRowIterators.MergeListener getRowMergeListener(DecoratedKey partitionKey, List<UnfilteredRowIterator> versions)
{
int merged = 0;
for (UnfilteredRowIterator iter : versions)
{
if (iter != null)
merged++;
}
assert merged > 0;
CompactionIterator.this.updateCounterFor(merged);
if (type != OperationType.COMPACTION || !controller.cfs.indexManager.hasIndexes())
return null;
Columns statics = Columns.NONE;
Columns regulars = Columns.NONE;
for (UnfilteredRowIterator iter : versions)
{
if (iter != null)
{
statics = statics.mergeTo(iter.columns().statics);
regulars = regulars.mergeTo(iter.columns().regulars);
}
}
final RegularAndStaticColumns regularAndStaticColumns = new RegularAndStaticColumns(statics, regulars);
// If we have a 2ndary index, we must update it with deleted/shadowed cells.
// we can reuse a single CleanupTransaction for the duration of a partition.
// Currently, it doesn't do any batching of row updates, so every merge event
// for a single partition results in a fresh cycle of:
// * Get new Indexer instances
// * Indexer::start
// * Indexer::onRowMerge (for every row being merged by the compaction)
// * Indexer::commit
// A new OpOrder.Group is opened in an ARM block wrapping the commits
// TODO: this should probably be done asynchronously and batched.
final CompactionTransaction indexTransaction =
controller.cfs.indexManager.newCompactionTransaction(partitionKey,
regularAndStaticColumns,
versions.size(),
nowInSec);
return new UnfilteredRowIterators.MergeListener()
{
public void onMergedPartitionLevelDeletion(DeletionTime mergedDeletion, DeletionTime[] versions)
{
}
public void onMergedRows(Row merged, Row[] versions)
{
indexTransaction.start();
indexTransaction.onRowMerge(merged, versions);
indexTransaction.commit();
}
public void onMergedRangeTombstoneMarkers(RangeTombstoneMarker mergedMarker, RangeTombstoneMarker[] versions)
{
}
public void close()
{
}
};
}
public void close()
{
}
};
}
private void updateBytesRead()
{
long n = 0;
for (ISSTableScanner scanner : scanners)
n += scanner.getCurrentPosition();
bytesRead = n;
}
public boolean hasNext()
{
return compacted.hasNext();
}
public UnfilteredRowIterator next()
{
return compacted.next();
}
public void remove()
{
throw new UnsupportedOperationException();
}
public void close()
{
try
{
compacted.close();
}
finally
{
activeCompactions.finishCompaction(this);
}
}
public String toString()
{
return this.getCompactionInfo().toString();
}
private class Purger extends PurgeFunction
{
private final CompactionController controller;
private DecoratedKey currentKey;
private LongPredicate purgeEvaluator;
private long compactedUnfiltered;
private Purger(CompactionController controller, int nowInSec)
{
super(nowInSec, controller.gcBefore, controller.compactingRepaired() ? Integer.MAX_VALUE : Integer.MIN_VALUE,
controller.cfs.getCompactionStrategyManager().onlyPurgeRepairedTombstones(),
controller.cfs.metadata.get().enforceStrictLiveness());
this.controller = controller;
}
@Override
protected void onEmptyPartitionPostPurge(DecoratedKey key)
{
if (type == OperationType.COMPACTION)
controller.cfs.invalidateCachedPartition(key);
}
@Override
protected void onNewPartition(DecoratedKey key)
{
currentKey = key;
purgeEvaluator = null;
}
@Override
protected void updateProgress()
{
totalSourceCQLRows++;
if ((++compactedUnfiltered) % UNFILTERED_TO_UPDATE_PROGRESS == 0)
updateBytesRead();
}
/*
* Evaluates whether a tombstone with the given deletion timestamp can be purged. This is the minimum
* timestamp for any sstable containing `currentKey` outside of the set of sstables involved in this compaction.
* This is computed lazily on demand as we only need this if there is tombstones and this a bit expensive
* (see #8914).
*/
protected LongPredicate getPurgeEvaluator()
{
if (purgeEvaluator == null)
{
purgeEvaluator = controller.getPurgeEvaluator(currentKey);
}
return purgeEvaluator;
}
}
/**
* Unfiltered row iterator that removes deleted data as provided by a "tombstone source" for the partition.
* The result produced by this iterator is such that when merged with tombSource it produces the same output
* as the merge of dataSource and tombSource.
*/
private static class GarbageSkippingUnfilteredRowIterator extends WrappingUnfilteredRowIterator
{
final UnfilteredRowIterator tombSource;
final DeletionTime partitionLevelDeletion;
final Row staticRow;
final ColumnFilter cf;
final TableMetadata metadata;
final boolean cellLevelGC;
DeletionTime tombOpenDeletionTime = DeletionTime.LIVE;
DeletionTime dataOpenDeletionTime = DeletionTime.LIVE;
DeletionTime openDeletionTime = DeletionTime.LIVE;
DeletionTime partitionDeletionTime;
DeletionTime activeDeletionTime;
Unfiltered tombNext = null;
Unfiltered dataNext = null;
Unfiltered next = null;
/**
* Construct an iterator that filters out data shadowed by the provided "tombstone source".
*
* @param dataSource The input row. The result is a filtered version of this.
* @param tombSource Tombstone source, i.e. iterator used to identify deleted data in the input row.
* @param cellLevelGC If false, the iterator will only look at row-level deletion times and tombstones.
* If true, deleted or overwritten cells within a surviving row will also be removed.
*/
protected GarbageSkippingUnfilteredRowIterator(UnfilteredRowIterator dataSource, UnfilteredRowIterator tombSource, boolean cellLevelGC)
{
super(dataSource);
this.tombSource = tombSource;
this.cellLevelGC = cellLevelGC;
metadata = dataSource.metadata();
cf = ColumnFilter.all(metadata);
activeDeletionTime = partitionDeletionTime = tombSource.partitionLevelDeletion();
// Only preserve partition level deletion if not shadowed. (Note: Shadowing deletion must not be copied.)
this.partitionLevelDeletion = dataSource.partitionLevelDeletion().supersedes(tombSource.partitionLevelDeletion()) ?
dataSource.partitionLevelDeletion() :
DeletionTime.LIVE;
Row dataStaticRow = garbageFilterRow(dataSource.staticRow(), tombSource.staticRow());
this.staticRow = dataStaticRow != null ? dataStaticRow : Rows.EMPTY_STATIC_ROW;
tombNext = advance(tombSource);
dataNext = advance(dataSource);
}
private static Unfiltered advance(UnfilteredRowIterator source)
{
return source.hasNext() ? source.next() : null;
}
@Override
public DeletionTime partitionLevelDeletion()
{
return partitionLevelDeletion;
}
public void close()
{
super.close();
tombSource.close();
}
@Override
public Row staticRow()
{
return staticRow;
}
@Override
public boolean hasNext()
{
// Produce the next element. This may consume multiple elements from both inputs until we find something
// from dataSource that is still live. We track the currently open deletion in both sources, as well as the
// one we have last issued to the output. The tombOpenDeletionTime is used to filter out content; the others
// to decide whether or not a tombstone is superseded, and to be able to surface (the rest of) a deletion
// range from the input when a suppressing deletion ends.
while (next == null && dataNext != null)
{
int cmp = tombNext == null ? -1 : metadata.comparator.compare(dataNext, tombNext);
if (cmp < 0)
{
if (dataNext.isRow())
next = ((Row) dataNext).filter(cf, activeDeletionTime, false, metadata);
else
next = processDataMarker();
}
else if (cmp == 0)
{
if (dataNext.isRow())
{
next = garbageFilterRow((Row) dataNext, (Row) tombNext);
}
else
{
tombOpenDeletionTime = updateOpenDeletionTime(tombOpenDeletionTime, tombNext);
activeDeletionTime = Ordering.natural().max(partitionDeletionTime,
tombOpenDeletionTime);
next = processDataMarker();
}
}
else // (cmp > 0)
{
if (tombNext.isRangeTombstoneMarker())
{
tombOpenDeletionTime = updateOpenDeletionTime(tombOpenDeletionTime, tombNext);
activeDeletionTime = Ordering.natural().max(partitionDeletionTime,
tombOpenDeletionTime);
boolean supersededBefore = openDeletionTime.isLive();
boolean supersededAfter = !dataOpenDeletionTime.supersedes(activeDeletionTime);
// If a range open was not issued because it was superseded and the deletion isn't superseded any more, we need to open it now.
if (supersededBefore && !supersededAfter)
next = new RangeTombstoneBoundMarker(((RangeTombstoneMarker) tombNext).closeBound(false).invert(), dataOpenDeletionTime);
// If the deletion begins to be superseded, we don't close the range yet. This can save us a close/open pair if it ends after the superseding range.
}
}
if (next instanceof RangeTombstoneMarker)
openDeletionTime = updateOpenDeletionTime(openDeletionTime, next);
if (cmp <= 0)
dataNext = advance(wrapped);
if (cmp >= 0)
tombNext = advance(tombSource);
}
return next != null;
}
protected Row garbageFilterRow(Row dataRow, Row tombRow)
{
if (cellLevelGC)
{
return Rows.removeShadowedCells(dataRow, tombRow, activeDeletionTime);
}
else
{
DeletionTime deletion = Ordering.natural().max(tombRow.deletion().time(),
activeDeletionTime);
return dataRow.filter(cf, deletion, false, metadata);
}
}
/**
* Decide how to act on a tombstone marker from the input iterator. We can decide what to issue depending on
* whether or not the ranges before and after the marker are superseded/live -- if none are, we can reuse the
* marker; if both are, the marker can be ignored; otherwise we issue a corresponding start/end marker.
*/
private RangeTombstoneMarker processDataMarker()
{
dataOpenDeletionTime = updateOpenDeletionTime(dataOpenDeletionTime, dataNext);
boolean supersededBefore = openDeletionTime.isLive();
boolean supersededAfter = !dataOpenDeletionTime.supersedes(activeDeletionTime);
RangeTombstoneMarker marker = (RangeTombstoneMarker) dataNext;
if (!supersededBefore)
if (!supersededAfter)
return marker;
else
return new RangeTombstoneBoundMarker(marker.closeBound(false), marker.closeDeletionTime(false));
else
if (!supersededAfter)
return new RangeTombstoneBoundMarker(marker.openBound(false), marker.openDeletionTime(false));
else
return null;
}
@Override
public Unfiltered next()
{
if (!hasNext())
throw new IllegalStateException();
Unfiltered v = next;
next = null;
return v;
}
private DeletionTime updateOpenDeletionTime(DeletionTime openDeletionTime, Unfiltered next)
{
RangeTombstoneMarker marker = (RangeTombstoneMarker) next;
assert openDeletionTime.isLive() == !marker.isClose(false);
assert openDeletionTime.isLive() || openDeletionTime.equals(marker.closeDeletionTime(false));
return marker.isOpen(false) ? marker.openDeletionTime(false) : DeletionTime.LIVE;
}
}
/**
* Partition transformation applying GarbageSkippingUnfilteredRowIterator, obtaining tombstone sources for each
* partition using the controller's shadowSources method.
*/
private static class GarbageSkipper extends Transformation<UnfilteredRowIterator>
{
final CompactionController controller;
final boolean cellLevelGC;
private GarbageSkipper(CompactionController controller)
{
this.controller = controller;
cellLevelGC = controller.tombstoneOption == TombstoneOption.CELL;
}
@Override
protected UnfilteredRowIterator applyToPartition(UnfilteredRowIterator partition)
{
Iterable<UnfilteredRowIterator> sources = controller.shadowSources(partition.partitionKey(), !cellLevelGC);
if (sources == null)
return partition;
List<UnfilteredRowIterator> iters = new ArrayList<>();
for (UnfilteredRowIterator iter : sources)
{
if (!iter.isEmpty())
iters.add(iter);
else
iter.close();
}
if (iters.isEmpty())
return partition;
return new GarbageSkippingUnfilteredRowIterator(partition, UnfilteredRowIterators.merge(iters), cellLevelGC);
}
}
private static class AbortableUnfilteredPartitionTransformation extends Transformation<UnfilteredRowIterator>
{
private final AbortableUnfilteredRowTransformation abortableIter;
private AbortableUnfilteredPartitionTransformation(CompactionIterator iter)
{
this.abortableIter = new AbortableUnfilteredRowTransformation(iter);
}
@Override
protected UnfilteredRowIterator applyToPartition(UnfilteredRowIterator partition)
{
if (abortableIter.iter.isStopRequested())
throw new CompactionInterruptedException(abortableIter.iter.getCompactionInfo());
return Transformation.apply(partition, abortableIter);
}
}
private static class AbortableUnfilteredRowTransformation extends Transformation
{
private final CompactionIterator iter;
private AbortableUnfilteredRowTransformation(CompactionIterator iter)
{
this.iter = iter;
}
public Row applyToRow(Row row)
{
if (iter.isStopRequested())
throw new CompactionInterruptedException(iter.getCompactionInfo());
return row;
}
}
}
| 10,327 |
937 | <reponame>zmyer/cyclops-react
package com.oath.cyclops.internal.react.exceptions;
public class SimpleReactProcessingException extends RuntimeException {
private static final long serialVersionUID = 1L;
public SimpleReactProcessingException() {
super();
}
public SimpleReactProcessingException(final String message, final Throwable cause, final boolean enableSuppression,
final boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public SimpleReactProcessingException(final String message, final Throwable cause) {
super(message, cause);
}
public SimpleReactProcessingException(final String message) {
super(message);
}
public SimpleReactProcessingException(final Throwable cause) {
super(cause);
}
@Override
public Throwable fillInStackTrace() {
return this;
}
}
| 314 |
368 | <gh_stars>100-1000
/*
Plugin-SDK (Grand Theft Auto 3) header file
Authors: GTA Community. See more here
https://github.com/DK22Pac/plugin-sdk
Do not delete this comment block. Respect others' work!
*/
#pragma once
#include "PluginBase.h"
class PLUGIN_API CDate {
PLUGIN_NO_DEFAULT_CONSTRUCTION(CDate)
public:
unsigned int m_nSecond;
unsigned int m_nMinute;
unsigned int m_nHour;
unsigned int m_nDay;
unsigned int m_nMonth;
unsigned int m_nYear;
inline bool operator>(const CDate &right) {
if (this->m_nYear > right.m_nYear)
return true;
if (this->m_nYear != right.m_nYear)
return false;
if (this->m_nMonth > right.m_nMonth)
return true;
if (this->m_nMonth != right.m_nMonth)
return false;
if (this->m_nDay > right.m_nDay)
return true;
if (this->m_nDay != right.m_nDay)
return false;
if (this->m_nHour > right.m_nHour)
return true;
if (this->m_nHour != right.m_nHour)
return false;
if (this->m_nMinute > right.m_nMinute)
return true;
if (this->m_nMinute != right.m_nMinute)
return false;
return this->m_nSecond > right.m_nSecond;
}
inline bool operator<(const CDate &right) {
if (this->m_nYear < right.m_nYear)
return true;
if (this->m_nYear != right.m_nYear)
return false;
if (this->m_nMonth < right.m_nMonth)
return true;
if (this->m_nMonth != right.m_nMonth)
return false;
if (this->m_nDay < right.m_nDay)
return true;
if (this->m_nDay != right.m_nDay)
return false;
if (this->m_nHour < right.m_nHour)
return true;
if (this->m_nHour != right.m_nHour)
return false;
if (this->m_nMinute < right.m_nMinute)
return true;
if (this->m_nMinute != right.m_nMinute)
return false;
return this->m_nSecond < right.m_nSecond;
}
inline bool operator==(const CDate &right) {
if (this->m_nYear != right.m_nYear || this->m_nMonth != right.m_nMonth || this->m_nDay != right.m_nDay || this->m_nHour != right.m_nHour || this->m_nMinute != right.m_nMinute)
return false;
return this->m_nSecond == right.m_nSecond;
}
inline void PopulateDateFields(char &second, char &minute, char &hour, char &day, char &month, short year) {
this->m_nSecond = second;
this->m_nMinute = minute;
this->m_nHour = hour;
this->m_nDay = day;
this->m_nMonth = month;
this->m_nYear = year;
}
};
VALIDATE_SIZE(CDate, 0x18);
#include "meta/meta.CDate.h"
| 1,385 |
5,169 | <reponame>ftapp/cocoapods
{
"name": "SMIconLabel",
"version": "0.3.0",
"summary": "UILabel with image placed on the left or right side",
"description": "UILabel with possibility to place small icon on the left or on the right side.\nTake a look at preview image or build smaple app to see how it works.",
"homepage": "https://github.com/anatoliyv/SMIconLabel",
"license": "MIT",
"authors": {
"<NAME>": "<EMAIL>"
},
"platforms": {
"ios": "8.0"
},
"source": {
"git": "https://github.com/anatoliyv/SMIconLabel.git",
"tag": "v.0.3.0"
},
"source_files": "SMIconLabel/*"
}
| 243 |
764 | {"symbol": "EGCC","address": "0xAf8A215e81FAea7C180CE22b72483525121813BD","overview":{"en": ""},"email": "<EMAIL>","website": "https://www.egcchain.com/","state": "NORMAL","links": {"blog": "","twitter": "https://twitter.com/enginechainegcc","telegram": "https://t.me/joinchat/IEbn1knC_iMb2cX16Dut3A","github": ""}} | 128 |
435 | <gh_stars>100-1000
{
"description": "As we move towards more customised experiences for our users, why do we\nstill insist of using the black boxes of male and female when asking\nusers about their gender? And why are we asking for it in the first\nplace?\n\nBetween 1 and 5 percent of the UK population identifies as having a\nnon-binary gender or are transgender. This talk aims to help developers\nask users about their gender in a useful and sensitive manner; educate\non what non-binary means and what other issues non-binary and gender\nvariant users may face when using the web.",
"duration": 1724,
"language": "eng",
"recorded": "2015-09-19",
"speakers": [
"<NAME>"
],
"thumbnail_url": "https://i.ytimg.com/vi/J1WJPyAh4Jw/hqdefault.jpg",
"title": "Asking About Gender - the Whats, Whys and Hows",
"videos": [
{
"type": "youtube",
"url": "https://www.youtube.com/watch?v=J1WJPyAh4Jw"
}
]
}
| 310 |
3,469 | <filename>QiChaCha/echarts_parks.py
from pyecharts.charts import Geo
from pyecharts import options as opts
from pyecharts.globals import ChartType, SymbolType
import pandas as pd
import csv
import json
csv_data = pd.read_csv("./csv/全国工业园区信息_addr.csv")
length = len(csv_data)
data = []
locations = []
for i in range(length):
park = csv_data.loc[i, 'park']
numcop = csv_data.loc[i, 'numcop']
parkxy = csv_data.loc[i, 'parkxy']
if ',' in str(parkxy):
# str_ = '\n\n' + str(numcop)+'\n' + '测试'
data.append([park, str(numcop)]) # 一定要写成字符串!!! 不然莫名其妙有bug, 针对pandas
locations.append([park, parkxy])
dat = [[i[0], int(i[1])] for i in data]
loc = {}
for l in locations:
park = l[0]
x = float(l[1].split(',')[0])
y = float(l[1].split(',')[1])
loc.update({park: [x, y]})
with open('jn_parks.json', 'w', encoding='utf8')as f:
json.dump(loc, f, ensure_ascii=False)
def bmap_visualmap_cities() -> Geo:
c = (
Geo()
.add_schema(maptype="china")
.add_coordinate_json('jn_parks.json')
.add(
"工业园区",
dat,
# "china",
is_selected=True,
symbol_size=5,
is_large=True,
progressive=4000
)
.set_series_opts(label_opts=opts.LabelOpts(is_show=False))
.set_global_opts(
visualmap_opts=opts.VisualMapOpts(
is_piecewise=True, min_=0, max_=100),
title_opts=opts.TitleOpts(title="全国工业园区企业数量分布图")
)
)
return c
c = bmap_visualmap_cities()
c.render('map.html')
| 885 |
1,056 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.core.multitabs.impl;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JTabbedPane;
import javax.swing.table.AbstractTableModel;
import org.netbeans.swing.tabcontrol.TabDataModel;
/**
*
* @author <NAME>
*/
class SingleRowTabTable extends TabTable {
private final ArrayList<Integer> tabIndexes;
public SingleRowTabTable( TabDataModel tabModel ) {
this( tabModel, new ArrayList<Integer>(30) );
}
private SingleRowTabTable( TabDataModel tabModel, ArrayList<Integer> tabIndexes ) {
super( TabTableModel.create( tabModel, tabIndexes ), JTabbedPane.HORIZONTAL );
this.tabIndexes = tabIndexes;
}
void setTabs( List<Integer> tabIndexes ) {
this.tabIndexes.clear();
this.tabIndexes.addAll( tabIndexes );
((AbstractTableModel)getModel()).fireTableStructureChanged();
}
boolean hasTabIndex( int tabIndex ) {
return tabIndexes.contains( tabIndex );
}
}
| 563 |
678 | <reponame>bzxy/cydia
/**
* This header is generated by class-dump-z 0.2b.
*
* Source: /System/Library/PrivateFrameworks/OfficeImport.framework/OfficeImport
*/
#import <OfficeImport/OfficeImport-Structs.h>
#import <OfficeImport/STSStgObject.h>
__attribute__((visibility("hidden")))
@interface STStream : STSStgObject {
@private
Stream *m_pCStream; // 4 = 0x4
}
- (id)initWithCStream:(Stream *)cstream; // 0x2c42ad
- (void)dealloc; // 0x2c4d15
- (void)close; // 0x2c4cf5
- (void)releaseCStream; // 0x2c4299
- (id)getInfo; // 0x2c4c15
- (void)seek:(long)seek fromOrigin:(int)origin; // 0x2c4bc5
- (unsigned long)getPos; // 0x2c4ba1
- (void)setClass:(SSRW_GUID)aClass; // 0x2c4b4d
- (id)readBytes:(unsigned long)bytes; // 0x2c4a89
- (BOOL)readLEchar; // 0x2c4a3d
- (unsigned char)readLEbyte; // 0x2c49f1
- (unsigned char)readLEboolean; // 0x2c4999
- (short)readLEshort; // 0x2c4951
- (unsigned short)readLEword; // 0x2c4909
- (long)readLElong; // 0x2c48c5
- (unsigned long)readLEdword; // 0x2c4881
- (float)readLEfloat; // 0x2c483d
- (double)readLEdouble; // 0x2c47ed
- (unsigned short)readLEunichar; // 0x2c47a9
- (id)readLEwstring:(unsigned long)ewstring; // 0x2c4695
- (void)writeBytes:(id)bytes; // 0x2c4625
- (void)writeLEbyte:(unsigned char)ebyte; // 0x2c45dd
- (void)writeLEchar:(BOOL)echar; // 0x2c4595
- (void)writeLEboolean:(unsigned char)eboolean; // 0x2c454d
- (void)writeLEshort:(short)eshort; // 0x2c4511
- (void)writeLEword:(unsigned short)eword; // 0x2c44d5
- (void)writeLElong:(long)elong; // 0x2c4499
- (void)writeLEdword:(unsigned long)edword; // 0x2c445d
- (void)writeLEfloat:(float)efloat; // 0x2c4421
- (void)writeLEdouble:(double)edouble; // 0x2c43e5
- (void)writeLEunichar:(unsigned short)eunichar; // 0x2c43d1
- (void)writeLEwstring:(id)ewstring; // 0x2c4361
- (void)writeLEwstringNoTerminator:(id)terminator; // 0x2c42f1
@end
| 833 |
335 | {
"word": "Haphazard",
"definitions": [
"Lacking any obvious principle of organization."
],
"parts-of-speech": "Adjective"
} | 62 |
309 | {"provider_arguments":[],"resources":{"cloudinit_config":{"arguments":[{"word":"base64_encode","kind":"Bool(O)"},{"word":"gzip","kind":"Bool(O)"},{"word":"part","kind":"List(R)(B)","subblock":[{"word":"content","kind":"String(R)"},{"word":"content_type","kind":"String(O)"},{"word":"filename","kind":"String(O)"},{"word":"merge_type","kind":"String(O)"}]}],"attributes":[{"word":"base64_encode","kind":"Bool"},{"word":"gzip","kind":"Bool"},{"word":"part","kind":"List(B)","subblock":[{"word":"content","kind":"String"},{"word":"content_type","kind":"String"},{"word":"filename","kind":"String"},{"word":"merge_type","kind":"String"},{"word":"id","kind":"String"}]},{"word":"rendered","kind":"String","info":"rendered cloudinit configuration"},{"word":"id","kind":"String"}]},"dir":{"arguments":[{"word":"destination_dir","kind":"String(R)","info":"Path to the directory where the templated files will be written"},{"word":"source_dir","kind":"String(R)","info":"Path to the directory where the files to template reside"},{"word":"vars","kind":"Map(O)","info":"Variables to substitute"}],"attributes":[{"word":"destination_dir","kind":"String","info":"Path to the directory where the templated files will be written"},{"word":"source_dir","kind":"String","info":"Path to the directory where the files to template reside"},{"word":"vars","kind":"Map","info":"Variables to substitute"},{"word":"id","kind":"String"}]},"file":{"arguments":[{"word":"filename","kind":"String(O)","info":"file to read template from"},{"word":"template","kind":"String(O)","info":"Contents of the template"},{"word":"vars","kind":"Map(O)","info":"variables to substitute"}],"attributes":[{"word":"filename","kind":"String","info":"file to read template from"},{"word":"rendered","kind":"String","info":"rendered template"},{"word":"template","kind":"String","info":"Contents of the template"},{"word":"vars","kind":"Map","info":"variables to substitute"},{"word":"id","kind":"String"}]}},"datas":{"cloudinit_config":{"arguments":[{"word":"base64_encode","kind":"Bool(O)"},{"word":"gzip","kind":"Bool(O)"},{"word":"part","kind":"List(R)(B)","subblock":[{"word":"content","kind":"String(R)"},{"word":"content_type","kind":"String(O)"},{"word":"filename","kind":"String(O)"},{"word":"merge_type","kind":"String(O)"}]}],"attributes":[{"word":"base64_encode","kind":"Bool"},{"word":"gzip","kind":"Bool"},{"word":"part","kind":"List(B)","subblock":[{"word":"content","kind":"String"},{"word":"content_type","kind":"String"},{"word":"filename","kind":"String"},{"word":"merge_type","kind":"String"},{"word":"id","kind":"String"}]},{"word":"rendered","kind":"String","info":"rendered cloudinit configuration"},{"word":"id","kind":"String"}]},"file":{"arguments":[{"word":"filename","kind":"String(O)","info":"file to read template from"},{"word":"template","kind":"String(O)","info":"Contents of the template"},{"word":"vars","kind":"Map(O)","info":"variables to substitute"}],"attributes":[{"word":"filename","kind":"String","info":"file to read template from"},{"word":"rendered","kind":"String","info":"rendered template"},{"word":"template","kind":"String","info":"Contents of the template"},{"word":"vars","kind":"Map","info":"variables to substitute"},{"word":"id","kind":"String"}]}},"unknowns":{}} | 877 |
22,688 | /******************************************************************************
* Copyright 2018 The Apollo 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 "modules/canbus/vehicle/transit/protocol/adc_motioncontrollimits1_12.h"
#include "gtest/gtest.h"
#include "modules/drivers/canbus/common/byte.h"
#include "modules/drivers/canbus/common/canbus_consts.h"
namespace apollo {
namespace canbus {
namespace transit {
using ::apollo::drivers::canbus::Byte;
class Motioncontrollimits1_12_test : public ::testing::Test {
public:
virtual void SetUp() {}
protected:
Adcmotioncontrollimits112 controllimits_;
};
TEST_F(Motioncontrollimits1_12_test, General) {
uint8_t data[8] = {0x8f, 0x9e, 0xad, 0xbc, 0xcb, 0xda, 0xe9, 0xf8};
const double adc_cmd_throttlecommandlimit = 64.00;
const double adc_cmd_steeringrate = 3071.15;
const double adc_cmd_steerwheelanglelimit = 640.0;
const uint8_t equivalent_throttlecommandlimit = 0x80;
const uint8_t equivalent_steeringrate1 = 0xef;
const uint8_t equivalent_steeringrate2 = 0xef;
const uint8_t equivalent_steerwheelanglelimit = 0x80;
controllimits_.set_p_adc_cmd_throttlecommandlimit(
data, adc_cmd_throttlecommandlimit);
controllimits_.set_p_adc_cmd_steeringrate(data, adc_cmd_steeringrate);
controllimits_.set_p_adc_cmd_steerwheelanglelimit(
data, adc_cmd_steerwheelanglelimit);
EXPECT_EQ(data[3], equivalent_throttlecommandlimit);
EXPECT_EQ(data[0], equivalent_steeringrate1);
EXPECT_EQ(data[1], equivalent_steeringrate2);
EXPECT_EQ(data[2], equivalent_steerwheelanglelimit);
}
} // namespace transit
} // namespace canbus
} // namespace apollo
| 736 |
794 | /******************************************************************************
* Author: <NAME> *
* Contact: <EMAIL> *
* License: Copyright (c) 2013 <NAME>, ANU. 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 ANU 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 ANU OR THE CONTRIBUTORS BE LIABLE *
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL *
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR *
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER *
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT *
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY *
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF *
* SUCH DAMAGE. *
******************************************************************************/
#include <opengv/absolute_pose/NoncentralAbsoluteMultiAdapter.hpp>
opengv::absolute_pose::NoncentralAbsoluteMultiAdapter::NoncentralAbsoluteMultiAdapter(
std::vector<std::shared_ptr<bearingVectors_t> > bearingVectors,
std::vector<std::shared_ptr<points_t> > points,
const translations_t & camOffsets,
const rotations_t & camRotations ) :
_bearingVectors(bearingVectors),
_points(points),
_camOffsets(camOffsets),
_camRotations(camRotations)
{
// The following variables are needed for the serialization and
// de-serialization of indices
size_t singleIndexOffset = 0;
for( size_t frameIndex = 0; frameIndex < bearingVectors.size(); frameIndex++ )
{
singleIndexOffsets.push_back(singleIndexOffset);
for(
size_t correspondenceIndex = 0;
correspondenceIndex < bearingVectors[frameIndex]->size();
correspondenceIndex++ )
{
multiFrameIndices.push_back(frameIndex);
multiKeypointIndices.push_back(correspondenceIndex);
}
singleIndexOffset += bearingVectors[frameIndex]->size();
}
}
opengv::absolute_pose::NoncentralAbsoluteMultiAdapter::~NoncentralAbsoluteMultiAdapter()
{}
opengv::point_t
opengv::absolute_pose::NoncentralAbsoluteMultiAdapter::
getPoint( size_t frameIndex, size_t correspondenceIndex ) const
{
assert(frameIndex < _points.size());
assert(correspondenceIndex < _points[frameIndex]->size());
return (*_points[frameIndex])[correspondenceIndex];
}
opengv::bearingVector_t
opengv::absolute_pose::NoncentralAbsoluteMultiAdapter::
getBearingVector( size_t frameIndex, size_t correspondenceIndex ) const
{
assert(frameIndex < _bearingVectors.size());
assert(correspondenceIndex < _bearingVectors[frameIndex]->size());
return (*_bearingVectors[frameIndex])[correspondenceIndex];
}
double
opengv::absolute_pose::NoncentralAbsoluteMultiAdapter::
getWeight( size_t frameIndex, size_t correspondenceIndex ) const
{
return 1.0;
}
opengv::translation_t
opengv::absolute_pose::NoncentralAbsoluteMultiAdapter::
getMultiCamOffset( size_t frameIndex ) const
{
assert(frameIndex < _camOffsets.size());
return _camOffsets[frameIndex];
}
opengv::rotation_t
opengv::absolute_pose::NoncentralAbsoluteMultiAdapter::
getMultiCamRotation( size_t frameIndex ) const
{
assert(frameIndex < _camRotations.size());
return _camRotations[frameIndex];
}
size_t
opengv::absolute_pose::NoncentralAbsoluteMultiAdapter::
getNumberCorrespondences(size_t frameIndex) const
{
assert(frameIndex < _bearingVectors.size());
return _bearingVectors[frameIndex]->size();
}
size_t
opengv::absolute_pose::NoncentralAbsoluteMultiAdapter::
getNumberFrames() const
{
return _camOffsets.size();
}
//important conversion between the serialized and the multi interface
std::vector<int>
opengv::absolute_pose::NoncentralAbsoluteMultiAdapter::
convertMultiIndices( const std::vector<std::vector<int> > & multiIndices ) const
{
std::vector<int> singleIndices;
for(size_t frameIndex = 0; frameIndex < multiIndices.size(); frameIndex++)
{
for(
size_t correspondenceIndex = 0;
correspondenceIndex < multiIndices[frameIndex].size();
correspondenceIndex++ )
{
singleIndices.push_back(convertMultiIndex(
frameIndex, multiIndices[frameIndex][correspondenceIndex] ));
}
}
return singleIndices;
}
int
opengv::absolute_pose::NoncentralAbsoluteMultiAdapter::
convertMultiIndex( size_t frameIndex, size_t correspondenceIndex ) const
{
return singleIndexOffsets[frameIndex]+correspondenceIndex;
}
int
opengv::absolute_pose::NoncentralAbsoluteMultiAdapter::
multiFrameIndex( size_t index ) const
{
return multiFrameIndices[index];
}
int
opengv::absolute_pose::NoncentralAbsoluteMultiAdapter::
multiCorrespondenceIndex( size_t index ) const
{
return multiKeypointIndices[index];
}
| 2,278 |
2,813 | <filename>src/main/java/org/jabref/logic/pdf/search/indexing/IndexingTaskManager.java
package org.jabref.logic.pdf.search.indexing;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.jabref.gui.util.BackgroundTask;
import org.jabref.gui.util.DefaultTaskExecutor;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.LinkedFile;
/**
* Wrapper around {@link PdfIndexer} to execute all operations in the background.
*/
public class IndexingTaskManager extends BackgroundTask<Void> {
private final Queue<Runnable> taskQueue = new ConcurrentLinkedQueue<>();
private TaskExecutor taskExecutor;
private int numOfIndexedFiles = 0;
private final Object lock = new Object();
private boolean isRunning = false;
public IndexingTaskManager(TaskExecutor taskExecutor) {
this.taskExecutor = taskExecutor;
showToUser(true);
DefaultTaskExecutor.runInJavaFXThread(() -> {
this.updateProgress(1, 1);
this.titleProperty().set(Localization.lang("Indexing pdf files"));
});
}
@Override
protected Void call() throws Exception {
synchronized (lock) {
isRunning = true;
}
updateProgress();
while (!taskQueue.isEmpty() && !isCanceled()) {
taskQueue.poll().run();
numOfIndexedFiles++;
updateProgress();
}
synchronized (lock) {
isRunning = false;
}
return null;
}
private void updateProgress() {
DefaultTaskExecutor.runInJavaFXThread(() -> {
updateMessage(Localization.lang("%0 of %1 linked files added to the index", numOfIndexedFiles, numOfIndexedFiles + taskQueue.size()));
updateProgress(numOfIndexedFiles, numOfIndexedFiles + taskQueue.size());
});
}
private void enqueueTask(Runnable indexingTask) {
taskQueue.add(indexingTask);
// What if already running?
synchronized (lock) {
if (!isRunning) {
isRunning = true;
this.executeWith(taskExecutor);
showToUser(false);
}
}
}
public void createIndex(PdfIndexer indexer) {
enqueueTask(() -> indexer.createIndex());
}
public void addToIndex(PdfIndexer indexer, BibDatabaseContext databaseContext) {
for (BibEntry entry : databaseContext.getEntries()) {
for (LinkedFile file : entry.getFiles()) {
enqueueTask(() -> indexer.addToIndex(entry, file, databaseContext));
}
}
}
public void addToIndex(PdfIndexer indexer, BibEntry entry, BibDatabaseContext databaseContext) {
enqueueTask(() -> addToIndex(indexer, entry, entry.getFiles(), databaseContext));
}
public void addToIndex(PdfIndexer indexer, BibEntry entry, List<LinkedFile> linkedFiles, BibDatabaseContext databaseContext) {
for (LinkedFile file : linkedFiles) {
enqueueTask(() -> indexer.addToIndex(entry, file, databaseContext));
}
}
public void removeFromIndex(PdfIndexer indexer, BibEntry entry, List<LinkedFile> linkedFiles) {
for (LinkedFile file : linkedFiles) {
enqueueTask(() -> indexer.removeFromIndex(entry, file));
}
}
public void removeFromIndex(PdfIndexer indexer, BibEntry entry) {
enqueueTask(() -> removeFromIndex(indexer, entry, entry.getFiles()));
}
public void updateDatabaseName(String name) {
DefaultTaskExecutor.runInJavaFXThread(() -> this.titleProperty().set(Localization.lang("Indexing for %0", name)));
}
}
| 1,506 |
1,346 | <filename>app/src/main/java/com/huanchengfly/tieba/post/components/spans/RoundBackgroundColorSpan.java
package com.huanchengfly.tieba.post.components.spans;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.text.TextPaint;
import android.text.style.ReplacementSpan;
import com.huanchengfly.tieba.post.utils.DisplayUtil;
public class RoundBackgroundColorSpan extends ReplacementSpan {
private Context context;
private float fontSizePx; //px
private int bgColor;
private int textColor;
public RoundBackgroundColorSpan(Context context, int bgColor, int textColor, float fontSizePx) {
super();
this.context = context;
this.bgColor = bgColor;
this.textColor = textColor;
this.fontSizePx = fontSizePx;
}
@Override
public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
return ((int) getCustomTextPaint(paint).measureText(text, start, end) + DisplayUtil.dp2px(context, 12));
}
@Override
public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
int color1 = paint.getColor();
Paint textPaint = getCustomTextPaint(paint);
paint.setColor(this.bgColor);
paint.setStyle(Paint.Style.FILL);
paint.setAntiAlias(true);
int padding = DisplayUtil.dp2px(context, 1);
canvas.drawRoundRect(new RectF(x, top + padding, x + ((int) textPaint.measureText(text, start, end) + DisplayUtil.dp2px(context, 10)), bottom - padding),
DisplayUtil.dp2px(context, 50),
DisplayUtil.dp2px(context, 50),
paint);
paint.setColor(this.textColor);
paint.setStyle(Paint.Style.FILL);
paint.setAntiAlias(false);
Paint.FontMetricsInt fm = textPaint.getFontMetricsInt();
canvas.drawText(text, start, end, x + DisplayUtil.dp2px(context, 5), y - ((y + fm.descent + y + fm.ascent) / 2 - (bottom + top) / 2), textPaint);
paint.setColor(color1);
}
private TextPaint getCustomTextPaint(Paint srcPaint) {
TextPaint paint = new TextPaint(srcPaint);
paint.setColor(this.textColor);
paint.setTextSize(fontSizePx);
return paint;
}
} | 961 |
384 | /*
* This file is part of the GROMACS molecular simulation package.
*
* Copyright (c) 2019,2020,2021, by the GROMACS development team, led by
* <NAME>, <NAME>, <NAME>, and <NAME>,
* and including many others, as listed in the AUTHORS file in the
* top-level source directory and at http://www.gromacs.org.
*
* GROMACS 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.
*
* GROMACS 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 GROMACS; if not, see
* http://www.gnu.org/licenses, or write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* If you want to redistribute modifications to GROMACS, please
* consider that scientific software is very special. Version
* control is crucial - bugs must be traceable. We will be happy to
* consider code for inclusion in the official distribution, but
* derived work must not be called official GROMACS. Details are found
* in the README & COPYING files - if they are missing, get the
* official version at http://www.gromacs.org.
*
* To help us fund GROMACS development, we humbly ask that you cite
* the research papers on the package. Check out http://www.gromacs.org.
*/
/*! \internal \file
* \brief Runner for GPU version of the integrator
*
* Handles GPU data management and actual numerical integration.
*
* \author <NAME> <<EMAIL>>
* \ingroup module_mdlib
*/
#include "gmxpre.h"
#include "config.h"
#include <gtest/gtest.h>
#include "leapfrogtestrunners.h"
#if GPU_LEAPFROG_SUPPORTED
# include "gromacs/gpu_utils/devicebuffer.h"
#endif
#include "gromacs/gpu_utils/gputraits.h"
#include "gromacs/mdlib/leapfrog_gpu.h"
#include "gromacs/mdlib/stat.h"
namespace gmx
{
namespace test
{
#if GPU_LEAPFROG_SUPPORTED
void LeapFrogDeviceTestRunner::integrate(LeapFrogTestData* testData, int numSteps)
{
const DeviceContext& deviceContext = testDevice_.deviceContext();
const DeviceStream& deviceStream = testDevice_.deviceStream();
setActiveDevice(testDevice_.deviceInfo());
int numAtoms = testData->numAtoms_;
Float3* h_x = gmx::asGenericFloat3Pointer(testData->x_);
Float3* h_xp = gmx::asGenericFloat3Pointer(testData->xPrime_);
Float3* h_v = gmx::asGenericFloat3Pointer(testData->v_);
Float3* h_f = gmx::asGenericFloat3Pointer(testData->f_);
DeviceBuffer<Float3> d_x, d_xp, d_v, d_f;
allocateDeviceBuffer(&d_x, numAtoms, deviceContext);
allocateDeviceBuffer(&d_xp, numAtoms, deviceContext);
allocateDeviceBuffer(&d_v, numAtoms, deviceContext);
allocateDeviceBuffer(&d_f, numAtoms, deviceContext);
copyToDeviceBuffer(&d_x, h_x, 0, numAtoms, deviceStream, GpuApiCallBehavior::Sync, nullptr);
copyToDeviceBuffer(&d_xp, h_xp, 0, numAtoms, deviceStream, GpuApiCallBehavior::Sync, nullptr);
copyToDeviceBuffer(&d_v, h_v, 0, numAtoms, deviceStream, GpuApiCallBehavior::Sync, nullptr);
copyToDeviceBuffer(&d_f, h_f, 0, numAtoms, deviceStream, GpuApiCallBehavior::Sync, nullptr);
auto integrator =
std::make_unique<LeapFrogGpu>(deviceContext, deviceStream, testData->numTCoupleGroups_);
integrator->set(testData->numAtoms_, testData->inverseMasses_.data(), testData->mdAtoms_.cTC);
bool doTempCouple = testData->numTCoupleGroups_ > 0;
for (int step = 0; step < numSteps; step++)
{
// This follows the logic of the CPU-based implementation
bool doPressureCouple = testData->doPressureCouple_
&& do_per_step(step + testData->inputRecord_.nstpcouple - 1,
testData->inputRecord_.nstpcouple);
integrator->integrate(d_x,
d_xp,
d_v,
d_f,
testData->timestep_,
doTempCouple,
testData->kineticEnergyData_.tcstat,
doPressureCouple,
testData->dtPressureCouple_,
testData->velocityScalingMatrix_);
}
copyFromDeviceBuffer(h_xp, &d_x, 0, numAtoms, deviceStream, GpuApiCallBehavior::Sync, nullptr);
copyFromDeviceBuffer(h_v, &d_v, 0, numAtoms, deviceStream, GpuApiCallBehavior::Sync, nullptr);
freeDeviceBuffer(&d_x);
freeDeviceBuffer(&d_xp);
freeDeviceBuffer(&d_v);
freeDeviceBuffer(&d_f);
}
#else // GPU_LEAPFROG_SUPPORTED
void LeapFrogDeviceTestRunner::integrate(LeapFrogTestData* /* testData */, int /* numSteps */)
{
GMX_UNUSED_VALUE(testDevice_);
FAIL() << "Dummy Leap-Frog GPU function was called instead of the real one.";
}
#endif // GPU_LEAPFROG_SUPPORTED
} // namespace test
} // namespace gmx
| 2,034 |
596 | <gh_stars>100-1000
/*
* Yet Another UserAgent Analyzer
* Copyright (C) 2013-2021 <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
*
* 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 nl.basjes.parse.useragent.utils;
public class CheckLoggingDependencies {
public static class InvalidLoggingDependencyException extends RuntimeException {
public InvalidLoggingDependencyException(String message, Throwable cause) {
super(message, cause);
}
}
void verifyLog4j2Dependencies() {
try {
org.apache.logging.log4j.LogManager.getLogger("Verify Logging Dependencies (Log4J2)");
} catch (NoClassDefFoundError e) {
throw new InvalidLoggingDependencyException("Failed loading Log4J2 (Not present)", e);
}
}
void verifySlf4jDependencies() {
try {
// Check slf4j (used by PublicSuffixMatcherLoader from httpclient)
org.slf4j.LoggerFactory.getLogger("Verify Logging Dependencies (Slf4j)");
} catch (NoClassDefFoundError e) {
throw new InvalidLoggingDependencyException("Failed testing SLF4J (Not present)", e);
}
}
void verifyJCLDependencies() {
try {
// Check JCL (used by PathMatchingResourcePatternResolver from Springframework)
org.apache.commons.logging.LogFactory.getLog("Verify Logging Dependencies (JCL)");
} catch (NoClassDefFoundError e) {
throw new InvalidLoggingDependencyException("Failed testing JCL (Not present)", e);
}
}
/**
* Checks if the logging dependencies needed for this library are available.
* Throws an exception if something is wrong.
*/
public static void verifyLoggingDependencies() {
CheckLoggingDependencies ldt = new CheckLoggingDependencies();
ldt.verifyLog4j2Dependencies();
ldt.verifySlf4jDependencies();
ldt.verifyJCLDependencies();
}
}
| 886 |
335 | {
"word": "Oleaginously",
"definitions": [
"In an oleaginous manner; obsequiously."
],
"parts-of-speech": "Adverb"
} | 66 |
697 | <gh_stars>100-1000
// Copyright (C) 2012-2019 The VPaint Developers.
// See the COPYRIGHT file at the top-level directory of this distribution
// and at https://github.com/dalboris/vpaint/blob/master/COPYRIGHT
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef GLWIDGET_LIGHT_H
#define GLWIDGET_LIGHT_H
#include <cmath> // for sqrt
#include <QString>
class GLWidget_Light
{
public:
// default Light
GLWidget_Light(QString s = QString("unnammed light")) :
name_(s),
ambient_r(0.3f),
ambient_g(0.3f),
ambient_b(0.3f),
ambient_a(1.0f),
diffuse_r(0.5f),
diffuse_g(0.5f),
diffuse_b(0.5f),
diffuse_a(1.0f),
specular_r(0.5f),
specular_g(0.5f),
specular_b(0.5f),
specular_a(1.0f),
position_x(0.0f),
position_y(0.0f),
position_z(0.0f),
position_w(1.0f),
spotDirection_x(0.0f),
spotDirection_y(0.0f),
spotDirection_z(-1.0f),
spotExponent(0.0f),
spotCutoff(180.0f),
constantAttenuation(1.0f),
linearAttenuation(0.0f),
quadraticAttenuation(0.0f)
{
}
// diffuse Light
GLWidget_Light(float x, float y, float z, float r, float g, float b, QString s = QString("unnammed light")) :
name_(s),
ambient_r(0.1f),
ambient_g(0.1f),
ambient_b(0.1f),
ambient_a(1.0f),
diffuse_r(r),
diffuse_g(g),
diffuse_b(b),
diffuse_a(1.0f),
specular_r(r),
specular_g(g),
specular_b(b),
specular_a(1.0f),
position_x(x),
position_y(y),
position_z(z),
position_w(1.0f),
spotDirection_x(0.0f),
spotDirection_y(0.0f),
spotDirection_z(-1.0f),
spotExponent(0.0f),
spotCutoff(180.0f),
constantAttenuation(1.0f),
linearAttenuation(0.0f),
quadraticAttenuation(0.0f)
{
lookAt(0,0,0);
}
// ambiant Light
GLWidget_Light(float r, float g, float b, QString s = QString("unnammed light")) :
name_(s),
ambient_r(r),
ambient_g(g),
ambient_b(b),
ambient_a(1.0f),
diffuse_r(0.0f),
diffuse_g(0.0f),
diffuse_b(0.0f),
diffuse_a(1.0f),
specular_r(0.5f),
specular_g(0.5f),
specular_b(0.5f),
specular_a(1.0f),
position_x(0.0f),
position_y(0.0f),
position_z(0.0f),
position_w(1.0f),
spotDirection_x(0.0f),
spotDirection_y(0.0f),
spotDirection_z(-1.0f),
spotExponent(0.0f),
spotCutoff(180.0f),
constantAttenuation(1.0f),
linearAttenuation(0.0f),
quadraticAttenuation(0.0f)
{
lookAt(0,0,0);
}
void lookAt(float x, float y, float z)
{
spotDirection_x = x - position_x;
spotDirection_y = y - position_y;
spotDirection_z = z - position_z;
float length = sqrt(
spotDirection_x*spotDirection_x +
spotDirection_y*spotDirection_y +
spotDirection_z*spotDirection_z);
if(length > 0)
{
spotDirection_x /= length;
spotDirection_y /= length;
spotDirection_z /= length;
}
else
{
spotDirection_z = - 1;
}
}
QString name() const {return name_;}
QString name_;
float ambient_r,
ambient_g,
ambient_b,
ambient_a,
diffuse_r,
diffuse_g,
diffuse_b,
diffuse_a,
specular_r,
specular_g,
specular_b,
specular_a,
position_x,
position_y,
position_z,
position_w,
spotDirection_x,
spotDirection_y,
spotDirection_z,
spotExponent,
spotCutoff,
constantAttenuation,
linearAttenuation,
quadraticAttenuation;
};
#endif
| 2,431 |
451 | <gh_stars>100-1000
"""
Script to load and save data using numpy.
"""
# Copyright (c) 2016 University of Edinburgh.
import recipy
import sys
import numpy as np
def run_numpy(in_file, out_file):
"""
Load data from in_file and save new data into out_file, using
numpy.
:param in_file: input file with comma-separated values
:type in_file: str or unicode
:param out_file: output file with comma-separated values
:type out_file: str or unicode
"""
data = np.loadtxt(in_file, delimiter=',')
data = np.array([[1, 2, 3], [1, 4, 9]])
np.savetxt(out_file, data, delimiter=',')
if __name__ == "__main__":
run_numpy(sys.argv[1], sys.argv[2])
| 267 |
5,250 | /* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flowable.form.engine.impl.cmd;
import java.util.Map;
/**
* @author <NAME>
*/
public class GetFormInstanceByScopeModelCmd extends AbstractGetFormInstanceModelCmd {
private static final long serialVersionUID = 1L;
public GetFormInstanceByScopeModelCmd(String formDefinitionKey, String parentDeploymentId, String scopeId, String scopeType,
Map<String, Object> variables) {
initializeValuesForScope(formDefinitionKey, parentDeploymentId, formDefinitionKey, null, scopeId, scopeType, variables, false);
}
public GetFormInstanceByScopeModelCmd(String formDefinitionKey, String parentDeploymentId, String scopeId, String scopeType,
String tenantId, Map<String, Object> variables, boolean fallbackToDefaultTenant) {
initializeValuesForScope(formDefinitionKey, parentDeploymentId, null, tenantId,
scopeId, scopeType, variables, fallbackToDefaultTenant);
}
}
| 481 |
530 | package org.carlspring.strongbox.storage.metadata;
import org.carlspring.strongbox.storage.metadata.maven.versions.MetadataVersion;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import org.apache.maven.artifact.repository.metadata.Plugin;
import org.apache.maven.artifact.repository.metadata.SnapshotVersion;
import org.apache.maven.artifact.repository.metadata.Versioning;
/**
* @author mtodorov
*/
public class VersionCollectionRequest
{
private Path artifactBasePath;
private Versioning versioning = new Versioning();
private List<SnapshotVersion> snapshotVersions = new ArrayList<>();
private List<MetadataVersion> metadataVersions = new ArrayList<>();
private List<Plugin> plugins = new ArrayList<>();
public VersionCollectionRequest()
{
}
public Path getArtifactBasePath()
{
return artifactBasePath;
}
public void setArtifactBasePath(Path artifactBasePath)
{
this.artifactBasePath = artifactBasePath;
}
public Versioning getVersioning()
{
return versioning;
}
public void setVersioning(Versioning versioning)
{
this.versioning = versioning;
}
public List<SnapshotVersion> getSnapshotVersions()
{
return snapshotVersions;
}
public void setSnapshotVersions(List<SnapshotVersion> snapshotVersions)
{
this.snapshotVersions = snapshotVersions;
}
public List<Plugin> getPlugins()
{
return plugins;
}
public void setPlugins(List<Plugin> plugins)
{
this.plugins = plugins;
}
public boolean addPlugin(Plugin plugin)
{
return plugins.add(plugin);
}
public List<MetadataVersion> getMetadataVersions()
{
return metadataVersions;
}
public void setMetadataVersions(List<MetadataVersion> metadataVersions)
{
this.metadataVersions = metadataVersions;
}
}
| 692 |
1,861 | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
#include "Encode.h"
#include <spectrum/core/SpectrumEnforce.h>
#include <sstream>
namespace facebook {
namespace spectrum {
namespace requirements {
constexpr Encode::Quality Encode::QualityUnset;
constexpr Encode::Quality Encode::QualityMin;
constexpr Encode::Quality Encode::QualityDefault;
constexpr Encode::Quality Encode::QualityMax;
std::string Encode::modeStringFromValue(const Mode mode) {
switch (mode) {
case Mode::Lossless:
return "lossless";
case Mode::Lossy:
return "lossy";
case Mode::Any:
return "any";
default:
return core::makeUnknownWithValue<std::uint8_t>(mode);
}
}
Encode::Mode Encode::modeFromValue(const int value) {
SPECTRUM_ENFORCE_IF_NOT(
value >= static_cast<int>(Mode::Lossless) &&
value <= static_cast<int>(Mode::Any));
return static_cast<Mode>(value);
}
void Encode::validate() const {
SPECTRUM_ENFORCE_IF(quality > QualityMax);
}
bool Encode::operator==(const Encode& rhs) const {
return format == rhs.format && quality == rhs.quality && mode == rhs.mode;
}
bool Encode::operator!=(const Encode& rhs) const {
return !(*this == rhs);
}
bool Encode::hasQuality() const {
return quality != QualityUnset;
}
Encode::Quality Encode::sanitizedQuality(
const Quality defaultValue,
const Quality min,
const Quality max) const {
if (quality == QualityUnset) {
return defaultValue;
} else {
return std::max(std::min(quality, max), min);
}
}
std::string Encode::string() const {
std::stringstream ss;
ss << "{format:\"" << format.identifier() << "\",";
ss << "quality:\"" << quality << "\",";
ss << "mode:\"" << modeStringFromValue(mode) << "\"";
ss << "}";
return ss.str();
}
} // namespace requirements
} // namespace spectrum
} // namespace facebook
| 673 |
697 | <reponame>catberry/catberry-watcher
{
"name": "another",
"logic": "./index.js",
"template": "test1.html",
"errorTemplate": "error.html",
"additional" : "some"
}
| 70 |
9,724 | <filename>tests/other/test_asan_strncpy.c
#include <string.h>
int main() {
char from[] = "x";
char to[4];
strncpy(to, from, sizeof(to));
return 0;
}
| 69 |
852 | #ifndef DataFormats_TrackerCommon_PixelEndcapName_H
#define DataFormats_TrackerCommon_PixelEndcapName_H
/** \class PixelEndcapName
* Endcap Module name (as in PixelDatabase) for endcaps
*/
#include "DataFormats/SiPixelDetId/interface/PixelModuleName.h"
#include "DataFormats/SiPixelDetId/interface/PXFDetId.h"
#include <string>
#include <iostream>
class DetId;
class TrackerTopology;
class PixelEndcapName : public PixelModuleName {
public:
enum HalfCylinder { mO = 1, mI = 2, pO = 3, pI = 4 };
/// ctor from DetId
PixelEndcapName(const DetId&, bool phase = false);
PixelEndcapName(const DetId&, const TrackerTopology* tt, bool phase = false);
/// ctor for defined name
PixelEndcapName(HalfCylinder part = mO, int disk = 0, int blade = 0, int pannel = 0, int plaq = 0, bool phase = false)
: PixelModuleName(false),
thePart(part),
theDisk(disk),
theBlade(blade),
thePannel(pannel),
thePlaquette(plaq),
phase1(phase) {}
/// ctor from name string
PixelEndcapName(std::string name, bool phase = false);
~PixelEndcapName() override {}
/// from base class
std::string name() const override;
HalfCylinder halfCylinder() const { return thePart; }
/// disk id
int diskName() const { return theDisk; }
/// blade id
int bladeName() const { return theBlade; }
/// pannel id
int pannelName() const { return thePannel; }
/// plaquetteId (in pannel)
int plaquetteName() const { return thePlaquette; }
/// ring Id
int ringName() const { return thePlaquette; }
/// module Type
PixelModuleName::ModuleType moduleType() const override;
/// return DetId
PXFDetId getDetId();
DetId getDetId(const TrackerTopology* tt);
/// check equality of modules from datamemebers
bool operator==(const PixelModuleName&) const override;
private:
HalfCylinder thePart;
int theDisk, theBlade, thePannel, thePlaquette;
bool phase1;
};
std::ostream& operator<<(std::ostream& out, const PixelEndcapName::HalfCylinder& t);
#endif
| 699 |
456 | <reponame>pafri/DJV
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2004-2020 <NAME>
// All rights reserved.
#include <djvUI/DialogSystem.h>
#include <djvUI/IconSystem.h>
#include <djvUI/IDialog.h>
#include <djvUI/Label.h>
#include <djvUI/PushButton.h>
#include <djvUI/RowLayout.h>
#include <djvUI/TextBlock.h>
#include <djvUI/Window.h>
#include <djvSystem/Context.h>
using namespace djv::Core;
namespace djv
{
namespace UI
{
namespace
{
class MessageDialog : public IDialog
{
DJV_NON_COPYABLE(MessageDialog);
protected:
void _init(const std::shared_ptr<System::Context>& context)
{
IDialog::_init(context);
setClassName("djv::UI::MessageDialog");
setFillLayout(false);
_textBlock = Text::Block::create(context);
_textBlock->setTextHAlign(TextHAlign::Center);
_textBlock->setMargin(MetricsRole::MarginLarge);
_closeButton = PushButton::create(context);
auto layout = VerticalLayout::create(context);
layout->setMargin(MetricsRole::Margin);
layout->addChild(_textBlock);
layout->addChild(_closeButton);
addChild(layout);
setStretch(layout);
auto weak = std::weak_ptr<MessageDialog>(std::dynamic_pointer_cast<MessageDialog>(shared_from_this()));
_closeButton->setClickedCallback(
[weak]
{
if (auto dialog = weak.lock())
{
dialog->_doCloseCallback();
}
});
}
MessageDialog()
{}
public:
static std::shared_ptr<MessageDialog> create(const std::shared_ptr<System::Context>& context)
{
auto out = std::shared_ptr<MessageDialog>(new MessageDialog);
out->_init(context);
return out;
}
void setText(const std::string& text)
{
_textBlock->setText(text);
}
void setCloseText(const std::string& text)
{
_closeButton->setText(text);
}
private:
std::shared_ptr<Text::Block> _textBlock;
std::shared_ptr<PushButton> _closeButton;
};
class ConfirmationDialog : public IDialog
{
DJV_NON_COPYABLE(ConfirmationDialog);
protected:
void _init(const std::shared_ptr<System::Context>& context)
{
IDialog::_init(context);
setClassName("djv::UI::ConfirmationDialog");
setFillLayout(false);
_textBlock = Text::Block::create(context);
_textBlock->setTextHAlign(TextHAlign::Center);
_textBlock->setMargin(MetricsRole::MarginLarge);
_acceptButton = PushButton::create(context);
_cancelButton = PushButton::create(context);
auto layout = VerticalLayout::create(context);
layout->setMargin(MetricsRole::Margin);
layout->addChild(_textBlock);
layout->setStretch(_textBlock);
auto hLayout = HorizontalLayout::create(context);
hLayout->addChild(_acceptButton);
hLayout->setStretch(_acceptButton);
hLayout->addChild(_cancelButton);
hLayout->setStretch(_cancelButton);
layout->addChild(hLayout);
addChild(layout);
setStretch(layout);
auto weak = std::weak_ptr<ConfirmationDialog>(std::dynamic_pointer_cast<ConfirmationDialog>(shared_from_this()));
_acceptButton->setClickedCallback(
[weak]
{
if (auto dialog = weak.lock())
{
if (dialog->_acceptCallback)
{
dialog->_acceptCallback();
}
dialog->_doCloseCallback();
}
});
_cancelButton->setClickedCallback(
[weak]
{
if (auto dialog = weak.lock())
{
if (dialog->_cancelCallback)
{
dialog->_cancelCallback();
}
dialog->_doCloseCallback();
}
});
}
ConfirmationDialog()
{}
public:
static std::shared_ptr<ConfirmationDialog> create(const std::shared_ptr<System::Context>& context)
{
auto out = std::shared_ptr<ConfirmationDialog>(new ConfirmationDialog);
out->_init(context);
return out;
}
void setText(const std::string& text)
{
_textBlock->setText(text);
}
void setAcceptText(const std::string& text)
{
_acceptButton->setText(text);
}
void setCancelText(const std::string& text)
{
_cancelButton->setText(text);
}
void setAcceptCallback(const std::function<void(void)>& value)
{
_acceptCallback = value;
}
void setCancelCallback(const std::function<void(void)>& value)
{
_cancelCallback = value;
}
private:
std::shared_ptr<Text::Block> _textBlock;
std::shared_ptr<PushButton> _acceptButton;
std::shared_ptr<PushButton> _cancelButton;
std::function<void(void)> _acceptCallback;
std::function<void(void)> _cancelCallback;
};
} // namespace
struct DialogSystem::Private
{
std::shared_ptr<Window> messageWindow;
std::shared_ptr<Window> confirmationWindow;
};
void DialogSystem::_init(const std::shared_ptr<System::Context>& context)
{
ISystem::_init("djv::UI::DialogSystem", context);
addDependency(IconSystem::create(context));
_logInitTime();
}
DialogSystem::DialogSystem() :
_p(new Private)
{}
DialogSystem::~DialogSystem()
{
DJV_PRIVATE_PTR();
if (p.messageWindow)
{
p.messageWindow->close();
}
if (p.confirmationWindow)
{
p.confirmationWindow->close();
}
}
std::shared_ptr<DialogSystem> DialogSystem::create(const std::shared_ptr<System::Context>& context)
{
auto out = context->getSystemT<DialogSystem>();
if (!out)
{
out = std::shared_ptr<DialogSystem>(new DialogSystem);
out->_init(context);
}
return out;
}
void DialogSystem::message(
const std::string& title,
const std::string& text,
const std::string& closeText)
{
DJV_PRIVATE_PTR();
if (auto context = getContext().lock())
{
if (p.messageWindow)
{
p.messageWindow->close();
p.messageWindow.reset();
}
auto messageDialog = MessageDialog::create(context);
messageDialog->setTitle(title);
messageDialog->setText(text);
messageDialog->setCloseText(closeText);
auto weak = std::weak_ptr<DialogSystem>(std::dynamic_pointer_cast<DialogSystem>(shared_from_this()));
messageDialog->setCloseCallback(
[weak]
{
if (auto system = weak.lock())
{
if (system->_p->messageWindow)
{
system->_p->messageWindow->close();
system->_p->messageWindow.reset();
}
}
});
p.messageWindow = Window::create(context);
p.messageWindow->setBackgroundColorRole(ColorRole::None);
p.messageWindow->addChild(messageDialog);
p.messageWindow->show();
}
}
void DialogSystem::confirmation(
const std::string& title,
const std::string& text,
const std::string& acceptText,
const std::string& cancelText,
const std::function<void(bool)>& callback)
{
DJV_PRIVATE_PTR();
if (auto context = getContext().lock())
{
if (p.confirmationWindow)
{
p.confirmationWindow->close();
p.confirmationWindow.reset();
}
auto confirmationDialog = ConfirmationDialog::create(context);
confirmationDialog->setTitle(title);
confirmationDialog->setText(text);
confirmationDialog->setAcceptText(acceptText);
confirmationDialog->setCancelText(cancelText);
confirmationDialog->setAcceptCallback(
[callback]
{
callback(true);
});
confirmationDialog->setCancelCallback(
[callback]
{
callback(false);
});
auto weak = std::weak_ptr<DialogSystem>(std::dynamic_pointer_cast<DialogSystem>(shared_from_this()));
confirmationDialog->setCloseCallback(
[weak]
{
if (auto system = weak.lock())
{
if (system->_p->confirmationWindow)
{
system->_p->confirmationWindow->close();
system->_p->confirmationWindow.reset();
}
}
});
p.confirmationWindow = Window::create(context);
p.confirmationWindow->setBackgroundColorRole(ColorRole::None);
p.confirmationWindow->addChild(confirmationDialog);
p.confirmationWindow->show();
}
}
} // namespace UI
} // namespace djv
| 6,593 |
6,098 | package water.rapids.ast.prims.mungers;
import org.junit.After;
import org.junit.BeforeClass;
import org.junit.Test;
import water.TestUtil;
import water.fvec.Frame;
import water.fvec.TestFrameBuilder;
import water.fvec.Vec;
import water.rapids.Rapids;
import water.rapids.Val;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class AstEqTest extends TestUtil {
@BeforeClass
static public void setup() { stall_till_cloudsize(1); }
private Frame fr = null;
@Test
public void IsNaTest() {
fr = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "ColB")
.withVecTypes(Vec.T_NUM, Vec.T_STR)
.withDataForCol(0, ard(1, 2))
.withDataForCol(1, ar("1", "3"))
.build();
String tree = "(== (cols testFrame [0.0] ) 1 )";
Val val = Rapids.exec(tree);
Frame results = val.getFrame();
assertTrue(results.numRows() == 2);
assertEquals(1, results.vec(0).at(0), 1e-5);
assertEquals(0, results.vec(0).at(1), 1e-5);
results.delete();
}
@After
public void afterEach() {
fr.delete();
}
}
| 494 |
2,686 | /*
* Copyright 2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.awaitility.classes;
public class Asynch {
private final FakeRepository repository;
public Asynch(FakeRepository repository) {
this.repository = repository;
}
public void perform() {
Thread thread = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(600);
repository.setValue(1);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
});
thread.start();
}
}
| 330 |
2,659 | /*
* Copyright 2021 4Paradigm
*
* 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 <brpc/server.h>
#include <gflags/gflags.h>
#include <gtest/gtest.h>
#include <sched.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "base/file_util.h"
#include "base/glog_wapper.h"
#include "client/tablet_client.h"
#include "common/thread_pool.h"
#include "common/timer.h"
#include "proto/tablet.pb.h"
#include "replica/log_replicator.h"
#include "replica/replicate_node.h"
#include "storage/segment.h"
#include "storage/table.h"
#include "storage/ticket.h"
#include "tablet/tablet_impl.h"
#include "test/util.h"
using ::baidu::common::ThreadPool;
using ::google::protobuf::Closure;
using ::google::protobuf::RpcController;
using ::openmldb::storage::DataBlock;
using ::openmldb::storage::Table;
using ::openmldb::storage::Ticket;
using ::openmldb::tablet::TabletImpl;
DECLARE_string(db_root_path);
DECLARE_int32(binlog_single_file_max_size);
DECLARE_int32(binlog_delete_interval);
DECLARE_int32(make_snapshot_threshold_offset);
DECLARE_string(snapshot_compression);
namespace openmldb {
namespace replica {
class BinlogTest : public ::testing::Test {
public:
BinlogTest() {}
~BinlogTest() {}
};
TEST_F(BinlogTest, DeleteBinlog) {
FLAGS_binlog_single_file_max_size = 1;
FLAGS_binlog_delete_interval = 500;
::openmldb::tablet::TabletImpl* tablet = new ::openmldb::tablet::TabletImpl();
tablet->Init("");
int offset = FLAGS_make_snapshot_threshold_offset;
FLAGS_make_snapshot_threshold_offset = 0;
brpc::Server server;
if (server.AddService(tablet, brpc::SERVER_OWNS_SERVICE) != 0) {
PDLOG(WARNING, "fail to register tablet rpc service");
exit(1);
}
brpc::ServerOptions options;
std::string leader_point = "127.0.0.1:18529";
if (server.Start(leader_point.c_str(), &options) != 0) {
PDLOG(WARNING, "fail to start server %s", leader_point.c_str());
exit(1);
}
uint32_t tid = 2;
uint32_t pid = 123;
::openmldb::client::TabletClient client(leader_point, "");
client.Init();
std::vector<std::string> endpoints;
bool ret =
client.CreateTable("table1", tid, pid, 100000, 0, true, endpoints, ::openmldb::type::TTLType::kAbsoluteTime, 16,
0, ::openmldb::type::CompressType::kNoCompress);
ASSERT_TRUE(ret);
uint64_t cur_time = ::baidu::common::timer::get_micros() / 1000;
int count = 1000;
while (count) {
std::string key = "testkey_" + std::to_string(count);
ret = client.Put(tid, pid, key, cur_time, ::openmldb::test::EncodeKV(key, std::string(10 * 1024, 'a')));
count--;
}
ret = client.MakeSnapshot(tid, pid, 0);
std::string binlog_path = FLAGS_db_root_path + "/2_123/binlog";
std::vector<std::string> vec;
ASSERT_TRUE(ret);
for (int i = 0; i < 50; i++) {
vec.clear();
::openmldb::base::GetFileName(binlog_path, vec);
if (vec.size() == 1) {
break;
}
sleep(2);
}
vec.clear();
::openmldb::base::GetFileName(binlog_path, vec);
ASSERT_EQ(1, (int64_t)vec.size());
std::string file_name = binlog_path + "/00000004.log";
ASSERT_STREQ(file_name.c_str(), vec[0].c_str());
FLAGS_make_snapshot_threshold_offset = offset;
}
} // namespace replica
} // namespace openmldb
inline std::string GenRand() { return std::to_string(rand() % 10000000 + 1); } // NOLINT
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
srand(time(NULL));
::openmldb::base::SetLogLevel(DEBUG);
::google::ParseCommandLineFlags(&argc, &argv, true);
int ret = 0;
std::vector<std::string> vec{"off", "zlib", "snappy"};
for (size_t i = 0; i < vec.size(); i++) {
std::cout << "compress type: " << vec[i] << std::endl;
FLAGS_db_root_path = "/tmp/" + GenRand();
FLAGS_snapshot_compression = vec[i];
ret += RUN_ALL_TESTS();
}
return ret;
// return RUN_ALL_TESTS();
}
| 1,891 |
405 | {
"version": 2,
"projects": {
"integration": "apps/integration",
"integration-e2e": "apps/integration-e2e",
"until-destroy": "libs/until-destroy",
"until-destroy-migration": "libs/until-destroy-migration"
}
}
| 96 |
1,383 | <filename>src/chrono_models/vehicle/uaz/UAZBUS_SAEToeBarLeafspringAxle.cpp
// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: <NAME>, <NAME>
// =============================================================================
//
// UAZBUS leafspring axle with SAE three-link model and Toebar Steering.
//
// These concrete suspension subsystems are defined with respect to right-handed
// frames with X pointing towards the front, Y to the left, and Z up (as imposed
// by the base class ChDoubleWishbone) and origins at the midpoint between the
// lower control arms' connection points to the chassis.
//
// All point locations are provided for the left half of the suspension.
//
// =============================================================================
#include "chrono_models/vehicle/uaz/UAZBUS_SAEToeBarLeafspringAxle.h"
namespace chrono {
namespace vehicle {
namespace uaz {
// -----------------------------------------------------------------------------
// Static variables
// -----------------------------------------------------------------------------
const double UAZBUS_SAEToeBarLeafspringAxle::m_leafHeight = 0.008;
const double UAZBUS_SAEToeBarLeafspringAxle::m_leafWidth = 0.08;
const double UAZBUS_SAEToeBarLeafspringAxle::m_axleTubeMass = 124.0;
const double UAZBUS_SAEToeBarLeafspringAxle::m_spindleMass = 14.705;
const double UAZBUS_SAEToeBarLeafspringAxle::m_knuckleMass = 10.0;
const double UAZBUS_SAEToeBarLeafspringAxle::m_tierodMass = 5.0;
const double UAZBUS_SAEToeBarLeafspringAxle::m_draglinkMass = 5.0;
const double UAZBUS_SAEToeBarLeafspringAxle::m_axleTubeRadius = 0.0476;
const double UAZBUS_SAEToeBarLeafspringAxle::m_spindleRadius = 0.10;
const double UAZBUS_SAEToeBarLeafspringAxle::m_spindleWidth = 0.06;
const double UAZBUS_SAEToeBarLeafspringAxle::m_knuckleRadius = 0.05;
const double UAZBUS_SAEToeBarLeafspringAxle::m_tierodRadius = 0.02;
const double UAZBUS_SAEToeBarLeafspringAxle::m_draglinkRadius = 0.02;
const ChVector<> UAZBUS_SAEToeBarLeafspringAxle::m_axleTubeInertia(22.21, 0.0775, 22.21);
const ChVector<> UAZBUS_SAEToeBarLeafspringAxle::m_spindleInertia(0.04117, 0.07352, 0.04117);
const ChVector<> UAZBUS_SAEToeBarLeafspringAxle::m_knuckleInertia(0.1, 0.1, 0.1);
const ChVector<> UAZBUS_SAEToeBarLeafspringAxle::m_tierodInertia(1.0, 0.1, 1.0);
const ChVector<> UAZBUS_SAEToeBarLeafspringAxle::m_draglinkInertia(0.1, 1.0, 0.1);
const double UAZBUS_SAEToeBarLeafspringAxle::m_auxSpringDesignLength = 0.2;
const double UAZBUS_SAEToeBarLeafspringAxle::m_auxSpringCoefficient = 0;
const double UAZBUS_SAEToeBarLeafspringAxle::m_auxSpringRestLength = m_auxSpringDesignLength + 0.0;
const double UAZBUS_SAEToeBarLeafspringAxle::m_auxSpringMinLength = m_auxSpringDesignLength - 0.08;
const double UAZBUS_SAEToeBarLeafspringAxle::m_auxSpringMaxLength = m_auxSpringDesignLength + 0.08;
const double UAZBUS_SAEToeBarLeafspringAxle::m_damperCoefficient = 15079.644737231;
const double UAZBUS_SAEToeBarLeafspringAxle::m_damperDegressivityCompression = 3.0;
const double UAZBUS_SAEToeBarLeafspringAxle::m_damperDegressivityExpansion = 1.0;
const double UAZBUS_SAEToeBarLeafspringAxle::m_axleShaftInertia = 0.4;
const double UAZBUS_SAEToeBarLeafspringAxle::m_vert_spring_trans_A = 94748.2022504578 / 2.0;
const double UAZBUS_SAEToeBarLeafspringAxle::m_vert_spring_trans_B = 94748.2022504578 / 2.0;
const double UAZBUS_SAEToeBarLeafspringAxle::m_lat_spring_trans_A =
10.0 * UAZBUS_SAEToeBarLeafspringAxle::m_vert_spring_trans_A;
const double UAZBUS_SAEToeBarLeafspringAxle::m_lat_spring_trans_B =
10.0 * UAZBUS_SAEToeBarLeafspringAxle::m_vert_spring_trans_B;
const double UAZBUS_SAEToeBarLeafspringAxle::m_vert_preload = 2000.0;
const double UAZBUS_SAEToeBarLeafspringAxle::m_frontleafMass = 3.5168;
const double UAZBUS_SAEToeBarLeafspringAxle::m_rearleafMass = 3.5168;
const double UAZBUS_SAEToeBarLeafspringAxle::m_clampMass = 0.70336;
const double UAZBUS_SAEToeBarLeafspringAxle::m_shackleMass = 0.70336;
const ChVector<> UAZBUS_SAEToeBarLeafspringAxle::m_frontleafInertia = {0.00191239, 0.0733034, 0.0751423};
const ChVector<> UAZBUS_SAEToeBarLeafspringAxle::m_rearleafInertia = {0.00191239, 0.0733034, 0.0751423};
const ChVector<> UAZBUS_SAEToeBarLeafspringAxle::m_clampInertia = {0.000382478, 0.000593486, 0.000961259};
const ChVector<> UAZBUS_SAEToeBarLeafspringAxle::m_shackleInertia = {0.000382478, 0.000593486, 0.000961259};
// ---------------------------------------------------------------------------------------
// UAZBUS spring functor class - implements a linear spring + bump stop + rebound stop
// ---------------------------------------------------------------------------------------
class UAZBUS_AuxSpringForceFront : public ChLinkTSDA::ForceFunctor {
public:
UAZBUS_AuxSpringForceFront(double spring_constant, double min_length, double max_length);
virtual double evaluate(double time,
double rest_length,
double length,
double vel,
const ChLinkTSDA& link) override;
private:
double m_spring_constant;
double m_min_length;
double m_max_length;
ChFunction_Recorder m_bump;
};
UAZBUS_AuxSpringForceFront::UAZBUS_AuxSpringForceFront(double spring_constant, double min_length, double max_length)
: m_spring_constant(spring_constant), m_min_length(min_length), m_max_length(max_length) {
// From ADAMS/Car
m_bump.AddPoint(0.0, 0.0);
m_bump.AddPoint(2.0e-3, 200.0);
m_bump.AddPoint(4.0e-3, 400.0);
m_bump.AddPoint(6.0e-3, 600.0);
m_bump.AddPoint(8.0e-3, 800.0);
m_bump.AddPoint(10.0e-3, 1000.0);
m_bump.AddPoint(20.0e-3, 2500.0);
m_bump.AddPoint(30.0e-3, 4500.0);
m_bump.AddPoint(40.0e-3, 7500.0);
m_bump.AddPoint(50.0e-3, 12500.0);
}
double UAZBUS_AuxSpringForceFront::evaluate(double time,
double rest_length,
double length,
double vel,
const ChLinkTSDA& link) {
double force = 0;
double defl_spring = rest_length - length;
double defl_bump = 0.0;
double defl_rebound = 0.0;
if (length < m_min_length) {
defl_bump = m_min_length - length;
}
if (length > m_max_length) {
defl_rebound = length - m_max_length;
}
force = defl_spring * m_spring_constant + m_bump.Get_y(defl_bump) - m_bump.Get_y(defl_rebound);
return force;
}
// -----------------------------------------------------------------------------
// UAZBUS shock functor class - implements a nonlinear damper
// -----------------------------------------------------------------------------
class UAZBUS_SAEShockForceFront : public ChLinkTSDA::ForceFunctor {
public:
UAZBUS_SAEShockForceFront(double compression_slope,
double compression_degressivity,
double expansion_slope,
double expansion_degressivity);
virtual double evaluate(double time,
double rest_length,
double length,
double vel,
const ChLinkTSDA& link) override;
private:
double m_slope_compr;
double m_slope_expand;
double m_degres_compr;
double m_degres_expand;
};
UAZBUS_SAEShockForceFront::UAZBUS_SAEShockForceFront(double compression_slope,
double compression_degressivity,
double expansion_slope,
double expansion_degressivity)
: m_slope_compr(compression_slope),
m_degres_compr(compression_degressivity),
m_slope_expand(expansion_slope),
m_degres_expand(expansion_degressivity) {}
double UAZBUS_SAEShockForceFront::evaluate(double time,
double rest_length,
double length,
double vel,
const ChLinkTSDA& link) {
// Simple model of a degressive damping characteristic
double force = 0;
// Calculate Damping Force
if (vel >= 0) {
force = -m_slope_expand / (1.0 + m_degres_expand * std::abs(vel)) * vel;
} else {
force = -m_slope_compr / (1.0 + m_degres_compr * std::abs(vel)) * vel;
}
return force;
}
UAZBUS_SAEToeBarLeafspringAxle::UAZBUS_SAEToeBarLeafspringAxle(const std::string& name)
: ChSAEToeBarLeafspringAxle(name) {
ChVector<> ra = getLocation(CLAMP_A) - getLocation(FRONT_HANGER);
ChVector<> rb = getLocation(CLAMP_B) - getLocation(SHACKLE);
ChVector<> preload(0, 0, m_vert_preload / 2.0);
ChVector<> Ma = preload.Cross(ra);
ChVector<> Mb = preload.Cross(rb);
double KrotLatA = m_lat_spring_trans_A * pow(ra.Length(), 2.0);
double KrotLatB = m_lat_spring_trans_B * pow(rb.Length(), 2.0);
double KrotVertA = m_vert_spring_trans_A * pow(ra.Length(), 2.0);
double KrotVertB = m_vert_spring_trans_B * pow(rb.Length(), 2.0);
double rest_angle_A = Ma.y() / KrotVertA;
double rest_angle_B = Mb.y() / KrotVertB;
double damping_factor = 0.05;
m_latRotSpringCBA = chrono_types::make_shared<LinearSpringDamperTorque>(KrotLatA, KrotLatA * damping_factor, 0);
m_latRotSpringCBB = chrono_types::make_shared<LinearSpringDamperTorque>(KrotLatB, KrotLatA * damping_factor, 0);
m_vertRotSpringCBA =
chrono_types::make_shared<LinearSpringDamperTorque>(KrotVertA, KrotVertA * damping_factor, rest_angle_A);
m_vertRotSpringCBB =
chrono_types::make_shared<LinearSpringDamperTorque>(KrotVertB, KrotVertB * damping_factor, rest_angle_B);
m_auxSpringForceCB = chrono_types::make_shared<UAZBUS_AuxSpringForceFront>(
m_auxSpringCoefficient, m_auxSpringMinLength, m_auxSpringMaxLength);
m_shockForceCB = chrono_types::make_shared<UAZBUS_SAEShockForceFront>(
m_damperCoefficient, m_damperDegressivityCompression, m_damperCoefficient, m_damperDegressivityExpansion);
}
// -----------------------------------------------------------------------------
// Destructors
// -----------------------------------------------------------------------------
UAZBUS_SAEToeBarLeafspringAxle::~UAZBUS_SAEToeBarLeafspringAxle() {}
const ChVector<> UAZBUS_SAEToeBarLeafspringAxle::getLocation(PointId which) {
switch (which) {
case SPRING_A:
return ChVector<>(0.0, 0.3824, m_axleTubeRadius);
case SPRING_C:
return ChVector<>(0.0, 0.3824, m_axleTubeRadius + m_auxSpringDesignLength);
case SHOCK_A:
return ChVector<>(-0.125, 0.441, -0.0507);
case SHOCK_C:
return ChVector<>(-0.3648, 0.4193, 0.3298);
case SPINDLE:
return ChVector<>(0.0, 0.7325, 0.0);
case KNUCKLE_CM:
return ChVector<>(0.0, 0.7325 - 0.07, 0.0);
case KNUCKLE_L:
return ChVector<>(0.0, 0.7325 - 0.07 + 0.0098058067569092, -0.1);
case KNUCKLE_U:
return ChVector<>(0.0, 0.7325 - 0.07 - 0.0098058067569092, 0.1);
case KNUCKLE_DRL:
return ChVector<>(0.0, 0.7325 - 0.2, 0.2);
case TIEROD_K:
return ChVector<>(-0.190568826619798, 0.7325 - 0.07 - 0.060692028477827, 0.1);
case DRAGLINK_C:
return ChVector<>(0.6, 0.7325 - 0.2, 0.2);
case CLAMP_A:
return ChVector<>(0.044697881113434, 0.3824, 0.102479751287605);
break;
case CLAMP_B:
return ChVector<>(-0.055165072362023, 0.3824, 0.097246155663310);
break;
case FRONT_HANGER:
return ChVector<>(0.494081171752993, 0.3824, 0.1260);
break;
case REAR_HANGER:
return ChVector<>(-0.445529598035440, 0.3824, 0.189525823498473);
break;
case SHACKLE:
return ChVector<>(-0.504548363001581, 0.3824, 0.073694975353985);
break;
default:
return ChVector<>(0, 0, 0);
}
}
} // end namespace uaz
} // end namespace vehicle
} // end namespace chrono
| 5,584 |
3,765 | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang;
import java.util.List;
import net.sourceforge.pmd.Rule;
import net.sourceforge.pmd.annotation.InternalApi;
/**
* Represents a version of a {@link Language}. Language instances provide
* a list of supported versions ({@link Language#getVersions()}). Individual
* versions can be retrieved from their version number ({@link Language#getVersion(String)}).
*
* <p>Versions are used to limit some rules to operate on only a version range.
* For instance, a rule that suggests eliding local variable types in Java
* (replacing them with {@code var}) makes no sense if the codebase is not
* using Java 10 or later. This is determined by {@link Rule#getMinimumLanguageVersion()}
* and {@link Rule#getMaximumLanguageVersion()}. These should be set in the
* ruleset XML (they're attributes of the {@code <rule>} element), and not
* overridden.
*
* <p>Example usage:
* <pre>
* Language javaLanguage = LanguageRegistry.{@link LanguageRegistry#getLanguage(String) getLanguage}("Java");
* LanguageVersion java11 = javaLanguage.{@link Language#getVersion(String) getVersion}("11");
* LanguageVersionHandler handler = java11.getLanguageVersionHandler();
* Parser parser = handler.getParser(handler.getDefaultParserOptions());
* // use parser
* </pre>
*/
public class LanguageVersion implements Comparable<LanguageVersion> {
private final Language language;
private final String version;
private final LanguageVersionHandler languageVersionHandler;
/**
* @deprecated Use {@link Language#getVersion(String)}. This is only
* supposed to be used when initializing a {@link Language} instance.
*/
@Deprecated
@InternalApi
public LanguageVersion(Language language, String version, LanguageVersionHandler languageVersionHandler) {
this.language = language;
this.version = version;
this.languageVersionHandler = languageVersionHandler;
}
/**
* Returns the language that owns this version.
*/
public Language getLanguage() {
return language;
}
/**
* Returns the version string. This is usually a version number, e.g.
* {@code "1.7"} or {@code "11"}. This is used by {@link Language#getVersion(String)}.
*/
public String getVersion() {
return version;
}
/**
* Returns the {@link LanguageVersionHandler}, which provides access
* to version-specific services, like the parser.
*/
public LanguageVersionHandler getLanguageVersionHandler() {
return languageVersionHandler;
}
/**
* Returns the name of this language version. This is the version string
* prefixed with the {@linkplain Language#getName() language name}.
*
* @return The name of this LanguageVersion.
*/
public String getName() {
return version.length() > 0 ? language.getName() + ' ' + version : language.getName();
}
/**
* Get the short name of this LanguageVersion. This is Language short name
* appended with the LanguageVersion version if not an empty String.
*
* @return The short name of this LanguageVersion.
*/
public String getShortName() {
return version.length() > 0 ? language.getShortName() + ' ' + version : language.getShortName();
}
/**
* Get the terse name of this LanguageVersion. This is Language terse name
* appended with the LanguageVersion version if not an empty String.
*
* @return The terse name of this LanguageVersion.
*/
public String getTerseName() {
return version.length() > 0 ? language.getTerseName() + ' ' + version : language.getTerseName();
}
@Override
public int compareTo(LanguageVersion o) {
List<LanguageVersion> versions = language.getVersions();
int thisPosition = versions.indexOf(this);
int otherPosition = versions.indexOf(o);
return Integer.compare(thisPosition, otherPosition);
}
/**
* Compare this version to another version of the same language identified
* by the given version string.
*
* @param versionString The version with which to compare
*
* @throws IllegalArgumentException If the argument is not a valid version
* string for the parent language
*/
public int compareToVersion(String versionString) {
LanguageVersion otherVersion = language.getVersion(versionString);
if (otherVersion == null) {
throw new IllegalArgumentException(
"No such version '" + versionString + "' for language " + language.getName());
}
return this.compareTo(otherVersion);
}
@Override
public String toString() {
return language.toString() + "+version:" + version;
}
}
| 1,587 |
672 | <reponame>vancexu/velox<filename>velox/core/tests/TestQueryConfig.cpp<gh_stars>100-1000
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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 <gtest/gtest.h>
#include "velox/core/Context.h"
#include "velox/core/QueryConfig.h"
#include "velox/core/QueryCtx.h"
using ::facebook::velox::core::MemConfig;
using ::facebook::velox::core::QueryConfig;
using ::facebook::velox::core::QueryCtx;
TEST(TestQueryConfig, emptyConfig) {
std::unordered_map<std::string, std::string> configData;
auto queryCtxConfig = std::make_shared<MemConfig>(configData);
auto queryCtx = QueryCtx::createForTest(queryCtxConfig);
const QueryConfig& config = queryCtx->config();
ASSERT_FALSE(config.codegenEnabled());
ASSERT_EQ(config.codegenConfigurationFilePath(), "");
ASSERT_FALSE(config.isCastIntByTruncate());
}
TEST(TestQueryConfig, setConfig) {
std::string path = "/tmp/CodeGenConfig";
std::unordered_map<std::string, std::string> configData(
{{QueryConfig::kCodegenEnabled, "true"},
{QueryConfig::kCodegenConfigurationFilePath, path}});
auto queryCtxConfig = std::make_shared<MemConfig>(configData);
auto queryCtx = QueryCtx::createForTest(queryCtxConfig);
const QueryConfig& config = queryCtx->config();
ASSERT_TRUE(config.codegenEnabled());
ASSERT_EQ(config.codegenConfigurationFilePath(), path);
ASSERT_FALSE(config.isCastIntByTruncate());
}
| 622 |
350 | /*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.accessibility.utils.compat.view;
public class InputDeviceCompatUtils {
/**
* The input source is a pointing device associated with a display. Examples: {@link
* #SOURCE_TOUCHSCREEN}, {@link #SOURCE_MOUSE}. A {@link android.view.MotionEvent} should be
* interpreted as absolute coordinates in display units according to the {@link android.view.View}
* hierarchy. Pointer down/up indicated when the finger touches the display or when the selection
* button is pressed/released.
*/
private static final int SOURCE_CLASS_POINTER = 0x00000002;
/**
* The input source is a mouse pointing device. This code is also used for other mouse-like
* pointing devices such as trackpads and trackpoints.
*
* @see #SOURCE_CLASS_POINTER
*/
public static final int SOURCE_MOUSE = 0x00002000 | SOURCE_CLASS_POINTER;
/**
* The input source is a touch screen pointing device.
*
* @see #SOURCE_CLASS_POINTER
*/
public static final int SOURCE_TOUCHSCREEN = 0x00001000 | SOURCE_CLASS_POINTER;
/** The input source is unknown. */
public static final int SOURCE_UNKNOWN = 0x00000000;
private InputDeviceCompatUtils() {
// This class is non-instantiable.
}
}
| 535 |
1,350 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.elastic.models;
import com.azure.core.util.ExpandableStringEnum;
import com.fasterxml.jackson.annotation.JsonCreator;
import java.util.Collection;
/** Defines values for SendingLogs. */
public final class SendingLogs extends ExpandableStringEnum<SendingLogs> {
/** Static value True for SendingLogs. */
public static final SendingLogs TRUE = fromString("True");
/** Static value False for SendingLogs. */
public static final SendingLogs FALSE = fromString("False");
/**
* Creates or finds a SendingLogs from its string representation.
*
* @param name a name to look for.
* @return the corresponding SendingLogs.
*/
@JsonCreator
public static SendingLogs fromString(String name) {
return fromString(name, SendingLogs.class);
}
/** @return known SendingLogs values. */
public static Collection<SendingLogs> values() {
return values(SendingLogs.class);
}
}
| 361 |
442 | <gh_stars>100-1000
#This file is part of ElectricEye.
#SPDX-License-Identifier: Apache-2.0
#Licensed to the Apache Software Foundation (ASF) under one
#or more contributor license agreements. See the NOTICE file
#distributed with this work for additional information
#regarding copyright ownership. The ASF licenses this file
#to you under the Apache License, Version 2.0 (the
#"License"); you may not use this file except in compliance
#with the License. You may obtain a copy of the License at
#http://www.apache.org/licenses/LICENSE-2.0
#Unless required by applicable law or agreed to in writing,
#software distributed under the License is distributed on an
#"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
#KIND, either express or implied. See the License for the
#specific language governing permissions and limitations
#under the License.
import boto3
import datetime
import os
from check_register import CheckRegister
registry = CheckRegister()
# import boto3 clients
licensemanager = boto3.client("license-manager")
@registry.register_check("license-manager")
def license_manager_hard_count_check(cache: dict, awsAccountId: str, awsRegion: str, awsPartition: str) -> dict:
"""[LicenseManager.1] License Manager license configurations should be configured to enforce a hard limit"""
try:
# TODO: need to catch the case that License Manager is not setup
response = licensemanager.list_license_configurations()
lmCheck = str(response["LicenseConfigurations"])
if lmCheck == "[]":
pass
else:
myLiscMgrConfigs = response["LicenseConfigurations"]
for lmconfigs in myLiscMgrConfigs:
liscConfigArn = str(lmconfigs["LicenseConfigurationArn"])
# ISO Time
iso8601Time = (
datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat()
)
try:
response = licensemanager.get_license_configuration(
LicenseConfigurationArn=liscConfigArn
)
liscConfigId = str(response["LicenseConfigurationId"])
liscConfigName = str(response["Name"])
hardLimitCheck = str(response["LicenseCountHardLimit"])
if hardLimitCheck == "False":
finding = {
"SchemaVersion": "2018-10-08",
"Id": liscConfigArn + "/license-manager-enforce-hard-limit-check",
"ProductArn": f"arn:{awsPartition}:securityhub:{awsRegion}:{awsAccountId}:product/{awsAccountId}/default",
"GeneratorId": liscConfigArn,
"AwsAccountId": awsAccountId,
"Types": [
"Software and Configuration Checks/AWS Security Best Practices"
],
"FirstObservedAt": iso8601Time,
"CreatedAt": iso8601Time,
"UpdatedAt": iso8601Time,
"Severity": {"Label": "LOW"},
"Confidence": 99,
"Title": "[LicenseManager.1] License Manager license configurations should be configured to enforce a hard limit",
"Description": "License Manager license configuration "
+ liscConfigName
+ " does not enforce a hard limit. Enforcing a hard limit prevents new instances from being created that if you have already provisioned all available licenses. Refer to the remediation instructions to remediate this behavior",
"Remediation": {
"Recommendation": {
"Text": "For information on hard limits refer to the License Configuration Parameters and Rules section of the AWS License Manager User Guide",
"Url": "https://docs.aws.amazon.com/license-manager/latest/userguide/config-overview.html",
}
},
"ProductFields": {"Product Name": "ElectricEye"},
"Resources": [
{
"Type": "AwsLicenseManagerLicenseConfiguration",
"Id": liscConfigArn,
"Partition": awsPartition,
"Region": awsRegion,
"Details": {
"Other": {
"licenseConfigurationId": liscConfigId,
"licenseConfigurationName": liscConfigName,
}
},
}
],
"Compliance": {
"Status": "FAILED",
"RelatedRequirements": [
"NIST CSF ID.AM-2",
"NIST SP 800-53 CM-8",
"NIST SP 800-53 PM-5",
"AICPA TSC CC3.2",
"AICPA TSC CC6.1",
"ISO 27001:2013 A.8.1.1",
"ISO 27001:2013 A.8.1.2",
"ISO 27001:2013 A.12.5.1",
],
},
"Workflow": {"Status": "NEW"},
"RecordState": "ACTIVE",
}
yield finding
else:
finding = {
"SchemaVersion": "2018-10-08",
"Id": liscConfigArn + "/license-manager-enforce-hard-limit-check",
"ProductArn": f"arn:{awsPartition}:securityhub:{awsRegion}:{awsAccountId}:product/{awsAccountId}/default",
"GeneratorId": liscConfigArn,
"AwsAccountId": awsAccountId,
"Types": [
"Software and Configuration Checks/AWS Security Best Practices"
],
"FirstObservedAt": iso8601Time,
"CreatedAt": iso8601Time,
"UpdatedAt": iso8601Time,
"Severity": {"Label": "INFORMATIONAL"},
"Confidence": 99,
"Title": "[LicenseManager.1] License Manager license configurations should be configured to enforce a hard limit",
"Description": "License Manager license configuration "
+ liscConfigName
+ " enforces a hard limit.",
"Remediation": {
"Recommendation": {
"Text": "For information on hard limits refer to the License Configuration Parameters and Rules section of the AWS License Manager User Guide",
"Url": "https://docs.aws.amazon.com/license-manager/latest/userguide/config-overview.html",
}
},
"ProductFields": {"Product Name": "ElectricEye"},
"Resources": [
{
"Type": "AwsLicenseManagerLicenseConfiguration",
"Id": liscConfigArn,
"Partition": awsPartition,
"Region": awsRegion,
"Details": {
"Other": {
"licenseConfigurationId": liscConfigId,
"licenseConfigurationName": liscConfigName,
}
},
}
],
"Compliance": {
"Status": "PASSED",
"RelatedRequirements": [
"NIST CSF ID.AM-2",
"NIST SP 800-53 CM-8",
"NIST SP 800-53 PM-5",
"AICPA TSC CC3.2",
"AICPA TSC CC6.1",
"ISO 27001:2013 A.8.1.1",
"ISO 27001:2013 A.8.1.2",
"ISO 27001:2013 A.12.5.1",
],
},
"Workflow": {"Status": "RESOLVED"},
"RecordState": "ARCHIVED",
}
yield finding
except Exception as e:
print(e)
except Exception as e:
print(e)
@registry.register_check("license-manager")
def license_manager_disassociation_check(cache: dict, awsAccountId: str, awsRegion: str, awsPartition: str) -> dict:
"""[LicenseManager.2] License Manager license configurations should disassociate hosts when license in scope is not found"""
try:
# TODO: need to catch the case that License Manager is not setup
response = licensemanager.list_license_configurations()
lmCheck = str(response["LicenseConfigurations"])
if lmCheck == "[]":
pass
else:
myLiscMgrConfigs = response["LicenseConfigurations"]
for lmconfigs in myLiscMgrConfigs:
liscConfigArn = str(lmconfigs["LicenseConfigurationArn"])
# ISO Time
iso8601Time = (
datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat()
)
try:
response = licensemanager.get_license_configuration(
LicenseConfigurationArn=liscConfigArn
)
liscConfigId = str(response["LicenseConfigurationId"])
liscConfigName = str(response["Name"])
disassocCheck = str(response["DisassociateWhenNotFound"])
if disassocCheck == "False":
finding = {
"SchemaVersion": "2018-10-08",
"Id": liscConfigArn + "/license-manager-disassociation-check",
"ProductArn": f"arn:{awsPartition}:securityhub:{awsRegion}:{awsAccountId}:product/{awsAccountId}/default",
"GeneratorId": liscConfigArn,
"AwsAccountId": awsAccountId,
"Types": [
"Software and Configuration Checks/AWS Security Best Practices"
],
"FirstObservedAt": iso8601Time,
"CreatedAt": iso8601Time,
"UpdatedAt": iso8601Time,
"Severity": {"Label": "LOW"},
"Confidence": 99,
"Title": "[LicenseManager.2] License Manager license configurations should disassociate hosts when license in scope is not found",
"Description": "License Manager license configuration "
+ liscConfigName
+ " does not enforce automatic disassociation. Refer to the remediation instructions to remediate this behavior.",
"Remediation": {
"Recommendation": {
"Text": "For information on disassociation refer to the Disassociating license configurations and AMIs section of the AWS License Manager User Guide",
"Url": "https://docs.aws.amazon.com/license-manager/latest/userguide/license-rules.html#ami-disassociation",
}
},
"ProductFields": {"Product Name": "ElectricEye"},
"Resources": [
{
"Type": "AwsLicenseManagerLicenseConfiguration",
"Id": liscConfigArn,
"Partition": awsPartition,
"Region": awsRegion,
"Details": {
"Other": {
"LicenseConfigurationId": liscConfigId,
"LicenseConfigurationName": liscConfigName,
}
},
}
],
"Compliance": {
"Status": "FAILED",
"RelatedRequirements": [
"NIST CSF ID.AM-2",
"NIST SP 800-53 CM-8",
"NIST SP 800-53 PM-5",
"AICPA TSC CC3.2",
"AICPA TSC CC6.1",
"ISO 27001:2013 A.8.1.1",
"ISO 27001:2013 A.8.1.2",
"ISO 27001:2013 A.12.5.1",
],
},
"Workflow": {"Status": "NEW"},
"RecordState": "ACTIVE",
}
yield finding
else:
finding = {
"SchemaVersion": "2018-10-08",
"Id": liscConfigArn + "/license-manager-disassociation-check",
"ProductArn": f"arn:{awsPartition}:securityhub:{awsRegion}:{awsAccountId}:product/{awsAccountId}/default",
"GeneratorId": liscConfigArn,
"AwsAccountId": awsAccountId,
"Types": [
"Software and Configuration Checks/AWS Security Best Practices"
],
"FirstObservedAt": iso8601Time,
"CreatedAt": iso8601Time,
"UpdatedAt": iso8601Time,
"Severity": {"Label": "INFORMATIONAL"},
"Confidence": 99,
"Title": "[LicenseManager.2] License Manager license configurations should disassociate hosts when license in scope is not found",
"Description": "License Manager license configuration "
+ liscConfigName
+ " enforces automatic disassociation.",
"Remediation": {
"Recommendation": {
"Text": "For information on disassociation refer to the Disassociating license configurations and AMIs section of the AWS License Manager User Guide",
"Url": "https://docs.aws.amazon.com/license-manager/latest/userguide/license-rules.html#ami-disassociation",
}
},
"ProductFields": {"Product Name": "ElectricEye"},
"Resources": [
{
"Type": "AwsLicenseManagerLicenseConfiguration",
"Id": liscConfigArn,
"Partition": awsPartition,
"Region": awsRegion,
"Details": {
"Other": {
"LicenseConfigurationId": liscConfigId,
"LicenseConfigurationName": liscConfigName,
}
},
}
],
"Compliance": {
"Status": "PASSED",
"RelatedRequirements": [
"NIST CSF ID.AM-2",
"NIST SP 800-53 CM-8",
"NIST SP 800-53 PM-5",
"AICPA TSC CC3.2",
"AICPA TSC CC6.1",
"ISO 27001:2013 A.8.1.1",
"ISO 27001:2013 A.8.1.2",
"ISO 27001:2013 A.12.5.1"
]
},
"Workflow": {"Status": "RESOLVED"},
"RecordState": "ARCHIVED",
}
yield finding
except Exception as e:
print(e)
except Exception as e:
print(e) | 10,829 |
1,056 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.web.jsf.api.editor;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.netbeans.api.project.Project;
import org.netbeans.modules.j2ee.metadata.model.api.MetadataModel;
import org.netbeans.modules.j2ee.metadata.model.api.MetadataModelAction;
import org.netbeans.modules.j2ee.metadata.model.api.MetadataModelException;
import org.netbeans.modules.web.jsf.JSFUtils;
import org.netbeans.modules.web.jsf.api.metamodel.FacesManagedBean;
import org.netbeans.modules.web.jsf.api.metamodel.JsfModel;
import org.openide.util.Lookup;
/**
* Actually this class does cache nothing, but grabs the data from beans model
* which is supposed to do the caching.
*
* @author <NAME>
* @author ads
*/
public class JSFBeanCache {
public static List<FacesManagedBean> getBeans(Project project) {
//unit testing, tests can provider a fake beans provider >>>
JsfBeansProvider beansProvider = Lookup.getDefault().lookup(JsfBeansProvider.class);
if(beansProvider != null) {
return beansProvider.getBeans(project);
}
//<<<
final List<FacesManagedBean> beans = new ArrayList<FacesManagedBean>();
MetadataModel<JsfModel> model = JSFUtils.getModel(project);
if ( model == null){
return beans;
}
try {
model.runReadAction( new MetadataModelAction<JsfModel, Void>() {
public Void run( JsfModel model ) throws Exception {
List<FacesManagedBean> managedBeans = model.getElements(
FacesManagedBean.class);
beans.addAll( managedBeans );
return null;
}
});
}
catch (MetadataModelException e) {
LOG.log( Level.WARNING , e.getMessage(), e );
}
catch (IOException e) {
LOG.log( Level.WARNING , e.getMessage(), e );
}
return beans;
}
private static final Logger LOG = Logger.getLogger(
JSFBeanCache.class.getCanonicalName() );
//for unit tests>>>
public static interface JsfBeansProvider {
public List<FacesManagedBean> getBeans(Project project);
}
//<<<
}
| 1,200 |
1,269 | package com.chiclaim.ipc.bean;
import android.os.Parcel;
import android.os.Parcelable;
public class Message implements Parcelable {
private String content;
private boolean isSendSuccess;
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public boolean isSendSuccess() {
return isSendSuccess;
}
public void setSendSuccess(boolean sendSuccess) {
isSendSuccess = sendSuccess;
}
@Override
public int describeContents() {
return 0;
}
public void readFromParcel(Parcel parcel) {
this.content = parcel.readString();
this.isSendSuccess = parcel.readByte() != 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.content);
dest.writeByte(this.isSendSuccess ? (byte) 1 : (byte) 0);
}
public Message() {
}
protected Message(Parcel in) {
this.content = in.readString();
this.isSendSuccess = in.readByte() != 0;
}
public static final Parcelable.Creator<Message> CREATOR = new Parcelable.Creator<Message>() {
@Override
public Message createFromParcel(Parcel source) {
return new Message(source);
}
@Override
public Message[] newArray(int size) {
return new Message[size];
}
};
}
| 572 |
577 | package org.fluentlenium.adapter.sharedwebdriver;
/**
* Stores and handles a {@link SharedWebDriver} instance for the whole JVM.
*
* @see org.fluentlenium.configuration.ConfigurationProperties.DriverLifecycle#JVM
* @see SharedWebdriverSingletonImpl
*/
public class JvmDriver implements FluentLeniumDriver {
private SharedWebDriver jvmDriver;
public SharedWebDriver getDriver() {
return jvmDriver;
}
@Override
public void quitDriver(SharedWebDriver driver) {
if (jvmDriver == driver) { // NOPMD CompareObjectsWithEquals
if (jvmDriver.getDriver() != null) {
jvmDriver.getDriver().quit();
}
jvmDriver = null;
}
}
@Override
public void addDriver(SharedWebDriver driver) {
this.jvmDriver = driver;
}
}
| 322 |
892 | {
"schema_version": "1.2.0",
"id": "GHSA-4pjg-hm2r-rj25",
"modified": "2022-05-02T03:17:56Z",
"published": "2022-05-02T03:17:56Z",
"aliases": [
"CVE-2009-0742"
],
"details": "The username command in Cisco ACE Application Control Engine Module for Catalyst 6500 Switches and 7600 Routers and Cisco ACE 4710 Application Control Engine Appliance stores a cleartext password by default, which allows context-dependent attackers to obtain sensitive information.",
"severity": [
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2009-0742"
},
{
"type": "WEB",
"url": "http://www.cisco.com/en/US/products/products_security_advisory09186a0080a7bc82.shtml"
}
],
"database_specific": {
"cwe_ids": [
],
"severity": "HIGH",
"github_reviewed": false
}
} | 361 |
1,738 | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_EDITOR_AI_AIDEBUGGER_H
#define CRYINCLUDE_EDITOR_AI_AIDEBUGGER_H
#pragma once
#include <QMainWindow>
#include <IAISystem.h>
class CAIDebuggerView;
namespace Ui
{
class AIDebugger;
}
//////////////////////////////////////////////////////////////////////////
//
// Main Dialog for AI Debugger
//
//////////////////////////////////////////////////////////////////////////
class CAIDebugger
: public QMainWindow
, public IEditorNotifyListener
{
Q_OBJECT
public:
static const char* ClassName();
static const GUID& GetClassID();
static void RegisterViewClass();
CAIDebugger(QWidget* parent = nullptr);
virtual ~CAIDebugger();
protected:
void closeEvent(QCloseEvent* event) override;
void FileLoad(void);
void FileSave(void);
void FileLoadAs(void);
void FileSaveAs(void);
//KDAB These are unused?
void DebugOptionsEnableAll(void);
void DebugOptionsDisableAll(void);
// Called by the editor to notify the listener about the specified event.
void OnEditorNotifyEvent(EEditorNotifyEvent event) Q_DECL_OVERRIDE;
void UpdateAll(void);
protected:
QScopedPointer<Ui::AIDebugger> m_ui;
};
#endif // CRYINCLUDE_EDITOR_AI_AIDEBUGGER_H
| 588 |
777 | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/arc/video/gpu_arc_video_service_host.h"
#include <string>
#include <utility>
#include "base/location.h"
#include "base/logging.h"
#include "base/memory/ptr_util.h"
#include "base/message_loop/message_loop.h"
#include "base/threading/thread_task_runner_handle.h"
#include "components/arc/arc_bridge_service.h"
#include "components/arc/common/video_accelerator.mojom.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/gpu_service_registry.h"
#include "mojo/edk/embedder/embedder.h"
#include "mojo/edk/embedder/platform_channel_pair.h"
#include "mojo/public/cpp/bindings/strong_binding.h"
#include "services/service_manager/public/cpp/interface_provider.h"
namespace arc {
namespace {
void ConnectToVideoAcceleratorServiceOnIOThread(
mojom::VideoAcceleratorServiceRequest request) {
content::GetGpuRemoteInterfaces()->GetInterface(std::move(request));
}
} // namespace
class VideoAcceleratorFactoryService : public mojom::VideoAcceleratorFactory {
public:
VideoAcceleratorFactoryService() = default;
void Create(mojom::VideoAcceleratorServiceRequest request) override {
content::BrowserThread::PostTask(
content::BrowserThread::IO, FROM_HERE,
base::Bind(&ConnectToVideoAcceleratorServiceOnIOThread,
base::Passed(&request)));
}
private:
DISALLOW_COPY_AND_ASSIGN(VideoAcceleratorFactoryService);
};
GpuArcVideoServiceHost::GpuArcVideoServiceHost(ArcBridgeService* bridge_service)
: ArcService(bridge_service), binding_(this) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
arc_bridge_service()->video()->AddObserver(this);
}
GpuArcVideoServiceHost::~GpuArcVideoServiceHost() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
arc_bridge_service()->video()->RemoveObserver(this);
}
void GpuArcVideoServiceHost::OnInstanceReady() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
auto* video_instance =
ARC_GET_INSTANCE_FOR_METHOD(arc_bridge_service()->video(), Init);
DCHECK(video_instance);
video_instance->Init(binding_.CreateInterfacePtrAndBind());
}
void GpuArcVideoServiceHost::OnBootstrapVideoAcceleratorFactory(
const OnBootstrapVideoAcceleratorFactoryCallback& callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
// Hardcode pid 0 since it is unused in mojo.
const base::ProcessHandle kUnusedChildProcessHandle =
base::kNullProcessHandle;
mojo::edk::PlatformChannelPair channel_pair;
std::string child_token = mojo::edk::GenerateRandomToken();
mojo::edk::ChildProcessLaunched(kUnusedChildProcessHandle,
channel_pair.PassServerHandle(), child_token);
MojoHandle wrapped_handle;
MojoResult wrap_result = mojo::edk::CreatePlatformHandleWrapper(
channel_pair.PassClientHandle(), &wrapped_handle);
if (wrap_result != MOJO_RESULT_OK) {
LOG(ERROR) << "Pipe failed to wrap handles. Closing: " << wrap_result;
callback.Run(mojo::ScopedHandle(), std::string());
return;
}
mojo::ScopedHandle child_handle{mojo::Handle(wrapped_handle)};
std::string token = mojo::edk::GenerateRandomToken();
mojo::ScopedMessagePipeHandle server_pipe =
mojo::edk::CreateParentMessagePipe(token, child_token);
if (!server_pipe.is_valid()) {
LOG(ERROR) << "Invalid pipe";
callback.Run(mojo::ScopedHandle(), std::string());
return;
}
callback.Run(std::move(child_handle), token);
mojo::MakeStrongBinding(base::MakeUnique<VideoAcceleratorFactoryService>(),
mojo::MakeRequest<mojom::VideoAcceleratorFactory>(
std::move(server_pipe)));
}
} // namespace arc
| 1,360 |
352 | <filename>src/tiny_http/http_factory.h<gh_stars>100-1000
/*
*Author:GeneralSandman
*Code:https://github.com/GeneralSandman/TinyWeb
*E-mail:<EMAIL>
*Web:www.dissigil.cn
*/
/*---XXX---
*
****************************************
*
*/
#ifndef HTTP_FACTORY_H
#define HTTP_FACTORY_H
#include <tiny_base/log.h>
#include <tiny_core/factory.h>
class WebServerFactory : public Factory {
private:
public:
WebServerFactory(EventLoop*, Protocol*);
virtual void buildProtocol(Protocol* newProt);
virtual ~WebServerFactory();
};
#endif // !HTTP_FACTORY_H
| 208 |
667 | <reponame>lsqtzj/TSeer
/**
* Tencent is pleased to support the open source community by making Tseer available.
*
* Copyright (C) 2018 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
#ifndef _APIREGIMP_H_
#define _APIREGIMP_H_
#include "servant/Application.h"
#include "servant/Servant.h"
#include "util/tc_http.h"
#include "rapidjson/document.h"
#include "rapidjson/prettywriter.h"
#include "RouterData.h"
#include "EtcdCommon.h"
#include "BaseHandle.h"
#include "TseerAgentUpdate.h"
class NotifyUpdateEvent : public TC_HandleBase
{
public:
//事件总数
int _run_times;
//已经完成的事件计数
tars::TC_Atomic _atomic;
tars::TC_ThreadLock _monitor;
tars::TC_ThreadLock _metux;
//ip=result
map<string,string> _succNum;
map<string,string> _failureNum;
NotifyUpdateEvent()
: _run_times(0)
, _atomic(0)
{
}
void addSuc(const string& ip);
void addFail(const string& ip,const string& errMsg);
};
typedef tars::TC_AutoPtr<NotifyUpdateEvent> NotifyUpdateEventPtr;
class UpdateAgentCallbackImp : public UpdatePrxCallback
{
public:
UpdateAgentCallbackImp(const NotifyUpdateEventPtr& notifyPtr, const string& ip) : _notify(notifyPtr), _ip(ip)
{
}
void callback_updateConfig(tars::Int32 ret,const std::string& result);
void callback_updateConfig_exception(tars::Int32 ret);
private:
NotifyUpdateEventPtr _notify;
string _ip;
};
class ApiRegImp : public tars::Servant
{
public:
virtual ~ApiRegImp() {}
virtual void initialize();
virtual void destroy();
/**
* @brief 处理客户端的主动请求
* @param current
* @param response
* @return int
*/
virtual int doRequest(tars::TarsCurrentPtr current, vector<char>& response);
//路由数据请求回包
static void doGetRouteResponse(TarsCurrentPtr ¤t, int ret,const vector<RouterData>& routerDataList,const string& errMsg);
//IDC分组信息请求回包
void doGetIdcGroupResponse(TarsCurrentPtr current, int ret, const vector<IDCGroupInfo> &idcGroupInfoList);
//IDC优先级信息请求回包
void doGetIdcPriorityResponse(TarsCurrentPtr current, int ret, const vector<IDCPriority> &idcPriority);
//非获取请求、获取失败回包
static void doResponse(TarsCurrentPtr current, int ret, const string& errMsg = "");
void doResponse(TarsCurrentPtr current, int ret, rapidjson::Document &document, const string& errMsg);
//添加IDC分组规则、优先级规则,返回规则的ID
static void doAddIdcResponse(TarsCurrentPtr current, int ret, const string &id);
private:
/**
* @brief 获取请求参数,包括方法名,key,接口参数(如果有)
* @param req
* @param method
* @param key
* @param methodParam
* @param errMsg
* @return 详见API_ERROR_CODE
*/
int getReqParam(const tars::TC_HttpRequest& req,string& method,string& key,string& methodParam,string& errMsg) const;
/**
* @brief 检查请求参数里指定的版本号是否合法
* @param req
* @return bool
*/
bool IsApiVersionValid(const tars::TC_HttpRequest &req) const;
private:
/**
* @brief 添加新模块或者新的ip port路由信息
* @param jData
* @return 详见API_ERROR_CODE
*/
int addServer(TarsCurrentPtr current, rapidjson::Document &jData);
/**
* @brief 更新指定模块的路由属性,包括set,idc 分组,权重,可用状态,流量开关
* @param jData
* @return 详见API_ERROR_CODE
*/
int updateServer(TarsCurrentPtr current, rapidjson::Document &jData);
/**
* @brief 删除模块或某个ip port路由信息
* @param jData
* @return 详见API_ERROR_CODE
*/
int delServer(TarsCurrentPtr current, rapidjson::Document &jData);
/**
* @brief 获取某个业务集下所有服务或者某个服务的路由数据信息
* @param jData
* @return 详见API_ERROR_CODE
*/
int getServer(TarsCurrentPtr current, rapidjson::Document &jData);
/**
* @brief 针对某个服务的路由端口上报心跳
* @param jData
* @return 详见API_ERROR_CODE
*/
int keepalive(TarsCurrentPtr current, rapidjson::Document &jData);
/**
* @brief 向名字服务注册一个业务集名称
* @param jData
* @return 详见API_ERROR_CODE
*/
int addServiceGroup(TarsCurrentPtr current, rapidjson::Document &jData);
/**
* @brief 获取所有或者指定业务集信息(业务集名称,key,user)
* @param jData
* @return 详见API_ERROR_CODE
*/
int getServiceGroup(TarsCurrentPtr current, rapidjson::Document &jData);
/**
* @brief 更新业务集对应的管理人员
* @param jData
* @return 详见API_ERROR_CODE
*/
int updateServiceGroup(TarsCurrentPtr current, rapidjson::Document &jData);
/**
* @brief 获取idc分组信息
* @param jData
* @return 详见API_ERROR_CODE
*/
int getIdcGroup(TarsCurrentPtr current, rapidjson::Document &jData);
/**
* @brief 下线agent
* @param jData
* @return 详见API_ERROR_CODE
*/
int deleteAgent(TarsCurrentPtr current, rapidjson::Document &jData);
/**
* @brief 更新某个或者多个agent的路由中心地址
* @param jData
* @return 详见API_ERROR_CODE
*/
int updateAgentLocator(TarsCurrentPtr current, rapidjson::Document &jData);
UpdatePrx getAgentPrx(const string & nodeName);
/**********************************IDC相关*****************************************/
//分组
int addIdcGroupRule(TarsCurrentPtr current, rapidjson::Document &jData);
int modifyIdcGroupRule(TarsCurrentPtr current, rapidjson::Document &jData);
int delIdcGroupRule(TarsCurrentPtr current, rapidjson::Document &jData);
int getAllIdcGroupRule(TarsCurrentPtr current, rapidjson::Document& jData);
//优先级
int addIdcPriority(TarsCurrentPtr current, rapidjson::Document &jData);
int modifyIdcPriority(TarsCurrentPtr current, rapidjson::Document &jData);
int delIdcPriority(TarsCurrentPtr current, rapidjson::Document &jData);
int getAllIdcPriority(TarsCurrentPtr current, rapidjson::Document& jData);
/*******************************SeerAgent管理********************************/
int getAgentBaseInfo(TarsCurrentPtr current, rapidjson::Document &jData);
int updateAgentGrayState(TarsCurrentPtr current, rapidjson::Document &jData);
int getAgentPackageInfo(TarsCurrentPtr current, rapidjson::Document &jData);
int updateAgentPackageInfo(TarsCurrentPtr current, rapidjson::Document &jData);
int deleteAgentPackageInfo(TarsCurrentPtr current, rapidjson::Document &jData);
int getAgentOstypeInfo(TarsCurrentPtr current, rapidjson::Document &jData);
int addAgentPackageInfo(TarsCurrentPtr current, rapidjson::Document &jData);
/**
* @brief 下载安装agent的脚本
*/
void downloadInstallScript(tars::TarsCurrentPtr current);
/**
* @brief 下载agent安装包
* @param reqParam wget请求参数
*/
void downloadAgentPackage(tars::TarsCurrentPtr current,const string& reqParam);
/**
* 通过wget方式获取locator列表
*/
void getLocatorList(tars::TarsCurrentPtr current);
private:
//支持的API名称
typedef int (ApiRegImp::*CommandHandler)(TarsCurrentPtr, rapidjson::Document& );
std::map<string, CommandHandler> _supportMethods;
//业务集鉴权key缓存,key=serviceGrp,value=skey
map<string,string> _mapServiceGrpKey;
};
#endif
| 3,561 |
1,056 | <reponame>timfel/netbeans
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.spi.java.project.support;
import java.text.MessageFormat;
import org.netbeans.api.annotations.common.CheckForNull;
import org.netbeans.api.annotations.common.NonNull;
import org.netbeans.api.java.platform.JavaPlatform;
import org.netbeans.api.java.platform.JavaPlatformManager;
import org.netbeans.api.java.platform.Specification;
import org.openide.util.NbPreferences;
import org.openide.util.Parameters;
/**
* Returns a preferred {@link JavaPlatform} for a new project.
* @author <NAME>
* @since 1.46
*/
public final class PreferredProjectPlatform {
private static final String PREFERRED_PLATFORM = "preferred.platform.{0}"; //NOI18N
private static final String PLATFORM_ANT_NAME = "platform.ant.name"; //NOI18N
private PreferredProjectPlatform() {
throw new AssertionError();
}
/**
* Returns a preferred {@link JavaPlatform} for a new project.
* @param platformType the platform type as specified by {@link Specification#getName()}
* @return the preferred {@link JavaPlatform}
*/
@CheckForNull
public static JavaPlatform getPreferredPlatform(@NonNull final String platformType) {
Parameters.notNull("platformType", platformType); //NOI18N
final String platformId = NbPreferences.forModule(PreferredProjectPlatform.class).get(
MessageFormat.format(PREFERRED_PLATFORM, platformType),
null);
final JavaPlatformManager jpm = JavaPlatformManager.getDefault();
if (platformId != null) {
for (JavaPlatform jp : jpm.getInstalledPlatforms()) {
if (platformId.equals(jp.getProperties().get(PLATFORM_ANT_NAME)) &&
platformType.equals(jp.getSpecification().getName()) &&
jp.isValid()) {
return jp;
}
}
}
final JavaPlatform defaultPlatform = jpm.getDefaultPlatform();
return platformType.equals(defaultPlatform.getSpecification().getName())?
defaultPlatform:
null;
}
/**
* Sets a preferred {@link JavaPlatform} for a new project.
* @param platform the preferred {@link JavaPlatform}
*/
public static void setPreferredPlatform(@NonNull final JavaPlatform platform) {
Parameters.notNull("platform", platform); //NOI18N
final String platformId = platform.getProperties().get(PLATFORM_ANT_NAME);
if (platformId == null) {
throw new IllegalArgumentException("Invalid platform, the platform has no platform.ant.name"); //NOI18N
}
final String platformType = platform.getSpecification().getName();
NbPreferences.forModule(PreferredProjectPlatform.class).put(
MessageFormat.format(PREFERRED_PLATFORM, platformType),
platformId);
}
}
| 1,320 |
777 | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/browsing_data/core/browsing_data_utils.h"
#include <string>
#include "base/message_loop/message_loop.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/thread_task_runner_handle.h"
#include "components/autofill/core/browser/webdata/autofill_webdata_service.h"
#include "components/browsing_data/core/counters/autofill_counter.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
class FakeWebDataService : public autofill::AutofillWebDataService {
public:
FakeWebDataService()
: AutofillWebDataService(base::ThreadTaskRunnerHandle::Get(),
base::ThreadTaskRunnerHandle::Get()) {}
protected:
~FakeWebDataService() override {}
};
} // namespace
class BrowsingDataUtilsTest : public testing::Test {
public:
BrowsingDataUtilsTest() {}
~BrowsingDataUtilsTest() override {}
private:
base::MessageLoop loop_;
};
// Tests the complex output of the Autofill counter.
TEST_F(BrowsingDataUtilsTest, AutofillCounterResult) {
browsing_data::AutofillCounter counter(
scoped_refptr<FakeWebDataService>(new FakeWebDataService()));
// Test all configurations of zero and nonzero partial results for datatypes.
// Test singular and plural for each datatype.
const struct TestCase {
int num_credit_cards;
int num_addresses;
int num_suggestions;
std::string expected_output;
} kTestCases[] = {
{0, 0, 0, "none"},
{1, 0, 0, "1 credit card"},
{0, 5, 0, "5 addresses"},
{0, 0, 1, "1 suggestion"},
{0, 0, 2, "2 suggestions"},
{4, 7, 0, "4 credit cards, 7 addresses"},
{3, 0, 9, "3 credit cards, 9 other suggestions"},
{0, 1, 1, "1 address, 1 other suggestion"},
{9, 6, 3, "9 credit cards, 6 addresses, 3 others"},
{4, 2, 1, "4 credit cards, 2 addresses, 1 other"},
};
for (const TestCase& test_case : kTestCases) {
browsing_data::AutofillCounter::AutofillResult result(
&counter, test_case.num_suggestions, test_case.num_credit_cards,
test_case.num_addresses);
SCOPED_TRACE(
base::StringPrintf("Test params: %d credit card(s), "
"%d address(es), %d suggestion(s).",
test_case.num_credit_cards, test_case.num_addresses,
test_case.num_suggestions));
base::string16 output = browsing_data::GetCounterTextFromResult(&result);
EXPECT_EQ(output, base::ASCIIToUTF16(test_case.expected_output));
}
}
| 1,050 |
1,899 | #pragma once
#include "BGModel.h"
namespace bgslibrary
{
namespace algorithms
{
namespace lb
{
namespace BGModelGaussParams {
const double THRESHGAUSS = 2.5; // Threshold
const double ALPHAGAUSS = 0.0001; // Learning rate
const double NOISEGAUSS = 50.0; // Minimum variance (noise)
}
class BGModelGauss : public BGModel
{
public:
BGModelGauss(int width, int height);
~BGModelGauss();
void setBGModelParameter(int id, int value);
protected:
double m_alpha;
double m_threshold;
double m_noise;
DBLRGB* m_pMu;
DBLRGB* m_pVar;
void Init();
void Update();
};
}
}
}
| 353 |
14,668 | <reponame>zealoussnow/chromium
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <limits.h>
#include <stddef.h>
#include <stdint.h>
#include <iostream>
#include <limits>
#include <map>
#include <set>
#include <utility>
#include <vector>
#include "base/bind.h"
#include "base/memory/ptr_util.h"
#include "base/message_loop/message_pump_type.h"
#include "build/build_config.h"
#include "net/base/load_flags.h"
#include "net/base/net_errors.h"
#include "net/base/url_util.h"
#include "net/cert/cert_verifier.h"
#include "net/cookies/cookie_monster.h"
#include "net/http/http_auth_handler_factory.h"
#include "net/proxy_resolution/proxy_config_service_fixed.h"
#include "net/tools/quic/quic_http_proxy_backend.h"
#include "net/tools/quic/quic_http_proxy_backend_stream.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_builder.h"
#include "net/url_request/url_request_interceptor.h"
namespace net {
QuicHttpProxyBackend::QuicHttpProxyBackend()
: context_(nullptr), thread_initialized_(false), proxy_thread_(nullptr) {}
QuicHttpProxyBackend::~QuicHttpProxyBackend() {
backend_stream_map_.clear();
thread_initialized_ = false;
proxy_task_runner_->DeleteSoon(FROM_HERE, context_.release());
if (proxy_thread_ != nullptr) {
LOG(INFO) << "QUIC Proxy thread: " << proxy_thread_->thread_name()
<< " has stopped !";
proxy_thread_.reset();
}
}
bool QuicHttpProxyBackend::InitializeBackend(const std::string& backend_url) {
if (!ValidateBackendUrl(backend_url)) {
return false;
}
if (proxy_thread_ == nullptr) {
proxy_thread_ = std::make_unique<base::Thread>("quic proxy thread");
base::Thread::Options options;
options.message_pump_type = base::MessagePumpType::IO;
bool result = proxy_thread_->StartWithOptions(std::move(options));
proxy_task_runner_ = proxy_thread_->task_runner();
CHECK(result);
}
thread_initialized_ = true;
return true;
}
bool QuicHttpProxyBackend::ValidateBackendUrl(const std::string& backend_url) {
backend_url_ = GURL(backend_url);
// Only Http(s) backend supported
if (!backend_url_.is_valid() || !backend_url_.SchemeIsHTTPOrHTTPS()) {
LOG(ERROR) << "QUIC Proxy Backend URL '" << backend_url
<< "' is not valid !";
return false;
}
LOG(INFO)
<< "Successfully configured to run as a QUIC Proxy with Backend URL: "
<< backend_url_.spec();
return true;
}
bool QuicHttpProxyBackend::IsBackendInitialized() const {
return thread_initialized_;
}
void QuicHttpProxyBackend::FetchResponseFromBackend(
const spdy::Http2HeaderBlock& request_headers,
const std::string& incoming_body,
QuicSimpleServerBackend::RequestHandler* quic_server_stream) {
QuicHttpProxyBackendStream* proxy_backend_stream =
InitializeQuicProxyBackendStream(quic_server_stream);
LOG(INFO) << " Forwarding QUIC request to the Backend Thread Asynchronously.";
if (proxy_backend_stream == nullptr ||
proxy_backend_stream->SendRequestToBackend(&request_headers,
incoming_body) != true) {
quic_server_stream->OnResponseBackendComplete(nullptr);
}
}
QuicHttpProxyBackendStream*
QuicHttpProxyBackend::InitializeQuicProxyBackendStream(
QuicSimpleServerBackend::RequestHandler* quic_server_stream) {
if (!thread_initialized_) {
return nullptr;
}
QuicHttpProxyBackendStream* proxy_backend_stream =
new QuicHttpProxyBackendStream(this);
proxy_backend_stream->set_delegate(quic_server_stream);
proxy_backend_stream->Initialize(quic_server_stream->connection_id(),
quic_server_stream->stream_id(),
quic_server_stream->peer_host());
{
// Aquire write lock for this scope
base::AutoLock lock(backend_stream_mutex_);
auto inserted = backend_stream_map_.insert(std::make_pair(
quic_server_stream, base::WrapUnique(proxy_backend_stream)));
DCHECK(inserted.second);
}
return proxy_backend_stream;
}
void QuicHttpProxyBackend::CloseBackendResponseStream(
QuicSimpleServerBackend::RequestHandler* quic_server_stream) {
// Clean close of the backend stream handler
if (quic_server_stream == nullptr) {
return;
}
// Cleanup the handler on the proxy thread, since it owns the url_request
if (!proxy_task_runner_->BelongsToCurrentThread()) {
proxy_task_runner_->PostTask(
FROM_HERE,
base::BindOnce(&QuicHttpProxyBackend::CloseBackendResponseStream,
base::Unretained(this), quic_server_stream));
} else {
// Aquire write lock for this scope and cancel if the request is still
// pending
base::AutoLock lock(backend_stream_mutex_);
QuicHttpProxyBackendStream* proxy_backend_stream = nullptr;
auto it = backend_stream_map_.find(quic_server_stream);
if (it != backend_stream_map_.end()) {
proxy_backend_stream = it->second.get();
proxy_backend_stream->CancelRequest();
proxy_backend_stream->reset_delegate();
LOG(INFO) << " Quic Proxy cleaned-up backend handler on context/main "
"thread for quic_conn_id: "
<< proxy_backend_stream->quic_connection_id()
<< " quic_stream_id: "
<< proxy_backend_stream->quic_stream_id();
size_t erased = backend_stream_map_.erase(quic_server_stream);
DCHECK_EQ(1u, erased);
}
}
}
void QuicHttpProxyBackend::InitializeURLRequestContext() {
DCHECK(context_ == nullptr);
net::URLRequestContextBuilder context_builder;
// Quic reverse proxy does not cache HTTP objects
context_builder.DisableHttpCache();
// Enable HTTP2, but disable QUIC on the backend
context_builder.SetSpdyAndQuicEnabled(true /* http2 */, false /* quic */);
#if defined(OS_LINUX) || defined(OS_CHROMEOS)
// On Linux, use a fixed ProxyConfigService, since the default one
// depends on glib.
context_builder.set_proxy_config_service(
std::make_unique<ProxyConfigServiceFixed>(
ProxyConfigWithAnnotation::CreateDirect()));
#endif
// Disable net::CookieStore.
context_builder.SetCookieStore(nullptr);
context_ = context_builder.Build();
}
net::URLRequestContext* QuicHttpProxyBackend::GetURLRequestContext() {
// Access to URLRequestContext is only available on Backend Thread
DCHECK(proxy_task_runner_->BelongsToCurrentThread());
if (context_ == nullptr) {
InitializeURLRequestContext();
}
return context_.get();
}
scoped_refptr<base::SingleThreadTaskRunner>
QuicHttpProxyBackend::GetProxyTaskRunner() const {
return proxy_task_runner_;
}
} // namespace net
| 2,515 |
578 | <reponame>499689317/lordofpomelo<filename>web-server/public/animation_json/1074.json
{"LeftAttack":{"height":123,"className":"LeftAttack","width":125,"id":"1074","totalFrames":26},"LeftDefend":{"height":115,"className":"LeftDefend","width":59,"id":"1074","totalFrames":2},"LeftDie":{"height":196,"className":"LeftDie","width":93,"id":"1074","totalFrames":20},"LeftHit":{"height":121,"className":"LeftHit","width":72,"id":"1074","totalFrames":4},"LeftMagic":{"height":120,"className":"LeftMagic","width":151,"id":"1074","totalFrames":31},"LeftStand":{"height":117,"className":"LeftStand","width":87,"id":"1074","totalFrames":24},"LeftWalk":{"height":122,"className":"LeftWalk","width":78,"id":"1074","totalFrames":16},"RightAttack":{"height":107,"className":"RightAttack","width":154,"id":"1074","totalFrames":26},"RightDefend":{"height":99,"className":"RightDefend","width":68,"id":"1074","totalFrames":2},"RightDie":{"height":195,"className":"RightDie","width":89,"id":"1074","totalFrames":20},"RightHit":{"height":103,"className":"RightHit","width":68,"id":"1074","totalFrames":4},"RightMagic":{"height":100,"className":"RightMagic","width":186,"id":"1074","totalFrames":31},"RightStand":{"height":100,"className":"RightStand","width":124,"id":"1074","totalFrames":24},"RightWalk":{"height":102,"className":"RightWalk","width":104,"id":"1074","totalFrames":16}} | 417 |
389 | <gh_stars>100-1000
package com.devskiller.jfairy.producer.payment;
public class IBAN {
private final String accountNumber;
private final String identificationNumber;
private final String branchCode;
private final String checkDigit;
private final String accountType;
private final String bankCode;
private final String bban;
private final String country;
private final String nationalCheckDigit;
private final String ownerAccountType;
private final String ibanNumber;
public IBAN(String accountNumber, String identificationNumber, String branchCode, String checkDigit, String accountType, String bankCode, String bban, String country, String nationalCheckDigit, String ownerAccountType, String ibanNumber) {
this.accountNumber = accountNumber;
this.identificationNumber = identificationNumber;
this.branchCode = branchCode;
this.checkDigit = checkDigit;
this.accountType = accountType;
this.bankCode = bankCode;
this.bban = bban;
this.country = country;
this.nationalCheckDigit = nationalCheckDigit;
this.ownerAccountType = ownerAccountType;
this.ibanNumber = ibanNumber;
}
public String getAccountNumber() {
return accountNumber;
}
public String getIdentificationNumber() {
return identificationNumber;
}
public String getBranchCode() {
return branchCode;
}
public String getCheckDigit() {
return checkDigit;
}
public String getAccountType() {
return accountType;
}
public String getBankCode() {
return bankCode;
}
public String getBban() {
return bban;
}
public String getCountry() {
return country;
}
public String getNationalCheckDigit() {
return nationalCheckDigit;
}
public String getOwnerAccountType() {
return ownerAccountType;
}
public String getIbanNumber() {
return ibanNumber;
}
}
| 534 |
32,544 | package com.baeldung.service.locator;
/**
* Created by Gebruiker on 4/20/2018.
*/
public class InitialContext {
public Object lookup(String serviceName) {
if (serviceName.equalsIgnoreCase("EmailService")) {
return new EmailService();
} else if (serviceName.equalsIgnoreCase("SMSService")) {
return new SMSService();
}
return null;
}
}
| 166 |
937 | package cyclops.typeclasses;
import com.oath.cyclops.hkt.DataWitness.option;
import cyclops.control.Option;
import cyclops.data.Seq;
import cyclops.function.Lambda;
import cyclops.instances.control.OptionInstances;
import cyclops.instances.data.SeqInstances;
import org.junit.Test;
import java.util.concurrent.atomic.AtomicInteger;
import static cyclops.control.Option.some;
import static cyclops.function.Function2._1;
import static cyclops.function.Function2._2;
import static cyclops.function.Function3.__1;
import static cyclops.function.Function3.__12;
import static cyclops.function.Function3.__2;
import static cyclops.function.Function3.__23;
import static cyclops.function.Function3.__3;
import static cyclops.function.Function4.___1;
import static cyclops.function.Function4.___12;
import static cyclops.function.Function4.___13;
import static cyclops.function.Function4.___14;
import static cyclops.function.Function4.___2;
import static cyclops.function.Function4.___23;
import static cyclops.function.Function4.___24;
import static cyclops.function.Function4.___3;
import static cyclops.function.Function4.___34;
import static cyclops.function.Function4.___4;
import static cyclops.function.Function5.____1;
import static cyclops.function.Function5.____12;
import static cyclops.function.Function5.____13;
import static cyclops.function.Function5.____14;
import static cyclops.function.Function5.____2;
import static cyclops.function.Function5.____23;
import static cyclops.function.Function5.____3;
import static cyclops.function.Function5.____34;
import static cyclops.function.Function5.____4;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat;
public class Do6Test {
@Test
public void doOption6(){
assertThat(Do.forEach(OptionInstances::monad)
.__(some(10))
.__(some(5))
.__(some(2))
.__(some(1))
.__(some(100))
.__(some(1000))
.__(some(10000))
.yield((a,b,c,d,e,f,g)->a+b+c+d+e+f+g)
.fold(Option::narrowK),equalTo(some(11118)));
}
@Test
public void doOptionUnbound6(){
assertThat(Do.forEach(OptionInstances::monad)
._of(10)
._of(5)
._of(2)
._of(1)
._of(100)
.__(some(1000))
.__(some(10000))
.yield((a,b,c,d,e,f,g)->a+b+c+d+e+f+g)
.fold(Option::narrowK),
equalTo(some(11118)));
}
@Test
public void doOptionLazy6(){
assertThat(Do.forEach(OptionInstances::monad)
._of(10)
.__(i->some(i/2))
.__((a,b)->some(a-b-3))
.__((a,b,c)->some(a-c-b-2))
.__((a,b,c,d)->some(a+b+c+d+82))
.__((a,b,c,d,e)->some(1000))
.__((a,b,c,d,e,g)->some(10000))
.yield((a,b,c,d,e,f,g)->a+b+c+d+e+f+g)
.fold(Option::narrowK),equalTo(some(11118)));
}
@Test
public void doOptionGuardSome3(){
assertThat(Do.forEach(OptionInstances::monad)
.__(some(10))
.__(some(5))
.__(some(2))
.__(some(1))
.__(some(100))
.__(some(1000))
.__(some(10000))
.guard(OptionInstances.monadZero(),(a,b,c,d,e,f,g)->a+b+c+d+e+f+g>117)
.yield((a,b,c,d,e,f,g)->a+b+c+d+e+f+g)
.fold(Option::narrowK),
equalTo(some(11118)));
}
@Test
public void doOptionGuardNone3(){
assertThat(Do.forEach(OptionInstances::monad)
.__(some(10))
.__(some(5))
.__(some(2))
.__(some(1))
.__(some(100))
.__(some(1000))
.__(some(10000))
.guard(OptionInstances.monadZero(),(a,b,c,d,e,f,g)->a+b+c+d+e+f+g<117)
.yield((a,b,c,d,e,f,g)->a+b+c+d+e+f+g)
.fold(Option::narrowK),equalTo(Option.none()));
}
@Test
public void doOptionShow(){
String s = Do.forEach(OptionInstances.monad())
._of(10)
._of(20)
._of(100)
._of(1000)
._of(10000)
._of(100000)
.show(new Show<option>(){})
.yield((a,b,c,d,e,f)->a+b+c+d+e+f)
.fold(Option::narrowK).orElse(null);
assertThat(s,equalTo("11130Some[10000]"));
}
@Test
public void doOptionShowDefault(){
String s = Do.forEach(OptionInstances.monad())
._of(10)
._of(20)
._of(200)
._of(1000)
._of(10000)
._of(100000)
._show(new Show<option>() {})
.yield((a,b,c,d,e,f,st)->st+a+b+c+d+e+f).fold(Option::narrowK).orElse(null);
assertThat(s,equalTo("Some[1000]1020200100010000100000"));
}
@Test
public void doOptionMap1(){
Option<Integer> eleven = Do.forEach(OptionInstances.monad())
._of(10)
._of(100)
._of(1000)
._of(10000)
._of(100000)
._of(1000000)
.map(i->i+1)
.fold(Option::narrowK);
assertThat(eleven,equalTo(some(1000001)));
}
@Test
public void doOptionPeek1(){
AtomicInteger ai = new AtomicInteger(-1);
Option<Integer> eleven = Do.forEach(OptionInstances.monad())
._of(10)
._of(100)
._of(1000)
._of(10000)
._of(100000)
._of(1000000)
.peek(i->{
ai.set(i);
})
.fold(Option::narrowK);
assertThat(ai.get(),equalTo(1000000));
}
@Test
public void doOptionFlatten (){
Option<Integer> res = Do.forEach(OptionInstances.monad())
._of(10)
._of(100)
._of(1000)
._of(10000)
._of(100000)
._of(1000000)
._flatten(some(some(10)))
.yield((a,b,c,d,e,f,g)->a+b+c+d+e+f+g)
.fold(Option::narrowK);
assertThat(res,equalTo(some(1111120)));
}
@Test
public void doSeqAp(){
Seq<Integer> seq = Do.forEach(SeqInstances::monad)
._of(10)
._of(20)
._of(1000)
._of(10000)
._of(100000)
._of(1000000)
.ap(Seq.of(Lambda.λ((Integer i) -> i + 1)))
.fold(Seq::narrowK);
assertThat(seq,equalTo(Seq.of(1000001)));
}
}
| 3,738 |
372 | <gh_stars>100-1000
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.networkmanagement.v1beta1.model;
/**
* For display only. Metadata associated with a VPC firewall rule, an implied VPC firewall rule, or
* a hierarchical firewall policy rule.
*
* <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 Network Management 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 FirewallInfo extends com.google.api.client.json.GenericJson {
/**
* Possible values: ALLOW, DENY
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String action;
/**
* Possible values: INGRESS, EGRESS
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String direction;
/**
* The display name of the VPC firewall rule. This field is not applicable to hierarchical
* firewall policy rules.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String displayName;
/**
* The firewall rule's type.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String firewallRuleType;
/**
* The URI of the VPC network that the firewall rule is associated with. This field is not
* applicable to hierarchical firewall policy rules.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String networkUri;
/**
* The hierarchical firewall policy that this rule is associated with. This field is not
* applicable to VPC firewall rules.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String policy;
/**
* The priority of the firewall rule.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Integer priority;
/**
* The target service accounts specified by the firewall rule.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> targetServiceAccounts;
/**
* The target tags defined by the VPC firewall rule. This field is not applicable to hierarchical
* firewall policy rules.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> targetTags;
/**
* The URI of the VPC firewall rule. This field is not applicable to implied firewall rules or
* hierarchical firewall policy rules.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String uri;
/**
* Possible values: ALLOW, DENY
* @return value or {@code null} for none
*/
public java.lang.String getAction() {
return action;
}
/**
* Possible values: ALLOW, DENY
* @param action action or {@code null} for none
*/
public FirewallInfo setAction(java.lang.String action) {
this.action = action;
return this;
}
/**
* Possible values: INGRESS, EGRESS
* @return value or {@code null} for none
*/
public java.lang.String getDirection() {
return direction;
}
/**
* Possible values: INGRESS, EGRESS
* @param direction direction or {@code null} for none
*/
public FirewallInfo setDirection(java.lang.String direction) {
this.direction = direction;
return this;
}
/**
* The display name of the VPC firewall rule. This field is not applicable to hierarchical
* firewall policy rules.
* @return value or {@code null} for none
*/
public java.lang.String getDisplayName() {
return displayName;
}
/**
* The display name of the VPC firewall rule. This field is not applicable to hierarchical
* firewall policy rules.
* @param displayName displayName or {@code null} for none
*/
public FirewallInfo setDisplayName(java.lang.String displayName) {
this.displayName = displayName;
return this;
}
/**
* The firewall rule's type.
* @return value or {@code null} for none
*/
public java.lang.String getFirewallRuleType() {
return firewallRuleType;
}
/**
* The firewall rule's type.
* @param firewallRuleType firewallRuleType or {@code null} for none
*/
public FirewallInfo setFirewallRuleType(java.lang.String firewallRuleType) {
this.firewallRuleType = firewallRuleType;
return this;
}
/**
* The URI of the VPC network that the firewall rule is associated with. This field is not
* applicable to hierarchical firewall policy rules.
* @return value or {@code null} for none
*/
public java.lang.String getNetworkUri() {
return networkUri;
}
/**
* The URI of the VPC network that the firewall rule is associated with. This field is not
* applicable to hierarchical firewall policy rules.
* @param networkUri networkUri or {@code null} for none
*/
public FirewallInfo setNetworkUri(java.lang.String networkUri) {
this.networkUri = networkUri;
return this;
}
/**
* The hierarchical firewall policy that this rule is associated with. This field is not
* applicable to VPC firewall rules.
* @return value or {@code null} for none
*/
public java.lang.String getPolicy() {
return policy;
}
/**
* The hierarchical firewall policy that this rule is associated with. This field is not
* applicable to VPC firewall rules.
* @param policy policy or {@code null} for none
*/
public FirewallInfo setPolicy(java.lang.String policy) {
this.policy = policy;
return this;
}
/**
* The priority of the firewall rule.
* @return value or {@code null} for none
*/
public java.lang.Integer getPriority() {
return priority;
}
/**
* The priority of the firewall rule.
* @param priority priority or {@code null} for none
*/
public FirewallInfo setPriority(java.lang.Integer priority) {
this.priority = priority;
return this;
}
/**
* The target service accounts specified by the firewall rule.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getTargetServiceAccounts() {
return targetServiceAccounts;
}
/**
* The target service accounts specified by the firewall rule.
* @param targetServiceAccounts targetServiceAccounts or {@code null} for none
*/
public FirewallInfo setTargetServiceAccounts(java.util.List<java.lang.String> targetServiceAccounts) {
this.targetServiceAccounts = targetServiceAccounts;
return this;
}
/**
* The target tags defined by the VPC firewall rule. This field is not applicable to hierarchical
* firewall policy rules.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getTargetTags() {
return targetTags;
}
/**
* The target tags defined by the VPC firewall rule. This field is not applicable to hierarchical
* firewall policy rules.
* @param targetTags targetTags or {@code null} for none
*/
public FirewallInfo setTargetTags(java.util.List<java.lang.String> targetTags) {
this.targetTags = targetTags;
return this;
}
/**
* The URI of the VPC firewall rule. This field is not applicable to implied firewall rules or
* hierarchical firewall policy rules.
* @return value or {@code null} for none
*/
public java.lang.String getUri() {
return uri;
}
/**
* The URI of the VPC firewall rule. This field is not applicable to implied firewall rules or
* hierarchical firewall policy rules.
* @param uri uri or {@code null} for none
*/
public FirewallInfo setUri(java.lang.String uri) {
this.uri = uri;
return this;
}
@Override
public FirewallInfo set(String fieldName, Object value) {
return (FirewallInfo) super.set(fieldName, value);
}
@Override
public FirewallInfo clone() {
return (FirewallInfo) super.clone();
}
}
| 2,744 |
3,897 | <filename>targets/TARGET_Silicon_Labs/TARGET_SL_RAIL/efr32-rf-driver/rail/rail.h
/**************************************************************************//**
* @file rail.h
* @brief The main header file for the RAIL library. It describes the external
* APIs available to a RAIL user
* @copyright Copyright 2015 Silicon Laboratories, Inc. www.silabs.com
*****************************************************************************/
#ifndef __RAIL_H__
#define __RAIL_H__
// Get the standard include types
#include <stdint.h>
#include <stdbool.h>
#include <string.h> // For memcpy()
// Get the RAIL-specific structures and types
#include "rail_chip_specific.h"
#include "rail_types.h"
#include "rail_assert_error_codes.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @addtogroup RAIL_API RAIL API
* @brief This is the primary API layer for the Radio Abstraction Interface
* Layer (RAIL)
* @{
*/
/**
* @defgroup Protocol_Specific Protocol Specific
* @brief Protocol specific RAIL APIs
*/
/******************************************************************************
* General Radio Operation
*****************************************************************************/
/**
* @addtogroup General
* @brief Basic APIs to set up and interact with the RAIL library
* @{
*/
/**
* Gets the version information for the compiled RAIL library.
*
* @param[out] version A pointer to \ref RAIL_Version_t structure to
* populate with version information.
* @param[in] verbose Populate \ref RAIL_Version_t struct with verbose
* information.
* @return void.
*
* The version information contains a major version number, a minor version
* number, and a rev (revision) number.
*/
void RAIL_GetVersion(RAIL_Version_t *version, bool verbose);
/**
* Initializes RAIL.
*
* @param[in,out] railCfg The configuration and state structure for setting up
* the library, which contains memory and other options needed by RAIL.
* This structure must be allocated in application global read-write
* memory. RAIL may modify fields within or referenced by this structure
* during its operation.
* @param[in] cb A callback that notifies the application when the radio is
* finished initializing and is ready for further configuration. This
* callback is useful for potential transceiver products that require a
* power up sequence before further configuration is available. After the
* callback fires, the radio is ready for additional configuration before
* transmit and receive operations.
* @return Handle for initialized rail instance or NULL if an
* invalid value was passed in the railCfg.
*/
RAIL_Handle_t RAIL_Init(RAIL_Config_t *railCfg,
RAIL_InitCompleteCallbackPtr_t cb);
/**
* Collects entropy from the radio if available.
*
* @param[in] railHandle A RAIL instance handle.
* @param[out] buffer The buffer to write the collected entropy.
* @param[in] bytes The number of bytes to fill in in the input buffer.
* @return Returns the number of bytes of entropy collected. For
* chips that don't support entropy collection, the function returns 0.
* Values less than the requested amount may also be returned on platforms
* that use entropy pools to collect random data periodically.
*
* Attempts to fill the provided buffer with the requested number of bytes of
* entropy. If the requested number of bytes can't be provided, as many
* bytes as possible will be filled and returned. For chips
* that do not support this function, 0 bytes will always be returned. For
* information about the specific mechanism for gathering entropy, see
* documentation for the chip family.
*/
uint16_t RAIL_GetRadioEntropy(RAIL_Handle_t railHandle,
uint8_t *buffer,
uint16_t bytes);
/** @} */ // end of group General
/******************************************************************************
* PTI
*****************************************************************************/
/**
* @addtogroup PTI Packet Trace (PTI)
* @brief Basic APIs to set up and interact with PTI settings
* @{
*/
/**
* Configures PTI pin locations, serial protocols, and baud rates.
*
* @param[in] railHandle A RAIL instance handle (currently not used).
* @param[in] ptiConfig A configuration structure applied to the
* relevant PTI registers.
* @return Status code indicating success of the function call.
*
* This method must be called before RAIL_EnablePti() is called.
* Although we do take a RAIL handle for potential future
* expansion of this function, it is currently not used. That is,
* there is only one PTI configuration that can be active on a
* chip, regardless of the number of protocols (unless the application
* takes responsibility to update the configuration upon a protocol switch),
* and the configuration is not saved in your RAIL instance. For optimal
* future compatibility, pass in a chip specific handle, such as
* \ref RAIL_EFR32_HANDLE for now.
*/
RAIL_Status_t RAIL_ConfigPti(RAIL_Handle_t railHandle,
const RAIL_PtiConfig_t *ptiConfig);
/**
* Gets the currently active PTI configuration.
*
* @param[in] railHandle A RAIL instance handle (currently not used).
* @param[out] ptiConfig A configuration structure filled with the active
* PTI configuration.
* @return RAIL status indicating success of the function call.
*
* Although most combinations of configurations can be set, it is safest
* to call this method after configuration to confirm which values were
* actually set. As in RAIL_ConfigPti, railHandle is not used. This function
* will always return the single active PTI configuration regardless of the
* active protocol. For optimal future compatibility, pass in a chip
* specific handle, such as \ref RAIL_EFR32_HANDLE for now.
*/
RAIL_Status_t RAIL_GetPtiConfig(RAIL_Handle_t railHandle,
RAIL_PtiConfig_t *ptiConfig);
/**
* Enables the PTI output of the packet data.
*
* @param[in] railHandle A RAIL instance handle (currently not used).
* @param[in] enable PTI is enabled if true; disable if false.
* @return RAIL status indicating success of the function call.
*
* Similarly to how there is only one PTI configuration per chip,
* PTI can only be enabled or disabled for all protocols. It cannot
* be individually set to enabled and disabled per protocol
* (unless the application takes the responsibility of switching it when
* the protocol switches), and enable/disable is not saved as part of your
* RAIL instance. For optimal future compatibility, pass in a chip
* specific handle, such as \ref RAIL_EFR32_HANDLE for now.
*/
RAIL_Status_t RAIL_EnablePti(RAIL_Handle_t railHandle,
bool enable);
/**
* Sets a protocol that RAIL outputs on PTI.
*
* @param[in] railHandle A RAIL instance handle.
* @param[in] protocol The enum representing which protocol the node is using.
* @return Status code indicating success of the function call.
*
* The protocol is output via the Packet Trace Interface (PTI) for each packet.
* Before any protocol is set, the default value is \ref
* RAIL_PTI_PROTOCOL_CUSTOM. One of the enum values should be used so that
* the Network Analyzer can decode the packet.
*/
RAIL_Status_t RAIL_SetPtiProtocol(RAIL_Handle_t railHandle,
RAIL_PtiProtocol_t protocol);
/** @} */ // end of group PTI
/******************************************************************************
* Antenna Control
*****************************************************************************/
/**
* @addtogroup Antenna_Control
* @brief Basic APIs to control the Antenna functionality
* @{
*/
/**
* Configures Antenna pin locations
* @param[in] railHandle a RAIL instance handle.
* @param[in] config A configuration structure applied to the relevant Antenna
* Configuration registers.
* @return Status code indicating success of the function call.
*
* Although we do take a RAIL handle for potential future expansion, it is
* currently not used.
*
*/
RAIL_Status_t RAIL_ConfigAntenna(RAIL_Handle_t railHandle,
const RAIL_AntennaConfig_t *config);
/** @} */ // end of group Antenna_Control
/******************************************************************************
* Radio Configuration
*****************************************************************************/
/// @addtogroup Radio_Configuration Radio Configuration
/// @brief Routines for setting up and querying radio configuration information.
///
/// These routines allow for runtime flexibility in the radio
/// configuration. Some of the parameters, however, are meant to be generated
/// from the radio calculator in Simplicity Studio. The basic code to configure
/// the radio from this calculator output looks like the example below.
///
/// @code{.c}
/// // Associate a specific channel config with a particular RAIL instance, and
/// // load the settings that correspond to the first usable channel.
/// RAIL_ConfigChannels(railHandle, channelConfigs[0]);
/// @endcode
///
/// For more information about the types of parameters that can be changed in
/// the other functions and how to use them, see their individual documentation.
///
/// @{
/**
* Loads a static radio configuration.
*
* @param[in] railHandle A RAIL instance handle.
* @param[in] config A pointer to a radio configuration.
* @return Status code indicating success of the function call.
*
* The configuration passed into this function should be generated for you
* and not manually created or edited. By default this function should not be
* called in RAIL 2.x and later unless a non-default radio configuration needs
* to be applied. In RAIL 2.x and later, the RAIL_ConfigChannels function
* applies the default radio configuration automatically.
*/
RAIL_Status_t RAIL_ConfigRadio(RAIL_Handle_t railHandle,
RAIL_RadioConfig_t config);
/**
* Modifies the currently configured fixed frame length in bytes.
*
* @param[in] railHandle A RAIL instance handle.
* @param[in] length The expected fixed frame length. A value of 0 is infinite.
* A value of RAIL_SETFIXEDLENGTH_INVALID restores the frame's length back to
* that length specified by the default frame type configuration.
* @return Length configured; The new frame length configured into the hardware
* for use. 0 if in infinite mode, or RAIL_SETFIXEDLENGTH_INVALID if the frame
* length has not yet been overridden by a valid value.
*
* Sets the fixed-length configuration for transmit and receive.
* Be careful when using this function in receive and transmit as this
* function changes the default frame configuration and remains in force until
* it is called again with an input value of RAIL_SETFIXEDLENGTH_INVALID. This
* function will override any fixed or variable length settings from a radio
* configuration.
*/
uint16_t RAIL_SetFixedLength(RAIL_Handle_t railHandle, uint16_t length);
/**
* Configures the channels supported by this device.
*
* @param[in] railHandle A RAIL instance handle.
* @param[in] config A pointer to the channel configuration for your device.
* This pointer will be cached in the library so it must be something that
* will exist for the runtime of the application. Typically, this should be
* what is stored in Flash by the configuration tool.
* @param[in] cb Function called whenever a radio configuration change occurs.
* @return Returns the first available channel in the configuration.
*
* When configuring channels on the EFR32, the radio tuner is reconfigured
* based on the frequency and channel spacing in the channel configuration.
*/
uint16_t RAIL_ConfigChannels(RAIL_Handle_t railHandle,
const RAIL_ChannelConfig_t *config,
RAIL_RadioConfigChangedCallback_t cb);
/**
* Checks to see if the channel exists in RAIL.
*
* @param[in] railHandle A RAIL instance handle.
* @param[in] channel A channel number to check.
* @return Returns RAIL_STATUS_NO_ERROR if channel exists
*
* Returns RAIL_STATUS_INVALID_PARAMETER if the given channel does not exist
* in the channel configuration currently used, and RAIL_STATUS_NO_ERROR if the
* channel is valid.
*/
RAIL_Status_t RAIL_IsValidChannel(RAIL_Handle_t railHandle,
uint16_t channel);
/**
* Returns the symbol rate for the current PHY.
*
* @param[in] railHandle A RAIL instance handle.
* @return The symbol rate in symbols per second or 0.
*
* The symbol rate is the rate of symbol changes over the air. For non-DSSS
* PHYs, this is the same as the baudrate. For DSSS PHYs, it is the baudrate
* divided by the length of a chipping sequence. For more information,
* see the modem calculator documentation. If the rate is unable to be
* calculated, this function will return 0.
*/
uint32_t RAIL_GetSymbolRate(RAIL_Handle_t railHandle);
/**
* Returns the bit rate for the current PHY.
*
* @param[in] railHandle A RAIL instance handle.
* @return The bit rate in bits per second or 0.
*
* The bit rate is the effective over-the-air data rate. It does not account
* for extra spreading for forward error correction, and so on, but
* accounts for modulation schemes, DSSS, and other configurations. For more
* information, see the modem calculator documentation. If the rate is unable
* to be calculated, this function will return 0.
*/
uint32_t RAIL_GetBitRate(RAIL_Handle_t railHandle);
/**
* Sets the PA capacitor tune value for transmit and receive.
*
* @param[in] railHandle A RAIL instance handle.
* @param[in] txPaCtuneValue PA Ctune value for TX mode.
* @param[in] rxPaCtuneValue PA Ctune value for RX mode.
* @return Status code indicating success of the function call.
*
* Provides the ability to tune the impedance of the transmit
* and receive modes by changing the amount of capacitance at
* the PA output.
*/
RAIL_Status_t RAIL_SetPaCTune(RAIL_Handle_t railHandle,
uint8_t txPaCtuneValue,
uint8_t rxPaCtuneValue);
/** @} */ // end of group Radio_Configuration
/******************************************************************************
* Timing Information
*****************************************************************************/
/**
* @addtogroup System_Timing System Timing
* @brief Functionality related to the RAIL timer and general system time.
*
* These functions can be used to get information about the current system time
* or to manipulate the RAIL timer.
*
* The system time returned by RAIL_GetTime() is in the same timebase that is
* used throughout RAIL. Any callbacks that return a timestamp, such as
* rxPacketReceived() callback, will use this same timebase as will any APIs
* that accept an absolute time for scheduling their action. Throughout this
* documentation the timebase used for this will be referred to as the RAIL
* timebase. This is currently a value in microseconds from chip boot time.
* This means that it will wrap every 1.19 hours.
* (`(2^32 - 1) / (3600 sec/hr * 1000000 us/sec)`).
*
* The provided timer is hardware backed and interrupt driven. It can be used
* for timing any event in your system, but will be especially helpful for
* timing protocol based state machines and other systems that interact with
* the radio. If you do not want to process the expiration in interrupt
* context, leave the timerExpired() callback empty and poll for expiration
* with the RAIL_IsTimerExpired() function.
*
* @{
*/
/**
* Configure the RAIL timer plugin.
*
* @param[in] enable Enables/Disables the RAIL multitimer.
* @return True if the multitimer was successfully enabled/disabled, false
* otherwise.
*
* @note This function must be called before calling \ref RAIL_SetMultiTimer.
* This function must be called to use the timer driver plugin
* with the RAIL single protocol library.
* This function should not be called while the RAIL timer is running.
* Call \ref RAIL_IsTimerRunning before enabling/disabling the multitimer.
* If the multitimer is not needed, do not call this function.
* This will allow the multitimer code to be dead stripped.
*/
bool RAIL_ConfigMultiTimer(bool enable);
/**
* Gets the current RAIL time.
*
* @return Returns the RAIL timebase in microseconds. Note that this wraps
* after around 1.19 hours since it's stored in a 32bit value.
*
* Returns the current time in the RAIL timebase (microseconds). It can be
* used to compare with packet timestamps or to schedule transmits.
*/
RAIL_Time_t RAIL_GetTime(void);
/**
* Sets the current RAIL time.
*
* @param[in] time Set the RAIL timebase to this value in microseconds.
* @return Status code indicating success of the function call.
*
* Sets the current time in the RAIL timebase in microseconds.
*/
RAIL_Status_t RAIL_SetTime(RAIL_Time_t time);
/**
* Schedules a timer to expire using the RAIL timebase.
*
* @param[in] railHandle A RAIL instance handle.
* @param[in] time The timer's expiration time in the RAIL timebase.
* @param[in] mode Indicates whether the time argument is an absolute
* RAIL time or relative to the current RAIL time. Specifying mode
* \ref RAIL_TIME_DISABLED is the same as calling RAIL_CancelTimer().
* @param[in] cb The callback for RAIL to call when the timer expires.
* @return RAIL_STATUS_NO_ERROR on success and
* RAIL_STATUS_INVALID_PARAMETER if the timer could not be scheduled.
*
* Configures a timer to expire after some period in the RAIL timebase.
* This timer can be used to implement low level protocol features.
*
* @warning It is an error to attempt to schedule the timer when it is
* still running from a previous request -- unless the cb callback is
* identical to that used in the previous request, in which case the
* timer is rescheduled to the new time. Note that in this case if
* the original timer expires as it is being rescheduled, the callback
* may or may not occur. It is generally good practice to cancel a
* running timer before rescheduling it to minimize such ambiguity.
*/
RAIL_Status_t RAIL_SetTimer(RAIL_Handle_t railHandle,
RAIL_Time_t time,
RAIL_TimeMode_t mode,
RAIL_TimerCallback_t cb);
/**
* Returns the absolute time that the RAIL timer was configured to expire.
*
* @param[in] railHandle A RAIL instance handle.
* @return The absolute time that this timer was set to expire.
*
* It will give the absolute time regardless of the \ref RAIL_TimeMode_t that
* was passed into \ref RAIL_SetTimer. Note that this time might be in the
* past if the timer already expired. The return value is undefined if the
* timer was never set.
*/
RAIL_Time_t RAIL_GetTimer(RAIL_Handle_t railHandle);
/**
* Stops the currently scheduled RAIL timer.
*
* @param[in] railHandle A RAIL instance handle.
* @return void.
*
* Cancels the timer. If this function is called before the timer expires,
* the cb callback specified in the earlier RAIL_SetTimer() call will never
* be called.
*/
void RAIL_CancelTimer(RAIL_Handle_t railHandle);
/**
* Checks whether the RAIL timer has expired.
*
* @param[in] railHandle A RAIL instance handle.
* @return True if the previously scheduled timer has expired and false
* otherwise.
*
* Polling via this function can be used as an alternative to the callback.
*/
bool RAIL_IsTimerExpired(RAIL_Handle_t railHandle);
/**
* Checks whether the RAIL timer is currently running.
*
* @param[in] railHandle A RAIL instance handle.
* @return Returns true if the timer is running and false if
* the timer has expired or was never set.
*/
bool RAIL_IsTimerRunning(RAIL_Handle_t railHandle);
/**
* Starts a multitimer instance.
*
* @note
* It is legal to start an already running timer. If this is done, the timer
* will first be stopped before the new configurations are applied.
* If expirationTime is 0, the callback will be called
* immediately.
*
* @param[in,out] tmr A pointer to the timer instance to start.
* @param[in] expirationTime When the timer is to expire.
* @param[in] expirationMode Select mode of expirationTime. See \ref
* RAIL_TimeMode_t.
* @param[in] callback Function to call on timer expiry. See \ref
* RAIL_MultiTimerCallback_t. NULL is a legal value.
* @param[in] cbArg Extra callback function parameter for user application.
*
* @return
* \ref RAIL_STATUS_NO_ERROR on success.@n
* \ref RAIL_STATUS_INVALID_PARAMETER if tmr has an illegal value or if
* timeout is in the past.
*/
RAIL_Status_t RAIL_SetMultiTimer(RAIL_MultiTimer_t *tmr,
RAIL_Time_t expirationTime,
RAIL_TimeMode_t expirationMode,
RAIL_MultiTimerCallback_t callback,
void *cbArg);
/**
* Stops the currently scheduled RAIL multi timer.
*
* @param[in,out] tmr A RAIL timer instance handle.
*
* @return
* true if timer was successfully cancelled.
* false if timer was not running.
*
* Cancels the timer. If this function is called before the timer expires,
* the cb callback specified in the earlier RAIL_SetTimer() call will never
* be called.
*/
bool RAIL_CancelMultiTimer(RAIL_MultiTimer_t *tmr);
/**
* Check if a given timer is running.
*
* @param[in] tmr A pointer to the timer structure to query.
*
* @return
* true if timer is running.
* false if timer is not running.
*/
bool RAIL_IsMultiTimerRunning(RAIL_MultiTimer_t *tmr);
/**
* Check if a given timer has expired.
*
* @param[in] tmr A pointer to the timer structure to query.
*
* @return
* true if timer is expired.
* false if timer is running.
*/
bool RAIL_IsMultiTimerExpired(RAIL_MultiTimer_t *tmr);
/**
* Get time left before a given timer instance expires.
*
* @param[in] tmr A pointer to the timer structure to query.
* @param[in] timeMode An indication as to how the function provides the time
* remaining. By choosing \ref
* RAIL_TimeMode_t::RAIL_TIME_ABSOLUTE, the function returns the
* absolute expiration time, and by choosing \ref
* RAIL_TimeMode_t::RAIL_TIME_DELAY, the function returns the
* amount of time remaining before the timer's expiration.
*
* @return
* Time left expressed in RAIL's time units.
* 0 if the soft timer is not running or has already expired.
*/
RAIL_Time_t RAIL_GetMultiTimer(RAIL_MultiTimer_t *tmr,
RAIL_TimeMode_t timeMode);
/**
* Initialize RAIL timer synchronization.
*
* @param[in] railHandle A RAIL instance handle.
* @param[in] sleepConfig A sleep configuration.
*
* @return Status code indicating success of the function call.
*/
RAIL_Status_t RAIL_ConfigSleep(RAIL_Handle_t railHandle,
RAIL_SleepConfig_t sleepConfig);
/**
* Stop the RAIL timer and prepare RAIL for sleep.
*
* @param[in] wakeupProcessTime Time in microseconds that the application and
* hardware need to recover from sleep state.
* @param[out] deepSleepAllowed
* true - system can go to deep sleep.
* false - system should not go to deep sleep. Deep sleep should be blocked
* in this case.
*
* @return Status code indicating success of the function call.
*
* @warning The active RAIL configuration must be idle for enabling sleep.
*/
RAIL_Status_t RAIL_Sleep(uint16_t wakeupProcessTime, bool *deepSleepAllowed);
/**
* Wake RAIL from sleep and restart the RAIL timer.
*
* @param[in] elapsedTime Add the sleep duration to the RAIL timer
* before restarting the RAIL timer.
*
* @return Status code indicating success of the function call.
*
* If timer sync was enabled by \ref RAIL_ConfigSleep, synchronize the RAIL
* timer using an alternate timer. Otherwise, add elapsedTime to the RAIL
* timer.
*/
RAIL_Status_t RAIL_Wake(RAIL_Time_t elapsedTime);
/** @} */ // end of group System_Timing
/******************************************************************************
* Events
*****************************************************************************/
/**
* @addtogroup Events
* @brief APIs related to events
* @{
*/
/**
* Configures radio events.
*
* @param[in] railHandle A RAIL instance handle.
* @param[in] mask Bitmask containing which events should be modified.
* @param[in] events Define which events should trigger \ref RAIL_Config_t::eventsCallback
* The full list of available callbacks can be found by looking at the
* RAIL_EVENT_* set of defines.
* @return Status code indicating success of the function call.
*
* Sets up which radio interrupts generate a RAIL event. The full list of
* options is in \ref RAIL_Events_t.
*/
RAIL_Status_t RAIL_ConfigEvents(RAIL_Handle_t railHandle,
RAIL_Events_t mask,
RAIL_Events_t events);
/** @} */ // end of group Events
/******************************************************************************
* Data Management
*****************************************************************************/
/// @addtogroup Data_Management Data Management
/// @brief Data management functions
///
/// These functions allow the application to choose how data is presented to the
/// application. RAIL provides data in a packet-based method or in a FIFO-based
/// method which gives the application more granularity and responsibility in
/// managing transmit and receive data, and allows packet sizes larger than
/// the RX or TX FIFO buffers.
///
/// The application can configure RAIL data management through
/// RAIL_ConfigData().
/// This function allows the application to specify the type of radio data
/// (\ref RAIL_TxDataSource_t and \ref RAIL_RxDataSource_t) and the method of
/// interacting with data (\ref RAIL_DataMethod_t). By default, RAIL
/// configures TX and RX both with packet data source and packet mode.
///
/// In packet based data management:
/// - Packet lengths are determined from the Radio Configurator configuration
/// or after receive packet completion using RAIL_GetRxPacketInfo().
/// - Load transmit data with RAIL_WriteTxFifo().
/// - Received packet data is made available on successful packet completion
/// via \ref RAIL_Config_t::eventsCallback with \ref RAIL_EVENT_RX_PACKET_RECEIVED
/// which can then use RAIL_GetRxPacketInfo() and RAIL_GetRxPacketDetails() to
/// access packet information, and RAIL_PeekRxPacket() to access packet
/// data.
/// - Filtered, Aborted, or FrameError received packet data is automatically
/// dropped without the application needing to worry about consuming it.
/// The application can choose to not even be bothered with the events
/// related to such packets: \ref RAIL_EVENT_RX_ADDRESS_FILTERED,
/// \ref RAIL_EVENT_RX_PACKET_ABORTED, or \ref RAIL_EVENT_RX_FRAME_ERROR.
///
/// In FIFO based data management:
/// - Packet Lengths are determined from the Radio Configurator configuration
/// or by application knowledge of packet payload structure.
/// - Load transmit data with RAIL_WriteTxFifo() with reset set to false.
/// - Received data can be retrieved prior to packet completion through
/// RAIL_ReadRxFifo(), and is never dropped on Filtered, Aborted, or
/// FrameError packets. The application should enable and handle these
/// events so it can flush any packet data it's already retrieved.
/// - After packet completion, remaining packet data for Filtered, Aborted,
/// or FrameError packets can be either flushed automatically by RAIL
/// or consumed by the application just like a successfully received packet,
/// as determined from RAIL_GetRxPacketInfo(). RAIL_GetRxPacketDetails()
/// provides packet detailed information only for successfully received
/// packets.
/// - Set the TX FIFO threshold through RAIL_SetTxFifoThreshold(). The
/// \ref RAIL_Config_t::eventsCallback with \ref RAIL_EVENT_TX_FIFO_ALMOST_EMPTY
/// will occur telling the application to load more TX packet data, if needed
/// lest a \ref RAIL_EVENT_TX_UNDERFLOW event occurs.
/// - Set the RX FIFO threshold through RAIL_SetRxFifoThreshold(). The
/// \ref RAIL_Config_t::eventsCallback with \ref RAIL_EVENT_RX_FIFO_ALMOST_FULL
/// will occur telling the application to consume some RX packet data lest a
/// \ref RAIL_EVENT_RX_FIFO_OVERFLOW event occurs.
/// - Get RX FIFO count information through
/// RAIL_GetRxPacketInfo(\ref RAIL_RX_PACKET_HANDLE_NEWEST)
/// (or RAIL_GetRxFifoBytesAvailable()).
/// - Get TX FIFO count information through RAIL_GetTxFifoSpaceAvailable().
/// - Reset RX and/or TX FIFOs with RAIL_ResetFifo().
///
/// When trying to determine an appropriate threshold, the application needs
/// to know each FIFO's size. The receive FIFO is internal to RAIL and its
/// size is 512 bytes. The receive FIFO is level-based in that the \ref
/// RAIL_EVENT_RX_FIFO_ALMOST_FULL event will constantly pend if the threshold
/// is exceeded. This normally means that inside this event's callback, the
/// application should
/// empty enough of the FIFO to go under the threshold. To defer reading the
/// FIFO to main context, the application can disable or re-enable the receive
/// FIFO threshold event using RAIL_ConfigEvents() with the mask
/// \ref RAIL_EVENT_RX_FIFO_ALMOST_FULL.
///
/// The transmit FIFO is specified by the application and its actual size is
/// the value returned from the most recent call to RAIL_SetTxFifo(),
/// The transmit FIFO is edge-based in that it only provides the \ref
/// RAIL_EVENT_TX_FIFO_ALMOST_EMPTY event once when the threshold is crossed
/// in the emptying direction.
///
/// In FIFO mode, the FIFOs can store multiple packets. Depending on the
/// traffic, RAIL can receive multiple packets into the receive FIFO before the
/// application gets around to reading out the received data from the FIFO.
/// RAIL_ReadRxFifo() won't allow reading beyond a packet boundary so
/// process packet completion events promptly. Keep in mind that in FIFO mode,
/// packet data already read from packets that are subsequently aborted,
/// frameerror, or filtered should be flushed.
///
/// While RAIL defaults to packet mode, the application can explicitly
/// initialize RAIL for packet mode in the following manner:
/// @code{.c}
/// static const RAIL_DataConfig_t railDataConfig = {
/// .txSource = TX_PACKET_DATA,
/// .rxSource = RX_PACKET_DATA,
/// .txMethod = PACKET_MODE,
/// .rxMethod = PACKET_MODE,
/// };
///
/// status = RAIL_ConfigData(&railDataConfig);
///
/// // Events that can occur in Packet Mode:
/// RAIL_EVENT_TX_PACKET_SENT
/// RAIL_EVENT_RX_PACKET_RECEIVED
/// and optionally (packet data automatically dropped):
/// RAIL_EVENT_RX_ADDRESS_FILTERED
/// RAIL_EVENT_RX_PACKET_ABORTED
/// RAIL_EVENT_RX_FRAME_ERROR
/// @endcode
///
/// Initializing RAIL for FIFO Mode requires a few more function calls:
/// @code{.c}
/// static const RAIL_DataConfig_t railDataConfig = {
/// .txSource = TX_PACKET_DATA,
/// .rxSource = RX_PACKET_DATA,
/// .txMethod = FIFO_MODE,
/// .rxMethod = FIFO_MODE,
/// };
///
/// status = RAIL_ConfigData(&railDataConfig);
///
/// // Gets the size of the FIFOs.
/// // The transmit and receive FIFOs are the same size
/// uint16_t fifoSize = RAIL_GetTxFifoSpaceAvailable();
///
/// // Sets the transmit and receive FIFO thresholds.
/// // For this example, set the threshold in the middle of each FIFO
/// RAIL_SetRxFifoThreshold(fifoSize / 2);
/// RAIL_SetTxFifoThreshold(fifoSize / 2);
///
/// // Events that can occur in FIFO mode:
/// RAIL_EVENT_TX_FIFO_ALMOST_EMPTY
/// RAIL_EVENT_TX_UNDERFLOW
/// RAIL_EVENT_TXACK_UNDERFLOW
/// RAIL_EVENT_TX_PACKET_SENT
/// RAIL_EVENT_RX_FIFO_ALMOST_FULL
/// RAIL_EVENT_RX_FIFO_OVERFLOW
/// RAIL_EVENT_RX_ADDRESS_FILTERED
/// RAIL_EVENT_RX_PACKET_ABORTED
/// RAIL_EVENT_RX_FRAME_ERROR
/// RAIL_EVENT_RX_PACKET_RECEIVED
/// @endcode
///
/// On receive, an application can use multiple data sources that
/// are only compatible with the FIFO method of data delivery. All that differs
/// from the FIFO mode example above is the RAIL_DataConfig_t::rxSource setting.
/// IQ data samples are taken at the hardware's oversample rate and the amount
/// of data can easily overwhelm the CPU processing time. The sample rate
/// depends on the chosen PHY, as determined by the data rate and the decimation
/// chain. It is <b>not</b> recommended to use the IQ data source with sample
/// rates above 300 k samples/second as the CPU might not be able to keep up
/// with the data. Depending on the application and needed CPU bandwidth, slower
/// data rates may be required.
/// @code{.c}
/// // IQ data is provided into the receive FIFO
/// static const RAIL_DataConfig_t railDataConfig = {
/// .txSource = TX_PACKET_DATA,
/// .rxSource = RX_IQDATA_FILTLSB,
/// .txMethod = FIFO_MODE,
/// .rxMethod = FIFO_MODE,
/// };
///
/// // When reading IQ data out of the FIFO, it comes in the following format:
/// //------------------------------------
/// // I[LSB] | I[MSB] | Q[LSB] | Q[MSB] |
/// //------------------------------------
/// @endcode
///
/// @note \ref RAIL_DataConfig_t.txMethod and \ref RAIL_DataConfig_t.rxMethod
/// must have the same \ref RAIL_DataMethod_t configuration.
///
/// @warning Do not call RAIL_ReadRxFifo() function while in
/// \ref RAIL_DataMethod_t::PACKET_MODE.
/// @{
/**
* RAIL data management configuration
*
* @param[in] railHandle A RAIL instance handle.
* @param[in] dataConfig RAIL data configuration structure.
* @return Status code indicating success of the function call.
*
* This function configures how RAIL manages data. The application can
* configure RAIL to receive data in a packet-based or FIFO-based format.
* FIFO mode is necessary to support packets larger than the radio's
* FIFO buffers.
*
* With FIFO mode, the application sets appropriate FIFO thresholds via
* RAIL_SetTxFifoThreshold() and RAIL_SetRxFifoThreshold(), and then
* enables and handles the \ref RAIL_EVENT_TX_FIFO_ALMOST_EMPTY event
* callback (to feed more packet data via RAIL_WriteTxFifo() before the
* FIFO underflows), and the \ref RAIL_EVENT_RX_FIFO_ALMOST_FULL event
* callback (to consume packet data via RAIL_ReadRxFifo() before the
* RX FIFO overflows).
*
* When configuring TX or RX for FIFO mode, this function resets the configured
* FIFOs. When configuring TX or RX for Packet mode, this function will reset
* the corresponding FIFO thresholds such that they won't trigger the
* \ref RAIL_EVENT_RX_FIFO_ALMOST_FULL or \ref RAIL_EVENT_TX_FIFO_ALMOST_EMPTY
* events.
*
* When \ref RAIL_DataConfig_t.rxMethod is set to \ref
* RAIL_DataMethod_t.FIFO_MODE, the radio won't drop packet data of
* aborted or CRC error packets, but will present it to the application
* to deal with accordingly. On completion of such erroneous packets, the
* \ref RAIL_Config_t::eventsCallback with \ref RAIL_EVENT_RX_PACKET_ABORTED,
* \ref RAIL_EVENT_RX_FRAME_ERROR, or \ref RAIL_EVENT_RX_ADDRESS_FILTERED will
* tell the application it can drop any data it read via RAIL_ReadRxFifo() during reception.
* For CRC error packets when the \ref RAIL_RX_OPTION_IGNORE_CRC_ERRORS
* RX option is in effect, the application would check for that from the
* \ref RAIL_RxPacketStatus_t obtained by calling RAIL_GetRxPacketInfo().
* RAIL will automatically flush any remaining packet data after reporting
* one of these packet completion events, or the application can explicitly
* flush it by calling RAIL_ReleaseRxPacket().
*
* When \ref RAIL_DataConfig_t.rxMethod is set to \ref
* RAIL_DataMethod_t.PACKET_MODE, the radio will drop all packet data
* associated with aborted packets including those with CRC errors (unless
* configured to ignore CRC errors via the
* \ref RAIL_RX_OPTION_IGNORE_CRC_ERRORS RX option). The application will
* never be bothered to deal with packet data from such packets.
*
* In either mode, the application can set RX options as needed, and
* packet details are not available for aborted packets.
*/
RAIL_Status_t RAIL_ConfigData(RAIL_Handle_t railHandle,
const RAIL_DataConfig_t *dataConfig);
/**
* Writes data to the transmit FIFO.
*
* @param[in] railHandle A RAIL instance handle.
* @param[in] dataPtr Application provided pointer to transmit data
* @param[in] writeLength Number of bytes to write to the transmit FIFO
* @param[in] reset If true resets TX FIFO before writing the data.
* @return The number of bytes written to the transmit FIFO.
*
* This function reads data from the provided dataPtr and writes it to the TX
* FIFO. If the requested writeLength exceeds the current number of bytes open
* in the transmit FIFO, the function only writes until the transmit FIFO
* is full. The function returns the number of bytes written to the transmit
* FIFO, and returns zero if railHandle is NULL or if the TX FIFO is full.
*
* @note It is the protocol's packet configuration, as set up by the radio
* configurator or via RAIL_SetFixedLength(), that determines how many
* bytes of data are consumed from the TX FIFO for a successful transmit
* operation, not the writeLength value passed in. If not enough data has
* been put into the TX FIFO, a \ref RAIL_EVENT_TX_UNDERFLOW event will
* occur. If too much data, the extra data will either become the first bytes
* sent in a subsequent packet, or will be thrown away if the FIFO gets
* reset prior to the next transmit. In general, the proper number of
* packet bytes to put into the TX FIFO are all payload bytes except for
* any CRC bytes which the packet configuration would cause to be sent
* automatically.
*
* @note This function does not create a critical section but, depending on the
* application, a critical section could be appropriate.
*/
uint16_t RAIL_WriteTxFifo(RAIL_Handle_t railHandle,
const uint8_t *dataPtr,
uint16_t writeLength,
bool reset);
/**
* Set the address of the TX FIFO, a circular buffer used for TX data
*
* @param[in] railHandle A RAIL instance handle.
* @param[in,out] addr Pointer to a read-write memory location in RAM
* used as the TX FIFO. This memory must persist until the next call to
* this function.
* @param[in] initLength Number of initial bytes already in the TX FIFO.
* @param[in] size Desired size of the TX FIFO in bytes.
* @return Returns the FIFO size in bytes that has been set.
*
* This function is used to set the memory location for the TX FIFO. This
* function must be called at least once before any transmit operations occur.
*
* The FIFO size can be determined by the return value of this function. The
* chosen size is determined based on the available FIFO sizes supported by
* the hardware. For more on supported FIFO sizes see chip-specific
* documentation, such as \ref efr32_main. The returned FIFO size will be the
* closest allowed size less than or equal to the passed in size parameter,
* unless the size parameter is smaller than the minimum FIFO size. If the
* initLength parameter is larger than the returned size, than the FIFO will be
* full up to its size.
*
* User may write to the custom memory location directly before calling this
* function, or use \ref RAIL_WriteTxFifo to write to the memory location after
* calling this function. For previously-written memory to be set in the TX
* FIFO, user must specify its initLength.
*
* This function reserves the block of RAM starting at txBufPtr with a length
* of the returned FIFO size. That RAM block is used internally as a circular
* buffer for the transmit FIFO. The FIFO must be able to hold the entire FIFO
* size. The caller must guarantee the custom FIFO remains intact and unchanged
* (except via calls to \ref RAIL_WriteTxFifo) until the next call to this
* function.
*
* @note It is the protocol's packet configuration, as set up by the radio
* configurator or via RAIL_SetFixedLength(), that determines how many
* bytes of data are consumed from the TX FIFO for a successful transmit
* operation, not the initLength value passed in. If not enough data has
* been put into the TX FIFO, a \ref RAIL_EVENT_TX_UNDERFLOW event will
* occur. If too much data, the extra data will either become the first bytes
* sent in a subsequent packet, or will be thrown away if the FIFO gets
* reset prior to the next transmit. In general, the proper number of
* packet bytes to put into the TX FIFO are all payload bytes except for
* any CRC bytes which the packet configuration would cause to be sent
* automatically.
*/
uint16_t RAIL_SetTxFifo(RAIL_Handle_t railHandle,
uint8_t *addr,
uint16_t initLength,
uint16_t size);
/**
* Reads packet data from RAIL's internal receive FIFO buffer.
* This function can be used in any RX mode, though in Packet
* mode it can only be used on the oldest unreleased packet whose
* RAIL_RxPacketStatus_t is among the RAIL_RX_PACKET_READY_ set.
*
* @param[in] railHandle A RAIL instance handle.
* @param[out] dataPtr An application-provided pointer to store data.
* If NULL, the data is thrown away rather than copied out.
* @param[in] readLength A number of packet bytes to read from the FIFO.
* @return The number of packet bytes read from the receive FIFO.
*
* This function reads packet data from the head of receive FIFO and
* writes it to the provided dataPtr. It does not permit reading more
* data than is available in the FIFO, nor does it permit reading more
* data than remains in the oldest unreleased packet.
*
* Because this function does not have a critical section, either use it
* only in one context or make sure function calls are protected to prevent
* buffer corruption.
*
* @note When reading data from an arriving packet that is not yet complete
* keep in mind its data is highly suspect because it has not yet passed
* any CRC integrity checking. Also note the packet could be aborted,
* cancelled, or fail momentarily, invalidating its data in Packet mode.
* Furthermore, there is a small chance towards the end of packet reception
* that the RX FIFO could include not only packet data received so far,
* but also some raw radio-appended info detail bytes that RAIL's
* packet-completion processing will subsequently deal with. It's up to the
* application to know its packet format well enough to avoid reading this
* info as it will corrupt the packet's details and possibly corrupt the
* RX FIFO buffer.
*/
uint16_t RAIL_ReadRxFifo(RAIL_Handle_t railHandle,
uint8_t *dataPtr,
uint16_t readLength);
/**
* Configures the RAIL transmit FIFO almost empty threshold.
*
* @param[in] railHandle A RAIL instance handle.
* @param[in] txThreshold The threshold once fallen under will fire \ref RAIL_Config_t::eventsCallback
* with \ref RAIL_EVENT_TX_FIFO_ALMOST_EMPTY set.
* @return Configured transmit FIFO threshold value.
*
* This function configures the threshold for the transmit FIFO. When the count
* of the transmit FIFO is less than the configured threshold, \ref RAIL_Config_t::eventsCallback
* will fire with \ref RAIL_EVENT_TX_FIFO_ALMOST_EMPTY set. A value of
* 0 is invalid and will not change the current configuration.
*/
uint16_t RAIL_SetTxFifoThreshold(RAIL_Handle_t railHandle,
uint16_t txThreshold);
/**
* Configures the RAIL receive FIFO almost full threshold.
*
* @param[in] railHandle A RAIL instance handle.
* @param[in] rxThreshold The threshold once exceeded will fire \ref RAIL_Config_t::eventsCallback
* with \ref RAIL_EVENT_RX_FIFO_ALMOST_FULL set.
* @return Configured receive FIFO threshold value.
*
* This function configures the threshold for the receive FIFO. When the count
* of the receive FIFO is greater than the configured threshold,
* \ref RAIL_Config_t::eventsCallback will fire with
* \ref RAIL_EVENT_RX_FIFO_ALMOST_FULL set. A value of 0xFFFF is invalid and
* will not change the current configuration. Depending on the size of the
* receive FIFO hardware, the maximum value can vary. If the rxThreshold value
* exceeds the capability of the hardware, the RX threshold will be configured
* so that it fires only when the FIFO is one byte away from being full.
*/
uint16_t RAIL_SetRxFifoThreshold(RAIL_Handle_t railHandle,
uint16_t rxThreshold);
/**
* Gets the RAIL transmit FIFO almost empty threshold value.
*
* @param[in] railHandle A RAIL instance handle.
* @return Configured TX Threshold value.
*
* Retrieves the configured TX threshold value.
*/
uint16_t RAIL_GetTxFifoThreshold(RAIL_Handle_t railHandle);
/**
* Gets the RAIL receive FIFO almost full threshold value.
*
* @param[in] railHandle A RAIL instance handle.
* @return Configured RX Threshold value.
*
* Retrieves the configured RX threshold value.
*/
uint16_t RAIL_GetRxFifoThreshold(RAIL_Handle_t railHandle);
/**
* Resets the RAIL FIFOs.
*
* @param[in] railHandle A RAIL instance handle.
* @param[in] txFifo If true, reset the transmit FIFO.
* @param[in] rxFifo If true, reset the receive FIFO.
* @return void.
*
* This function can reset each FIFO. The application should not reset the RX
* FIFO while receiving a frame.
*/
void RAIL_ResetFifo(RAIL_Handle_t railHandle, bool txFifo, bool rxFifo);
/**
* Get the number of bytes available in the receive FIFO.
* This function should only be used in RX FIFO mode; apps should
* probably be using RAIL_GetRxPacketInfo() instead.
*
* @param[in] railHandle A RAIL instance handle.
* @return Number of raw bytes in the receive FIFO.
*
* @note The number of bytes returned may not just reflect the current
* packet's data but could also include raw appended info bytes added
* after successful packet reception and bytes from subsequently received
* packets. It is up to the app to never try to consume more than the
* packet's actual data when using the value returned here in a subsequent
* call to RAIL_ReadRxFifo(), otherwise the Rx buffer will be corrupted.
*/
uint16_t RAIL_GetRxFifoBytesAvailable(RAIL_Handle_t railHandle);
/**
* Gets the number of bytes open in the transmit FIFO.
*
* @param[in] railHandle A RAIL instance handle.
* @return Number of bytes open in the transmit FIFO.
*
* Gets the number of bytes open in the transmit FIFO.
*/
uint16_t RAIL_GetTxFifoSpaceAvailable(RAIL_Handle_t railHandle);
/** @} */ // end of group Data_Management
/******************************************************************************
* State Transitions
*****************************************************************************/
/**
* @addtogroup State_Transitions State Transitions
* @{
*/
/**
* Configures RAIL automatic state transitions after RX.
*
* @param[in] railHandle A RAIL instance handle.
* @param[in] transitions The state transitions to apply after reception.
* @return Status code indicating success of the function call.
*
* This function fails if unsupported transitions are passed in or if the
* radio is currently in the RX state. Success can transition to TX, RX, or
* IDLE, while error can transition to RX or IDLE.
*/
RAIL_Status_t RAIL_SetRxTransitions(RAIL_Handle_t railHandle,
const RAIL_StateTransitions_t *transitions);
/**
* Configures RAIL automatic state transitions after TX.
*
* @param[in] railHandle A RAIL instance handle.
* @param[in] transitions The state transitions to apply after transmission.
* @return Status code indicating a success of the function call.
*
* This function fails if unsupported transitions are passed in or if the
* radio is currently in the TX state. Success and error can each transition
* to RX or IDLE.
*/
RAIL_Status_t RAIL_SetTxTransitions(RAIL_Handle_t railHandle,
const RAIL_StateTransitions_t *transitions);
/**
* Configures RAIL automatic state transition timing.
*
* @param[in] railHandle A RAIL instance handle.
* @param[in,out] timings The timings used to configure the RAIL state
* machine. This structure is overwritten with the actual times that were
* set, if an input timing is invalid.
* @return Status code indicating a success of the function call.
*
* The timings given are close to the actual transition time. However,
* a still uncharacterized software overhead occurs. Also, timings are not
* always adhered to when using an automatic transition after an error, due to
* the cleanup required to recover from the error.
*/
RAIL_Status_t RAIL_SetStateTiming(RAIL_Handle_t railHandle,
RAIL_StateTiming_t *timings);
/**
* Places the radio into an idle state.
*
* @param[in] railHandle A RAIL instance handle.
* @param[in] mode The method for shutting down the radio.
* @param[in] wait Whether this function should wait for the radio to reach
* idle before returning.
* @return void.
*
* This function is used to remove the radio from TX and RX states. How these
* states are left is defined by the mode parameter.
*
* In multiprotocol, this API will also cause the radio to be yielded so that
* other tasks can be run. See \ref rail_radio_scheduler_yield for more details.
*/
void RAIL_Idle(RAIL_Handle_t railHandle,
RAIL_IdleMode_t mode,
bool wait);
/**
* Gets the current radio state.
*
* @param[in] railHandle A RAIL instance handle.
* @return An enumeration for the current radio state.
*
* Returns the state of the radio as a bitmask containing:
* \ref RAIL_RF_STATE_IDLE, \ref RAIL_RF_STATE_RX, \ref RAIL_RF_STATE_TX,
* and \ref RAIL_RF_STATE_ACTIVE. \ref RAIL_RF_STATE_IDLE, \ref
* RAIL_RF_STATE_RX, and \ref RAIL_RF_STATE_TX bits are mutually exclusive.
* The radio can transition through intermediate states,
* which are not reported but are instead bucketed into the state
* being transitioned into. For example, when the transmitter is in the
* process of shutting down, this function will return TX, as if the
* shutdown process hadn't started yet.
*/
RAIL_RadioState_t RAIL_GetRadioState(RAIL_Handle_t railHandle);
/** @} */ // end of group State_Transitions
/******************************************************************************
* Transmit
*****************************************************************************/
/**
* @addtogroup Transmit
* @brief APIs related to transmitting data packets
* @{
*/
/// @addtogroup PA Power Amplifier (PA)
/// @brief APIs for interacting with one of the on chip PAs.
///
/// These APIs let you configure the on chip PA to get the appropriate output
/// power.
///
/// There a few types of functions that are found here
/// 1) Configuration functions: These functions set and get configuration
/// for the PA. In this case, "configuration" refers to a) indicating
/// which PA to use, b) the voltage supplied by your board to the PA,
/// and c) the ramp time over which to ramp the PA up to its full
/// power.
/// 2) Power-setting functions: These functions consume the actual
/// values written to the PA registers, and write them appropriately.
/// These values are referred to as "(raw) power levels". The range of
/// acceptable values for these functions depends on which PA is
/// currently active. The higher the power level set, the higher
/// the dBm power actually output by the chip. However, the mapping
/// between dBm and these power levels can vary greatly between
/// modules/boards.
/// 3) Conversion functions: These functions do the work of converting
/// between the "power levels" discussed previously and the actual
/// dBm values output by the chip. Continue reading for more details
/// on how to handle unit conversion.
///
/// The accuracy of the chip output power in dBm will vary from application to
/// to application. For some protocols or channels the protocol itself or
/// legal limitations will require applications to know exactly what power
/// they're transmitting at, in dBm. Other applications will not have
/// these restrictions, and users will simply find some power level(s)
/// that fit their criteria for the trade-off between radio range and
/// power savings, regardless of what dBm power that maps to.
///
/// In order to provide a solution that fits all these applications,
/// Silicon Labs has provided a great deal of flexibility in
/// \ref RAIL_ConvertRawToDbm and \ref RAIL_ConvertDbmToRaw, the two functions
/// that do the conversion between the dBm power and the raw power levels.
/// Those levels of customizability are outlined below
/// 1) No customizability needed: for a given dBm value, the result
/// of RAIL_ConvertDbmToRaw provides an appropriate
/// raw power level that, when written to the registers via
/// RAIL_SetPowerLevel, causes the chip to actually output at that
/// dBm power. In this case, no action is needed by the user,
/// the WEAK versions of the conversion functions can be used,
/// and the default include paths in pa_conversions_efr32.h can
/// be used.
/// 2) The mapping of power level to dBm is not good, but the
/// level of precision is sufficient: In pa_conversions_efr32.c
/// the WEAK versions of the conversion functions work by using
/// 8-segment piecewise linear curves to convert between dBm
/// and power levels for PA's with hundreds of power levels
/// and simple mapping tables for use with PA's with only a few
/// levels. If this method is sufficiently precise, but the mapping
/// between power levels and dBm is wrong, Silicon Labs recommends
/// copying pa_curves_efr32.h into a new file, updating the segments
/// to form a better fit (_DCDC_CURVES or _VBAT_CURVES defines), and
/// then adding the RAIL_PA_CURVES define to your build with the path
/// to the new file.
/// 3) A different level of precision is needed and the fit is bad:
/// If the piecewise-linear line segment fit is not appropriate for
/// your solution, the functions in pa_conversions_efr32.c can be
/// totally rewritten, as long as RAIL_ConvertDbmToRaw and
/// RAIL_ConvertRawToDbm have the same signatures. It is completely
/// acceptable to re-write these in a way that makes the
/// pa_curves_efr32.h and pa_curve_types_efr32.h files referenced in
/// pa_conversions_efr32.h unnecessary. Those files are needed solely
/// for the conversion methods that Silicon Labs provides.
/// 4) dBm values are not necessary: If your application does not require
/// dBm values at all, Silicon Labs recommends overwriting
/// RAIL_ConvertDbmToRaw and RAIL_ConvertRawToDbm with smaller functions
/// (i.e. return 0 or whatever was input). These functions are called
/// from within the RAIL library, so they can never be deadstripped,
/// but making them as small as possible is the best way to reduce code
/// size. From there, you can simply call RAIL_SetTxPower, without
/// converting from a dBm value. If you never want the library to coerce the
/// power based on channels, RAIL_ConvertRawToDbm should be overwritten
/// to always return 0 and RAIL_ConvertDbmToRaw should be overwritten to
/// always return 255.
///
/// The following is example code on how to initialize your PA
/// @code{.c}
///
/// #include "pa_conversions_efr32.h"
///
/// // Helper macro to declare all the curve structures used by the Silicon Labs-provided
/// // conversion functions
/// RAIL_DECLARE_TX_POWER_VBAT_CURVES(piecewiseSegments, curvesSg, curves24Hp, curves24Lp);
///
/// // Put the variables declared above into the appropriate structure
/// RAIL_TxPowerCurvesConfig_t txPowerCurvesConfig = { curves24Hp, curvesSg, curves24Lp, piecewiseSegments };
///
/// // In the Silicon Labs implementation, the user is required to save those curves into
/// // to be referenced when the conversion functions are called
/// RAIL_InitTxPowerCurves(&txPowerCurvesConfig);
///
/// // Declare the structure used to configure the PA
/// RAIL_TxPowerConfig_t txPowerConfig = { RAIL_TX_POWER_MODE_2P4_HP, 3300, 10 };
///
/// // And then init the PA. Here, it is assumed that 'railHandle' is a valid RAIL_Handle_t
/// // that has already been initialized.
/// RAIL_ConfigTxPower(railHandle, &txPowerConfig);
///
/// // Pick a dBm power to use: 100 deci-dBm = 10 dBm. See docs on RAIL_TxPower_t
/// RAIL_TxPower_t power = 100;
///
/// // Get the config written by RAIL_ConfigTxPower to confirm what was actually set
/// RAIL_GetTxPowerConfig(railHandle, &txPowerConfig);
///
/// // RAIL_ConvertDbmToRaw will be the weak version provided by Silicon Labs
/// // by default, or the customer version, if overwritten.
/// RAIL_TxPowerLevel_t powerLevel = RAIL_ConvertDbmToRaw(railHandle,
/// txPowerConfig.mode,
/// power);
///
/// // Write the result of the conversion to the PA power registers in terms
/// // of raw power levels
/// RAIL_SetTxPower(railHandle, powerLevel);
/// @endcode
///
/// @note: all the lines following "RAIL_TxPower_t power = 100;" can be
/// replaced with the provided utility function, \ref RAIL_SetTxPowerDbm.
/// However, the full example here was provided for clarity. See the
/// documentation on \ref RAIL_SetTxPowerDbm for more details.
///
/// @{
/**
* Initialize TxPower Settings
*
* @param[in] railHandle A RAIL instance handle.
* @param[in] config Instance which contains desired initial settings
* for the TX amplifier.
* @return RAIL_Status_t indicating success or an error.
*
* These settings include the selection between the multiple TX amplifiers,
* voltage supplied to the TX power amplifier, and ramp times. This must
* be called before any transmit occurs, or \ref RAIL_SetTxPower is called.
* While we recommend always calling this function during initialization,
* it can also be called anytime if these settings need to change to adapt
* to a different application/protocol. This API will also reset TX Power to
* its minimum value, so \ref RAIL_SetTxPower must be called after calling this.
*
* At times, certain combinations of configurations cannot be achieved.
* This API attempts to get as close as possible to the requested settings. The
* following "RAIL_Get..." API can be used to determine what values were set.
*/
RAIL_Status_t RAIL_ConfigTxPower(RAIL_Handle_t railHandle,
const RAIL_TxPowerConfig_t *config);
/**
* Get the TX power settings currently used in the amplifier
*
* @param[in] railHandle A RAIL instance handle.
* @param[out] config Pointer to memory allocated to hold current TxPower
* configuration structure.
* @return RAIL_TxPowerConfig_t RAIL status variable indicating whether
* or not the get was successful.
*
* Note, this API does not return the current TX power - that is separately
* managed by the \ref RAIL_GetTxPower/\ref RAIL_SetTxPower API's. This API
* should be used to know exactly which values were set as a result of
* \ref RAIL_ConfigTxPower.
*/
RAIL_Status_t RAIL_GetTxPowerConfig(RAIL_Handle_t railHandle,
RAIL_TxPowerConfig_t *config);
/**
* Set the TX power in units of raw units (see \ref rail_chip_specific.h for
* value ranges).
*
* @param[in] railHandle A RAIL instance handle.
* @param[in] powerLevel Power in chip specific \ref RAIL_TxPowerLevel_t units.
* @return RAIL_Status_t indicating success or an error.
*
* In order to convert between decibels and the integer values that the
* registers take, call \ref RAIL_ConvertDbmToRaw. Silicon Labs provides
* a weak version of this function which works well with our boards. However
* a customer using his/her own custom board will want to characterize
* chip operation on that board and override the function to do the conversion
* appropriately from the desired dB values to raw integer values.
*
* Depending on the configuration used in \ref RAIL_ConfigTxPower, not all
* power levels are achievable. This API will get as close as possible to
* the desired power without exceeding it, and calling \ref RAIL_GetTxPower is
* the only way to know the exact value written.
*
* Calling this function before configuring the PA (i.e. before a successful
* call to \ref RAIL_ConfigTxPower) will cause an error to be returned.
*/
RAIL_Status_t RAIL_SetTxPower(RAIL_Handle_t railHandle,
RAIL_TxPowerLevel_t powerLevel);
/**
* Returns the current power setting of the PA.
*
* @param[in] railHandle A RAIL instance handle.
* @return The chip specific \ref RAIL_TxPowerLevel_t value of the current
* transmit power.
*
* This API returns the raw value that was actually set by \ref RAIL_SetTxPower.
* Silicon Labs provides a weak version of \ref RAIL_ConvertRawToDbm that works
* with our boards to convert these raw values into actual output dBm values.
* However, if a customer is using a custom board, we recommend that he/she re-
* characterizes the relationship between raw and decibel values, and overrides
* the provided function with one more that more accurately reflects the actual
* relationship.
*
* Calling this function before configuring the PA (i.e. before a successful
* call to \ref RAIL_ConfigTxPower) will cause an error to be returned
* (RAIL_TX_POWER_LEVEL_INVALID).
*/
RAIL_TxPowerLevel_t RAIL_GetTxPower(RAIL_Handle_t railHandle);
/**
* Converts raw values written to registers to decibel value (in units of
* deci-dBm).
*
* @param[in] railHandle A RAIL instance handle.
* @param[in] mode PA mode for which to do the conversion.
* @param[in] powerLevel Raw amplifier register value to be converted to
* deci-dBm.
* @return raw amplifier values converted to units of deci-dBm.
*
* A weak version of this function is provided by Silicon Labs that is tuned
* to provide accurate values for our boards. If the customer intends to use
* a custom board, the relationship between what is written to the Tx amplifier
* and the actual output power should be re-characterized and implemented in an
* overriding version of \ref RAIL_ConvertRawToDbm. For minimum code size and
* best speed use only raw values with the TxPower API and override this
* function with a smaller function. In the weak version provided with the RAIL
* library, railHandle is only used to indicate to the user from where the
* function was called, so it is OK to use either a real protocol handle, or one
* of the chip specific ones, such as \ref RAIL_EFR32_HANDLE.
*
* Although the definitions of this function may change, the signature
* must be as declared here.
*/
RAIL_TxPower_t RAIL_ConvertRawToDbm(RAIL_Handle_t railHandle,
RAIL_TxPowerMode_t mode,
RAIL_TxPowerLevel_t powerLevel);
/**
* Converts the desired decibel value (in units of deci-dBm)
* to raw integer values used by the TX amplifier registers.
*
* @param[in] railHandle A RAIL instance handle.
* @param[in] mode PA mode for which to do the conversion.
* @param[in] power Desired dBm values in units of deci-dBm.
* @return deci-dBm value converted to a raw
* integer value that can be used directly with \ref RAIL_SetTxPower.
*
* A weak version of this function is provided by Silicon Labs that is tuned
* to provide accurate values for our boards. If the customer intends to use
* a custom board, the relationship between what is written to the TX amplifier
* and the actual output power should be characterized and implemented in an
* overriding version of \ref RAIL_ConvertDbmToRaw. For minimum code size and
* best speed use only raw values with the TxPower API and override this
* function with a smaller function. In the weak version provided with the RAIL
* library, railHandle is only used to indicate to the user from where the
* function was called, so it is OK to use either a real protocol handle, or one
* of the chip specific ones, such as \ref RAIL_EFR32_HANDLE.
*
* Although the definitions of this function may change, the signature
* must be as declared here.
*
* @note This function is called from within the RAIL library for
* comparison between channel limitations and current power. It will
* throw an assert if you haven't called RAIL_InitTxPowerCurves
* which initializes the mappings between raw power levels and
* actual dBm powers. To avoid this assert, ensure that the
* maxPower of all channel config entries is \ref RAIL_TX_POWER_MAX
* or above, or override this function to always return 255.
*/
RAIL_TxPowerLevel_t RAIL_ConvertDbmToRaw(RAIL_Handle_t railHandle,
RAIL_TxPowerMode_t mode,
RAIL_TxPower_t power);
/** @} */ // end of group PA
/// Sets the TX power in terms of deci-dBm instead of raw power level.
///
/// @param[in] railHandle A RAIL instance handle.
/// @param[in] power Desired deci-dBm power to be set.
/// @return RAIL Status variable indicate whether setting the
/// power was successful.
///
/// This is a utility function crafted for user convenience. Normally, to set TX
/// power in dBm, the user would have to do the following:
///
/// @code{.c}
/// RAIL_TxPower_t power = 100; // 100 deci-dBm, 10 dBm
/// RAIL_TxPowerConfig_t txPowerConfig;
/// RAIL_GetTxPowerConfig(railHandle, &txPowerConfig);
/// // RAIL_ConvertDbmToRaw will be the weak version provided by Silicon Labs
/// // by default, or the customer version, if overwritten.
/// RAIL_TxPowerLevel_t powerLevel = RAIL_ConvertDbmToRaw(railHandle,
/// txPowerConfig.mode,
/// power);
/// RAIL_SetTxPower(railHandle, powerLevel);
/// @endcode
///
/// This function wraps all those calls in a single function with power passed in
/// as a parameter.
///
RAIL_Status_t RAIL_SetTxPowerDbm(RAIL_Handle_t railHandle,
RAIL_TxPower_t power);
/// Gets the TX power in terms of deci-dBm instead of raw power level.
///
/// @param[in] railHandle A RAIL instance handle.
/// @return The current output power in deci-dBm
///
/// This is a utility function crafted for user convenience. Normally, to get TX
/// power in dBm, the user would have to do the following:
///
/// @code{.c}
/// RAIL_TxPowerLevel_t powerLevel = RAIL_GetTxPower(railHandle);
/// RAIL_TxPowerConfig_t txPowerConfig;
/// RAIL_GetTxPowerConfig(railHandle, &txPowerConfig);
/// // RAIL_ConvertRawToDbm will be the weak version provided by Silicon Labs
/// // by default, or the customer version, if overwritten.
/// RAIL_TxPower_t power = RAIL_ConvertRawToDbm(railHandle,
/// txPowerConfig.mode,
/// power);
/// return power;
/// @endcode
///
/// This function wraps all those calls in a single function with power returned
/// as the result.
///
RAIL_TxPower_t RAIL_GetTxPowerDbm(RAIL_Handle_t railHandle);
/**
* Start a non-blocking transmit
*
* @param[in] railHandle A RAIL instance handle.
* @param[in] channel Define the channel to transmit on.
* @param[in] options TX options to be applied to this transmit only.
* @param[in] schedulerInfo Information to allow the radio scheduler to place
* this transmit appropriately. This is only used in multiprotocol version of
* RAIL and may be set to NULL in all other versions.
* @return Status code indicating success of the function call. If successfully
* initiated, transmit completion or failure will be reported by a later
* \ref RAIL_Config_t::eventsCallback with the appropriate \ref RAIL_Events_t.
*
* Will begin transmission of the payload previously loaded via
* \ref RAIL_WriteTxFifo() immediately, or right after a packet currently being
* received is completed.
*
* Returns an error if a previous transmit is still in progress.
* If changing channels, any ongoing packet reception is aborted.
*
* In multiprotocol you must ensure that you properly yield the radio after this
* operation completes. See \ref rail_radio_scheduler_yield for more details.
*/
RAIL_Status_t RAIL_StartTx(RAIL_Handle_t railHandle,
uint16_t channel,
RAIL_TxOptions_t options,
const RAIL_SchedulerInfo_t *schedulerInfo);
/**
* Send a packet on a schedule, instead of immediately
*
* @param[in] railHandle A RAIL instance handle.
* @param[in] channel Define the channel to transmit on.
* @param[in] options TX options to be applied to this transmit only.
* @param[in] config A pointer to the \ref RAIL_ScheduleTxConfig_t
* structure containing when the transmit should occur.
* @param[in] schedulerInfo Information to allow the radio scheduler to place
* this transmit appropriately. This is only used in multiprotocol version of
* RAIL and may be set to NULL in all other versions.
* @return Status code indicating success of the function call. If successfully
* initiated, a transmit completion or failure will be reported by a later
* \ref RAIL_Config_t::eventsCallback with the appropriate \ref RAIL_Events_t.
*
* Will begin transmission of the payload previously loaded via
* \ref RAIL_WriteTxFifo() at the scheduled time.
* The time (in microseconds) as well as whether that time is absolute or
* relative, is specified using the \ref RAIL_ScheduleTxConfig_t structure.
* Also specified in this structure is what to do if a scheduled transmit
* fires in the midst of receiving a packet.
*
* Returns an error if a previous transmit is still in progress.
* If changing channels, any ongoing packet reception is aborted.
*
* In multiprotocol you must ensure that you properly yield the radio after this
* operation completes. See \ref rail_radio_scheduler_yield for more details.
*/
RAIL_Status_t RAIL_StartScheduledTx(RAIL_Handle_t railHandle,
uint16_t channel,
RAIL_TxOptions_t options,
const RAIL_ScheduleTxConfig_t *config,
const RAIL_SchedulerInfo_t *schedulerInfo);
/**
* Start a non-blocking Transmit using CSMA
*
* @param[in] railHandle A RAIL instance handle.
* @param[in] channel Define the channel to transmit on.
* @param[in] options TX options to be applied to this transmit only.
* @param[in] csmaConfig A pointer to the RAIL_CsmaConfig_t structure
* describing the CSMA parameters to use for this transmit.
* @param[in] schedulerInfo Information to allow the radio scheduler to place
* this transmit appropriately. This is only used in multiprotocol version of
* RAIL and may be set to NULL in all other versions.
* @return Status code indicating success of the function call. If successfully
* initiated, a transmit completion or failure will be reported by a later
* \ref RAIL_Config_t::eventsCallback with the appropriate \ref RAIL_Events_t.
*
* First performs the Carrier Sense Multiple Access (CSMA) algorithm and if
* the channel is deemed clear (RSSI below the specified threshold) it will
* commence transmission of the payload previously loaded via
* RAIL_WriteTxFifo().
* Packets can be received during CSMA backoff periods if receive is active
* throughout the CSMA process. This will happen either by starting the CSMA
* process while receive is already active, or if the csmaBackoff time in
* the \ref RAIL_CsmaConfig_t is less than the idleToRx time (set by
* RAIL_SetStateTiming()). If the csmaBackoff time is greater than the
* idleToRx time, then receive will only be active during CSMA's clear channel
* assessments.
*
* If the CSMA algorithm deems the channel busy, the \ref RAIL_Config_t::eventsCallback
* occurs with \ref RAIL_EVENT_TX_CHANNEL_BUSY, and the contents
* of the TX FIFO remain intact, untouched.
*
* Returns an error if a previous transmit is still in progress.
* If changing channels, any ongoing packet reception is aborted.
*
* In multiprotocol you must ensure that you properly yield the radio after this
* operation completes. See \ref rail_radio_scheduler_yield for more details.
*/
RAIL_Status_t RAIL_StartCcaCsmaTx(RAIL_Handle_t railHandle,
uint16_t channel,
RAIL_TxOptions_t options,
const RAIL_CsmaConfig_t *csmaConfig,
const RAIL_SchedulerInfo_t *schedulerInfo);
/**
* Start a non-blocking Transmit using LBT
*
* @param[in] railHandle A RAIL instance handle.
* @param[in] channel Define the channel to transmit on.
* @param[in] options TX options to be applied to this transmit only.
* @param[in] lbtConfig A pointer to the RAIL_LbtConfig_t structure
* describing the LBT parameters to use for this transmit.
* @param[in] schedulerInfo Information to allow the radio scheduler to place
* this transmit appropriately. This is only used in multiprotocol version of
* RAIL and may be set to NULL in all other versions.
* @return Status code indicating success of the function call. If successfully
* initiated, a transmit completion or failure will be reported by a later
* \ref RAIL_Config_t::eventsCallback with the appropriate \ref RAIL_Events_t.
*
* First performs the Listen Before Talk (LBT) algorithm and if the channel
* is deemed clear (RSSI below the specified threshold) it will commence
* transmission of the payload previously loaded via RAIL_WriteTxFifo().
* Packets can be received during LBT backoff periods if receive is active
* throughout the LBT process. This will happen either by starting the LBT
* process while receive is already active, or if the lbtBackoff time in
* the \ref RAIL_LbtConfig_t is less than the idleToRx time (set by
* RAIL_SetStateTiming()). If the lbtBackoff time is greater than the
* idleToRx time, then receive will only be active during LBT's clear channel
* assessments.
*
* If the LBT algorithm deems the channel busy, the \ref RAIL_Config_t::eventsCallback occurs with
* \ref RAIL_EVENT_TX_CHANNEL_BUSY, and the contents
* of the TX FIFO remain intact, untouched.
*
* Returns an error if a previous transmit is still in progress.
* If changing channels, any ongoing packet reception is aborted.
*
* In multiprotocol you must ensure that you properly yield the radio after this
* operation completes. See \ref rail_radio_scheduler_yield for more details.
*/
RAIL_Status_t RAIL_StartCcaLbtTx(RAIL_Handle_t railHandle,
uint16_t channel,
RAIL_TxOptions_t options,
const RAIL_LbtConfig_t *lbtConfig,
const RAIL_SchedulerInfo_t *schedulerInfo);
/**
* Sets the CCA threshold in dBm
*
* @param[in] railHandle A RAIL instance handle.
* @param[in] ccaThresholdDbm The CCA threshold in dBm.
* @return Status code indicating success of the function call.
*
* Unlike RAIL_StartCcaCsmaTx() or RAIL_StartCcaLbtTx(), which can cause a
* transmit, this function only modifies the CCA threshold. A possible
* use case for this function is to set the CCA threshold to invalid RSSI
* of -128 which blocks transmission by preventing clear channel assessments
* from succeeding.
*/
RAIL_Status_t RAIL_SetCcaThreshold(RAIL_Handle_t railHandle,
int8_t ccaThresholdDbm);
/**
* Gets detailed information about the last packet transmitted.
*
* @param[in] railHandle A RAIL instance handle.
* @param[in,out] pPacketDetails An application-provided pointer to store
* RAIL_TxPacketDetails_t corresponding to the transmit event.
* The isAck and timeSent fields totalPacketBytes and timePosition
* must be initialized prior to each call:
* - isAck true to obtain details about the most recent ACK transmit,
* false to obtain details about the most recent app-initiated transmit.
* - totalPacketBytes with the total number of bytes of the transmitted
* packet for RAIL to use when calculating the specified timestamp.
* This should account for all bytes sent over the air after the
* Preamble and Sync word(s), including CRC bytes.
* - timePosition with a \ref RAIL_PacketTimePosition_t value specifying
* the packet position to put in the timeSent field on return.
* This field will also be updated with the actual position corresponding
* to the timeSent value filled in.
* @return \ref RAIL_STATUS_NO_ERROR if pPacketDetails was filled in,
* or an appropriate error code otherwise.
*
* This function can only be called from callback context for either
* \ref RAIL_EVENT_TX_PACKET_SENT or \ref RAIL_EVENT_TXACK_PACKET_SENT
* events.
*/
RAIL_Status_t RAIL_GetTxPacketDetails(RAIL_Handle_t railHandle,
RAIL_TxPacketDetails_t *pPacketDetails);
/**
* Prevent the radio from starting a transmit.
*
* @param[in] railHandle A RAIL instance handle.
* @param[in] enable Enable/Disable TX hold off.
* @return void.
*
* Enable TX hold off to prevent the radio from starting any transmits.
* Disable TX hold off to allow the radio to transmit again.
* Attempting to transmit with the TX hold off enabled will result in
* \ref RAIL_EVENT_TX_BLOCKED and/or \ref RAIL_EVENT_TXACK_BLOCKED
* events.
*
* @note This function does not affect a transmit that has already started.
* To stop an already-started transmission, use RAIL_Idle() with
* \ref RAIL_IDLE_ABORT.
*/
void RAIL_EnableTxHoldOff(RAIL_Handle_t railHandle, bool enable);
/**
* Check whether or not TX hold off is enabled.
*
* @param[in] railHandle A RAIL instance handle.
* @return Returns true if TX hold off is enabled, false otherwise.
*
* TX hold off can be enabled/disabled using \ref RAIL_EnableTxHoldOff.
* Attempting to transmit with the TX hold off enabled will block the
* transmission and result in \ref RAIL_EVENT_TX_BLOCKED
* and/or \ref RAIL_EVENT_TXACK_BLOCKED events.
*/
bool RAIL_IsTxHoldOffEnabled(RAIL_Handle_t railHandle);
/** @} */ // end of group Transmit
/******************************************************************************
* Receive
*****************************************************************************/
/**
* @addtogroup Receive
* @brief APIs related to packet receive
* @{
*/
/**
* Configures receive options.
*
* @param[in] railHandle A RAIL instance handle.
* @param[in] mask A bitmask containing which options should be modified.
* @param[in] options A bitmask containing desired configuration settings.
* Bit positions for each option are found in the \ref RAIL_RxOptions_t.
* @return Status code indicating success of the function call.
*
* Configures the radio receive flow based on the list of available options.
* Only the options indicated by the mask parameter will be affected. Pass
* \ref RAIL_RX_OPTIONS_ALL to set all parameters.
* The previous settings may affect the current frame if a packet is
* received during this configuration.
*/
RAIL_Status_t RAIL_ConfigRxOptions(RAIL_Handle_t railHandle,
RAIL_RxOptions_t mask,
RAIL_RxOptions_t options);
/**
* Start the receiver on a specific channel.
*
* @param[in] railHandle A RAIL instance handle.
* @param[in] channel The channel to listen on.
* @param[in] schedulerInfo Information to allow the radio scheduler to place
* this receive appropriately. This is only used in multiprotocol version of
* RAIL and may be set to NULL in all other versions.
* @return Status code indicating success of the function call.
*
* This is a non-blocking function. Whenever a packet is received \ref RAIL_Config_t::eventsCallback
* will fire with \ref RAIL_EVENT_RX_PACKET_RECEIVED set. If you call
* this while not idle but with a different channel we will abort any ongoing
* receive or transmit operation.
*/
RAIL_Status_t RAIL_StartRx(RAIL_Handle_t railHandle,
uint16_t channel,
const RAIL_SchedulerInfo_t *schedulerInfo);
/**
* Schedules a receive window for some future time.
*
* @param[in] railHandle A RAIL instance handle.
* @param[in] channel A channel to listen on.
* @param[in] cfg The configuration structure to define the receive window.
* @param[in] schedulerInfo Information to allow the radio scheduler to place
* this receive appropriately. This is only used in multiprotocol version of
* RAIL and may be set to NULL in all other versions.
* @return Status code indicating success of the function call.
*
* This API immediately changes the channel and schedules receive to start
* at the specified time and end at the given end time. If you do not specify
* an end time, you may call this API later with an end time as long as you set
* the start time to disabled. You can also terminate the receive
* operation immediately using the RAIL_Idle() function. Note that relative
* end times are always relative to the start unless no start time is
* specified. If changing channels, aborts any ongoing packet transmission or
* reception.
*
* In multiprotocol you must ensure that you properly yield the radio after this
* call. See \ref rail_radio_scheduler_yield for more details.
*/
RAIL_Status_t RAIL_ScheduleRx(RAIL_Handle_t railHandle,
uint16_t channel,
const RAIL_ScheduleRxConfig_t *cfg,
const RAIL_SchedulerInfo_t *schedulerInfo);
/**
* Get basic information about a pending or received packet.
* This function can be used in any RX mode; it does not free up any
* internal resources.
*
* @param[in] railHandle A RAIL instance handle.
* @param[in] packetHandle A packet handle for the unreleased packet as
* returned from a previous call, or sentinel values
* \ref RAIL_RX_PACKET_HANDLE_OLDEST or \ref RAIL_RX_PACKET_HANDLE_NEWEST.
* @param[out] pPacketInfo An application-provided pointer to store
* \ref RAIL_RxPacketInfo_t for the requested packet.
* @return The packet handle for the requested packet:
* if packetHandle was one of the sentinel values, returns the actual
* packet handle for that packet, otherwise returns packetHandle.
* It may return \ref RAIL_RX_PACKET_HANDLE_INVALID to indicate an error.
*
* @note When getting info about an arriving packet that is not yet complete
* (i.e. pPacketInfo->packetStatus == \ref RAIL_RX_PACKET_RECEIVING), keep
* in mind its data is highly suspect because it has not yet passed any CRC
* integrity checking. Also note the packet could be aborted, cancelled, or
* fail momentarily, invalidating its data in Packet mode. Furthermore, there
* is a small chance towards the end of packet reception that the filled-in
* RAIL_RxPacketInfo_t could include not only packet data received so far,
* but also some raw radio-appended info detail bytes that RAIL's
* packet-completion processing will subsequently deal with. It's up to the
* application to know its packet format well enough to avoid confusing such
* info as packet data.
*/
RAIL_RxPacketHandle_t RAIL_GetRxPacketInfo(RAIL_Handle_t railHandle,
RAIL_RxPacketHandle_t packetHandle,
RAIL_RxPacketInfo_t *pPacketInfo);
/**
* Convenience helper function to copy a full packet to a user-specified
* contiguous buffer.
*
* @param[out] pDest An application-provided pointer to a buffer of at
* least pPacketInfo->packetBytes in size to store the packet data
* contiguously. This buffer must never overlay RAIL's Rx FIFO buffer.
* Exactly pPacketInfo->packetBytes of packet data will be written into it.
* @param[out] pPacketInfo
* \ref RAIL_RxPacketInfo_t for the requested packet.
* @return void.
*
* @note This helper is intended to be expedient -- it does not check the
* validity of its arguments, so don't pass either as NULL, and don't
* pass a pDest pointer to a buffer that's too small for the packet's data.
* @note If only a portion of the packet is needed, use RAIL_PeekRxPacket()
* instead.
*/
static inline
void RAIL_CopyRxPacket(uint8_t *pDest,
const RAIL_RxPacketInfo_t *pPacketInfo)
{
memcpy(pDest, pPacketInfo->firstPortionData, pPacketInfo->firstPortionBytes);
if (pPacketInfo->lastPortionData != NULL) {
memcpy(pDest + pPacketInfo->firstPortionBytes,
pPacketInfo->lastPortionData,
pPacketInfo->packetBytes - pPacketInfo->firstPortionBytes);
}
}
/**
* Get detailed information about a ready packet received (one whose
* \ref RAIL_RxPacketStatus_t is among the RAIL_RX_PACKET_READY_ set).
* This function can be used in any RX mode; it does not free up any
* internal resources.
*
* @param[in] railHandle A RAIL instance handle.
* @param[in] packetHandle A packet handle for the unreleased packet as
* returned from a previous call to RAIL_GetRxPacketInfo() or
* RAIL_HoldRxPacket(), or sentinel values \ref RAIL_RX_PACKET_HANDLE_OLDEST
* or \ref RAIL_RX_PACKET_HANDLE_NEWEST.
* @param[in,out] pPacketDetails An application-provided pointer to store
* \ref RAIL_RxPacketDetails_t for the requested packet.
* The timeReceived fields totalPacketBytes and timePosition must be
* initialized prior to each call:
* - totalPacketBytes with the total number of bytes of the received
* packet for RAIL to use when calculating the specified timestamp.
* This should account for all bytes received over the air after the
* Preamble and Sync word(s), including CRC bytes.
* - timePosition with a \ref RAIL_PacketTimePosition_t value specifying
* the packet position to put in the timeReceived field on return.
* This field will also be updated with the actual position corresponding
* to the timeReceived value filled in.
* @return \ref RAIL_STATUS_NO_ERROR if pPacketDetails was filled in,
* or an appropriate error code otherwise.
*/
RAIL_Status_t RAIL_GetRxPacketDetails(RAIL_Handle_t railHandle,
RAIL_RxPacketHandle_t packetHandle,
RAIL_RxPacketDetails_t *pPacketDetails);
/**
* Place a temporary hold on this packet's data and information resources
* within RAIL.
* This shall only be called from within RAIL callback context.
* This function can be used in any RX mode.
*
* Normally when RAIL issues its callback indicating a packet is ready
* or aborted, it expects the application's callback to retrieve and
* copy (or discard) the packet's information and data, and will free up
* its internal packet data after the callback returns. This function
* tells RAIL to hold onto those resources after the callback returns in
* case the application wants to defer processing the packet to a later
* time, e.g. outside of callback context.
*
* @param[in] railHandle A RAIL instance handle.
* @return The packet handle for the packet associated with the callback,
* or \ref RAIL_RX_PACKET_HANDLE_INVALID if no such packet yet exists.
*/
RAIL_RxPacketHandle_t RAIL_HoldRxPacket(RAIL_Handle_t railHandle);
/**
* Copies 'len' bytes of packet data starting from 'offset' from the
* receive FIFO. Those bytes remain valid for re-peeking.
*
* @param[in] railHandle A RAIL instance handle.
* @param[in] packetHandle A packet handle as returned from a previous
* RAIL_GetRxPacketInfo() or RAIL_HoldRxPacket() call, or
* sentinel values \ref RAIL_RX_PACKET_HANDLE_OLDEST
* or \ref RAIL_RX_PACKET_HANDLE_NEWEST.
* @param[out] pDst A pointer to the location where the received bytes will
* be copied. If NULL, no copying occurs.
* @param[in] len A number of packet data bytes to copy.
* @param[in] offset A byte offset within remaining packet data from which
* to copy.
* @return Number of packet bytes copied.
*
* @note Peek does not permit peeking beyond the requested packet's
* available packet data (though there is a small chance it might
* for a \ref RAIL_RX_PACKET_HANDLE_NEWEST packet at the very end of
* still being received). Nor can one peek into already-consumed data read
* by RAIL_ReadRxFifo(). len and offset are relative to the remaining data
* available in the packet, if any was already consumed by RAIL_ReadRxFifo().
*/
uint16_t RAIL_PeekRxPacket(RAIL_Handle_t railHandle,
RAIL_RxPacketHandle_t packetHandle,
uint8_t *pDst,
uint16_t len,
uint16_t offset);
/**
* Release RAIL's internal resources for the packet.
* This must be called for any packet previously held via
* RAIL_HoldRxPacket(), and may optionally be called within
* callback context to release RAIL resources sooner than at
* callback completion time when not holding the packet.
* This function can be used in any RX mode.
*
* @param[in] railHandle A RAIL instance handle.
* @param[in] packetHandle A packet handle as returned from a previous
* RAIL_HoldRxPacket() call, or sentinel values
* \ref RAIL_RX_PACKET_HANDLE_OLDEST or \ref RAIL_RX_PACKET_HANDLE_NEWEST.
* The latter might be used within RAIL callback context to explicitly
* release the packet associated with the callback early, before it would
* be released automatically by RAIL on callback return (unless explicitly
* held).
* @return \ref RAIL_STATUS_NO_ERROR if the held packet was released
* or an appropriate error code otherwise.
*/
RAIL_Status_t RAIL_ReleaseRxPacket(RAIL_Handle_t railHandle,
RAIL_RxPacketHandle_t packetHandle);
/**
* Returns the current raw RSSI.
*
* @param[in] railHandle A RAIL instance handle.
* @param[in] wait if false returns instant RSSI with no checks.
* @return \ref RAIL_RSSI_INVALID if the receiver is disabled and an RSSI
* value can't be obtained. Otherwise, return the RSSI in quarter dBm, dbm*4.
*
* Gets the current RSSI value. This value represents the current energy of the
* channel, it can change rapidly, and will be low if no RF energy is
* in the current channel. The function from the value reported to dBm is an
* offset dependent on the PHY and the PCB layout. Users should characterize the
* RSSI received on their hardware and apply an offset in the application to
* account for board and PHY parameters. 'Wait' argument doesn't guarantee
* a valid RSSI reading.'Wait' being true gives assurance that that the RSSI is
* current and not stale value from previous radio state. If GetRssi is called
* during RX-to-RX, RX-to-IDLE or RX-to-TX transition the RSSI is considered
* stale and \ref RAIL_RSSI_INVALID is returned if wait=true. 'Wait' being false
* will return either current RSSI or stale RSSI measurement (if called during
* RX-to-RX, RX-to-IDLE or RX-to-TX transition). \ref RAIL_RSSI_INVALID is
* returned if radio hasn't been in RX longer than 'idleToRx' time
* (see \ref RAIL_StateTiming_t), regardless of wait argument.
*
* In multiprotocol, this function returns \ref RAIL_RSSI_INVALID
* immediately if railHandle is not the current active \ref RAIL_Handle_t.
* Additionally 'wait' should never be set 'true' in multiprotocol
* as the wait time is not consistent, so scheduling a scheduler
* slot cannot be done accurately.
*/
int16_t RAIL_GetRssi(RAIL_Handle_t railHandle, bool wait);
/**
* Starts the RSSI averaging over a specified time in us.
*
* @param[in] railHandle A RAIL instance handle.
* @param[in] channel The physical channel to set.
* @param[in] averagingTimeUs Averaging time in microseconds.
* @param[in] schedulerInfo Information to allow the radio scheduler to place
* this operation appropriately. This is only used in multiprotocol version of
* RAIL and may be set to NULL in all other versions.
* @return Status code indicating success of the function call.
*
* Starts a non-blocking hardware-based RSSI averaging mechanism. Only a single
* instance of RSSI averaging can be run at any time and the radio must be idle
* to start.
*
* In multiprotocol, this is a scheduled event. It will start when railHandle
* becomes active, and railHandle will need to stay active until the averaging
* completes. If the averaging is interrupted, calls to
* \ref RAIL_GetAverageRssi will return \ref RAIL_RSSI_INVALID.
*
* Also in multiprotocol, the user is required to call \ref RAIL_YieldRadio
* after this event completes (i.e. when \ref RAIL_EVENT_RSSI_AVERAGE_DONE
* occurs).
*/
RAIL_Status_t RAIL_StartAverageRssi(RAIL_Handle_t railHandle,
uint16_t channel,
RAIL_Time_t averagingTimeUs,
const RAIL_SchedulerInfo_t *schedulerInfo);
/**
* Queries whether the RSSI averaging is done.
*
* @param[in] railHandle A RAIL instance handle.
* @return Returns true if done and false otherwise.
*
* This function can be used to poll for completion of the RSSI averaging
* to avoid relying on an interrupt-based callback.
*/
bool RAIL_IsAverageRssiReady(RAIL_Handle_t railHandle);
/**
* Gets the RSSI averaged over specified time in us.
*
* @param[in] railHandle A RAIL instance handle.
* @return Return \ref RAIL_RSSI_INVALID if the receiver is disabled
* an RSSI value can't be obtained. Otherwise, return the RSSI in
* quarter dBm,dbm*4.
*
* Gets the hardware RSSI average after issuing RAIL_StartAverageRssi.
* It should be used after \ref RAIL_StartAverageRssi.
*/
int16_t RAIL_GetAverageRssi(RAIL_Handle_t railHandle);
/******************************************************************************
* Address Filtering (RX)
*****************************************************************************/
/**
* @addtogroup Address_Filtering Address Filtering
* @brief Configuration APIs for receive packet address filtering.
*
* The address filtering code examines the packet as follows.
*
* | `Bytes: 0 - 255` | `0 - 8` | `0 - 255` | `0 - 8` | `Variable` |
* |:----------------:|---------:|----------:|---------:|:----------:|
* | `Data0` | `Field0` | `Data1` | `Field1` | `Data2` |
*
* In the above structure, anything listed as DataN is an optional section of
* bytes that RAIL will not process for address filtering. The FieldN segments
* reference-specific sections in the packet that will each be interpreted
* as an address during address filtering. The application may submit up to
* four addresses to attempt to match each field segment and each address may
* have a size of up to 8 bytes. To set up address filtering, first configure
* the locations and length of the addresses in the packet. Next, configure
* which combinations of matches in Field0 and Field1 should constitute an
* address match. Lastly, enter addresses into tables for each field and
* enable them. The first two of these are part of the \ref RAIL_AddrConfig_t
* structure while the second part is configured at runtime using the
* RAIL_SetAddressFilterAddress() API. A brief description of each
* configuration is listed below.
*
* For the first piece of configuration, the offsets and sizes of the fields
* are assumed fixed for the RAIL address filter. To set them, specify
* arrays for these values in the sizes and offsets entries in the
* \ref RAIL_AddrConfig_t structure. A size of zero indicates that a field is
* disabled. The start offset for a field is relative to the previous start
* offset and, if you're using FrameType decoding, the first start offset is
* relative to the end of the byte containing the frame type.
*
* Configuring which combinations of Field0 and Field1 constitute a match is
* the most complex portion of the address filter. The easiest way to think
* about this is with a truth table. If you consider each of the four possible
* address entries in a field, you can have a match on any one of those or a
* match for none of them. This can be represented as a 4-bit mask where 1
* indicates a match and 0 indicates no match. Representing the Field0 match
* options as rows and the Field1 options as columns results in a truth table
* as shown below.
*
* | | 0000 | 0001 | 0010 | 0100 | 1000 |
* |----------|------|------|------|------|------|
* | __0000__ | bit0 | bit1 | bit2 | bit3 | bit4 |
* | __0001__ | bit5 | bit6 | bit7 | bit8 | bit9 |
* | __0010__ | bit10| bit11| bit12| bit13| bit14|
* | __0100__ | bit15| bit16| bit17| bit18| bit19|
* | __1000__ | bit20| bit21| bit22| bit23| bit24|
*
* Because this is only 25 bits, it can be represented in one 32-bit integer
* where 1 indicates a filter pass and 0 indicates a filter fail. This is the
* matchTable parameter in the configuration struct and is used during
* filtering. For common simple configurations two defines are provided with
* the truth tables as shown below. The first is \ref
* ADDRCONFIG_MATCH_TABLE_SINGLE_FIELD, which can be used if only using
* one address field (either field). If using two fields and want to
* force in the same address entry in each field, use the second define: \ref
* ADDRCONFIG_MATCH_TABLE_DOUBLE_FIELD. For more complex systems,
* create a valid custom table.
*
* @note Address filtering does not function reliably with PHYs that use a data
* rate greater than 500 kbps. If this is a requirement, filter in software
* for the time being.
*
* @{
*/
/**
* Configures address filtering.
*
* @param[in] railHandle A RAIL instance handle.
* @param[in] addrConfig The configuration structure, which defines how
* addresses are setup in your packets.
* @return Status code indicating success of the function call.
*
* This function must be called to set up address filtering. You may call it
* multiple times but all previous information is wiped out each time you call
* and any configured addresses must be reset.
*/
RAIL_Status_t RAIL_ConfigAddressFilter(RAIL_Handle_t railHandle,
const RAIL_AddrConfig_t *addrConfig);
/**
* Enables address filtering.
*
* @param[in] railHandle A RAIL instance handle.
* @param[in] enable An argument to indicate whether or not to enable address
* filtering.
* @return True if address filtering was enabled to start with and false
* otherwise.
*
* Only allow packets through that pass the current address filtering
* configuration. This does not reset or change the configuration so you can
* set that up before turning on this feature.
*/
bool RAIL_EnableAddressFilter(RAIL_Handle_t railHandle, bool enable);
/**
* Returns whether address filtering is currently enabled.
*
* @param[in] railHandle A RAIL instance handle.
* @return True if address filtering is enabled and false otherwise.
*/
bool RAIL_IsAddressFilterEnabled(RAIL_Handle_t railHandle);
/**
* Resets the address filtering configuration.
*
* @param[in] railHandle A RAIL instance handle.
* @return void.
*
* Resets all structures related to address filtering. This does not disable
* address filtering. It leaves the radio in a state where no packets
* pass filtering.
*/
void RAIL_ResetAddressFilter(RAIL_Handle_t railHandle);
/**
* Sets an address for filtering in hardware.
*
* @param[in] railHandle A RAIL instance handle.
* @param[in] field Which address field you want to use for this address.
* @param[in] index Which match entry you want to place this address in for a
* given field.
* @param[in] value A pointer to the address data. This must be at least as
* long as the size specified in RAIL_ConfigAddressFilter().
* @param[in] enable A boolean to indicate whether this address should be
* enabled immediately.
* @return Status code indicating success of the function call.
*
* This function loads the given address into hardware for filtering and
* starts filtering if you set the enable parameter to true. Otherwise,
* call RAIL_EnableAddressFilterAddress() to turn it on later.
*/
RAIL_Status_t RAIL_SetAddressFilterAddress(RAIL_Handle_t railHandle,
uint8_t field,
uint8_t index,
const uint8_t *value,
bool enable);
/**
* Enables address filtering for the specified address.
*
* @param[in] railHandle A RAIL instance handle.
* @param[in] enable An argument to indicate whether or not to enable address
* filtering.
* @param[in] field Which address field you want to enable the address in.
* @param[in] index Which match entry in the given field you want to enable.
* @return Status code indicating success of the function call.
*/
RAIL_Status_t RAIL_EnableAddressFilterAddress(RAIL_Handle_t railHandle,
bool enable,
uint8_t field,
uint8_t index);
/** @} */ // end of group Address_Filtering
/** @} */ // end of group Receive
/******************************************************************************
* Auto Acking
*****************************************************************************/
/// @addtogroup Auto_Ack Auto ACK
/// @brief APIs for configuring auto ACK functionality
///
/// These APIs are used to configure the radio for auto acknowledgment
/// features. Auto ACK inherently changes how the underlying state machine
/// behaves so users should not modify RAIL_SetRxTransitions() and
/// RAIL_SetTxTransitions() while using auto ACK features.
///
/// @code{.c}
/// // Go to RX after ACK operation
/// RAIL_AutoAckConfig_t autoAckConfig = {
/// .enable = true,
/// .ackTimeout = 1000,
/// // "error" param ignored
/// .rxTransitions = { RAIL_RF_STATE_RX, RAIL_RF_STATE_RX},
/// // "error" param ignored
/// .txTransitions = { RAIL_RF_STATE_RX, RAIL_RF_STATE_RX}
/// };
///
/// RAIL_Status_t status = RAIL_ConfigAutoAck(railHandle, &autoAckConfig);
///
/// uint8_t ackData[] = {0x05, 0x02, 0x10, 0x00};
///
/// RAIL_Status_t status = RAIL_WriteAutoAckFifo(ackData, sizeof(ackData));
/// @endcode
///
/// The acknowledgment transmits based on the frame format configured via
/// the Radio Configurator. For example, if the frame format is using a variable
/// length scheme, the ACK will be sent according to that scheme. If a 10-byte
/// packet is loaded into the ACK, but the variable length field of the ACK
/// payload specifies a length of 5, only 5 bytes will transmit for the ACK.
/// The converse is also true, if the frame length is configured to be a fixed
/// 10-byte packet but only 5 bytes are loaded into the ACK buffer, a TX
/// underflow occurs during the ACK transmit.
///
/// Unlike in non-ACK mode, ACK mode will always return to a single
/// state after all ACK sequences complete, regardless of whether
/// the ACK was successfully received/sent or not. Read the documentation
/// of RAIL_ConfigAutoAck for more detail on how that is configured. To
/// not auto acknowledge a series of packets after transmit
/// or receive, call RAIL_PauseTxAutoAck(true) or RAIL_PauseRxAutoAck(true).
/// When auto acking is paused, after receiving or transmitting (also
/// regardless of success) a packet, the radio transitions to the same single
/// state it always defaults to while acking. To return to
/// normal state transition logic outside of acking, you must call
/// RAIL_ConfigAutoAck with the "enable" field false, and specify the
/// desired transitions in the rxTransitions and txTransitions fields.
/// To simply get out of a paused state and resume auto acking, call
/// RAIL_PauseTxAutoAck(false) or RAIL_PauseRxAutoAck(false).
///
/// Applications can cancel the transmission of an ACK with
/// RAIL_CancelAutoAck(). Conversely, applications can control if a transmit
/// operation should wait for an ACK after transmitting by using
/// the \ref RAIL_TX_OPTION_WAIT_FOR_ACK bit.
///
/// If the ACK payload is dynamic, the application must call
/// RAIL_WriteAutoAckFifo() with the appropriate ACK payload after the
/// application processes the receive. RAIL can auto ACK from the normal
/// transmit buffer if RAIL_UseTxFifoForAutoAck() is called before the radio
/// transmits the ACK. Ensure the transmit buffer contains data loaded by
/// RAIL_WriteTxFifo().
///
/// Standard-based protocols that contain auto ACK functionality are normally
/// configured in the protocol-specific configuration function. For example,
/// RAIL_IEEE802154_Init() provides auto ACK configuration parameters in \ref
/// RAIL_IEEE802154_Config_t and should only be configured through that
/// function. It is not advisable to call both RAIL_IEEE802154_Init() and
/// RAIL_ConfigAutoAck(). However, ACK modification functions are still valid to
/// use with protocol-specific ACKs. To cancel a IEEE 802.15.4 ACK transmit, use
/// RAIL_CancelAutoAck().
///
/// @{
/// Configures and enable auto acknowledgment.
///
/// @param[in] railHandle A RAIL instance handle.
/// @param[in] config Auto ACK configuration structure.
/// @return Status code indicating success of the function call.
///
/// Configures the RAIL state machine to for hardware-accelerated auto
/// acknowledgment. ACK timing parameters are defined in the configuration
/// structure.
///
/// While auto acking is enabled, do not call the following RAIL functions:
/// - RAIL_SetRxTransitions()
/// - RAIL_SetTxTransitions()
///
/// Note, that if you are enabling auto ACK (i.e. "enable" field is true)
/// The "error" fields of rxTransitions and txTransitions are ignored.
/// After all ACK sequences, (success or fail) the state machine will return
/// the radio to the "success" state. If you need information about the
/// actual success of the ACK sequence, you can use RAIL events such as
/// \ref RAIL_EVENT_TXACK_PACKET_SENT to make sure an ACK was sent, or
/// \ref RAIL_EVENT_RX_ACK_TIMEOUT to make sure that an ACK was received
/// within the specified timeout.
///
/// If you wish to set a certain turnaround time (i.e. txToRx and rxToTx
/// in \ref RAIL_StateTiming_t), we recommend that you make txToRx lower than
/// desired, in order to ensure you get to RX in time to receive the ACK.
/// Silicon Labs recommends setting 10us lower than desired:
///
/// @code{.c}
/// void setAutoAckStateTimings()
/// {
/// RAIL_StateTiming_t timings;
///
/// // User is already in auto ACK and wants a turnaround of 192us
/// timings.rxToTx = 192;
/// timings.txToRx = 192 - 10;
///
/// // Set other fields of timings...
/// timings.idleToRx = 100;
/// timings.idleToTx = 100;
/// timings.rxSearchTimeout = 0;
/// timings.txToRxSearchTimeout = 0;
///
/// RAIL_SetStateTiming(railHandle, &timings);
/// }
/// @endcode
///
/// As opposed to an explicit "Disable" API, simply set the "enable"
/// field of the RAIL_AutoAckConfig_t to false. Then, auto ACK will be
/// disabled and state transitions will be returned to the values set
/// in \ref RAIL_AutoAckConfig_t. During this disable, the "ackTimeout" field
/// isn't used.
///
RAIL_Status_t RAIL_ConfigAutoAck(RAIL_Handle_t railHandle,
const RAIL_AutoAckConfig_t *config);
/**
* Returns the enable status of the auto ACK feature.
*
* @param[in] railHandle A RAIL instance handle.
* @return true if auto ACK is enabled, false if disabled.
*/
bool RAIL_IsAutoAckEnabled(RAIL_Handle_t railHandle);
/**
* Loads the auto ACK buffer with ACK data.
*
* @param[in] railHandle A RAIL instance handle.
* @param[in] ackData A pointer to ACK data to transmit.
* @param[in] ackDataLen Number of bytes of ACK data.
* @return Status code indicating success of the function call.
*
* If the ACK buffer is available for updates, load the ACK buffer with data.
*/
RAIL_Status_t RAIL_WriteAutoAckFifo(RAIL_Handle_t railHandle,
const uint8_t *ackData,
uint8_t ackDataLen);
/**
* Pauses/resumes RX auto ACK functionality.
*
* @param[in] railHandle A RAIL instance handle.
* @param[in] pause Pause or resume RX auto acking.
* @return void.
*
* When RX auto acking is paused, the radio transitions to default
* state after receiving a packet and does not transmit an ACK.
* When RX auto ACK is resumed, the radio resumes automatically acking
* every successfully received packet.
*/
void RAIL_PauseRxAutoAck(RAIL_Handle_t railHandle,
bool pause);
/**
* Returns whether the RX auto ACK is paused.
*
* @param[in] railHandle A RAIL instance handle.
* @return true if RX auto ACK is paused, false if not paused.
*/
bool RAIL_IsRxAutoAckPaused(RAIL_Handle_t railHandle);
/**
* Pauses/resumes TX auto ACK functionality.
*
* @param[in] railHandle A RAIL instance handle.
* @param[in] pause Pause or resume TX auto acking.
* @return void.
*
* When TX auto acking is paused, the radio transitions to a default
* state after transmitting a packet and does not wait for an ACK. When TX
* auto ACK is resumed, the radio resumes automatically waiting for
* an ACK after a successful transmit.
*/
void RAIL_PauseTxAutoAck(RAIL_Handle_t railHandle, bool pause);
/**
* Returns whether the TX auto ACK is paused.
*
* @param[in] railHandle A RAIL instance handle.
* @return true if TX auto ACK is paused, false if not paused.
*/
bool RAIL_IsTxAutoAckPaused(RAIL_Handle_t railHandle);
/**
* Modifies the upcoming ACK to use the TX Buffer.
*
* @param[in] railHandle A RAIL instance handle.
* @return Status code indicating success of the function call. This call will
* fail if it is too late to modify the outgoing ACK.
*
* This function allows the application to use the normal TX buffer as the data
* source for the upcoming ACK. The ACK modification to use the TX buffer only
* applies to one ACK transmission.
*
* This function only returns true if the following conditions are met:
* - Radio has not already decided to use the ACK buffer AND
* - Radio is either looking for sync, receiving the packet after sync, or in
* the Rx2Tx turnaround before the ACK is sent.
*/
RAIL_Status_t RAIL_UseTxFifoForAutoAck(RAIL_Handle_t railHandle);
/**
* Cancels the upcoming ACK.
*
* @param[in] railHandle A RAIL instance handle.
* @return Status code indicating success of the function call. This call will
* fail if it is too late to modify the outgoing ACK.
*
* This function allows the application to cancel the upcoming automatic
* acknowledgment.
*
* This function only returns true if the following conditions are met:
* - Radio has not already decided to transmit the ACK AND
* - Radio is either looking for sync, receiving the packet after sync or in
* the Rx2Tx turnaround before the ACK is sent.
*/
RAIL_Status_t RAIL_CancelAutoAck(RAIL_Handle_t railHandle);
/**
* Returns whether the radio is currently waiting for an ACK.
*
* @param[in] railHandle A RAIL instance handle.
* @return True if radio is waiting for ACK, false if radio is not waiting for
* an ACK.
*
* This function allows the application to query whether the radio is currently
* waiting for an ACK after a transmit operation.
*/
bool RAIL_IsAutoAckWaitingForAck(RAIL_Handle_t railHandle);
/** @} */ // end of group Auto_Ack
/******************************************************************************
* Calibration
*****************************************************************************/
/// @addtogroup Calibration
/// @brief APIs for calibrating the radio
/// @{
///
/// These APIs can be used to calibrate the radio. The RAIL library
/// determines which calibrations are necessary. Calibrations can
/// be enabled/disabled with the RAIL_CalMask_t parameter.
///
/// Some calibrations produce values that can be saved and reapplied to
/// save repetition of the calibration process.
///
/// Calibrations can either be run with \ref RAIL_Calibrate, or with the
/// individual chip-specific calibration routines. An example for running code
/// with \ref RAIL_Calibrate looks like:
///
/// @code{.c}
/// static RAIL_CalValues_t calValues = RAIL_CALVALUES_UNINIT;
///
/// void RAILCb_Event(RAIL_Handle_t railHandle, RAIL_Events_t events) {
/// // Omitting other event handlers
/// if (events & RAIL_EVENT_CAL_NEEDED) {
/// // Run all pending calibrations, and save the results
/// RAIL_Calibrate(railHandle, &calValues, RAIL_CAL_ALL_PENDING);
/// }
/// }
/// @endcode
///
/// Alternatively, if the image rejection calibration for your chip can be
/// determined ahead of time, such as by running the calibration on a separate
/// firmware image on each chip, then the following calibration process will
/// result in smaller code.
///
/// @code{.c}
/// static uint32_t imageRejection = IRCAL_VALUE;
///
/// void RAILCb_Event(RAIL_Handle_t railHandle, RAIL_Events_t events) {
/// // Omitting other event handlers
/// if (events & RAIL_EVENT_CAL_NEEDED) {
/// RAIL_CalMask_t pendingCals = RAIL_GetPendingCal(railHandle);
/// // Disable the radio if we have to do an offline calibration
/// if (pendingCals & RAIL_CAL_TEMP_VC0) {
/// RAIL_CalibrateTemp(railHandle);
/// }
/// if (pendingCals & RAIL_CAL_ONETIME_IRCAL) {
/// RAIL_ApplyIrCalibration(railHandle, imageRejection);
/// }
/// }
/// }
/// @endcode
/**
* Initialize RAIL Calibration
*
* @param[in] railHandle A RAIL instance handle.
* @param[in] calEnable A bitmask of which calibrations to enable for callback
* notification. The exact meaning of these bits is chip specific.
* @return Status code indicating success of the function call.
*
* Calibration initialization provides the calibration settings that
* correspond to the current radio configuration.
*/
RAIL_Status_t RAIL_ConfigCal(RAIL_Handle_t railHandle,
RAIL_CalMask_t calEnable);
/**
* Starts the calibration process.
*
* @param[in] railHandle A RAIL instance handle.
* @param[in,out] calValues A structure of calibration values to apply.
* If a valid calibration values structure is provided and the structure
* contains valid calibration values, those values will be applied to the
* hardware, and the RAIL library will cache those values for use again later.
* If a valid calibration values structure is provided and the structure
* contains a calibration value of \ref RAIL_CAL_INVALID_VALUE for the
* desired calibration, the desired calibration will run, the calibration
* values structure will be updated with a valid calibration value, and the
* RAIL library will cache that value for use again later.
* If a NULL pointer is provided, the desired calibration will run,
* and the RAIL library will cache that value for use again later; however,
* the valid calibration value will not be returned to the application.
* @param[in] calForce A mask to force specific calibration(s) to execute.
* To run all pending calibrations, use the value \ref RAIL_CAL_ALL_PENDING.
* Only the calibrations specified will run, even if not enabled during
* initialization.
* @return Status code indicating success of the function call.
*
* If calibrations were performed previously and the application saves the
* calibration values (i.e. call this function with a calibration values
* structure containing calibration values of \ref RAIL_CAL_INVALID_VALUE
* before a reset), the application can later bypass the time it would normally
* take to recalibrate hardware by reusing previous calibration values (i.e.
* call this function with a calibration values structure containing valid
* calibration values after a reset).
*
* If multiple protocols are used, this function will return
* \ref RAIL_STATUS_INVALID_STATE if it is called and the given railHandle is
* not active. The caller must attempt to re-call this function later, in that
* case.
*
* @note Instead of this function, consider using the individual chip-specific
* functions. Using the individual functions will allow for better
* dead-stripping if not all calibrations are run.
* @note Some calibrations should only be executed when the radio is IDLE. See
* chip-specific documentation for more details.
*/
RAIL_Status_t RAIL_Calibrate(RAIL_Handle_t railHandle,
RAIL_CalValues_t *calValues,
RAIL_CalMask_t calForce);
/**
* Returns the current set of pending calibrations.
*
* @param[in] railHandle A RAIL instance handle.
* @return A mask of all pending calibrations that the user has been asked to
* perform.
*
* This function returns a full set of pending calibrations. The only way
* to clear pending calibrations is to perform them using the \ref
* RAIL_Calibrate() API with the appropriate list of calibrations.
*/
RAIL_CalMask_t RAIL_GetPendingCal(RAIL_Handle_t railHandle);
/**
* Enable/Disable PA calibration
*
* @param[in] enable Enables/Disables PA calibration
* @return void.
*
* Enabling this will ensure that the PA power remains constant chip to chip.
* By default this feature is disabled after reset.
*
* @note this function should be called before \ref RAIL_ConfigTxPower() if this
* feature is desired.
*/
void RAIL_EnablePaCal(bool enable);
/** @} */ // end of group Calibration
/******************************************************************************
* RF Sense Structures
*****************************************************************************/
/**
* @addtogroup Rf_Sense RF Sense
* @{
*/
/**
* Starts/stops RF Sense functionality for use during low-energy sleep modes.
*
* @param[in] railHandle A RAIL instance handle.
* @param[in] band The frequency band(s) on which to sense the RF energy.
* To stop RF Sense, specify \ref RAIL_RFSENSE_OFF.
* @param[in] senseTime The time (in microseconds) the RF energy must be
* continually detected to be considered "sensed".
* @param[in] cb \ref RAIL_RfSense_CallbackPtr_t is called when the RF is
* sensed. Set null if polling via \ref RAIL_IsRfSensed().
* @return The actual senseTime used, which may be different than
* requested due to limitations of the hardware. If 0, RF sense was
* disabled or could not be enabled (no callback will be issued).
*
* The EFR32 has the ability to sense the presence of RF Energy above -20 dBm
* within either or both the 2.4 GHz and Sub-GHz bands and trigger an event
* if that energy is continuously present for certain durations of time.
*
* @note After RF energy has been sensed, the RF Sense is automatically
* disabled. RAIL_StartRfSense() must be called again to reactivate it.
*
* @note Packet reception is not guaranteed to work correctly once RF Sense is
* enabled. To be safe, an application should turn this on only after idling
* the radio to stop receive and turn it off before attempting to restart
* receive. Since EM4 sleep causes the chip to come up through the reset
* vector any wake from EM4 must also shut off RF Sense to ensure proper
* receive functionality.
*
* @warning RF Sense functionality is only guaranteed from 0 to 85 degrees
* Celsius. RF Sense should be disabled outside of this temperature range.
*/
RAIL_Time_t RAIL_StartRfSense(RAIL_Handle_t railHandle,
RAIL_RfSenseBand_t band,
RAIL_Time_t senseTime,
RAIL_RfSense_CallbackPtr_t cb);
/**
* Checks if the RF was sensed.
*
* @param[in] railHandle A RAIL instance handle.
* @return true if RF was sensed since the last call to \ref RAIL_StartRfSense.
* False otherwise.
*
* This function is useful if \ref RAIL_StartRfSense is called with a null
* callback. It is generally used after EM4 reboot but can be used any time.
*/
bool RAIL_IsRfSensed(RAIL_Handle_t railHandle);
/** @} */ // end of group Rf_Sense
/******************************************************************************
* Multiprotocol Structures
*****************************************************************************/
/**
* @addtogroup Multiprotocol
* @brief Multiprotocol scheduler APIs to support multiple time-sliced PHYs.
* @{
*/
/**
* Yields the radio to other configurations
*
* @param[in] railHandle A RAIL instance handle.
* @return void.
*
* This function is used to indicate that the previous transmit or scheduled
* receive operation has completed. It must be used in multiprotocol RAIL since
* the scheduler assumes that any transmit or receive operation that is started
* by you can go on infinitely based on state transitions and your protocol.
* RAIL will not allow a lower priority tasks to run until this is called so it
* can negatively impact performance of those protocols if this is omitted or
* delayed. It is also possible to simply call the \ref RAIL_Idle() API to
* to both terminate the operation and idle the radio. In single protocol RAIL
* this API does nothing.
*
* See \ref rail_radio_scheduler_yield for more details.
*/
void RAIL_YieldRadio(RAIL_Handle_t railHandle);
/**
* Get the status of the RAIL scheduler.
*
* @param[in] railHandle A RAIL instance handle.
* @return \ref RAIL_SchedulerStatus_t status.
*
* This function can only be called from callback context after the
* \ref RAIL_EVENT_SCHEDULER_STATUS event occurs.
*/
RAIL_SchedulerStatus_t RAIL_GetSchedulerStatus(RAIL_Handle_t railHandle);
/** @} */ // end of group Multiprotocol
/******************************************************************************
* Diagnostic
*****************************************************************************/
/**
* @addtogroup Diagnostic
* @brief APIs for diagnostic and test chip modes
* @{
*/
/**
* Enables or disables direct mode for RAIL.
*
* @param[in] railHandle A RAIL instance handle.
* @param[in] enable Whether or not to enable direct mode.
* @return \ref RAIL_STATUS_NO_ERROR on success and an error code on failure.
*
* @warning This API configures fixed pins for TX data in, RX data out,
* RX clock out. There should be more control over these pins in the
* future but they are currently fixed. Also, this API is not safe to
* use in a true multiprotocol app.
*
* In this mode packets are output and input directly to the radio via GPIO
* and RAIL packet handling is ignored. On the EFR32, the DIN pin in TX is
* EFR32_PC10, which corresponds to EXP_HEADER15/WSTKP12, and the DOUT pin in
* RX is EFR32_PC11, which corresponds to EXP_HEADER16/WSTKP13.
*/
RAIL_Status_t RAIL_EnableDirectMode(RAIL_Handle_t railHandle,
bool enable);
/**
* Sets the crystal tuning.
*
* @param[in] railHandle A RAIL instance handle.
* @param[in] tune A chip-dependent crystal capacitor bank tuning parameter.
* @return Status code indicating success of the function call.
*
* Tunes the crystal that the radio depends on to change the location of the
* center frequency for transmitting and receiving. This function will only
* succeed if the radio is idle at the time of the call.
*
* @note This function proportionally affects the entire chip's timing
* across all its peripherals, including radio tuning and channel spacing.
* A separate function, \ref RAIL_SetFreqOffset(), can be used to adjust
* just the radio tuner without disturbing channel spacing or other chip
* peripheral timing.
*/
RAIL_Status_t RAIL_SetTune(RAIL_Handle_t railHandle, uint32_t tune);
/**
* Gets the crystal tuning.
*
* @param[in] railHandle A RAIL instance handle.
* @return A chip-dependent crystal capacitor bank tuning parameter.
*
* Retrieves the current tuning value used by the crystal that the radio
* depends on.
*/
uint32_t RAIL_GetTune(RAIL_Handle_t railHandle);
/**
* Gets the frequency offset.
*
* @param[in] railHandle A RAIL instance handle.
* @return Returns the measured frequency offset on a received packet.
* The units are described in the \ref RAIL_FrequencyOffset_t
* documentation. If this returns \ref RAIL_FREQUENCY_OFFSET_INVALID
* it was called while the radio wasn't active and there is no way
* to get the frequency offset.
*
* Retrieves the measured frequency offset used during the previous
* received packet, which includes the current radio frequency offset
* (see \ref RAIL_SetFreqOffset()). If the chip has not been in RX,
* it returns the nominal radio frequency offset.
*/
RAIL_FrequencyOffset_t RAIL_GetRxFreqOffset(RAIL_Handle_t railHandle);
/**
* Sets the nominal radio frequency offset.
*
* @param[in] railHandle A RAIL instance handle.
* @param[in] freqOffset \ref RAIL_FrequencyOffset_t parameter (signed, 2's
* complement).
* @return Status code indicating success of the function call.
*
* This is used to adjust the radio's tuning frequency slightly up or down.
* It might be used in conjunction with \ref RAIL_GetRxFreqOffset() after
* receiving a packet from a peer to adjust the tuner to better match the
* peer's tuned frequency.
*
* @note Unlike \ref RAIL_SetTune(), which affects the entire chip's
* timing including radio tuning and channel spacing, this function
* only affects radio tuning without disturbing channel spacing or
* other chip peripheral timing.
*/
RAIL_Status_t RAIL_SetFreqOffset(RAIL_Handle_t railHandle,
RAIL_FrequencyOffset_t freqOffset);
/**
* Starts transmitting a stream on a certain channel.
*
* @param[in] railHandle A RAIL instance handle.
* @param[in] channel A channel on which to emit a stream.
* @param[in] mode Choose the stream mode (PN9, and so on).
* @return Status code indicating success of the function call.
*
* Begins streaming onto the given channel. The sources can either be an
* unmodulated carrier wave, or an encoded stream of bits from a PN9 source.
* All ongoing radio operations will be stopped before transmission begins.
*/
RAIL_Status_t RAIL_StartTxStream(RAIL_Handle_t railHandle,
uint16_t channel,
RAIL_StreamMode_t mode);
/**
* Stops stream transmission.
*
* @param[in] railHandle A RAIL instance handle.
* @return Status code indicating success of the function call.
*
* Halts the transmission started by RAIL_StartTxStream().
*/
RAIL_Status_t RAIL_StopTxStream(RAIL_Handle_t railHandle);
/**
* Configures the verification of radio memory contents.
*
* @param[in] railHandle A RAIL instance handle.
* @param[in,out] configVerify A configuration structure made available to
* RAIL in order to perform radio state verification. This structure must be
* allocated in application global read-write memory. RAIL may modify
* fields within or referenced by this structure during its operation.
* @param[in] radioConfig A ptr to a radioConfig that is to be used as a
* white list for verifying memory contents.
* @param[in] cb A callback that notifies the application of a mismatch in
* expected vs actual memory contents. A NULL parameter may be passed in
* if a callback is not provided by the application.
* @return \ref RAIL_STATUS_NO_ERROR if setup of the verification feature
* successfully occurred.
* \ref RAIL_STATUS_INVALID_PARAMETER is returned if the provided railHandle
* or configVerify structures are invalid.
*/
RAIL_Status_t RAIL_ConfigVerification(RAIL_Handle_t railHandle,
RAIL_VerifyConfig_t *configVerify,
const uint32_t *radioConfig,
RAIL_VerifyCallbackPtr_t cb);
/**
* Verifies radio memory contents.
*
* @param[in,out] configVerify A configuration structure made available to
* RAIL in order to perform radio state verification. This structure must be
* allocated in application global read-write memory. RAIL may modify
* fields within or referenced by this structure during its operation.
* @param[in] durationUs The duration (in microseconds) for how long memory
* verification should occur before returning to the application. A value of
* RAIL_VERIFY_DURATION_MAX indicates that all memory contents should be
* verified before returning to the application.
* @param[in] restart This flag only has meaning if a previous call of this
* function returned \ref RAIL_STATUS_SUSPENDED. By restarting (true), the
* verification process starts over from the beginning, or by resuming
* where verification left off after being suspended (false), verification
* can proceed towards completion.
* @return \ref RAIL_STATUS_NO_ERROR if the contents of all applicable
* memory locations have been verified.
* \ref RAIL_STATUS_SUSPENDED is returned if the provided test duration
* expired but the time was not sufficient to verify all memory contents.
* By calling \ref RAIL_Verify again, further verification will commence.
* \ref RAIL_STATUS_INVALID_PARAMETER is returned if the provided
* verifyConfig structure pointer is not configured for use by the active
* RAIL handle.
* \ref RAIL_STATUS_INVALID_STATE is returned if any of the verified
* memory contents are different from their reference values.
*/
RAIL_Status_t RAIL_Verify(RAIL_VerifyConfig_t *configVerify,
uint32_t durationUs,
bool restart);
/** @} */ // end of group Diagnostic
#ifndef DOXYGEN_SHOULD_SKIP_THIS
/******************************************************************************
* Debug
*****************************************************************************/
/**
* @addtogroup Debug
* @brief APIs for debugging
* @{
*/
/**
* Configures the debug mode for the radio library. Do not use this function
* unless instructed by Silicon Labs.
* @param[in] railHandle A RAIL instance handle.
* @param[in] debugMode Debug mode to enter.
* @return Status code indicating success of the function call.
*/
RAIL_Status_t RAIL_SetDebugMode(RAIL_Handle_t railHandle, uint32_t debugMode);
/**
* Returns the debug mode for the radio library. Do not use this function
* unless instructed by Silicon Labs.
* @param[in] railHandle A RAIL instance handle.
* @return Debug mode for the radio library.
*/
uint32_t RAIL_GetDebugMode(RAIL_Handle_t railHandle);
/**
* Overrides the radio base frequency.
*
* @param[in] railHandle A RAIL instance handle.
* @param[in] freq A desired frequency in Hz.
* @return Status code indicating success of the function call.
*
* Sets the radio to transmit at the frequency given. This function can only
* be used while in \ref RAIL_DEBUG_MODE_FREQ_OVERRIDE. The given frequency
* needs to be close to the base frequency of the current PHY.
*/
RAIL_Status_t RAIL_OverrideDebugFrequency(RAIL_Handle_t railHandle,
uint32_t freq);
/** @} */ // end of group Debug
#endif//DOXYGEN_SHOULD_SKIP_THIS
/******************************************************************************
* Assertion Callback
*****************************************************************************/
/**
* @addtogroup Assertions
* @brief Callbacks called by assertions
*
* This assertion framework was implemented for the purpose of not only being
* able to assert that certain conditions be true in a block of code, but also
* to be able to handle them more appropriately. In previous implementations,
* the behavior upon a failed assert would be to hang in a while(1) loop.
* However, with the callback, each assert is given a unique error code so that
* they can be handled on a more case-by-case basis. For documentation on each
* of the errors, please see the rail_assert_error_codes.h file.
* RAIL_ASSERT_ERROR_MESSAGES[errorCode] gives the explanation of the error.
* With asserts built into the library, customers can choose how to handle each
* error inside the callback.
*
* @{
*/
/**
* Callback called upon failed assertion.
*
* @param[in] railHandle A RAIL instance handle.
* @param[in] errorCode Value passed in by the calling assertion API indicating
* the RAIL error that is indicated by the failing assertion.
* @return void.
*/
void RAILCb_AssertFailed(RAIL_Handle_t railHandle,
RAIL_AssertErrorCodes_t errorCode);
/** @} */ // end of group Assertions
/** @} */ // end of group RAIL_API
#ifdef __cplusplus
}
#endif
#endif // __RAIL_H__
| 40,464 |
378 | <filename>container/openejb-core/src/test/java/org/apache/openejb/assembler/classic/ApplicationResourceLifecycleTest.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.apache.openejb.assembler.classic;
import org.apache.openejb.config.sys.Resources;
import org.apache.openejb.testing.ApplicationComposers;
import org.apache.openejb.testing.Classes;
import org.apache.openejb.testing.Module;
import org.apache.openejb.testing.SimpleLog;
import org.junit.Test;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@Classes
@SimpleLog
public class ApplicationResourceLifecycleTest {
@Resource(name = "test")
private MyResource resource;
@Module
public Resources resources() {
return new Resources() {{
getResource().add(new org.apache.openejb.config.sys.Resource() {{
setId("test");
setClassName(MyResource.class.getName());
}});
}};
}
@Test
public void lifecycle() throws Exception {
new ApplicationComposers(this).evaluate(this, new Runnable() {
@Override
public void run() {
assertTrue(resource.init);
assertFalse(resource.destroy);
}
});
assertTrue(resource.init);
assertTrue(resource.destroy);
}
public static class MyResource {
private boolean init;
private boolean destroy;
@PostConstruct
private void init() {
init = true;
}
@PreDestroy
private void destroy() {
destroy = true;
}
public boolean isInit() {
return init;
}
public boolean isDestroy() {
return destroy;
}
}
}
| 984 |
332 | <filename>spring-xd-tuple/src/main/java/org/springframework/xd/tuple/package-info.java
/**
* Base package for tuple classes.
*/
package org.springframework.xd.tuple;
| 57 |
966 | # -*- coding: utf-8 -*-
"""Request/response schemas for ``gp_hyper_opt`` endpoints."""
import colander
from moe.optimal_learning.python.constant import DEFAULT_MAX_NUM_THREADS, MAX_ALLOWED_NUM_THREADS, LIKELIHOOD_TYPES, LOG_MARGINAL_LIKELIHOOD
from moe.views.schemas import base_schemas
class GpHyperOptRequest(base_schemas.StrictMappingSchema):
"""A :class:`moe.views.rest.gp_hyper_opt.GpHyperOptView` request colander schema.
.. Note:: Particularly when the amount of historical data is low, the log likelihood
may grow toward extreme hyperparameter values (i.e., toward 0 or infinity). Select
reasonable domain bounds. For example, in a driving distance parameter, the scale
of feet is irrelevant, as is the scale of 1000s of miles.
.. Note:: MOE's default optimization parameters were tuned for hyperparameter values roughly in [0.01, 100].
Venturing too far out of this range means the defaults may perform poorly.
See additional notes in :class:`moe.views.schemas.base_schemas.CovarianceInfo`,
:class:`moe.views.schemas.base_schemas.GpHistoricalInfo`.
**Required fields**
:ivar gp_historical_info: (:class:`moe.views.schemas.base_schemas.GpHistoricalInfo`) object of historical data
:ivar domain_info: (:class:`moe.views.schemas.base_schemas.DomainInfo`) dict of domain information for the GP
:ivar hyperparameter_domain_info: (:class:`moe.views.schemas.base_schemas.BoundedDomainInfo`) dict of domain information for the hyperparameter optimization
**Optional fields**
:ivar max_num_threads: (*int*) maximum number of threads to use in computation
:ivar covariance_info: (:class:`moe.views.schemas.base_schemas.CovarianceInfo`) dict of covariance information, used as a starting point for optimization
:ivar optimizer_info: (:class:`moe.views.schemas.base_schemas.OptimizerInfo`) dict of optimizer information
**General Timing Results**
Here are some "broad-strokes" timing results for hyperparameter optimization.
These tests are not complete nor comprehensive; they're just a starting point.
The tests were run on a Ivy Bridge 2.3 GHz quad-core CPU (i7-3615QM). Data was generated
from a Gaussian Process prior. The optimization parameters were the default
values (see :mod:`moe.optimal_learning.python.constant`) as of sha
``c19257049f16036e5e2823df87fbe0812720e291``.
Below, ``N = num_sampled``.
======== ===================== ========================
Scaling with dim (N = 40)
-------------------------------------------------------
dim Gradient Descent Newton
======== ===================== ========================
3 85s 3.6s
6 80s 7.2s
12 108s 19.5s
======== ===================== ========================
GD scales ``~ O(dim)`` and Newton ``~ O(dim^2)`` although these dim values
are not large enough to show the asymptotic behavior.
======== ===================== ========================
Scaling with N (dim = 3)
-------------------------------------------------------
N Gradient Descent Newton
======== ===================== ========================
20 14s 0.72s
40 85s 3.6s
120 2100s 60s
======== ===================== ========================
Both methods scale as ``~ O(N^3)`` which is clearly shown here.
**Example Request**
.. sourcecode:: http
Content-Type: text/javascript
{
"max_num_threads": 1,
"gp_historical_info": {
"points_sampled": [
{"value_var": 0.01, "value": 0.1, "point": [0.0]},
{"value_var": 0.01, "value": 0.2, "point": [1.0]}
],
},
"domain_info": {
"dim": 1,
},
"covariance_info": {
"covariance_type": "square_exponential",
"hyperparameters": [1.0, 1.0],
},
"hyperparameter_domain_info": {
"dim": 2,
"domain_bounds": [
{"min": 0.1, "max": 2.0},
{"min": 0.1, "max": 2.0},
],
},
"optimizer_info": {
"optimizer_type": "newton_optimizer",
"num_multistarts": 200,
"num_random_samples": 4000,
"optimizer_parameters": {
"gamma": 1.2,
...
},
},
"log_likelihood_info": "log_marginal_likelihood"
}
"""
max_num_threads = colander.SchemaNode(
colander.Int(),
validator=colander.Range(min=1, max=MAX_ALLOWED_NUM_THREADS),
missing=DEFAULT_MAX_NUM_THREADS,
)
gp_historical_info = base_schemas.GpHistoricalInfo()
domain_info = base_schemas.DomainInfo()
covariance_info = base_schemas.CovarianceInfo(
missing=base_schemas.CovarianceInfo().deserialize({}),
)
hyperparameter_domain_info = base_schemas.BoundedDomainInfo()
optimizer_info = base_schemas.OptimizerInfo(
missing=base_schemas.OptimizerInfo().deserialize({}),
)
log_likelihood_info = colander.SchemaNode(
colander.String(),
validator=colander.OneOf(LIKELIHOOD_TYPES),
missing=LOG_MARGINAL_LIKELIHOOD,
)
class GpHyperOptStatus(base_schemas.StrictMappingSchema):
"""A :class:`moe.views.rest.gp_hyper_opt.GpHyperOptView` status schema.
**Output fields**
:ivar log_likelihood: (*float64*) The log likelihood at the new hyperparameters
:ivar grad_log_likelihood: (*list of float64*) The gradient of the log likelihood at the new hyperparameters
:ivar optimizer_success: (*dict*) Whether or not the optimizer converged to an optimal set of hyperparameters
"""
log_likelihood = colander.SchemaNode(colander.Float())
grad_log_likelihood = base_schemas.ListOfFloats()
optimizer_success = colander.SchemaNode(
colander.Mapping(unknown='preserve'),
default={'found_update': False},
)
class GpHyperOptResponse(base_schemas.StrictMappingSchema):
"""A :class:`moe.views.rest.gp_hyper_opt.GpHyperOptView` response colander schema.
**Output fields**
:ivar endpoint: (*str*) the endpoint that was called
:ivar covariance_info: (:class:`moe.views.schemas.base_schemas.CovarianceInfo`) dict of covariance information
:ivar status: (:class:`moe.views.schemas.rest.gp_hyper_opt.GpHyperOptStatus`) dict indicating final log likelihood value/gradient and
optimization status messages (e.g., success)
**Example Response**
.. sourcecode:: http
{
"endpoint":"gp_hyper_opt",
"covariance_info": {
"covariance_type": "square_exponential",
"hyperparameters": ["0.88", "1.24"],
},
"status": {
"log_likelihood": "-37.3279872",
"grad_log_likelihood: ["-3.8897e-12", "1.32789789e-11"],
"optimizer_success": {
'newton_found_update': True,
},
},
}
"""
endpoint = colander.SchemaNode(colander.String())
covariance_info = base_schemas.CovarianceInfo()
status = GpHyperOptStatus()
| 3,372 |
2,042 | <reponame>oguzturker8sdfep/imranvisualpath1<gh_stars>1000+
/*
Copyright 2017 yangchong211(github.com/yangchong211)
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.yc.video.old.player;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.MediaPlayer;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import com.yc.kernel.utils.VideoLogUtils;
import com.yc.video.config.ConstantKeys;
import com.yc.video.old.controller.AbsVideoPlayerController;
import com.yc.video.tool.BaseToast;
import com.yc.video.tool.PlayerUtils;
import com.yc.video.old.other.VideoPlayerManager;
import java.util.Map;
import tv.danmaku.ijk.media.player.AndroidMediaPlayer;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;
/**
* <pre>
* @author yangchong
* blog : https://github.com/yangchong211
* time : 2017/9/21
* desc : 播放器
* revise: 注意:在对应的播放Activity页面,清单文件中一定要添加
* android:configChanges="orientation|keyboardHidden|screenSize"
* android:screenOrientation="portrait"
* </pre>
*/
@Deprecated
public class OldVideoPlayer extends FrameLayout implements IVideoPlayer {
/**
* 播放类型
* TYPE_IJK 基于IjkPlayer封装播放器
* TYPE_NATIVE 基于原生自带的播放器控件
**/
public int mPlayerType = ConstantKeys.VideoPlayerType.TYPE_IJK;
/**
* 播放状态,错误,开始播放,暂停播放,缓存中等等状态
**/
private int mCurrentState = ConstantKeys.CurrentState.STATE_IDLE;
/**
* 播放模式,普通模式,小窗口模式,正常模式等等
* 存在局限性:比如小窗口下的正在播放模式,那么mCurrentMode就是STATE_PLAYING,而不是MODE_TINY_WINDOW并存
**/
private int mCurrentMode = ConstantKeys.PlayMode.MODE_NORMAL;
private Context mContext;
private FrameLayout mContainer;
private AbsVideoPlayerController mController;
private String mUrl;
private Map<String, String> mHeaders;
private int mBufferPercentage;
/**
* 是否从上一次位置播放,默认是false
*/
private boolean continueFromLastPosition = false;
public long skipToPosition;
private VideoMediaPlayer videoMediaPlayer;
public OldVideoPlayer(Context context) {
this(context, null);
}
public OldVideoPlayer(Context context, AttributeSet attrs) {
this(context, attrs ,0);
}
public OldVideoPlayer(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mContext = context;
init();
}
/**
* 初始化
*/
private void init() {
BaseToast.init(mContext.getApplicationContext());
mContainer = new FrameLayout(mContext);
//设置背景颜色,目前设置为纯黑色
mContainer.setBackgroundColor(Color.BLACK);
LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
videoMediaPlayer = new VideoMediaPlayer(this);
//将布局添加到该视图中
this.addView(mContainer, params);
}
/**
* 如果锁屏,则屏蔽返回键,这个地方设置无效,需要在activity中设置处理返回键逻辑
* 后期找替代方案
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
VideoLogUtils.i("如果锁屏1,则屏蔽返回键onKeyDown"+event.getAction());
if(keyCode == KeyEvent.KEYCODE_BACK ){
if(mController!=null && mController.getLock()){
//如果锁屏,那就屏蔽返回键
return true;
}
}
return super.onKeyDown(keyCode, event);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
VideoLogUtils.d("onAttachedToWindow");
//init();
//在构造函数初始化时addView
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
VideoLogUtils.d("onDetachedFromWindow");
if (mController!=null){
mController.destroy();
}
//onDetachedFromWindow方法是在Activity destroy的时候被调用的,也就是act对应的window被删除的时候,
//且每个view只会被调用一次,父view的调用在后,也不论view的visibility状态都会被调用,适合做最后的清理操作
//防止开发者没有在onDestroy中没有做销毁视频的优化
release();
}
/*--------------setUp为必须设置的方法,二选其一--------------------------------------*/
/**
* 设置,必须设置
* @param url 视频地址,可以是本地,也可以是网络视频
* @param headers 请求header.
*/
@Override
public final void setUp(String url, Map<String, String> headers) {
if(url==null || url.length()==0){
VideoLogUtils.d("设置参数-------设置的视频链接不能为空");
}
mUrl = url;
mHeaders = headers;
}
/**
* 设置视频控制器,必须设置
* @param controller AbsVideoPlayerController子类对象,可用VideoPlayerController,也可自定义
*/
public void setController(@NonNull AbsVideoPlayerController controller) {
//这里必须先移除
mContainer.removeView(mController);
mController = controller;
mController.reset();
mController.setVideoPlayer(this);
LayoutParams params = new LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
mContainer.addView(mController, params);
}
public AbsVideoPlayerController getController(){
return mController;
}
public FrameLayout getContainer() {
return mContainer;
}
public String getUrl(){
return mUrl;
}
public Map<String, String> getHeaders(){
return mHeaders;
}
/**
* 设置播放器类型,必须设置
* 注意:感谢某人建议,这里限定了传入值类型
* 输入值:ConstantKeys.IjkPlayerType.TYPE_IJK 或者 ConstantKeys.IjkPlayerType.TYPE_NATIVE
* @param playerType IjkPlayer or MediaPlayer.
*/
public void setPlayerType(@ConstantKeys.PlayerType int playerType) {
//默认是基于IjkPlayer封装播放器
mPlayerType = playerType;
}
/**
* 是否从上一次的位置继续播放,不必须
*
* @param continueFromLastPosition true从上一次的位置继续播放
*/
@Override
public void continueFromLastPosition(boolean continueFromLastPosition) {
//默认是从上一次的位置继续播放
this.continueFromLastPosition = continueFromLastPosition;
}
public boolean getContinueFromLastPosition(){
return continueFromLastPosition;
}
public long getSkipToPosition() {
return skipToPosition;
}
/**
* 注意:MediaPlayer没有这个方法
* 设置播放速度,不必须
* @param speed 播放速度
*/
@Override
public void setSpeed(float speed) {
if (speed<0){
VideoLogUtils.d("设置参数-------设置的视频播放速度不能小于0");
}
if (videoMediaPlayer.getMediaPlayer() instanceof IjkMediaPlayer) {
((IjkMediaPlayer) videoMediaPlayer.getMediaPlayer()).setSpeed(speed);
} else if (videoMediaPlayer.getMediaPlayer() instanceof AndroidMediaPlayer){
//((AndroidMediaPlayer) videoMediaPlayer.getMediaPlayer()).setSpeed(speed);
VideoLogUtils.d("设置参数-------只有IjkPlayer才能设置播放速度");
}else if(videoMediaPlayer.getMediaPlayer() instanceof MediaPlayer){
//((MediaPlayer) videoMediaPlayer.getMediaPlayer()).setSpeed(speed);
VideoLogUtils.d("设置参数-------只有IjkPlayer才能设置播放速度");
} else {
VideoLogUtils.d("设置参数-------只有IjkPlayer才能设置播放速度");
}
}
/**
* 开始播放
*/
@Override
public void start() {
if (mController==null){
//在调用start方法前,请先初始化视频控制器,调用setController方法
throw new NullPointerException("Controller must not be null , please setController first");
}
if (mCurrentState == ConstantKeys.CurrentState.STATE_IDLE) {
VideoPlayerManager.instance().setCurrentVideoPlayer(this);
videoMediaPlayer.initAudioManager();
videoMediaPlayer.initMediaPlayer();
videoMediaPlayer.initTextureView();
} else {
VideoLogUtils.d("播放状态--------VideoPlayer只有在mCurrentState == STATE_IDLE时才能调用start方法.");
}
}
/**
* 开始播放
* @param position 播放位置
*/
@Override
public void start(long position) {
if (position<0){
VideoLogUtils.d("设置参数-------设置开始播放的播放位置不能小于0");
}
skipToPosition = position;
start();
}
/**
* 重新播放
*/
@Override
public void restart() {
if (mCurrentState == ConstantKeys.CurrentState.STATE_PAUSED) {
//如果是暂停状态,那么则继续播放
videoMediaPlayer.getMediaPlayer().start();
mCurrentState = ConstantKeys.CurrentState.STATE_PLAYING;
mController.onPlayStateChanged(mCurrentState);
VideoLogUtils.d("播放状态--------STATE_PLAYING");
} else if (mCurrentState == ConstantKeys.CurrentState.STATE_BUFFERING_PAUSED) {
//如果是缓存暂停状态,那么则继续播放
videoMediaPlayer.getMediaPlayer().start();
mCurrentState = ConstantKeys.CurrentState.STATE_BUFFERING_PLAYING;
mController.onPlayStateChanged(mCurrentState);
VideoLogUtils.d("播放状态--------STATE_BUFFERING_PLAYING");
} else if (mCurrentState == ConstantKeys.CurrentState.STATE_COMPLETED
|| mCurrentState == ConstantKeys.CurrentState.STATE_ERROR) {
//如果是完成播放或者播放错误,则重新播放
videoMediaPlayer.getMediaPlayer().reset();
videoMediaPlayer.openMediaPlayer();
VideoLogUtils.d("播放状态--------完成播放或者播放错误,则重新播放");
} else {
VideoLogUtils.d("VideoPlayer在mCurrentState == " + mCurrentState + "时不能调用restart()方法.");
}
}
/**
* 暂停播放
*/
@Override
public void pause() {
if (mCurrentState == ConstantKeys.CurrentState.STATE_PLAYING) {
//如果是播放状态,那么则暂停播放
videoMediaPlayer.getMediaPlayer().pause();
mCurrentState = ConstantKeys.CurrentState.STATE_PAUSED;
mController.onPlayStateChanged(mCurrentState);
VideoLogUtils.d("播放状态--------STATE_PAUSED");
} else if (mCurrentState == ConstantKeys.CurrentState.STATE_BUFFERING_PLAYING) {
//如果是正在缓冲状态,那么则暂停暂停缓冲
videoMediaPlayer.getMediaPlayer().pause();
mCurrentState = ConstantKeys.CurrentState.STATE_BUFFERING_PAUSED;
mController.onPlayStateChanged(mCurrentState);
VideoLogUtils.d("播放状态--------STATE_BUFFERING_PAUSED");
}
}
/**
* 设置播放位置
* @param pos 播放位置
*/
@Override
public void seekTo(long pos) {
if (pos<0){
VideoLogUtils.d("设置参数-------设置开始跳转播放位置不能小于0");
}
if (videoMediaPlayer.getMediaPlayer() != null) {
videoMediaPlayer.getMediaPlayer().seekTo(pos);
}
}
/**
* 设置音量
* @param volume 音量值
*/
@Override
public void setVolume(int volume) {
if (videoMediaPlayer.getAudioManager() != null) {
videoMediaPlayer.getAudioManager().setStreamVolume(AudioManager.STREAM_MUSIC, volume, 0);
}
}
/**
* 判断是否开始播放
* @return true表示播放未开始
*/
@Override
public boolean isIdle() {
return mCurrentState == ConstantKeys.CurrentState.STATE_IDLE;
}
/**
* 判断视频是否播放准备中
* @return true表示播放准备中
*/
@Override
public boolean isPreparing() {
return mCurrentState == ConstantKeys.CurrentState.STATE_PREPARING;
}
/**
* 判断视频是否准备就绪
* @return true表示播放准备就绪
*/
@Override
public boolean isPrepared() {
return mCurrentState == ConstantKeys.CurrentState.STATE_PREPARED;
}
/**
* 判断视频是否正在缓冲(播放器正在播放时,缓冲区数据不足,进行缓冲,缓冲区数据足够后恢复播放)
* @return true表示正在缓冲
*/
@Override
public boolean isBufferingPlaying() {
return mCurrentState == ConstantKeys.CurrentState.STATE_BUFFERING_PLAYING;
}
/**
* 判断是否是否缓冲暂停
* @return true表示缓冲暂停
*/
@Override
public boolean isBufferingPaused() {
return mCurrentState == ConstantKeys.CurrentState.STATE_BUFFERING_PAUSED;
}
/**
* 判断视频是否正在播放
* @return true表示正在播放
*/
@Override
public boolean isPlaying() {
return mCurrentState == ConstantKeys.CurrentState.STATE_PLAYING;
}
/**
* 判断视频是否暂停播放
* @return true表示暂停播放
*/
@Override
public boolean isPaused() {
return mCurrentState == ConstantKeys.CurrentState.STATE_PAUSED;
}
/**
* 判断视频是否播放错误
* @return true表示播放错误
*/
@Override
public boolean isError() {
return mCurrentState == ConstantKeys.CurrentState.STATE_ERROR;
}
/**
* 判断视频是否播放完成
* @return true表示播放完成
*/
@Override
public boolean isCompleted() {
return mCurrentState == ConstantKeys.CurrentState.STATE_COMPLETED;
}
/**
* 判断视频是否播放全屏
* @return true表示播放全屏
*/
@Override
public boolean isFullScreen() {
return mCurrentMode == ConstantKeys.PlayMode.MODE_FULL_SCREEN;
}
/**
* 判断视频是否播放小窗口
* @return true表示播放小窗口
*/
@Override
public boolean isTinyWindow() {
return mCurrentMode == ConstantKeys.PlayMode.MODE_TINY_WINDOW;
}
/**
* 判断视频是否正常播放
* @return true表示正常播放
*/
@Override
public boolean isNormal() {
return mCurrentMode == ConstantKeys.PlayMode.MODE_NORMAL;
}
/**
* 获取最大音量
* @return 音量值
*/
@Override
public int getMaxVolume() {
if (videoMediaPlayer.getAudioManager() != null) {
return videoMediaPlayer.getAudioManager().getStreamMaxVolume(AudioManager.STREAM_MUSIC);
}
return 0;
}
/**
* 获取当前播放状态
*
* @return 播放状态
*/
@Override
public int getPlayType() {
return mCurrentMode;
}
/**
* 获取音量值
* @return 音量值
*/
@Override
public int getVolume() {
if (videoMediaPlayer.getAudioManager() != null) {
return videoMediaPlayer.getAudioManager().getStreamVolume(AudioManager.STREAM_MUSIC);
}
return 0;
}
/**
* 获取持续时长
* @return long时间值
*/
@Override
public long getDuration() {
return videoMediaPlayer.getMediaPlayer() != null ? videoMediaPlayer.getMediaPlayer().getDuration() : 0;
}
/**
* 获取播放位置
* @return 位置
*/
@Override
public long getCurrentPosition() {
return videoMediaPlayer.getMediaPlayer() != null ? videoMediaPlayer.getMediaPlayer().getCurrentPosition() : 0;
}
/**
* 获取缓冲区百分比
* @return 百分比
*/
@Override
public int getBufferPercentage() {
return mBufferPercentage;
}
/**
* 设置缓冲区百分比
* @param bufferPercentage
*/
public void setBufferPercentage(int bufferPercentage) {
this.mBufferPercentage = bufferPercentage;
}
/**
* 获取播放速度
* @param speed 播放速度
* @return 速度
*/
@Override
public float getSpeed(float speed) {
if (videoMediaPlayer.getMediaPlayer() instanceof IjkMediaPlayer) {
return ((IjkMediaPlayer) videoMediaPlayer.getMediaPlayer()).getSpeed(speed);
}
return 0;
}
/**
* 获取播放速度
* @return 速度
*/
@Override
public long getTcpSpeed() {
if (videoMediaPlayer.getMediaPlayer() instanceof IjkMediaPlayer) {
return ((IjkMediaPlayer) videoMediaPlayer.getMediaPlayer()).getTcpSpeed();
}
return 0;
}
/**
* 获取当前播放模式
* @return 返回当前播放模式
*/
public int getCurrentState(){
return mCurrentState;
}
/**
* 设置当前播放模式
* @param state 当前播放模式
*/
public void setCurrentState(@ConstantKeys.CurrentState int state){
mCurrentState = state;
}
/**
* 进入全屏模式
* 全屏,将mContainer(内部包含mTextureView和mController)从当前容器中移除,并添加到android.R.content中.
* 切换横屏时需要在manifest的activity标签下添加android:configChanges="orientation|keyboardHidden|screenSize"配置,
* 以避免Activity重新走生命周期
*/
@Override
public void enterFullScreen() {
if (mCurrentMode == ConstantKeys.PlayMode.MODE_FULL_SCREEN){
return;
}
// 隐藏ActionBar、状态栏,并横屏
PlayerUtils.hideActionBar(mContext);
//设置更改此页面的所需方向。如果页面当前位于前台或以其他方式影响方向
//则屏幕将立即更改(可能导致重新启动该页面)。否则,这将在下一次页面可见时使用。
PlayerUtils.scanForActivity(mContext).setRequestedOrientation(
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
//找到contentView
ViewGroup contentView = PlayerUtils.scanForActivity(mContext)
.findViewById(android.R.id.content);
if (mCurrentMode == ConstantKeys.PlayMode.MODE_TINY_WINDOW) {
contentView.removeView(mContainer);
} else {
this.removeView(mContainer);
}
LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
contentView.addView(mContainer, params);
mCurrentMode = ConstantKeys.PlayMode.MODE_FULL_SCREEN;
mController.onPlayModeChanged(mCurrentMode);
VideoLogUtils.d("播放模式--------MODE_FULL_SCREEN");
}
/**
* 进入竖屏的全屏模式
*/
@Override
public void enterVerticalScreenScreen() {
if (mCurrentMode == ConstantKeys.PlayMode.MODE_FULL_SCREEN){
return;
}
// 隐藏ActionBar、状态栏,并横屏
PlayerUtils.hideActionBar(mContext);
PlayerUtils.scanForActivity(mContext).
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
ViewGroup contentView = PlayerUtils.
scanForActivity(mContext).findViewById(android.R.id.content);
if (mCurrentMode == ConstantKeys.PlayMode.MODE_TINY_WINDOW) {
contentView.removeView(mContainer);
} else {
this.removeView(mContainer);
}
LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
contentView.addView(mContainer, params);
mCurrentMode = ConstantKeys.PlayMode.MODE_FULL_SCREEN;
mController.onPlayModeChanged(mCurrentMode);
VideoLogUtils.d("播放模式--------MODE_FULL_SCREEN");
}
/**
* 退出全屏模式
* 退出全屏,移除mTextureView和mController,并添加到非全屏的容器中。
* 切换竖屏时需要在manifest的activity标签下添加
* android:configChanges="orientation|keyboardHidden|screenSize"配置,
* 以避免Activity重新走生命周期.
*
* @return true退出全屏.
*/
@Override
public boolean exitFullScreen() {
if (mCurrentMode == ConstantKeys.PlayMode.MODE_FULL_SCREEN) {
PlayerUtils.showActionBar(mContext);
PlayerUtils.scanForActivity(mContext).setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
ViewGroup contentView = PlayerUtils.scanForActivity(mContext).findViewById(android.R.id.content);
//将视图移除
contentView.removeView(mContainer);
//重新添加到当前视图
LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
this.addView(mContainer, params);
mCurrentMode = ConstantKeys.PlayMode.MODE_NORMAL;
mController.onPlayModeChanged(mCurrentMode);
VideoLogUtils.d("播放模式--------MODE_NORMAL");
this.setOnKeyListener(null);
return true;
}
return false;
}
/**
* 进入小窗口播放,小窗口播放的实现原理与全屏播放类似。
* 注意:小窗口播放视频比例是 16:9
*/
@Override
public void enterTinyWindow() {
//如果是小窗口模式,则不执行下面代码
if (mCurrentMode == ConstantKeys.PlayMode.MODE_TINY_WINDOW) {
return;
}
//先移除
this.removeView(mContainer);
ViewGroup contentView = PlayerUtils.scanForActivity(mContext).findViewById(android.R.id.content);
// 小窗口的宽度为屏幕宽度的60%,长宽比默认为16:9,右边距、下边距为8dp。
LayoutParams params = new LayoutParams(
(int) (PlayerUtils.getScreenWidth(mContext) * 0.6f),
(int) (PlayerUtils.getScreenWidth(mContext) * 0.6f * 9f / 16f));
params.gravity = Gravity.BOTTOM | Gravity.END;
params.rightMargin = PlayerUtils.dp2px(mContext, 8f);
params.bottomMargin = PlayerUtils.dp2px(mContext, 8f);
contentView.addView(mContainer, params);
mCurrentMode = ConstantKeys.PlayMode.MODE_TINY_WINDOW;
mController.onPlayModeChanged(mCurrentMode);
VideoLogUtils.d("播放模式-------MODE_TINY_WINDOW");
}
/**
* 退出小窗口播放
*/
@Override
public boolean exitTinyWindow() {
if (mCurrentMode == ConstantKeys.PlayMode.MODE_TINY_WINDOW) {
ViewGroup contentView = PlayerUtils.scanForActivity(mContext).findViewById(android.R.id.content);
contentView.removeView(mContainer);
LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
this.addView(mContainer, params);
mCurrentMode = ConstantKeys.PlayMode.MODE_NORMAL;
mController.onPlayModeChanged(mCurrentMode);
VideoLogUtils.d("播放模式-------MODE_NORMAL");
return true;
}
return false;
}
/**
* 释放,内部的播放器被释放掉,同时如果在全屏、小窗口模式下都会退出
* 逻辑
* 1.先保存播放位置
* 2.退出全屏或小窗口,回复播放模式为正常模式
* 3.释放播放器
* 4.恢复控制器
* 5.gc回收
*/
@Override
public void release() {
// 保存播放位置,当正在播放时,缓冲时,缓冲暂停时,暂停时
if (isPlaying() || isBufferingPlaying() || isBufferingPaused() || isPaused()) {
PlayerUtils.savePlayPosition(mContext, mUrl, getCurrentPosition());
} else if (isCompleted()) {
//如果播放完成,则保存播放位置为0,也就是初始位置
PlayerUtils.savePlayPosition(mContext, mUrl, 0);
}
// 退出全屏或小窗口
if (isFullScreen()) {
exitFullScreen();
}
if (isTinyWindow()) {
exitTinyWindow();
}
mCurrentMode = ConstantKeys.PlayMode.MODE_NORMAL;
// 释放播放器
releasePlayer();
// 恢复控制器
if (mController != null) {
mController.reset();
}
// gc回收
Runtime.getRuntime().gc();
}
/**
* 释放播放器,注意一定要判断对象是否为空,增强严谨性
* 这样以便在当前播放器状态下可以方便的切换不同的清晰度的视频地址
* 关于我的github:https://github.com/yangchong211
* 杨充修改:
* 17年12月23日,添加释放音频和TextureView
*/
@Override
public void releasePlayer() {
videoMediaPlayer.setAudioManagerNull();
if (videoMediaPlayer.getMediaPlayer() != null) {
//释放视频焦点
videoMediaPlayer.getMediaPlayer().release();
videoMediaPlayer.setMediaPlayerNull();
}
if (mContainer!=null){
//从视图中移除TextureView
mContainer.removeView(videoMediaPlayer.getTextureView());
}
videoMediaPlayer.releaseSurface();
//如果SurfaceTexture不为null,则释放
videoMediaPlayer.releaseSurfaceTexture();
mCurrentState = ConstantKeys.CurrentState.STATE_IDLE;
}
}
| 14,093 |
348 | <reponame>chamberone/Leaflet.PixiOverlay<gh_stars>100-1000
{"nom":"Buzançais","circ":"1ère circonscription","dpt":"Indre","inscrits":3561,"abs":1973,"votants":1588,"blancs":100,"nuls":49,"exp":1439,"res":[{"nuance":"REM","nom":"<NAME>","voix":955},{"nuance":"FN","nom":"<NAME>","voix":484}]} | 120 |
777 | <gh_stars>100-1000
// Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef IOS_CHROME_BROWSER_UI_ACTIVITY_SERVICES_SHARE_TO_DATA_H_
#define IOS_CHROME_BROWSER_UI_ACTIVITY_SERVICES_SHARE_TO_DATA_H_
#import <UIKit/UIKit.h>
#include "url/gurl.h"
@interface ShareToData : NSObject
// Designated initializer.
- (id)initWithURL:(const GURL&)url
title:(NSString*)title
isOriginalTitle:(BOOL)isOriginalTitle
isPagePrintable:(BOOL)isPagePrintable;
@property(nonatomic, readonly) const GURL& url;
// NSURL version of 'url'. Use only for passing to libraries that take NSURL.
@property(strong, nonatomic, readonly) NSURL* nsurl;
@property(nonatomic, readonly, copy) NSString* title;
@property(nonatomic, readonly, assign) BOOL isOriginalTitle;
@property(nonatomic, readonly, assign) BOOL isPagePrintable;
@property(nonatomic, strong) UIImage* image;
@end
#endif // IOS_CHROME_BROWSER_UI_ACTIVITY_SERVICES_SHARE_TO_DATA_H_
| 385 |
5,788 | <gh_stars>1000+
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.shardingsphere.scaling.postgresql.wal.decode;
import java.sql.SQLException;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Calendar;
/**
* logical replication decoding plugin interface.
*/
public interface BaseTimestampUtils {
/**
* Get time.
*
* @param cal the cal
* @param input the input time of string
* @return Time the time
* @throws SQLException the exp
*/
Time toTime(Calendar cal, String input) throws SQLException;
/**
* Get timestamp.
*
* @param cal the cal
* @param input the input timestamp of string
* @return Timestamp the timestamp
* @throws SQLException the exp
*/
Timestamp toTimestamp(Calendar cal, String input) throws SQLException;
}
| 492 |
427 | <filename>SymbolExtractorAndRenamer/lldb/include/lldb/Core/Log.h<gh_stars>100-1000
//===-- Log.h ---------------------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef liblldb_Log_h_
#define liblldb_Log_h_
// C Includes
#include <signal.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
// C++ Includes
// Other libraries and framework includes
// Project includes
#include "lldb/Core/ConstString.h"
#include "lldb/Core/Flags.h"
#include "lldb/Core/Logging.h"
#include "lldb/Core/PluginInterface.h"
#include "lldb/lldb-private.h"
#include "llvm/Support/FormatVariadic.h"
//----------------------------------------------------------------------
// Logging Options
//----------------------------------------------------------------------
#define LLDB_LOG_OPTION_THREADSAFE (1u << 0)
#define LLDB_LOG_OPTION_VERBOSE (1u << 1)
#define LLDB_LOG_OPTION_DEBUG (1u << 2)
#define LLDB_LOG_OPTION_PREPEND_SEQUENCE (1u << 3)
#define LLDB_LOG_OPTION_PREPEND_TIMESTAMP (1u << 4)
#define LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD (1u << 5)
#define LLDB_LOG_OPTION_PREPEND_THREAD_NAME (1U << 6)
#define LLDB_LOG_OPTION_BACKTRACE (1U << 7)
#define LLDB_LOG_OPTION_APPEND (1U << 8)
//----------------------------------------------------------------------
// Logging Functions
//----------------------------------------------------------------------
namespace lldb_private {
class Log final {
public:
//------------------------------------------------------------------
// Callback definitions for abstracted plug-in log access.
//------------------------------------------------------------------
typedef void (*DisableCallback)(const char **categories,
Stream *feedback_strm);
typedef Log *(*EnableCallback)(lldb::StreamSP &log_stream_sp,
uint32_t log_options, const char **categories,
Stream *feedback_strm);
typedef void (*ListCategoriesCallback)(Stream *strm);
struct Callbacks {
DisableCallback disable;
EnableCallback enable;
ListCategoriesCallback list_categories;
};
//------------------------------------------------------------------
// Static accessors for logging channels
//------------------------------------------------------------------
static void RegisterLogChannel(const ConstString &channel,
const Log::Callbacks &log_callbacks);
static bool UnregisterLogChannel(const ConstString &channel);
static bool GetLogChannelCallbacks(const ConstString &channel,
Log::Callbacks &log_callbacks);
static bool EnableLogChannel(lldb::StreamSP &log_stream_sp,
uint32_t log_options, const char *channel,
const char **categories, Stream &error_stream);
static void EnableAllLogChannels(lldb::StreamSP &log_stream_sp,
uint32_t log_options,
const char **categories,
Stream *feedback_strm);
static void DisableAllLogChannels(Stream *feedback_strm);
static void ListAllLogChannels(Stream *strm);
static void Initialize();
static void Terminate();
//------------------------------------------------------------------
// Auto completion
//------------------------------------------------------------------
static void AutoCompleteChannelName(const char *channel_name,
StringList &matches);
//------------------------------------------------------------------
// Member functions
//------------------------------------------------------------------
Log();
Log(const lldb::StreamSP &stream_sp);
~Log();
void PutCString(const char *cstr);
void PutString(llvm::StringRef str);
template <typename... Args> void Format(const char *fmt, Args &&... args) {
PutString(llvm::formatv(fmt, std::forward<Args>(args)...).str());
}
// CLEANUP: Add llvm::raw_ostream &Stream() function.
void Printf(const char *format, ...) __attribute__((format(printf, 2, 3)));
void VAPrintf(const char *format, va_list args);
void LogIf(uint32_t mask, const char *fmt, ...)
__attribute__((format(printf, 3, 4)));
void Debug(const char *fmt, ...) __attribute__((format(printf, 2, 3)));
void Error(const char *fmt, ...) __attribute__((format(printf, 2, 3)));
void VAError(const char *format, va_list args);
void Verbose(const char *fmt, ...) __attribute__((format(printf, 2, 3)));
void Warning(const char *fmt, ...) __attribute__((format(printf, 2, 3)));
Flags &GetOptions();
const Flags &GetOptions() const;
Flags &GetMask();
const Flags &GetMask() const;
bool GetVerbose() const;
bool GetDebug() const;
void SetStream(const lldb::StreamSP &stream_sp) { m_stream_sp = stream_sp; }
protected:
//------------------------------------------------------------------
// Member variables
//------------------------------------------------------------------
lldb::StreamSP m_stream_sp;
Flags m_options;
Flags m_mask_bits;
private:
DISALLOW_COPY_AND_ASSIGN(Log);
};
class LogChannel : public PluginInterface {
public:
LogChannel();
~LogChannel() override;
static lldb::LogChannelSP FindPlugin(const char *plugin_name);
// categories is an array of chars that ends with a NULL element.
virtual void Disable(const char **categories, Stream *feedback_strm) = 0;
virtual bool
Enable(lldb::StreamSP &log_stream_sp, uint32_t log_options,
Stream *feedback_strm, // Feedback stream for argument errors etc
const char **categories) = 0; // The categories to enable within this
// logging stream, if empty, enable
// default set
virtual void ListCategories(Stream *strm) = 0;
protected:
std::unique_ptr<Log> m_log_ap;
private:
DISALLOW_COPY_AND_ASSIGN(LogChannel);
};
} // namespace lldb_private
#endif // liblldb_Log_h_
| 2,141 |
2,921 | {
"name": "wRipple",
"website": "https://wripple.net",
"description": "Do more something with your Ripple",
"explorer": "https://bscscan.com/token/<KEY>",
"symbol": "wXRP",
"type": "BEP20",
"decimals": 18,
"status": "active",
"id": "0xbbC9Fa4B395FeE68465C2Cd4a88cdE267a34ed2a"
} | 153 |
2,232 | /*
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: <NAME>
*/
#include <string>
#include <iostream>
#include "util/exception.h"
#include "util/bitap_fuzzy_search.h"
namespace lean {
bitap_fuzzy_search::bitap_fuzzy_search(std::string const & pattern, unsigned k):
m_R(k+1) {
if (pattern.size() > 63)
throw exception("pattern is too long");
m_k = k;
m_pattern_size = pattern.size();
for (unsigned i = 0; i < mask_size; i++)
m_pattern_mask[i] = ~static_cast<uint64>(0);
for (unsigned i = 0; i < m_pattern_size; i++) {
unsigned u = static_cast<unsigned char>(pattern[i]);
m_pattern_mask[u] &= ~(static_cast<uint64>(1) << i);
}
}
size_t bitap_fuzzy_search::operator()(std::string const & text) {
if (m_pattern_size == 0)
return 0;
for (unsigned i = 0; i < m_k+1; i++)
m_R[i] = ~static_cast<uint64>(1);
unsigned text_sz = text.size();
for (unsigned i = 0; i < text_sz; i++) {
uint64 old_Rd1 = m_R[0];
unsigned u = static_cast<unsigned char>(text[i]);
uint64 Sc = m_pattern_mask[u];
m_R[0] = (m_R[0] | Sc) << 1;
for (unsigned d = 1; d < m_k+1; d++) {
uint64 tmp = m_R[d];
m_R[d] =
// Case 1. there is a match with <= d errors upto this point, and
// current character is matching
((m_R[d] | Sc) << 1) &
// Case 2. there is a match with <= d-1 errors upto this point.
// This case corresponds to substitution.
(old_Rd1 << 1) &
// Case 3. there is a match with <= d-1 errors upto this point.
// This case corresponds to deletion.
(m_R[d-1] << 1) &
// Case 3. there is a match with <= d-1 errors upto this point.
// This case corresponds to insertion.
old_Rd1;
old_Rd1 = tmp;
}
if ((m_R[m_k] & (static_cast<uint64>(1) << m_pattern_size)) == 0)
return i - m_pattern_size + 1;
}
return std::string::npos;
}
}
| 1,077 |
6,034 | <gh_stars>1000+
package cn.iocoder.mall.managementweb.controller.pay;
import cn.iocoder.common.framework.vo.CommonResult;
import cn.iocoder.common.framework.vo.PageResult;
import cn.iocoder.mall.managementweb.controller.pay.vo.transaction.PayTransactionPageReqVO;
import cn.iocoder.mall.managementweb.controller.pay.vo.transaction.PayTransactionRespVO;
import cn.iocoder.mall.managementweb.service.pay.transaction.PayTransactionService;
import cn.iocoder.security.annotations.RequiresPermissions;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import static cn.iocoder.common.framework.vo.CommonResult.success;
@Api("支付交易单 API")
@RestController
@RequestMapping("/pay/transaction")
@Validated
@Slf4j
public class PayTransactionController {
@Autowired
private PayTransactionService payTransactionService;
@GetMapping("/page")
@RequiresPermissions("pay:transaction:page")
@ApiOperation("获得交易支付单分页")
public CommonResult<PageResult<PayTransactionRespVO>> pagePayTransaction(PayTransactionPageReqVO pageReqVO) {
// 执行查询
return success(payTransactionService.pagePayTransaction(pageReqVO));
}
}
| 538 |
560 | <reponame>isayapin/cracking-the-coding-interview
/*
Chapter 01 - Problem 05 - One Away - CTCI 6th Edition page 91
Problem Statement:
There are three types of edits that can be performed on strings:
insert a character, remove a character, or replace a character.
Given two strings, write a function to check if they are one edit (or zero edits) away.
Example:
pale, ple -> true
pales, pale -> true
pale, bale -> true
pale, bae -> false
Solution:
1. If the strings differ in length by more than 1 character, return false.
2. If two strings differ in length by exactly one character, then search for an insertion / removal.
Traverse each string until a difference is found. If a difference is found, advance the index of the
longer string by 1 and the index of the shorter string by 0. If another difference is found, return false.
If no other difference is found, return true.
3. If the strings have the same length, search for a replacement: traverse each string counting differences.
If more than one difference is found, return false else return true.
Time complexity: O(N) where N is the length of the shorter string.
Space complexity: O(1)
*/
#include "problem_01_05_oneAway.h"
#include <stdlib.h>
#include <assert.h>
bool searchInsertion(const std::string &s1, const std::string &s2) {
assert(abs(static_cast<int>(s1.size() - s2.size())) == 1);
int i1 = 0, i2 = 0;
bool foundDifference = false;
while (i1 < s1.size() && i2 < s2.size()){
if (s1[i1] != s2[i2]){
if (foundDifference){ // if difference already found, return false
return false;
}
foundDifference = true;
if (s1.size() > s2.size()){ // if first difference found, assume we've found the place where a char was inserted
i1 ++;
} else {
i2 ++;
}
} else { // if no difference, continue iterating as normal
i1 ++;
i2 ++;
}
}
return true;
}
bool searchReplacement(const std::string &s1, const std::string &s2) {
assert(s1.size() == s2.size());
int i = 0;
bool foundDifference = false;
while (i < s1.size()){
if (s1[i] != s2[i]){
if (foundDifference){ // if more that one difference found, return false
return false;
}
foundDifference = true;
}
i ++;
}
return true;
}
bool chapter_01::oneAway(const std::string &s1, const std::string &s2) {
int len_difference = abs(static_cast<int>(s1.size() - s2.size()));
if (len_difference > 1){ // different by more than 1 edit: return false
return false;
}
if (len_difference == 1){ // different by exactly one edit: could be an insertion / removal
return searchInsertion(s1, s2);
}
return searchReplacement(s1, s2); // same length: could be a replacement
} | 1,117 |
488 | <reponame>ouankou/rose
float foo(int f, float a, float b)
{
float c;
#pragma aitool fp_plus(1) fp_multiply(1)
switch(f)
{
case 1:
c = a+b;
c = c*b;
break;
case 2:
c = a-b;
break;
default:
break;
}
return c;
}
| 168 |
19,438 | <filename>AK/Platform.h<gh_stars>1000+
/*
* Copyright (c) 2018-2020, <NAME> <<EMAIL>>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
#ifdef __i386__
# define AK_ARCH_I386 1
#endif
#ifdef __x86_64__
# define AK_ARCH_X86_64 1
#endif
#ifdef __aarch64__
# define AK_ARCH_AARCH64 1
#endif
#if defined(__APPLE__) && defined(__MACH__)
# define AK_OS_MACOS
# define AK_OS_BSD_GENERIC
#endif
#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)
# define AK_OS_BSD_GENERIC
#endif
#define ARCH(arch) (defined(AK_ARCH_##arch) && AK_ARCH_##arch)
#if ARCH(I386) || ARCH(X86_64)
# define VALIDATE_IS_X86()
#else
# define VALIDATE_IS_X86() static_assert(false, "Trying to include x86 only header on non x86 platform");
#endif
#if !defined(__clang__) && !defined(__CLION_IDE_)
# define AK_HAS_CONDITIONALLY_TRIVIAL
#endif
#ifdef ALWAYS_INLINE
# undef ALWAYS_INLINE
#endif
#define ALWAYS_INLINE __attribute__((always_inline)) inline
#ifdef NEVER_INLINE
# undef NEVER_INLINE
#endif
#define NEVER_INLINE __attribute__((noinline))
#ifdef FLATTEN
# undef FLATTEN
#endif
#define FLATTEN __attribute__((flatten))
#ifdef RETURNS_NONNULL
# undef RETURNS_NONNULL
#endif
#define RETURNS_NONNULL __attribute__((returns_nonnull))
#ifdef NO_SANITIZE_ADDRESS
# undef NO_SANITIZE_ADDRESS
#endif
#define NO_SANITIZE_ADDRESS __attribute__((no_sanitize_address))
#ifdef NAKED
# undef NAKED
#endif
#define NAKED __attribute__((naked))
#ifdef DISALLOW
# undef DISALLOW
#endif
#ifdef __clang__
# define DISALLOW(message) __attribute__((diagnose_if(1, message, "error")))
#else
# define DISALLOW(message) __attribute__((error(message)))
#endif
// GCC doesn't have __has_feature but clang does
#ifndef __has_feature
# define __has_feature(...) 0
#endif
#if __has_feature(address_sanitizer) || defined(__SANITIZE_ADDRESS__)
# define HAS_ADDRESS_SANITIZER
# define ASAN_POISON_MEMORY_REGION(addr, size) __asan_poison_memory_region(addr, size)
# define ASAN_UNPOISON_MEMORY_REGION(addr, size) __asan_unpoison_memory_region(addr, size)
#else
# define ASAN_POISON_MEMORY_REGION(addr, size)
# define ASAN_UNPOISON_MEMORY_REGION(addr, size)
#endif
#ifndef __serenity__
// On macOS (at least Mojave), Apple's version of this header is not wrapped
// in extern "C".
# ifdef AK_OS_MACOS
extern "C" {
# endif
# include <unistd.h>
# undef PAGE_SIZE
# define PAGE_SIZE sysconf(_SC_PAGESIZE)
# ifdef AK_OS_MACOS
};
# endif
#endif
#ifdef AK_OS_BSD_GENERIC
# define CLOCK_MONOTONIC_COARSE CLOCK_MONOTONIC
# define CLOCK_REALTIME_COARSE CLOCK_REALTIME
#endif
| 1,135 |
879 | package org.zstack.network.l2.vxlan.vxlanNetworkPool;
import org.springframework.beans.factory.annotation.Autowired;
import org.zstack.core.Platform;
import org.zstack.core.db.DatabaseFacade;
import org.zstack.core.db.Q;
import org.zstack.core.errorcode.ErrorFacade;
import org.zstack.header.errorcode.OperationFailureException;
import org.zstack.header.network.l2.L2Errors;
import org.zstack.network.l2.L2NetworkManager;
import org.zstack.network.l2.vxlan.vxlanNetwork.VxlanNetworkVO;
import org.zstack.network.l2.vxlan.vxlanNetwork.VxlanNetworkVO_;
import org.zstack.utils.CollectionUtils;
import org.zstack.utils.function.Function;
import java.util.List;
/**
* Created by weiwang on 10/03/2017.
*/
public abstract class AbstractVniAllocatorStrategy implements VniAllocatorStrategy {
@Autowired
protected DatabaseFacade dbf;
@Autowired
protected L2NetworkManager l2NwMgr;
@Autowired
protected ErrorFacade errf;
protected Integer allocateRequiredVni(VniAllocateMessage msg) {
List<VniRangeVO> vnirs = Q.New(VniRangeVO.class).eq(VniRangeVO_.l2NetworkUuid, msg.getL2NetworkUuid()).list();
final int rvni = msg.getRequiredVni();
VniRangeVO vnir = CollectionUtils.find(vnirs, new Function<VniRangeVO, VniRangeVO>() {
@Override
public VniRangeVO call(VniRangeVO arg) {
int s = arg.getStartVni();
int e = arg.getEndVni();
return s <= rvni && rvni <= e ? arg : null;
}
});
String duplicate = Q.New(VxlanNetworkVO.class).select(VxlanNetworkVO_.uuid).eq(VxlanNetworkVO_.vni, msg.getRequiredVni()).eq(VxlanNetworkVO_.poolUuid, msg.getL2NetworkUuid()).findValue();
if (vnir == null) {
throw new OperationFailureException(Platform.err(L2Errors.ALLOCATE_VNI_ERROR,
"cannot allocate vni[%s] in l2Network[uuid:%s], out of vni range", msg.getRequiredVni(), msg.getL2NetworkUuid()
));
} else if (duplicate != null) {
throw new OperationFailureException(Platform.err(L2Errors.ALLOCATE_VNI_ERROR,
"cannot allocate vni[%s] in l2Network[uuid:%s], duplicate with l2Network[uuid:%s]", msg.getRequiredVni(), msg.getL2NetworkUuid(), duplicate));
}
return rvni;
}
}
| 985 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.