max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
344 |
<reponame>jbellis/superpixel-benchmark<gh_stars>100-1000
#include "PDS.hpp"
#include "Tools.hpp"
#include <density/ScalePyramid.hpp>
namespace pds
{
namespace spds_old
{
void FindSeedsDepthMipmap_Walk(
std::vector<Eigen::Vector2f>& seeds,
const std::vector<Eigen::MatrixXf>& mipmaps,
int level, unsigned int x, unsigned int y)
{
static boost::uniform_real<float> rnd(0.0f, 1.0f);
static boost::variate_generator<boost::mt19937&, boost::uniform_real<float> > die(impl::Rnd(), rnd);
float v = mipmaps[level](x, y);
if(v > 1.0f && level > 0) { // do not access mipmap 0!
// go down
FindSeedsDepthMipmap_Walk(seeds, mipmaps, level - 1, 2*x, 2*y );
FindSeedsDepthMipmap_Walk(seeds, mipmaps, level - 1, 2*x, 2*y + 1);
FindSeedsDepthMipmap_Walk(seeds, mipmaps, level - 1, 2*x + 1, 2*y );
FindSeedsDepthMipmap_Walk(seeds, mipmaps, level - 1, 2*x + 1, 2*y + 1);
}
else {
if(die() <= v) {
seeds.push_back(
impl::RandomCellPoint(1 << level, x, y, 0.38f));
}
}
}
std::vector<Eigen::Vector2f> FindSeedsDepthMipmap(const Eigen::MatrixXf& density)
{
// compute mipmaps
std::vector<Eigen::MatrixXf> mipmaps = density::ComputeMipmaps(density, 1);
#ifdef CREATE_DEBUG_IMAGES
//DebugMipmap<2>(mipmaps, "mm");
for(unsigned int i=0; i<mipmaps.size(); i++) {
std::string tag = (boost::format("mm_%1d") % i).str();
DebugShowMatrix(mipmaps[i], tag);
DebugWriteMatrix(mipmaps[i], tag);
}
#endif
// sample points
std::vector<Eigen::Vector2f> seeds;
FindSeedsDepthMipmap_Walk(seeds, mipmaps, mipmaps.size() - 1, 0, 0);
// scale points with base constant
impl::ScalePoints(seeds, 2.f);
return seeds;
}
std::vector<Eigen::Vector2f> FindSeedsDepthMipmap640(const Eigen::MatrixXf& density)
{
// compute mipmaps
std::vector<Eigen::MatrixXf> mipmaps = density::ComputeMipmaps640x480(density);
#ifdef CREATE_DEBUG_IMAGES
DebugMipmap<5>(mipmaps, "mm640");
for(unsigned int i=0; i<mipmaps.size(); i++) {
std::string tag = (boost::format("mm640_%1d") % i).str();
DebugShowMatrix(mipmaps[i], tag);
DebugWriteMatrix(mipmaps[i], tag);
}
#endif
// now create pixel seeds
std::vector<Eigen::Vector2f> seeds;
const unsigned int l0 = mipmaps.size() - 1;
for(unsigned int y=0; y<mipmaps[l0].cols(); ++y) {
for(unsigned int x=0; x<mipmaps[l0].rows(); x++) {
FindSeedsDepthMipmap_Walk(seeds, mipmaps, l0, x, y);
}
}
// scale points with base constant
impl::ScalePoints(seeds, 5.f);
return seeds;
}
}
std::vector<Eigen::Vector2f> SimplifiedPDSOld(const Eigen::MatrixXf& density)
{
if(density.rows() == 640 && density.cols() == 480) {
return spds_old::FindSeedsDepthMipmap640(density);
}
else {
return spds_old::FindSeedsDepthMipmap(density);
}
}
}
| 1,299 |
812 |
/*
* Copyright (C) 2016 Appflate.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 io.appflate.restmock;
import java.net.InetAddress;
import java.net.UnknownHostException;
import okhttp3.tls.HandshakeCertificates;
import okhttp3.tls.HeldCertificate;
//DISCLAIMER
// since android does not support ECDSA by default, I've copied this code from OkHttp's tests and replaced the algorithm with RSA
public class SslUtils {
private static HandshakeCertificates localhost; // Lazily initialized.
private SslUtils() {
}
/** Returns an SSL client for this host's localhost address. */
public static synchronized HandshakeCertificates localhost() {
if (localhost != null) return localhost;
try {
// Generate a self-signed cert for the server to serve and the client to trust.
HeldCertificate heldCertificate = new HeldCertificate.Builder()
.rsa2048()
.commonName("localhost")
.addSubjectAlternativeName(InetAddress.getByName("localhost").getCanonicalHostName())
.build();
localhost = new HandshakeCertificates.Builder()
.heldCertificate(heldCertificate)
.addTrustedCertificate(heldCertificate.certificate())
.build();
return localhost;
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
}
}
| 686 |
350 |
/*
* Copyright (c) 2009 <NAME> <<EMAIL>>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package lljvm.io;
import java.io.IOException;
import lljvm.runtime.Error;
import lljvm.runtime.Memory;
/**
* A minimal implementation of the FileHandle interface.
*
* @author <NAME>
*/
public abstract class AbstractFileHandle implements FileHandle {
/** Specifies whether this file descriptor supports reading */
protected final boolean read;
/** Specifies whether this file descriptor supports writing */
protected final boolean write;
/** Specifies whether to enable synchronous I/O */
protected final boolean synchronous;
/**
* Construct a new instance with the given read/write capabilities.
*
* @param read specifies whether this file descriptor supports
* reading
* @param write specifies whether this file descriptor supports
* writing
*/
protected AbstractFileHandle(boolean read, boolean write,
boolean synchronous) {
this.read = read;
this.write = write;
this.synchronous = synchronous;
}
/**
* Reads the next byte of data.
*
* @return the next byte of data, or -1 on EOF
* @throws IOException if an I/O error occurs
*/
protected int read() throws IOException {
return -1;
}
/**
* Returns true if there is at least one byte available for reading.
*
* @return true if there is at least one byte available
* for reading
* @throws IOException if an I/O error occurs
*/
protected boolean available() throws IOException {
return false;
}
public int read(int buf, int count) {
if(!read)
return Error.errno(Error.EINVAL);
int num_bytes = 0;
try {
while(num_bytes < count) {
int b = read();
if(b < 0)
break;
Memory.store(buf++, (byte) b);
num_bytes++;
if(!available())
break;
}
} catch(IOException e) {
return Error.errno(Error.EIO);
}
return num_bytes;
}
/**
* Writes the given byte.
*
* @param b the byte to be written
* @throws IOException if an I/O error occurs
*/
protected void write(int b) throws IOException {}
/**
* Forces any buffered bytes to be written.
*
* @throws IOException if an I/O error occurs
*/
protected void flush() throws IOException {}
public int write(int buf, int count) {
if(!write)
return Error.errno(Error.EINVAL);
int num_bytes = 0;
try {
while(num_bytes < count) {
write(Memory.load_i8(buf++));
num_bytes++;
}
if(synchronous)
flush();
} catch(IOException e) {
return Error.errno(Error.EIO);
}
return num_bytes;
}
public int seek(int offset, int whence) {
return Error.errno(Error.ESPIPE);
}
}
| 1,742 |
339 |
#include <Python.h>
typedef struct {
PyObject ob_base;
PyObject* filelike;
PyObject* blksize;
} FileWrapper;
PyTypeObject FileWrapper_Type;
#define FileWrapper_CheckExact(object) ((object)->ob_type == &FileWrapper_Type)
void FileWrapper_Init(void);
| 102 |
645 |
<reponame>xuantan/viewfinder
# Copyright 2011 Viewfinder Inc. All Rights Reserved.
"""Classes to handle file object storage.
Intended for local testing.
FileObjectStore: store files in a temporary directory
FileObjectStoreHandler: serves and stores files on GET and PUT
requests.
"""
__author__ = '<EMAIL> (<NAME>)'
import atexit
import base64
import errno
import logging
import os
import shutil
import tempfile
import time
import functools
from tornado import gen, options, web
from tornado.ioloop import IOLoop
from viewfinder.backend.base import constants, handler, util
from viewfinder.backend.storage.object_store import ObjectStore
def GetS3CompatibleFileList(root, prefix=None):
"""Returns a list of filenames from the local object store
which emulates the sorting order of keys returned from an
AWS S3 file store.
"""
def _ListFiles(dir):
for obj in os.listdir(dir):
objpath = os.path.join(dir, obj)
if os.path.isfile(objpath):
yield os.path.relpath(objpath, root)
elif os.path.isdir(objpath):
for f in _ListFiles(objpath):
yield f
filelist = [x for x in _ListFiles(root) if not prefix or x.startswith(prefix)]
return sorted(filelist)
class FileObjectStore(ObjectStore):
"""Simple object storage interface supporting key/value pairs backed
by the file system. URLs are created based on a supplied URL which
is formatted with the key name.
"""
def __init__(self, bucket_name, temporary=False, read_only=False):
logging.info('initializing local file object store bucket %s' % bucket_name)
self._read_only = read_only
if temporary:
dir = tempfile.mkdtemp()
atexit.register(shutil.rmtree, dir)
self._bucket_name = os.path.join(dir, bucket_name)
else:
self._bucket_name = os.path.join(options.options.fileobjstore_dir, bucket_name)
try:
if options.options.fileobjstore_reset:
logging.warning('clearing file object store')
shutil.rmtree(self._bucket_name)
except:
pass
def _MakePath(self, key):
return os.path.join(self._bucket_name, key)
def Put(self, key, value, callback, content_type=None, request_timeout=None):
assert not self._read_only, 'Received "Put" request on read-only object store.'
# Only support byte strings.
assert not value or type(value) is str, \
'Put does not support type "%s". Only byte strings are supported.' % type(value)
path = self._MakePath(key)
try:
os.makedirs(os.path.dirname(path))
except:
pass
fp = open(path, 'wb')
try:
fp.write(value)
IOLoop.current().add_callback(callback)
finally:
fp.close()
def Get(self, key, callback, must_exist=True):
path = self._MakePath(key)
# First attempt to open the file and catch "no such file" exception.
try:
fp = open(path, 'rb')
except IOError as e:
if must_exist or e.errno != errno.ENOENT:
raise
else:
IOLoop.current().add_callback(functools.partial(callback, None))
return
# Now read it.
try:
value = fp.read()
IOLoop.current().add_callback(functools.partial(callback, value))
finally:
fp.close()
def ListKeys(self, callback, prefix=None, marker=None, maxkeys=None):
maxkeys = min(maxkeys, 1000) if maxkeys else 1000
filelist = GetS3CompatibleFileList(self._bucket_name, prefix)
index = 0
if marker:
# Marker is "excluded first key". It does not have to match an existing key.
for f in filelist:
if f == marker:
index += 1
break
elif f > marker:
break
index += 1
IOLoop.current().add_callback(functools.partial(callback, filelist[index:index + maxkeys]))
@gen.engine
def ListCommonPrefixes(self, delimiter, callback, prefix=None, marker=None, maxkeys=None):
# We can just call ListKeys with no limit, then compute the prefixes.
assert delimiter is not None, 'delimiter arg is required on ListCommonPrefixes'
file_list = yield gen.Task(self.ListKeys, prefix=prefix, marker=marker, maxkeys=None)
prefixes = set()
keys = []
prefix_length = len(prefix) if prefix else 0
for f in file_list:
# We search for the first occurence of the delimiter after the prefix.
ind = f.find(delimiter, prefix_length)
if ind != -1:
prefixes.add(f[0:ind + 1]) # include the delimiter
else:
keys.append(f)
if maxkeys is not None and (len(prefixes) + len(keys)) >= maxkeys:
break
IOLoop.current().add_callback(functools.partial(callback, (sorted(prefixes), keys)))
def Delete(self, key, callback):
assert not self._read_only, 'Received "Delete" request on read-only object store.'
path = self._MakePath(key)
try:
os.remove(path)
IOLoop.current().add_callback(callback)
except:
pass
def SetUrlFmtString(self, url_fmt_str):
self._url_fmt_str = url_fmt_str
def GenerateUrl(self, key, method='GET', cache_control=None, expires_in=constants.SECONDS_PER_DAY,
content_type=None):
assert self._url_fmt_str
url = self._url_fmt_str % key
if cache_control is not None:
url += '?response-cache-control=%s' % cache_control
return url
def GenerateUploadUrl(self, key, content_type=None, content_md5=None,
expires_in=constants.SECONDS_PER_DAY, max_bytes=5 << 20):
assert self._url_fmt_str
url = self._url_fmt_str % key
if content_md5 is not None:
# Re-encode Content-MD5 value in URL friendly format.
url += '?MD5=%s' % base64.b64decode(content_md5).encode('hex')
return url
class FileObjectStoreHandler(web.RequestHandler):
"""Simple request handler which returns contents of specified key in
response on a 'GET' or 'HEAD' request, or 404 if not found. An
object may be stored by making a 'PUT' request and supplying the
object contents in the request body.
"""
_CACHE_MAX_AGE = 86400 * 365 * 10 #10 years
def initialize(self, storename, contenttype):
self.content_type = contenttype
self.object_store = ObjectStore.GetInstance(storename)
@handler.asynchronous()
def get(self, key):
self._Get(key)
@handler.asynchronous()
def head(self, key):
self._Get(key, include_body=False)
@handler.asynchronous()
def put(self, key):
def _OnCompletedPut():
self.finish()
# Check that Content-MD5 header matches the MD5 query argument (if it's specified).
expected_md5 = self.get_argument('MD5', None)
if expected_md5 is not None:
if 'Content-MD5' not in self.request.headers:
raise web.HTTPError(400, 'expected Content-MD5 "%s", received nothing' % expected_md5)
actual_md5 = base64.b64decode(self.request.headers['Content-MD5']).encode('hex')
if actual_md5 != expected_md5:
raise web.HTTPError(400, 'expected Content-MD5 "%s", received "%s"' %
(expected_md5, actual_md5))
self.object_store.Put(key, self.request.body, callback=_OnCompletedPut)
def _Get(self, key, include_body=True):
# On error, return 404 to client.
def _OnError(type, value, traceback):
self.send_error(404)
def _OnCompletedGet(content):
md5_hex = util.ComputeMD5Hex(content)
self.set_header("Expires", int(time.time()) + FileObjectStoreHandler._CACHE_MAX_AGE)
self.set_header('Content-Type', self.content_type)
self.set_header('Content-Length', len(content))
self.set_header('Content-MD5', md5_hex)
self.set_header('Etag', '"%s"' % md5_hex)
cache_control = self.get_argument('response-cache-control', None)
if cache_control is not None:
self.set_header("Cache-Control", cache_control)
if include_body:
self.write(content)
self.finish()
with util.MonoBarrier(_OnCompletedGet, on_exception=_OnError) as b:
self.object_store.Get(key, b.Callback())
def check_xsrf_cookie(self):
"""Override tornado's xsrf cookie check.
S3 doesn't require XSRF, so we won't expect it for the file object store in the local server.
"""
pass
| 3,110 |
665 |
<filename>testing/MLDB-1911_horizontal_agg_no_from.py<gh_stars>100-1000
#
# MLDB-1911_horizontal_agg_no_from.py
# <NAME>, 2016-09-30
# This file is part of MLDB. Copyright 2016 mldb.ai inc. All rights reserved.
#
import unittest
from mldb import mldb, MldbUnitTest, ResponseException
class Mldb1911HorizontalAggNoFrom(MldbUnitTest): # noqa
@classmethod
def setUpClass(cls):
# useless dataset to compare results with a FROM clause
ds = mldb.create_dataset({'id' : 'ds', 'type' : 'sparse.mutable'})
ds.record_row('row1', [['A', 1, 0]])
ds.commit()
@unittest.expectedFailure
def test_sum(self):
expected = [
['_rowName', 'horizontal_sum({1 AS a, 2 AS b})'],
['row1', 3]
]
# works
res = mldb.query("SELECT horizontal_sum({1 AS a, 2 AS b}) FROM ds")
self.assertTableResultEquals(res, expected)
# fails
res = mldb.query("SELECT horizontal_sum({1 AS a, 2 AS b})")
self.assertTableResultEquals(res, expected)
@unittest.expectedFailure
def test_count(self):
expected = [
['_rowName', 'horizontal_count({1 AS a, 2 AS b})'],
['row1', 2]
]
# works
res = mldb.query("SELECT horizontal_count({1 AS a, 2 AS b}) FROM ds")
self.assertTableResultEquals(res, expected)
# fails
res = mldb.query("SELECT horizontal_count({1 AS a, 2 AS b})")
self.assertTableResultEquals(res, expected)
@unittest.expectedFailure
def test_min(self):
expected = [
['_rowName', 'horizontal_min({1 AS a, 2 AS b})'],
['row1', 1]
]
# works
res = mldb.query("SELECT horizontal_min({1 AS a, 2 AS b}) FROM ds")
self.assertTableResultEquals(res, expected)
# fails
res = mldb.query("SELECT horizontal_min({1 AS a, 2 AS b})")
self.assertTableResultEquals(res, expected)
# TODO Add tests for the other horizontal aggregators.
if __name__ == '__main__':
mldb.run_tests()
| 938 |
980 |
package org.jcodec.movtool.streaming;
import java.lang.IllegalStateException;
import java.lang.System;
import java.lang.IllegalArgumentException;
import org.jcodec.common.io.NIOUtils;
import org.jcodec.platform.BaseInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
/**
* This class is part of JCodec ( www.jcodec.org ) This software is distributed
* under FreeBSD License
*
* Retrieves a movie range
*
* @author The JCodec project
*
*/
public class MovieRange extends BaseInputStream {
private VirtualMovie movie;
private long remaining;
private int chunkNo;
private ByteBuffer chunkData;
public MovieRange(VirtualMovie movie, long from, long to) throws IOException {
if (to < from)
throw new IllegalArgumentException("from < to");
this.movie = movie;
MovieSegment chunk = movie.getPacketAt(from);
this.remaining = to - from + 1;
if (chunk != null) {
chunkData = checkDataLen(chunk.getData(), chunk.getDataLen());
chunkNo = chunk.getNo();
NIOUtils.skip(chunkData, (int) (from - chunk.getPos()));
}
}
static ByteBuffer checkDataLen(ByteBuffer chunkData, int chunkDataLen) throws IOException {
if(chunkData == null) {
System.err.println("WARN: packet expected data len != actual data len " + chunkDataLen + " != 0"
);
return ByteBuffer.allocate(chunkDataLen);
}
if (chunkData.remaining() != chunkDataLen) {
System.err.println("WARN: packet expected data len != actual data len " + chunkDataLen + " != "
+ chunkData.remaining());
chunkDataLen = Math.max(0, chunkDataLen);
if (chunkDataLen < chunkData.remaining() || chunkData.capacity() - chunkData.position() >= chunkDataLen) {
chunkData.limit(chunkData.position() + chunkDataLen);
} else {
ByteBuffer correct = ByteBuffer.allocate(chunkDataLen);
correct.put(chunkData);
correct.clear();
return correct;
}
}
return chunkData;
}
@Override
public int readBuffer(byte[] b, int from, int len) throws IOException {
tryFetch();
if (chunkData == null || remaining == 0)
return -1;
len = (int) Math.min(remaining, len);
int totalRead = 0;
while (len > 0) {
int toRead = Math.min(chunkData.remaining(), len);
chunkData.get(b, from, toRead);
totalRead += toRead;
len -= toRead;
from += toRead;
tryFetch();
if (chunkData == null)
break;
}
remaining -= totalRead;
return totalRead;
}
private void tryFetch() throws IOException {
if (chunkData == null || !chunkData.hasRemaining()) {
MovieSegment chunk = movie.getPacketByNo(chunkNo + 1);
if (chunk != null) {
chunkData = checkDataLen(chunk.getData(), chunk.getDataLen());
chunkNo = chunk.getNo();
} else
chunkData = null;
}
}
@Override
public int readByte() throws IOException {
tryFetch();
if (chunkData == null || remaining == 0)
return -1;
--remaining;
return chunkData.get() & 0xff;
}
}
| 1,531 |
2,209 |
//
// Created by <NAME> on 2019-06-10.
//
#include <kungfu/yijinjing/util/os.h>
namespace kungfu {
namespace yijinjing {
namespace util {
}
}
}
| 83 |
984 |
<filename>phoenix-core/src/main/java/org/apache/phoenix/mapreduce/index/IndexVerificationOutputRow.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.phoenix.mapreduce.index;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.phoenix.mapreduce.index.IndexVerificationOutputRepository.IndexVerificationErrorType;
import java.util.Arrays;
import java.util.Objects;
public class IndexVerificationOutputRow {
public static final String SCAN_MAX_TIMESTAMP = "ScanMaxTimestamp: ";
private String dataTableName;
private String indexTableName;
private Long scanMaxTimestamp;
private byte[] dataTableRowKey;
private byte[] indexTableRowKey;
private Long dataTableRowTimestamp;
private Long indexTableRowTimestamp;
private String errorMessage;
private byte[] expectedValue;
private byte[] actualValue;
private byte[] phaseValue;
private IndexVerificationErrorType errorType;
private IndexVerificationOutputRow(String dataTableName, String indexTableName,
byte[] dataTableRowKey, Long scanMaxTimestamp,
byte[] indexTableRowKey,
long dataTableRowTimestamp, long indexTableRowTimestamp,
String errorMessage, byte[] expectedValue, byte[] actualValue,
byte[] phaseValue, IndexVerificationErrorType errorType) {
this.dataTableName = dataTableName;
this.indexTableName = indexTableName;
this.scanMaxTimestamp = scanMaxTimestamp;
this.dataTableRowKey = dataTableRowKey;
this.indexTableRowKey = indexTableRowKey;
this.dataTableRowTimestamp = dataTableRowTimestamp;
this.indexTableRowTimestamp = indexTableRowTimestamp;
this.errorMessage = errorMessage;
this.expectedValue = expectedValue;
this.actualValue = actualValue;
this.phaseValue = phaseValue;
this.errorType = errorType;
}
public String getDataTableName() {
return dataTableName;
}
public String getIndexTableName() {
return indexTableName;
}
public Long getScanMaxTimestamp() {
return scanMaxTimestamp;
}
public byte[] getIndexTableRowKey() {
return indexTableRowKey;
}
public long getIndexTableRowTimestamp() {
return indexTableRowTimestamp;
}
public String getErrorMessage() {
return errorMessage;
}
public byte[] getExpectedValue() {
return expectedValue;
}
public byte[] getActualValue() {
return actualValue;
}
public byte[] getPhaseValue() {
return phaseValue;
}
public byte[] getDataTableRowKey() {
return dataTableRowKey;
}
public Long getDataTableRowTimestamp() {
return dataTableRowTimestamp;
}
@Override
public boolean equals(Object o) {
if (o == null ) {
return false;
}
if (!(o instanceof IndexVerificationOutputRow)) {
return false;
}
IndexVerificationOutputRow otherRow = (IndexVerificationOutputRow) o;
return Objects.equals(dataTableName, otherRow.getDataTableName()) &&
Objects.equals(indexTableName, otherRow.getIndexTableName()) &&
Objects.equals(scanMaxTimestamp, otherRow.getScanMaxTimestamp()) &&
Arrays.equals(dataTableRowKey, otherRow.getDataTableRowKey()) &&
Arrays.equals(indexTableRowKey, otherRow.getIndexTableRowKey()) &&
Objects.equals(dataTableRowTimestamp, otherRow.getDataTableRowTimestamp()) &&
Objects.equals(indexTableRowTimestamp, otherRow.getIndexTableRowTimestamp()) &&
Objects.equals(errorMessage, otherRow.getErrorMessage()) &&
Arrays.equals(expectedValue, otherRow.getExpectedValue()) &&
Arrays.equals(actualValue, otherRow.getActualValue()) &&
Arrays.equals(phaseValue, otherRow.getPhaseValue()) &&
Objects.equals(errorType, otherRow.getErrorType());
}
@Override
public int hashCode(){
return Objects.hashCode(scanMaxTimestamp) ^ Objects.hashCode(indexTableName) ^
Arrays.hashCode(dataTableRowKey);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(IndexVerificationOutputRepository.DATA_TABLE_NAME + ": ").append(dataTableName).append(",");
sb.append(IndexVerificationOutputRepository.INDEX_TABLE_NAME + ": ").append(indexTableName).append(",");
sb.append(SCAN_MAX_TIMESTAMP).append(": ").append(scanMaxTimestamp).append(",");
sb.append(IndexVerificationOutputRepository.DATA_TABLE_ROW_KEY + ": ").append(Bytes.toString(dataTableRowKey)).append(",");
sb.append(IndexVerificationOutputRepository.INDEX_TABLE_ROW_KEY + ": ").append(Bytes.toString(indexTableRowKey)).append(",");
sb.append(IndexVerificationOutputRepository.DATA_TABLE_TS + ": ").append(dataTableRowTimestamp).append(",");
sb.append(IndexVerificationOutputRepository.INDEX_TABLE_TS + ": ").append(indexTableRowTimestamp).append(",");
sb.append(IndexVerificationOutputRepository.ERROR_MESSAGE + ": ").append(errorMessage).append(",");
sb.append(IndexVerificationOutputRepository.EXPECTED_VALUE + ": ").append(Bytes.toString(expectedValue)).append(",");
sb.append(IndexVerificationOutputRepository.ACTUAL_VALUE + ": ").append(Bytes.toString(actualValue)).append(
",");
sb.append(IndexVerificationOutputRepository.VERIFICATION_PHASE + ": ").append(Bytes.toString(phaseValue));
sb.append(IndexVerificationOutputRepository.ERROR_TYPE + ": " ).append(Objects.toString(errorType));
return sb.toString();
}
public IndexVerificationErrorType getErrorType() {
return errorType;
}
public static class IndexVerificationOutputRowBuilder {
private String dataTableName;
private String indexTableName;
private Long scanMaxTimestamp;
private byte[] dataTableRowKey;
private byte[] indexTableRowKey;
private long dataTableRowTimestamp;
private long indexTableRowTimestamp;
private String errorMessage;
private byte[] expectedValue;
private byte[] actualValue;
private byte[] phaseValue;
private IndexVerificationErrorType errorType;
public IndexVerificationOutputRowBuilder setDataTableName(String dataTableName) {
this.dataTableName = dataTableName;
return this;
}
public IndexVerificationOutputRowBuilder setIndexTableName(String indexTableName) {
this.indexTableName = indexTableName;
return this;
}
public IndexVerificationOutputRowBuilder setScanMaxTimestamp(Long scanMaxTimestamp) {
this.scanMaxTimestamp = scanMaxTimestamp;
return this;
}
public IndexVerificationOutputRowBuilder setIndexTableRowKey(byte[] indexTableRowKey) {
this.indexTableRowKey = indexTableRowKey;
return this;
}
public IndexVerificationOutputRowBuilder setDataTableRowKey(byte[] dataTableRowKey){
this.dataTableRowKey = dataTableRowKey;
return this;
}
public IndexVerificationOutputRowBuilder setDataTableRowTimestamp(long dataTableRowTimestamp) {
this.dataTableRowTimestamp = dataTableRowTimestamp;
return this;
}
public IndexVerificationOutputRowBuilder setIndexTableRowTimestamp(long indexTableRowTimestamp) {
this.indexTableRowTimestamp = indexTableRowTimestamp;
return this;
}
public IndexVerificationOutputRowBuilder setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
return this;
}
public IndexVerificationOutputRowBuilder setExpectedValue(byte[] expectedValue) {
this.expectedValue = expectedValue;
return this;
}
public IndexVerificationOutputRowBuilder setActualValue(byte[] actualValue) {
this.actualValue = actualValue;
return this;
}
public IndexVerificationOutputRowBuilder setPhaseValue(byte[] phaseValue) {
this.phaseValue = phaseValue;
return this;
}
public IndexVerificationOutputRowBuilder setErrorType(IndexVerificationErrorType errorType) {
this.errorType = errorType;
return this;
}
public IndexVerificationOutputRow build() {
return new IndexVerificationOutputRow(dataTableName, indexTableName, dataTableRowKey,
scanMaxTimestamp, indexTableRowKey, dataTableRowTimestamp, indexTableRowTimestamp,
errorMessage, expectedValue, actualValue, phaseValue, errorType);
}
}
}
| 3,708 |
356 |
#include "axis.h"
#include <utils/drawable.h>
#include "model.h"
#include "node.h"
#include "spatial.h"
#include "light.h"
#include <utils/nk.h>
#include <utils/shader.h>
#include <systems/editmode.h>
#include <systems/window.h>
#include <candle.h>
#define SCALE 0.25f
static mesh_t *g_rot_axis_mesh = NULL;
static void c_axis_init(c_axis_t *self)
{
if(!g_rot_axis_mesh)
{
g_rot_axis_mesh = mesh_torus(0.5f * SCALE, 0.02f * SCALE, 32, 3);
g_rot_axis_mesh->has_texcoords = 0;
}
}
int c_axis_press(c_axis_t *self, model_button_data *event)
{
c_mouse_t *mouse;
if(event->button != CANDLE_MOUSE_BUTTON_LEFT) return CONTINUE;
mouse = c_mouse(self);
c_mouse_visible(mouse, false);
c_mouse_activate(mouse, false);
return STOP;
}
int c_axis_release(c_axis_t *self, mouse_button_data *event)
{
c_mouse_t *mouse = c_mouse(self);
if(c_mouse_active(mouse))
{
c_mouse_deactivate(mouse);
}
return CONTINUE;
}
int c_axis_mouse_move(c_axis_t *self, mouse_move_data *event)
{
entity_t arrows = c_node(self)->parent;
entity_t target = c_node(&arrows)->parent;
if(target)
{
entity_t parent = c_node(&target)->parent;
float amount = -event->sy * 0.01;
c_spatial_t *sc = c_spatial(&target);
vec3_t dir = self->dir;
if(parent)
{
c_node_t *nc = c_node(&parent);
vec3_t world_dir = c_node_dir_to_global(c_node(&target), dir);
world_dir = vec3_norm(world_dir);
dir = c_node_dir_to_local(nc, world_dir);
}
else
{
dir = quat_mul_vec3(sc->rot_quat, dir);
}
dir = vec3_scale(dir, amount);
if(self->type == 0)
{
c_spatial_set_pos(sc, vec3_add(dir, sc->pos));
}
else if(self->type == 1)
{
if(self->dir.x > 0.0f)
{
c_spatial_rotate_X(sc, amount);
}
else if(self->dir.y > 0.0f)
{
c_spatial_rotate_Y(sc, amount);
}
else if(self->dir.z > 0.0f)
{
c_spatial_rotate_Z(sc, amount);
}
}
else if(self->type == 2)
{
c_spatial_set_scale(sc, vec3_add(vec3_scale(self->dir, amount), sc->scale));
}
}
return CONTINUE;
}
int c_axis_created(c_axis_t *self)
{
entity_signal_same(c_entity(self), sig("mesh_changed"), NULL, NULL);
return CONTINUE;
}
void ct_axis(ct_t *self)
{
ct_init(self, "axis", sizeof(c_axis_t));
ct_set_init(self, (init_cb)c_axis_init);
ct_add_dependency(self, ct_node);
ct_add_dependency(self, ct_mouse);
ct_add_listener(self, ENTITY, 0, sig("entity_created"), c_axis_created);
ct_add_listener(self, ENTITY, 0, sig("model_press"), c_axis_press);
ct_add_listener(self, ENTITY, 0, sig("mouse_release"), c_axis_release);
ct_add_listener(self, ENTITY, 0, sig("mouse_move"), c_axis_mouse_move);
}
c_axis_t *c_axis_new(int type, vecN_t dir)
{
c_axis_t *self = component_new(ct_axis);
mat_t *m = mat_new("m", "default");
mat4f(m, ref("emissive.color"), vec4(_vec3(dir), 0.8f));
mat4f(m, ref("albedo.color"), vec4(_vec3(dir), 0.8f));
#ifdef MESH4
if(dir.w)
{
mat4f(m, ref("emissive.color"), vec4(1.0f, 0.0f, 0.9f, 0.8f));
mat4f(m, ref("albedo.color"), vec4(1.0f, 0.0f, 0.9f, 0.8f));
}
#endif
/* mat4f(m, ref("albedo.color"), vec4(1.0f, 1.0f, 1.0f, 1.0f)); */
self->type = type;
if(type == 0)
{
self->dir_mesh = mesh_new();
mesh_lock(self->dir_mesh);
mesh_circle(self->dir_mesh, 0.02f * SCALE, 8, dir);
mesh_extrude_edges(self->dir_mesh, 1, vecN_(scale)(dir, 0.5f * SCALE), 1.0f, NULL, NULL, NULL);
mesh_extrude_edges(self->dir_mesh, 1, ZN, 1.70f, NULL, NULL, NULL);
mesh_extrude_edges(self->dir_mesh, 1, vecN_(scale)(dir, 0.1f * SCALE), 0.01f, NULL, NULL, NULL);
mesh_unlock(self->dir_mesh);
}
else if(type == 1)
{
self->dir_mesh = g_rot_axis_mesh;
}
else if(type == 2)
{
vecN_t point;
self->dir_mesh = mesh_new();
mesh_lock(self->dir_mesh);
point = vecN_(scale)(dir, 0.5f * SCALE);
mesh_circle(self->dir_mesh, 0.03f * SCALE, 8, dir);
mesh_extrude_edges(self->dir_mesh, 1, point, 1.0f, NULL, NULL, NULL);
mesh_translate(self->dir_mesh, vecN_xyz(point));
mesh_cube(self->dir_mesh, 0.1 * SCALE, 1.0f);
mesh_unlock(self->dir_mesh);
}
entity_add_component(c_entity(self), c_model_new(self->dir_mesh, m, 0, 0));
c_model_set_groups(c_model(self), ref("widget"), ~0, ~0, ref("selectable"));
c_model_set_xray(c_model(self), 1);
c_model_set_vs(c_model(self), widget_vs());
self->dir = vecN_xyz(dir);
return self;
}
| 2,082 |
4,538 |
#pragma once
/******************************************************
* Constants
******************************************************/
#define IPERF_DEBUG_ENABLE
#define IPERF_DEBUG_RECEIVE (1<<0)
#define IPERF_DEBUG_SEND (1<<1)
#define IPERF_DEBUG_REPORT (1<<2)
| 121 |
1,240 |
<gh_stars>1000+
package com.eventyay.organizer.core.main;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import com.eventyay.organizer.common.Constants;
import com.eventyay.organizer.common.ContextManager;
import com.eventyay.organizer.common.livedata.SingleEventLiveData;
import com.eventyay.organizer.common.rx.Logger;
import com.eventyay.organizer.data.auth.AuthService;
import com.eventyay.organizer.data.user.User;
import com.eventyay.organizer.data.user.UserRepository;
import com.eventyay.organizer.utils.DateUtils;
import com.f2prateek.rx.preferences2.RxSharedPreferences;
import javax.inject.Inject;
import io.reactivex.disposables.CompositeDisposable;
public class OrganizerViewModel extends ViewModel {
private final UserRepository userRepository;
private final AuthService authService;
private final RxSharedPreferences sharedPreferences;
private final ContextManager contextManager;
private final CompositeDisposable compositeDisposable = new CompositeDisposable();
private final MutableLiveData<User> organizer = new MutableLiveData<>();
private final MutableLiveData<String> error = new MutableLiveData<>();
private final SingleEventLiveData<Void> logoutAction = new SingleEventLiveData<>();
private final SingleEventLiveData<Void> localDatePreferenceAction = new SingleEventLiveData<>();
@Inject
public OrganizerViewModel(UserRepository userRepository, AuthService authService,
RxSharedPreferences sharedPreferences, ContextManager contextManager) {
this.userRepository = userRepository;
this.authService = authService;
this.sharedPreferences = sharedPreferences;
this.contextManager = contextManager;
}
protected LiveData<User> getOrganizer() {
compositeDisposable.add(userRepository
.getOrganizer(false)
.subscribe(organizer::setValue, Logger::logError));
return organizer;
}
protected void setLocalDatePreferenceAction() {
compositeDisposable.add(sharedPreferences.getBoolean(Constants.SHARED_PREFS_LOCAL_DATE)
.asObservable()
.distinctUntilChanged()
.doOnNext(changed -> localDatePreferenceAction.call())
.subscribe(DateUtils::setShowLocal));
}
public void logout() {
compositeDisposable.add(authService.logout()
.subscribe(() -> {
contextManager.clearOrganiser();
logoutAction.call();
}, throwable -> {
error.setValue(throwable.getMessage());
Logger.logError(throwable);
}));
}
protected LiveData<String> getError() {
return error;
}
protected LiveData<Void> getLocalDatePreferenceAction() {
return localDatePreferenceAction;
}
protected LiveData<Void> getLogoutAction() {
return logoutAction;
}
@Override
protected void onCleared() {
super.onCleared();
compositeDisposable.dispose();
}
}
| 1,171 |
892 |
{
"schema_version": "1.2.0",
"id": "GHSA-qw86-xx8q-rx6f",
"modified": "2022-05-04T00:28:31Z",
"published": "2022-05-04T00:28:31Z",
"aliases": [
"CVE-2012-0178"
],
"details": "Race condition in partmgr.sys in Windows Partition Manager in Microsoft Windows Vista SP2, Windows Server 2008 SP2, R2, and R2 SP1, and Windows 7 Gold and SP1 allows local users to gain privileges via a crafted application that makes multiple simultaneous Plug and Play (PnP) Configuration Manager function calls, aka \"Plug and Play (PnP) Configuration Manager Vulnerability.\"",
"severity": [
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2012-0178"
},
{
"type": "WEB",
"url": "https://docs.microsoft.com/en-us/security-updates/securitybulletins/2012/ms12-033"
},
{
"type": "WEB",
"url": "https://oval.cisecurity.org/repository/search/definition/oval%3Aorg.mitre.oval%3Adef%3A15229"
},
{
"type": "WEB",
"url": "http://osvdb.org/81735"
},
{
"type": "WEB",
"url": "http://secunia.com/advisories/49115"
},
{
"type": "WEB",
"url": "http://www.securityfocus.com/bid/53378"
},
{
"type": "WEB",
"url": "http://www.securitytracker.com/id?1027043"
},
{
"type": "WEB",
"url": "http://www.us-cert.gov/cas/techalerts/TA12-129A.html"
}
],
"database_specific": {
"cwe_ids": [
],
"severity": "HIGH",
"github_reviewed": false
}
}
| 705 |
1,350 |
<gh_stars>1000+
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.data.tables.models;
import com.azure.core.annotation.Fluent;
/**
* A model representing configurable metrics settings of the Table service.
*/
@Fluent
public final class TableServiceMetrics {
/*
* The version of Analytics to configure.
*/
private String version;
/*
* Indicates whether metrics are enabled for the Table service.
*/
private boolean enabled;
/*
* Indicates whether metrics should generate summary statistics for called API operations.
*/
private Boolean includeApis;
/*
* The retention policy.
*/
private TableServiceRetentionPolicy retentionPolicy;
/**
* Get the version of Analytics to configure.
*
* @return The {@code version}.
*/
public String getVersion() {
return this.version;
}
/**
* Set the version of Analytics to configure.
*
* @param version The {@code version} to set.
*
* @return The updated {@link TableServiceMetrics} object.
*/
public TableServiceMetrics setVersion(String version) {
this.version = version;
return this;
}
/**
* Get a value that indicates whether metrics are enabled for the Table service.
*
* @return The {@code enabled} value.
*/
public boolean isEnabled() {
return this.enabled;
}
/**
* Set a value that indicates whether metrics are enabled for the Table service.
*
* @param enabled The {@code enabled} value to set.
*
* @return The updated {@link TableServiceMetrics} object.
*/
public TableServiceMetrics setEnabled(boolean enabled) {
this.enabled = enabled;
return this;
}
/**
* Get a value that indicates whether metrics should generate summary statistics for called API operations.
*
* @return The {@code includeApis} value.
*/
public Boolean isIncludeApis() {
return this.includeApis;
}
/**
* Set a value that indicates whether metrics should generate summary statistics for called API operations.
*
* @param includeApis The {@code includeApis} value to set.
*
* @return The updated {@link TableServiceMetrics} object.
*/
public TableServiceMetrics setIncludeApis(Boolean includeApis) {
this.includeApis = includeApis;
return this;
}
/**
* Get the {@link TableServiceRetentionPolicy} for these metrics on the Table service.
*
* @return The {@link TableServiceRetentionPolicy}.
*/
public TableServiceRetentionPolicy getTableServiceRetentionPolicy() {
return this.retentionPolicy;
}
/**
* Set the {@link TableServiceRetentionPolicy} for these metrics on the Table service.
*
* @param retentionPolicy The {@link TableServiceRetentionPolicy} to set.
*
* @return The updated {@link TableServiceMetrics} object.
*/
public TableServiceMetrics setRetentionPolicy(TableServiceRetentionPolicy retentionPolicy) {
this.retentionPolicy = retentionPolicy;
return this;
}
}
| 1,118 |
1,340 |
import torch
import torchio as tio
from ...utils import TorchioTestCase
class TestZNormalization(TorchioTestCase):
"""Tests for :class:`ZNormalization` class."""
def test_z_normalization(self):
transform = tio.ZNormalization()
transformed = transform(self.sample_subject)
self.assertAlmostEqual(float(transformed.t1.data.mean()), 0, places=6)
self.assertAlmostEqual(float(transformed.t1.data.std()), 1)
def test_no_std(self):
image = tio.ScalarImage(tensor=torch.ones(1, 2, 2, 2))
with self.assertRaises(RuntimeError):
tio.ZNormalization()(image)
def test_dtype(self):
# https://github.com/fepegar/torchio/issues/407
tensor_int = (100 * torch.rand(1, 2, 3, 4)).byte()
transform = tio.ZNormalization(masking_method=tio.ZNormalization.mean)
transform(tensor_int)
transform = tio.ZNormalization()
transform(tensor_int)
| 396 |
1,331 |
<reponame>fergonaut/metasploit-payloads<filename>c/meterpreter/source/extensions/kiwi/main.h
/*!
* @file main.h
* @brief TLV related bits for the KIWI extension.
*/
#ifndef _METERPRETER_SOURCE_EXTENSION_KIWI_KIWI_H
#define _METERPRETER_SOURCE_EXTENSION_KIWI_KIWI_H
#include "../../common/common.h"
#define TLV_TYPE_EXTENSION_KIWI 0
#define TLV_TYPE_KIWI_CMD MAKE_CUSTOM_TLV(TLV_META_TYPE_STRING, TLV_TYPE_EXTENSION_KIWI, TLV_EXTENSIONS + 100)
#define TLV_TYPE_KIWI_CMD_RESULT MAKE_CUSTOM_TLV(TLV_META_TYPE_STRING, TLV_TYPE_EXTENSION_KIWI, TLV_EXTENSIONS + 101)
#endif
| 286 |
322 |
///////////////////////////////////////////////////////////////////////////////
// BSD 3-Clause License
//
// Copyright (C) 2019-2021, LAAS-CNRS, University of Edinburgh
// Copyright note valid unless otherwise stated in individual files.
// All rights reserved.
///////////////////////////////////////////////////////////////////////////////
#ifndef CROCODDYL_RANDOM_GENERATOR_HPP_
#define CROCODDYL_RANDOM_GENERATOR_HPP_
#include <boost/bind.hpp>
#include <Eigen/Dense>
#if __cplusplus >= 201103L
#include <random>
std::mt19937 rng;
#else
#include <boost/random.hpp>
#include <boost/nondet_random.hpp>
boost::random::mt19937 rng;
#endif
namespace crocoddyl {
namespace unittest {
template <typename IntType>
IntType random_int_in_range(IntType first = 0, IntType last = 10) {
#if __cplusplus >= 201103L
return std::uniform_int_distribution<IntType>(first, last)(rng);
#else
return boost::random::uniform_int_distribution<IntType>(first, last)(rng);
#endif
}
template <typename RealType>
RealType random_real_in_range(RealType first = 0, RealType last = 1) {
#if __cplusplus >= 201103L
return std::uniform_real_distribution<RealType>(first, last)(rng);
#else
return boost::random::uniform_real_distribution<RealType>(first, last)(rng);
#endif
}
bool random_boolean() {
static auto generator = boost::bind(std::uniform_int_distribution<>(0, 1), std::default_random_engine());
return generator();
}
} // namespace unittest
} // namespace crocoddyl
#endif // CROCODDYL_RANDOM_GENERATOR_HPP_
| 504 |
5,169 |
<filename>Specs/3/9/f/TYKYLibrary/1.3.8/TYKYLibrary.podspec.json
{
"name": "TYKYLibrary",
"version": "1.3.8",
"summary": "Library for TYKY",
"homepage": "https://github.com/chenteng85912/TYKYLibrary",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"CHENTENG": "<EMAIL>"
},
"platforms": {
"ios": "8.0"
},
"source": {
"git": "https://github.com/chenteng85912/TYKYLibrary.git",
"tag": "1.3.8"
},
"requires_arc": true,
"source_files": "TYKYLibrary/**/TYKYLibrary.h",
"frameworks": [
"CoreLocation",
"MapKit",
"AssetsLibrary",
"AVFoundation",
"LocalAuthentication"
],
"subspecs": [
{
"name": "Download",
"source_files": "TYKYLibrary/**/Download/*.{h,m}"
},
{
"name": "CustomAlbum",
"source_files": "TYKYLibrary/**/CustomAlbum/*.{h,m}",
"resources": "TYKYLibrary/**/CustomAlbum/*.{png,xib}",
"dependencies": {
"TYKYLibrary/TYKYCategory": [
]
}
},
{
"name": "AutoLocation",
"source_files": "TYKYLibrary/**/AutoLocation/*.{h,m}",
"resources": "TYKYLibrary/**/AutoLocation/*.{png,plist,xib}",
"dependencies": {
"TYKYLibrary/TYKYCategory": [
]
}
},
{
"name": "ShowPictures",
"source_files": "TYKYLibrary/**/ShowPictures/*.{h,m}",
"dependencies": {
"TYKYLibrary/Download": [
]
}
},
{
"name": "ONEPhoto",
"source_files": "TYKYLibrary/**/CTONEPhoto.{h,m}",
"dependencies": {
"TYKYLibrary/CustomAlbum": [
]
}
},
{
"name": "AutoLoop",
"source_files": "TYKYLibrary/**/CTAutoLoopViewController.{h,m}"
},
{
"name": "CustomCamera",
"source_files": "TYKYLibrary/**/CTCustomCameraSuperViewController.{h,m}",
"dependencies": {
"TYKYLibrary/CustomAlbum": [
]
}
},
{
"name": "PageViewController",
"source_files": "TYKYLibrary/**/CTCustomePageController.{h,m}"
},
{
"name": "TouchIDAuthorize",
"source_files": "TYKYLibrary/**/CTTouchIDAuthorize.{h,m}"
},
{
"name": "Request",
"source_files": "TYKYLibrary/**/CTRequest.{h,m}"
},
{
"name": "TableViewDelegate",
"source_files": "TYKYLibrary/**/TableViewDelegate/*.{h,m}"
},
{
"name": "VersionAutoUpdate",
"source_files": "TYKYLibrary/**/VersionAutoUpdate/*.{h,m}",
"dependencies": {
"TYKYLibrary/Request": [
]
}
},
{
"name": "AutoRunLabel",
"source_files": "TYKYLibrary/**/CTAutoRunLabel.{h,m}"
},
{
"name": "TYKYCategory",
"source_files": "TYKYLibrary/**/TYKYCategory/*.{h,m}"
},
{
"name": "CustomLibrary",
"source_files": "TYKYLibrary/**/CustomLibrary/*.{h,m}"
}
]
}
| 1,395 |
417 |
<reponame>1847123212/TeenyUSB
#ifndef __CH56x_BUS8_H__
#define __CH56x_BUS8_H__
#ifdef __cplusplus
extern "C" {
#endif
#define ADDR_NONE 0x00
#define ADDR_6 0x04
#define ADDR_10 0x08
#define ADDR_15 0x0c
#define WIDTH_3 0x00
#define WIDTH_5 0x10
#define WIDTH_9 0x20
#define WIDTH_16 0x30
#define HOLD_2 0x00
#define HOLD_3 0x40
#define SETUP_2 0x00
#define SETUP_3 0x80
void BUS8_Init(UINT8 addroe, UINT8 width, UINT8 hold, UINT8 setup);
#ifdef __cplusplus
}
#endif
#endif // __CH56x_BUS8_H__
| 279 |
742 |
<reponame>TotalCaesar659/OpenTESArena
#include "SkyLightningDefinition.h"
void SkyLightningDefinition::init(Buffer<TextureAssetReference> &&textureAssetRefs, double animSeconds)
{
this->textureAssetRefs = std::move(textureAssetRefs);
this->animSeconds = animSeconds;
}
int SkyLightningDefinition::getTextureCount() const
{
return static_cast<int>(this->textureAssetRefs.getCount());
}
const TextureAssetReference &SkyLightningDefinition::getTextureAssetRef(int index) const
{
return this->textureAssetRefs.get(index);
}
double SkyLightningDefinition::getAnimationSeconds() const
{
return this->animSeconds;
}
| 190 |
348 |
{"nom":"Pietrosella","circ":"2ème circonscription","dpt":"Corse-du-Sud","inscrits":1203,"abs":584,"votants":619,"blancs":53,"nuls":21,"exp":545,"res":[{"nuance":"REG","nom":"<NAME>","voix":291},{"nuance":"LR","nom":"<NAME>","voix":254}]}
| 97 |
964 |
{
"id": "6a2c219f-da5e-4745-941e-5ea8cde23356",
"queryName": "Example JSON Reference Does Not Exists",
"severity": "INFO",
"category": "Structure and Semantics",
"descriptionText": "Example reference should exists on components field",
"descriptionUrl": "https://swagger.io/specification/#components-object",
"platform": "OpenAPI",
"descriptionID": "026db32d"
}
| 130 |
1,853 |
int i(0);
int main()
{
int b(0);
}
| 22 |
1,645 |
"""
:Description: Sphinx extension to remove leading under-scores from directories names in the html build output directory.
"""
import os
import shutil
def setup(app):
"""
Add a html-page-context and a build-finished event handlers
"""
app.connect('html-page-context', change_pathto)
app.connect('build-finished', move_private_folders)
def change_pathto(app, pagename, templatename, context, doctree):
"""
Replace pathto helper to change paths to folders with a leading underscore.
"""
pathto = context.get('pathto')
def gh_pathto(otheruri, *args, **kw):
if otheruri.startswith('_'):
otheruri = otheruri[1:]
return pathto(otheruri, *args, **kw)
context['pathto'] = gh_pathto
def move_private_folders(app, e):
"""
remove leading underscore from folders in in the output folder.
:todo: should only affect html built
"""
def join(dir):
return os.path.join(app.builder.outdir, dir)
for item in os.listdir(app.builder.outdir):
if item.startswith('_') and os.path.isdir(join(item)):
shutil.move(join(item), join(item[1:]))
| 460 |
1,099 |
package com.snew.video.bean;
import java.io.Serializable;
/**
* 项目名称: NewFastFrame
* 创建人: 陈锦军
* 创建时间: 2018/12/14 19:55
*/
public class HotVideoItemBean implements Serializable {
private String title;
private String id;
private String url;
private int videoType;
public int getVideoType() {
return videoType;
}
public void setVideoType(int videoType) {
this.videoType = videoType;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getTitle() {
return title;
}
public String getId() {
return id;
}
public void setTitle(String title) {
this.title = title;
}
public void setId(String id) {
this.id = id;
}
}
| 384 |
428 |
package loon.build.sys;
/*
* 此类用来处理Robovm项目的构建
*/
public class Robovm {
}
| 55 |
1,398 |
<filename>labs/03_neural_recsys/movielens_paramsearch_results.py
import pandas as pd
from pathlib import Path
import json
def load_results_df(folder='results'):
folder = Path(folder)
results_dicts = []
for p in sorted(folder.glob('**/results.json')):
with p.open('r') as f:
results_dicts.append(json.load(f))
return pd.DataFrame.from_dict(results_dicts)
if __name__ == "__main__":
df = load_results_df().sort_values(by=['test_mae'], ascending=True)
print(df.head(5))
| 213 |
6,270 |
<reponame>gabegorelick/aws-sdk-js
[
{
"type": "feature",
"category": "EC2",
"description": "ec2.DescribeVpcPeeringConnections pagination support"
},
{
"type": "feature",
"category": "Shield",
"description": "The DescribeProtection request now accepts resource ARN as valid parameter."
}
]
| 153 |
1,962 |
package com.bolingcavalry.grpctutorials;
import com.bolingcavalry.grpctutorials.lib.AddCartReply;
import com.bolingcavalry.grpctutorials.lib.CartServiceGrpc;
import com.bolingcavalry.grpctutorials.lib.ProductOrder;
import io.grpc.stub.StreamObserver;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.springframework.stereotype.Service;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
/**
* @author will (<EMAIL>)
* @version 1.0
* @description: 业务服务类,调用gRPC服务
* @date 2021/4/17 10:05
*/
@Service
@Slf4j
public class GrpcClientService {
@GrpcClient("client-stream-server-side")
private CartServiceGrpc.CartServiceStub cartServiceStub;
public String addToCart(int count) {
CountDownLatch countDownLatch = new CountDownLatch(1);
// responseObserver的onNext和onCompleted会在另一个线程中被执行,
// ExtendResponseObserver继承自StreamObserver
ExtendResponseObserver<AddCartReply> responseObserver = new ExtendResponseObserver<AddCartReply>() {
String extraStr;
@Override
public String getExtra() {
return extraStr;
}
private int code;
private String message;
@Override
public void onNext(AddCartReply value) {
log.info("on next");
code = value.getCode();
message = value.getMessage();
}
@Override
public void onError(Throwable t) {
log.error("gRPC request error", t);
extraStr = "gRPC error, " + t.getMessage();
countDownLatch.countDown();
}
@Override
public void onCompleted() {
log.info("on complete");
extraStr = String.format("返回码[%d],返回信息:%s" , code, message);
countDownLatch.countDown();
}
};
// 远程调用,此时数据还没有给到服务端
StreamObserver<ProductOrder> requestObserver = cartServiceStub.addToCart(responseObserver);
for(int i=0; i<count; i++) {
// 发送一笔数据到服务端
requestObserver.onNext(build(101 + i, 1 + i));
}
// 客户端告诉服务端:数据已经发完了
requestObserver.onCompleted();
try {
// 开始等待,如果服务端处理完成,那么responseObserver的onCompleted方法会在另一个线程被执行,
// 那里会执行countDownLatch的countDown方法,一但countDown被执行,下面的await就执行完毕了,
// await的超时时间设置为2秒
countDownLatch.await(2, TimeUnit.SECONDS);
} catch (InterruptedException e) {
log.error("countDownLatch await error", e);
}
log.info("service finish");
// 服务端返回的内容被放置在requestObserver中,从getExtra方法可以取得
return responseObserver.getExtra();
}
/**
* 创建ProductOrder对象
* @param productId
* @param num
* @return
*/
private static ProductOrder build(int productId, int num) {
return ProductOrder.newBuilder().setProductId(productId).setNumber(num).build();
}
}
| 1,696 |
575 |
<reponame>iridium-browser/iridium-browser
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/policy/remote_commands/user_command_arc_job.h"
#include <memory>
#include <string>
#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/macros.h"
#include "base/run_loop.h"
#include "base/time/time.h"
#include "chrome/browser/ash/arc/policy/arc_policy_bridge.h"
#include "chrome/test/base/testing_profile.h"
#include "components/arc/arc_service_manager.h"
#include "components/arc/session/arc_bridge_service.h"
#include "components/arc/session/connection_holder.h"
#include "components/arc/test/fake_policy_instance.h"
#include "components/policy/core/common/remote_commands/remote_command_job.h"
#include "components/policy/proto/device_management_backend.pb.h"
#include "content/public/test/browser_task_environment.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace policy {
std::unique_ptr<policy::RemoteCommandJob> CreateArcJob(
Profile* profile,
base::TimeTicks issued_time,
const std::string& payload) {
// Create the job proto.
enterprise_management::RemoteCommand command_proto;
command_proto.set_type(
enterprise_management::RemoteCommand_Type_USER_ARC_COMMAND);
constexpr policy::RemoteCommandJob::UniqueIDType kUniqueID = 123456789;
command_proto.set_command_id(kUniqueID);
command_proto.set_age_of_command(
(base::TimeTicks::Now() - issued_time).InMilliseconds());
command_proto.set_payload(payload);
// Create the job and validate.
auto job = std::make_unique<policy::UserCommandArcJob>(profile);
EXPECT_TRUE(job->Init(base::TimeTicks::Now(), command_proto, nullptr));
EXPECT_EQ(kUniqueID, job->unique_id());
EXPECT_EQ(policy::RemoteCommandJob::NOT_STARTED, job->status());
return job;
}
class UserCommandArcJobTest : public testing::Test {
protected:
UserCommandArcJobTest();
~UserCommandArcJobTest() override;
content::BrowserTaskEnvironment task_environment_;
// ArcServiceManager needs to be created before ArcPolicyBridge (since the
// Bridge depends on the Manager), and it needs to be destroyed after Profile
// (because BrowserContextKeyedServices are destroyed together with Profile,
// and ArcPolicyBridge is such a service).
const std::unique_ptr<arc::ArcServiceManager> arc_service_manager_;
const std::unique_ptr<TestingProfile> profile_;
arc::ArcPolicyBridge* const arc_policy_bridge_;
const std::unique_ptr<arc::FakePolicyInstance> policy_instance_;
private:
DISALLOW_COPY_AND_ASSIGN(UserCommandArcJobTest);
};
UserCommandArcJobTest::UserCommandArcJobTest()
: arc_service_manager_(std::make_unique<arc::ArcServiceManager>()),
profile_(std::make_unique<TestingProfile>()),
arc_policy_bridge_(
arc::ArcPolicyBridge::GetForBrowserContextForTesting(profile_.get())),
policy_instance_(std::make_unique<arc::FakePolicyInstance>()) {
arc_service_manager_->arc_bridge_service()->policy()->SetInstance(
policy_instance_.get());
}
UserCommandArcJobTest::~UserCommandArcJobTest() {
arc_service_manager_->arc_bridge_service()->policy()->CloseInstance(
policy_instance_.get());
}
TEST_F(UserCommandArcJobTest, TestPayloadReceiving) {
const std::string kPayload = "testing payload";
std::unique_ptr<policy::RemoteCommandJob> job =
CreateArcJob(profile_.get(), base::TimeTicks::Now(), kPayload);
base::RunLoop run_loop;
auto check_result_callback = base::BindOnce(
[](base::RunLoop* run_loop, policy::RemoteCommandJob* job,
arc::FakePolicyInstance* policy_instance,
std::string expected_payload) {
EXPECT_EQ(policy::RemoteCommandJob::SUCCEEDED, job->status());
EXPECT_EQ(expected_payload, policy_instance->command_payload());
run_loop->Quit();
},
&run_loop, job.get(), policy_instance_.get(), kPayload);
EXPECT_TRUE(job->Run(base::Time::Now(), base::TimeTicks::Now(),
std::move(check_result_callback)));
run_loop.Run();
}
} // namespace policy
| 1,428 |
917 |
<filename>bitcoin-script/src/test/java/com/itranswarp/bitcoin/script/ScriptEngineTest.java
package com.itranswarp.bitcoin.script;
import static org.junit.Assert.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import com.itranswarp.bitcoin.io.BitcoinInput;
import com.itranswarp.bitcoin.struct.Transaction;
import com.itranswarp.bitcoin.struct.TxIn;
import com.itranswarp.bitcoin.struct.TxOut;
import com.itranswarp.bitcoin.util.ClasspathUtils;
import com.itranswarp.bitcoin.util.HashUtils;
public class ScriptEngineTest {
@Test
public void testExecute() throws Exception {
// pizza transaction:
// https://webbtc.com/tx/cca7507897abc89628f450e8b1e0c6fca4ec3f7b34cccf55f3f531c659ff4d79
String pizzaTxHash = "cca7507897abc89628f450e8b1e0c6fca4ec3f7b34cccf55f3f531c659ff4d79";
String prevTxHash = "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d";
byte[] pizzaTxData = ClasspathUtils.loadAsBytes("/tx-" + pizzaTxHash + ".dat");
byte[] prevTxData = ClasspathUtils.loadAsBytes("/tx-" + prevTxHash + ".dat");
Transaction pizzaTx = null;
Transaction prevTx = null;
try (BitcoinInput input = new BitcoinInput(pizzaTxData)) {
pizzaTx = new Transaction(input);
}
try (BitcoinInput input = new BitcoinInput(prevTxData)) {
prevTx = new Transaction(input);
}
assertEquals(1, pizzaTx.getTxInCount());
TxIn txIn = pizzaTx.tx_ins[0];
assertEquals(139, txIn.sigScript.length);
byte[] sigScript = txIn.sigScript;
assertEquals(
"4830450221009908144ca6539e09512b9295c8a27050d478fbb96f8addbc3d075544dc41328702201aa528be2b907d316d2da068dd9eb1e23243d97e444d59290d2fddf25269ee0e0141042e930f39ba62c6534ee98ed20ca98959d34aa9e057cda01cfd422c6bab3667b76426529382c23f42b9b08d7832d4fee1d6b437a8526e59667ce9c4e9dcebcabb",
HashUtils.toHexString(sigScript));
// find previous output:
assertEquals(1, prevTx.getTxOutCount());
TxOut txOut = prevTx.tx_outs[0];
byte[] outScript = txOut.pk_script;
assertEquals("76a91446af3fb481837fadbb421727f9959c2d32a3682988ac", HashUtils.toHexString(outScript));
// execute:
ScriptEngine engine = ScriptEngine.parse(sigScript, outScript);
System.out.println(engine);
Map<String, TxOut> prevUtxos = new HashMap<>();
for (int i = 0; i < prevTx.getTxOutCount(); i++) {
prevUtxos.put(HashUtils.toHexStringAsLittleEndian(prevTx.getTxHash()) + "#" + i, prevTx.tx_outs[i]);
}
assertTrue(engine.execute(pizzaTx, 0, prevUtxos));
assertEquals("17SkEw2md5avVNyYgj6RiXuQKNwkXaxFyQ", engine.getExtractAddress());
// modify signature and execute again:
byte[] sigScript2 = Arrays.copyOf(sigScript, sigScript.length);
sigScript2[10] = 0x1f;
ScriptEngine engine2 = ScriptEngine.parse(sigScript2, outScript);
assertFalse(engine2.execute(pizzaTx, 0, prevUtxos));
}
@Test
public void testTx2Inputs2Outputs() throws Exception {
// transaction:
// https://webbtc.com/tx/d7202bbc2bc3e1300217ec629ae902260a0440dcdb089f3dd90ce405268ccdf3
String txHash = "d7202bbc2bc3e1300217ec629ae902260a0440dcdb089f3dd90ce405268ccdf3";
byte[] txData = ClasspathUtils.loadAsBytes("/tx-" + txHash + ".dat");
Transaction tx = null;
try (BitcoinInput input = new BitcoinInput(txData)) {
tx = new Transaction(input);
}
assertEquals(2, tx.getTxInCount());
assertEquals(2, tx.getTxOutCount());
// load prev txs:
Transaction prevTx0 = null;
Transaction prevTx1 = null;
try (BitcoinInput input = new BitcoinInput(ClasspathUtils.loadAsBytes(
"/tx-" + HashUtils.toHexStringAsLittleEndian(tx.tx_ins[0].previousOutput.hash) + ".dat"))) {
prevTx0 = new Transaction(input);
}
try (BitcoinInput input = new BitcoinInput(ClasspathUtils.loadAsBytes(
"/tx-" + HashUtils.toHexStringAsLittleEndian(tx.tx_ins[1].previousOutput.hash) + ".dat"))) {
prevTx1 = new Transaction(input);
}
// load prev output:
TxOut prevOutput0 = prevTx0.tx_outs[(int) tx.tx_ins[0].previousOutput.index];
assertEquals(15879600L, prevOutput0.value);
TxOut prevOutput1 = prevTx1.tx_outs[(int) tx.tx_ins[1].previousOutput.index];
assertEquals(7950000L, prevOutput1.value);
// execute:
Map<String, TxOut> prevUtxos = new HashMap<>();
prevUtxos.put(
HashUtils.toHexStringAsLittleEndian(prevTx0.getTxHash()) + "#" + tx.tx_ins[0].previousOutput.index,
prevOutput0);
prevUtxos.put(
HashUtils.toHexStringAsLittleEndian(prevTx1.getTxHash()) + "#" + tx.tx_ins[1].previousOutput.index,
prevOutput1);
ScriptEngine engine = null;
// in0:
engine = ScriptEngine.parse(tx.tx_ins[0].sigScript, prevOutput0.pk_script);
assertTrue(engine.execute(tx, 0, prevUtxos));
assertEquals("1A9WgSDNBvrgSvTT5CH9iYyZRANw5mo4pP", engine.getExtractAddress());
// in1:
engine = ScriptEngine.parse(tx.tx_ins[1].sigScript, prevOutput1.pk_script);
assertTrue(engine.execute(tx, 1, prevUtxos));
assertEquals("1LygMU2TCKLsmQe8Hd7XV4ZYJoKtVHdMm9", engine.getExtractAddress());
}
@Test
public void testGetAddress() throws Exception {
// pizza transaction:
// https://webbtc.com/tx/cca7507897abc89628f450e8b1e0c6fca4ec3f7b34cccf55f3f531c659ff4d79
String pizzaTxHash = "cca7507897abc89628f450e8b1e0c6fca4ec3f7b34cccf55f3f531c659ff4d79";
byte[] pizzaTxData = ClasspathUtils.loadAsBytes("/tx-" + pizzaTxHash + ".dat");
Transaction pizzaTx = null;
try (BitcoinInput input = new BitcoinInput(pizzaTxData)) {
pizzaTx = new Transaction(input);
}
assertEquals(1, pizzaTx.getTxInCount());
assertEquals(2, pizzaTx.getTxOutCount());
// output 1:
TxOut out0 = pizzaTx.tx_outs[0];
ScriptEngine engine0 = ScriptEngine.parse(new byte[0], out0.pk_script);
assertEquals("1MLh2UVHgonJY4ZtsakoXtkcXDJ2EPU6RY", engine0.getExtractAddress());
// output 2:
TxOut out1 = pizzaTx.tx_outs[1];
ScriptEngine engine1 = ScriptEngine.parse(new byte[0], out1.pk_script);
assertEquals("13TETb2WMr58mexBaNq1jmXV1J7Abk2tE2", engine1.getExtractAddress());
}
}
| 2,482 |
14,668 |
// 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 "components/ntp_tiles/custom_links_manager_impl.h"
#include <memory>
#include <string>
#include <utility>
#include "base/auto_reset.h"
#include "base/bind.h"
#include "base/containers/cxx20_erase.h"
#include "components/ntp_tiles/constants.h"
#include "components/ntp_tiles/deleted_tile_type.h"
#include "components/ntp_tiles/metrics.h"
#include "components/ntp_tiles/most_visited_sites.h"
#include "components/ntp_tiles/pref_names.h"
#include "components/pref_registry/pref_registry_syncable.h"
#include "components/prefs/pref_service.h"
namespace ntp_tiles {
CustomLinksManagerImpl::CustomLinksManagerImpl(
PrefService* prefs,
history::HistoryService* history_service)
: prefs_(prefs), store_(prefs) {
DCHECK(prefs);
if (history_service)
history_service_observation_.Observe(history_service);
if (IsInitialized()) {
current_links_ = store_.RetrieveLinks();
RemoveCustomLinksForPreinstalledApps();
}
base::RepeatingClosure callback =
base::BindRepeating(&CustomLinksManagerImpl::OnPreferenceChanged,
weak_ptr_factory_.GetWeakPtr());
pref_change_registrar_.Init(prefs_);
pref_change_registrar_.Add(prefs::kCustomLinksInitialized, callback);
pref_change_registrar_.Add(prefs::kCustomLinksList, callback);
}
CustomLinksManagerImpl::~CustomLinksManagerImpl() = default;
bool CustomLinksManagerImpl::Initialize(const NTPTilesVector& tiles) {
if (IsInitialized())
return false;
for (const NTPTile& tile : tiles)
current_links_.emplace_back(Link{tile.url, tile.title, true});
{
base::AutoReset<bool> auto_reset(&updating_preferences_, true);
prefs_->SetBoolean(prefs::kCustomLinksInitialized, true);
}
StoreLinks();
return true;
}
void CustomLinksManagerImpl::Uninitialize() {
{
base::AutoReset<bool> auto_reset(&updating_preferences_, true);
prefs_->SetBoolean(prefs::kCustomLinksInitialized, false);
}
ClearLinks();
}
bool CustomLinksManagerImpl::IsInitialized() const {
return prefs_->GetBoolean(prefs::kCustomLinksInitialized);
}
const std::vector<CustomLinksManager::Link>& CustomLinksManagerImpl::GetLinks()
const {
return current_links_;
}
bool CustomLinksManagerImpl::AddLink(const GURL& url,
const std::u16string& title) {
if (!IsInitialized() || !url.is_valid() ||
current_links_.size() == ntp_tiles::kMaxNumCustomLinks) {
return false;
}
if (FindLinkWithUrl(url) != current_links_.end())
return false;
previous_links_ = current_links_;
current_links_.emplace_back(Link{url, title, false});
StoreLinks();
return true;
}
bool CustomLinksManagerImpl::UpdateLink(const GURL& url,
const GURL& new_url,
const std::u16string& new_title) {
if (!IsInitialized() || !url.is_valid() ||
(new_url.is_empty() && new_title.empty())) {
return false;
}
// Do not update if |new_url| is invalid or already exists in the list.
if (!new_url.is_empty() &&
(!new_url.is_valid() ||
FindLinkWithUrl(new_url) != current_links_.end())) {
return false;
}
auto it = FindLinkWithUrl(url);
if (it == current_links_.end())
return false;
// At this point, we will be modifying at least one of the values.
previous_links_ = current_links_;
if (!new_url.is_empty())
it->url = new_url;
if (!new_title.empty())
it->title = new_title;
it->is_most_visited = false;
StoreLinks();
return true;
}
bool CustomLinksManagerImpl::ReorderLink(const GURL& url, size_t new_pos) {
if (!IsInitialized() || !url.is_valid() || new_pos < 0 ||
new_pos >= current_links_.size()) {
return false;
}
auto curr_it = FindLinkWithUrl(url);
if (curr_it == current_links_.end())
return false;
auto new_it = current_links_.begin() + new_pos;
if (new_it == curr_it)
return false;
previous_links_ = current_links_;
// If the new position is to the left of the current position, left rotate the
// range [new_pos, curr_pos] until the link is first.
if (new_it < curr_it)
std::rotate(new_it, curr_it, curr_it + 1);
// If the new position is to the right, we only need to left rotate the range
// [curr_pos, new_pos] once so that the link is last.
else
std::rotate(curr_it, curr_it + 1, new_it + 1);
StoreLinks();
return true;
}
bool CustomLinksManagerImpl::DeleteLink(const GURL& url) {
if (!IsInitialized() || !url.is_valid())
return false;
auto it = FindLinkWithUrl(url);
if (it == current_links_.end())
return false;
previous_links_ = current_links_;
current_links_.erase(it);
StoreLinks();
return true;
}
bool CustomLinksManagerImpl::UndoAction() {
if (!IsInitialized() || !previous_links_.has_value())
return false;
// Replace the current links with the previous state.
current_links_ = *previous_links_;
previous_links_ = absl::nullopt;
StoreLinks();
return true;
}
void CustomLinksManagerImpl::ClearLinks() {
{
base::AutoReset<bool> auto_reset(&updating_preferences_, true);
store_.ClearLinks();
}
current_links_.clear();
previous_links_ = absl::nullopt;
}
void CustomLinksManagerImpl::StoreLinks() {
base::AutoReset<bool> auto_reset(&updating_preferences_, true);
store_.StoreLinks(current_links_);
}
void CustomLinksManagerImpl::RemoveCustomLinksForPreinstalledApps() {
if (!prefs_->GetBoolean(prefs::kCustomLinksForPreinstalledAppsRemoved)) {
bool default_app_links_deleted = false;
for (const Link& link : current_links_) {
if (MostVisitedSites::IsNtpTileFromPreinstalledApp(link.url) &&
MostVisitedSites::WasNtpAppMigratedToWebApp(prefs_, link.url)) {
DeleteLink(link.url);
default_app_links_deleted = true;
}
}
if (default_app_links_deleted) {
metrics::RecordsMigratedDefaultAppDeleted(DeletedTileType::kCustomLink);
prefs_->SetBoolean(prefs::kCustomLinksForPreinstalledAppsRemoved, true);
}
}
}
std::vector<CustomLinksManager::Link>::iterator
CustomLinksManagerImpl::FindLinkWithUrl(const GURL& url) {
return std::find_if(current_links_.begin(), current_links_.end(),
[&url](const Link& link) { return link.url == url; });
}
base::CallbackListSubscription
CustomLinksManagerImpl::RegisterCallbackForOnChanged(
base::RepeatingClosure callback) {
return closure_list_.Add(callback);
}
// history::HistoryServiceObserver implementation.
void CustomLinksManagerImpl::OnURLsDeleted(
history::HistoryService* history_service,
const history::DeletionInfo& deletion_info) {
// We don't care about expired entries.
if (!IsInitialized() || deletion_info.is_from_expiration())
return;
size_t initial_size = current_links_.size();
if (deletion_info.IsAllHistory()) {
base::EraseIf(current_links_,
[](auto& link) { return link.is_most_visited; });
} else {
for (const history::URLRow& row : deletion_info.deleted_rows()) {
auto it = FindLinkWithUrl(row.url());
if (it != current_links_.end() && it->is_most_visited)
current_links_.erase(it);
}
}
StoreLinks();
previous_links_ = absl::nullopt;
// Alert MostVisitedSites that some links have been deleted.
if (initial_size != current_links_.size())
closure_list_.Notify();
}
void CustomLinksManagerImpl::HistoryServiceBeingDeleted(
history::HistoryService* history_service) {
DCHECK(history_service_observation_.IsObserving());
history_service_observation_.Reset();
}
void CustomLinksManagerImpl::OnPreferenceChanged() {
if (updating_preferences_)
return;
if (IsInitialized())
current_links_ = store_.RetrieveLinks();
else
current_links_.clear();
previous_links_ = absl::nullopt;
closure_list_.Notify();
}
// static
void CustomLinksManagerImpl::RegisterProfilePrefs(
user_prefs::PrefRegistrySyncable* user_prefs) {
user_prefs->RegisterBooleanPref(
prefs::kCustomLinksInitialized, false,
user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
user_prefs->RegisterBooleanPref(prefs::kCustomLinksForPreinstalledAppsRemoved,
false);
CustomLinksStore::RegisterProfilePrefs(user_prefs);
}
} // namespace ntp_tiles
| 3,106 |
374 |
"""
This file contains definitions of layers used as building blocks in SMPLParamRegressor
"""
from __future__ import division
import torch
import torch.nn as nn
import torch.nn.functional as F
class FCBlock(nn.Module):
"""Wrapper around nn.Linear that includes batch normalization and activation functions."""
def __init__(self, in_size, out_size, batchnorm=True, activation=nn.ReLU(inplace=True), dropout=False):
super(FCBlock, self).__init__()
module_list = [nn.Linear(in_size, out_size)]
if batchnorm:
module_list.append(nn.BatchNorm1d(out_size))
if activation is not None:
module_list.append(activation)
if dropout:
module_list.append(dropout)
self.fc_block = nn.Sequential(*module_list)
def forward(self, x):
return self.fc_block(x)
class FCResBlock(nn.Module):
"""Residual block using fully-connected layers."""
def __init__(self, in_size, out_size, batchnorm=True, activation=nn.ReLU(inplace=True), dropout=False):
super(FCResBlock, self).__init__()
self.fc_block = nn.Sequential(nn.Linear(in_size, out_size),
nn.BatchNorm1d(out_size),
nn.ReLU(inplace=True),
nn.Linear(out_size, out_size),
nn.BatchNorm1d(out_size))
def forward(self, x):
return F.relu(x + self.fc_block(x))
| 706 |
631 |
/**
* 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.metron.enrichment.adapters.jdbc;
public class MySqlConfig extends BaseJdbcConfig {
@Override
public String getClassName() {
return "com.mysql.jdbc.Driver";
}
@Override
public String getJdbcUrl() {
StringBuilder url = new StringBuilder();
url.append("jdbc:mysql://").append(host);
if (port > 0) {
url.append(":").append(port);
}
url.append("/").append(table);
url.append("?user=").append(username);
url.append("&password=").append(password);
return url.toString();
}
}
| 403 |
326 |
{
"title": "Blog Details",
"enabled": true,
"systemId": "blog-details",
"canBeAddedToColumn": true,
"version": "0.0.0.1",
"systemidUpperCase": "BLOG-DETAILS",
"systemidCamelCase": "blogDetails"
}
| 85 |
14,668 |
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/modules/csspaint/nativepaint/clip_path_paint_image_generator_impl.h"
#include "third_party/blink/renderer/modules/csspaint/nativepaint/clip_path_paint_definition.h"
#include "third_party/blink/renderer/platform/graphics/image.h"
namespace blink {
ClipPathPaintImageGenerator* ClipPathPaintImageGeneratorImpl::Create(
LocalFrame& local_root) {
ClipPathPaintDefinition* clip_path_paint_definition =
ClipPathPaintDefinition::Create(local_root);
DCHECK(clip_path_paint_definition);
ClipPathPaintImageGeneratorImpl* generator =
MakeGarbageCollected<ClipPathPaintImageGeneratorImpl>(
clip_path_paint_definition);
return generator;
}
ClipPathPaintImageGeneratorImpl::ClipPathPaintImageGeneratorImpl(
ClipPathPaintDefinition* clip_path_paint_definition)
: clip_path_paint_definition_(clip_path_paint_definition) {}
scoped_refptr<Image> ClipPathPaintImageGeneratorImpl::Paint(
float zoom,
const gfx::RectF& reference_box,
const Node& node) {
return clip_path_paint_definition_->Paint(zoom, reference_box, node);
}
Animation* ClipPathPaintImageGeneratorImpl::GetAnimationIfCompositable(
const Element* element) {
return ClipPathPaintDefinition::GetAnimationIfCompositable(element);
}
void ClipPathPaintImageGeneratorImpl::Shutdown() {
clip_path_paint_definition_->UnregisterProxyClient();
}
void ClipPathPaintImageGeneratorImpl::Trace(Visitor* visitor) const {
visitor->Trace(clip_path_paint_definition_);
ClipPathPaintImageGenerator::Trace(visitor);
}
} // namespace blink
| 586 |
988 |
<reponame>vpostrigan/xdocreport
/**
* Copyright (C) 2011-2015 The XDocReport Team <<EMAIL>>
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package fr.opensagres.poi.xwpf.converter.core;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDecimalNumber;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTLvl;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTNumFmt;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STNumberFormat;
import fr.opensagres.poi.xwpf.converter.core.utils.RomanAlphabetFactory;
import fr.opensagres.poi.xwpf.converter.core.utils.RomanNumberFactory;
import fr.opensagres.poi.xwpf.converter.core.utils.StringUtils;
public class ListItemContext
{
private int startIndex = 0;
private int nb = 0;
private final int number;
private final CTLvl lvl;
private final ListItemContext parent;
private final String numberText;
public ListItemContext( CTLvl lvl, int number, ListItemContext parent )
{
this.lvl = lvl;
this.parent = parent;
this.startIndex = 0;
if ( lvl != null )
{
CTDecimalNumber start = lvl.getStart();
if ( start != null )
{
BigInteger val = start.getVal();
if ( val != null )
{
this.startIndex = val.intValue();
}
}
}
this.nb = 0;
this.number = number + startIndex;
if ( lvl != null )
{
CTNumFmt numFmt = lvl.getNumFmt();
this.numberText = computeNumberText( this.number, numFmt != null ? numFmt.getVal() : null);
}
else
{
this.numberText = null;
}
}
public ListItemContext getParent()
{
return parent;
}
public CTLvl getLvl()
{
return lvl;
}
public int getNumber()
{
return number;
}
public String getNumberText()
{
return numberText;
}
private static String computeNumberText( int number, STNumberFormat.Enum numFmt )
{
if ( STNumberFormat.LOWER_LETTER.equals( numFmt ) )
{
return RomanAlphabetFactory.getLowerCaseString( number );
}
else if ( STNumberFormat.UPPER_LETTER.equals( numFmt ) )
{
return RomanAlphabetFactory.getUpperCaseString( number );
}
else if ( STNumberFormat.LOWER_ROMAN.equals( numFmt ) )
{
return RomanNumberFactory.getLowerCaseString( number );
}
else if ( STNumberFormat.UPPER_ROMAN.equals( numFmt ) )
{
return RomanNumberFactory.getUpperCaseString( number );
}
return String.valueOf( number );
}
public ListItemContext createAndAddItem( CTLvl lvl )
{
return new ListItemContext( lvl, nb++, this );
}
public boolean isRoot()
{
return false;
}
public String getText()
{
String text = lvl.getLvlText().getVal();
CTNumFmt numFmt = lvl.getNumFmt();
if ( STNumberFormat.BULLET.equals( numFmt ) )
{
}
else
{
List<String> numbers = new ArrayList<String>();
ListItemContext item = this;
while ( !item.isRoot() )
{
numbers.add( 0, item.getNumberText() );
item = item.getParent();
}
String number = null;
for ( int i = 0; i < numbers.size(); i++ )
{
number = numbers.get( i );
text = StringUtils.replaceAll( text, "%" + ( i + 1 ), number );
}
}
return text;
}
}
| 2,291 |
348 |
<reponame>chamberone/Leaflet.PixiOverlay
{"nom":"Sainte-Aurence-Cazaux","circ":"1ère circonscription","dpt":"Gers","inscrits":87,"abs":42,"votants":45,"blancs":5,"nuls":1,"exp":39,"res":[{"nuance":"REM","nom":"<NAME>","voix":23},{"nuance":"SOC","nom":"<NAME>","voix":16}]}
| 115 |
1,467 |
/**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef IROHA_NETWORK_IMPL_HPP
#define IROHA_NETWORK_IMPL_HPP
#include "consensus/yac/transport/yac_network_interface.hpp" // for YacNetwork
#include "yac.grpc.pb.h"
#include <memory>
#include <mutex>
#include "consensus/yac/vote_message.hpp"
#include "logger/logger_fwd.hpp"
#include "network/impl/client_factory.hpp"
namespace iroha::consensus::yac {
/**
* Class which provides implementation of client-side transport for
* consensus based on grpc
*/
class NetworkImpl : public YacNetwork {
public:
using Service = proto::Yac;
using ClientFactory = iroha::network::ClientFactory<Service>;
NetworkImpl(std::unique_ptr<iroha::network::ClientFactory<
::iroha::consensus::yac::proto::Yac>> client_factory,
logger::LoggerPtr log);
void sendState(const shared_model::interface::Peer &to,
const std::vector<VoteMessage> &state) override;
void stop() override;
private:
/**
* Yac stub creator
*/
std::unique_ptr<ClientFactory> client_factory_;
std::mutex stop_mutex_;
bool stop_requested_{false};
logger::LoggerPtr log_;
};
} // namespace iroha::consensus::yac
#endif // IROHA_NETWORK_IMPL_HPP
| 530 |
521 |
<filename>third_party/virtualbox/src/libs/xpcom18a4/ipc/ipcd/extensions/dconnect/src/ipcDConnectService.cpp
/* vim:set ts=2 sw=2 et cindent: */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* 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 is Mozilla IPC.
*
* The Initial Developer of the Original Code is IBM Corporation.
* Portions created by the Initial Developer are Copyright (C) 2004
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* <NAME> <<EMAIL>>
* <NAME> <<EMAIL>>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "ipcDConnectService.h"
#include "ipcMessageWriter.h"
#include "ipcMessageReader.h"
#include "ipcLog.h"
#include "nsIServiceManagerUtils.h"
#include "nsIInterfaceInfo.h"
#include "nsIInterfaceInfoManager.h"
#include "nsIExceptionService.h"
#include "nsString.h"
#include "nsVoidArray.h"
#include "nsCRT.h"
#include "nsDeque.h"
#include "xptcall.h"
#ifdef VBOX
# include <map>
# include <list>
# include <iprt/err.h>
# include <iprt/req.h>
# include <iprt/mem.h>
# include <iprt/time.h>
# include <iprt/thread.h>
#endif /* VBOX */
#if defined(DCONNECT_MULTITHREADED)
#if !defined(DCONNECT_WITH_IPRT_REQ_POOL)
#include "nsIThread.h"
#include "nsIRunnable.h"
#endif
#if defined(DEBUG) && !defined(DCONNECT_STATS)
#define DCONNECT_STATS
#endif
#if defined(DCONNECT_STATS)
#include <stdio.h>
#endif
#endif
// XXX TODO:
// 1. add thread affinity field to SETUP messages
//-----------------------------------------------------------------------------
#define DCONNECT_IPC_TARGETID \
{ /* 43ca47ef-ebc8-47a2-9679-a4703218089f */ \
0x43ca47ef, \
0xebc8, \
0x47a2, \
{0x96, 0x79, 0xa4, 0x70, 0x32, 0x18, 0x08, 0x9f} \
}
static const nsID kDConnectTargetID = DCONNECT_IPC_TARGETID;
//-----------------------------------------------------------------------------
#define DCON_WAIT_TIMEOUT PR_INTERVAL_NO_TIMEOUT
//-----------------------------------------------------------------------------
//
// +--------------------------------------+
// | major opcode : 1 byte |
// +--------------------------------------+
// | minor opcode : 1 byte |
// +--------------------------------------+
// | flags : 2 bytes |
// +--------------------------------------+
// . .
// . variable payload .
// . .
// +--------------------------------------+
//
// dconnect major opcodes
#define DCON_OP_SETUP 1
#define DCON_OP_RELEASE 2
#define DCON_OP_INVOKE 3
#define DCON_OP_SETUP_REPLY 4
#define DCON_OP_INVOKE_REPLY 5
// dconnect minor opcodes for DCON_OP_SETUP
#define DCON_OP_SETUP_NEW_INST_CLASSID 1
#define DCON_OP_SETUP_NEW_INST_CONTRACTID 2
#define DCON_OP_SETUP_GET_SERV_CLASSID 3
#define DCON_OP_SETUP_GET_SERV_CONTRACTID 4
#define DCON_OP_SETUP_QUERY_INTERFACE 5
// dconnect minor opcodes for RELEASE
// dconnect minor opcodes for INVOKE
// DCON_OP_SETUP_REPLY and DCON_OP_INVOKE_REPLY flags
#define DCON_OP_FLAGS_REPLY_EXCEPTION 0x0001
// Within this time all the worker threads must be terminated.
#define VBOX_XPCOM_SHUTDOWN_TIMEOUT_MS (5000)
#pragma pack(1)
struct DConnectOp
{
PRUint8 opcode_major;
PRUint8 opcode_minor;
PRUint16 flags;
PRUint32 request_index; // initialized with NewRequestIndex
};
// SETUP structs
struct DConnectSetup : DConnectOp
{
nsID iid;
};
struct DConnectSetupClassID : DConnectSetup
{
nsID classid;
};
struct DConnectSetupContractID : DConnectSetup
{
char contractid[1]; // variable length
};
struct DConnectSetupQueryInterface : DConnectSetup
{
DConAddr instance;
};
// SETUP_REPLY struct
struct DConnectSetupReply : DConnectOp
{
DConAddr instance;
nsresult status;
// optionally followed by a specially serialized nsIException instance (see
// ipcDConnectService::SerializeException) if DCON_OP_FLAGS_REPLY_EXCEPTION is
// present in flags
};
// RELEASE struct
struct DConnectRelease : DConnectOp
{
DConAddr instance;
};
// INVOKE struct
struct DConnectInvoke : DConnectOp
{
DConAddr instance;
PRUint16 method_index;
// followed by an array of in-param blobs
};
// INVOKE_REPLY struct
struct DConnectInvokeReply : DConnectOp
{
nsresult result;
// followed by an array of out-param blobs if NS_SUCCEEDED(result), and
// optionally by a specially serialized nsIException instance (see
// ipcDConnectService::SerializeException) if DCON_OP_FLAGS_REPLY_EXCEPTION is
// present in flags
};
#pragma pack()
//-----------------------------------------------------------------------------
struct DConAddrPlusPtr
{
DConAddr addr;
void *p;
};
//-----------------------------------------------------------------------------
ipcDConnectService *ipcDConnectService::mInstance = nsnull;
//-----------------------------------------------------------------------------
static nsresult
SetupPeerInstance(PRUint32 aPeerID, DConnectSetup *aMsg, PRUint32 aMsgLen,
void **aInstancePtr);
//-----------------------------------------------------------------------------
// A wrapper class holding an instance to an in-process XPCOM object.
class DConnectInstance
{
public:
DConnectInstance(PRUint32 peer, nsIInterfaceInfo *iinfo, nsISupports *instance)
: mPeer(peer)
, mIInfo(iinfo)
, mInstance(instance)
{}
nsISupports *RealInstance() { return mInstance; }
nsIInterfaceInfo *InterfaceInfo() { return mIInfo; }
PRUint32 Peer() { return mPeer; }
DConnectInstanceKey::Key GetKey() {
const nsID *iid;
mIInfo->GetIIDShared(&iid);
return DConnectInstanceKey::Key(mPeer, mInstance, iid);
}
NS_IMETHODIMP_(nsrefcnt) AddRef(void)
{
NS_PRECONDITION(PRInt32(mRefCnt) >= 0, "illegal refcnt");
nsrefcnt count;
count = PR_AtomicIncrement((PRInt32*)&mRefCnt);
return count;
}
NS_IMETHODIMP_(nsrefcnt) Release(void)
{
nsrefcnt count;
NS_PRECONDITION(0 != mRefCnt, "dup release");
count = PR_AtomicDecrement((PRInt32 *)&mRefCnt);
if (0 == count) {
NS_PRECONDITION(PRInt32(mRefCntIPC) == 0, "non-zero IPC refcnt");
mRefCnt = 1; /* stabilize */
delete this;
return 0;
}
return count;
}
// this gets called after calling AddRef() on an instance passed to the
// client over IPC in order to have a count of IPC client-related references
// separately from the overall reference count
NS_IMETHODIMP_(nsrefcnt) AddRefIPC(void)
{
NS_PRECONDITION(PRInt32(mRefCntIPC) >= 0, "illegal refcnt");
nsrefcnt count = PR_AtomicIncrement((PRInt32*)&mRefCntIPC);
return count;
}
// this gets called before calling Release() when DCON_OP_RELEASE is
// received from the IPC client and in other cases to balance AddRefIPC()
NS_IMETHODIMP_(nsrefcnt) ReleaseIPC(PRBool locked = PR_FALSE)
{
NS_PRECONDITION(0 != mRefCntIPC, "dup release");
nsrefcnt count = PR_AtomicDecrement((PRInt32 *)&mRefCntIPC);
if (0 == count) {
// If the last IPC reference is released, remove this instance from the map.
// ipcDConnectService is guaranteed to still exist here
// (DConnectInstance lifetime is bound to ipcDConnectService)
nsRefPtr <ipcDConnectService> dConnect (ipcDConnectService::GetInstance());
if (dConnect)
dConnect->DeleteInstance(this, locked);
else
NS_NOTREACHED("ipcDConnectService has gone before DConnectInstance");
}
return count;
}
private:
nsAutoRefCnt mRefCnt;
nsAutoRefCnt mRefCntIPC;
PRUint32 mPeer; // peer process "owning" this instance
nsCOMPtr<nsIInterfaceInfo> mIInfo;
nsCOMPtr<nsISupports> mInstance;
};
void
ipcDConnectService::ReleaseWrappers(nsVoidArray &wrappers, PRUint32 peer)
{
nsAutoLock lock (mLock);
for (PRInt32 i=0; i<wrappers.Count(); ++i)
{
DConnectInstance *wrapper = (DConnectInstance *)wrappers[i];
if (mInstanceSet.Contains(wrapper) && wrapper->Peer() == peer)
{
wrapper->ReleaseIPC(PR_TRUE /* locked */);
wrapper->Release();
}
}
}
//-----------------------------------------------------------------------------
static nsresult
SerializeParam(ipcMessageWriter &writer, const nsXPTType &t, const nsXPTCMiniVariant &v)
{
switch (t.TagPart())
{
case nsXPTType::T_I8:
case nsXPTType::T_U8:
writer.PutInt8(v.val.u8);
break;
case nsXPTType::T_I16:
case nsXPTType::T_U16:
writer.PutInt16(v.val.u16);
break;
case nsXPTType::T_I32:
case nsXPTType::T_U32:
writer.PutInt32(v.val.u32);
break;
case nsXPTType::T_I64:
case nsXPTType::T_U64:
writer.PutBytes(&v.val.u64, sizeof(PRUint64));
break;
case nsXPTType::T_FLOAT:
writer.PutBytes(&v.val.f, sizeof(float));
break;
case nsXPTType::T_DOUBLE:
writer.PutBytes(&v.val.d, sizeof(double));
break;
case nsXPTType::T_BOOL:
writer.PutBytes(&v.val.b, sizeof(PRBool));
break;
case nsXPTType::T_CHAR:
writer.PutBytes(&v.val.c, sizeof(char));
break;
case nsXPTType::T_WCHAR:
writer.PutBytes(&v.val.wc, sizeof(PRUnichar));
break;
case nsXPTType::T_IID:
{
if (v.val.p)
writer.PutBytes(v.val.p, sizeof(nsID));
else
return NS_ERROR_INVALID_POINTER;
}
break;
case nsXPTType::T_CHAR_STR:
{
if (v.val.p)
{
int len = strlen((const char *) v.val.p);
writer.PutInt32(len);
writer.PutBytes(v.val.p, len);
}
else
{
// put -1 to indicate null string
writer.PutInt32((PRUint32) -1);
}
}
break;
case nsXPTType::T_WCHAR_STR:
{
if (v.val.p)
{
int len = 2 * nsCRT::strlen((const PRUnichar *) v.val.p);
writer.PutInt32(len);
writer.PutBytes(v.val.p, len);
}
else
{
// put -1 to indicate null string
writer.PutInt32((PRUint32) -1);
}
}
break;
case nsXPTType::T_INTERFACE:
case nsXPTType::T_INTERFACE_IS:
NS_NOTREACHED("this should be handled elsewhere");
return NS_ERROR_UNEXPECTED;
case nsXPTType::T_ASTRING:
case nsXPTType::T_DOMSTRING:
{
const nsAString *str = (const nsAString *) v.val.p;
PRUint32 len = 2 * str->Length();
nsAString::const_iterator begin;
const PRUnichar *data = str->BeginReading(begin).get();
writer.PutInt32(len);
writer.PutBytes(data, len);
}
break;
case nsXPTType::T_UTF8STRING:
case nsXPTType::T_CSTRING:
{
const nsACString *str = (const nsACString *) v.val.p;
PRUint32 len = str->Length();
nsACString::const_iterator begin;
const char *data = str->BeginReading(begin).get();
writer.PutInt32(len);
writer.PutBytes(data, len);
}
break;
case nsXPTType::T_ARRAY:
// arrays are serialized after all other params outside this routine
break;
case nsXPTType::T_VOID:
case nsXPTType::T_PSTRING_SIZE_IS:
case nsXPTType::T_PWSTRING_SIZE_IS:
default:
LOG(("unexpected parameter type: %d\n", t.TagPart()));
return NS_ERROR_UNEXPECTED;
}
return NS_OK;
}
static nsresult
DeserializeParam(ipcMessageReader &reader, const nsXPTType &t, nsXPTCVariant &v)
{
// defaults
v.ptr = nsnull;
v.type = t;
v.flags = 0;
switch (t.TagPart())
{
case nsXPTType::T_I8:
case nsXPTType::T_U8:
v.val.u8 = reader.GetInt8();
break;
case nsXPTType::T_I16:
case nsXPTType::T_U16:
v.val.u16 = reader.GetInt16();
break;
case nsXPTType::T_I32:
case nsXPTType::T_U32:
v.val.u32 = reader.GetInt32();
break;
case nsXPTType::T_I64:
case nsXPTType::T_U64:
reader.GetBytes(&v.val.u64, sizeof(v.val.u64));
break;
case nsXPTType::T_FLOAT:
reader.GetBytes(&v.val.f, sizeof(v.val.f));
break;
case nsXPTType::T_DOUBLE:
reader.GetBytes(&v.val.d, sizeof(v.val.d));
break;
case nsXPTType::T_BOOL:
reader.GetBytes(&v.val.b, sizeof(v.val.b));
break;
case nsXPTType::T_CHAR:
reader.GetBytes(&v.val.c, sizeof(v.val.c));
break;
case nsXPTType::T_WCHAR:
reader.GetBytes(&v.val.wc, sizeof(v.val.wc));
break;
case nsXPTType::T_IID:
{
nsID *buf = (nsID *) nsMemory::Alloc(sizeof(nsID));
reader.GetBytes(buf, sizeof(nsID));
v.val.p = buf;
v.SetValIsAllocated();
}
break;
case nsXPTType::T_CHAR_STR:
{
PRUint32 len = reader.GetInt32();
if (len == (PRUint32) -1)
{
// it's a null string
v.val.p = nsnull;
}
else
{
char *buf = (char *) nsMemory::Alloc(len + 1);
reader.GetBytes(buf, len);
buf[len] = char(0);
v.val.p = buf;
v.SetValIsAllocated();
}
}
break;
case nsXPTType::T_WCHAR_STR:
{
PRUint32 len = reader.GetInt32();
if (len == (PRUint32) -1)
{
// it's a null string
v.val.p = nsnull;
}
else
{
PRUnichar *buf = (PRUnichar *) nsMemory::Alloc(len + 2);
reader.GetBytes(buf, len);
buf[len / 2] = PRUnichar(0);
v.val.p = buf;
v.SetValIsAllocated();
}
}
break;
case nsXPTType::T_INTERFACE:
case nsXPTType::T_INTERFACE_IS:
{
reader.GetBytes(&v.val.u64, sizeof(DConAddr));
// stub creation will be handled outside this routine. we only
// deserialize the DConAddr into v.val.u64 temporarily.
}
break;
case nsXPTType::T_ASTRING:
case nsXPTType::T_DOMSTRING:
{
PRUint32 len = reader.GetInt32();
nsString *str = new nsString();
str->SetLength(len / 2);
PRUnichar *buf = str->BeginWriting();
reader.GetBytes(buf, len);
v.val.p = str;
v.SetValIsDOMString();
}
break;
case nsXPTType::T_UTF8STRING:
case nsXPTType::T_CSTRING:
{
PRUint32 len = reader.GetInt32();
nsCString *str = new nsCString();
str->SetLength(len);
char *buf = str->BeginWriting();
reader.GetBytes(buf, len);
v.val.p = str;
// this distinction here is pretty pointless
if (t.TagPart() == nsXPTType::T_CSTRING)
v.SetValIsCString();
else
v.SetValIsUTF8String();
}
break;
case nsXPTType::T_ARRAY:
// arrays are deserialized after all other params outside this routine
break;
case nsXPTType::T_VOID:
case nsXPTType::T_PSTRING_SIZE_IS:
case nsXPTType::T_PWSTRING_SIZE_IS:
default:
LOG(("unexpected parameter type\n"));
return NS_ERROR_UNEXPECTED;
}
return NS_OK;
}
static nsresult
SetupParam(const nsXPTParamInfo &p, nsXPTCVariant &v)
{
const nsXPTType &t = p.GetType();
if (p.IsIn() && p.IsDipper())
{
v.ptr = nsnull;
v.flags = 0;
switch (t.TagPart())
{
case nsXPTType::T_ASTRING:
case nsXPTType::T_DOMSTRING:
v.val.p = new nsString();
if (!v.val.p)
return NS_ERROR_OUT_OF_MEMORY;
v.type = t;
v.SetValIsDOMString();
break;
case nsXPTType::T_UTF8STRING:
case nsXPTType::T_CSTRING:
v.val.p = new nsCString();
if (!v.val.p)
return NS_ERROR_OUT_OF_MEMORY;
v.type = t;
v.SetValIsCString();
break;
default:
LOG(("unhandled dipper: type=%d\n", t.TagPart()));
return NS_ERROR_UNEXPECTED;
}
}
else if (p.IsOut() || p.IsRetval())
{
memset(&v.val, 0, sizeof(v.val));
v.ptr = &v.val;
v.type = t;
v.flags = 0;
v.SetPtrIsData();
// the ownership of output nsID, string, wstring, interface pointers and
// arrays is transferred to the receiving party. Therefore, we need to
// instruct FinishParam() to perform a cleanup after serializing them.
switch (t.TagPart())
{
case nsXPTType::T_IID:
case nsXPTType::T_CHAR_STR:
case nsXPTType::T_WCHAR_STR:
case nsXPTType::T_ARRAY:
v.SetValIsAllocated();
break;
case nsXPTType::T_INTERFACE:
case nsXPTType::T_INTERFACE_IS:
v.SetValIsInterface();
break;
default:
break;
}
}
return NS_OK;
}
static void
FinishParam(nsXPTCVariant &v)
{
#ifdef VBOX
/* make valgrind happy */
if (!v.MustFreeVal())
return;
#endif
if (!v.val.p)
return;
if (v.IsValAllocated())
nsMemory::Free(v.val.p);
else if (v.IsValInterface())
((nsISupports *) v.val.p)->Release();
else if (v.IsValDOMString())
delete (nsAString *) v.val.p;
else if (v.IsValUTF8String() || v.IsValCString())
delete (nsACString *) v.val.p;
}
static nsresult
DeserializeResult(ipcMessageReader &reader, const nsXPTType &t, nsXPTCMiniVariant &v)
{
if (v.val.p == nsnull)
return NS_OK;
switch (t.TagPart())
{
case nsXPTType::T_I8:
case nsXPTType::T_U8:
*((PRUint8 *) v.val.p) = reader.GetInt8();
break;
case nsXPTType::T_I16:
case nsXPTType::T_U16:
*((PRUint16 *) v.val.p) = reader.GetInt16();
break;
case nsXPTType::T_I32:
case nsXPTType::T_U32:
*((PRUint32 *) v.val.p) = reader.GetInt32();
break;
case nsXPTType::T_I64:
case nsXPTType::T_U64:
reader.GetBytes(v.val.p, sizeof(PRUint64));
break;
case nsXPTType::T_FLOAT:
reader.GetBytes(v.val.p, sizeof(float));
break;
case nsXPTType::T_DOUBLE:
reader.GetBytes(v.val.p, sizeof(double));
break;
case nsXPTType::T_BOOL:
reader.GetBytes(v.val.p, sizeof(PRBool));
break;
case nsXPTType::T_CHAR:
reader.GetBytes(v.val.p, sizeof(char));
break;
case nsXPTType::T_WCHAR:
reader.GetBytes(v.val.p, sizeof(PRUnichar));
break;
case nsXPTType::T_IID:
{
nsID *buf = (nsID *) nsMemory::Alloc(sizeof(nsID));
reader.GetBytes(buf, sizeof(nsID));
*((nsID **) v.val.p) = buf;
}
break;
case nsXPTType::T_CHAR_STR:
{
PRUint32 len = reader.GetInt32();
if (len == (PRUint32) -1)
{
// it's a null string
#ifdef VBOX
*((char **) v.val.p) = NULL;
#else
v.val.p = 0;
#endif
}
else
{
char *buf = (char *) nsMemory::Alloc(len + 1);
reader.GetBytes(buf, len);
buf[len] = char(0);
*((char **) v.val.p) = buf;
}
}
break;
case nsXPTType::T_WCHAR_STR:
{
PRUint32 len = reader.GetInt32();
if (len == (PRUint32) -1)
{
// it's a null string
#ifdef VBOX
*((PRUnichar **) v.val.p) = 0;
#else
v.val.p = 0;
#endif
}
else
{
PRUnichar *buf = (PRUnichar *) nsMemory::Alloc(len + 2);
reader.GetBytes(buf, len);
buf[len / 2] = PRUnichar(0);
*((PRUnichar **) v.val.p) = buf;
}
}
break;
case nsXPTType::T_INTERFACE:
case nsXPTType::T_INTERFACE_IS:
{
// stub creation will be handled outside this routine. we only
// deserialize the DConAddr and the original value of v.val.p
// into v.val.p temporarily. needs temporary memory alloc.
DConAddrPlusPtr *buf = (DConAddrPlusPtr *) nsMemory::Alloc(sizeof(DConAddrPlusPtr));
reader.GetBytes(&buf->addr, sizeof(DConAddr));
buf->p = v.val.p;
v.val.p = buf;
}
break;
case nsXPTType::T_ASTRING:
case nsXPTType::T_DOMSTRING:
{
PRUint32 len = reader.GetInt32();
nsAString *str = (nsAString *) v.val.p;
nsAString::iterator begin;
str->SetLength(len / 2);
str->BeginWriting(begin);
reader.GetBytes(begin.get(), len);
}
break;
case nsXPTType::T_UTF8STRING:
case nsXPTType::T_CSTRING:
{
PRUint32 len = reader.GetInt32();
nsACString *str = (nsACString *) v.val.p;
nsACString::iterator begin;
str->SetLength(len);
str->BeginWriting(begin);
reader.GetBytes(begin.get(), len);
}
break;
case nsXPTType::T_ARRAY:
// arrays are deserialized after all other params outside this routine
break;
case nsXPTType::T_VOID:
case nsXPTType::T_PSTRING_SIZE_IS:
case nsXPTType::T_PWSTRING_SIZE_IS:
default:
LOG(("unexpected parameter type\n"));
return NS_ERROR_UNEXPECTED;
}
return NS_OK;
}
//-----------------------------------------------------------------------------
//
// Returns an element from the nsXPTCMiniVariant array by properly casting it to
// nsXPTCVariant when requested
#define GET_PARAM(params, isXPTCVariantArray, idx) \
(isXPTCVariantArray ? ((nsXPTCVariant *) params) [idx] : params [idx])
// isResult is PR_TRUE if the size_is and length_is params are out or retval
// so that nsXPTCMiniVariants contain pointers to their locations instead of the
// values themselves.
static nsresult
GetArrayParamInfo(nsIInterfaceInfo *iinfo, uint16 methodIndex,
const nsXPTMethodInfo &methodInfo, nsXPTCMiniVariant *params,
PRBool isXPTCVariantArray, const nsXPTParamInfo ¶mInfo,
PRBool isResult, PRUint32 &size, PRUint32 &length,
nsXPTType &elemType)
{
// XXX multidimensional arrays are not supported so dimension is always 0 for
// getting the size_is argument number of the array itself and 1 for getting
// the type of elements stored in the array.
nsresult rv;
// get the array size
PRUint8 sizeArg;
rv = iinfo->GetSizeIsArgNumberForParam(methodIndex, ¶mInfo, 0, &sizeArg);
if (NS_FAILED(rv))
return rv;
// get the number of valid elements
PRUint8 lenArg;
rv = iinfo->GetLengthIsArgNumberForParam(methodIndex, ¶mInfo, 0, &lenArg);
if (NS_FAILED(rv))
return rv;
// according to XPT specs
// (http://www.mozilla.org/scriptable/typelib_file.html), size_is and
// length_is for arrays is always uint32. Check this too.
{
nsXPTParamInfo pi = methodInfo.GetParam (sizeArg);
if (pi.GetType().TagPart() != nsXPTType::T_U32)
{
LOG(("unexpected size_is() parameter type: $d\n",
pi.GetType().TagPart()));
return NS_ERROR_UNEXPECTED;
}
pi = methodInfo.GetParam (lenArg);
if (pi.GetType().TagPart() != nsXPTType::T_U32)
{
LOG(("unexpected length_is() parameter type: $d\n",
pi.GetType().TagPart()));
return NS_ERROR_UNEXPECTED;
}
}
if (isResult)
{
length = *((PRUint32 *) GET_PARAM(params,isXPTCVariantArray, lenArg).val.p);
size = *((PRUint32 *) GET_PARAM(params, isXPTCVariantArray, sizeArg).val.p);
}
else
{
length = GET_PARAM(params, isXPTCVariantArray, lenArg).val.u32;
size = GET_PARAM(params, isXPTCVariantArray, sizeArg).val.u32;
}
if (length > size)
{
NS_WARNING("length_is() value is greater than size_is() value");
length = size;
}
// get type of array elements
rv = iinfo->GetTypeForParam(methodIndex, ¶mInfo, 1, &elemType);
if (NS_FAILED(rv))
return rv;
if (elemType.IsArithmetic() &&
(elemType.IsPointer() || elemType.IsUniquePointer() ||
elemType.IsReference()))
{
LOG(("arrays of pointers and references to arithmetic types are "
"not yet supported\n"));
return NS_ERROR_NOT_IMPLEMENTED;
}
if (elemType.IsArray())
{
LOG(("multidimensional arrays are not yet supported\n"));
return NS_ERROR_NOT_IMPLEMENTED;
}
return NS_OK;
}
static nsresult
GetTypeSize(const nsXPTType &type, PRUint32 &size, PRBool &isSimple)
{
// get the type size in bytes
size = 0;
isSimple = PR_TRUE;
switch (type.TagPart())
{
case nsXPTType::T_I8: size = sizeof(PRInt8); break;
case nsXPTType::T_I16: size = sizeof(PRInt16); break;
case nsXPTType::T_I32: size = sizeof(PRInt32); break;
case nsXPTType::T_I64: size = sizeof(PRInt64); break;
case nsXPTType::T_U8: size = sizeof(PRUint8); break;
case nsXPTType::T_U16: size = sizeof(PRUint16); break;
case nsXPTType::T_U32: size = sizeof(PRUint32); break;
case nsXPTType::T_U64: size = sizeof(PRUint64); break;
case nsXPTType::T_FLOAT: size = sizeof(float); break;
case nsXPTType::T_DOUBLE: size = sizeof(double); break;
case nsXPTType::T_BOOL: size = sizeof(PRBool); break;
case nsXPTType::T_CHAR: size = sizeof(char); break;
case nsXPTType::T_WCHAR: size = sizeof(PRUnichar); break;
case nsXPTType::T_IID: /* fall through */
case nsXPTType::T_CHAR_STR: /* fall through */
case nsXPTType::T_WCHAR_STR: /* fall through */
case nsXPTType::T_ASTRING: /* fall through */
case nsXPTType::T_DOMSTRING: /* fall through */
case nsXPTType::T_UTF8STRING: /* fall through */
case nsXPTType::T_CSTRING: /* fall through */
size = sizeof(void *);
isSimple = PR_FALSE;
break;
case nsXPTType::T_INTERFACE: /* fall through */
case nsXPTType::T_INTERFACE_IS: /* fall through */
size = sizeof(DConAddr);
isSimple = PR_FALSE;
break;
default:
LOG(("unexpected parameter type: %d\n", type.TagPart()));
return NS_ERROR_UNEXPECTED;
}
return NS_OK;
}
static nsresult
SerializeArrayParam(ipcDConnectService *dConnect,
ipcMessageWriter &writer, PRUint32 peerID,
nsIInterfaceInfo *iinfo, uint16 methodIndex,
const nsXPTMethodInfo &methodInfo,
nsXPTCMiniVariant *params, PRBool isXPTCVariantArray,
const nsXPTParamInfo ¶mInfo,
void *array, nsVoidArray &wrappers)
{
if (!array)
{
// put 0 to indicate null array
writer.PutInt8(0);
return NS_OK;
}
// put 1 to indicate non-null array
writer.PutInt8(1);
PRUint32 size = 0;
PRUint32 length = 0;
nsXPTType elemType;
nsresult rv = GetArrayParamInfo(iinfo, methodIndex, methodInfo, params,
isXPTCVariantArray, paramInfo, PR_FALSE,
size, length, elemType);
if (NS_FAILED (rv))
return rv;
PRUint32 elemSize = 0;
PRBool isSimple = PR_TRUE;
rv = GetTypeSize(elemType, elemSize, isSimple);
if (NS_FAILED (rv))
return rv;
if (isSimple)
{
// this is a simple arithmetic type, write the whole array at once
writer.PutBytes(array, length * elemSize);
return NS_OK;
}
// iterate over valid (length_is) elements of the array
// and serialize each of them
nsXPTCMiniVariant v;
for (PRUint32 i = 0; i < length; ++i)
{
v.val.p = ((void **) array) [i];
if (elemType.IsInterfacePointer())
{
nsID iid;
rv = dConnect->GetIIDForMethodParam(iinfo, &methodInfo, paramInfo, elemType,
methodIndex, params, isXPTCVariantArray,
iid);
if (NS_SUCCEEDED(rv))
rv = dConnect->SerializeInterfaceParam(writer, peerID, iid,
(nsISupports *) v.val.p,
wrappers);
}
else
rv = SerializeParam(writer, elemType, v);
if (NS_FAILED(rv))
return rv;
}
return NS_OK;
}
// isResult is PR_TRUE if the array param is out or retval
static nsresult
DeserializeArrayParam(ipcDConnectService *dConnect,
ipcMessageReader &reader, PRUint32 peerID,
nsIInterfaceInfo *iinfo, uint16 methodIndex,
const nsXPTMethodInfo &methodInfo,
nsXPTCMiniVariant *params, PRBool isXPTCVariantArray,
const nsXPTParamInfo ¶mInfo,
PRBool isResult, void *&array)
{
PRUint32 size = 0;
PRUint32 length = 0;
nsXPTType elemType;
nsresult rv = GetArrayParamInfo(iinfo, methodIndex, methodInfo, params,
isXPTCVariantArray, paramInfo, isResult,
size, length, elemType);
if (NS_FAILED(rv))
return rv;
PRUint8 prefix = reader.GetInt8();
if (prefix == 0)
{
// it's a null array
array = nsnull;
return NS_OK;
}
// sanity
if (prefix != 1)
{
LOG(("unexpected array prefix: %u\n", prefix));
return NS_ERROR_UNEXPECTED;
}
PRUint32 elemSize = 0;
PRBool isSimple = PR_TRUE;
rv = GetTypeSize(elemType, elemSize, isSimple);
if (NS_FAILED (rv))
return rv;
// Note: for zero-sized arrays, we use the size of 1 because whether
// malloc(0) returns a null pointer or not (which is used in isNull())
// is implementation-dependent according to the C standard
void *arr = nsMemory::Alloc((size ? size : 1) * elemSize);
if (arr == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
// initialize the unused space of the array with zeroes
if (length < size)
memset(((PRUint8 *) arr) + length * elemSize, 0,
(size - length) * elemSize);
if (isSimple)
{
// this is a simple arithmetic type, read the whole array at once
reader.GetBytes(arr, length * elemSize);
array = arr;
return NS_OK;
}
// iterate over valid (length_is) elements of the array
// and deserialize each of them individually
nsXPTCVariant v;
for (PRUint32 i = 0; i < length; ++i)
{
rv = DeserializeParam(reader, elemType, v);
if (NS_SUCCEEDED(rv) && elemType.IsInterfacePointer())
{
// grab the DConAddr value temporarily stored in the param
PtrBits bits = v.val.u64;
// DeserializeInterfaceParamBits needs IID only if it's a remote object
nsID iid;
if (bits & PTRBITS_REMOTE_BIT)
rv = dConnect->GetIIDForMethodParam(iinfo, &methodInfo, paramInfo,
elemType, methodIndex,
params, isXPTCVariantArray, iid);
if (NS_SUCCEEDED(rv))
{
nsISupports *obj = nsnull;
rv = dConnect->DeserializeInterfaceParamBits(bits, peerID, iid, obj);
if (NS_SUCCEEDED(rv))
v.val.p = obj;
}
}
if (NS_FAILED(rv))
break;
// note that we discard extended param informaton provided by nsXPTCVariant
// and will have to "reconstruct" it from the type tag in FinishArrayParam()
((void **) arr) [i] = v.val.p;
}
if (NS_FAILED(rv))
nsMemory::Free(arr);
else
array = arr;
return rv;
}
static void
FinishArrayParam(nsIInterfaceInfo *iinfo, uint16 methodIndex,
const nsXPTMethodInfo &methodInfo, nsXPTCMiniVariant *params,
PRBool isXPTCVariantArray, const nsXPTParamInfo ¶mInfo,
const nsXPTCMiniVariant &arrayVal)
{
// nothing to do for a null array
void *arr = arrayVal.val.p;
if (!arr)
return;
PRUint32 size = 0;
PRUint32 length = 0;
nsXPTType elemType;
// note that FinishArrayParam is called only from OnInvoke to free memory
// after the call has been served. When OnInvoke sets up out and retval
// parameters for the real method, it passes pointers to the nsXPTCMiniVariant
// elements of the params array themselves so that they will eventually
// receive the returned values. For this reason, both in 'in' param and
// 'out/retaval' param cases, size_is and length_is may be read by
// GetArrayParamInfo() by value. Therefore, isResult is always PR_FALSE.
nsresult rv = GetArrayParamInfo(iinfo, methodIndex, methodInfo, params,
isXPTCVariantArray, paramInfo, PR_FALSE,
size, length, elemType);
if (NS_FAILED (rv))
return;
nsXPTCVariant v;
v.ptr = nsnull;
v.flags = 0;
// iterate over valid (length_is) elements of the array
// and free each of them
for (PRUint32 i = 0; i < length; ++i)
{
v.type = elemType.TagPart();
switch (elemType.TagPart())
{
case nsXPTType::T_I8: /* fall through */
case nsXPTType::T_I16: /* fall through */
case nsXPTType::T_I32: /* fall through */
case nsXPTType::T_I64: /* fall through */
case nsXPTType::T_U8: /* fall through */
case nsXPTType::T_U16: /* fall through */
case nsXPTType::T_U32: /* fall through */
case nsXPTType::T_U64: /* fall through */
case nsXPTType::T_FLOAT: /* fall through */
case nsXPTType::T_DOUBLE: /* fall through */
case nsXPTType::T_BOOL: /* fall through */
case nsXPTType::T_CHAR: /* fall through */
case nsXPTType::T_WCHAR: /* fall through */
// nothing to free for arithmetic types
continue;
case nsXPTType::T_IID: /* fall through */
case nsXPTType::T_CHAR_STR: /* fall through */
case nsXPTType::T_WCHAR_STR: /* fall through */
v.val.p = ((void **) arr) [i];
v.SetValIsAllocated();
break;
case nsXPTType::T_INTERFACE: /* fall through */
case nsXPTType::T_INTERFACE_IS: /* fall through */
v.val.p = ((void **) arr) [i];
v.SetValIsInterface();
break;
case nsXPTType::T_ASTRING: /* fall through */
case nsXPTType::T_DOMSTRING: /* fall through */
v.val.p = ((void **) arr) [i];
v.SetValIsDOMString();
break;
case nsXPTType::T_UTF8STRING: /* fall through */
v.val.p = ((void **) arr) [i];
v.SetValIsUTF8String();
break;
case nsXPTType::T_CSTRING: /* fall through */
v.val.p = ((void **) arr) [i];
v.SetValIsCString();
break;
default:
LOG(("unexpected parameter type: %d\n", elemType.TagPart()));
return;
}
FinishParam(v);
}
}
//-----------------------------------------------------------------------------
static PRUint32
NewRequestIndex()
{
static PRInt32 sRequestIndex;
return (PRUint32) PR_AtomicIncrement(&sRequestIndex);
}
//-----------------------------------------------------------------------------
#ifdef VBOX
typedef struct ClientDownInfo
{
ClientDownInfo(PRUint32 aClient)
{
uClient = aClient;
uTimestamp = PR_IntervalNow();
}
PRUint32 uClient;
PRIntervalTime uTimestamp;
} ClientDownInfo;
typedef std::map<PRUint32, ClientDownInfo *> ClientDownMap;
typedef std::list<ClientDownInfo *> ClientDownList;
#define MAX_CLIENT_DOWN_SIZE 10000
/* Protected by the queue monitor. */
static ClientDownMap g_ClientDownMap;
static ClientDownList g_ClientDownList;
#endif /* VBOX */
class DConnectMsgSelector : public ipcIMessageObserver
{
public:
DConnectMsgSelector(PRUint32 peer, PRUint8 opCodeMajor, PRUint32 requestIndex)
: mPeer (peer)
, mOpCodeMajor(opCodeMajor)
, mRequestIndex(requestIndex)
{}
// stack based only
NS_IMETHOD_(nsrefcnt) AddRef() { return 1; }
NS_IMETHOD_(nsrefcnt) Release() { return 1; }
NS_IMETHOD QueryInterface(const nsIID &aIID, void **aInstancePtr);
NS_IMETHOD OnMessageAvailable(PRUint32 aSenderID, const nsID &aTarget,
const PRUint8 *aData, PRUint32 aDataLen)
{
// accept special "client dead" messages for a given peer
// (empty target id, zero data and data length)
#ifndef VBOX
if (aSenderID == mPeer && aTarget.Equals(nsID()) && !aData && !aDataLen)
return NS_OK;
#else /* VBOX */
if (aSenderID != IPC_SENDER_ANY && aTarget.Equals(nsID()) && !aData && !aDataLen)
{
// Insert new client down information. Start by expiring outdated
// entries and free one element if there's still no space (if needed).
PRIntervalTime now = PR_IntervalNow();
while (!g_ClientDownList.empty())
{
ClientDownInfo *cInfo = g_ClientDownList.back();
PRInt64 diff = (PRInt64)now - cInfo->uTimestamp;
if (diff < 0)
diff += (PRInt64)((PRIntervalTime)-1) + 1;
if (diff > PR_SecondsToInterval(15 * 60))
{
g_ClientDownMap.erase(cInfo->uClient);
g_ClientDownList.pop_back();
NS_ASSERTION(g_ClientDownMap.size() == g_ClientDownList.size(),
"client down info inconsistency during expiry");
delete cInfo;
}
else
break;
}
ClientDownMap::iterator it = g_ClientDownMap.find(aSenderID);
if (it == g_ClientDownMap.end())
{
/* Getting size of a map is O(1), size of a list can be O(n). */
while (g_ClientDownMap.size() >= MAX_CLIENT_DOWN_SIZE)
{
ClientDownInfo *cInfo = g_ClientDownList.back();
g_ClientDownMap.erase(cInfo->uClient);
g_ClientDownList.pop_back();
NS_ASSERTION(g_ClientDownMap.size() == g_ClientDownList.size(),
"client down info inconsistency during emergency evicting");
delete cInfo;
}
ClientDownInfo *cInfo = new ClientDownInfo(aSenderID);
g_ClientDownMap[aSenderID] = cInfo;
g_ClientDownList.push_front(cInfo);
NS_ASSERTION(g_ClientDownMap.size() == g_ClientDownList.size(),
"client down info inconsistency after adding entry");
}
return (aSenderID == mPeer) ? NS_OK : IPC_WAIT_NEXT_MESSAGE;
}
// accept special "client up" messages for a given peer
// (empty target id, zero data and data length=1)
if (aTarget.Equals(nsID()) && !aData && aDataLen == 1)
{
ClientDownMap::iterator it = g_ClientDownMap.find(aSenderID);
if (it != g_ClientDownMap.end())
{
ClientDownInfo *cInfo = it->second;
g_ClientDownMap.erase(it);
g_ClientDownList.remove(cInfo);
NS_ASSERTION(g_ClientDownMap.size() == g_ClientDownList.size(),
"client down info inconsistency in client up case");
delete cInfo;
}
return (aSenderID == mPeer) ? NS_OK : IPC_WAIT_NEXT_MESSAGE;
}
// accept special "client check" messages for an anonymous sender
// (invalid sender id, empty target id, zero data and data length
if (aSenderID == IPC_SENDER_ANY && aTarget.Equals(nsID()) && !aData && !aDataLen)
{
LOG(("DConnectMsgSelector::OnMessageAvailable: poll liveness for mPeer=%d\n",
mPeer));
ClientDownMap::iterator it = g_ClientDownMap.find(mPeer);
return (it == g_ClientDownMap.end()) ? IPC_WAIT_NEXT_MESSAGE : NS_OK;
}
#endif /* VBOX */
const DConnectOp *op = (const DConnectOp *) aData;
// accept only reply messages with the given peer/opcode/index
// (to prevent eating replies the other thread might be waiting for)
// as well as any non-reply messages (to serve external requests that
// might arrive while we're waiting for the given reply).
if (aDataLen >= sizeof(DConnectOp) &&
((op->opcode_major != DCON_OP_SETUP_REPLY &&
op->opcode_major != DCON_OP_INVOKE_REPLY) ||
(aSenderID == mPeer &&
op->opcode_major == mOpCodeMajor &&
op->request_index == mRequestIndex)))
return NS_OK;
else
return IPC_WAIT_NEXT_MESSAGE;
}
const PRUint32 mPeer;
const PRUint8 mOpCodeMajor;
const PRUint32 mRequestIndex;
};
NS_IMPL_QUERY_INTERFACE1(DConnectMsgSelector, ipcIMessageObserver)
class DConnectCompletion : public ipcIMessageObserver
{
public:
DConnectCompletion(PRUint32 peer, PRUint8 opCodeMajor, PRUint32 requestIndex)
: mSelector(peer, opCodeMajor, requestIndex)
{}
// stack based only
NS_IMETHOD_(nsrefcnt) AddRef() { return 1; }
NS_IMETHOD_(nsrefcnt) Release() { return 1; }
NS_IMETHOD QueryInterface(const nsIID &aIID, void **aInstancePtr);
NS_IMETHOD OnMessageAvailable(PRUint32 aSenderID, const nsID &aTarget,
const PRUint8 *aData, PRUint32 aDataLen)
{
const DConnectOp *op = (const DConnectOp *) aData;
LOG((
"DConnectCompletion::OnMessageAvailable: "
"senderID=%d, opcode_major=%d, index=%d (waiting for %d)\n",
aSenderID, op->opcode_major, op->request_index, mSelector.mRequestIndex
));
if (aSenderID == mSelector.mPeer &&
op->opcode_major == mSelector.mOpCodeMajor &&
op->request_index == mSelector.mRequestIndex)
{
OnResponseAvailable(aSenderID, op, aDataLen);
}
else
{
// ensure ipcDConnectService is not deleted before we finish
nsRefPtr <ipcDConnectService> dConnect (ipcDConnectService::GetInstance());
if (dConnect)
dConnect->OnMessageAvailable(aSenderID, aTarget, aData, aDataLen);
}
return NS_OK;
}
virtual void OnResponseAvailable(PRUint32 sender, const DConnectOp *op, PRUint32 opLen) = 0;
DConnectMsgSelector &GetSelector()
{
return mSelector;
}
protected:
DConnectMsgSelector mSelector;
};
NS_IMPL_QUERY_INTERFACE1(DConnectCompletion, ipcIMessageObserver)
//-----------------------------------------------------------------------------
class DConnectInvokeCompletion : public DConnectCompletion
{
public:
DConnectInvokeCompletion(PRUint32 peer, const DConnectInvoke *invoke)
: DConnectCompletion(peer, DCON_OP_INVOKE_REPLY, invoke->request_index)
, mReply(nsnull)
, mParamsLen(0)
{}
~DConnectInvokeCompletion() { if (mReply) free(mReply); }
void OnResponseAvailable(PRUint32 sender, const DConnectOp *op, PRUint32 opLen)
{
mReply = (DConnectInvokeReply *) malloc(opLen);
memcpy(mReply, op, opLen);
// the length in bytes of the parameter blob
mParamsLen = opLen - sizeof(*mReply);
}
PRBool IsPending() const { return mReply == nsnull; }
nsresult GetResult() const { return mReply->result; }
const PRUint8 *Params() const { return (const PRUint8 *) (mReply + 1); }
PRUint32 ParamsLen() const { return mParamsLen; }
const DConnectInvokeReply *Reply() const { return mReply; }
private:
DConnectInvokeReply *mReply;
PRUint32 mParamsLen;
};
//-----------------------------------------------------------------------------
#define DCONNECT_STUB_ID \
{ /* 132c1f14-5442-49cb-8fe6-e60214bbf1db */ \
0x132c1f14, \
0x5442, \
0x49cb, \
{0x8f, 0xe6, 0xe6, 0x02, 0x14, 0xbb, 0xf1, 0xdb} \
}
static NS_DEFINE_IID(kDConnectStubID, DCONNECT_STUB_ID);
// this class represents the non-local object instance.
class DConnectStub : public nsXPTCStubBase
{
public:
NS_DECL_ISUPPORTS
DConnectStub(nsIInterfaceInfo *aIInfo,
DConAddr aInstance,
PRUint32 aPeerID)
: mIInfo(aIInfo)
, mInstance(aInstance)
, mPeerID(aPeerID)
, mCachedISupports(0)
, mRefCntLevels(0)
{}
NS_HIDDEN ~DConnectStub();
// return a refcounted pointer to the InterfaceInfo for this object
// NOTE: on some platforms this MUST not fail or we crash!
NS_IMETHOD GetInterfaceInfo(nsIInterfaceInfo **aInfo);
// call this method and return result
NS_IMETHOD CallMethod(PRUint16 aMethodIndex,
const nsXPTMethodInfo *aInfo,
nsXPTCMiniVariant *aParams);
DConAddr Instance() { return mInstance; }
PRUint32 PeerID() { return mPeerID; }
DConnectStubKey::Key GetKey() {
return DConnectStubKey::Key(mPeerID, mInstance);
}
NS_IMETHOD_(nsrefcnt) AddRefIPC();
private:
nsCOMPtr<nsIInterfaceInfo> mIInfo;
// uniquely identifies this object instance between peers.
DConAddr mInstance;
// the "client id" of our IPC peer. this guy owns the real object.
PRUint32 mPeerID;
// cached nsISupports stub for this object
DConnectStub *mCachedISupports;
// stack of reference counter values (protected by
// ipcDConnectService::StubLock())
nsDeque mRefCntLevels;
};
NS_IMETHODIMP_(nsrefcnt)
DConnectStub::AddRefIPC()
{
// in this special version, we memorize the resulting reference count in the
// associated stack array. This stack is then used by Release() to determine
// when it is necessary to send a RELEASE request to the peer owning the
// object in order to balance AddRef() the peer does on DConnectInstance every
// time it passes an object over IPC.
// NOTE: this function is to be called from DConnectInstance::CreateStub only!
nsRefPtr <ipcDConnectService> dConnect (ipcDConnectService::GetInstance());
NS_ASSERTION(dConnect, "no ipcDConnectService (uninitialized?)");
if (!dConnect)
return 0;
// dConnect->StubLock() must be already locked here by
// DConnectInstance::CreateStub
nsrefcnt count = AddRef();
mRefCntLevels.Push((void *)(uintptr_t) count);
return count;
}
nsresult
ipcDConnectService::CreateStub(const nsID &iid, PRUint32 peer, DConAddr instance,
DConnectStub **result)
{
nsresult rv;
nsCOMPtr<nsIInterfaceInfo> iinfo;
rv = GetInterfaceInfo(iid, getter_AddRefs(iinfo));
if (NS_FAILED(rv))
return rv;
nsAutoLock lock (mLock);
if (mDisconnected)
return NS_ERROR_NOT_INITIALIZED;
// we also need the stub lock which protects DConnectStub::mRefCntLevels and
// ipcDConnectService::mStubs
nsAutoLock stubLock (mStubLock);
DConnectStub *stub = nsnull;
// first try to find an existing stub for a given peer and instance
// (we do not care about IID because every DConAddr instance represents
// exactly one interface of the real object on the peer's side)
if (!mStubs.Get(DConnectStubKey::Key(peer, instance), &stub))
{
stub = new DConnectStub(iinfo, instance, peer);
if (NS_UNLIKELY(!stub))
rv = NS_ERROR_OUT_OF_MEMORY;
else
{
rv = StoreStub(stub);
if (NS_FAILED(rv))
delete stub;
}
}
if (NS_SUCCEEDED(rv))
{
stub->AddRefIPC();
*result = stub;
}
return rv;
}
nsresult
ipcDConnectService::SerializeInterfaceParam(ipcMessageWriter &writer,
PRUint32 peer, const nsID &iid,
nsISupports *obj,
nsVoidArray &wrappers)
{
nsAutoLock lock (mLock);
if (mDisconnected)
return NS_ERROR_NOT_INITIALIZED;
// we create an instance wrapper, and assume that the other side will send a
// RELEASE message when it no longer needs the instance wrapper. that will
// usually happen after the call returns.
//
// XXX a lazy scheme might be better, but for now simplicity wins.
// if the interface pointer references a DConnectStub corresponding
// to an object in the address space of the peer, then no need to
// create a new wrapper.
// if the interface pointer references an object for which we already have
// an existing wrapper, then we use it instead of creating a new one. this
// is based on the assumption that a valid COM object always returns exactly
// the same pointer value in response to every
// QueryInterface(NS_GET_IID(nsISupports), ...).
if (!obj)
{
// write null address
DConAddr nullobj = 0;
writer.PutBytes(&nullobj, sizeof(nullobj));
}
else
{
DConnectStub *stub = nsnull;
nsresult rv = obj->QueryInterface(kDConnectStubID, (void **) &stub);
if (NS_SUCCEEDED(rv) && (stub->PeerID() == peer))
{
DConAddr p = stub->Instance();
writer.PutBytes(&p, sizeof(p));
}
else
{
// create instance wrapper
nsCOMPtr<nsIInterfaceInfo> iinfo;
rv = GetInterfaceInfo(iid, getter_AddRefs(iinfo));
if (NS_FAILED(rv))
return rv;
DConnectInstance *wrapper = nsnull;
// first try to find an existing wrapper for the given object
if (!FindInstanceAndAddRef(peer, obj, &iid, &wrapper))
{
wrapper = new DConnectInstance(peer, iinfo, obj);
if (!wrapper)
return NS_ERROR_OUT_OF_MEMORY;
rv = StoreInstance(wrapper);
if (NS_FAILED(rv))
{
delete wrapper;
return rv;
}
// reference the newly created wrapper
wrapper->AddRef();
}
// increase the second, IPC-only, reference counter (mandatory before
// trying wrappers.AppendElement() to make sure ReleaseIPC() will remove
// the wrapper from the instance map on failure)
wrapper->AddRefIPC();
if (!wrappers.AppendElement(wrapper))
{
wrapper->ReleaseIPC();
wrapper->Release();
return NS_ERROR_OUT_OF_MEMORY;
}
// wrapper remains referenced when passing it to the client
// (will be released upon DCON_OP_RELEASE)
// send address of the instance wrapper, and set the low bit to indicate
// to the remote party that this is a remote instance wrapper.
PtrBits bits = ((PtrBits)(uintptr_t) wrapper);
NS_ASSERTION((bits & PTRBITS_REMOTE_BIT) == 0, "remote bit wrong)");
bits |= PTRBITS_REMOTE_BIT;
writer.PutBytes(&bits, sizeof(bits));
}
NS_IF_RELEASE(stub);
}
return NS_OK;
}
// NOTE: peer and iid are ignored if bits doesn't contain PTRBITS_REMOTE_BIT
nsresult
ipcDConnectService::DeserializeInterfaceParamBits(PtrBits bits, PRUint32 peer,
const nsID &iid,
nsISupports *&obj)
{
nsresult rv;
obj = nsnull;
if (bits & PTRBITS_REMOTE_BIT)
{
// pointer is to a remote object. we need to build a stub.
bits &= ~PTRBITS_REMOTE_BIT;
DConnectStub *stub;
rv = CreateStub(iid, peer, (DConAddr) bits, &stub);
if (NS_SUCCEEDED(rv))
obj = stub;
}
else if (bits)
{
// pointer is to one of our instance wrappers. Replace it with the
// real instance.
DConnectInstance *wrapper = (DConnectInstance *) bits;
// make sure we've been sent a valid wrapper
if (!CheckInstanceAndAddRef(wrapper, peer))
{
NS_NOTREACHED("instance wrapper not found");
return NS_ERROR_INVALID_ARG;
}
obj = wrapper->RealInstance();
NS_ADDREF(obj);
NS_RELEASE(wrapper);
}
else
{
// obj is alredy nsnull
}
return NS_OK;
}
//-----------------------------------------------------------------------------
#define EXCEPTION_STUB_ID \
{ /* 70578d68-b25e-4370-a70c-89bbe56e6699 */ \
0x70578d68, \
0xb25e, \
0x4370, \
{0xa7, 0x0c, 0x89, 0xbb, 0xe5, 0x6e, 0x66, 0x99} \
}
static NS_DEFINE_IID(kExceptionStubID, EXCEPTION_STUB_ID);
// ExceptionStub is used to cache all primitive-typed bits of a remote nsIException
// instance (such as the error message or line number) to:
//
// a) reduce the number of IPC calls;
// b) make sure exception information is available to the calling party even if
// the called party terminates immediately after returning an exception.
// To achieve this, all cacheable information is serialized together with
// the instance wrapper itself.
class ExceptionStub : public nsIException
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIEXCEPTION
ExceptionStub(const nsACString &aMessage, nsresult aResult,
const nsACString &aName, const nsACString &aFilename,
PRUint32 aLineNumber, PRUint32 aColumnNumber,
DConnectStub *aXcptStub)
: mMessage(aMessage), mResult(aResult)
, mName(aName), mFilename(aFilename)
, mLineNumber (aLineNumber), mColumnNumber (aColumnNumber)
, mXcptStub (aXcptStub) { NS_ASSERTION(aXcptStub, "NULL"); }
~ExceptionStub() {}
nsIException *Exception() { return (nsIException *)(nsISupports *) mXcptStub; }
DConnectStub *Stub() { return mXcptStub; }
private:
nsCString mMessage;
nsresult mResult;
nsCString mName;
nsCString mFilename;
PRUint32 mLineNumber;
PRUint32 mColumnNumber;
nsRefPtr<DConnectStub> mXcptStub;
};
NS_IMPL_THREADSAFE_ADDREF(ExceptionStub)
NS_IMPL_THREADSAFE_RELEASE(ExceptionStub)
NS_IMETHODIMP
ExceptionStub::QueryInterface(const nsID &aIID, void **aInstancePtr)
{
NS_ASSERTION(aInstancePtr,
"QueryInterface requires a non-NULL destination!");
// used to discover if this is an ExceptionStub instance.
if (aIID.Equals(kExceptionStubID))
{
*aInstancePtr = this;
NS_ADDREF_THIS();
return NS_OK;
}
// regular NS_IMPL_QUERY_INTERFACE1 sequence
nsISupports* foundInterface = 0;
if (aIID.Equals(NS_GET_IID(nsIException)))
foundInterface = NS_STATIC_CAST(nsIException*, this);
else
if (aIID.Equals(NS_GET_IID(nsISupports)))
foundInterface = NS_STATIC_CAST(nsISupports*,
NS_STATIC_CAST(nsIException *, this));
else
if (mXcptStub)
{
// ask the real nsIException object
return mXcptStub->QueryInterface(aIID, aInstancePtr);
}
nsresult status;
if (!foundInterface)
status = NS_NOINTERFACE;
else
{
NS_ADDREF(foundInterface);
status = NS_OK;
}
*aInstancePtr = foundInterface;
return status;
}
/* readonly attribute string message; */
NS_IMETHODIMP ExceptionStub::GetMessage(char **aMessage)
{
if (!aMessage)
return NS_ERROR_INVALID_POINTER;
*aMessage = ToNewCString(mMessage);
return NS_OK;
}
/* readonly attribute nsresult result; */
NS_IMETHODIMP ExceptionStub::GetResult(nsresult *aResult)
{
if (!aResult)
return NS_ERROR_INVALID_POINTER;
*aResult = mResult;
return NS_OK;
}
/* readonly attribute string name; */
NS_IMETHODIMP ExceptionStub::GetName(char **aName)
{
if (!aName)
return NS_ERROR_INVALID_POINTER;
*aName = ToNewCString(mName);
return NS_OK;
}
/* readonly attribute string filename; */
NS_IMETHODIMP ExceptionStub::GetFilename(char **aFilename)
{
if (!aFilename)
return NS_ERROR_INVALID_POINTER;
*aFilename = ToNewCString(mFilename);
return NS_OK;
}
/* readonly attribute PRUint32 lineNumber; */
NS_IMETHODIMP ExceptionStub::GetLineNumber(PRUint32 *aLineNumber)
{
if (!aLineNumber)
return NS_ERROR_INVALID_POINTER;
*aLineNumber = mLineNumber;
return NS_OK;
}
/* readonly attribute PRUint32 columnNumber; */
NS_IMETHODIMP ExceptionStub::GetColumnNumber(PRUint32 *aColumnNumber)
{
if (!aColumnNumber)
return NS_ERROR_INVALID_POINTER;
*aColumnNumber = mColumnNumber;
return NS_OK;
}
/* readonly attribute nsIStackFrame location; */
NS_IMETHODIMP ExceptionStub::GetLocation(nsIStackFrame **aLocation)
{
if (Exception())
return Exception()->GetLocation (aLocation);
return NS_ERROR_UNEXPECTED;
}
/* readonly attribute nsIException inner; */
NS_IMETHODIMP ExceptionStub::GetInner(nsIException **aInner)
{
if (Exception())
return Exception()->GetInner (aInner);
return NS_ERROR_UNEXPECTED;
}
/* readonly attribute nsISupports data; */
NS_IMETHODIMP ExceptionStub::GetData(nsISupports * *aData)
{
if (Exception())
return Exception()->GetData (aData);
return NS_ERROR_UNEXPECTED;
}
/* string toString (); */
NS_IMETHODIMP ExceptionStub::ToString(char **_retval)
{
if (Exception())
return Exception()->ToString (_retval);
return NS_ERROR_UNEXPECTED;
}
nsresult
ipcDConnectService::SerializeException(ipcMessageWriter &writer,
PRUint32 peer, nsIException *xcpt,
nsVoidArray &wrappers)
{
PRBool cache_fields = PR_FALSE;
// first, seralize the nsIException pointer. The code is merely the same as
// in SerializeInterfaceParam() except that when the exception to serialize
// is an ExceptionStub instance and the real instance it stores as mXcpt
// is a DConnectStub corresponding to an object in the address space of the
// peer, we simply pass that object back instead of creating a new wrapper.
{
nsAutoLock lock (mLock);
if (mDisconnected)
return NS_ERROR_NOT_INITIALIZED;
if (!xcpt)
{
// write null address
#ifdef VBOX
// see ipcDConnectService::DeserializeException()!
PtrBits bits = 0;
writer.PutBytes(&bits, sizeof(bits));
#else
writer.PutBytes(&xcpt, sizeof(xcpt));
#endif
}
else
{
ExceptionStub *stub = nsnull;
nsresult rv = xcpt->QueryInterface(kExceptionStubID, (void **) &stub);
if (NS_SUCCEEDED(rv) && (stub->Stub()->PeerID() == peer))
{
// send the wrapper instance back to the peer
DConAddr p = stub->Stub()->Instance();
writer.PutBytes(&p, sizeof(p));
}
else
{
// create instance wrapper
const nsID &iid = nsIException::GetIID();
nsCOMPtr<nsIInterfaceInfo> iinfo;
rv = GetInterfaceInfo(iid, getter_AddRefs(iinfo));
if (NS_FAILED(rv))
return rv;
DConnectInstance *wrapper = nsnull;
// first try to find an existing wrapper for the given object
if (!FindInstanceAndAddRef(peer, xcpt, &iid, &wrapper))
{
wrapper = new DConnectInstance(peer, iinfo, xcpt);
if (!wrapper)
return NS_ERROR_OUT_OF_MEMORY;
rv = StoreInstance(wrapper);
if (NS_FAILED(rv))
{
delete wrapper;
return rv;
}
// reference the newly created wrapper
wrapper->AddRef();
}
// increase the second, IPC-only, reference counter (mandatory before
// trying wrappers.AppendElement() to make sure ReleaseIPC() will remove
// the wrapper from the instance map on failure)
wrapper->AddRefIPC();
if (!wrappers.AppendElement(wrapper))
{
wrapper->ReleaseIPC();
wrapper->Release();
return NS_ERROR_OUT_OF_MEMORY;
}
// wrapper remains referenced when passing it to the client
// (will be released upon DCON_OP_RELEASE)
// send address of the instance wrapper, and set the low bit to indicate
// to the remote party that this is a remote instance wrapper.
PtrBits bits = ((PtrBits)(uintptr_t) wrapper) | PTRBITS_REMOTE_BIT;
writer.PutBytes(&bits, sizeof(bits));
// we want to cache fields to minimize the number of IPC calls when
// accessing exception data on the peer side
cache_fields = PR_TRUE;
}
NS_IF_RELEASE(stub);
}
}
if (!cache_fields)
return NS_OK;
nsresult rv;
nsXPIDLCString str;
PRUint32 num;
// message
rv = xcpt->GetMessage(getter_Copies(str));
if (NS_SUCCEEDED (rv))
{
PRUint32 len = str.Length();
nsACString::const_iterator begin;
const char *data = str.BeginReading(begin).get();
writer.PutInt32(len);
writer.PutBytes(data, len);
}
else
writer.PutInt32(0);
// result
nsresult res = 0;
xcpt->GetResult(&res);
writer.PutInt32(res);
// name
rv = xcpt->GetName(getter_Copies(str));
if (NS_SUCCEEDED (rv))
{
PRUint32 len = str.Length();
nsACString::const_iterator begin;
const char *data = str.BeginReading(begin).get();
writer.PutInt32(len);
writer.PutBytes(data, len);
}
else
writer.PutInt32(0);
// filename
rv = xcpt->GetFilename(getter_Copies(str));
if (NS_SUCCEEDED (rv))
{
PRUint32 len = str.Length();
nsACString::const_iterator begin;
const char *data = str.BeginReading(begin).get();
writer.PutInt32(len);
writer.PutBytes(data, len);
}
else
writer.PutInt32(0);
// lineNumber
num = 0;
xcpt->GetLineNumber(&num);
writer.PutInt32(num);
// columnNumber
num = 0;
xcpt->GetColumnNumber(&num);
writer.PutInt32(num);
return writer.HasError() ? NS_ERROR_OUT_OF_MEMORY : NS_OK;
}
nsresult
ipcDConnectService::DeserializeException(ipcMessageReader &reader,
PRUint32 peer,
nsIException **xcpt)
{
NS_ASSERTION (xcpt, "NULL");
if (!xcpt)
return NS_ERROR_INVALID_POINTER;
nsresult rv;
PRUint32 len;
PtrBits bits = 0;
reader.GetBytes(&bits, sizeof(DConAddr));
if (reader.HasError())
return NS_ERROR_INVALID_ARG;
if (bits & PTRBITS_REMOTE_BIT)
{
// pointer is a peer-side exception instance wrapper,
// read cahced exception data and create a stub for it.
nsCAutoString message;
len = reader.GetInt32();
if (len)
{
message.SetLength(len);
char *buf = message.BeginWriting();
reader.GetBytes(buf, len);
}
nsresult result = reader.GetInt32();
nsCAutoString name;
len = reader.GetInt32();
if (len)
{
name.SetLength(len);
char *buf = name.BeginWriting();
reader.GetBytes(buf, len);
}
nsCAutoString filename;
len = reader.GetInt32();
if (len)
{
filename.SetLength(len);
char *buf = filename.BeginWriting();
reader.GetBytes(buf, len);
}
PRUint32 lineNumber = reader.GetInt32();
PRUint32 columnNumber = reader.GetInt32();
if (reader.HasError())
rv = NS_ERROR_INVALID_ARG;
else
{
DConAddr addr = (DConAddr) (bits & ~PTRBITS_REMOTE_BIT);
nsRefPtr<DConnectStub> stub;
rv = CreateStub(nsIException::GetIID(), peer, addr,
getter_AddRefs(stub));
if (NS_SUCCEEDED(rv))
{
// create a special exception "stub" with cached error info
ExceptionStub *xcptStub =
new ExceptionStub (message, result,
name, filename,
lineNumber, columnNumber,
stub);
if (xcptStub)
{
*xcpt = xcptStub;
NS_ADDREF(xcptStub);
}
else
rv = NS_ERROR_OUT_OF_MEMORY;
}
}
}
else if (bits)
{
// pointer is to our instance wrapper for nsIException we've sent before
// (the remote method we've called had called us back and got an exception
// from us that it decided to return as its own result). Replace it with
// the real instance.
DConnectInstance *wrapper = (DConnectInstance *) bits;
if (CheckInstanceAndAddRef(wrapper, peer))
{
*xcpt = (nsIException *) wrapper->RealInstance();
NS_ADDREF(wrapper->RealInstance());
wrapper->Release();
rv = NS_OK;
}
else
{
NS_NOTREACHED("instance wrapper not found");
rv = NS_ERROR_INVALID_ARG;
}
}
else
{
// the peer explicitly passed us a NULL exception to indicate that the
// exception on the current thread should be reset
*xcpt = NULL;
return NS_OK;
}
return rv;
}
//-----------------------------------------------------------------------------
DConnectStub::~DConnectStub()
{
#ifdef IPC_LOGGING
if (IPC_LOG_ENABLED())
{
const char *name = NULL;
mIInfo->GetNameShared(&name);
LOG(("{%p} DConnectStub::<dtor>(): peer=%d instance=0x%Lx {%s}\n",
this, mPeerID, mInstance, name));
}
#endif
// release the cached nsISupports instance if it's not the same object
if (mCachedISupports != 0 && mCachedISupports != this)
NS_RELEASE(mCachedISupports);
}
NS_IMETHODIMP_(nsrefcnt)
DConnectStub::AddRef()
{
nsrefcnt count;
count = PR_AtomicIncrement((PRInt32*)&mRefCnt);
NS_LOG_ADDREF(this, count, "DConnectStub", sizeof(*this));
return count;
}
NS_IMETHODIMP_(nsrefcnt)
DConnectStub::Release()
{
nsrefcnt count;
nsRefPtr <ipcDConnectService> dConnect (ipcDConnectService::GetInstance());
if (dConnect)
{
// lock the stub lock on every release to make sure that once the counter
// drops to zero, we delete the stub from the set of stubs before a new
// request to create a stub on other thread tries to find the existing
// stub in the set (wchich could otherwise AddRef the object after it had
// Released to zero and pass it to the client right before its
// destruction).
nsAutoLock stubLock (dConnect->StubLock());
count = PR_AtomicDecrement((PRInt32 *)&mRefCnt);
NS_LOG_RELEASE(this, count, "DConnectStub");
#ifdef IPC_LOGGING
if (IPC_LOG_ENABLED())
{
const char *name;
mIInfo->GetNameShared(&name);
LOG(("{%p} DConnectStub::Release(): peer=%d instance=0x%Lx {%s}, new count=%d\n",
this, mPeerID, mInstance, name, count));
}
#endif
// mRefCntLevels may already be empty here (due to the "stabilize" trick below)
if (mRefCntLevels.GetSize() > 0)
{
nsrefcnt top = (nsrefcnt) (long) mRefCntLevels.Peek();
NS_ASSERTION(top <= count + 1, "refcount is beyond the top level");
if (top == count + 1)
{
// refcount dropped to a value stored in ipcDConnectService::CreateStub.
// Send a RELEASE request to the peer (see also AddRefIPC).
// remove the top refcount value
mRefCntLevels.Pop();
if (0 == count)
{
// this is the last reference, remove from the set before we leave
// the lock, to provide atomicity of these two operations
dConnect->DeleteStub (this);
NS_ASSERTION(mRefCntLevels.GetSize() == 0, "refcnt levels are still left");
}
// leave the lock before sending a message
stubLock.unlock();
nsresult rv;
DConnectRelease msg;
msg.opcode_major = DCON_OP_RELEASE;
msg.opcode_minor = 0;
msg.flags = 0;
msg.request_index = 0; // not used, set to some unused value
msg.instance = mInstance;
// fire off asynchronously... we don't expect any response to this message.
rv = IPC_SendMessage(mPeerID, kDConnectTargetID,
(const PRUint8 *) &msg, sizeof(msg));
if (NS_FAILED(rv))
NS_WARNING("failed to send RELEASE event");
}
}
}
else
{
count = PR_AtomicDecrement((PRInt32 *)&mRefCnt);
NS_LOG_RELEASE(this, count, "DConnectStub");
}
if (0 == count)
{
mRefCnt = 1; /* stabilize */
delete this;
return 0;
}
return count;
}
NS_IMETHODIMP
DConnectStub::QueryInterface(const nsID &aIID, void **aInstancePtr)
{
// used to discover if this is a DConnectStub instance.
if (aIID.Equals(kDConnectStubID))
{
*aInstancePtr = this;
NS_ADDREF_THIS();
return NS_OK;
}
// In order to truely support the COM Identity Rule across processes,
// we need to make the following code work:
//
// IFoo *foo = ...
// nsISupports unk;
// foo->QueryInterface(NS_GET_IID(nsISupports), (void **) &unk);
// unk->Release();
// nsISupports unk2;
// foo->QueryInterface(NS_GET_IID(nsISupports), (void **) &unk2);
// Assert (unk == unk2);
//
// I.e. querying nsISupports on the same object must always return the same
// pointer, even if the nsISupports object returned for the first time is
// released before it is requested for the second time, as long as the
// original object is kept alive (referenced by the client) between these
// two queries.
//
// This is done by remembering the nsISupports stub returned by the peer
// when nsISupports is queried for the first time. The remembered stub, when
// it is not the same as this object, is strongly referenced in order to
// keep it alive (and therefore have the same pointer value) as long as this
// object is alive.
//
// Besides supporting the Identity Rule, this also reduces the number of IPC
// calls, since an IPC call requesting nsISupports will be done only once
// per every stub object.
nsRefPtr <ipcDConnectService> dConnect (ipcDConnectService::GetInstance());
NS_ASSERTION(dConnect, "no ipcDConnectService (uninitialized?)");
if (!dConnect)
return NS_ERROR_NOT_INITIALIZED;
nsresult rv;
PRBool needISupports = aIID.Equals(NS_GET_IID(nsISupports));
if (needISupports)
{
// XXX it would be sufficient to use cmpxchg here to protect access to
// mCachedISupports, but NSPR doesn't provide cross-platform cmpxchg
// functionality, so we have to use a shared lock instead...
PR_Lock(dConnect->StubQILock());
// check if we have already got a nsISupports stub for this object
if (mCachedISupports != 0)
{
*aInstancePtr = mCachedISupports;
NS_ADDREF(mCachedISupports);
PR_Unlock(dConnect->StubQILock());
return NS_OK;
}
// check if this object is nsISupports itself
{
nsIID *iid = 0;
rv = mIInfo->GetInterfaceIID(&iid);
NS_ASSERTION(NS_SUCCEEDED(rv) && iid,
"nsIInterfaceInfo::GetInterfaceIID failed");
if (NS_SUCCEEDED(rv) && iid &&
iid->Equals(NS_GET_IID(nsISupports)))
{
nsMemory::Free((void*)iid);
// nsISupports is queried on nsISupports, return ourselves
*aInstancePtr = this;
NS_ADDREF_THIS();
// cache ourselves weakly
mCachedISupports = this;
PR_Unlock(dConnect->StubQILock());
return NS_OK;
}
if (iid)
nsMemory::Free((void*)iid);
}
// stub lock remains held until we've queried the peer
}
// else, we need to query the peer object by making an IPC call
#ifdef IPC_LOGGING
if (IPC_LOG_ENABLED())
{
const char *name;
mIInfo->GetNameShared(&name);
const char *nameQ;
nsCOMPtr <nsIInterfaceInfo> iinfoQ;
dConnect->GetInterfaceInfo(aIID, getter_AddRefs(iinfoQ));
if (iinfoQ) {
iinfoQ->GetNameShared(&nameQ);
LOG(("calling QueryInterface {%s} on peer object "
"(stub=%p, instance=0x%Lx {%s})\n",
nameQ, this, mInstance, name));
}
}
#endif
DConnectSetupQueryInterface msg;
msg.opcode_minor = DCON_OP_SETUP_QUERY_INTERFACE;
msg.iid = aIID;
msg.instance = mInstance;
rv = SetupPeerInstance(mPeerID, &msg, sizeof(msg), aInstancePtr);
if (needISupports)
{
if (NS_SUCCEEDED(rv))
{
// cache the nsISupports object (SetupPeerInstance returns DConnectStub)
mCachedISupports = (DConnectStub *) *aInstancePtr;
// use a weak reference if nsISupports is the same object as us
if (this != mCachedISupports)
NS_ADDREF(mCachedISupports);
}
PR_Unlock(dConnect->StubQILock());
}
return rv;
}
NS_IMETHODIMP
DConnectStub::GetInterfaceInfo(nsIInterfaceInfo **aInfo)
{
NS_ADDREF(*aInfo = mIInfo);
return NS_OK;
}
NS_IMETHODIMP
DConnectStub::CallMethod(PRUint16 aMethodIndex,
const nsXPTMethodInfo *aInfo,
nsXPTCMiniVariant *aParams)
{
LOG(("DConnectStub::CallMethod [methodIndex=%hu]\n", aMethodIndex));
nsresult rv;
// reset the exception early. this is necessary because we may return a
// failure from here without setting an exception (which might be expected
// by the caller to detect the error origin: the interface we are stubbing
// may indicate in some way that it always sets the exception info on
// failure, therefore an "infoless" failure means the origin is RPC).
// besides that, resetting the excetion before every IPC call is exactly the
// same thing as Win32 RPC does, so doing this is useful for getting
// similarity in behaviors.
nsCOMPtr <nsIExceptionService> es;
es = do_GetService (NS_EXCEPTIONSERVICE_CONTRACTID, &rv);
if (NS_FAILED (rv))
return rv;
nsCOMPtr <nsIExceptionManager> em;
rv = es->GetCurrentExceptionManager (getter_AddRefs(em));
if (NS_FAILED (rv))
return rv;
rv = em->SetCurrentException(NULL);
if (NS_FAILED (rv))
return rv;
// ensure ipcDConnectService is not deleted before we finish
nsRefPtr <ipcDConnectService> dConnect (ipcDConnectService::GetInstance());
if (!dConnect)
return NS_ERROR_FAILURE;
// dump arguments
PRUint8 i, paramCount = aInfo->GetParamCount();
#ifdef IPC_LOGGING
if (IPC_LOG_ENABLED())
{
const char *name;
nsCOMPtr<nsIInterfaceInfo> iinfo;
GetInterfaceInfo(getter_AddRefs(iinfo));
iinfo->GetNameShared(&name);
LOG((" instance=0x%Lx {%s}\n", mInstance, name));
LOG((" name=%s\n", aInfo->GetName()));
LOG((" param-count=%u\n", (PRUint32) paramCount));
}
#endif
ipcMessageWriter writer(16 * paramCount);
// INVOKE message header
DConnectInvoke invoke;
invoke.opcode_major = DCON_OP_INVOKE;
invoke.opcode_minor = 0;
invoke.flags = 0;
invoke.request_index = NewRequestIndex();
invoke.instance = mInstance;
invoke.method_index = aMethodIndex;
LOG((" request-index=%d\n", (PRUint32) invoke.request_index));
writer.PutBytes(&invoke, sizeof(invoke));
// list of wrappers that get created during parameter serialization. if we
// are unable to send the INVOKE message, then we'll clean these up.
nsVoidArray wrappers;
for (i=0; i<paramCount; ++i)
{
const nsXPTParamInfo ¶mInfo = aInfo->GetParam(i);
if (paramInfo.IsIn() && !paramInfo.IsDipper())
{
const nsXPTType &type = paramInfo.GetType();
if (type.IsInterfacePointer())
{
nsID iid;
rv = dConnect->GetIIDForMethodParam(mIInfo, aInfo, paramInfo, type,
aMethodIndex, aParams, PR_FALSE, iid);
if (NS_SUCCEEDED(rv))
rv = dConnect->SerializeInterfaceParam(writer, mPeerID, iid,
(nsISupports *) aParams[i].val.p,
wrappers);
}
else
rv = SerializeParam(writer, type, aParams[i]);
if (NS_FAILED(rv))
break;
}
else if ((paramInfo.IsOut() || paramInfo.IsRetval()) && !aParams[i].val.p)
{
// report error early if NULL pointer is passed as an output parameter
rv = NS_ERROR_NULL_POINTER;
break;
}
}
if (NS_FAILED(rv))
{
// INVOKE message wasn't sent; clean up wrappers
dConnect->ReleaseWrappers(wrappers, mPeerID);
return rv;
}
// serialize input array parameters after everything else since the
// deserialization procedure will need to get a size_is value which may be
// stored in any preceeding or following param
for (i=0; i<paramCount; ++i)
{
const nsXPTParamInfo ¶mInfo = aInfo->GetParam(i);
if (paramInfo.GetType().IsArray() &&
paramInfo.IsIn() && !paramInfo.IsDipper())
{
rv = SerializeArrayParam(dConnect, writer, mPeerID, mIInfo, aMethodIndex,
*aInfo, aParams, PR_FALSE, paramInfo,
aParams[i].val.p, wrappers);
if (NS_FAILED(rv))
{
// INVOKE message wasn't sent; clean up wrappers
dConnect->ReleaseWrappers(wrappers, mPeerID);
return rv;
}
}
}
// temporarily disable the DConnect target observer to block normal processing
// of pending messages through the event queue.
IPC_DISABLE_MESSAGE_OBSERVER_FOR_SCOPE(kDConnectTargetID);
rv = IPC_SendMessage(mPeerID, kDConnectTargetID,
writer.GetBuffer(),
writer.GetSize());
LOG(("DConnectStub::CallMethod: IPC_SendMessage()=%08X\n", rv));
if (NS_FAILED(rv))
{
// INVOKE message wasn't delivered; clean up wrappers
dConnect->ReleaseWrappers(wrappers, mPeerID);
return rv;
}
// now, we wait for the method call to complete. during that time, it's
// possible that we'll receive other method call requests. we'll process
// those while waiting for out method call to complete. it's critical that
// we do so since those other method calls might need to complete before
// out method call can complete!
DConnectInvokeCompletion completion(mPeerID, &invoke);
do
{
rv = IPC_WaitMessage(IPC_SENDER_ANY, kDConnectTargetID,
&completion.GetSelector(), &completion,
DCON_WAIT_TIMEOUT);
LOG(("DConnectStub::CallMethod: IPC_WaitMessage()=%08X\n", rv));
if (NS_FAILED(rv))
{
// INVOKE message wasn't received; clean up wrappers
dConnect->ReleaseWrappers(wrappers, mPeerID);
return rv;
}
}
while (completion.IsPending());
ipcMessageReader reader(completion.Params(), completion.ParamsLen());
rv = completion.GetResult();
if (NS_SUCCEEDED(rv))
{
PRUint8 i;
// handle out-params and retvals: DCON_OP_INVOKE_REPLY has the data
for (i=0; i<paramCount; ++i)
{
const nsXPTParamInfo ¶mInfo = aInfo->GetParam(i);
if (paramInfo.IsOut() || paramInfo.IsRetval())
DeserializeResult(reader, paramInfo.GetType(), aParams[i]);
}
// fixup any interface pointers using a second pass so we can properly
// handle INTERFACE_IS referencing an IID that is an out param! This pass is
// also used to deserialize arrays (array data goes after all other params).
for (i=0; i<paramCount && NS_SUCCEEDED(rv); ++i)
{
const nsXPTParamInfo ¶mInfo = aInfo->GetParam(i);
if ((paramInfo.IsOut() || paramInfo.IsRetval()) && aParams[i].val.p)
{
const nsXPTType &type = paramInfo.GetType();
if (type.IsInterfacePointer())
{
// grab the DConAddr value temporarily stored in the param, restore
// the pointer and free the temporarily allocated memory.
DConAddrPlusPtr *dptr = (DConAddrPlusPtr *)aParams[i].val.p;
PtrBits bits = dptr->addr;
aParams[i].val.p = dptr->p;
nsMemory::Free((void *)dptr);
// DeserializeInterfaceParamBits needs IID only if it's a remote object
nsID iid;
if (bits & PTRBITS_REMOTE_BIT)
rv = dConnect->GetIIDForMethodParam(mIInfo, aInfo, paramInfo, type,
aMethodIndex, aParams, PR_FALSE,
iid);
if (NS_SUCCEEDED(rv))
{
nsISupports *obj = nsnull;
rv = dConnect->DeserializeInterfaceParamBits(bits, mPeerID, iid, obj);
if (NS_SUCCEEDED(rv))
*(void **)aParams[i].val.p = obj;
}
}
else if (type.IsArray())
{
void *array = nsnull;
rv = DeserializeArrayParam(dConnect, reader, mPeerID, mIInfo,
aMethodIndex, *aInfo, aParams, PR_FALSE,
paramInfo, PR_TRUE, array);
if (NS_SUCCEEDED(rv))
*(void **)aParams[i].val.p = array;
}
}
}
}
if (completion.Reply()->flags & DCON_OP_FLAGS_REPLY_EXCEPTION)
{
LOG(("got nsIException instance, will create a stub\n"));
nsIException *xcpt = nsnull;
rv = dConnect->DeserializeException (reader, mPeerID, &xcpt);
if (NS_SUCCEEDED(rv))
{
rv = em->SetCurrentException(xcpt);
NS_IF_RELEASE(xcpt);
}
NS_ASSERTION(NS_SUCCEEDED(rv), "failed to deserialize/set exception");
}
return NS_SUCCEEDED(rv) ? completion.GetResult() : rv;
}
//-----------------------------------------------------------------------------
class DConnectSetupCompletion : public DConnectCompletion
{
public:
DConnectSetupCompletion(PRUint32 peer, const DConnectSetup *setup)
: DConnectCompletion(peer, DCON_OP_SETUP_REPLY, setup->request_index)
, mSetup(setup)
, mStatus(NS_OK)
{}
void OnResponseAvailable(PRUint32 sender, const DConnectOp *op, PRUint32 opLen)
{
if (op->opcode_major != DCON_OP_SETUP_REPLY)
{
NS_NOTREACHED("unexpected response");
mStatus = NS_ERROR_UNEXPECTED;
return;
}
if (opLen < sizeof(DConnectSetupReply))
{
NS_NOTREACHED("unexpected response size");
mStatus = NS_ERROR_UNEXPECTED;
return;
}
const DConnectSetupReply *reply = (const DConnectSetupReply *) op;
LOG(("got SETUP_REPLY: status=%x instance=0x%Lx\n", reply->status, reply->instance));
mStatus = reply->status;
if (NS_SUCCEEDED(reply->status))
{
// ensure ipcDConnectService is not deleted before we finish
nsRefPtr <ipcDConnectService> dConnect (ipcDConnectService::GetInstance());
nsresult rv;
if (dConnect)
rv = dConnect->CreateStub(mSetup->iid, sender, reply->instance,
getter_AddRefs(mStub));
else
rv = NS_ERROR_FAILURE;
if (NS_FAILED(rv))
mStatus = rv;
}
if (reply->flags & DCON_OP_FLAGS_REPLY_EXCEPTION)
{
const PRUint8 *params = ((const PRUint8 *) op) + sizeof (DConnectSetupReply);
const PRUint32 paramsLen = opLen - sizeof (DConnectSetupReply);
ipcMessageReader reader(params, paramsLen);
LOG(("got nsIException instance, will create a stub\n"));
nsresult rv;
nsCOMPtr <nsIExceptionService> es;
es = do_GetService (NS_EXCEPTIONSERVICE_CONTRACTID, &rv);
if (NS_SUCCEEDED(rv))
{
nsCOMPtr <nsIExceptionManager> em;
rv = es->GetCurrentExceptionManager (getter_AddRefs(em));
if (NS_SUCCEEDED(rv))
{
// ensure ipcDConnectService is not deleted before we finish
nsRefPtr <ipcDConnectService> dConnect (ipcDConnectService::GetInstance());
if (dConnect)
{
nsIException *xcpt = nsnull;
rv = dConnect->DeserializeException (reader, sender, &xcpt);
if (NS_SUCCEEDED(rv))
{
rv = em->SetCurrentException(xcpt);
NS_IF_RELEASE(xcpt);
}
}
else
rv = NS_ERROR_UNEXPECTED;
}
}
NS_ASSERTION(NS_SUCCEEDED(rv), "failed to deserialize/set exception");
if (NS_FAILED(rv))
mStatus = rv;
}
}
nsresult GetStub(void **aInstancePtr)
{
if (NS_FAILED(mStatus))
return mStatus;
DConnectStub *stub = mStub;
NS_IF_ADDREF(stub);
*aInstancePtr = stub;
return NS_OK;
}
private:
const DConnectSetup *mSetup;
nsresult mStatus;
nsRefPtr<DConnectStub> mStub;
};
// static
nsresult
SetupPeerInstance(PRUint32 aPeerID, DConnectSetup *aMsg, PRUint32 aMsgLen,
void **aInstancePtr)
{
*aInstancePtr = nsnull;
aMsg->opcode_major = DCON_OP_SETUP;
aMsg->flags = 0;
aMsg->request_index = NewRequestIndex();
// temporarily disable the DConnect target observer to block normal processing
// of pending messages through the event queue.
IPC_DISABLE_MESSAGE_OBSERVER_FOR_SCOPE(kDConnectTargetID);
// send SETUP message, expect SETUP_REPLY
nsresult rv = IPC_SendMessage(aPeerID, kDConnectTargetID,
(const PRUint8 *) aMsg, aMsgLen);
if (NS_FAILED(rv))
return rv;
DConnectSetupCompletion completion(aPeerID, aMsg);
// need to allow messages from other clients to be processed immediately
// to avoid distributed dead locks. the completion's OnMessageAvailable
// will call our default OnMessageAvailable if it receives any message
// other than the one for which it is waiting.
do
{
rv = IPC_WaitMessage(IPC_SENDER_ANY, kDConnectTargetID,
&completion.GetSelector(), &completion,
DCON_WAIT_TIMEOUT);
if (NS_FAILED(rv))
break;
rv = completion.GetStub(aInstancePtr);
}
while (NS_SUCCEEDED(rv) && *aInstancePtr == nsnull);
return rv;
}
//-----------------------------------------------------------------------------
#if defined(DCONNECT_MULTITHREADED) && !defined(DCONNECT_WITH_IPRT_REQ_POOL)
class DConnectWorker : public nsIRunnable
{
public:
// no reference counting
NS_IMETHOD_(nsrefcnt) AddRef() { return 1; }
NS_IMETHOD_(nsrefcnt) Release() { return 1; }
NS_IMETHOD QueryInterface(const nsIID &aIID, void **aInstancePtr);
NS_DECL_NSIRUNNABLE
DConnectWorker(ipcDConnectService *aDConnect) : mDConnect (aDConnect), mIsRunnable (PR_FALSE) {}
NS_HIDDEN_(nsresult) Init();
NS_HIDDEN_(void) Join() { mThread->Join(); };
NS_HIDDEN_(bool) IsRunning() { return mIsRunnable; };
private:
nsCOMPtr <nsIThread> mThread;
ipcDConnectService *mDConnect;
// Indicate if thread might be quickly joined on shutdown.
volatile bool mIsRunnable;
};
NS_IMPL_QUERY_INTERFACE1(DConnectWorker, nsIRunnable)
nsresult
DConnectWorker::Init()
{
return NS_NewThread(getter_AddRefs(mThread), this, 0, PR_JOINABLE_THREAD);
}
NS_IMETHODIMP
DConnectWorker::Run()
{
LOG(("DConnect Worker thread started.\n"));
mIsRunnable = PR_TRUE;
nsAutoMonitor mon(mDConnect->mPendingMon);
while (!mDConnect->mDisconnected)
{
DConnectRequest *request = mDConnect->mPendingQ.First();
if (!request)
{
mDConnect->mWaitingWorkers++;
{
// Note: we attempt to enter mWaitingWorkersMon from under mPendingMon
// here, but it should be safe because it's the only place where it
// happens. We could exit mPendingMon first, but we need to wait on it
// shorltly afterwards, which in turn will require us to enter it again
// just to exit immediately and start waiting. This seems to me a bit
// stupid (exit->enter->exit->wait).
nsAutoMonitor workersMon(mDConnect->mWaitingWorkersMon);
workersMon.NotifyAll();
}
nsresult rv = mon.Wait();
mDConnect->mWaitingWorkers--;
if (NS_FAILED(rv))
break;
}
else
{
LOG(("DConnect Worker thread got request.\n"));
// remove the request from the queue
mDConnect->mPendingQ.RemoveFirst();
PRBool pendingQEmpty = mDConnect->mPendingQ.IsEmpty();
mon.Exit();
if (pendingQEmpty)
{
nsAutoMonitor workersMon(mDConnect->mWaitingWorkersMon);
workersMon.NotifyAll();
}
// request is processed outside the queue monitor
mDConnect->OnIncomingRequest(request->peer, request->op, request->opLen);
delete request;
mon.Enter();
}
}
mIsRunnable = PR_FALSE;
LOG(("DConnect Worker thread stopped.\n"));
return NS_OK;
}
// called only on DConnect message thread
nsresult
ipcDConnectService::CreateWorker()
{
DConnectWorker *worker = new DConnectWorker(this);
if (!worker)
return NS_ERROR_OUT_OF_MEMORY;
nsresult rv = worker->Init();
if (NS_SUCCEEDED(rv))
{
nsAutoLock lock(mLock);
/* tracking an illegal join in Shutdown. */
NS_ASSERTION(!mDisconnected, "CreateWorker racing Shutdown");
if (!mWorkers.AppendElement(worker))
rv = NS_ERROR_OUT_OF_MEMORY;
}
if (NS_FAILED(rv))
delete worker;
return rv;
}
#endif // defined(DCONNECT_MULTITHREADED) && !defined(DCONNECT_WITH_IPRT_REQ_POOL)
//-----------------------------------------------------------------------------
ipcDConnectService::ipcDConnectService()
: mLock(NULL)
, mStubLock(NULL)
, mDisconnected(PR_TRUE)
, mStubQILock(NULL)
#if defined(DCONNECT_WITH_IPRT_REQ_POOL)
, mhReqPool(NIL_RTREQPOOL)
#endif
{
}
PR_STATIC_CALLBACK(PLDHashOperator)
EnumerateInstanceMapAndDelete (const DConnectInstanceKey::Key &aKey,
DConnectInstance *aData,
void *userArg)
{
// this method is to be called on ipcDConnectService shutdown only
// (after which no DConnectInstances may exist), so forcibly delete them
// disregarding the reference counter
#ifdef IPC_LOGGING
if (IPC_LOG_ENABLED())
{
const char *name;
aData->InterfaceInfo()->GetNameShared(&name);
LOG(("ipcDConnectService: WARNING: deleting unreleased "
"instance=%p iface=%p {%s}\n", aData, aData->RealInstance(), name));
}
#endif
delete aData;
return PL_DHASH_NEXT;
}
ipcDConnectService::~ipcDConnectService()
{
if (!mDisconnected)
Shutdown();
mInstance = nsnull;
PR_DestroyLock(mStubQILock);
PR_DestroyLock(mStubLock);
PR_DestroyLock(mLock);
#if defined(DCONNECT_WITH_IPRT_REQ_POOL)
RTReqPoolRelease(mhReqPool);
mhReqPool = NIL_RTREQPOOL;
#endif
}
//-----------------------------------------------------------------------------
nsresult
ipcDConnectService::Init()
{
nsresult rv;
LOG(("ipcDConnectService::Init.\n"));
rv = IPC_DefineTarget(kDConnectTargetID, this);
if (NS_FAILED(rv))
return rv;
rv = IPC_AddClientObserver(this);
if (NS_FAILED(rv))
return rv;
mLock = PR_NewLock();
if (!mLock)
return NS_ERROR_OUT_OF_MEMORY;
if (!mInstances.Init())
return NS_ERROR_OUT_OF_MEMORY;
if (!mInstanceSet.Init())
return NS_ERROR_OUT_OF_MEMORY;
mStubLock = PR_NewLock();
if (!mStubLock)
return NS_ERROR_OUT_OF_MEMORY;
if (!mStubs.Init())
return NS_ERROR_OUT_OF_MEMORY;
mIIM = do_GetService(NS_INTERFACEINFOMANAGER_SERVICE_CONTRACTID, &rv);
if (NS_FAILED(rv))
return rv;
mStubQILock = PR_NewLock();
if (!mStubQILock)
return NS_ERROR_OUT_OF_MEMORY;
#if defined(DCONNECT_MULTITHREADED)
# if defined(DCONNECT_WITH_IPRT_REQ_POOL)
int vrc = RTReqPoolCreate(1024 /*cMaxThreads*/, 10*RT_MS_1SEC /*cMsMinIdle*/,
8 /*cThreadsPushBackThreshold */, RT_MS_1SEC /* cMsMaxPushBack */,
"DCon", &mhReqPool);
if (RT_FAILURE(vrc))
{
mhReqPool = NIL_RTREQPOOL;
return NS_ERROR_FAILURE;
}
mDisconnected = PR_FALSE;
# else
mPendingMon = nsAutoMonitor::NewMonitor("DConnect pendingQ monitor");
if (!mPendingMon)
return NS_ERROR_OUT_OF_MEMORY;
mWaitingWorkers = 0;
mWaitingWorkersMon = nsAutoMonitor::NewMonitor("DConnect waiting workers monitor");
if (!mWaitingWorkersMon)
return NS_ERROR_OUT_OF_MEMORY;
/* The DConnectWorker::Run method checks the ipcDConnectService::mDisconnected.
* So mDisconnect must be set here to avoid an immediate exit of the worker thread.
*/
mDisconnected = PR_FALSE;
// create a single worker thread
rv = CreateWorker();
if (NS_FAILED(rv))
{
mDisconnected = PR_TRUE;
return rv;
}
# endif
#else
mDisconnected = PR_FALSE;
#endif
mInstance = this;
LOG(("ipcDConnectService::Init NS_OK.\n"));
return NS_OK;
}
void
ipcDConnectService::Shutdown()
{
{
// set the disconnected flag to make sensitive public methods
// unavailale from other (non worker) threads.
nsAutoLock lock(mLock);
mDisconnected = PR_TRUE;
}
#if defined(DCONNECT_MULTITHREADED)
# if defined(DCONNECT_WITH_IPRT_REQ_POOL)
# if defined(DCONNECT_STATS)
fprintf(stderr, "ipcDConnectService Stats\n");
fprintf(stderr,
" => number of worker threads: %llu (created %llu)\n"
" => requests processed: %llu\n"
" => avg requests process time: %llu ns\n"
" => avg requests waiting time: %llu ns\n",
RTReqPoolGetStat(mhReqPool, RTREQPOOLSTAT_THREADS),
RTReqPoolGetStat(mhReqPool, RTREQPOOLSTAT_THREADS_CREATED),
RTReqPoolGetStat(mhReqPool, RTREQPOOLSTAT_REQUESTS_PROCESSED),
RTReqPoolGetStat(mhReqPool, RTREQPOOLSTAT_NS_AVERAGE_REQ_PROCESSING),
RTReqPoolGetStat(mhReqPool, RTREQPOOLSTAT_NS_AVERAGE_REQ_QUEUED)
);
# endif
RTReqPoolRelease(mhReqPool);
mhReqPool = NIL_RTREQPOOL;
# else
{
// remove all pending messages and wake up all workers.
// mDisconnected is true here and they will terminate execution after
// processing the last request.
nsAutoMonitor mon(mPendingMon);
mPendingQ.DeleteAll();
mon.NotifyAll();
}
#if defined(DCONNECT_STATS)
fprintf(stderr, "ipcDConnectService Stats\n");
fprintf(stderr, " => number of worker threads: %d\n", mWorkers.Count());
LOG(("ipcDConnectService Stats\n"));
LOG((" => number of worker threads: %d\n", mWorkers.Count()));
#endif
// Iterate over currently running worker threads
// during VBOX_XPCOM_SHUTDOWN_TIMEOUT_MS, join() those who
// exited a working loop and abandon ones which have not
// managed to do that when timeout occurred.
LOG(("Worker threads: %d\n", mWorkers.Count()));
uint64_t tsStart = RTTimeMilliTS();
while ((tsStart + VBOX_XPCOM_SHUTDOWN_TIMEOUT_MS ) > RTTimeMilliTS() && mWorkers.Count() > 0)
{
// Some array elements might be deleted while iterating. Going from the last
// to the first array element (intentionally) in order to do not conflict with
// array indexing once element is deleted.
for (int i = mWorkers.Count() - 1; i >= 0; i--)
{
DConnectWorker *worker = NS_STATIC_CAST(DConnectWorker *, mWorkers[i]);
if (worker->IsRunning() == PR_FALSE)
{
LOG(("Worker %p joined.\n", worker));
worker->Join();
delete worker;
mWorkers.RemoveElementAt(i);
}
}
/* Double-ckeck if we already allowed to quit. */
if ((tsStart + VBOX_XPCOM_SHUTDOWN_TIMEOUT_MS ) < RTTimeMilliTS() || mWorkers.Count() == 0)
break;
// Relax a bit before the next round.
RTThreadSleep(10);
}
LOG(("There are %d thread(s) left.\n", mWorkers.Count()));
// If there are some running threads left, terminate the process.
if (mWorkers.Count() > 0)
exit(1);
nsAutoMonitor::DestroyMonitor(mWaitingWorkersMon);
nsAutoMonitor::DestroyMonitor(mPendingMon);
# endif
#endif
// make sure we have released all instances
mInstances.EnumerateRead(EnumerateInstanceMapAndDelete, nsnull);
mInstanceSet.Clear();
mInstances.Clear();
// clear the stub table
// (this will not release stubs -- it's the client's responsibility)
mStubs.Clear();
}
// this should be inlined
nsresult
ipcDConnectService::GetInterfaceInfo(const nsID &iid, nsIInterfaceInfo **result)
{
return mIIM->GetInfoForIID(&iid, result);
}
// this is adapted from the version in xpcwrappednative.cpp
nsresult
ipcDConnectService::GetIIDForMethodParam(nsIInterfaceInfo *iinfo,
const nsXPTMethodInfo *methodInfo,
const nsXPTParamInfo ¶mInfo,
const nsXPTType &type,
PRUint16 methodIndex,
nsXPTCMiniVariant *dispatchParams,
PRBool isXPTCVariantArray,
nsID &result)
{
PRUint8 argnum, tag = type.TagPart();
nsresult rv;
if (tag == nsXPTType::T_INTERFACE)
{
rv = iinfo->GetIIDForParamNoAlloc(methodIndex, ¶mInfo, &result);
}
else if (tag == nsXPTType::T_INTERFACE_IS)
{
rv = iinfo->GetInterfaceIsArgNumberForParam(methodIndex, ¶mInfo, &argnum);
if (NS_FAILED(rv))
return rv;
const nsXPTParamInfo& arg_param = methodInfo->GetParam(argnum);
const nsXPTType& arg_type = arg_param.GetType();
// The xpidl compiler ensures this. We reaffirm it for safety.
if (!arg_type.IsPointer() || arg_type.TagPart() != nsXPTType::T_IID)
return NS_ERROR_UNEXPECTED;
nsID *p = (nsID *) GET_PARAM(dispatchParams, isXPTCVariantArray, argnum).val.p;
if (!p)
return NS_ERROR_UNEXPECTED;
result = *p;
}
else
rv = NS_ERROR_UNEXPECTED;
return rv;
}
nsresult
ipcDConnectService::StoreInstance(DConnectInstance *wrapper)
{
#ifdef IPC_LOGGING
if (IPC_LOG_ENABLED())
{
const char *name;
wrapper->InterfaceInfo()->GetNameShared(&name);
LOG(("ipcDConnectService::StoreInstance(): instance=%p iface=%p {%s}\n",
wrapper, wrapper->RealInstance(), name));
}
#endif
nsresult rv = mInstanceSet.Put(wrapper);
if (NS_SUCCEEDED(rv))
{
rv = mInstances.Put(wrapper->GetKey(), wrapper)
? NS_OK : NS_ERROR_OUT_OF_MEMORY;
if (NS_FAILED(rv))
mInstanceSet.Remove(wrapper);
}
return rv;
}
void
ipcDConnectService::DeleteInstance(DConnectInstance *wrapper,
PRBool locked /* = PR_FALSE */)
{
if (!locked)
PR_Lock(mLock);
#ifdef IPC_LOGGING
if (IPC_LOG_ENABLED())
{
const char *name;
wrapper->InterfaceInfo()->GetNameShared(&name);
LOG(("ipcDConnectService::DeleteInstance(): instance=%p iface=%p {%s}\n",
wrapper, wrapper->RealInstance(), name));
}
#endif
mInstances.Remove(wrapper->GetKey());
mInstanceSet.Remove(wrapper);
if (!locked)
PR_Unlock(mLock);
}
PRBool
ipcDConnectService::FindInstanceAndAddRef(PRUint32 peer,
const nsISupports *obj,
const nsIID *iid,
DConnectInstance **wrapper)
{
PRBool result = mInstances.Get(DConnectInstanceKey::Key(peer, obj, iid), wrapper);
if (result)
(*wrapper)->AddRef();
return result;
}
PRBool
ipcDConnectService::CheckInstanceAndAddRef(DConnectInstance *wrapper, PRUint32 peer)
{
nsAutoLock lock (mLock);
if (mInstanceSet.Contains(wrapper) && wrapper->Peer() == peer)
{
wrapper->AddRef();
return PR_TRUE;
}
return PR_FALSE;
}
nsresult
ipcDConnectService::StoreStub(DConnectStub *stub)
{
#ifdef IPC_LOGGING
if (IPC_LOG_ENABLED())
{
const char *name;
nsCOMPtr<nsIInterfaceInfo> iinfo;
stub->GetInterfaceInfo(getter_AddRefs(iinfo));
iinfo->GetNameShared(&name);
LOG(("ipcDConnectService::StoreStub(): stub=%p instance=0x%Lx {%s}\n",
stub, stub->Instance(), name));
}
#endif
return mStubs.Put(stub->GetKey(), stub)
? NS_OK : NS_ERROR_OUT_OF_MEMORY;
}
void
ipcDConnectService::DeleteStub(DConnectStub *stub)
{
#ifdef IPC_LOGGING
if (IPC_LOG_ENABLED())
{
const char *name;
nsCOMPtr<nsIInterfaceInfo> iinfo;
stub->GetInterfaceInfo(getter_AddRefs(iinfo));
iinfo->GetNameShared(&name);
LOG(("ipcDConnectService::DeleteStub(): stub=%p instance=0x%Lx {%s}\n",
stub, stub->Instance(), name));
}
#endif
// this method is intended to be called only from DConnectStub::Release().
// the stub object is not deleted when removed from the table, because
// DConnectStub pointers are not owned by mStubs.
mStubs.Remove(stub->GetKey());
}
// not currently used
#if 0
PRBool
ipcDConnectService::FindStubAndAddRef(PRUint32 peer, const DConAddr instance,
DConnectStub **stub)
{
nsAutoLock stubLock (mStubLock);
PRBool result = mStubs.Get(DConnectStubKey::Key(peer, instance), stub);
if (result)
NS_ADDREF(*stub);
return result;
}
#endif
NS_IMPL_THREADSAFE_ISUPPORTS3(ipcDConnectService, ipcIDConnectService,
ipcIMessageObserver,
ipcIClientObserver)
NS_IMETHODIMP
ipcDConnectService::CreateInstance(PRUint32 aPeerID,
const nsID &aCID,
const nsID &aIID,
void **aInstancePtr)
{
DConnectSetupClassID msg;
msg.opcode_minor = DCON_OP_SETUP_NEW_INST_CLASSID;
msg.iid = aIID;
msg.classid = aCID;
return SetupPeerInstance(aPeerID, &msg, sizeof(msg), aInstancePtr);
}
NS_IMETHODIMP
ipcDConnectService::CreateInstanceByContractID(PRUint32 aPeerID,
const char *aContractID,
const nsID &aIID,
void **aInstancePtr)
{
size_t slen = strlen(aContractID);
size_t size = sizeof(DConnectSetupContractID) + slen;
DConnectSetupContractID *msg =
(DConnectSetupContractID *) malloc(size);
msg->opcode_minor = DCON_OP_SETUP_NEW_INST_CONTRACTID;
msg->iid = aIID;
memcpy(&msg->contractid, aContractID, slen + 1);
nsresult rv = SetupPeerInstance(aPeerID, msg, size, aInstancePtr);
free(msg);
return rv;
}
NS_IMETHODIMP
ipcDConnectService::GetService(PRUint32 aPeerID,
const nsID &aCID,
const nsID &aIID,
void **aInstancePtr)
{
DConnectSetupClassID msg;
msg.opcode_minor = DCON_OP_SETUP_GET_SERV_CLASSID;
msg.iid = aIID;
msg.classid = aCID;
return SetupPeerInstance(aPeerID, &msg, sizeof(msg), aInstancePtr);
}
NS_IMETHODIMP
ipcDConnectService::GetServiceByContractID(PRUint32 aPeerID,
const char *aContractID,
const nsID &aIID,
void **aInstancePtr)
{
size_t slen = strlen(aContractID);
size_t size = sizeof(DConnectSetupContractID) + slen;
DConnectSetupContractID *msg =
(DConnectSetupContractID *) malloc(size);
msg->opcode_minor = DCON_OP_SETUP_GET_SERV_CONTRACTID;
msg->iid = aIID;
memcpy(&msg->contractid, aContractID, slen + 1);
nsresult rv = SetupPeerInstance(aPeerID, msg, size, aInstancePtr);
free(msg);
return rv;
}
//-----------------------------------------------------------------------------
NS_IMETHODIMP
ipcDConnectService::OnMessageAvailable(PRUint32 aSenderID,
const nsID &aTarget,
const PRUint8 *aData,
PRUint32 aDataLen)
{
if (mDisconnected)
return NS_ERROR_NOT_INITIALIZED;
const DConnectOp *op = (const DConnectOp *) aData;
LOG (("ipcDConnectService::OnMessageAvailable: "
"senderID=%d, opcode_major=%d, index=%d\n",
aSenderID, op->opcode_major, op->request_index));
#if defined(DCONNECT_MULTITHREADED)
# if defined(DCONNECT_WITH_IPRT_REQ_POOL)
void *pvDataDup = RTMemDup(aData, aDataLen);
if (RT_UNLIKELY(!pvDataDup))
return NS_ERROR_OUT_OF_MEMORY;
int rc = RTReqPoolCallVoidNoWait(mhReqPool, (PFNRT)ProcessMessageOnWorkerThread, 4,
this, aSenderID, pvDataDup, aDataLen);
if (RT_FAILURE(rc))
return NS_ERROR_FAILURE;
# else
nsAutoMonitor mon(mPendingMon);
mPendingQ.Append(new DConnectRequest(aSenderID, op, aDataLen));
// notify a worker
mon.Notify();
mon.Exit();
// Yield the cpu so a worker can get a chance to start working without too much fuss.
PR_Sleep(PR_INTERVAL_NO_WAIT);
mon.Enter();
// examine the queue
if (mPendingQ.Count() > mWaitingWorkers)
{
// wait a little while to let the workers empty the queue.
mon.Exit();
{
PRUint32 ticks = PR_MillisecondsToInterval(PR_MIN(mWorkers.Count() / 20 + 1, 10));
nsAutoMonitor workersMon(mWaitingWorkersMon);
workersMon.Wait(ticks);
}
mon.Enter();
// examine the queue again
if (mPendingQ.Count() > mWaitingWorkers)
{
// we need one more worker
nsresult rv = CreateWorker();
NS_ASSERTION(NS_SUCCEEDED(rv), "failed to create one more worker thread");
rv = rv;
}
}
# endif
#else
OnIncomingRequest(aSenderID, op, aDataLen);
#endif
return NS_OK;
}
struct PruneInstanceMapForPeerArgs
{
ipcDConnectService *that;
PRUint32 clientID;
nsVoidArray &wrappers;
};
PR_STATIC_CALLBACK(PLDHashOperator)
PruneInstanceMapForPeer (const DConnectInstanceKey::Key &aKey,
DConnectInstance *aData,
void *userArg)
{
PruneInstanceMapForPeerArgs *args = (PruneInstanceMapForPeerArgs *)userArg;
NS_ASSERTION(args, "PruneInstanceMapForPeerArgs is NULL");
if (args && args->clientID == aData->Peer())
{
nsrefcnt countIPC = aData->ReleaseIPC(PR_TRUE /* locked */);
LOG(("ipcDConnectService::PruneInstanceMapForPeer: "
"instance=%p: %d IPC refs to release\n",
aData, countIPC + 1));
// release all IPC instances of the "officially dead" client (see
// #OnRelease() to understand why it must be done under the lock). Note
// that due to true multithreading, late OnRelease() requests may still
// happen on other worker threads *after* OnClientStateChange() has been
// called, but it's OK because the instance will be removed from the map
// by the below code alreay and won't be deleted for the second time.
while (countIPC)
{
countIPC = aData->ReleaseIPC(PR_TRUE /* locked */);
aData->Release();
}
// collect the instance for the last release
// (we'll do it later outside the lock)
if (!args->wrappers.AppendElement(aData))
{
NS_NOTREACHED("Not enough memory");
// bad but what to do
aData->Release();
}
}
return PL_DHASH_NEXT;
}
NS_IMETHODIMP
ipcDConnectService::OnClientStateChange(PRUint32 aClientID,
PRUint32 aClientState)
{
LOG(("ipcDConnectService::OnClientStateChange: aClientID=%d, aClientState=%d\n",
aClientID, aClientState));
if (aClientState == ipcIClientObserver::CLIENT_DOWN)
{
if (aClientID == IPC_SENDER_ANY)
{
// a special case: our IPC system is being shutdown, try to safely
// uninitialize everything...
Shutdown();
}
else
{
LOG(("ipcDConnectService::OnClientStateChange: "
"pruning all instances created for peer %d...\n", aClientID));
nsVoidArray wrappers;
{
nsAutoLock lock (mLock);
// make sure we have removed all instances from instance maps
PruneInstanceMapForPeerArgs args = { this, aClientID, wrappers };
mInstances.EnumerateRead(PruneInstanceMapForPeer, (void *)&args);
}
LOG(("ipcDConnectService::OnClientStateChange: "
"%d lost instances\n", wrappers.Count()));
// release all pending references left after PruneInstanceMapForPeer().
// this may call wrapper destructors so it's important to do that
// outside the lock because destructors will release the real objects
// which may need to make asynchronous use our service
for (PRInt32 i = 0; i < wrappers.Count(); ++i)
((DConnectInstance *) wrappers[i])->Release();
}
}
return NS_OK;
}
//-----------------------------------------------------------------------------
#if defined(DCONNECT_WITH_IPRT_REQ_POOL)
/**
* Function called by the request thread pool to process a incoming request in
* the context of a worker thread.
*/
/* static */ DECLCALLBACK(void)
ipcDConnectService::ProcessMessageOnWorkerThread(ipcDConnectService *aThis, PRUint32 aSenderID, void *aData, PRUint32 aDataLen)
{
if (!aThis->mDisconnected)
aThis->OnIncomingRequest(aSenderID, (const DConnectOp *)aData, aDataLen);
RTMemFree(aData);
}
#endif
void
ipcDConnectService::OnIncomingRequest(PRUint32 peer, const DConnectOp *op, PRUint32 opLen)
{
switch (op->opcode_major)
{
case DCON_OP_SETUP:
OnSetup(peer, (const DConnectSetup *) op, opLen);
break;
case DCON_OP_RELEASE:
OnRelease(peer, (const DConnectRelease *) op);
break;
case DCON_OP_INVOKE:
OnInvoke(peer, (const DConnectInvoke *) op, opLen);
break;
default:
NS_NOTREACHED("unknown opcode major");
}
}
void
ipcDConnectService::OnSetup(PRUint32 peer, const DConnectSetup *setup, PRUint32 opLen)
{
nsISupports *instance = nsnull;
nsresult rv = NS_ERROR_FAILURE;
switch (setup->opcode_minor)
{
// CreateInstance
case DCON_OP_SETUP_NEW_INST_CLASSID:
{
const DConnectSetupClassID *setupCI = (const DConnectSetupClassID *) setup;
nsCOMPtr<nsIComponentManager> compMgr;
rv = NS_GetComponentManager(getter_AddRefs(compMgr));
if (NS_SUCCEEDED(rv))
rv = compMgr->CreateInstance(setupCI->classid, nsnull, setupCI->iid, (void **) &instance);
break;
}
// CreateInstanceByContractID
case DCON_OP_SETUP_NEW_INST_CONTRACTID:
{
const DConnectSetupContractID *setupCI = (const DConnectSetupContractID *) setup;
nsCOMPtr<nsIComponentManager> compMgr;
rv = NS_GetComponentManager(getter_AddRefs(compMgr));
if (NS_SUCCEEDED(rv))
rv = compMgr->CreateInstanceByContractID(setupCI->contractid, nsnull, setupCI->iid, (void **) &instance);
break;
}
// GetService
case DCON_OP_SETUP_GET_SERV_CLASSID:
{
const DConnectSetupClassID *setupCI = (const DConnectSetupClassID *) setup;
nsCOMPtr<nsIServiceManager> svcMgr;
rv = NS_GetServiceManager(getter_AddRefs(svcMgr));
if (NS_SUCCEEDED(rv))
rv = svcMgr->GetService(setupCI->classid, setupCI->iid, (void **) &instance);
break;
}
// GetServiceByContractID
case DCON_OP_SETUP_GET_SERV_CONTRACTID:
{
const DConnectSetupContractID *setupCI = (const DConnectSetupContractID *) setup;
nsCOMPtr<nsIServiceManager> svcMgr;
rv = NS_GetServiceManager(getter_AddRefs(svcMgr));
if (NS_SUCCEEDED(rv))
rv = svcMgr->GetServiceByContractID(setupCI->contractid, setupCI->iid, (void **) &instance);
break;
}
// QueryInterface
case DCON_OP_SETUP_QUERY_INTERFACE:
{
const DConnectSetupQueryInterface *setupQI = (const DConnectSetupQueryInterface *) setup;
DConnectInstance *QIinstance = (DConnectInstance *)setupQI->instance;
// make sure we've been sent a valid wrapper
if (!CheckInstanceAndAddRef(QIinstance, peer))
{
NS_NOTREACHED("instance wrapper not found");
rv = NS_ERROR_INVALID_ARG;
}
else
{
rv = QIinstance->RealInstance()->QueryInterface(setupQI->iid, (void **) &instance);
QIinstance->Release();
}
break;
}
default:
NS_NOTREACHED("unexpected minor opcode");
rv = NS_ERROR_UNEXPECTED;
break;
}
nsVoidArray wrappers;
// now, create instance wrapper, and store it in our instances set.
// this allows us to keep track of object references held on behalf of a
// particular peer. we can use this information to cleanup after a peer
// that disconnects without sending RELEASE messages for its objects.
DConnectInstance *wrapper = nsnull;
if (NS_SUCCEEDED(rv))
{
nsCOMPtr<nsIInterfaceInfo> iinfo;
rv = GetInterfaceInfo(setup->iid, getter_AddRefs(iinfo));
if (NS_SUCCEEDED(rv))
{
nsAutoLock lock (mLock);
// first try to find an existing wrapper for the given object
if (!FindInstanceAndAddRef(peer, instance, &setup->iid, &wrapper))
{
wrapper = new DConnectInstance(peer, iinfo, instance);
if (!wrapper)
rv = NS_ERROR_OUT_OF_MEMORY;
else
{
rv = StoreInstance(wrapper);
if (NS_FAILED(rv))
{
delete wrapper;
wrapper = nsnull;
}
else
{
// reference the newly created wrapper
wrapper->AddRef();
}
}
}
if (wrapper)
{
// increase the second, IPC-only, reference counter (mandatory before
// trying wrappers.AppendElement() to make sure ReleaseIPC() will remove
// the wrapper from the instance map on failure)
wrapper->AddRefIPC();
if (!wrappers.AppendElement(wrapper))
{
wrapper->ReleaseIPC();
wrapper->Release();
rv = NS_ERROR_OUT_OF_MEMORY;
}
}
// wrapper remains referenced when passing it to the client
// (will be released upon DCON_OP_RELEASE)
}
}
NS_IF_RELEASE(instance);
nsCOMPtr <nsIException> exception;
PRBool got_exception = PR_FALSE;
if (rv != NS_OK)
{
// try to fetch an nsIException possibly set by one of the setup methods
nsresult rv2;
nsCOMPtr <nsIExceptionService> es;
es = do_GetService(NS_EXCEPTIONSERVICE_CONTRACTID, &rv2);
if (NS_SUCCEEDED(rv2))
{
nsCOMPtr <nsIExceptionManager> em;
rv2 = es->GetCurrentExceptionManager (getter_AddRefs (em));
if (NS_SUCCEEDED(rv2))
{
rv2 = em->GetCurrentException (getter_AddRefs (exception));
if (NS_SUCCEEDED(rv2))
{
LOG(("got nsIException instance, will serialize\n"));
got_exception = PR_TRUE;
}
}
}
NS_ASSERTION(NS_SUCCEEDED(rv2), "failed to get/serialize exception");
if (NS_FAILED(rv2))
rv = rv2;
}
ipcMessageWriter writer(64);
DConnectSetupReply msg;
msg.opcode_major = DCON_OP_SETUP_REPLY;
msg.opcode_minor = 0;
msg.flags = 0;
msg.request_index = setup->request_index;
msg.instance = (DConAddr)(uintptr_t)wrapper;
msg.status = rv;
if (got_exception)
msg.flags |= DCON_OP_FLAGS_REPLY_EXCEPTION;
writer.PutBytes(&msg, sizeof(msg));
if (got_exception)
{
rv = SerializeException(writer, peer, exception, wrappers);
NS_ASSERTION(NS_SUCCEEDED(rv), "failed to get/serialize exception");
}
// fire off SETUP_REPLY, don't wait for a response
if (NS_FAILED(rv))
rv = IPC_SendMessage(peer, kDConnectTargetID,
(const PRUint8 *) &msg, sizeof(msg));
else
rv = IPC_SendMessage(peer, kDConnectTargetID,
writer.GetBuffer(), writer.GetSize());
if (NS_FAILED(rv))
{
LOG(("unable to send SETUP_REPLY: rv=%x\n", rv));
ReleaseWrappers(wrappers, peer);
}
}
void
ipcDConnectService::OnRelease(PRUint32 peer, const DConnectRelease *release)
{
LOG(("ipcDConnectService::OnRelease [peer=%u instance=0x%Lx]\n",
peer, release->instance));
DConnectInstance *wrapper = (DConnectInstance *)release->instance;
nsAutoLock lock (mLock);
// make sure we've been sent a valid wrapper from the same peer we created
// this wrapper for
if (mInstanceSet.Contains(wrapper) && wrapper->Peer() == peer)
{
// release the IPC reference from under the lock to ensure atomicity of
// the "check + possible delete" sequence ("delete" is remove this wrapper
// from the instance map when the IPC reference counter drops to zero)
wrapper->ReleaseIPC(PR_TRUE /* locked */);
// leave the lock before Release() because it may call the destructor
// which will release the real object which may need to make asynchronous
// use our service
lock.unlock();
wrapper->Release();
}
else
{
// it is possible that the client disconnection event handler has released
// all client instances before the DCON_OP_RELEASE message sent by the
// client gets processed here (because of true multithreading). Just log
// a debug warning
LOG(("ipcDConnectService::OnRelease: WARNING: "
"instance wrapper %p for peer %d not found", wrapper, peer));
}
}
void
ipcDConnectService::OnInvoke(PRUint32 peer, const DConnectInvoke *invoke, PRUint32 opLen)
{
LOG(("ipcDConnectService::OnInvoke [peer=%u instance=0x%Lx method=%u]\n",
peer, invoke->instance, invoke->method_index));
DConnectInstance *wrapper = (DConnectInstance *)invoke->instance;
ipcMessageReader reader((const PRUint8 *) (invoke + 1), opLen - sizeof(*invoke));
const nsXPTMethodInfo *methodInfo;
nsXPTCVariant *params = nsnull;
nsCOMPtr<nsIInterfaceInfo> iinfo = nsnull;
PRUint8 i, paramCount = 0, paramUsed = 0;
nsresult rv;
nsCOMPtr <nsIException> exception;
PRBool got_exception = PR_FALSE;
// make sure we've been sent a valid wrapper
if (!CheckInstanceAndAddRef(wrapper, peer))
{
NS_NOTREACHED("instance wrapper not found");
wrapper = nsnull;
rv = NS_ERROR_INVALID_ARG;
goto end;
}
iinfo = wrapper->InterfaceInfo();
rv = iinfo->GetMethodInfo(invoke->method_index, &methodInfo);
if (NS_FAILED(rv))
goto end;
paramCount = methodInfo->GetParamCount();
LOG((" iface=%p\n", wrapper->RealInstance()));
LOG((" name=%s\n", methodInfo->GetName()));
LOG((" param-count=%u\n", (PRUint32) paramCount));
LOG((" request-index=%d\n", (PRUint32) invoke->request_index));
params = new nsXPTCVariant[paramCount];
if (!params)
{
rv = NS_ERROR_OUT_OF_MEMORY;
goto end;
}
// setup |params| for xptcall
for (i=0; i<paramCount; ++i, ++paramUsed)
{
const nsXPTParamInfo ¶mInfo = methodInfo->GetParam(i);
// XXX are inout params an issue?
// yes, we will need to do v.ptr = &v.val for them (DeserializeParam doesn't
// currently do that) to let the callee correctly pick it up and change.
if (paramInfo.IsIn() && !paramInfo.IsDipper())
rv = DeserializeParam(reader, paramInfo.GetType(), params[i]);
else
rv = SetupParam(paramInfo, params[i]);
if (NS_FAILED(rv))
goto end;
}
// fixup any interface pointers. we do this with a second pass so that
// we can properly handle INTERFACE_IS. This pass is also used to deserialize
// arrays (array data goes after all other params).
for (i=0; i<paramCount; ++i)
{
const nsXPTParamInfo ¶mInfo = methodInfo->GetParam(i);
if (paramInfo.IsIn())
{
const nsXPTType &type = paramInfo.GetType();
if (type.IsInterfacePointer())
{
// grab the DConAddr value temporarily stored in the param
#ifdef VBOX
PtrBits bits = params[i].val.u64;
#else
PtrBits bits = (PtrBits)(uintptr_t) params[i].val.p;
#endif
// DeserializeInterfaceParamBits needs IID only if it's a remote object
nsID iid;
if (bits & PTRBITS_REMOTE_BIT)
{
rv = GetIIDForMethodParam(iinfo, methodInfo, paramInfo, type,
invoke->method_index, params, PR_TRUE, iid);
if (NS_FAILED(rv))
goto end;
}
nsISupports *obj = nsnull;
rv = DeserializeInterfaceParamBits(bits, peer, iid, obj);
if (NS_FAILED(rv))
goto end;
params[i].val.p = obj;
// mark as interface to let FinishParam() release this param
params[i].SetValIsInterface();
}
else if (type.IsArray())
{
void *array = nsnull;
rv = DeserializeArrayParam(this, reader, peer, iinfo,
invoke->method_index, *methodInfo, params,
PR_TRUE, paramInfo, PR_FALSE, array);
if (NS_FAILED(rv))
goto end;
params[i].val.p = array;
// mark to let FinishParam() free this param
params[i].SetValIsAllocated();
}
}
}
rv = XPTC_InvokeByIndex(wrapper->RealInstance(),
invoke->method_index,
paramCount,
params);
if (rv != NS_OK)
{
// try to fetch an nsIException possibly set by the method
nsresult rv2;
nsCOMPtr <nsIExceptionService> es;
es = do_GetService(NS_EXCEPTIONSERVICE_CONTRACTID, &rv2);
if (NS_SUCCEEDED(rv2))
{
nsCOMPtr <nsIExceptionManager> em;
rv2 = es->GetCurrentExceptionManager (getter_AddRefs (em));
if (NS_SUCCEEDED(rv2))
{
rv2 = em->GetCurrentException (getter_AddRefs (exception));
if (NS_SUCCEEDED(rv2))
{
LOG(("got nsIException instance, will serialize\n"));
got_exception = PR_TRUE;
}
}
}
NS_ASSERTION(NS_SUCCEEDED(rv2), "failed to get/serialize exception");
if (NS_FAILED(rv2))
rv = rv2;
}
end:
LOG(("sending INVOKE_REPLY: rv=%x\n", rv));
// balance CheckInstanceAndAddRef()
if (wrapper)
wrapper->Release();
ipcMessageWriter writer(64);
DConnectInvokeReply reply;
reply.opcode_major = DCON_OP_INVOKE_REPLY;
reply.opcode_minor = 0;
reply.flags = 0;
reply.request_index = invoke->request_index;
reply.result = rv;
if (got_exception)
reply.flags |= DCON_OP_FLAGS_REPLY_EXCEPTION;
writer.PutBytes(&reply, sizeof(reply));
nsVoidArray wrappers;
if (NS_SUCCEEDED(rv) && params)
{
// serialize out-params and retvals
for (i=0; i<paramCount; ++i)
{
const nsXPTParamInfo paramInfo = methodInfo->GetParam(i);
if (paramInfo.IsRetval() || paramInfo.IsOut())
{
const nsXPTType &type = paramInfo.GetType();
if (type.IsInterfacePointer())
{
nsID iid;
rv = GetIIDForMethodParam(iinfo, methodInfo, paramInfo, type,
invoke->method_index, params, PR_TRUE, iid);
if (NS_SUCCEEDED(rv))
rv = SerializeInterfaceParam(writer, peer, iid,
(nsISupports *) params[i].val.p, wrappers);
}
else
rv = SerializeParam(writer, type, params[i]);
if (NS_FAILED(rv))
{
reply.result = rv;
break;
}
}
}
if (NS_SUCCEEDED(rv))
{
// serialize output array parameters after everything else since the
// deserialization procedure will need to get a size_is value which may be
// stored in any preceeding or following param
for (i=0; i<paramCount; ++i)
{
const nsXPTParamInfo ¶mInfo = methodInfo->GetParam(i);
if (paramInfo.GetType().IsArray() &&
(paramInfo.IsRetval() || paramInfo.IsOut()))
{
rv = SerializeArrayParam(this, writer, peer, iinfo, invoke->method_index,
*methodInfo, params, PR_TRUE, paramInfo,
params[i].val.p, wrappers);
if (NS_FAILED(rv))
{
reply.result = rv;
break;
}
}
}
}
}
if (got_exception)
{
rv = SerializeException(writer, peer, exception, wrappers);
NS_ASSERTION(NS_SUCCEEDED(rv), "failed to get/serialize exception");
}
if (NS_FAILED(rv))
rv = IPC_SendMessage(peer, kDConnectTargetID, (const PRUint8 *) &reply, sizeof(reply));
else
rv = IPC_SendMessage(peer, kDConnectTargetID, writer.GetBuffer(), writer.GetSize());
if (NS_FAILED(rv))
{
LOG(("unable to send INVOKE_REPLY: rv=%x\n", rv));
ReleaseWrappers(wrappers, peer);
}
if (params)
{
// free individual elements of arrays (note: before freeing arrays
// themselves in FinishParam())
for (i=0; i<paramUsed; ++i)
{
const nsXPTParamInfo ¶mInfo = methodInfo->GetParam(i);
if (paramInfo.GetType().IsArray())
FinishArrayParam(iinfo, invoke->method_index, *methodInfo,
params, PR_TRUE, paramInfo, params[i]);
}
for (i=0; i<paramUsed; ++i)
FinishParam(params[i]);
delete[] params;
}
}
| 53,539 |
471 |
<filename>src/test/java/net/greghaines/jesque/SleepAction.java
package net.greghaines.jesque;
/**
* An action that sleeps for the given number of milliseconds.
*
* @author <NAME>
*/
public class SleepAction implements Runnable {
private final int millis;
/**
* Construct a sleep action.
*
* @param millis The number of milliseconds to sleep.
*/
public SleepAction(int millis) {
this.millis = millis;
}
@Override
public void run() {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
}
}
}
| 239 |
335 |
{
"word": "Vegetarianism",
"definitions": [
"The practice of not eating meat or fish, especially for moral, religious, or health reasons."
],
"parts-of-speech": "Noun"
}
| 73 |
2,151 |
<filename>chromeos/system/version_loader.h
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROMEOS_SYSTEM_VERSION_LOADER_H_
#define CHROMEOS_SYSTEM_VERSION_LOADER_H_
#include <string>
#include "base/callback_forward.h"
#include "chromeos/chromeos_export.h"
#include "chromeos/dbus/cryptohome_client.h"
namespace chromeos {
namespace version_loader {
enum VersionFormat {
VERSION_SHORT,
VERSION_SHORT_WITH_DATE,
VERSION_FULL,
};
using GetTpmVersionCallback = base::OnceCallback<void(
const CryptohomeClient::TpmVersionInfo& tpm_version_info)>;
// Gets the version.
// If |full_version| is true version string with extra info is extracted,
// otherwise it's in short format x.x.xx.x.
// May block.
CHROMEOS_EXPORT std::string GetVersion(VersionFormat format);
// Gets the TPM version information. Asynchronous, result is passed on to
// callback.
CHROMEOS_EXPORT void GetTpmVersion(GetTpmVersionCallback callback);
// Gets the ARC version.
// May block.
CHROMEOS_EXPORT std::string GetARCVersion();
// Gets the firmware info.
// May block.
CHROMEOS_EXPORT std::string GetFirmware();
// Extracts the firmware from the file.
CHROMEOS_EXPORT std::string ParseFirmware(const std::string& contents);
} // namespace version_loader
} // namespace chromeos
#endif // CHROMEOS_SYSTEM_VERSION_LOADER_H_
| 469 |
765 |
<filename>lldb/include/lldb/Target/UnixSignals.h
//===-- UnixSignals.h -------------------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#ifndef lldb_UnixSignals_h_
#define lldb_UnixSignals_h_
#include <map>
#include <string>
#include <vector>
#include "lldb/Utility/ConstString.h"
#include "lldb/lldb-private.h"
#include "llvm/ADT/Optional.h"
namespace lldb_private {
class UnixSignals {
public:
static lldb::UnixSignalsSP Create(const ArchSpec &arch);
static lldb::UnixSignalsSP CreateForHost();
// Constructors and Destructors
UnixSignals();
virtual ~UnixSignals();
const char *GetSignalAsCString(int32_t signo) const;
bool SignalIsValid(int32_t signo) const;
int32_t GetSignalNumberFromName(const char *name) const;
const char *GetSignalInfo(int32_t signo, bool &should_suppress,
bool &should_stop, bool &should_notify) const;
bool GetShouldSuppress(int32_t signo) const;
bool SetShouldSuppress(int32_t signo, bool value);
bool SetShouldSuppress(const char *signal_name, bool value);
bool GetShouldStop(int32_t signo) const;
bool SetShouldStop(int32_t signo, bool value);
bool SetShouldStop(const char *signal_name, bool value);
bool GetShouldNotify(int32_t signo) const;
bool SetShouldNotify(int32_t signo, bool value);
bool SetShouldNotify(const char *signal_name, bool value);
// These provide an iterator through the signals available on this system.
// Call GetFirstSignalNumber to get the first entry, then iterate on
// GetNextSignalNumber till you get back LLDB_INVALID_SIGNAL_NUMBER.
int32_t GetFirstSignalNumber() const;
int32_t GetNextSignalNumber(int32_t current_signal) const;
int32_t GetNumSignals() const;
int32_t GetSignalAtIndex(int32_t index) const;
ConstString GetShortName(ConstString name) const;
// We assume that the elements of this object are constant once it is
// constructed, since a process should never need to add or remove symbols as
// it runs. So don't call these functions anywhere but the constructor of
// your subclass of UnixSignals or in your Process Plugin's GetUnixSignals
// method before you return the UnixSignal object.
void AddSignal(int signo, const char *name, bool default_suppress,
bool default_stop, bool default_notify,
const char *description, const char *alias = nullptr);
void RemoveSignal(int signo);
// Returns a current version of the data stored in this class. Version gets
// incremented each time Set... method is called.
uint64_t GetVersion() const;
// Returns a vector of signals that meet criteria provided in arguments. Each
// should_[suppress|stop|notify] flag can be None - no filtering by this
// flag true - only signals that have it set to true are returned false -
// only signals that have it set to true are returned
std::vector<int32_t> GetFilteredSignals(llvm::Optional<bool> should_suppress,
llvm::Optional<bool> should_stop,
llvm::Optional<bool> should_notify);
protected:
// Classes that inherit from UnixSignals can see and modify these
struct Signal {
ConstString m_name;
ConstString m_alias;
std::string m_description;
bool m_suppress : 1, m_stop : 1, m_notify : 1;
Signal(const char *name, bool default_suppress, bool default_stop,
bool default_notify, const char *description, const char *alias);
~Signal() {}
};
virtual void Reset();
typedef std::map<int32_t, Signal> collection;
collection m_signals;
// This version gets incremented every time something is changing in this
// class, including when we call AddSignal from the constructor. So after the
// object is constructed m_version is going to be > 0 if it has at least one
// signal registered in it.
uint64_t m_version = 0;
// GDBRemote signals need to be copyable.
UnixSignals(const UnixSignals &rhs);
const UnixSignals &operator=(const UnixSignals &rhs) = delete;
};
} // Namespace lldb
#endif // lldb_UnixSignals_h_
| 1,443 |
2,177 |
<gh_stars>1000+
/**
* 分页
*/package org.nutz.dao.pager;
| 32 |
2,293 |
<gh_stars>1000+
#include "Test.h"
#include "Pattern.h"
#include "dsp/svm_functions.h"
class SVMF32:public Client::Suite
{
public:
SVMF32(Testing::testID_t id);
virtual void setUp(Testing::testID_t,std::vector<Testing::param_t>& params,Client::PatternMgr *mgr);
virtual void tearDown(Testing::testID_t,Client::PatternMgr *mgr);
private:
#include "SVMF32_decl.h"
Client::Pattern<float32_t> samples;
Client::Pattern<int16_t> dims;
Client::Pattern<float32_t> params;
arm_svm_linear_instance_f32 linear;
arm_svm_polynomial_instance_f32 poly;
arm_svm_rbf_instance_f32 rbf;
arm_svm_sigmoid_instance_f32 sigmoid;
int vecDim,nbSupportVectors,nbTestSamples,degree;
int32_t classes[2]={0,0};
float32_t intercept;
const float32_t *supportVectors;
const float32_t *dualCoefs;
float32_t coef0, gamma;
float32_t *inp;
int nbLinear=0,nbPoly=0,nbRBF=0,nbSigmoid=0;
enum {
LINEAR=1,
POLY=2,
RBF=3,
SIGMOID=4
} kind;
};
| 717 |
429 |
<reponame>DEDZTBH/ejml
/*
* Copyright (c) 2021, <NAME>. All Rights Reserved.
*
* This file is part of Efficient Java Matrix Library (EJML).
*
* 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.ejml.data;
import org.ejml.EjmlStandardJUnit;
import org.ejml.UtilEjml;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotSame;
/**
* @author <NAME>
*/
public class TestDMatrixRBlock extends EjmlStandardJUnit {
@Test
public void testGeneric() {
GenericTestsDMatrixD1 g;
g = new GenericTestsDMatrixD1() {
@Override
protected DMatrixD1 createMatrix(int numRows, int numCols) {
return new DMatrixRBlock(numRows,numCols,10);
}
};
g.allTests();
}
@Test
public void constructor_double_array() {
double[] foo = new double[]{1,2,3};
DMatrixRMaj m = new DMatrixRMaj(foo);
assertEquals(3,m.numRows);
assertEquals(1,m.numCols);
assertNotSame(foo, m.data);
for (int i = 0; i < foo.length; i++) {
assertEquals(foo[i],m.get(i), UtilEjml.TEST_F64);
}
}
@Test
public void constructor_double2_array() {
double[][] foo = new double[][]{{1},{2},{3}};
DMatrixRMaj m = new DMatrixRMaj(foo);
assertEquals(3,m.numRows);
assertEquals(1,m.numCols);
for (int i = 0; i < foo.length; i++) {
assertEquals(foo[i][0],m.get(i), UtilEjml.TEST_F64);
}
}
}
| 886 |
500 |
<filename>sdk/src/androidTest/java/ly/count/android/sdk/EventTests.java<gh_stars>100-1000
/*
Copyright (c) 2012, 2013, 2014 Countly
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package ly.count.android.sdk;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
@RunWith(AndroidJUnit4.class)
@SuppressWarnings("ConstantConditions")
public class EventTests {
@Before
public void setUp() {
Countly.sharedInstance().setLoggingEnabled(true);
}
@Test
public void testConstructor() {
final Event event = new Event();
assertNull(event.key);
assertNull(event.segmentation);
assertEquals(0, event.count);
assertEquals(0, event.timestamp);
assertEquals(0.0d, event.sum, 0.0000001);
}
@Test
public void testEqualsAndHashCode() {
final Event event1 = new Event();
final Event event2 = new Event();
//noinspection ObjectEqualsNull
assertFalse(event1.equals(null));
assertNotEquals(event1, new Object());
assertEquals(event1, event2);
assertEquals(event1.hashCode(), event2.hashCode());
event1.key = "eventKey";
assertNotEquals(event1, event2);
assertNotEquals(event2, event1);
assertTrue(event1.hashCode() != event2.hashCode());
event2.key = "eventKey";
assertEquals(event1, event2);
assertEquals(event2, event1);
assertEquals(event1.hashCode(), event2.hashCode());
event1.timestamp = 1234;
assertNotEquals(event1, event2);
assertNotEquals(event2, event1);
assertTrue(event1.hashCode() != event2.hashCode());
event2.timestamp = 1234;
assertEquals(event1, event2);
assertEquals(event2, event1);
assertEquals(event1.hashCode(), event2.hashCode());
event1.segmentation = new HashMap<>();
assertNotEquals(event1, event2);
assertNotEquals(event2, event1);
assertTrue(event1.hashCode() != event2.hashCode());
event2.segmentation = new HashMap<>();
assertEquals(event1, event2);
assertEquals(event2, event1);
assertEquals(event1.hashCode(), event2.hashCode());
event1.segmentation.put("segkey", "segvalue");
assertNotEquals(event1, event2);
assertNotEquals(event2, event1);
assertTrue(event1.hashCode() != event2.hashCode());
event2.segmentation.put("segkey", "segvalue");
assertEquals(event1, event2);
assertEquals(event2, event1);
assertEquals(event1.hashCode(), event2.hashCode());
event1.sum = 3.2;
event2.count = 42;
assertEquals(event1, event2);
assertEquals(event2, event1);
assertEquals(event1.hashCode(), event2.hashCode());
}
@Test
public void testToJSON_nullSegmentation() throws JSONException {
final Event event = new Event();
event.key = "eventKey";
event.timestamp = 1234;
event.count = 42;
event.sum = 3.2;
final JSONObject jsonObj = event.toJSON();
assertEquals(6, jsonObj.length());
assertEquals(event.key, jsonObj.getString("key"));
assertEquals(event.timestamp, jsonObj.getInt("timestamp"));
assertEquals(event.count, jsonObj.getInt("count"));
assertEquals(event.sum, jsonObj.getDouble("sum"), 0.0000001);
}
@Test
public void testToJSON_emptySegmentation() throws JSONException {
final Event event = new Event();
event.key = "eventKey";
event.timestamp = 1234;
event.count = 42;
event.sum = 3.2;
event.segmentation = new HashMap<>();
event.segmentationInt = new HashMap<>();
event.segmentationDouble = new HashMap<>();
event.segmentationBoolean = new HashMap<>();
final JSONObject jsonObj = event.toJSON();
assertEquals(7, jsonObj.length());
assertEquals(event.key, jsonObj.getString("key"));
assertEquals(event.timestamp, jsonObj.getInt("timestamp"));
assertEquals(event.count, jsonObj.getInt("count"));
assertEquals(event.sum, jsonObj.getDouble("sum"), 0.0000001);
assertEquals(0, jsonObj.getJSONObject("segmentation").length());
}
@Test
public void testToJSON_withSegmentation() throws JSONException {
final Event event = new Event();
event.key = "eventKey";
event.timestamp = 1234;
event.count = 42;
event.sum = 3.2;
event.segmentation = new HashMap<>();
event.segmentationInt = new HashMap<>();
event.segmentationDouble = new HashMap<>();
event.segmentationBoolean = new HashMap<>();
event.segmentation.put("segkey", "segvalue");
event.segmentationInt.put("segkey1", 123);
event.segmentationDouble.put("segkey2", 544.43d);
event.segmentationBoolean.put("segkey3", true);
final JSONObject jsonObj = event.toJSON();
assertEquals(7, jsonObj.length());
assertEquals(event.key, jsonObj.getString("key"));
assertEquals(event.timestamp, jsonObj.getInt("timestamp"));
assertEquals(event.count, jsonObj.getInt("count"));
assertEquals(event.sum, jsonObj.getDouble("sum"), 0.0000001);
assertEquals(4, jsonObj.getJSONObject("segmentation").length());
assertEquals(event.segmentation.get("segkey"), jsonObj.getJSONObject("segmentation").getString("segkey"));
assertEquals(event.segmentationInt.get("segkey1").intValue(), jsonObj.getJSONObject("segmentation").getInt("segkey1"));
assertEquals(event.segmentationDouble.get("segkey2").doubleValue(), jsonObj.getJSONObject("segmentation").getDouble("segkey2"), 0.0001d);
assertEquals(event.segmentationBoolean.get("segkey3").booleanValue(), jsonObj.getJSONObject("segmentation").getBoolean("segkey3"));
}
@Test
public void testToJSON_sumNaNCausesJSONException() throws JSONException {
final Event event = new Event();
event.key = "eventKey";
event.timestamp = 1234;
event.count = 42;
event.sum = Double.NaN;
event.segmentation = new HashMap<>();
event.segmentation.put("segkey", "segvalue");
final JSONObject jsonObj = event.toJSON();
assertEquals(6, jsonObj.length());
assertEquals(event.key, jsonObj.getString("key"));
assertEquals(event.timestamp, jsonObj.getInt("timestamp"));
assertEquals(event.count, jsonObj.getInt("count"));
assertEquals(1, jsonObj.getJSONObject("segmentation").length());
assertEquals(event.segmentation.get("segkey"), jsonObj.getJSONObject("segmentation").getString("segkey"));
}
@Test
public void testFromJSON_nullJSONObj() {
try {
Event.fromJSON(null);
fail("Expected NPE when calling Event.fromJSON with null");
} catch (NullPointerException ignored) {
// success
}
}
@Test
public void testFromJSON_noKeyCausesJSONException() {
final JSONObject jsonObj = new JSONObject();
assertNull(Event.fromJSON(jsonObj));
}
@Test
public void testFromJSON_nullKey() throws JSONException {
final JSONObject jsonObj = new JSONObject();
jsonObj.put("key", JSONObject.NULL);
assertNull(Event.fromJSON(jsonObj));
}
@Test
public void testFromJSON_emptyKey() throws JSONException {
final JSONObject jsonObj = new JSONObject();
jsonObj.put("key", "");
assertNull(Event.fromJSON(jsonObj));
}
@Test
public void testFromJSON_keyOnly() throws JSONException {
final Event expected = new Event();
expected.key = "eventKey";
final JSONObject jsonObj = new JSONObject();
jsonObj.put("key", expected.key);
final Event actual = Event.fromJSON(jsonObj);
assertEquals(expected, actual);
assertEquals(expected.count, actual.count);
assertEquals(expected.sum, actual.sum, 0.0000001);
}
@Test
public void testFromJSON_keyOnly_nullOtherValues() throws JSONException {
final Event expected = new Event();
expected.key = "eventKey";
final JSONObject jsonObj = new JSONObject();
jsonObj.put("key", expected.key);
jsonObj.put("timestamp", JSONObject.NULL);
jsonObj.put("count", JSONObject.NULL);
jsonObj.put("sum", JSONObject.NULL);
final Event actual = Event.fromJSON(jsonObj);
assertEquals(expected, actual);
assertEquals(expected.count, actual.count);
assertEquals(expected.sum, actual.sum, 0.0000001);
}
@Test
public void testFromJSON_noSegmentation() throws JSONException {
final Event expected = new Event();
expected.key = "eventKey";
expected.timestamp = 1234;
expected.count = 42;
expected.sum = 3.2;
final JSONObject jsonObj = new JSONObject();
jsonObj.put("key", expected.key);
jsonObj.put("timestamp", expected.timestamp);
jsonObj.put("count", expected.count);
jsonObj.put("sum", expected.sum);
final Event actual = Event.fromJSON(jsonObj);
assertEquals(expected, actual);
assertEquals(expected.count, actual.count);
assertEquals(expected.sum, actual.sum, 0.0000001);
}
@Test
public void testFromJSON_nullSegmentation() throws JSONException {
final Event expected = new Event();
expected.key = "eventKey";
expected.timestamp = 1234;
expected.count = 42;
expected.sum = 3.2;
final JSONObject jsonObj = new JSONObject();
jsonObj.put("key", expected.key);
jsonObj.put("timestamp", expected.timestamp);
jsonObj.put("count", expected.count);
jsonObj.put("sum", expected.sum);
jsonObj.put("segmentation", JSONObject.NULL);
final Event actual = Event.fromJSON(jsonObj);
assertEquals(expected, actual);
assertEquals(expected.count, actual.count);
assertEquals(expected.sum, actual.sum, 0.0000001);
}
@Test
public void testFromJSON_segmentationNotADictionary() throws JSONException {
final Event expected = new Event();
expected.key = "eventKey";
expected.timestamp = 1234;
expected.count = 42;
expected.sum = 3.2;
final JSONObject jsonObj = new JSONObject();
jsonObj.put("key", expected.key);
jsonObj.put("timestamp", expected.timestamp);
jsonObj.put("count", expected.count);
jsonObj.put("sum", expected.sum);
jsonObj.put("segmentation", 1234);
assertNull(Event.fromJSON(jsonObj));
}
@Test
public void testFromJSON_emptySegmentation() throws JSONException {
final Event expected = new Event();
expected.key = "eventKey";
expected.timestamp = 1234;
expected.count = 42;
expected.sum = 3.2;
expected.segmentation = new HashMap<>();
final JSONObject jsonObj = new JSONObject();
jsonObj.put("key", expected.key);
jsonObj.put("timestamp", expected.timestamp);
jsonObj.put("count", expected.count);
jsonObj.put("sum", expected.sum);
jsonObj.put("segmentation", new JSONObject(expected.segmentation));
final Event actual = Event.fromJSON(jsonObj);
assertEquals(expected, actual);
assertEquals(expected.count, actual.count);
assertEquals(expected.sum, actual.sum, 0.0000001);
}
@Test
public void testFromJSON_withSegmentation() throws JSONException {
final Event expected = new Event();
expected.key = "eventKey";
expected.timestamp = 1234;
expected.count = 42;
expected.sum = 3.2;
expected.segmentation = new HashMap<>();
expected.segmentation.put("segkey", "segvalue");
final JSONObject jsonObj = new JSONObject();
jsonObj.put("key", expected.key);
jsonObj.put("timestamp", expected.timestamp);
jsonObj.put("count", expected.count);
jsonObj.put("sum", expected.sum);
jsonObj.put("segmentation", new JSONObject(expected.segmentation));
final Event actual = Event.fromJSON(jsonObj);
assertEquals(expected, actual);
assertEquals(expected.count, actual.count);
assertEquals(expected.sum, actual.sum, 0.0000001);
}
@Test
public void testFromJSON_withSegmentation_nonStringValues() throws JSONException {
final Event expected = new Event();
expected.key = "eventKey";
expected.timestamp = 1234;
expected.count = 42;
expected.sum = 3.2;
expected.segmentation = new HashMap<>();
expected.segmentation.put("sk1", "vall");
expected.segmentationDouble = new HashMap<>();
expected.segmentationDouble.put("sk2", 334.33d);
expected.segmentationInt = new HashMap<>();
expected.segmentationInt.put("segkey", 1234);
expected.segmentationBoolean = new HashMap<>();
expected.segmentationBoolean.put("sk3", true);
final Map<Object, Object> valueMap = new HashMap<>();
valueMap.put("segkey", 1234);
valueMap.put("sk1", "vall");
valueMap.put("sk2", 334.33d);
valueMap.put("sk3", true);
final JSONObject jsonObj = new JSONObject();
jsonObj.put("key", expected.key);
jsonObj.put("timestamp", expected.timestamp);
jsonObj.put("count", expected.count);
jsonObj.put("sum", expected.sum);
jsonObj.put("segmentation", new JSONObject(valueMap));
final Event actual = Event.fromJSON(jsonObj);
assertEquals(expected, actual);
assertEquals(expected.count, actual.count);
assertEquals(expected.sum, actual.sum, 0.0000001);
}
@Test
public void testSegmentationSorter() {
String[] keys = new String[] { "a", "b", "c", "d", "e", "f", "l", "r" };
Map<String, Object> automaticViewSegmentation = new HashMap<>();
automaticViewSegmentation.put(keys[0], 2);
automaticViewSegmentation.put(keys[1], 12);
automaticViewSegmentation.put(keys[2], 123);
automaticViewSegmentation.put(keys[3], 4.44d);
automaticViewSegmentation.put(keys[4], "Six");
automaticViewSegmentation.put(keys[5], "asdSix");
automaticViewSegmentation.put(keys[6], false);
automaticViewSegmentation.put(keys[7], true);
HashMap<String, String> segmentsString = new HashMap<>();
HashMap<String, Integer> segmentsInt = new HashMap<>();
HashMap<String, Double> segmentsDouble = new HashMap<>();
HashMap<String, Boolean> segmentsBoolean = new HashMap<>();
HashMap<String, Object> segmentsReminder = new HashMap<>();
Utils.fillInSegmentation(automaticViewSegmentation, segmentsString, segmentsInt, segmentsDouble, segmentsBoolean, segmentsReminder);
assertEquals(automaticViewSegmentation.size(), keys.length);
assertEquals(segmentsInt.size(), 3);
assertEquals(segmentsDouble.size(), 1);
assertEquals(segmentsString.size(), 2);
assertEquals(segmentsBoolean.size(), 2);
assertEquals(segmentsReminder.size(), 0);
assertEquals(segmentsInt.get(keys[0]).intValue(), 2);
assertEquals(segmentsInt.get(keys[1]).intValue(), 12);
assertEquals(segmentsInt.get(keys[2]).intValue(), 123);
assertEquals(segmentsDouble.get(keys[3]).doubleValue(), 4.44d, 0.00001);
assertEquals(segmentsString.get(keys[4]), "Six");
assertEquals(segmentsString.get(keys[5]), "asdSix");
assertEquals(segmentsBoolean.get(keys[6]), false);
assertEquals(segmentsBoolean.get(keys[7]), true);
}
@Test
public void testSegmentationSorterReminder() {
String[] keys = new String[] { "a", "b", "c", "d", "e", "f", "l", "r" };
Map<String, Object> automaticViewSegmentation = new HashMap<>();
Object obj = new Object();
int[] arr = new int[] { 1, 2, 3 };
automaticViewSegmentation.put(keys[0], 2);
automaticViewSegmentation.put(keys[1], 12.2f);
automaticViewSegmentation.put(keys[2], 4.44d);
automaticViewSegmentation.put(keys[3], "Six");
automaticViewSegmentation.put(keys[4], obj);
automaticViewSegmentation.put(keys[5], arr);
automaticViewSegmentation.put(keys[6], false);
automaticViewSegmentation.put(keys[7], true);
HashMap<String, String> segmentsString = new HashMap<>();
HashMap<String, Integer> segmentsInt = new HashMap<>();
HashMap<String, Double> segmentsDouble = new HashMap<>();
HashMap<String, Boolean> segmentsBoolean = new HashMap<>();
HashMap<String, Object> segmentsReminder = new HashMap<>();
Utils.fillInSegmentation(automaticViewSegmentation, segmentsString, segmentsInt, segmentsDouble, segmentsBoolean, segmentsReminder);
assertEquals(automaticViewSegmentation.size(), keys.length);
assertEquals(segmentsInt.size(), 1);
assertEquals(segmentsDouble.size(), 1);
assertEquals(segmentsString.size(), 1);
assertEquals(segmentsReminder.size(), 3);
assertEquals(segmentsInt.get(keys[0]).intValue(), 2);
assertEquals(segmentsDouble.get(keys[2]).doubleValue(), 4.44d, 0.00001);
assertEquals(segmentsString.get(keys[3]), "Six");
assertEquals(segmentsReminder.get(keys[1]), 12.2f);
assertEquals(segmentsReminder.get(keys[4]), obj);
assertEquals(segmentsReminder.get(keys[5]), arr);
assertEquals(segmentsBoolean.get(keys[6]), false);
assertEquals(segmentsBoolean.get(keys[7]), true);
}
}
| 7,645 |
772 |
<gh_stars>100-1000
{
"danceFeedbackNeedNewDancer": "crwdns304606:0crwdne304606:0",
"danceFeedbackNoDancers": "crwdns304608:0crwdne304608:0",
"danceFeedbackNoBackground": "crwdns304610:0crwdne304610:0",
"danceFeedbackTooManyDancers": "crwdns304612:0crwdne304612:0",
"danceFeedbackUseSetSize": "crwdns304614:0crwdne304614:0",
"danceFeedbackUseSetTint": "crwdns304616:0crwdne304616:0",
"danceFeedbackUseStartMapping": "crwdns304618:0crwdne304618:0",
"danceFeedbackStartNewMove": "crwdns304620:0crwdne304620:0",
"danceFeedbackNeedDifferentDance": "crwdns304622:0crwdne304622:0",
"danceFeedbackNeedEveryTwoMeasures": "crwdns304624:0crwdne304624:0",
"danceFeedbackNeedMakeANewDancer": "crwdns304626:0crwdne304626:0",
"danceFeedbackKeyEvent": "crwdns404020:0crwdne404020:0",
"danceFeedbackDidntPress": "crwdns2067172:0crwdne2067172:0",
"danceFeedbackPressedKey": "crwdns2067174:0crwdne2067174:0",
"danceFeedbackNeedTwoDancers": "crwdns2067176:0crwdne2067176:0",
"danceFeedbackOnlyOneDancerMoved": "crwdns2067178:0crwdne2067178:0",
"danceFeedbackNeedLead": "crwdns2067180:0'{'x: 200, y: 200'}'crwdne2067180:0",
"danceFeedbackNeedBackup": "crwdns2067182:0crwdne2067182:0",
"danceFeedbackSetSize": "crwdns2067184:0crwdne2067184:0",
"measure": "crwdns331090:0crwdne331090:0"
}
| 606 |
2,605 |
// https://leetcode.com/problems/maximum-equal-frequency/
class Solution {
public:
int maxEqualFreq(vector<int>& nums) {
const int n = nums.size();
int answer = 0;
map<int,int> freq;
map<int,int> freq_freq;
for(int i = 0; i < n; i++) {
int x = nums[i];
if(freq[x] > 0) {
if(--freq_freq[freq[x]] == 0) {
freq_freq.erase(freq[x]);
}
}
++freq[nums[i]];
++freq_freq[freq[x]];
bool flag = false;
if((int) freq_freq.size() <= 2) {
// 3 3 3 3
pair<int,int> p = *freq_freq.begin();
if((int) freq_freq.size() == 1) {
if(p.first == 1) {
flag = true; // (1, 1, 1) -> (1, 1)
}
// (5)
if(p.second == 1) {
flag = true;
}
}
else {
pair<int,int> q = *freq_freq.rbegin();
// 5 5 5 1
if(p.first == 1 && p.second == 1) {
flag = true;
}
// 5 4 4 4 4
if(p.first + 1 == q.first && q.second == 1) {
flag = true;
}
}
}
if(flag) {
answer = i + 1;
}
}
return answer;
}
};
| 1,053 |
2,113 |
<gh_stars>1000+
//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
// Arcane-FX for MIT Licensed Open Source version of Torque 3D from GarageGames
// Copyright (C) 2015 Faust Logic, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
#include "afx/arcaneFX.h"
#include "materials/shaderData.h"
#include "gfx/gfxTransformSaver.h"
#include "scene/sceneRenderState.h"
#include "collision/concretePolyList.h"
#include "T3D/tsStatic.h"
#include "gfx/primBuilder.h"
#include "afx/ce/afxZodiacMgr.h"
#include "afx/afxZodiacGroundPlaneRenderer_T3D.h"
//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
const RenderInstType afxZodiacGroundPlaneRenderer::RIT_GroundPlaneZodiac("GroundPlaneZodiac");
afxZodiacGroundPlaneRenderer* afxZodiacGroundPlaneRenderer::master = 0;
IMPLEMENT_CONOBJECT(afxZodiacGroundPlaneRenderer);
ConsoleDocClass( afxZodiacGroundPlaneRenderer,
"@brief A render bin for zodiac rendering on GroundPlane objects.\n\n"
"This bin renders instances of AFX zodiac effects onto GroundPlane surfaces.\n\n"
"@ingroup RenderBin\n"
"@ingroup AFX\n"
);
afxZodiacGroundPlaneRenderer::afxZodiacGroundPlaneRenderer()
: RenderBinManager(RIT_GroundPlaneZodiac, 1.0f, 1.0f)
{
if (!master)
master = this;
shader_initialized = false;
}
afxZodiacGroundPlaneRenderer::afxZodiacGroundPlaneRenderer(F32 renderOrder, F32 processAddOrder)
: RenderBinManager(RIT_GroundPlaneZodiac, renderOrder, processAddOrder)
{
if (!master)
master = this;
shader_initialized = false;
}
afxZodiacGroundPlaneRenderer::~afxZodiacGroundPlaneRenderer()
{
if (this == master)
master = 0;
}
//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
void afxZodiacGroundPlaneRenderer::initShader()
{
if (shader_initialized)
return;
shader_initialized = true;
shader_consts = 0;
norm_norefl_zb_SB = norm_refl_zb_SB;
add_norefl_zb_SB = add_refl_zb_SB;
sub_norefl_zb_SB = sub_refl_zb_SB;
zodiac_shader = afxZodiacMgr::getGroundPlaneZodiacShader();
if (!zodiac_shader)
return;
GFXStateBlockDesc d;
d.cullDefined = true;
d.ffLighting = false;
d.blendDefined = true;
d.blendEnable = true;
d.zDefined = false;
d.zEnable = true;
d.zWriteEnable = false;
d.zFunc = GFXCmpLessEqual;
d.zSlopeBias = 0;
d.alphaDefined = true;
d.alphaTestEnable = true;
d.alphaTestRef = 0;
d.alphaTestFunc = GFXCmpGreater;
d.samplersDefined = true;
d.samplers[0] = GFXSamplerStateDesc::getClampLinear();
// normal
d.blendSrc = GFXBlendSrcAlpha;
d.blendDest = GFXBlendInvSrcAlpha;
//
d.cullMode = GFXCullCCW;
d.zBias = arcaneFX::sPolysoupZodiacZBias;
norm_norefl_zb_SB = GFX->createStateBlock(d);
//
d.cullMode = GFXCullCW;
d.zBias = arcaneFX::sPolysoupZodiacZBias;
norm_refl_zb_SB = GFX->createStateBlock(d);
// additive
d.blendSrc = GFXBlendSrcAlpha;
d.blendDest = GFXBlendOne;
//
d.cullMode = GFXCullCCW;
d.zBias = arcaneFX::sPolysoupZodiacZBias;
add_norefl_zb_SB = GFX->createStateBlock(d);
//
d.cullMode = GFXCullCW;
d.zBias = arcaneFX::sPolysoupZodiacZBias;
add_refl_zb_SB = GFX->createStateBlock(d);
// subtractive
d.blendSrc = GFXBlendZero;
d.blendDest = GFXBlendInvSrcColor;
//
d.cullMode = GFXCullCCW;
d.zBias = arcaneFX::sPolysoupZodiacZBias;
sub_norefl_zb_SB = GFX->createStateBlock(d);
//
d.cullMode = GFXCullCW;
d.zBias = arcaneFX::sPolysoupZodiacZBias;
sub_refl_zb_SB = GFX->createStateBlock(d);
shader_consts = zodiac_shader->getShader()->allocConstBuffer();
projection_sc = zodiac_shader->getShader()->getShaderConstHandle("$modelView");
color_sc = zodiac_shader->getShader()->getShaderConstHandle("$zodiacColor");
}
void afxZodiacGroundPlaneRenderer::clear()
{
Parent::clear();
groundPlane_zodiacs.clear();
}
void afxZodiacGroundPlaneRenderer::addZodiac(U32 zode_idx, const Point3F& pos, F32 ang, const GroundPlane* gp, F32 camDist)
{
groundPlane_zodiacs.increment();
GroundPlaneZodiacElem& elem = groundPlane_zodiacs.last();
elem.gp = gp;
elem.zode_idx = zode_idx;
elem.ang = ang;
elem.camDist = camDist;
}
afxZodiacGroundPlaneRenderer* afxZodiacGroundPlaneRenderer::getMaster()
{
if (!master)
master = new afxZodiacGroundPlaneRenderer;
return master;
}
//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
GFXStateBlock* afxZodiacGroundPlaneRenderer::chooseStateBlock(U32 blend, bool isReflectPass)
{
GFXStateBlock* sb = 0;
switch (blend)
{
case afxZodiacData::BLEND_ADDITIVE:
sb = (isReflectPass) ? add_refl_zb_SB : add_norefl_zb_SB;
break;
case afxZodiacData::BLEND_SUBTRACTIVE:
sb = (isReflectPass) ? sub_refl_zb_SB : sub_norefl_zb_SB;
break;
default: // afxZodiacData::BLEND_NORMAL:
sb = (isReflectPass) ? norm_refl_zb_SB : norm_norefl_zb_SB;
break;
}
return sb;
}
void afxZodiacGroundPlaneRenderer::render(SceneRenderState* state)
{
PROFILE_SCOPE(afxRenderZodiacGroundPlaneMgr_render);
// Early out if no ground-plane zodiacs to draw.
if (groundPlane_zodiacs.size() == 0)
return;
initShader();
if (!zodiac_shader)
return;
bool is_reflect_pass = state->isReflectPass();
// Automagically save & restore our viewport and transforms.
GFXTransformSaver saver;
MatrixF proj = GFX->getProjectionMatrix();
// Set up world transform
MatrixF world = GFX->getWorldMatrix();
proj.mul(world);
shader_consts->set(projection_sc, proj);
//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//
// RENDER EACH ZODIAC
//
for (S32 zz = 0; zz < groundPlane_zodiacs.size(); zz++)
{
GroundPlaneZodiacElem& elem = groundPlane_zodiacs[zz];
afxZodiacMgr::ZodiacSpec* zode = &afxZodiacMgr::terr_zodes[elem.zode_idx];
if (!zode)
continue;
if (is_reflect_pass)
{
//if ((zode->zflags & afxZodiacData::SHOW_IN_REFLECTIONS) == 0)
continue;
}
else
{
if ((zode->zflags & afxZodiacData::SHOW_IN_NON_REFLECTIONS) == 0)
continue;
}
F32 fadebias = zode->calcDistanceFadeBias(elem.camDist);
if (fadebias < 0.01f)
continue;
F32 cos_ang = mCos(elem.ang);
F32 sin_ang = mSin(elem.ang);
GFXStateBlock* sb = chooseStateBlock(zode->zflags & afxZodiacData::BLEND_MASK, is_reflect_pass);
GFX->setShader(zodiac_shader->getShader());
GFX->setStateBlock(sb);
GFX->setShaderConstBuffer(shader_consts);
// set the texture
GFX->setTexture(0, *zode->txr);
LinearColorF zode_color = (LinearColorF)zode->color;
zode_color.alpha *= fadebias;
shader_consts->set(color_sc, zode_color);
F32 rad_xy = zode->radius_xy;
F32 inv_radius = 1.0f/rad_xy;
F32 offset_xy = mSqrt(2*rad_xy*rad_xy);
F32 zx = zode->pos.x;
F32 zy = zode->pos.y;
F32 z = 0.00001f;
Point3F verts[4];
verts[0].set(zx+offset_xy, zy+offset_xy, z);
verts[1].set(zx-offset_xy, zy+offset_xy, z);
verts[2].set(zx-offset_xy, zy-offset_xy, z);
verts[3].set(zx+offset_xy, zy-offset_xy, z);
S32 vertind[6];
vertind[0] = 2;
vertind[1] = 1;
vertind[2] = 0;
vertind[3] = 3;
vertind[4] = 2;
vertind[5] = 0;
PrimBuild::begin(GFXTriangleList, 6);
for (U32 i = 0; i < 2; i++)
{
for (U32 j = 0; j < 3; j++)
{
const Point3F& vtx = verts[vertind[i*3+j]];
// compute UV
F32 u1 = (vtx.x - zode->pos.x)*inv_radius;
F32 v1 = (vtx.y - zode->pos.y)*inv_radius;
F32 ru1 = u1*cos_ang - v1*sin_ang;
F32 rv1 = u1*sin_ang + v1*cos_ang;
F32 uu = (ru1 + 1.0f)/2.0f;
F32 vv = 1.0f - (rv1 + 1.0f)/2.0f;
PrimBuild::texCoord2f(uu, vv);
PrimBuild::vertex3fv(vtx);
}
}
PrimBuild::end(false);
}
}
//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
| 3,904 |
473 |
#!/usr/bin/env python
#
# Copyright (C) 2014, 2015
# <NAME> <<EMAIL>>
# Narf Industries <<EMAIL>>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
from generator.actions import Actions, Variable
from random import randint, choice, sample
import struct
import copy
# Almost random. We need to avoid delim chars (' ' and '\n' and NULL)
def random_bytes(min, max, mod=255):
return (''.join(chr(choice(range(mod))) for _ in range(randint(min,max)))).replace(' ', '').replace('\n', '').replace('\x00', '')
class Insulatr(Actions):
GLOBAL_DEBUG = False
GLOBAL_POV = False
# rx_buf is 65535 bytes; lines are capped at MAX_SZ_LINE = 256.
# 65535 / 256 = 255.
# Let's cap at 250 to be safe.
MAX_PENDING_INSN = 250
MSG_DESERIALIZE = 1
MSG_SERIALIZE = 2
MSG_EXIT = 3
NUM_OBJS = 256
MAX_SZ_LINE = 256
MAX_SZ_STRING = MAX_SZ_LINE - len('255 STRING \n') - 50
def exit(self):
"""
Tell CB to immediately exit.
"""
self.write(struct.pack("<B", self.MSG_EXIT))
return -1
def deserialize(self):
"""
Flush pending INSNs to the CB.
"""
DEBUG = self.GLOBAL_DEBUG and True
if DEBUG: print "\n[D] deserialize | pending:\n %s" % self.state['pending_insns']
# Prepend initial newline.
self.state['pending_insns'] = '\n' + self.state['pending_insns']
# Write & flush the INSNs.
self.write(struct.pack("<BH", self.MSG_DESERIALIZE, len(self.state['pending_insns'])) + self.state['pending_insns'])
self.state['pending_insns'] = ""
self.state['pending_count'] = 0
# Actualize the state.
self.state['obj_real'] = copy.deepcopy(self.state['obj_pend'])
def serialize(self):
"""
Request state from the CB.
"""
DEBUG = self.GLOBAL_DEBUG and True
if DEBUG: print "\n[D] serialize"
self.write(struct.pack("<B", self.MSG_SERIALIZE))
for obj_id in range(self.NUM_OBJS):
try:
expected = "%d %s %s" % (obj_id, self.state['obj_real'][obj_id]['type'], str(self.state['obj_real'][obj_id]['val']))
self.read(delim='\n', expect=expected)
except KeyError: continue
def obj_new(self):
"""
We (may) create an object.
INSN appended to outgoing buffer.
"""
DEBUG = self.GLOBAL_DEBUG and True
if DEBUG: print "\n[D] obj_new"
# Check whether we've hit our INSN limit.
if (self.state['pending_count'] > self.MAX_PENDING_INSN):
if DEBUG: print "obj_new | exceeded MAX_PENDING_INSN"
return
obj_id = randint(0, self.NUM_OBJS-1)
obj_type = ["NUMBER", "STRING"][randint(0, 1)]
if "NUMBER" == obj_type:
if randint(0, 1):
obj_val = randint(0, 0xFFFFFFFFFFFFFFFF)
else:
obj_val = randint(0, 0xFFFFFFFF)
else:
obj_val = random_bytes(0, self.MAX_SZ_STRING)
if DEBUG: print "OBJ_VAL: %s" % obj_val
cmd = "NEW %d %s %s \n" % (obj_id, obj_type, str(obj_val))
self.state['pending_insns'] += cmd
self.state['pending_count'] += 1
if DEBUG: print "[D] obj_new | generated INSN:\n%s" % cmd[:-1]
# If we attempt to create a NEW object for an ID that already exists,
# the new object is ignored.
try:
tmp = self.state['obj_pend'][obj_id]
if DEBUG:
print "[D] obj_new | ID %03d already exists, not adding to state" % obj_id
return
except KeyError: pass
# Append to pending state, promote if necessary.
if 0xFFFFFFFF < obj_val: obj_type = "STRING"
self.state['obj_pend'][obj_id] = {"type" : obj_type, "val" : obj_val}
def obj_set(self):
"""
We (may) modify an object.
INSN appended to outgoing buffer.
"""
DEBUG = self.GLOBAL_DEBUG and True
if DEBUG: print "\n[D] obj_set"
if (self.state['pending_count'] > self.MAX_PENDING_INSN):
if self.DEBUG:
print "obj_set | exceeded MAX_PENDING_INSN"
return
# 50/50 chance we pick an object that actually exists (if any exist).
if randint(0, 1):
if (0 != len(self.state['obj_pend'].keys())):
id_exists = True
obj_id = choice(self.state['obj_pend'].keys())
obj_type = self.state['obj_pend'][obj_id]['type']
else:
id_exists = False
obj_id = randint(0, self.NUM_OBJS-1)
obj_type = ["NUMBER", "STRING"][randint(0, 1)]
# Otherwise we (try) to pick a non-existant obj_id (they may all exist).
else:
existing = set(self.state['obj_pend'].keys())
#existing.update(self.state['obj_pend'].keys())
# Every object exists, pick an existing one.
if (len(existing) == self.NUM_OBJS):
id_exists = True
obj_id = sample(existing, 1)[0]
obj_type = self.state['obj_pend'][obj_id]['type']
# Some objects don't exist. Pick an obj_id that doesn't exist.
else:
id_exists = False
obj_id = sample(set([i for i in xrange(self.NUM_OBJS)]).difference(existing), 1)[0]
obj_type = ["NUMBER", "STRING"][randint(0, 1)]
if "NUMBER" == obj_type:
# We do not cause PROMOTION via the SET command so as to avoid the
# vulnerable code path.
obj_val = randint(0, 0xFFFFFFFF)
else:
obj_val = random_bytes(0, self.MAX_SZ_STRING)
cmd = "SET %d %s \n" % (obj_id, str(obj_val))
self.state['pending_insns'] += cmd
self.state['pending_count'] += 1
if DEBUG: print "[D] obj_set | generated INSN:\n%s" % cmd[:-1]
# If we attempt to SET an object that doesn't exist, no state change.
if False == id_exists:
if DEBUG:
print "[D] obj_set | %03d does not exist; not modifying state" % obj_id
return
# Otherwise, update state.
if DEBUG:
print "id_exists: %s" % id_exists
print "SET | obj_id = %d; before: %s" % (obj_id, self.state['obj_pend'])
self.state['obj_pend'][obj_id] = {"type" : obj_type, "val" : obj_val}
if DEBUG: print "SET | obj_id = %d; after: %s" % (obj_id, self.state['obj_pend'])
def obj_del(self):
"""
We (may) delete an object.
INSN appended to outgoing buffer.
"""
DEBUG = self.GLOBAL_DEBUG and True
if DEBUG: print "\n[D] obj_del"
if (self.state['pending_count'] > self.MAX_PENDING_INSN):
if self.DEBUG:
print "obj_del | exceeded MAX_PENDING_INSN"
return
existing = set(self.state['obj_pend'].keys())
# 50/50 chance we pick an object that actually exists (if any exist).
if randint(0, 1):
if (0 != len(existing)):
id_exists = True
obj_id = sample(existing, 1)[0]
else:
id_exists = False
obj_id = randint(0, self.NUM_OBJS-1)
else:
obj_id = sample(set([i for i in xrange(self.NUM_OBJS)]).difference(existing), 1)[0]
cmd = "DEL %d \n" % obj_id
self.state['pending_insns'] += cmd
self.state['pending_count'] += 1
if DEBUG: print "[D] obj_del | generated INSN:\n%s" % cmd[:-1]
# If we attempt to DEL an object that doesn't exist, no state change.
try:
del self.state['obj_pend'][obj_id]
except KeyError: pass
def start(self):
"""
Initialize state.
"""
DEBUG = self.GLOBAL_DEBUG and True
if DEBUG:
print "**** NEW RUN ****"
print "[D] start"
self.state['obj_real'] = {}
self.state['obj_pend'] = {}
self.state['pending_insns'] = ""
self.state['pending_count'] = 0
def dispatch(self):
"""
No-op. Easier than linking all nodes directly together.
"""
pass
| 4,338 |
571 |
package de.gurkenlabs.litiengine.entities;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Collection;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
public class EntityActionMapTests {
private EntityAction entityAction;
private EntityActionMap actionMap;
private final String ACTION_NAME = "Action1";
@BeforeEach
public void setUp() {
entityAction = new EntityAction(ACTION_NAME, () -> {});
actionMap = new EntityActionMap();
actionMap.register(entityAction);
}
@ParameterizedTest(name = "testExists actionName={0}, expectedResult={1}")
@CsvSource({"Action1, true", "Action2, false"})
public void testExists(String actionName, boolean expectedResult) {
// act
boolean exists = actionMap.exists(actionName);
// assert
assertEquals(expectedResult, exists);
}
@Test
public void testGet() {
// act
EntityAction action = actionMap.get(ACTION_NAME);
// assert
assertEquals(entityAction, action);
}
@Test
public void testGetActions() {
// arrange
actionMap.register(new EntityAction("Action2", () -> {}));
// act
Collection<EntityAction> actions = actionMap.getActions();
// assert
assertEquals(2, actions.size());
}
@Test
public void testRegister() {
// arrange
EntityAction action = new EntityAction("Action2", () -> {});
// act
actionMap.register(action);
// assert
assertTrue(actionMap.getActions().contains(action));
}
@Test
public void testUnregister() {
// act
actionMap.unregister(ACTION_NAME);
// assert
assertFalse(actionMap.getActions().contains(entityAction));
}
}
| 736 |
348 |
<reponame>chamberone/Leaflet.PixiOverlay
{"nom":"Marcilly-en-Villette","circ":"3ème circonscription","dpt":"Loiret","inscrits":1633,"abs":804,"votants":829,"blancs":69,"nuls":21,"exp":739,"res":[{"nuance":"REM","nom":"<NAME>","voix":428},{"nuance":"LR","nom":"<NAME>","voix":311}]}
| 116 |
319 |
<reponame>84KaliPleXon3/OMEN
/*
* nGramReader.h
* @authors: <NAME>, <NAME>
* @copyright: Horst Goertz Institute for IT-Security, Ruhr-University Bochum
*
* Provides functions to read nGram and the according configuration from files
* under the given filenames and store them in the given arrays.
*
*/
#ifndef NGRAMREADER_H_
#define NGRAMREADER_H_
#include "common.h"
#include "commonStructs.h"
// === intern functions ===
/*
* // reads config file
* BOOL read_config();
*
* // skips the header of given fp
* BOOL skip_header();
*
* // reads any level file assigning the read values to the given levelArray
* BOOL read_levelFromFile();
*
* // reads any count file assigning the read values to the given countArray
* BOOL read_countFromFile();
*
* // reads any array from given file according to the arrayType
* BOOL read_array();
*/
// === public funtions ===
/*
* Reads all needed input files (levels for nGram and initalProb, count and levels for lengths)
* based on the config file that must be set in filenames, creating the filenames (attaching
* the default file ending) and sets the corresponding @nGrams and @alphabet variables using the
* other read function (read_ngramLevel, read_initialProbLevel, read_lengthLevel, read_lengthCount).
* Returns TRUE, if reading was successful.
* Otherwise any occurred error can be checked using the @errorHandler
*/
bool read_inputFiles (struct nGram_struct *nGrams, // nGram arrays (must be initialized)
struct alphabet_struct *alphabet, // alphabet (must be initialized)
struct filename_struct *filenames, // filenames (must contain a set config file name!)
char *maxLevel // max level
);
#endif /* NGRAMIO_H_ */
| 584 |
402 |
/*
* Copyright 2000-2021 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.vaadin.fusion.auth;
import javax.servlet.http.Cookie;
import org.jsoup.nodes.Document;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.ArgumentMatchers;
import org.mockito.Mockito;
import com.vaadin.flow.server.VaadinRequest;
import com.vaadin.flow.server.VaadinResponse;
import com.vaadin.flow.server.communication.IndexHtmlResponse;
import com.vaadin.flow.shared.ApplicationConstants;
public class CsrfIndexHtmlRequestListenerTest {
static private final String TEST_CONTEXT_PATH = "/test-context";
private CsrfIndexHtmlRequestListener csrfIndexHtmlRequestListener;
private IndexHtmlResponse indexHtmlResponse;
private VaadinRequest vaadinRequest;
@Before
public void setup() {
csrfIndexHtmlRequestListener = Mockito
.spy(new CsrfIndexHtmlRequestListener());
vaadinRequest = Mockito.mock(VaadinRequest.class);
Mockito.doReturn(TEST_CONTEXT_PATH).when(vaadinRequest)
.getContextPath();
Mockito.doReturn(true).when(vaadinRequest).isSecure();
VaadinResponse vaadinResponse = Mockito.mock(VaadinResponse.class);
Document document = Mockito.mock(Document.class);
indexHtmlResponse = new IndexHtmlResponse(vaadinRequest, vaadinResponse,
document);
}
@Test
public void should_setCsrfCookie_when_null_cookies_and_SpringCsrfTokenNotPresent() {
Mockito.doReturn(false).when(csrfIndexHtmlRequestListener)
.isSpringCsrfTokenPresent(vaadinRequest);
useRequestCookies(null);
csrfIndexHtmlRequestListener.modifyIndexHtmlResponse(indexHtmlResponse);
verifyCsrfCookieAdded();
}
@Test
public void should_setCsrfCookie_when_absent_and_SpringCsrfTokenNotPresent() {
Mockito.doReturn(false).when(csrfIndexHtmlRequestListener)
.isSpringCsrfTokenPresent(vaadinRequest);
useRequestCookies(new Cookie[0]);
csrfIndexHtmlRequestListener.modifyIndexHtmlResponse(indexHtmlResponse);
verifyCsrfCookieAdded();
}
@Test
public void should_notSetCsrfCookie_when_SpringCsrfPresents() {
Mockito.doReturn(true).when(csrfIndexHtmlRequestListener)
.isSpringCsrfTokenPresent(vaadinRequest);
csrfIndexHtmlRequestListener.modifyIndexHtmlResponse(indexHtmlResponse);
Mockito.verify(indexHtmlResponse.getVaadinResponse(), Mockito.never())
.addCookie(ArgumentMatchers.any());
}
@Test
public void should_notSetCsrfCookie_when_present() {
Mockito.doReturn(false).when(csrfIndexHtmlRequestListener)
.isSpringCsrfTokenPresent(vaadinRequest);
Cookie csrfRequestCookie = new Cookie(ApplicationConstants.CSRF_TOKEN,
"foo");
useRequestCookies(new Cookie[] { csrfRequestCookie });
csrfIndexHtmlRequestListener.modifyIndexHtmlResponse(indexHtmlResponse);
Mockito.verify(indexHtmlResponse.getVaadinResponse(), Mockito.never())
.addCookie(ArgumentMatchers.any());
}
private void useRequestCookies(Cookie[] cookies) {
Mockito.doReturn(cookies).when(indexHtmlResponse.getVaadinRequest())
.getCookies();
}
private void verifyCsrfCookieAdded() {
ArgumentCaptor<Cookie> cookieArgumentCaptor = ArgumentCaptor
.forClass(Cookie.class);
Mockito.verify(indexHtmlResponse.getVaadinResponse())
.addCookie(cookieArgumentCaptor.capture());
Cookie csrfCookie = cookieArgumentCaptor.getValue();
Assert.assertEquals(ApplicationConstants.CSRF_TOKEN,
csrfCookie.getName());
Assert.assertFalse("Unexpected empty string value",
csrfCookie.getValue().isEmpty());
Assert.assertFalse(csrfCookie.isHttpOnly());
Assert.assertTrue(csrfCookie.getSecure());
Assert.assertEquals(TEST_CONTEXT_PATH, csrfCookie.getPath());
}
}
| 1,803 |
665 |
from adafruit_circuitplayground.express import cpx
while True:
cpx.red_led = True
| 32 |
860 |
<reponame>xiefan46/samza
/*
* 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.samza.serializers;
import java.util.Map;
/**
* Used for Json serialization of the {@link org.apache.samza.checkpoint.Checkpoint} class by the
* {@link CheckpointV2Serde}
* This cannot be an internal class as required by Jackson Object mapper
*/
public class JsonCheckpoint {
private String checkpointId;
private Map<String, Map<String, String>> inputOffsets;
// Map<StorageBackendFactoryName, Map<StoreName, StateCheckpointMarker>>
private Map<String, Map<String, String>> stateCheckpointMarkers;
// Default constructor required for Jackson ObjectMapper
public JsonCheckpoint() {}
public JsonCheckpoint(String checkpointId,
Map<String, Map<String, String>> inputOffsets,
Map<String, Map<String, String>> stateCheckpointMakers) {
this.checkpointId = checkpointId;
this.inputOffsets = inputOffsets;
this.stateCheckpointMarkers = stateCheckpointMakers;
}
public String getCheckpointId() {
return checkpointId;
}
public Map<String, Map<String, String>> getInputOffsets() {
return inputOffsets;
}
public Map<String, Map<String, String>> getStateCheckpointMarkers() {
return stateCheckpointMarkers;
}
}
| 577 |
2,414 |
<filename>SpringBoot咨询发布系统实战项目源码/springboot-project-news-publish-system/src/main/java/com/site/springboot/core/controller/admin/UploadController.java
package com.site.springboot.core.controller.admin;
import com.site.springboot.core.config.Constants;
import com.site.springboot.core.util.Result;
import com.site.springboot.core.util.ResultGenerator;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
/**
* @author 13
* @qq交流群 796794009
* @email <EMAIL>
* @link http://13blog.site
*/
@Controller
@RequestMapping("/admin")
public class UploadController {
@PostMapping({"/upload/file"})
@ResponseBody
public Result upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
if (file.isEmpty()) {
return ResultGenerator.genFailResult("请选择文件");
}
String fileName = file.getOriginalFilename();
String suffixName = fileName.substring(fileName.lastIndexOf("."));
//生成文件名称通用方法
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
Random r = new Random();
StringBuilder tempName = new StringBuilder();
tempName.append(sdf.format(new Date())).append(r.nextInt(100)).append(suffixName);
String newFileName = tempName.toString();
try {
// 保存文件
byte[] bytes = file.getBytes();
Path path = Paths.get(Constants.FILE_UPLOAD_PATH + newFileName);
Files.write(path, bytes);
} catch (IOException e) {
e.printStackTrace();
}
Result result = ResultGenerator.genSuccessResult();
result.setData("/files/" + newFileName);
return result;
}
}
| 892 |
2,797 |
class UnionFind(object):
""" Disjoint Set data structure supporting union and find operations used
for Kruskal's MST algorithm
Methods -
insert(a, b) -> inserts 2 items in the sets
get_leader(a) -> returns the leader(representative) corresponding to item a
make_union(leadera, leaderb) -> unions two sets with leadera and leaderb
in O(nlogn) time where n the number of elements in the data structure
count_keys() -> returns the number of groups in the data structure
"""
def __init__(self):
self.leader = {}
self.group = {}
self.__repr__ = self.__str__
def __str__(self):
return str(self.group)
def get_sets(self):
""" returns a list of all the sets in the data structure"""
return [i[1] for i in self.group.items()]
def insert(self, a, b=None):
""" takes a hash of object and inserts it in the
data structure """
leadera = self.get_leader(a)
leaderb = self.get_leader(b)
if not b:
# only one item is inserted
if a not in self.leader:
# a is not already in any set
self.leader[a] = a
self.group[a] = set([a])
return
if leadera is not None:
if leaderb is not None:
if leadera == leaderb: return # Do nothing
self.make_union(leadera, leaderb)
else:
# leaderb is none
self.group[leadera].add(b)
self.leader[b] = leadera
else:
if leaderb is not None:
# leadera is none
self.group[leaderb].add(a)
self.leader[a] = leaderb
else:
self.leader[a] = self.leader[b] = a
self.group[a] = set([a, b])
def get_leader(self, a):
return self.leader.get(a)
def count_groups(self):
""" returns a count of the number of groups/sets in the
data structure"""
return len(self.group)
def make_union(self, leadera, leaderb):
""" takes union of two sets with leaders, leadera and leaderb
in O(nlogn) time """
if leadera not in self.group or leaderb not in self.group:
raise Exception("Invalid leader specified leadera -%s, leaderb - %s" % (leadera, leaderb))
groupa = self.group[leadera]
groupb = self.group[leaderb]
if len(groupa) < len(groupb):
# swap a and b if a is a smaller set
leadera, groupa, leaderb, groupb = leaderb, groupb, leadera, groupa
groupa |= groupb # taking union of a with b
del self.group[leaderb] # delete b
for k in groupb:
self.leader[k] = leadera
if __name__ == "__main__":
uf = UnionFind()
uf.insert("a", "b")
| 1,319 |
848 |
<gh_stars>100-1000
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "mlir/IR/Attributes.h" // TF:local_config_mlir
#include "mlir/IR/StandardTypes.h" // TF:local_config_mlir
namespace mlir {
namespace TFL {
FloatAttr ExtractSingleElementAsFloat(ElementsAttr attr) {
if (attr.getType().getNumElements() != 1 ||
!attr.getType().getElementType().isa<FloatType>()) {
return {};
}
SmallVector<uint64_t, 8> index(attr.getType().getRank(), 0);
return attr.getValue<FloatAttr>(index);
}
FloatAttr GetSingleElementAsFloatOrSelf(Attribute attr) {
if (auto m = attr.dyn_cast_or_null<ElementsAttr>()) {
return ExtractSingleElementAsFloat(m);
} else {
return attr.dyn_cast_or_null<FloatAttr>();
}
}
IntegerAttr ExtractSingleElementAsInteger(ElementsAttr attr) {
if (attr.getType().getNumElements() != 1 ||
!attr.getType().getElementType().isa<IntegerType>()) {
return {};
}
SmallVector<uint64_t, 8> index(attr.getType().getRank(), 0);
return attr.getValue<IntegerAttr>(index);
}
} // namespace TFL
} // namespace mlir
| 546 |
1,668 |
package org.elixir_lang.psi.scope.call_definition_clause;
import com.intellij.codeInsight.completion.CompletionType;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiReference;
import com.intellij.testFramework.fixtures.LightPlatformCodeInsightFixtureTestCase;
import org.elixir_lang.psi.call.Call;
import java.util.List;
public class VariantsTest extends LightPlatformCodeInsightFixtureTestCase {
/*
* Tests
*/
public void testIssue453() {
myFixture.configureByFiles("defmodule.ex");
myFixture.complete(CompletionType.BASIC);
List<String> strings = myFixture.getLookupElementStrings();
assertNotNull("Completion not shown", strings);
assertEquals("Wrong number of completions", 0, strings.size());
}
public void testIssue462() {
myFixture.configureByFiles("self_completion.ex");
PsiElement head = myFixture
.getFile()
.findElementAt(myFixture.getCaretOffset() - 1)
.getParent()
.getParent();
assertInstanceOf(head, Call.class);
PsiReference reference = head.getReference();
assertNotNull("Call definition head does not have a reference", reference);
Object[] variants = reference.getVariants();
int count = 0;
for (Object variant : variants) {
if (variant instanceof LookupElement) {
LookupElement lookupElement = (LookupElement) variant;
if (lookupElement.getLookupString().equals("the_function_currently_being_defined")) {
count += 1;
}
}
}
assertEquals("There is at least one entry for the function currently being defined in variants", 0, count);
}
/*
* Protected Instance Methods
*/
@Override
protected String getTestDataPath() {
return "testData/org/elixir_lang/psi/scope/call_definition_clause/variants";
}
}
| 832 |
841 |
<filename>testsuite/integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/resource/InputPartDefaultContentTypeWildcardOverwriteContainerBean.java
package org.jboss.resteasy.test.providers.multipart.resource;
import org.jboss.resteasy.annotations.providers.multipart.PartType;
import jakarta.ws.rs.FormParam;
import jakarta.ws.rs.core.MediaType;
public class InputPartDefaultContentTypeWildcardOverwriteContainerBean {
@FormParam("foo")
@PartType(MediaType.APPLICATION_XML)
private InputPartDefaultContentTypeWildcardOverwriteXmlBean foo;
public InputPartDefaultContentTypeWildcardOverwriteXmlBean getFoo() {
return foo;
}
public void setFoo(InputPartDefaultContentTypeWildcardOverwriteXmlBean foo) {
this.foo = foo;
}
}
| 266 |
2,970 |
#
# Copyright 2018 Analytics Zoo 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.
#
import pytest
from test.zoo.pipeline.utils.test_utils import ZooTestCase
from zoo.orca.automl.search import TensorboardLogger
import numpy as np
import random
import os.path
class TestTensorboardLogger(ZooTestCase):
def setup_method(self, method):
pass
def teardown_method(self, method):
pass
def test_tblogger_valid_type(self):
trail_num = 100
test_config = {}
test_metric = {}
for i in range(trail_num):
test_config["run_{}".format(i)] =\
{"config_good": random.randint(8, 96),
"config_unstable": None if random.random() < 0.5 else 1,
"config_bad": None}
test_metric["run_{}".format(i)] =\
{"matrix_good": random.randint(0, 100)/100,
"matrix_unstable": np.nan if random.random() < 0.5 else 1,
"matrix_bad": np.nan}
logger = TensorboardLogger(os.path.abspath(os.path.expanduser("~/test_tbxlogger")))
logger.run(test_config, test_metric)
logger.close()
def test_tblogger_keys(self):
test_config = {"run1": {"lr": 0.01}}
test_metric = {"run2": {"lr": 0.02}}
logger = TensorboardLogger(os.path.abspath(os.path.expanduser("~/test_tbxlogger")))
with pytest.raises(Exception):
logger.run(test_config, test_metric)
logger.close()
| 885 |
701 |
package com.c9mj.platform.demo_list.mvp.model.bean;
public class DemoListBean {
public DemoListBean() {
}
}
| 50 |
6,098 |
<gh_stars>1000+
package water.rapids.ast.prims.advmath;
import water.fvec.Frame;
import water.fvec.Vec;
import water.rapids.Env;
import water.rapids.vals.ValFrame;
import water.rapids.ast.AstPrimitive;
import water.rapids.ast.AstRoot;
import java.util.Random;
public class AstStratifiedKFold extends AstPrimitive {
@Override
public String[] args() {
return new String[]{"ary", "nfolds", "seed"};
}
@Override
public int nargs() {
return 1 + 3;
} // (stratified_kfold_column x nfolds seed)
@Override
public String str() {
return "stratified_kfold_column";
}
@Override
public ValFrame apply(Env env, Env.StackHelp stk, AstRoot asts[]) {
Vec foldVec = stk.track(asts[1].exec(env)).getFrame().anyVec().makeZero();
int nfolds = (int) asts[2].exec(env).getNum();
long seed = (long) asts[3].exec(env).getNum();
return new ValFrame(new Frame(AstKFold.stratifiedKFoldColumn(foldVec, nfolds, seed == -1 ? new Random().nextLong() : seed)));
}
}
| 380 |
14,668 |
<reponame>chromium/chromium<filename>content/browser/attribution_reporting/attribution_storage_sql_migrations.cc<gh_stars>1000+
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/attribution_reporting/attribution_storage_sql_migrations.h"
#include <vector>
#include "base/guid.h"
#include "base/metrics/histogram_functions.h"
#include "content/browser/attribution_reporting/attribution_report.h"
#include "content/browser/attribution_reporting/attribution_storage.h"
#include "content/browser/attribution_reporting/sql_utils.h"
#include "content/browser/attribution_reporting/storable_source.h"
#include "net/base/schemeful_site.h"
#include "sql/database.h"
#include "sql/meta_table.h"
#include "sql/statement.h"
#include "sql/transaction.h"
#include "url/origin.h"
namespace content {
namespace {
WARN_UNUSED_RESULT
StorableSource::Id NextImpressionId(StorableSource::Id id) {
return StorableSource::Id(*id + 1);
}
WARN_UNUSED_RESULT
AttributionReport::Id NextConversionId(AttributionReport::Id id) {
return AttributionReport::Id(*id + 1);
}
struct ImpressionIdAndConversionOrigin {
StorableSource::Id impression_id;
url::Origin conversion_origin;
};
std::vector<ImpressionIdAndConversionOrigin>
GetImpressionIdAndConversionOrigins(sql::Database* db,
StorableSource::Id start_impression_id) {
static constexpr char kGetImpressionsSql[] =
"SELECT impression_id,conversion_origin "
"FROM impressions "
"WHERE impression_id >= ? "
"ORDER BY impression_id "
"LIMIT ?";
sql::Statement statement(
db->GetCachedStatement(SQL_FROM_HERE, kGetImpressionsSql));
statement.BindInt64(0, *start_impression_id);
const int kNumImpressions = 100;
statement.BindInt(1, kNumImpressions);
std::vector<ImpressionIdAndConversionOrigin> impressions;
while (statement.Step()) {
StorableSource::Id impression_id(statement.ColumnInt64(0));
url::Origin conversion_origin =
DeserializeOrigin(statement.ColumnString(1));
impressions.push_back({impression_id, std::move(conversion_origin)});
}
if (!statement.Succeeded())
return {};
return impressions;
}
struct ImpressionIdAndImpressionOrigin {
StorableSource::Id impression_id;
url::Origin impression_origin;
};
std::vector<ImpressionIdAndImpressionOrigin>
GetImpressionIdAndImpressionOrigins(sql::Database* db,
StorableSource::Id start_impression_id) {
static constexpr char kGetImpressionsSql[] =
"SELECT impression_id,impression_origin "
"FROM impressions "
"WHERE impression_id >= ? "
"ORDER BY impression_id "
"LIMIT ?";
sql::Statement statement(
db->GetCachedStatement(SQL_FROM_HERE, kGetImpressionsSql));
statement.BindInt64(0, *start_impression_id);
const int kNumImpressions = 100;
statement.BindInt(1, kNumImpressions);
std::vector<ImpressionIdAndImpressionOrigin> impressions;
while (statement.Step()) {
StorableSource::Id impression_id(statement.ColumnInt64(0));
url::Origin impression_origin =
DeserializeOrigin(statement.ColumnString(1));
impressions.push_back({impression_id, std::move(impression_origin)});
}
if (!statement.Succeeded())
return {};
return impressions;
}
std::vector<AttributionReport::Id> GetConversionIds(
sql::Database* db,
AttributionReport::Id start_conversion_id) {
static constexpr char kGetConversionsSql[] =
"SELECT conversion_id FROM conversions "
"WHERE conversion_id >= ? "
"ORDER BY conversion_id "
"LIMIT ?";
sql::Statement statement(
db->GetCachedStatement(SQL_FROM_HERE, kGetConversionsSql));
statement.BindInt64(0, *start_conversion_id);
const int kNumConversions = 100;
statement.BindInt(1, kNumConversions);
std::vector<AttributionReport::Id> conversion_ids;
while (statement.Step()) {
conversion_ids.emplace_back(statement.ColumnInt64(0));
}
if (!statement.Succeeded())
return {};
return conversion_ids;
}
bool MigrateToVersion2(sql::Database* db, sql::MetaTable* meta_table) {
// Wrap each migration in its own transaction. This results in smaller
// transactions, so it's less likely that a transaction's buffer will need to
// spill to disk. Also, if the database grows a lot and Chrome stops (user
// quit, process kill, etc.) during the migration process, per-migration
// transactions make it more likely that we'll make forward progress each time
// Chrome stops.
sql::Transaction transaction(db);
if (!transaction.Begin())
return false;
// Add a new conversion_destination column to the impressions table. This
// follows the steps documented at
// https://sqlite.org/lang_altertable.html#otheralter. Other approaches, like
// using "ALTER ... ADD COLUMN" require setting a DEFAULT value for the column
// which is undesirable.
static constexpr char kNewImpressionTableSql[] =
"CREATE TABLE IF NOT EXISTS new_impressions"
"(impression_id INTEGER PRIMARY KEY,"
"impression_data TEXT NOT NULL,"
"impression_origin TEXT NOT NULL,"
"conversion_origin TEXT NOT NULL,"
"reporting_origin TEXT NOT NULL,"
"impression_time INTEGER NOT NULL,"
"expiry_time INTEGER NOT NULL,"
"num_conversions INTEGER DEFAULT 0,"
"active INTEGER DEFAULT 1,"
"conversion_destination TEXT NOT NULL)";
if (!db->Execute(kNewImpressionTableSql))
return false;
// Transfer the existing rows to the new table, inserting a placeholder for
// the conversion_destination column.
static constexpr char kPopulateNewImpressionTableSql[] =
"INSERT INTO new_impressions SELECT "
"impression_id,impression_data,impression_origin,"
"conversion_origin,reporting_origin,impression_time,"
"expiry_time,num_conversions,active,'' "
"FROM impressions";
if (!db->Execute(kPopulateNewImpressionTableSql))
return false;
static constexpr char kDropOldImpressionTableSql[] = "DROP TABLE impressions";
if (!db->Execute(kDropOldImpressionTableSql))
return false;
static constexpr char kRenameImpressionTableSql[] =
"ALTER TABLE new_impressions RENAME TO impressions";
if (!db->Execute(kRenameImpressionTableSql))
return false;
// Update each of the impression rows to have the correct associated
// conversion_destination. This is only relevant for active impressions, as
// the column is only used for matching impressions to conversions, but we
// update all impressions regardless.
//
// We update a subset of rows at a time to avoid pulling the entire
// impressions table into memory.
std::vector<ImpressionIdAndConversionOrigin> impressions =
GetImpressionIdAndConversionOrigins(db, StorableSource::Id(0));
static constexpr char kUpdateDestinationSql[] =
"UPDATE impressions SET conversion_destination = ? WHERE impression_id = "
"?";
sql::Statement update_destination_statement(
db->GetCachedStatement(SQL_FROM_HERE, kUpdateDestinationSql));
while (!impressions.empty()) {
// Perform the column updates for each row we pulled into memory.
for (const auto& impression : impressions) {
update_destination_statement.Reset(/*clear_bound_vars=*/true);
// The conversion destination is derived from the conversion origin
// dynamically.
update_destination_statement.BindString(
0, net::SchemefulSite(impression.conversion_origin).Serialize());
update_destination_statement.BindInt64(1, *impression.impression_id);
update_destination_statement.Run();
}
// Fetch the next batch of rows from the database.
impressions = GetImpressionIdAndConversionOrigins(
db, NextImpressionId(impressions.back().impression_id));
}
// Create the pre-existing impression table indices on the new table.
static constexpr char kImpressionExpiryIndexSql[] =
"CREATE INDEX IF NOT EXISTS impression_expiry_idx "
"ON impressions(expiry_time)";
if (!db->Execute(kImpressionExpiryIndexSql))
return false;
static constexpr char kImpressionOriginIndexSql[] =
"CREATE INDEX IF NOT EXISTS impression_origin_idx "
"ON impressions(impression_origin)";
if (!db->Execute(kImpressionOriginIndexSql))
return false;
// Replace the pre-existing conversion_origin_idx with an index that uses the
// conversion destination, as attribution logic now depends on the
// conversion_destination.
static constexpr char kConversionDestinationIndexSql[] =
"CREATE INDEX IF NOT EXISTS conversion_destination_idx "
"ON impressions(active,conversion_destination,reporting_origin)";
if (!db->Execute(kConversionDestinationIndexSql))
return false;
meta_table->SetVersionNumber(2);
return transaction.Commit();
}
bool MigrateToVersion3(sql::Database* db, sql::MetaTable* meta_table) {
// Wrap each migration in its own transaction. See comment in
// |MigrateToVersion2|.
sql::Transaction transaction(db);
if (!transaction.Begin())
return false;
// Add new source_type and attributed_truthfully columns to the impressions
// table. This follows the steps documented at
// https://sqlite.org/lang_altertable.html#otheralter. Other approaches, like
// using "ALTER ... ADD COLUMN" require setting a DEFAULT value for the column
// which is undesirable.
static constexpr char kNewImpressionTableSql[] =
"CREATE TABLE IF NOT EXISTS new_impressions"
"(impression_id INTEGER PRIMARY KEY,"
"impression_data TEXT NOT NULL,"
"impression_origin TEXT NOT NULL,"
"conversion_origin TEXT NOT NULL,"
"reporting_origin TEXT NOT NULL,"
"impression_time INTEGER NOT NULL,"
"expiry_time INTEGER NOT NULL,"
"num_conversions INTEGER DEFAULT 0,"
"active INTEGER DEFAULT 1,"
"conversion_destination TEXT NOT NULL,"
"source_type INTEGER NOT NULL,"
"attributed_truthfully INTEGER NOT NULL)";
if (!db->Execute(kNewImpressionTableSql))
return false;
// Transfer the existing rows to the new table, inserting default values for
// the source_type and attributed_truthfully columns.
static constexpr char kPopulateNewImpressionTableSql[] =
"INSERT INTO new_impressions SELECT "
"impression_id,impression_data,impression_origin,"
"conversion_origin,reporting_origin,impression_time,"
"expiry_time,num_conversions,active,conversion_destination,?,? "
"FROM impressions";
sql::Statement populate_statement(
db->GetCachedStatement(SQL_FROM_HERE, kPopulateNewImpressionTableSql));
// Only navigation type was supported prior to this column being added.
populate_statement.BindInt(
0, static_cast<int>(StorableSource::SourceType::kNavigation));
populate_statement.BindBool(1, true);
if (!populate_statement.Run())
return false;
static constexpr char kDropOldImpressionTableSql[] = "DROP TABLE impressions";
if (!db->Execute(kDropOldImpressionTableSql))
return false;
static constexpr char kRenameImpressionTableSql[] =
"ALTER TABLE new_impressions RENAME TO impressions";
if (!db->Execute(kRenameImpressionTableSql))
return false;
// Create the pre-existing impression table indices on the new table.
static constexpr char kImpressionExpiryIndexSql[] =
"CREATE INDEX IF NOT EXISTS impression_expiry_idx "
"ON impressions(expiry_time)";
if (!db->Execute(kImpressionExpiryIndexSql))
return false;
static constexpr char kImpressionOriginIndexSql[] =
"CREATE INDEX IF NOT EXISTS impression_origin_idx "
"ON impressions(impression_origin)";
if (!db->Execute(kImpressionOriginIndexSql))
return false;
static constexpr char kConversionDestinationIndexSql[] =
"CREATE INDEX IF NOT EXISTS conversion_destination_idx "
"ON impressions(active,conversion_destination,reporting_origin)";
if (!db->Execute(kConversionDestinationIndexSql))
return false;
meta_table->SetVersionNumber(3);
return transaction.Commit();
}
bool MigrateToVersion4(sql::Database* db, sql::MetaTable* meta_table) {
// Wrap each migration in its own transaction. See comment in
// |MigrateToVersion2|.
sql::Transaction transaction(db);
if (!transaction.Begin())
return false;
static constexpr char kRateLimitTableSql[] =
"CREATE TABLE IF NOT EXISTS rate_limits"
"(rate_limit_id INTEGER PRIMARY KEY,"
"attribution_type INTEGER NOT NULL,"
"impression_id INTEGER NOT NULL,"
"impression_site TEXT NOT NULL,"
"impression_origin TEXT NOT NULL,"
"conversion_destination TEXT NOT NULL,"
"conversion_origin TEXT NOT NULL,"
"conversion_time INTEGER NOT NULL)";
if (!db->Execute(kRateLimitTableSql))
return false;
static constexpr char kRateLimitImpressionSiteTypeIndexSql[] =
"CREATE INDEX IF NOT EXISTS rate_limit_impression_site_type_idx "
"ON rate_limits(attribution_type,conversion_destination,"
"impression_site,conversion_time)";
if (!db->Execute(kRateLimitImpressionSiteTypeIndexSql))
return false;
static constexpr char kRateLimitConversionTimeIndexSql[] =
"CREATE INDEX IF NOT EXISTS rate_limit_conversion_time_idx "
"ON rate_limits(conversion_time)";
if (!db->Execute(kRateLimitConversionTimeIndexSql))
return false;
static constexpr char kRateLimitImpressionIndexSql[] =
"CREATE INDEX IF NOT EXISTS rate_limit_impression_id_idx "
"ON rate_limits(impression_id)";
if (!db->Execute(kRateLimitImpressionIndexSql))
return false;
meta_table->SetVersionNumber(4);
return transaction.Commit();
}
bool MigrateToVersion5(sql::Database* db, sql::MetaTable* meta_table) {
// Wrap each migration in its own transaction. See comment in
// |MigrateToVersion2|.
sql::Transaction transaction(db);
if (!transaction.Begin())
return false;
// Any corresponding impressions will naturally be cleaned up by the expiry
// logic.
static constexpr char kDropZeroCreditConversionsSql[] =
"DELETE FROM conversions WHERE attribution_credit = 0";
if (!db->Execute(kDropZeroCreditConversionsSql))
return false;
static constexpr char kDropAttributionCreditColumnSql[] =
"ALTER TABLE conversions DROP COLUMN attribution_credit";
if (!db->Execute(kDropAttributionCreditColumnSql))
return false;
meta_table->SetVersionNumber(5);
return transaction.Commit();
}
bool MigrateToVersion6(sql::Database* db, sql::MetaTable* meta_table) {
// Wrap each migration in its own transaction. See comment in
// |MigrateToVersion2|.
sql::Transaction transaction(db);
if (!transaction.Begin())
return false;
// Add new priority column to the impressions table. This follows the steps
// documented at https://sqlite.org/lang_altertable.html#otheralter. Other
// approaches, like using "ALTER ... ADD COLUMN" require setting a DEFAULT
// value for the column which is undesirable.
static constexpr char kNewImpressionTableSql[] =
"CREATE TABLE IF NOT EXISTS new_impressions"
"(impression_id INTEGER PRIMARY KEY,"
"impression_data TEXT NOT NULL,"
"impression_origin TEXT NOT NULL,"
"conversion_origin TEXT NOT NULL,"
"reporting_origin TEXT NOT NULL,"
"impression_time INTEGER NOT NULL,"
"expiry_time INTEGER NOT NULL,"
"num_conversions INTEGER DEFAULT 0,"
"active INTEGER DEFAULT 1,"
"conversion_destination TEXT NOT NULL,"
"source_type INTEGER NOT NULL,"
"attributed_truthfully INTEGER NOT NULL,"
"priority INTEGER NOT NULL)";
if (!db->Execute(kNewImpressionTableSql))
return false;
// Transfer the existing rows to the new table, inserting default values for
// the priority column.
static constexpr char kPopulateNewImpressionTableSql[] =
"INSERT INTO new_impressions SELECT "
"impression_id,impression_data,impression_origin,"
"conversion_origin,reporting_origin,impression_time,"
"expiry_time,num_conversions,active,conversion_destination,source_type,"
"attributed_truthfully,0 "
"FROM impressions";
sql::Statement populate_statement(
db->GetCachedStatement(SQL_FROM_HERE, kPopulateNewImpressionTableSql));
if (!populate_statement.Run())
return false;
static constexpr char kDropOldImpressionTableSql[] = "DROP TABLE impressions";
if (!db->Execute(kDropOldImpressionTableSql))
return false;
static constexpr char kRenameImpressionTableSql[] =
"ALTER TABLE new_impressions RENAME TO impressions";
if (!db->Execute(kRenameImpressionTableSql))
return false;
// Create the pre-existing impression table indices on the new table.
static constexpr char kImpressionExpiryIndexSql[] =
"CREATE INDEX IF NOT EXISTS impression_expiry_idx "
"ON impressions(expiry_time)";
if (!db->Execute(kImpressionExpiryIndexSql))
return false;
static constexpr char kImpressionOriginIndexSql[] =
"CREATE INDEX IF NOT EXISTS impression_origin_idx "
"ON impressions(impression_origin)";
if (!db->Execute(kImpressionOriginIndexSql))
return false;
static constexpr char kConversionDestinationIndexSql[] =
"CREATE INDEX IF NOT EXISTS conversion_destination_idx "
"ON impressions(active,conversion_destination,reporting_origin)";
if (!db->Execute(kConversionDestinationIndexSql))
return false;
meta_table->SetVersionNumber(6);
return transaction.Commit();
}
bool MigrateToVersion7(sql::Database* db, sql::MetaTable* meta_table) {
// Wrap each migration in its own transaction. See comment in
// |MigrateToVersion2|.
sql::Transaction transaction(db);
if (!transaction.Begin())
return false;
// Add new impression_site column to the impressions table. This follows the
// steps documented at https://sqlite.org/lang_altertable.html#otheralter.
// Other approaches, like using "ALTER ... ADD COLUMN" require setting a
// DEFAULT value for the column which is undesirable.
static constexpr char kNewImpressionTableSql[] =
"CREATE TABLE IF NOT EXISTS new_impressions"
"(impression_id INTEGER PRIMARY KEY,"
"impression_data TEXT NOT NULL,"
"impression_origin TEXT NOT NULL,"
"conversion_origin TEXT NOT NULL,"
"reporting_origin TEXT NOT NULL,"
"impression_time INTEGER NOT NULL,"
"expiry_time INTEGER NOT NULL,"
"num_conversions INTEGER DEFAULT 0,"
"active INTEGER DEFAULT 1,"
"conversion_destination TEXT NOT NULL,"
"source_type INTEGER NOT NULL,"
"attributed_truthfully INTEGER NOT NULL,"
"priority INTEGER NOT NULL,"
"impression_site TEXT NOT NULL)";
if (!db->Execute(kNewImpressionTableSql))
return false;
// Transfer the existing rows to the new table, inserting placeholder values
// for the impression_site column.
static constexpr char kPopulateNewImpressionTableSql[] =
"INSERT INTO new_impressions SELECT "
"impression_id,impression_data,impression_origin,"
"conversion_origin,reporting_origin,impression_time,"
"expiry_time,num_conversions,active,conversion_destination,source_type,"
"attributed_truthfully,priority,'' "
"FROM impressions";
sql::Statement populate_statement(
db->GetCachedStatement(SQL_FROM_HERE, kPopulateNewImpressionTableSql));
if (!populate_statement.Run())
return false;
static constexpr char kDropOldImpressionTableSql[] = "DROP TABLE impressions";
if (!db->Execute(kDropOldImpressionTableSql))
return false;
static constexpr char kRenameImpressionTableSql[] =
"ALTER TABLE new_impressions RENAME TO impressions";
if (!db->Execute(kRenameImpressionTableSql))
return false;
// Update each of the impression rows to have the correct associated
// impression_site.
//
// We update a subset of rows at a time to avoid pulling the entire
// impressions table into memory.
std::vector<ImpressionIdAndImpressionOrigin> impressions =
GetImpressionIdAndImpressionOrigins(db, StorableSource::Id(0));
static constexpr char kUpdateImpressionSiteSql[] =
"UPDATE impressions SET impression_site = ? WHERE impression_id = ?";
sql::Statement update_impression_site_statement(
db->GetCachedStatement(SQL_FROM_HERE, kUpdateImpressionSiteSql));
while (!impressions.empty()) {
// Perform the column updates for each row we pulled into memory.
for (const auto& impression : impressions) {
update_impression_site_statement.Reset(/*clear_bound_vars=*/true);
// The impression site is derived from the impression origin dynamically.
update_impression_site_statement.BindString(
0, net::SchemefulSite(impression.impression_origin).Serialize());
update_impression_site_statement.BindInt64(1, *impression.impression_id);
if (!update_impression_site_statement.Run())
return false;
}
// Fetch the next batch of rows from the database.
impressions = GetImpressionIdAndImpressionOrigins(
db, NextImpressionId(impressions.back().impression_id));
}
// Create the pre-existing impression table indices on the new table.
static constexpr char kImpressionExpiryIndexSql[] =
"CREATE INDEX IF NOT EXISTS impression_expiry_idx "
"ON impressions(expiry_time)";
if (!db->Execute(kImpressionExpiryIndexSql))
return false;
static constexpr char kImpressionOriginIndexSql[] =
"CREATE INDEX IF NOT EXISTS impression_origin_idx "
"ON impressions(impression_origin)";
if (!db->Execute(kImpressionOriginIndexSql))
return false;
static constexpr char kConversionDestinationIndexSql[] =
"CREATE INDEX IF NOT EXISTS conversion_destination_idx "
"ON impressions(active,conversion_destination,reporting_origin)";
if (!db->Execute(kConversionDestinationIndexSql))
return false;
// Create the new impression table index.
static constexpr char kImpressionSiteIndexSql[] =
"CREATE INDEX IF NOT EXISTS impression_site_idx "
"ON impressions(active,impression_site,source_type)";
if (!db->Execute(kImpressionSiteIndexSql))
return false;
meta_table->SetVersionNumber(7);
return transaction.Commit();
}
struct ImpressionIdAndImpressionData {
StorableSource::Id impression_id;
std::string impression_data;
};
std::vector<ImpressionIdAndImpressionData> GetImpressionIdAndImpressionData(
sql::Database* db,
StorableSource::Id start_impression_id) {
static constexpr char kGetImpressionsSql[] =
"SELECT impression_id,impression_data "
"FROM impressions "
"WHERE impression_id >= ? "
"ORDER BY impression_id "
"LIMIT ?";
sql::Statement statement(
db->GetCachedStatement(SQL_FROM_HERE, kGetImpressionsSql));
statement.BindInt64(0, *start_impression_id);
const int kNumImpressions = 100;
statement.BindInt(1, kNumImpressions);
std::vector<ImpressionIdAndImpressionData> impressions;
while (statement.Step()) {
StorableSource::Id impression_id(statement.ColumnInt64(0));
std::string impression_data = statement.ColumnString(1);
impressions.push_back({impression_id, std::move(impression_data)});
}
if (!statement.Succeeded())
return {};
return impressions;
}
bool MigrateToVersion8(sql::Database* db, sql::MetaTable* meta_table) {
// Wrap each migration in its own transaction. See comment in
// |MigrateToVersion2|.
sql::Transaction transaction(db);
if (!transaction.Begin())
return false;
// Change the impression_data column from TEXT to INTEGER. This follows the
// steps documented at https://sqlite.org/lang_altertable.html#otheralter.
// Other approaches, like using "ALTER ... ADD COLUMN" require setting a
// DEFAULT value for the column which is undesirable.
static constexpr char kNewImpressionTableSql[] =
"CREATE TABLE IF NOT EXISTS new_impressions"
"(impression_id INTEGER PRIMARY KEY,"
"impression_data INTEGER NOT NULL,"
"impression_origin TEXT NOT NULL,"
"conversion_origin TEXT NOT NULL,"
"reporting_origin TEXT NOT NULL,"
"impression_time INTEGER NOT NULL,"
"expiry_time INTEGER NOT NULL,"
"num_conversions INTEGER DEFAULT 0,"
"active INTEGER DEFAULT 1,"
"conversion_destination TEXT NOT NULL,"
"source_type INTEGER NOT NULL,"
"attributed_truthfully INTEGER NOT NULL,"
"priority INTEGER NOT NULL,"
"impression_site TEXT NOT NULL)";
if (!db->Execute(kNewImpressionTableSql))
return false;
// Transfer the existing impressions rows to the new table with a placeholder
// for the impression_data column.
static constexpr char kPopulateNewImpressionsSql[] =
"INSERT INTO new_impressions SELECT "
"impression_id,0,impression_origin,conversion_origin,reporting_origin,"
"impression_time,expiry_time,num_conversions,active,"
"conversion_destination,source_type,attributed_truthfully,priority,"
"impression_site FROM impressions";
sql::Statement populate_new_impressions_statement(
db->GetCachedStatement(SQL_FROM_HERE, kPopulateNewImpressionsSql));
if (!populate_new_impressions_statement.Run())
return false;
// Update each of the impression rows to have the correct associated
// impression_data. We can't use the CAST SQL function here because it
// doesn't support the full range of `uint64_t`.
//
// We update a subset of rows at a time to avoid pulling the entire
// impressions table into memory.
std::vector<ImpressionIdAndImpressionData> impressions =
GetImpressionIdAndImpressionData(db, StorableSource::Id(0));
static constexpr char kUpdateImpressionDataSql[] =
"UPDATE new_impressions SET impression_data = ? WHERE impression_id = ?";
sql::Statement update_impression_data_statement(
db->GetCachedStatement(SQL_FROM_HERE, kUpdateImpressionDataSql));
while (!impressions.empty()) {
// Perform the column updates for each row we pulled into memory.
for (const auto& impression : impressions) {
// If we can't parse the data, skip the update to leave the column as 0.
uint64_t impression_data = 0u;
if (!base::StringToUint64(impression.impression_data, &impression_data))
continue;
update_impression_data_statement.Reset(/*clear_bound_vars=*/true);
update_impression_data_statement.BindInt64(
0, SerializeUint64(impression_data));
update_impression_data_statement.BindInt64(1, *impression.impression_id);
update_impression_data_statement.Run();
}
// Fetch the next batch of rows from the database.
impressions = GetImpressionIdAndImpressionData(
db, NextImpressionId(impressions.back().impression_id));
}
static constexpr char kDropOldImpressionTableSql[] = "DROP TABLE impressions";
if (!db->Execute(kDropOldImpressionTableSql))
return false;
static constexpr char kRenameImpressionTableSql[] =
"ALTER TABLE new_impressions RENAME TO impressions";
if (!db->Execute(kRenameImpressionTableSql))
return false;
// Create the pre-existing impression table indices on the new table.
static constexpr char kImpressionExpiryIndexSql[] =
"CREATE INDEX IF NOT EXISTS impression_expiry_idx "
"ON impressions(expiry_time)";
if (!db->Execute(kImpressionExpiryIndexSql))
return false;
static constexpr char kImpressionOriginIndexSql[] =
"CREATE INDEX IF NOT EXISTS impression_origin_idx "
"ON impressions(impression_origin)";
if (!db->Execute(kImpressionOriginIndexSql))
return false;
static constexpr char kConversionDestinationIndexSql[] =
"CREATE INDEX IF NOT EXISTS conversion_destination_idx "
"ON impressions(active,conversion_destination,reporting_origin)";
if (!db->Execute(kConversionDestinationIndexSql))
return false;
static constexpr char kImpressionSiteIndexSql[] =
"CREATE INDEX IF NOT EXISTS impression_site_idx "
"ON impressions(active,impression_site,source_type)";
if (!db->Execute(kImpressionSiteIndexSql))
return false;
// Change the conversion_data column from TEXT to INTEGER and make
// impression_id NOT NULL. This follows the steps documented at
// https://sqlite.org/lang_altertable.html#otheralter./ Other approaches, like
// using "ALTER ... ADD COLUMN" require setting a DEFAULT value for the column
// which is undesirable.
static constexpr char kNewConversionTableSql[] =
"CREATE TABLE IF NOT EXISTS new_conversions"
"(conversion_id INTEGER PRIMARY KEY,"
"impression_id INTEGER NOT NULL,"
"conversion_data INTEGER NOT NULL,"
"conversion_time INTEGER NOT NULL,"
"report_time INTEGER NOT NULL)";
if (!db->Execute(kNewConversionTableSql))
return false;
// Transfer the existing conversions rows to the new table. See
// https://www.sqlite.org/lang_expr.html#castexpr for details on CAST, which
// we can use here because valid conversion_data is in the range [0, 8].
// Existing impression_id values should never be NULL, but if they are, we
// insert 0 instead of failing.
static constexpr char kPopulateNewConversionsSql[] =
"INSERT INTO new_conversions SELECT "
"conversion_id,IFNULL(impression_id,0),"
"CAST(conversion_data AS INTEGER),conversion_time,report_time "
"FROM conversions";
sql::Statement populate_new_conversions_statement(
db->GetCachedStatement(SQL_FROM_HERE, kPopulateNewConversionsSql));
if (!populate_new_conversions_statement.Run())
return false;
static constexpr char kDropOldConversionTableSql[] = "DROP TABLE conversions";
if (!db->Execute(kDropOldConversionTableSql))
return false;
static constexpr char kRenameConversionTableSql[] =
"ALTER TABLE new_conversions RENAME TO conversions";
if (!db->Execute(kRenameConversionTableSql))
return false;
// Create the pre-existing conversion table indices on the new table.
static constexpr char kConversionReportTimeIndexSql[] =
"CREATE INDEX IF NOT EXISTS conversion_report_idx "
"ON conversions(report_time)";
if (!db->Execute(kConversionReportTimeIndexSql))
return false;
static constexpr char kConversionClickIdIndexSql[] =
"CREATE INDEX IF NOT EXISTS conversion_impression_id_idx "
"ON conversions(impression_id)";
if (!db->Execute(kConversionClickIdIndexSql))
return false;
meta_table->SetVersionNumber(8);
return transaction.Commit();
}
bool MigrateToVersion9(sql::Database* db, sql::MetaTable* meta_table) {
// Wrap each migration in its own transaction. See comment in
// |MigrateToVersion2|.
sql::Transaction transaction(db);
if (!transaction.Begin())
return false;
// Add new priority column to the conversions table. This follows the
// steps documented at https://sqlite.org/lang_altertable.html#otheralter.
// Other approaches, like using "ALTER ... ADD COLUMN" require setting a
// DEFAULT value for the column which is undesirable.
static constexpr char kNewTableSql[] =
"CREATE TABLE IF NOT EXISTS new_conversions"
"(conversion_id INTEGER PRIMARY KEY,"
"impression_id INTEGER NOT NULL,"
"conversion_data INTEGER NOT NULL,"
"conversion_time INTEGER NOT NULL,"
"report_time INTEGER NOT NULL,"
"priority INTEGER NOT NULL)";
if (!db->Execute(kNewTableSql))
return false;
// Transfer the existing rows to the new table, inserting 0 for the priority
// column.
static constexpr char kPopulateSql[] =
"INSERT INTO new_conversions SELECT "
"conversion_id,impression_id,conversion_data,conversion_time,"
"report_time,0 "
"FROM conversions";
sql::Statement populate_statement(
db->GetCachedStatement(SQL_FROM_HERE, kPopulateSql));
if (!populate_statement.Run())
return false;
static constexpr char kDropOldTableSql[] = "DROP TABLE conversions";
if (!db->Execute(kDropOldTableSql))
return false;
static constexpr char kRenameTableSql[] =
"ALTER TABLE new_conversions RENAME TO conversions";
if (!db->Execute(kRenameTableSql))
return false;
// Create the pre-existing conversion table indices on the new table.
static constexpr char kConversionReportTimeIndexSql[] =
"CREATE INDEX IF NOT EXISTS conversion_report_idx "
"ON conversions(report_time)";
if (!db->Execute(kConversionReportTimeIndexSql))
return false;
static constexpr char kConversionClickIdIndexSql[] =
"CREATE INDEX IF NOT EXISTS conversion_impression_id_idx "
"ON conversions(impression_id)";
if (!db->Execute(kConversionClickIdIndexSql))
return false;
meta_table->SetVersionNumber(9);
return transaction.Commit();
}
bool MigrateToVersion10(sql::Database* db, sql::MetaTable* meta_table) {
// Wrap each migration in its own transaction. See comment in
// |MigrateToVersion2|.
sql::Transaction transaction(db);
if (!transaction.Begin())
return false;
static constexpr char kDedupKeyTableSql[] =
"CREATE TABLE IF NOT EXISTS dedup_keys"
"(impression_id INTEGER NOT NULL,"
"dedup_key INTEGER NOT NULL,"
"PRIMARY KEY(impression_id,dedup_key))WITHOUT ROWID";
if (!db->Execute(kDedupKeyTableSql))
return false;
meta_table->SetVersionNumber(10);
return transaction.Commit();
}
bool MigrateToVersion11(sql::Database* db, sql::MetaTable* meta_table) {
// Wrap each migration in its own transaction. See comment in
// |MigrateToVersion2|.
sql::Transaction transaction(db);
if (!transaction.Begin())
return false;
static constexpr char kDropOldImpressionSiteIdxSql[] =
"DROP INDEX impression_site_idx";
if (!db->Execute(kDropOldImpressionSiteIdxSql))
return false;
static constexpr char kEventSourceImpressionSiteIndexSql[] =
"CREATE INDEX IF NOT EXISTS event_source_impression_site_idx "
"ON impressions(impression_site)"
"WHERE active = 1 AND num_conversions = 0 AND source_type = 1";
if (!db->Execute(kEventSourceImpressionSiteIndexSql))
return false;
meta_table->SetVersionNumber(11);
return transaction.Commit();
}
bool MigrateToVersion12(sql::Database* db, sql::MetaTable* meta_table) {
// Wrap each migration in its own transaction. See comment in
// |MigrateToVersion2|.
sql::Transaction transaction(db);
if (!transaction.Begin())
return false;
static constexpr char kNewRateLimitTableSql[] =
"CREATE TABLE IF NOT EXISTS new_rate_limits"
"(rate_limit_id INTEGER PRIMARY KEY NOT NULL,"
"attribution_type INTEGER NOT NULL,"
"impression_id INTEGER NOT NULL,"
"impression_site TEXT NOT NULL,"
"impression_origin TEXT NOT NULL,"
"conversion_destination TEXT NOT NULL,"
"conversion_origin TEXT NOT NULL,"
"conversion_time INTEGER NOT NULL,"
"bucket TEXT NOT NULL,"
"value INTEGER NOT NULL)";
if (!db->Execute(kNewRateLimitTableSql))
return false;
// Transfer the existing rows to the new table, inserting 0 for `bucket` and
// 1 for `value`, since all existing rows are non-aggregate.
static constexpr char kPopulateNewRateLimitTableSql[] =
"INSERT INTO new_rate_limits SELECT "
"rate_limit_id,attribution_type,impression_id,impression_site,"
"impression_origin,conversion_destination,conversion_origin,"
"conversion_time,0,1 "
"FROM rate_limits";
if (!db->Execute(kPopulateNewRateLimitTableSql))
return false;
static constexpr char kDropOldRateLimitTableSql[] = "DROP TABLE rate_limits";
if (!db->Execute(kDropOldRateLimitTableSql))
return false;
static constexpr char kRenameRateLimitTableSql[] =
"ALTER TABLE new_rate_limits RENAME TO rate_limits";
if (!db->Execute(kRenameRateLimitTableSql))
return false;
// Create the pre-existing indices on the new table.
static constexpr char kRateLimitImpressionSiteTypeIndexSql[] =
"CREATE INDEX IF NOT EXISTS rate_limit_impression_site_type_idx "
"ON rate_limits(attribution_type,conversion_destination,"
"impression_site,conversion_time)";
if (!db->Execute(kRateLimitImpressionSiteTypeIndexSql))
return false;
// Add the attribution_type as a prefix of the index.
static constexpr char kRateLimitAttributionTypeConversionTimeIndexSql[] =
"CREATE INDEX IF NOT EXISTS "
"rate_limit_attribution_type_conversion_time_idx "
"ON rate_limits(attribution_type,conversion_time)";
if (!db->Execute(kRateLimitAttributionTypeConversionTimeIndexSql))
return false;
static constexpr char kRateLimitImpressionIndexSql[] =
"CREATE INDEX IF NOT EXISTS rate_limit_impression_id_idx "
"ON rate_limits(impression_id)";
if (!db->Execute(kRateLimitImpressionIndexSql))
return false;
meta_table->SetVersionNumber(12);
return transaction.Commit();
}
bool MigrateToVersion13(sql::Database* db, sql::MetaTable* meta_table) {
// Wrap each migration in its own transaction. See comment in
// |MigrateToVersion2|.
sql::Transaction transaction(db);
if (!transaction.Begin())
return false;
// Create the new impressions table with impression_id `NOT NULL` and
// `AUTOINCREMENT`.
static constexpr char kNewImpressionTableSql[] =
"CREATE TABLE IF NOT EXISTS new_impressions"
"(impression_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
"impression_data INTEGER NOT NULL,"
"impression_origin TEXT NOT NULL,"
"conversion_origin TEXT NOT NULL,"
"reporting_origin TEXT NOT NULL,"
"impression_time INTEGER NOT NULL,"
"expiry_time INTEGER NOT NULL,"
"num_conversions INTEGER DEFAULT 0,"
"active INTEGER DEFAULT 1,"
"conversion_destination TEXT NOT NULL,"
"source_type INTEGER NOT NULL,"
"attributed_truthfully INTEGER NOT NULL,"
"priority INTEGER NOT NULL,"
"impression_site TEXT NOT NULL)";
if (!db->Execute(kNewImpressionTableSql))
return false;
// Transfer the existing rows to the new table.
static constexpr char kPopulateNewImpressionTableSql[] =
"INSERT INTO new_impressions SELECT "
"impression_id,impression_data,impression_origin,"
"conversion_origin,reporting_origin,impression_time,"
"expiry_time,num_conversions,active,conversion_destination,"
"source_type,attributed_truthfully,priority,impression_site "
"FROM impressions";
if (!db->Execute(kPopulateNewImpressionTableSql))
return false;
static constexpr char kDropOldImpressionTableSql[] = "DROP TABLE impressions";
if (!db->Execute(kDropOldImpressionTableSql))
return false;
static constexpr char kRenameImpressionTableSql[] =
"ALTER TABLE new_impressions RENAME TO impressions";
if (!db->Execute(kRenameImpressionTableSql))
return false;
// Create the pre-existing impression table indices on the new table.
static constexpr char kConversionDestinationIndexSql[] =
"CREATE INDEX IF NOT EXISTS conversion_destination_idx "
"ON impressions(active,conversion_destination,reporting_origin)";
if (!db->Execute(kConversionDestinationIndexSql))
return false;
static constexpr char kImpressionExpiryIndexSql[] =
"CREATE INDEX IF NOT EXISTS impression_expiry_idx "
"ON impressions(expiry_time)";
if (!db->Execute(kImpressionExpiryIndexSql))
return false;
static constexpr char kImpressionOriginIndexSql[] =
"CREATE INDEX IF NOT EXISTS impression_origin_idx "
"ON impressions(impression_origin)";
if (!db->Execute(kImpressionOriginIndexSql))
return false;
static constexpr char kEventSourceImpressionSiteIndexSql[] =
"CREATE INDEX IF NOT EXISTS event_source_impression_site_idx "
"ON impressions(impression_site)"
"WHERE active = 1 AND num_conversions = 0 AND source_type = 1";
if (!db->Execute(kEventSourceImpressionSiteIndexSql))
return false;
// Create the new conversions table with conversion_id `NOT NULL` and
// `AUTOINCREMENT`.
static constexpr char kNewConversionTableSql[] =
"CREATE TABLE IF NOT EXISTS new_conversions"
"(conversion_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
"impression_id INTEGER NOT NULL,"
"conversion_data INTEGER NOT NULL,"
"conversion_time INTEGER NOT NULL,"
"report_time INTEGER NOT NULL,"
"priority INTEGER NOT NULL)";
if (!db->Execute(kNewConversionTableSql))
return false;
// Transfer the existing rows to the new table.
static constexpr char kPopulateNewConversionTableSql[] =
"INSERT INTO new_conversions SELECT "
"conversion_id,impression_id,conversion_data,conversion_time,"
"report_time,priority "
"FROM conversions";
if (!db->Execute(kPopulateNewConversionTableSql))
return false;
static constexpr char kDropOldConversionTableSql[] = "DROP TABLE conversions";
if (!db->Execute(kDropOldConversionTableSql))
return false;
static constexpr char kRenameConversionTableSql[] =
"ALTER TABLE new_conversions RENAME TO conversions";
if (!db->Execute(kRenameConversionTableSql))
return false;
// Create the pre-existing conversion table indices on the new table.
static constexpr char kConversionReportTimeIndexSql[] =
"CREATE INDEX IF NOT EXISTS conversion_report_idx "
"ON conversions(report_time)";
if (!db->Execute(kConversionReportTimeIndexSql))
return false;
static constexpr char kConversionImpressionIdIndexSql[] =
"CREATE INDEX IF NOT EXISTS conversion_impression_id_idx "
"ON conversions(impression_id)";
if (!db->Execute(kConversionImpressionIdIndexSql))
return false;
meta_table->SetVersionNumber(13);
return transaction.Commit();
}
bool MigrateToVersion14(sql::Database* db, sql::MetaTable* meta_table) {
// Wrap each migration in its own transaction. See comment in
// |MigrateToVersion2|.
sql::Transaction transaction(db);
if (!transaction.Begin())
return false;
// Create the new conversions table with failed_send_attempts.
static constexpr char kNewConversionTableSql[] =
"CREATE TABLE IF NOT EXISTS new_conversions"
"(conversion_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
"impression_id INTEGER NOT NULL,"
"conversion_data INTEGER NOT NULL,"
"conversion_time INTEGER NOT NULL,"
"report_time INTEGER NOT NULL,"
"priority INTEGER NOT NULL,"
"failed_send_attempts INTEGER NOT NULL)";
if (!db->Execute(kNewConversionTableSql))
return false;
// Transfer the existing conversions rows to the new table, using 0 for
// failed_send_attempts since we have no basis to say otherwise.
static constexpr char kPopulateNewConversionsSql[] =
"INSERT INTO new_conversions SELECT "
"conversion_id,impression_id,conversion_data,conversion_time,report_time,"
"priority,0 FROM conversions";
sql::Statement populate_new_conversions_statement(
db->GetCachedStatement(SQL_FROM_HERE, kPopulateNewConversionsSql));
if (!populate_new_conversions_statement.Run())
return false;
static constexpr char kDropOldConversionTableSql[] = "DROP TABLE conversions";
if (!db->Execute(kDropOldConversionTableSql))
return false;
static constexpr char kRenameConversionTableSql[] =
"ALTER TABLE new_conversions RENAME TO conversions";
if (!db->Execute(kRenameConversionTableSql))
return false;
// Create the pre-existing conversion table indices on the new table.
static constexpr char kConversionReportTimeIndexSql[] =
"CREATE INDEX IF NOT EXISTS conversion_report_idx "
"ON conversions(report_time)";
if (!db->Execute(kConversionReportTimeIndexSql))
return false;
static constexpr char kConversionImpressionIdIndexSql[] =
"CREATE INDEX IF NOT EXISTS conversion_impression_id_idx "
"ON conversions(impression_id)";
if (!db->Execute(kConversionImpressionIdIndexSql))
return false;
meta_table->SetVersionNumber(14);
return transaction.Commit();
}
bool MigrateToVersion15(sql::Database* db,
sql::MetaTable* meta_table,
AttributionStorage::Delegate* delegate) {
// Wrap each migration in its own transaction. See comment in
// |MigrateToVersion2|.
sql::Transaction transaction(db);
if (!transaction.Begin())
return false;
// Create the new conversions table with external_report_id.
static constexpr char kNewConversionTableSql[] =
"CREATE TABLE IF NOT EXISTS new_conversions"
"(conversion_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
"impression_id INTEGER NOT NULL,"
"conversion_data INTEGER NOT NULL,"
"conversion_time INTEGER NOT NULL,"
"report_time INTEGER NOT NULL,"
"priority INTEGER NOT NULL,"
"failed_send_attempts INTEGER NOT NULL,"
"external_report_id TEXT NOT NULL)";
if (!db->Execute(kNewConversionTableSql))
return false;
// Transfer the existing conversions rows to the new table, using the empty
// string for external_report_id, which we will update afterward.
static constexpr char kPopulateNewConversionsSql[] =
"INSERT INTO new_conversions SELECT "
"conversion_id,impression_id,conversion_data,conversion_time,report_time,"
"priority,failed_send_attempts,'' FROM conversions";
sql::Statement populate_new_conversions_statement(
db->GetCachedStatement(SQL_FROM_HERE, kPopulateNewConversionsSql));
if (!populate_new_conversions_statement.Run())
return false;
// Update each of the conversion rows to have a random external_report_id.
//
// We update a subset of rows at a time to avoid pulling the entire
// conversions table into memory.
std::vector<AttributionReport::Id> conversion_ids =
GetConversionIds(db, AttributionReport::Id(0));
static constexpr char kUpdateExternalReportIdSql[] =
"UPDATE new_conversions SET external_report_id = ? "
"WHERE conversion_id = ?";
sql::Statement update_statement(
db->GetCachedStatement(SQL_FROM_HERE, kUpdateExternalReportIdSql));
while (!conversion_ids.empty()) {
// Perform the column updates for each row we pulled into memory.
for (AttributionReport::Id conversion_id : conversion_ids) {
update_statement.Reset(/*clear_bound_vars=*/true);
base::GUID external_report_id = delegate->NewReportID();
DCHECK(external_report_id.is_valid());
update_statement.BindString(0, external_report_id.AsLowercaseString());
update_statement.BindInt64(1, *conversion_id);
if (!update_statement.Run())
return false;
}
// Fetch the next batch of rows from the database.
conversion_ids =
GetConversionIds(db, NextConversionId(conversion_ids.back()));
}
static constexpr char kDropOldConversionTableSql[] = "DROP TABLE conversions";
if (!db->Execute(kDropOldConversionTableSql))
return false;
static constexpr char kRenameConversionTableSql[] =
"ALTER TABLE new_conversions RENAME TO conversions";
if (!db->Execute(kRenameConversionTableSql))
return false;
// Create the pre-existing conversion table indices on the new table.
static constexpr char kConversionReportTimeIndexSql[] =
"CREATE INDEX IF NOT EXISTS conversion_report_idx "
"ON conversions(report_time)";
if (!db->Execute(kConversionReportTimeIndexSql))
return false;
static constexpr char kConversionImpressionIdIndexSql[] =
"CREATE INDEX IF NOT EXISTS conversion_impression_id_idx "
"ON conversions(impression_id)";
if (!db->Execute(kConversionImpressionIdIndexSql))
return false;
meta_table->SetVersionNumber(15);
return transaction.Commit();
}
} // namespace
bool UpgradeAttributionStorageSqlSchema(
sql::Database* db,
sql::MetaTable* meta_table,
AttributionStorage::Delegate* delegate) {
DCHECK(db);
DCHECK(meta_table);
DCHECK(delegate);
base::ThreadTicks start_timestamp = base::ThreadTicks::Now();
if (meta_table->GetVersionNumber() == 1) {
if (!MigrateToVersion2(db, meta_table))
return false;
}
if (meta_table->GetVersionNumber() == 2) {
if (!MigrateToVersion3(db, meta_table))
return false;
}
if (meta_table->GetVersionNumber() == 3) {
if (!MigrateToVersion4(db, meta_table))
return false;
}
if (meta_table->GetVersionNumber() == 4) {
if (!MigrateToVersion5(db, meta_table))
return false;
}
if (meta_table->GetVersionNumber() == 5) {
if (!MigrateToVersion6(db, meta_table))
return false;
}
if (meta_table->GetVersionNumber() == 6) {
if (!MigrateToVersion7(db, meta_table))
return false;
}
if (meta_table->GetVersionNumber() == 7) {
if (!MigrateToVersion8(db, meta_table))
return false;
}
if (meta_table->GetVersionNumber() == 8) {
if (!MigrateToVersion9(db, meta_table))
return false;
}
if (meta_table->GetVersionNumber() == 9) {
if (!MigrateToVersion10(db, meta_table))
return false;
}
if (meta_table->GetVersionNumber() == 10) {
if (!MigrateToVersion11(db, meta_table))
return false;
}
if (meta_table->GetVersionNumber() == 11) {
if (!MigrateToVersion12(db, meta_table))
return false;
}
if (meta_table->GetVersionNumber() == 12) {
if (!MigrateToVersion13(db, meta_table))
return false;
}
if (meta_table->GetVersionNumber() == 13) {
if (!MigrateToVersion14(db, meta_table))
return false;
}
if (meta_table->GetVersionNumber() == 14) {
if (!MigrateToVersion15(db, meta_table, delegate))
return false;
}
// Add similar if () blocks for new versions here.
base::UmaHistogramMediumTimes("Conversions.Storage.MigrationTime",
base::ThreadTicks::Now() - start_timestamp);
return true;
}
} // namespace content
| 17,022 |
1,202 |
<filename>source/tvision/tlabel.cpp<gh_stars>1000+
/*------------------------------------------------------------*/
/* filename - tlabel.cpp */
/* */
/* function(s) */
/* TLabel member functions */
/*------------------------------------------------------------*/
/*
* Turbo Vision - Version 2.0
*
* Copyright (c) 1994 by Borland International
* All Rights Reserved.
*
*/
#define Uses_TLabel
#define Uses_TEvent
#define Uses_TDrawBuffer
#define Uses_TGroup
#define Uses_TView
#define Uses_opstream
#define Uses_ipstream
#include <tvision/tv.h>
#if !defined( __CTYPE_H )
#include <ctype.h>
#endif // __CTYPE_H
#define cpLabel "\x07\x08\x09\x09"
TLabel::TLabel( const TRect& bounds, TStringView aText, TView* aLink) noexcept :
TStaticText( bounds, aText ),
link( aLink ),
light( False )
{
options |= ofPreProcess | ofPostProcess;
eventMask |= evBroadcast;
}
void TLabel::shutDown()
{
link = 0;
TStaticText::shutDown();
}
void TLabel::draw()
{
TAttrPair color;
TDrawBuffer b;
uchar scOff;
if( light )
{
color = getColor(0x0402);
scOff = 0;
}
else
{
color = getColor(0x0301);
scOff = 4;
}
b.moveChar( 0, ' ', color, size.x );
if( text != 0 )
b.moveCStr( 1, text, color );
if( showMarkers )
b.putChar( 0, specialChars[scOff] );
writeLine( 0, 0, size.x, 1, b );
}
TPalette& TLabel::getPalette() const
{
static TPalette palette( cpLabel, sizeof( cpLabel )-1 );
return palette;
}
void TLabel::focusLink(TEvent& event)
{
if (link && (link->options & ofSelectable))
link->focus();
clearEvent(event);
}
void TLabel::handleEvent( TEvent& event )
{
TStaticText::handleEvent(event);
if( event.what == evMouseDown )
focusLink(event);
else if( event.what == evKeyDown )
{
char c = hotKey( text );
if( getAltCode(c) == event.keyDown.keyCode ||
( c != 0 && owner->phase == TGroup::phPostProcess &&
toupper(event.keyDown.charScan.charCode) == c )
)
focusLink(event);
}
else if( event.what == evBroadcast && link &&
( event.message.command == cmReceivedFocus ||
event.message.command == cmReleasedFocus )
)
{
light = Boolean( (link->state & sfFocused) != 0 );
drawView();
}
}
#if !defined(NO_STREAMABLE)
void TLabel::write( opstream& os )
{
TStaticText::write( os );
os << link;
}
void *TLabel::read( ipstream& is )
{
TStaticText::read( is );
is >> link;
light = False;
return this;
}
TStreamable *TLabel::build()
{
return new TLabel( streamableInit );
}
TLabel::TLabel( StreamableInit ) noexcept : TStaticText( streamableInit )
{
}
#endif
| 1,548 |
1,168 |
/*
* Copyright (C) 2019 <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package me.panpf.sketch.request;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import me.panpf.sketch.util.SketchUtils;
public class CallbackHandler {
private static final Handler handler;
private static final int WHAT_RUN_COMPLETED = 33001;
private static final int WHAT_RUN_FAILED = 33002;
private static final int WHAT_RUN_CANCELED = 33003;
private static final int WHAT_RUN_UPDATE_PROGRESS = 33004;
private static final int WHAT_CALLBACK_STARTED = 44001;
private static final int WHAT_CALLBACK_FAILED = 44002;
private static final int WHAT_CALLBACK_CANCELED = 44003;
private static final String PARAM_FAILED_CAUSE = "failedCause";
private static final String PARAM_CANCELED_CAUSE = "canceledCause";
static {
handler = new Handler(Looper.getMainLooper(), new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case WHAT_RUN_COMPLETED:
((AsyncRequest) msg.obj).runCompletedInMainThread();
break;
case WHAT_RUN_CANCELED:
((AsyncRequest) msg.obj).runCanceledInMainThread();
break;
case WHAT_RUN_UPDATE_PROGRESS:
((AsyncRequest) msg.obj).runUpdateProgressInMainThread(msg.arg1, msg.arg2);
break;
case WHAT_RUN_FAILED:
((AsyncRequest) msg.obj).runErrorInMainThread();
break;
case WHAT_CALLBACK_STARTED:
((Listener) msg.obj).onStarted();
break;
case WHAT_CALLBACK_FAILED:
((Listener) msg.obj).onError(ErrorCause.valueOf(msg.getData().getString(PARAM_FAILED_CAUSE)));
break;
case WHAT_CALLBACK_CANCELED:
((Listener) msg.obj).onCanceled(CancelCause.valueOf(msg.getData().getString(PARAM_CANCELED_CAUSE)));
break;
}
return true;
}
});
}
private CallbackHandler() {
}
/**
* 推到主线程处理完成
*/
static void postRunCompleted(@NonNull AsyncRequest request) {
if (request.isSync()) {
request.runCompletedInMainThread();
} else {
handler.obtainMessage(WHAT_RUN_COMPLETED, request).sendToTarget();
}
}
/**
* 推到主线程处理取消
*/
static void postRunCanceled(@NonNull AsyncRequest request) {
if (request.isSync()) {
request.runCanceledInMainThread();
} else {
handler.obtainMessage(WHAT_RUN_CANCELED, request).sendToTarget();
}
}
/**
* 推到主线程处理失败
*/
static void postRunError(@NonNull AsyncRequest request) {
if (request.isSync()) {
request.runErrorInMainThread();
} else {
handler.obtainMessage(WHAT_RUN_FAILED, request).sendToTarget();
}
}
/**
* 推到主线程处理进度
*/
static void postRunUpdateProgress(@NonNull AsyncRequest request, int totalLength, int completedLength) {
if (request.isSync()) {
request.runUpdateProgressInMainThread(totalLength, completedLength);
} else {
handler.obtainMessage(WHAT_RUN_UPDATE_PROGRESS, totalLength, completedLength, request).sendToTarget();
}
}
static void postCallbackStarted(@Nullable Listener listener, boolean sync) {
if (listener != null) {
if (sync || SketchUtils.isMainThread()) {
listener.onStarted();
} else {
handler.obtainMessage(WHAT_CALLBACK_STARTED, listener).sendToTarget();
}
}
}
static void postCallbackError(@Nullable Listener listener, @NonNull ErrorCause errorCause, boolean sync) {
if (listener != null) {
if (sync || SketchUtils.isMainThread()) {
listener.onError(errorCause);
} else {
Message message = handler.obtainMessage(WHAT_CALLBACK_FAILED, listener);
Bundle bundle = new Bundle();
bundle.putString(PARAM_FAILED_CAUSE, errorCause.name());
message.setData(bundle);
message.sendToTarget();
}
}
}
static void postCallbackCanceled(@Nullable Listener listener, @NonNull CancelCause cancelCause, boolean sync) {
if (listener != null) {
if (sync || SketchUtils.isMainThread()) {
listener.onCanceled(cancelCause);
} else {
Message message = handler.obtainMessage(WHAT_CALLBACK_CANCELED, listener);
Bundle bundle = new Bundle();
bundle.putString(PARAM_CANCELED_CAUSE, cancelCause.name());
message.setData(bundle);
message.sendToTarget();
}
}
}
}
| 2,713 |
488 |
<gh_stars>100-1000
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <stdint.h>
#include <map>
#include <stack>
#include <list>
#if 1
#ifdef __cplusplus
extern "C" {
#endif
#endif
typedef std::pair<uint64_t, uint64_t> IntPair;
IntPair insertIntoSLK();
void removeFromSLK();
IntPair insert_lock();
void remove_lock(uint64_t lock_index);
void execAtFirst();
void execAtLast();
int* fn1(int *temp, int lock) {
insertIntoSLK();
free(temp);
remove_lock(lock);
removeFromSLK();
return temp;
}
int main() {
execAtFirst();
int* temp = (int*)malloc(sizeof(int));
IntPair lock_key = insert_lock();
*temp = 3;
temp = fn1(temp, lock_key.first);
free(temp);
*temp = 2;
execAtLast();
return 1;
}
#if 1
#ifdef __cplusplus
}
#endif
#endif
| 367 |
1,475 |
<reponame>mhansonp/geode
/*
* 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.geode.cache.query;
/**
* This class provides methods to get aggregate statistical information about the CQs of a client.
*
* @since GemFire 5.5
*/
public interface CqServiceStatistics {
/**
* Get the number of CQs currently active. Active CQs are those which are executing (in running
* state).
*
* @return long number of CQs
*/
long numCqsActive();
/**
* Get the total number of CQs created. This is a cumulative number.
*
* @return long number of CQs created.
*/
long numCqsCreated();
/**
* Get the total number of closed CQs. This is a cumulative number.
*
* @return long number of CQs closed.
*/
long numCqsClosed();
/**
* Get the number of stopped CQs currently.
*
* @return number of CQs stopped.
*/
long numCqsStopped();
/**
* Get number of CQs that are currently active or stopped. The CQs included in this number are
* either running or stopped (suspended). Closed CQs are not included.
*
* @return long number of CQs on client.
*/
long numCqsOnClient();
/**
* Get number of CQs on the given region. Active CQs and stopped CQs on this region are included
* and closed CQs are not included.
*
* @return long number of CQs on the region.
*/
long numCqsOnRegion(String regionFullPath);
}
| 637 |
6,240 |
<filename>src/com/google/javascript/jscomp/Es6CheckModule.java<gh_stars>1000+
/*
* Copyright 2017 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp;
import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
import com.google.javascript.rhino.Node;
/**
* Checks that ES6 Modules are used correctly, and do not reference undefined keywords or features.
*/
public final class Es6CheckModule extends AbstractPostOrderCallback implements CompilerPass {
static final DiagnosticType ES6_MODULE_REFERENCES_THIS =
DiagnosticType.warning(
"ES6_MODULE_REFERENCES_THIS", "The body of an ES6 module cannot reference 'this'.");
static final DiagnosticType IMPORT_CANNOT_BE_REASSIGNED =
DiagnosticType.error(
"JSC_IMPORT_CANNOT_BE_REASSIGNED", "Assignment to constant variable \"{0}\".");
private final AbstractCompiler compiler;
public Es6CheckModule(AbstractCompiler compiler) {
this.compiler = compiler;
}
@Override
public void process(Node externs, Node root) {
NodeTraversal.traverse(compiler, root, this);
}
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
switch (n.getToken()) {
case THIS:
if (t.inModuleHoistScope()) {
t.report(n, ES6_MODULE_REFERENCES_THIS);
}
break;
case GETPROP:
case GETELEM:
if (NodeUtil.isLValue(n)
&& !NodeUtil.isDeclarationLValue(n)
&& n.getFirstChild().isName()) {
Var var = t.getScope().getVar(n.getFirstChild().getString());
if (var != null) {
Node nameNode = var.getNameNode();
if (nameNode != null && nameNode.isImportStar()) {
// import * as M from '';
// M.x = 2;
compiler.report(JSError.make(n, IMPORT_CANNOT_BE_REASSIGNED, nameNode.getString()));
}
}
}
break;
case NAME:
if (NodeUtil.isLValue(n) && !NodeUtil.isDeclarationLValue(n)) {
Var var = t.getScope().getVar(n.getString());
if (var != null) {
Node nameNode = var.getNameNode();
if (nameNode != null && nameNode != n) {
if (NodeUtil.isImportedName(nameNode)) {
// import { x } from '';
// x = 2;
compiler.report(JSError.make(n, IMPORT_CANNOT_BE_REASSIGNED, nameNode.getString()));
}
}
}
}
break;
default:
break;
}
}
}
| 1,271 |
3,633 |
import pytest
import stanza
from stanza.utils.conll import CoNLL
from stanza.models.common.doc import Document
from stanza.tests import *
pytestmark = [pytest.mark.pipeline, pytest.mark.travis]
# data for testing
EN_DOCS = ["<NAME> was born in Hawaii.", "He was elected president in 2008.", "Obama attended Harvard."]
EXPECTED_ENTS = [[{
"text": "<NAME>",
"type": "PERSON",
"start_char": 0,
"end_char": 12
}, {
"text": "Hawaii",
"type": "GPE",
"start_char": 25,
"end_char": 31
}],
[{
"text": "2008",
"type": "DATE",
"start_char": 28,
"end_char": 32
}],
[{
"text": "Obama",
"type": "PERSON",
"start_char": 0,
"end_char": 5
}, {
"text": "Harvard",
"type": "ORG",
"start_char": 15,
"end_char": 22
}]]
@pytest.fixture(scope="module")
def pipeline():
"""
A reusable pipeline with the NER module
"""
return stanza.Pipeline(dir=TEST_MODELS_DIR, processors="tokenize,ner")
@pytest.fixture(scope="module")
def processed_doc(pipeline):
""" Document created by running full English pipeline on a few sentences """
return [pipeline(text) for text in EN_DOCS]
@pytest.fixture(scope="module")
def processed_bulk(pipeline):
""" Document created by running full English pipeline on a few sentences """
docs = [Document([], text=t) for t in EN_DOCS]
return pipeline(docs)
def check_entities_equal(doc, expected):
"""
Checks that the entities of a doc are equal to the given list of maps
"""
assert len(doc.ents) == len(expected)
for doc_entity, expected_entity in zip(doc.ents, expected):
for k in expected_entity:
assert getattr(doc_entity, k) == expected_entity[k]
def test_bulk_ents(processed_bulk):
assert len(processed_bulk) == len(EXPECTED_ENTS)
for doc, expected in zip(processed_bulk, EXPECTED_ENTS):
check_entities_equal(doc, expected)
def test_ents(processed_doc):
assert len(processed_doc) == len(EXPECTED_ENTS)
for doc, expected in zip(processed_doc, EXPECTED_ENTS):
check_entities_equal(doc, expected)
| 822 |
892 |
{
"schema_version": "1.2.0",
"id": "GHSA-24wf-7vf2-pv59",
"modified": "2021-06-25T13:06:33Z",
"published": "2021-06-28T16:38:29Z",
"aliases": [
"CVE-2021-29620"
],
"summary": "XXE vulnerability on Launch import with externally-defined DTD file",
"details": "### Impact\nStarting from version 3.1.0 we introduced a new feature of JUnit XML launch import. Unfortunately XML parser was not configured properly to prevent XML external entity (XXE) attacks. This allows a user to import a specifically-crafted XML file which imports external Document Type Definition (DTD) file with external entities for extraction of secrets from Report Portal service-api module or server-side request forgery.\n\n### Patches\nFixed with: https://github.com/reportportal/service-api/pull/1392\n\n### Binaries\n`docker pull reportportal/service-api:5.4.0`\nhttps://github.com/reportportal/service-api/packages/846871?version=5.4.0\n\n### For more information\nIf you have any questions or comments about this advisory email us: [<EMAIL>](mailto:<EMAIL>)\n",
"severity": [
{
"type": "CVSS_V3",
"score": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N"
}
],
"affected": [
{
"package": {
"ecosystem": "Maven",
"name": "com.epam.reportportal:service-api"
},
"ranges": [
{
"type": "ECOSYSTEM",
"events": [
{
"introduced": "3.1.0"
},
{
"fixed": "5.4.0"
}
]
}
]
}
],
"references": [
{
"type": "WEB",
"url": "https://github.com/reportportal/reportportal/security/advisories/GHSA-24wf-7vf2-pv59"
},
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29620"
},
{
"type": "WEB",
"url": "https://github.com/reportportal/service-api/pull/1392"
},
{
"type": "WEB",
"url": "https://github.com/reportportal/service-api/commit/a73e0dfb4eda844c37139df1f9847013d55f084e"
},
{
"type": "WEB",
"url": "https://mvnrepository.com/artifact/com.epam.reportportal/service-api"
}
],
"database_specific": {
"cwe_ids": [
"CWE-611"
],
"severity": "HIGH",
"github_reviewed": true
}
}
| 1,070 |
348 |
{"nom":"Saint-Antonin-de-Lacalm","circ":"1ère circonscription","dpt":"Tarn","inscrits":203,"abs":94,"votants":109,"blancs":9,"nuls":5,"exp":95,"res":[{"nuance":"DVD","nom":"<NAME>","voix":62},{"nuance":"FN","nom":"<NAME>","voix":33}]}
| 95 |
778 |
// | / |
// ' / __| _` | __| _ \ __|
// . \ | ( | | ( |\__ `
// _|\_\_| \__,_|\__|\___/ ____/
// Multi-Physics
//
// License: BSD License
// Kratos default license: kratos/license.txt
//
// Main authors: <NAME>, <NAME>
//
//
// External includes
// Project includes
#include "includes/model_part.h"
#include "processes/process.h"
#include "custom_python/add_custom_processes_to_python.h"
#include "includes/kratos_parameters.h"
// Processes
#include "custom_processes/apply_component_table_process.hpp"
#include "custom_processes/dam_fix_temperature_condition_process.hpp"
#include "custom_processes/dam_bofang_condition_temperature_process.hpp"
#include "custom_processes/dam_reservoir_constant_temperature_process.hpp"
#include "custom_processes/dam_reservoir_monitoring_temperature_process.hpp"
#include "custom_processes/dam_hydro_condition_load_process.hpp"
#include "custom_processes/dam_uplift_condition_load_process.hpp"
#include "custom_processes/dam_uplift_circular_condition_load_process.hpp"
#include "custom_processes/dam_westergaard_condition_load_process.hpp"
#include "custom_processes/dam_nodal_young_modulus_process.hpp"
#include "custom_processes/dam_chemo_mechanical_aging_young_process.hpp"
#include "custom_processes/dam_temperature_by_device_process.hpp"
#include "custom_processes/dam_added_mass_condition_process.hpp"
#include "custom_processes/dam_t_sol_air_heat_flux_process.hpp"
#include "custom_processes/dam_noorzai_heat_source_process.hpp"
#include "custom_processes/dam_azenha_heat_source_process.hpp"
#include "custom_processes/dam_nodal_reference_temperature_process.hpp"
#include "custom_processes/dam_grouting_reference_temperature_process.hpp"
namespace Kratos
{
namespace Python
{
void AddCustomProcessesToPython(pybind11::module& m)
{
namespace py = pybind11;
typedef Table<double,double> TableType;
// Apply table values
py::class_<ApplyComponentTableProcessDam, ApplyComponentTableProcessDam::Pointer, Process>
(m, "ApplyComponentTableProcessDam")
.def(py::init < ModelPart&, Parameters>());
// Fix Temperature
py::class_<DamFixTemperatureConditionProcess, DamFixTemperatureConditionProcess::Pointer, Process>
(m, "DamFixTemperatureConditionProcess")
.def(py::init < ModelPart&, Parameters&>());
// Bofang Process
py::class_<DamBofangConditionTemperatureProcess, DamBofangConditionTemperatureProcess::Pointer, Process>
(m, "DamBofangConditionTemperatureProcess")
.def(py::init < ModelPart&, Parameters&>());
// Uniform Reservoir Temperature Process
py::class_<DamReservoirConstantTemperatureProcess, DamReservoirConstantTemperatureProcess::Pointer, Process>
(m, "DamReservoirConstantTemperatureProcess")
.def(py::init < ModelPart&, Parameters&>());
// Uniform Reservoir Temperature Process
py::class_<DamReservoirMonitoringTemperatureProcess, DamReservoirMonitoringTemperatureProcess::Pointer, Process>
(m, "DamReservoirMonitoringTemperatureProcess")
.def(py::init < ModelPart&, Parameters&>());
// Hydrostatic condition
py::class_<DamHydroConditionLoadProcess, DamHydroConditionLoadProcess::Pointer, Process>
(m, "DamHydroConditionLoadProcess")
.def(py::init < ModelPart&, Parameters&>());
// Uplift Condition
py::class_<DamUpliftConditionLoadProcess, DamUpliftConditionLoadProcess::Pointer, Process>
(m, "DamUpliftConditionLoadProcess")
.def(py::init < ModelPart&, Parameters&>());
// Uplift Condition for arch dams
py::class_<DamUpliftCircularConditionLoadProcess, DamUpliftCircularConditionLoadProcess::Pointer, Process>
(m, "DamUpliftCircularConditionLoadProcess")
.def(py::init < ModelPart&, Parameters&>());
// Westergaard Condition (for hydrostatic + hydrodynamic pressure)
py::class_<DamWestergaardConditionLoadProcess, DamWestergaardConditionLoadProcess::Pointer, Process>
(m, "DamWestergaardConditionLoadProcess")
.def(py::init < ModelPart&, Parameters&>());
// Nodal Young Modulus Process
py::class_<DamNodalYoungModulusProcess, DamNodalYoungModulusProcess::Pointer, Process>
(m, "DamNodalYoungModulusProcess")
.def(py::init < ModelPart&, Parameters&>());
// Chemo Mechanical Aging Young Modulus Process
py::class_<DamChemoMechanicalAgingYoungProcess, DamChemoMechanicalAgingYoungProcess::Pointer, Process>
(m, "DamChemoMechanicalAgingYoungProcess")
.def(py::init < ModelPart&, Parameters&>());
// Added Mass Distribution
py::class_<DamAddedMassConditionProcess, DamAddedMassConditionProcess::Pointer, Process>
(m, "DamAddedMassConditionProcess")
.def(py::init < ModelPart&, Parameters&>());
//Temperature by device
py::class_<DamTemperaturebyDeviceProcess, DamTemperaturebyDeviceProcess::Pointer, Process>
(m, "DamTemperaturebyDeviceProcess")
.def(py::init < ModelPart&, Parameters&>());
// Heat Flux by t_sol_air
py::class_<DamTSolAirHeatFluxProcess, DamTSolAirHeatFluxProcess::Pointer, Process>
(m, "DamTSolAirHeatFluxProcess")
.def(py::init < ModelPart&, Parameters&>());
// Heat Source According Noorzai (Adiabatic Hidratation)
py::class_<DamNoorzaiHeatFluxProcess, DamNoorzaiHeatFluxProcess::Pointer, Process>
(m, "DamNoorzaiHeatFluxProcess")
.def(py::init < ModelPart&, Parameters&>());
// Heat Source according Azenha (Arrhenius formulation NonAdiabatic Hidratation)
py::class_<DamAzenhaHeatFluxProcess, DamAzenhaHeatFluxProcess::Pointer, Process>
(m, "DamAzenhaHeatFluxProcess")
.def(py::init < ModelPart&, Parameters&>());
// Nodal Reference Temperature Process
py::class_< DamNodalReferenceTemperatureProcess, DamNodalReferenceTemperatureProcess::Pointer, Process >
(m, "DamNodalReferenceTemperatureProcess")
.def(py::init < ModelPart&, TableType&, Parameters&>());
// Grouting Reference Temperature Process
py::class_< DamGroutingReferenceTemperatureProcess, DamGroutingReferenceTemperatureProcess::Pointer, Process >
(m, "DamGroutingReferenceTemperatureProcess")
.def(py::init < ModelPart&, Parameters&>());
}
} // namespace Python.
} // Namespace Kratos
| 2,151 |
884 |
/*
* Copyright 2014 - 2021 Blazebit.
*
* 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.blazebit.persistence.parser.util;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Calendar;
/**
* @author <NAME>
* @since 1.6.0
*/
public class LocalDateTimeTypeConverter extends TypeUtils.AbstractLiteralFunctionTypeConverter<LocalDateTime> {
public static final TypeConverter<?> INSTANCE = new LocalDateTimeTypeConverter();
private static final long serialVersionUID = 1L;
private LocalDateTimeTypeConverter() {
super("literal_local_date_time");
}
public LocalDateTime convert(Object value) {
if (value == null) {
return null;
}
if (value instanceof java.util.Date) {
java.util.Date date = (java.util.Date) value;
return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
} else if (value instanceof Calendar) {
Calendar calendar = (Calendar) value;
return LocalDateTime.ofInstant(calendar.toInstant(), calendar.getTimeZone().toZoneId());
} else if (value instanceof String) {
return LocalDateTime.ofInstant(java.sql.Timestamp.valueOf((String) value).toInstant(), ZoneId.systemDefault());
}
throw unknownConversion(value, LocalDateTime.class);
}
@Override
public String toString(LocalDateTime value) {
return TypeUtils.jdbcTimestamp(
value.getYear(),
value.getMonthValue(),
value.getDayOfMonth(),
value.getHour(),
value.getMinute(),
value.getSecond(),
value.getNano()
);
}
@Override
public void appendTo(LocalDateTime value, StringBuilder stringBuilder) {
TypeUtils.appendJdbcTimestamp(
stringBuilder,
value.getYear(),
value.getMonthValue(),
value.getDayOfMonth(),
value.getHour(),
value.getMinute(),
value.getSecond(),
value.getNano()
);
}
}
| 1,072 |
348 |
{"nom":"Caracas","circ":"2ème circonscription","dpt":"Français établis hors de France","inscrits":3012,"abs":2694,"votants":318,"blancs":10,"nuls":3,"exp":305,"res":[{"nuance":"REM","nom":"<NAME>","voix":259},{"nuance":"ECO","nom":"M. <NAME>","voix":46}]}
| 99 |
6,098 |
package water.rapids.ast.prims.reducers;
import org.junit.BeforeClass;
import org.junit.Test;
import water.TestUtil;
import water.fvec.Frame;
import water.rapids.Rapids;
import water.rapids.Val;
import water.util.ArrayUtils;
import static org.junit.Assert.assertEquals;
/**
* Test the AstNaCnt.java class
*/
public class AstNaCntTest extends TestUtil {
@BeforeClass
static public void setup() { stall_till_cloudsize(1); }
//--------------------------------------------------------------------------------------------------------------------
// Tests
//--------------------------------------------------------------------------------------------------------------------
@Test public void testAstNaCnt() {
Frame f = null;
try {
f = ArrayUtils.frame(ar("A", "B"), ard(1.0, Double.NaN), ard(2.0, 23.3), ard(3.0, 3.3),
ard(Double.NaN, 3.3));
String x = String.format("(naCnt %s)", f._key);
Val res = Rapids.exec(x); // make the call to count number of NAs in frame
// get frame without any NAs
// assertEquals(f.numRows()-fNew.numRows() ,2); // 2 rows of NAs removed.
double[] naCnts = res.getNums();
double totalNacnts = 0;
for (int index = 0; index < f.numCols(); index++) {
totalNacnts += naCnts[index];
}
assertEquals((int) totalNacnts, 2);
} finally {
if (f != null) f.delete();
}
}
}
| 530 |
381 |
<filename>jgiven-examples/src/test/java/com/tngtech/jgiven/examples/userguide/GivenSomeState.java
package com.tngtech.jgiven.examples.userguide;
// tag::noPackage[]
import com.tngtech.jgiven.Stage;
public class GivenSomeState extends Stage<GivenSomeState> {
public GivenSomeState some_state() {
return self();
}
}
// end::noPackage[]
| 127 |
2,921 |
<gh_stars>1000+
{
"name": "<NAME>",
"type": "BEP20",
"symbol": "BDCC",
"decimals": 18,
"website": "https://www.thebitica.com/",
"description": "Bitica Token (BDCC), created in 2018, it is based on BEP-20 Smart Technology which is owned by Block Beats Company Registered in Estonia (the first country to legalise Cryptocurreny).",
"explorer": "https://bscscan.com/token/<KEY>",
"status": "active",
"id": "<KEY>"
}
| 173 |
353 |
package me.maxdev.popularmoviesapp.ui.detail;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.ColorInt;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.CardView;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.trello.rxlifecycle.components.support.RxFragment;
import java.util.ArrayList;
import java.util.Locale;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
import me.maxdev.popularmoviesapp.PopularMoviesApp;
import me.maxdev.popularmoviesapp.R;
import me.maxdev.popularmoviesapp.api.MovieReviewsResponse;
import me.maxdev.popularmoviesapp.api.MovieVideosResponse;
import me.maxdev.popularmoviesapp.api.TheMovieDbService;
import me.maxdev.popularmoviesapp.data.Movie;
import me.maxdev.popularmoviesapp.data.MovieReview;
import me.maxdev.popularmoviesapp.data.MovieVideo;
import me.maxdev.popularmoviesapp.ui.ItemOffsetDecoration;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
public class MovieDetailFragment extends RxFragment {
private static final String POSTER_IMAGE_BASE_URL = "https://image.tmdb.org/t/p/";
private static final String POSTER_IMAGE_SIZE = "w780";
private static final String ARG_MOVIE = "ArgMovie";
private static final String MOVIE_VIDEOS_KEY = "MovieVideos";
private static final String MOVIE_REVIEWS_KEY = "MovieReviews";
private static final String LOG_TAG = "MovieDetailFragment";
private static final double VOTE_PERFECT = 9.0;
private static final double VOTE_GOOD = 7.0;
private static final double VOTE_NORMAL = 5.0;
@BindView(R.id.image_movie_detail_poster)
ImageView movieImagePoster;
@BindView(R.id.text_movie_original_title)
TextView movieOriginalTitle;
@BindView(R.id.text_movie_user_rating)
TextView movieUserRating;
@BindView(R.id.text_movie_release_date)
TextView movieReleaseDate;
@BindView(R.id.text_movie_overview)
TextView movieOverview;
@BindView(R.id.card_movie_detail)
CardView cardMovieDetail;
@BindView(R.id.card_movie_overview)
CardView cardMovieOverview;
@BindView(R.id.card_movie_videos)
CardView cardMovieVideos;
@BindView(R.id.movie_videos)
RecyclerView movieVideos;
@BindView(R.id.card_movie_reviews)
CardView cardMovieReviews;
@BindView(R.id.movie_reviews)
RecyclerView movieReviews;
@Inject
TheMovieDbService theMovieDbService;
private Movie movie;
private MovieVideosAdapter videosAdapter;
private MovieReviewsAdapter reviewsAdapter;
public MovieDetailFragment() {
// Required empty public constructor
}
public static MovieDetailFragment create(Movie movie) {
MovieDetailFragment fragment = new MovieDetailFragment();
Bundle args = new Bundle();
args.putParcelable(ARG_MOVIE, movie);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
movie = getArguments().getParcelable(ARG_MOVIE);
}
((PopularMoviesApp) getActivity().getApplication()).getNetworkComponent().inject(this);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_movie_detail, container, false);
ButterKnife.bind(this, rootView);
initViews();
initVideosList();
initReviewsList();
setupCardsElevation();
return rootView;
}
@Override
public void onResume() {
super.onResume();
if (videosAdapter.getItemCount() == 0) {
loadMovieVideos();
}
if (reviewsAdapter.getItemCount() == 0) {
loadMovieReviews();
}
updateMovieVideosCard();
updateMovieReviewsCard();
}
private void setupCardsElevation() {
setupCardElevation(cardMovieDetail);
setupCardElevation(cardMovieVideos);
setupCardElevation(cardMovieOverview);
setupCardElevation(cardMovieReviews);
}
private void updateMovieVideosCard() {
if (videosAdapter == null || videosAdapter.getItemCount() == 0) {
cardMovieVideos.setVisibility(View.GONE);
} else {
cardMovieVideos.setVisibility(View.VISIBLE);
}
}
private void updateMovieReviewsCard() {
if (reviewsAdapter == null || reviewsAdapter.getItemCount() == 0) {
cardMovieReviews.setVisibility(View.GONE);
} else {
cardMovieReviews.setVisibility(View.VISIBLE);
}
}
private void setupCardElevation(View view) {
ViewCompat.setElevation(view,
convertDpToPixel(getResources().getInteger(R.integer.movie_detail_content_elevation_in_dp)));
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (videosAdapter.getItemCount() != 0) {
outState.putParcelableArrayList(MOVIE_VIDEOS_KEY, videosAdapter.getMovieVideos());
}
if (reviewsAdapter.getItemCount() != 0) {
outState.putParcelableArrayList(MOVIE_REVIEWS_KEY, reviewsAdapter.getMovieReviews());
}
}
@Override
public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
if (savedInstanceState != null) {
videosAdapter.setMovieVideos(savedInstanceState.getParcelableArrayList(MOVIE_VIDEOS_KEY));
reviewsAdapter.setMovieReviews(savedInstanceState.getParcelableArrayList(MOVIE_REVIEWS_KEY));
}
}
private void loadMovieVideos() {
theMovieDbService.getMovieVideos(movie.getId())
.compose(bindToLifecycle())
.subscribeOn(Schedulers.newThread())
.map(MovieVideosResponse::getResults)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<ArrayList<MovieVideo>>() {
@Override
public void onCompleted() {
// do nothing
}
@Override
public void onError(Throwable e) {
Log.e(LOG_TAG, e.getMessage());
updateMovieVideosCard();
}
@Override
public void onNext(ArrayList<MovieVideo> movieVideos) {
videosAdapter.setMovieVideos(movieVideos);
updateMovieVideosCard();
}
});
}
private void loadMovieReviews() {
theMovieDbService.getMovieReviews(movie.getId())
.compose(bindToLifecycle())
.subscribeOn(Schedulers.newThread())
.map(MovieReviewsResponse::getResults)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<ArrayList<MovieReview>>() {
@Override
public void onCompleted() {
// do nothing
}
@Override
public void onError(Throwable e) {
Log.e(LOG_TAG, e.getMessage());
updateMovieReviewsCard();
}
@Override
public void onNext(ArrayList<MovieReview> movieReviews) {
reviewsAdapter.setMovieReviews(movieReviews);
updateMovieReviewsCard();
}
});
}
private void initViews() {
Glide.with(this)
.load(POSTER_IMAGE_BASE_URL + POSTER_IMAGE_SIZE + movie.getPosterPath())
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(movieImagePoster);
movieOriginalTitle.setText(movie.getOriginalTitle());
movieUserRating.setText(String.format(Locale.US, "%.1f", movie.getAverageVote()));
movieUserRating.setTextColor(getRatingColor(movie.getAverageVote()));
String releaseDate = String.format(getString(me.maxdev.popularmoviesapp.R.string.movie_detail_release_date),
movie.getReleaseDate());
movieReleaseDate.setText(releaseDate);
movieOverview.setText(movie.getOverview());
}
@ColorInt
private int getRatingColor(double averageVote) {
if (averageVote >= VOTE_PERFECT) {
return ContextCompat.getColor(getContext(), R.color.vote_perfect);
} else if (averageVote >= VOTE_GOOD) {
return ContextCompat.getColor(getContext(), R.color.vote_good);
} else if (averageVote >= VOTE_NORMAL) {
return ContextCompat.getColor(getContext(), R.color.vote_normal);
} else {
return ContextCompat.getColor(getContext(), R.color.vote_bad);
}
}
private void initVideosList() {
videosAdapter = new MovieVideosAdapter(getContext());
videosAdapter.setOnItemClickListener((itemView, position) -> onMovieVideoClicked(position));
movieVideos.setAdapter(videosAdapter);
movieVideos.setItemAnimator(new DefaultItemAnimator());
movieVideos.addItemDecoration(new ItemOffsetDecoration(getActivity(), R.dimen.movie_item_offset));
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext(),
LinearLayoutManager.HORIZONTAL, false);
movieVideos.setLayoutManager(layoutManager);
}
private void initReviewsList() {
reviewsAdapter = new MovieReviewsAdapter();
reviewsAdapter.setOnItemClickListener((itemView, position) -> onMovieReviewClicked(position));
movieReviews.setAdapter(reviewsAdapter);
movieReviews.setItemAnimator(new DefaultItemAnimator());
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
movieReviews.setLayoutManager(layoutManager);
}
private void onMovieReviewClicked(int position) {
MovieReview review = reviewsAdapter.getItem(position);
if (review != null && review.getReviewUrl() != null) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(review.getReviewUrl()));
startActivity(intent);
}
}
private void onMovieVideoClicked(int position) {
MovieVideo video = videosAdapter.getItem(position);
if (video != null && video.isYoutubeVideo()) {
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.youtube.com/watch?v=" + video.getKey()));
startActivity(intent);
}
}
public float convertDpToPixel(float dp) {
DisplayMetrics metrics = getResources().getDisplayMetrics();
return dp * ((float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT);
}
}
| 4,926 |
1,144 |
<filename>backend/de.metas.swat/de.metas.swat.base/src/main/java/org/adempiere/process/AD_ColumnCallout_Migrate.java
/**
*
*/
package org.adempiere.process;
/*
* #%L
* de.metas.swat.base
* %%
* Copyright (C) 2015 metas GmbH
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import org.adempiere.exceptions.DBException;
import org.adempiere.model.InterfaceWrapperHelper;
import org.compiere.model.I_AD_ColumnCallout;
import org.compiere.model.Query;
import org.compiere.util.DB;
import de.metas.process.JavaProcess;
/**
* Migrate AD_Column.Callout fields to new approach, by using AD_ColumnCallout table
* @author <NAME>, <EMAIL>
*/
public class AD_ColumnCallout_Migrate extends JavaProcess
{
@Override
protected void prepare()
{
}
@Override
protected String doIt() throws Exception
{
final String sql = "SELECT c.AD_Table_ID, c.AD_Column_ID, t.TableName, c.ColumnName, c.Callout, c.EntityType"
+" FROM AD_Column c"
+" INNER JOIN AD_Table t ON (t.AD_Table_ID=c.AD_Table_ID)"
+" WHERE c.Callout IS NOT NULL"
+" ORDER BY t.TableName, c.ColumnName";
PreparedStatement pstmt = null;
ResultSet rs = null;
int cnt_ok = 0; int cnt_err = 0;
try
{
pstmt = DB.prepareStatement(sql, get_TrxName());
rs = pstmt.executeQuery();
while(rs.next())
{
//final int AD_Table_ID = rs.getInt("AD_Table_ID");
final int AD_Column_ID = rs.getInt("AD_Column_ID");
final String TableName = rs.getString("TableName");
final String ColumnName = rs.getString("ColumnName");
final String Callout = rs.getString("Callout");
final String EntityType = rs.getString("EntityType");
try
{
migrate(AD_Column_ID, Callout, EntityType);
addLog("Migrate "+TableName+"."+ColumnName);
cnt_ok++;
}
catch(Exception e)
{
addLog("Error on "+TableName+"."+ColumnName+": "+e.getLocalizedMessage());
cnt_err++;
}
}
}
catch(SQLException e)
{
throw new DBException(e, sql);
}
finally
{
DB.close(rs, pstmt);
rs = null; pstmt = null;
}
//
return "@Created@ OK="+cnt_ok+" / Error="+cnt_err;
}
private void migrate(int AD_Column_ID, String callouts, String entityType)
{
int seqNo = 10;
for (String classname : toCalloutsList(callouts))
{
I_AD_ColumnCallout cc = getColumnCallout(AD_Column_ID, classname);
if (cc == null)
{
cc = InterfaceWrapperHelper.create(getCtx(), I_AD_ColumnCallout.class, get_TrxName());
cc.setAD_Column_ID(AD_Column_ID);
cc.setClassname(classname);
cc.setEntityType(entityType);
cc.setAD_Org_ID(0);
}
cc.setIsActive(true);
cc.setSeqNo(seqNo);
InterfaceWrapperHelper.save(cc);
seqNo += 10;
}
// // Update AD_Column.Callout
// DB.executeUpdateEx(
// "UPDATE AD_Column SET Callout=NULL, Updated=now(), UpdatedBy=? WHERE AD_Column_ID=?",
// new Object[]{getAD_User_ID(), AD_Column_ID},
// get_TrxName());
}
private List<String> toCalloutsList(String callouts)
{
List<String> list = new ArrayList<String>();
if (callouts == null)
return list;
StringTokenizer st = new StringTokenizer(callouts, ";,", false);
while (st.hasMoreTokens()) // for each callout
{
String classname = st.nextToken().trim();
list.add(classname);
}
return list;
}
private I_AD_ColumnCallout getColumnCallout(int AD_Column_ID, String classname)
{
String whereClause = I_AD_ColumnCallout.COLUMNNAME_AD_Column_ID+"=?"
+" AND "+I_AD_ColumnCallout.COLUMNNAME_Classname+"=?"
+" AND "+I_AD_ColumnCallout.COLUMNNAME_AD_Client_ID+"=0"
+" AND "+I_AD_ColumnCallout.COLUMNNAME_AD_Org_ID+"=0";
return new Query(getCtx(), I_AD_ColumnCallout.Table_Name, whereClause, get_TrxName())
.setParameters(AD_Column_ID, classname)
.firstOnly(I_AD_ColumnCallout.class);
}
}
| 1,806 |
411 |
<reponame>sumau/tick
# License: BSD 3 clause
import pickle
import unittest
import numpy as np
from tick.base import TimeFunction
from tick.hawkes import (HawkesKernel0, HawkesKernelExp, HawkesKernelSumExp,
HawkesKernelPowerLaw, HawkesKernelTimeFunc)
class Test(unittest.TestCase):
def setUp(self):
self.random_times = np.random.rand(10)
def test_HawkesKernel0_pickle(self):
"""...Test pickling ability of HawkesKernel0
"""
obj = HawkesKernel0()
pickled = pickle.loads(pickle.dumps(obj))
self.assertTrue(str(obj) == str(pickled))
self.assertEqual(obj.get_support(), pickled.get_support())
np.testing.assert_array_equal(
obj.get_values(self.random_times),
obj.get_values(self.random_times))
def test_HawkesKernelExp_pickle(self):
"""...Test pickling ability of HawkesKernelExp
"""
obj = HawkesKernelExp(decay=2, intensity=3)
pickled = pickle.loads(pickle.dumps(obj))
self.assertTrue(str(obj) == str(pickled))
self.assertEqual(obj.decay, pickled.decay)
self.assertEqual(obj.intensity, pickled.intensity)
np.testing.assert_array_equal(
obj.get_values(self.random_times),
obj.get_values(self.random_times))
def test_HawkesKernelSumExp_pickle(self):
"""...Test pickling ability of HawkesKernelSumExp
"""
obj = HawkesKernelSumExp(
decays=np.arange(1., 2., 0.2), intensities=np.arange(0.3, 2.3, .4))
pickled = pickle.loads(pickle.dumps(obj))
self.assertTrue(str(obj) == str(pickled))
self.assertTrue(np.array_equal(obj.decays, pickled.decays))
self.assertTrue(np.array_equal(obj.intensities, pickled.intensities))
np.testing.assert_array_equal(
obj.get_values(self.random_times),
obj.get_values(self.random_times))
def test_HawkesKernelPowerLaw_pickle(self):
"""...Test pickling ability of HawkesKernelPowerLaw
"""
obj = HawkesKernelPowerLaw(0.1, 0.01, 1.2)
pickled = pickle.loads(pickle.dumps(obj))
self.assertTrue(str(obj) == str(pickled))
np.testing.assert_array_equal(
obj.get_values(self.random_times),
obj.get_values(self.random_times))
def test_HawkesKernelTimeFunc_pickle(self):
"""...Test pickling ability of HawkesKernelTimeFunc
"""
size = 10
y_values = np.random.rand(size)
t_values = np.arange(size, dtype=float)
time_function = TimeFunction([t_values, y_values])
obj = HawkesKernelTimeFunc(time_function)
pickled = pickle.loads(pickle.dumps(obj))
self.assertEqual(
obj.time_function.value(1), pickled.time_function.value(1))
self.assertEqual(
obj.time_function.value(2), pickled.time_function.value(2))
self.assertEqual(
obj.time_function.value(1.5), pickled.time_function.value(1.5))
self.assertEqual(
obj.time_function.value(0.75), pickled.time_function.value(0.75))
np.testing.assert_array_equal(
obj.get_values(self.random_times),
obj.get_values(self.random_times))
if __name__ == "__main__":
unittest.main()
| 1,529 |
923 |
<gh_stars>100-1000
package core.config;
import java.util.logging.Logger;
import argo.jdom.JsonRootNode;
public class Parser1_0 extends ConfigParser {
private static final Logger LOGGER = Logger.getLogger(Parser1_0.class.getName());
@Override
protected String getVersion() {
return "1.0";
}
@Override
protected String getPreviousVersion() {
return null;
}
@Override
protected JsonRootNode internalConvertFromPreviousVersion(JsonRootNode previousVersion) {
return previousVersion;
}
@Override
protected boolean internalImportData(Config config, JsonRootNode data) {
LOGGER.warning("Unsupported import data at version " + getVersion());
return false;
}
}
| 215 |
310 |
<filename>research/compression/entropy_coder/dataset/synthetic_model.py
# Copyright 2016 The TensorFlow Authors All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Binary code sample generator."""
import numpy as np
_CRC_LINE = [
[0, 1, 0],
[1, 1, 0],
[1, 0, 0]
]
_CRC_DEPTH = [1, 1, 0, 1]
def ComputeLineCrc(code, width, y, x, d):
crc = 0
for dy in xrange(len(_CRC_LINE)):
i = y - 1 - dy
if i < 0:
continue
for dx in xrange(len(_CRC_LINE[dy])):
j = x - 2 + dx
if j < 0 or j >= width:
continue
crc += 1 if (code[i, j, d] != _CRC_LINE[dy][dx]) else 0
return crc
def ComputeDepthCrc(code, y, x, d):
crc = 0
for delta in xrange(len(_CRC_DEPTH)):
k = d - 1 - delta
if k < 0:
continue
crc += 1 if (code[y, x, k] != _CRC_DEPTH[delta]) else 0
return crc
def GenerateSingleCode(code_shape):
code = np.zeros(code_shape, dtype=np.int)
keep_value_proba = 0.8
height = code_shape[0]
width = code_shape[1]
depth = code_shape[2]
for d in xrange(depth):
for y in xrange(height):
for x in xrange(width):
v1 = ComputeLineCrc(code, width, y, x, d)
v2 = ComputeDepthCrc(code, y, x, d)
v = 1 if (v1 + v2 >= 6) else 0
if np.random.rand() < keep_value_proba:
code[y, x, d] = v
else:
code[y, x, d] = 1 - v
return code
| 795 |
416 |
/*
* Please do not edit this file.
* It was generated using rpcgen.
*/
#ifndef _MOUNT_H_RPCGEN
#define _MOUNT_H_RPCGEN
#define RPCGEN_VERSION 199506
#include <rpc/rpc.h>
#define MNTPATHLEN 1024
#define MNTNAMLEN 255
#define FHSIZE 32
typedef char fhandle[FHSIZE];
#ifdef __cplusplus
extern "C" bool_t xdr_fhandle(XDR *, fhandle);
#elif __STDC__
extern bool_t xdr_fhandle(XDR *, fhandle);
#else /* Old Style C */
bool_t xdr_fhandle();
#endif /* Old Style C */
struct fhstatus {
u_int fhs_status;
union {
fhandle fhs_fhandle;
} fhstatus_u;
};
typedef struct fhstatus fhstatus;
#ifdef __cplusplus
extern "C" bool_t xdr_fhstatus(XDR *, fhstatus*);
#elif __STDC__
extern bool_t xdr_fhstatus(XDR *, fhstatus*);
#else /* Old Style C */
bool_t xdr_fhstatus();
#endif /* Old Style C */
typedef char *dirpath;
#ifdef __cplusplus
extern "C" bool_t xdr_dirpath(XDR *, dirpath*);
#elif __STDC__
extern bool_t xdr_dirpath(XDR *, dirpath*);
#else /* Old Style C */
bool_t xdr_dirpath();
#endif /* Old Style C */
typedef char *name;
#ifdef __cplusplus
extern "C" bool_t xdr_name(XDR *, name*);
#elif __STDC__
extern bool_t xdr_name(XDR *, name*);
#else /* Old Style C */
bool_t xdr_name();
#endif /* Old Style C */
typedef struct mountbody *mountlist;
#ifdef __cplusplus
extern "C" bool_t xdr_mountlist(XDR *, mountlist*);
#elif __STDC__
extern bool_t xdr_mountlist(XDR *, mountlist*);
#else /* Old Style C */
bool_t xdr_mountlist();
#endif /* Old Style C */
struct mountbody {
name ml_hostname;
dirpath ml_directory;
mountlist ml_next;
};
typedef struct mountbody mountbody;
#ifdef __cplusplus
extern "C" bool_t xdr_mountbody(XDR *, mountbody*);
#elif __STDC__
extern bool_t xdr_mountbody(XDR *, mountbody*);
#else /* Old Style C */
bool_t xdr_mountbody();
#endif /* Old Style C */
typedef struct groupnode *groups;
#ifdef __cplusplus
extern "C" bool_t xdr_groups(XDR *, groups*);
#elif __STDC__
extern bool_t xdr_groups(XDR *, groups*);
#else /* Old Style C */
bool_t xdr_groups();
#endif /* Old Style C */
struct groupnode {
name gr_name;
groups gr_next;
};
typedef struct groupnode groupnode;
#ifdef __cplusplus
extern "C" bool_t xdr_groupnode(XDR *, groupnode*);
#elif __STDC__
extern bool_t xdr_groupnode(XDR *, groupnode*);
#else /* Old Style C */
bool_t xdr_groupnode();
#endif /* Old Style C */
typedef struct exportnode *exports;
#ifdef __cplusplus
extern "C" bool_t xdr_exports(XDR *, exports*);
#elif __STDC__
extern bool_t xdr_exports(XDR *, exports*);
#else /* Old Style C */
bool_t xdr_exports();
#endif /* Old Style C */
struct exportnode {
dirpath ex_dir;
groups ex_groups;
exports ex_next;
};
typedef struct exportnode exportnode;
#ifdef __cplusplus
extern "C" bool_t xdr_exportnode(XDR *, exportnode*);
#elif __STDC__
extern bool_t xdr_exportnode(XDR *, exportnode*);
#else /* Old Style C */
bool_t xdr_exportnode();
#endif /* Old Style C */
#define MOUNTPROG ((rpc_uint)100005)
#define MOUNTVERS ((rpc_uint)1)
#ifdef __cplusplus
#define MOUNTPROC_NULL ((rpc_uint)0)
extern "C" void * mountproc_null_1(void *, CLIENT *);
extern "C" void * mountproc_null_1_svc(void *, struct svc_req *);
#define MOUNTPROC_MNT ((rpc_uint)1)
extern "C" fhstatus * mountproc_mnt_1(dirpath *, CLIENT *);
extern "C" fhstatus * mountproc_mnt_1_svc(dirpath *, struct svc_req *);
#define MOUNTPROC_DUMP ((rpc_uint)2)
extern "C" mountlist * mountproc_dump_1(void *, CLIENT *);
extern "C" mountlist * mountproc_dump_1_svc(void *, struct svc_req *);
#define MOUNTPROC_UMNT ((rpc_uint)3)
extern "C" void * mountproc_umnt_1(dirpath *, CLIENT *);
extern "C" void * mountproc_umnt_1_svc(dirpath *, struct svc_req *);
#define MOUNTPROC_UMNTALL ((rpc_uint)4)
extern "C" void * mountproc_umntall_1(void *, CLIENT *);
extern "C" void * mountproc_umntall_1_svc(void *, struct svc_req *);
#define MOUNTPROC_EXPORT ((rpc_uint)5)
extern "C" exports * mountproc_export_1(void *, CLIENT *);
extern "C" exports * mountproc_export_1_svc(void *, struct svc_req *);
#define MOUNTPROC_EXPORTALL ((rpc_uint)6)
extern "C" exports * mountproc_exportall_1(void *, CLIENT *);
extern "C" exports * mountproc_exportall_1_svc(void *, struct svc_req *);
#elif __STDC__
#define MOUNTPROC_NULL ((rpc_uint)0)
extern void * mountproc_null_1(void *, CLIENT *);
extern void * mountproc_null_1_svc(void *, struct svc_req *);
#define MOUNTPROC_MNT ((rpc_uint)1)
extern fhstatus * mountproc_mnt_1(dirpath *, CLIENT *);
extern fhstatus * mountproc_mnt_1_svc(dirpath *, struct svc_req *);
#define MOUNTPROC_DUMP ((rpc_uint)2)
extern mountlist * mountproc_dump_1(void *, CLIENT *);
extern mountlist * mountproc_dump_1_svc(void *, struct svc_req *);
#define MOUNTPROC_UMNT ((rpc_uint)3)
extern void * mountproc_umnt_1(dirpath *, CLIENT *);
extern void * mountproc_umnt_1_svc(dirpath *, struct svc_req *);
#define MOUNTPROC_UMNTALL ((rpc_uint)4)
extern void * mountproc_umntall_1(void *, CLIENT *);
extern void * mountproc_umntall_1_svc(void *, struct svc_req *);
#define MOUNTPROC_EXPORT ((rpc_uint)5)
extern exports * mountproc_export_1(void *, CLIENT *);
extern exports * mountproc_export_1_svc(void *, struct svc_req *);
#define MOUNTPROC_EXPORTALL ((rpc_uint)6)
extern exports * mountproc_exportall_1(void *, CLIENT *);
extern exports * mountproc_exportall_1_svc(void *, struct svc_req *);
#else /* Old Style C */
#define MOUNTPROC_NULL ((rpc_uint)0)
extern void * mountproc_null_1();
extern void * mountproc_null_1_svc();
#define MOUNTPROC_MNT ((rpc_uint)1)
extern fhstatus * mountproc_mnt_1();
extern fhstatus * mountproc_mnt_1_svc();
#define MOUNTPROC_DUMP ((rpc_uint)2)
extern mountlist * mountproc_dump_1();
extern mountlist * mountproc_dump_1_svc();
#define MOUNTPROC_UMNT ((rpc_uint)3)
extern void * mountproc_umnt_1();
extern void * mountproc_umnt_1_svc();
#define MOUNTPROC_UMNTALL ((rpc_uint)4)
extern void * mountproc_umntall_1();
extern void * mountproc_umntall_1_svc();
#define MOUNTPROC_EXPORT ((rpc_uint)5)
extern exports * mountproc_export_1();
extern exports * mountproc_export_1_svc();
#define MOUNTPROC_EXPORTALL ((rpc_uint)6)
extern exports * mountproc_exportall_1();
extern exports * mountproc_exportall_1_svc();
#endif /* Old Style C */
#endif /* !_MOUNT_H_RPCGEN */
| 2,570 |
2,294 |
<filename>tutorials/W2D3_BiologicalNeuronModels/solutions/W2D3_Tutorial1_Solution_eba2370f.py
"""
If we use a DC input, the F-I curve is deterministic, and we can
found its shape by solving the membrane equation of the neuron. If we have GWN,
as we increase the sigma, the F-I curve has a more linear shape, and the neuron
reaches its threshold using less average injected current.
"""
| 117 |
4,403 |
<filename>hutool-core/src/test/java/cn/hutool/core/clone/CloneTest.java
package cn.hutool.core.clone;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.junit.Assert;
import org.junit.Test;
/**
* 克隆单元测试
* @author Looly
*
*/
public class CloneTest {
@Test
public void cloneTest(){
//实现Cloneable接口
Cat cat = new Cat();
Cat cat2 = cat.clone();
Assert.assertEquals(cat, cat2);
}
@Test
public void cloneTest2(){
//继承CloneSupport类
Dog dog = new Dog();
Dog dog2 = dog.clone();
Assert.assertEquals(dog, dog2);
}
//------------------------------------------------------------------------------- private Class for test
/**
* 猫猫类,使用实现Cloneable方式
* @author Looly
*
*/
@Data
static class Cat implements Cloneable<Cat>{
private String name = "miaomiao";
private int age = 2;
@Override
public Cat clone() {
try {
return (Cat) super.clone();
} catch (CloneNotSupportedException e) {
throw new CloneRuntimeException(e);
}
}
}
/**
* 狗狗类,用于继承CloneSupport类
* @author Looly
*
*/
@EqualsAndHashCode(callSuper = false)
@Data
static class Dog extends CloneSupport<Dog>{
private String name = "wangwang";
private int age = 3;
}
}
| 514 |
354 |
<reponame>muehleisen/OpenStudio<filename>src/energyplus/Test/AirLoopHVAC_GTest.cpp
/***********************************************************************************************************************
* OpenStudio(R), Copyright (c) 2008-2021, Alliance for Sustainable Energy, LLC, and other contributors. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following
* disclaimer.
*
* (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the distribution.
*
* (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products
* derived from this software without specific prior written permission from the respective party.
*
* (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works
* may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior
* written permission from Alliance for Sustainable Energy, LLC.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED
* STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, 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 <gtest/gtest.h>
#include "EnergyPlusFixture.hpp"
#include "../ForwardTranslator.hpp"
#include "../../model/AirLoopHVAC.hpp"
#include "../../model/AirLoopHVAC_Impl.hpp"
#include "../../model/Model.hpp"
#include "../../model/AvailabilityManagerAssignmentList.hpp"
#include "../../model/AvailabilityManagerAssignmentList_Impl.hpp"
#include "../../model/AvailabilityManagerScheduledOn.hpp"
#include "../../model/Node.hpp"
#include "../../model/Schedule.hpp"
#include "../../model/ScheduleCompact.hpp"
#include "../../model/FanVariableVolume.hpp"
#include "../../model/FanConstantVolume.hpp"
#include "../../model/AirTerminalSingleDuctSeriesPIUReheat.hpp"
#include "../../model/AirTerminalSingleDuctConstantVolumeNoReheat.hpp"
#include "../../model/CoilHeatingElectric.hpp"
#include "../../model/DesignSpecificationOutdoorAir.hpp"
#include "../../model/Space.hpp"
#include "../../model/ThermalZone.hpp"
#include "../../model/ThermalZone_Impl.hpp"
#include "../../model/AirLoopHVACOutdoorAirSystem.hpp"
#include "../../model/ControllerOutdoorAir.hpp"
#include "../../model/ControllerMechanicalVentilation.hpp"
#include "../../model/DesignDay.hpp"
#include "../../model/SetpointManagerSingleZoneHumidityMinimum.hpp"
#include "../../model/SetpointManagerScheduled.hpp"
#include "../../model/HumidifierSteamElectric.hpp"
#include "../../model/ScheduleConstant.hpp"
#include "../../utilities/geometry/Point3d.hpp"
#include <utilities/idd/AirLoopHVAC_FieldEnums.hxx>
#include <utilities/idd/AvailabilityManagerAssignmentList_FieldEnums.hxx>
#include <utilities/idd/Fan_ConstantVolume_FieldEnums.hxx>
#include <utilities/idd/Fan_VariableVolume_FieldEnums.hxx>
#include <utilities/idd/AirTerminal_SingleDuct_SeriesPIU_Reheat_FieldEnums.hxx>
#include <utilities/idd/Controller_MechanicalVentilation_FieldEnums.hxx>
#include <utilities/idd/SetpointManager_Scheduled_FieldEnums.hxx>
#include <utilities/idd/SetpointManager_MixedAir_FieldEnums.hxx>
#include <utilities/idd/SetpointManager_SingleZone_Humidity_Minimum_FieldEnums.hxx>
#include <utilities/idd/IddEnums.hxx>
#include "../../utilities/idf/IdfExtensibleGroup.hpp"
#include "../../utilities/core/Logger.hpp"
#include "utilities/core/Compare.hpp"
using namespace openstudio::energyplus;
using namespace openstudio::model;
using namespace openstudio;
Model createModelWithDummyAirLoop() {
// Generate the example Model
Model m = openstudio::model::exampleModel();
// Remove the existing loop
AirLoopHVAC example_loop = m.getModelObjects<AirLoopHVAC>()[0];
example_loop.remove();
AirLoopHVAC a(m);
FanVariableVolume fan(m);
Node outletNode = a.supplyOutletNode();
fan.addToNode(outletNode);
fan.setName("AirLoopHVAC Supply Fan");
ScheduleCompact hvac_op_sch(m);
hvac_op_sch.setName("HVAC Operation Schedule");
a.setAvailabilitySchedule(hvac_op_sch);
FanConstantVolume piu_fan(m);
piu_fan.setName("ATU PIU Fan");
CoilHeatingElectric reheatC(m);
reheatC.setName("ATU PIU Reheat Coil");
AirTerminalSingleDuctSeriesPIUReheat piu(m, piu_fan, reheatC);
// Get the single thermal Zone in the model
ThermalZone z = m.getModelObjects<ThermalZone>()[0];
a.addBranchForZone(z, piu);
return m;
}
bool checkAvailabilityManagerList(Workspace w, std::vector<std::string> avm_types) {
// Get AVM list (only one should be present)
WorkspaceObjectVector idfObjs(w.getObjectsByType(IddObjectType::AvailabilityManagerAssignmentList));
if (idfObjs.size() != 1u) {
std::cout << "Expected one AVMList, got " << idfObjs.size() << '\n';
return false;
}
WorkspaceObject idf_avm(idfObjs[0]);
// The avm_types should have the same size as the extensible groups to begin with
if (avm_types.size() != idf_avm.extensibleGroups().size()) {
return false;
}
for (std::size_t i = 0; i != avm_types.size(); ++i) {
IdfExtensibleGroup eg = idf_avm.extensibleGroups()[i];
std::string s = eg.getString(AvailabilityManagerAssignmentListExtensibleFields::AvailabilityManagerObjectType).get();
if (avm_types[i] != s) {
std::cout << "AVM type not matching: expected '" << avm_types[i] << "' and got '" << s << '\n';
return false;
}
}
return true;
}
bool CheckFanSchedules(Workspace w) {
boost::optional<WorkspaceObject> _wo;
// Loop availabilitySchedule ends up on the Fan
_wo = w.getObjectByTypeAndName(IddObjectType::Fan_VariableVolume, "AirLoopHVAC Supply Fan");
if (!_wo.is_initialized()) {
std::cout << "Cannot locate a Fan:VariableVolume named 'AirLoopHVAC Supply Fan'" << '\n';
return false;
}
WorkspaceObject idf_a_fan = _wo.get();
std::string idf_a_fan_avail = idf_a_fan.getString(Fan_VariableVolumeFields::AvailabilityScheduleName).get();
if ("HVAC Operation Schedule" != idf_a_fan_avail) {
std::cout << "AirLoop Fan Availability Schedule Name was expected to be 'HVAC Operation Schedule', instead it is " << idf_a_fan_avail << '\n';
return false;
}
// And on the PIU Fan too
_wo = w.getObjectByTypeAndName(IddObjectType::Fan_ConstantVolume, "ATU PIU Fan");
std::string idf__fan_name = idf_a_fan.getString(Fan_ConstantVolumeFields::AvailabilityScheduleName).get();
if (!_wo.is_initialized()) {
std::cout << "Cannot locate a Fan:ConstantVolume named 'ATU PIU Fan'" << '\n';
return false;
}
WorkspaceObject idf_piu_fan = _wo.get();
std::string idf_piu_fan_avail = idf_piu_fan.getString(Fan_ConstantVolumeFields::AvailabilityScheduleName).get();
if ("HVAC Operation Schedule" != idf_piu_fan_avail) {
std::cout << "PIU Fan Availability Schedule Name was expected to be 'HVAC Operation Schedule', instead it is " << idf_piu_fan_avail << '\n';
return false;
}
return true;
}
TEST_F(EnergyPlusFixture, ForwardTranslator_AirLoopHVAC_AvailabilityManagers_None) {
Model m = createModelWithDummyAirLoop();
// Add new AVMs
// Not for this case
// ForwardTranslate
ForwardTranslator forwardTranslator;
Workspace w = forwardTranslator.translateModel(m);
// There should only be an AVM:Scheduled (auto created)
std::vector<std::string> avm_types;
avm_types.push_back("AvailabilityManager:Scheduled");
ASSERT_TRUE(checkAvailabilityManagerList(w, avm_types));
// Check that the loop availability schedule ended up in the Fan Schedules
ASSERT_TRUE(CheckFanSchedules(w));
// m.save(toPath("./AirLoopHVAC_AVM_None.osm"), true);
// w.save(toPath("./AirLoopHVAC_AVM_None.idf"), true);
}
TEST_F(EnergyPlusFixture, ForwardTranslator_AirLoopHVAC_AvailabilityManagers_NightCycle) {
Model m = createModelWithDummyAirLoop();
// Add new AVMs
AirLoopHVAC a = m.getModelObjects<AirLoopHVAC>()[0];
// This triggers creation of an AVM:NightCycle
a.setNightCycleControlType("CycleOnAny");
// ForwardTranslate
ForwardTranslator forwardTranslator;
Workspace w = forwardTranslator.translateModel(m);
// There should only be an AVM:Scheduled (auto created)
std::vector<std::string> avm_types;
avm_types.push_back("AvailabilityManager:NightCycle");
ASSERT_TRUE(checkAvailabilityManagerList(w, avm_types));
// Check that the loop availability schedule ended up in the Fan Schedules
ASSERT_TRUE(CheckFanSchedules(w));
// m.save(toPath("./AirLoopHVAC_AVM_NightCycle.osm"), true);
// w.save(toPath("./AirLoopHVAC_AVM_NightCycle.idf"), true);
}
TEST_F(EnergyPlusFixture, ForwardTranslator_AirLoopHVAC_AvailabilityManagers_ScheduledOn) {
Model m = createModelWithDummyAirLoop();
// Add new AVMs
AirLoopHVAC a = m.getModelObjects<AirLoopHVAC>()[0];
AvailabilityManagerScheduledOn avm_schOn(m);
a.addAvailabilityManager(avm_schOn);
// ForwardTranslate
ForwardTranslator forwardTranslator;
Workspace w = forwardTranslator.translateModel(m);
// There should only be an AVM:Scheduled (auto created)
std::vector<std::string> avm_types;
avm_types.push_back("AvailabilityManager:ScheduledOn");
ASSERT_TRUE(checkAvailabilityManagerList(w, avm_types));
// Check that the loop availability schedule ended up in the Fan Schedules
ASSERT_TRUE(CheckFanSchedules(w));
// m.save(toPath("./AirLoopHVAC_AVM_ScheduledOn.osm"), true);
// w.save(toPath("./AirLoopHVAC_AVM_ScheduledOn.idf"), true);
}
TEST_F(EnergyPlusFixture, ForwardTranslator_AirLoopHVAC_AvailabilityManagers_NightCycle_ScheduledOn) {
Model m = createModelWithDummyAirLoop();
// Add new AVMs
AirLoopHVAC a = m.getModelObjects<AirLoopHVAC>()[0];
// This triggers creation of an AVM:NightCycle
a.setNightCycleControlType("CycleOnAny");
// Add an AVM:ScheduledOn
AvailabilityManagerScheduledOn avm_schOn(m);
a.addAvailabilityManager(avm_schOn);
// Not for this case
// ForwardTranslate
ForwardTranslator forwardTranslator;
Workspace w = forwardTranslator.translateModel(m);
// There should only be an AVM:Scheduled (auto created)
std::vector<std::string> avm_types;
avm_types.push_back("AvailabilityManager:NightCycle");
avm_types.push_back("AvailabilityManager:ScheduledOn");
ASSERT_TRUE(checkAvailabilityManagerList(w, avm_types));
// Check that the loop availability schedule ended up in the Fan Schedules
ASSERT_TRUE(CheckFanSchedules(w));
// m.save(toPath("./AirLoopHVAC_AVM_NightCycle_ScheduledOn.osm"), true);
// w.save(toPath("./AirLoopHVAC_AVM_NightCycle_ScheduledOn.idf"), true);
}
TEST_F(EnergyPlusFixture, ForwardTranslator_AirLoopHVAC_MultiLoop_ControllerMV) {
// Test for #3926
Model m;
ThermalZone z(m);
Space s(m);
DesignSpecificationOutdoorAir dsoa(m);
EXPECT_TRUE(dsoa.setOutdoorAirMethod("Sum"));
EXPECT_TRUE(dsoa.setOutdoorAirFlowAirChangesperHour(0.5));
EXPECT_TRUE(s.setThermalZone(z));
EXPECT_TRUE(s.setDesignSpecificationOutdoorAir(dsoa));
// Absolutely need a sizing period for the Sizing:Zone to be translated
DesignDay d(m);
Schedule alwaysOn = m.alwaysOnDiscreteSchedule();
AirLoopHVAC a1(m);
ControllerOutdoorAir controller_oa1(m);
AirLoopHVACOutdoorAirSystem oa_sys1(m, controller_oa1);
Node supplyInletNode1 = a1.supplyInletNode();
EXPECT_TRUE(oa_sys1.addToNode(supplyInletNode1));
AirTerminalSingleDuctConstantVolumeNoReheat atu1(m, alwaysOn);
EXPECT_TRUE(a1.multiAddBranchForZone(z, atu1));
AirLoopHVAC a2(m);
ControllerOutdoorAir controller_oa2(m);
AirLoopHVACOutdoorAirSystem oa_sys2(m, controller_oa2);
Node supplyInletNode2 = a2.supplyInletNode();
EXPECT_TRUE(oa_sys2.addToNode(supplyInletNode2));
AirTerminalSingleDuctConstantVolumeNoReheat atu2(m, alwaysOn);
EXPECT_TRUE(a2.multiAddBranchForZone(z, atu2));
EXPECT_EQ(2u, z.airLoopHVACs().size());
ForwardTranslator ft;
Workspace w = ft.translateModel(m);
WorkspaceObjectVector idf_controller_mvs(w.getObjectsByType(IddObjectType::Controller_MechanicalVentilation));
ASSERT_EQ(2u, idf_controller_mvs.size());
int i = 1;
for (const auto& idf_controller_mv : idf_controller_mvs) {
// This construct is weird but I want to showcase that it works fine for the first ControllerMV but not the second one
// so I don't want to use ASSERT_EQ
if (idf_controller_mv.numExtensibleGroups() == 1u) {
IdfExtensibleGroup w_eg = idf_controller_mv.extensibleGroups()[0];
EXPECT_EQ(z.nameString(), w_eg.getString(Controller_MechanicalVentilationExtensibleFields::ZoneorZoneListName).get());
EXPECT_EQ(dsoa.nameString(), w_eg.getString(Controller_MechanicalVentilationExtensibleFields::DesignSpecificationOutdoorAirObjectName).get());
} else {
EXPECT_EQ(1u, idf_controller_mv.numExtensibleGroups()) << "Failed for " << idf_controller_mv.nameString() << "(i = " << i << ")";
}
++i;
}
}
TEST_F(EnergyPlusFixture, ForwardTranslator_AirLoopHVAC_designReturnAirFlowFractionofSupplyAirFlow) {
ForwardTranslator ft;
Model m;
AirLoopHVAC a(m);
// Test Ctor value (E+ IDD default)
EXPECT_TRUE(a.setDesignReturnAirFlowFractionofSupplyAirFlow(0.5));
EXPECT_EQ(0.5, a.designReturnAirFlowFractionofSupplyAirFlow());
Workspace w = ft.translateModel(m);
// Get AVM list (only one should be present)
WorkspaceObjectVector idfObjs(w.getObjectsByType(IddObjectType::AirLoopHVAC));
ASSERT_EQ(1u, idfObjs.size());
WorkspaceObject idf_loop(idfObjs[0]);
EXPECT_EQ(0.5, idf_loop.getDouble(AirLoopHVACFields::DesignReturnAirFlowFractionofSupplyAirFlow).get());
}
TEST_F(EnergyPlusFixture, ForwardTranslator_AirLoopHVAC_Automatic_SPMs) {
Model m;
// Makes an AirLoopHVAC with:
// o o
// | |
// ---- OA SYS ----o---HC----o----Fan----o-----Humidifier------
// | |
// o o < SPM:Scheduled, and SPM:SingleZone:HumidityMinimum
AirLoopHVAC a(m);
ThermalZone z(m);
auto alwaysOn = m.alwaysOnDiscreteSchedule();
AirTerminalSingleDuctConstantVolumeNoReheat atu(m, alwaysOn);
a.addBranchForZone(z, atu);
Node supplyOutletNode = a.supplyOutletNode();
ControllerOutdoorAir oaController(m);
AirLoopHVACOutdoorAirSystem oaSystem(m, oaController);
oaSystem.addToNode(supplyOutletNode);
CoilHeatingElectric hc(m);
hc.addToNode(supplyOutletNode);
hc.setName("Heating Coil");
FanVariableVolume fan(m);
fan.setName("AirLoopHVAC Supply Fan");
EXPECT_TRUE(fan.addToNode(supplyOutletNode));
HumidifierSteamElectric humidifier(m);
humidifier.setName("Humidifier");
EXPECT_TRUE(humidifier.addToNode(supplyOutletNode));
ScheduleConstant sch(m);
sch.setName("SPM schedule");
sch.setValue(15);
SetpointManagerScheduled spm_scheduled(m, sch);
spm_scheduled.setName("SPM Scheduled");
EXPECT_TRUE(spm_scheduled.addToNode(supplyOutletNode));
SetpointManagerSingleZoneHumidityMinimum spm_hum_min(m);
spm_hum_min.setName("SPM SZ Min Hum");
EXPECT_TRUE(spm_hum_min.addToNode(supplyOutletNode));
// This should be done automatically in addToNode since the zone was hooked already
EXPECT_TRUE(spm_hum_min.setControlZone(z));
a.supplyInletNode().setName("Supply Inlet Node");
a.mixedAirNode()->setName("Mixed Air Node");
hc.outletModelObject()->setName("Coil to Fan Node");
fan.outletModelObject()->setName("Fan to Humidifier Node");
supplyOutletNode.setName("Supply Outlet Node");
z.zoneAirNode().setName("Zone Air Node");
// Add new AVMs
// Not for this case
// ForwardTranslate
ForwardTranslator ft;
Workspace w = ft.translateModel(m);
// What I expect in terms of SPMs
//
// o o SPM:MixedAir SPM Scheduled (cloned)
// | | v v v
// ---- OA SYS ----o---HC----o----Fan----o-----Humidifier------
// | |
// o o < SPM:Scheduled, and SPM:SingleZone:HumidityMinimum
{
auto idf_spm_scheduleds = w.getObjectsByType(IddObjectType::SetpointManager_Scheduled);
ASSERT_EQ(2u, idf_spm_scheduleds.size());
bool foundSupplyOutlet = false;
bool foundFanToHumidifierNode = false;
for (auto spm : idf_spm_scheduleds) {
EXPECT_EQ("Temperature", spm.getString(SetpointManager_ScheduledFields::ControlVariable).get());
EXPECT_EQ("SPM schedule", spm.getString(SetpointManager_ScheduledFields::ScheduleName).get());
auto spm_node = spm.getString(SetpointManager_ScheduledFields::SetpointNodeorNodeListName).get();
if (openstudio::istringEqual("Supply Outlet Node", spm_node)) {
foundSupplyOutlet = true;
EXPECT_EQ("SPM Scheduled", spm.nameString());
} else if (openstudio::istringEqual("Fan to Humidifier Node", spm_node)) {
foundFanToHumidifierNode = true;
EXPECT_NE(std::string::npos, spm.nameString().find("OS Default SPM"));
}
}
EXPECT_TRUE(foundSupplyOutlet);
EXPECT_TRUE(foundFanToHumidifierNode);
}
{
auto idf_spm_mixed_airs = w.getObjectsByType(IddObjectType::SetpointManager_MixedAir);
ASSERT_EQ(2u, idf_spm_mixed_airs.size());
bool foundMixedAirNode = false;
bool foundCoilToFanNode = false;
for (auto spm : idf_spm_mixed_airs) {
EXPECT_NE(std::string::npos, spm.nameString().find("OS Default SPM"));
EXPECT_EQ("Temperature", spm.getString(SetpointManager_MixedAirFields::ControlVariable).get());
EXPECT_EQ("Supply Outlet Node", spm.getString(SetpointManager_MixedAirFields::ReferenceSetpointNodeName).get());
EXPECT_EQ("Coil to Fan Node", spm.getString(SetpointManager_MixedAirFields::FanInletNodeName).get());
EXPECT_EQ("Fan to Humidifier Node", spm.getString(SetpointManager_MixedAirFields::FanOutletNodeName).get());
auto spm_node = spm.getString(SetpointManager_MixedAirFields::SetpointNodeorNodeListName).get();
if (openstudio::istringEqual("Mixed Air Node", spm_node)) {
foundMixedAirNode = true;
} else if (openstudio::istringEqual("Coil to Fan Node", spm_node)) {
foundCoilToFanNode = true;
}
}
EXPECT_TRUE(foundMixedAirNode);
EXPECT_TRUE(foundCoilToFanNode);
}
{
auto idf_spm_hum_mins = w.getObjectsByType(IddObjectType::SetpointManager_SingleZone_Humidity_Minimum);
ASSERT_EQ(1u, idf_spm_hum_mins.size());
EXPECT_EQ("SPM SZ Min Hum", idf_spm_hum_mins[0].nameString());
EXPECT_EQ("Supply Outlet Node",
idf_spm_hum_mins[0].getString(SetpointManager_SingleZone_Humidity_MinimumFields::SetpointNodeorNodeListName).get());
EXPECT_EQ("Zone Air Node", idf_spm_hum_mins[0].getString(SetpointManager_SingleZone_Humidity_MinimumFields::ControlZoneAirNodeName).get());
}
}
| 7,290 |
713 |
/**
* {@link org.infinispan.manager.EmbeddedCacheManager}-specific listener events
*
* @public
*/
package org.infinispan.notifications.cachemanagerlistener.event;
| 50 |
329 |
<filename>macroslib/tests/expectations/return_foreign_enum_as_err.cpp
"std::variant<Moo, Foo> f() const";
"Foo f2(Foo a0) const noexcept;";
r#"template<bool OWN_DATA>
inline std::variant<Moo, Foo> BooWrapper<OWN_DATA>::f() const noexcept
{
struct CRustResult4232mut3232c_voidu32 ret = Boo_f(this->self_);
return ret.is_ok != 0 ?
std::variant<Moo, Foo> { Moo(static_cast<MooOpaque *>(ret.data.ok)) } :
std::variant<Moo, Foo> { static_cast<Foo>(ret.data.err) };
}"#;
r#"template<bool OWN_DATA>
inline Foo BooWrapper<OWN_DATA>::f2(Foo a0) const noexcept
{
uint32_t ret = Boo_f2(this->self_, static_cast<uint32_t>(a0));
return static_cast<Foo>(ret);
}"#;
| 353 |
34,359 |
<reponame>Harshitha91/Tmdb-react-native-node<filename>ReactNativeFrontend/ios/Pods/boost/boost/detail/winapi/crypt.hpp
/*
* Copyright 2017 <NAME>
*
* Distributed under the Boost Software License, Version 1.0.
* See http://www.boost.org/LICENSE_1_0.txt
*
* This header is deprecated, use boost/winapi/crypt.hpp instead.
*/
#ifndef BOOST_DETAIL_WINAPI_CRYPT_HPP
#define BOOST_DETAIL_WINAPI_CRYPT_HPP
#include <boost/config/header_deprecated.hpp>
BOOST_HEADER_DEPRECATED("<boost/winapi/crypt.hpp>")
#include <boost/winapi/crypt.hpp>
#include <boost/detail/winapi/detail/deprecated_namespace.hpp>
#ifdef BOOST_HAS_PRAGMA_ONCE
#pragma once
#endif
#endif // BOOST_DETAIL_WINAPI_CRYPT_HPP
| 288 |
1,531 |
<reponame>alykhank/tailor
package com.sleekbyte.tailor.common;
import static junit.framework.TestCase.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
/**
* Tests for {@link Severity}.
*/
@RunWith(MockitoJUnitRunner.class)
public class SeverityTest {
@Test
public void testSeverityParserWithValidInputs() throws Severity.IllegalSeverityException {
assertEquals(Severity.parseSeverity("error"), Severity.ERROR);
assertEquals(Severity.parseSeverity("warning"), Severity.WARNING);
assertEquals(Severity.parseSeverity("Error"), Severity.ERROR);
assertEquals(Severity.parseSeverity("ERROR"), Severity.ERROR);
}
@Test(expected = Severity.IllegalSeverityException.class)
public void testSeverityParserWithInvalidInputs() throws Severity.IllegalSeverityException {
Severity.parseSeverity("invalid");
}
@Test
public void testSeverityToString() {
assertEquals(Severity.ERROR.toString(), Messages.ERROR);
assertEquals(Severity.WARNING.toString(), Messages.WARNING);
}
@Test
public void testSeverityMinimum() {
assertEquals(Severity.min(Severity.ERROR, Severity.ERROR), Severity.ERROR);
assertEquals(Severity.min(Severity.ERROR, Severity.WARNING), Severity.WARNING);
assertEquals(Severity.min(Severity.WARNING, Severity.ERROR), Severity.WARNING);
}
}
| 542 |
892 |
<reponame>westonsteimel/advisory-database-github
{
"schema_version": "1.2.0",
"id": "GHSA-9m3w-j6gp-86c9",
"modified": "2022-05-02T03:41:51Z",
"published": "2022-05-02T03:41:51Z",
"aliases": [
"CVE-2009-3120"
],
"details": "Cross-site scripting (XSS) vulnerability in public/index.php in BIGACE Web CMS 2.6 allows remote attackers to inject arbitrary web script or HTML via the id parameter. NOTE: some of these details are obtained from third party information.",
"severity": [
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2009-3120"
},
{
"type": "WEB",
"url": "http://bigace.cvs.sourceforge.net/viewvc/bigace/BIGACE/CORE/public/index.php?revision=1.22&view=markup"
},
{
"type": "WEB",
"url": "http://secunia.com/advisories/36523"
}
],
"database_specific": {
"cwe_ids": [
"CWE-79"
],
"severity": "MODERATE",
"github_reviewed": false
}
}
| 450 |
5,411 |
<filename>code/components/rage-graphics-payne/src/DrawCommands.cpp
#include "StdInc.h"
#include "DrawCommands.h"
#include "Hooking.h"
#include "Rect.h"
#define PURECALL() __asm { jmp _purecall }
static hook::cdecl_stub<void(void(*)(uint32_t, uint32_t), uint32_t*, uint32_t*)> enqueueGenericDC2Args([] ()
{
return hook::get_call(hook::pattern("89 08 C7 44 24 18 FF FF FF FF E8").count(1).get(0).get<void>(10));
});
void EnqueueGenericDrawCommand(void(*cb)(uint32_t, uint32_t), uint32_t* arg1, uint32_t* arg2)
{
enqueueGenericDC2Args(cb, arg1, arg2);
}
bool IsOnRenderThread()
{
/*DWORD* gtaTLS = *(DWORD**)(__readfsdword(44) + (4 * *(uint32_t*)0x17237B0));
return !gtaTLS[306];*/
return false;
}
//void WRAPPER SetTexture(rage::grcTexture* texture) { EAXJMP(0x627FB0); }
static hook::cdecl_stub<void()> drawImVertices([] ()
{
// reuse a pattern from below for performance
return hook::get_call(hook::pattern("5F 5E 75 05 E8 ? ? ? ? 8B 0D").get(0).get<void>(4));
});
static hook::cdecl_stub<void(int, int)> beginImVertices([] ()
{
// fairly annoying pattern :(
return hook::pattern("89 86 40 0C 00 00 C7 86 38 0C 00 00").get(0).get<void>(-0x9A);
});
static hook::cdecl_stub<void(float, float, float, float, float, float, uint32_t, float, float)> addImVertex([] ()
{
return hook::pattern("F3 0F 10 44 24 04 8D 51 24 89 90 40 0C 00 00").get(0).get<void>(-0x3D);
});
void BeginImVertices(int type, int count)
{
beginImVertices(type, count);
}
void AddImVertex(float x, float y, float z, float nX, float nY, float nZ, uint32_t color, float u, float v)
{
// colors are the other way around in Payne again, so RGBA-swap we go
color = (color & 0xFF00FF00) | _rotl(color & 0x00FF00FF, 16);
addImVertex(x, y, z, nX, nY, nZ, color, u, v);
}
void DrawImVertices()
{
drawImVertices();
}
/*void WRAPPER PushUnlitImShader() { EAXJMP(0x852540); }
void WRAPPER PopUnlitImShader() { EAXJMP(0x852570); }*/
static hook::cdecl_stub<void()> setScreenSpaceMatrix([] ()
{
return hook::pattern("57 6A 01 33 FF 33 C0 E8").count(1).get(0).get<void>();
});
static hook::thiscall_stub<void(intptr_t, int, int, intptr_t)> setSubShader([] ()
{
// there's 3 in the current game, but this part matches for all
return hook::get_call(hook::pattern("33 FF 33 C0 E8 ? ? ? ? A1 ? ? ? ? 8B 0D").get(0).get<void>(0x1A));
});
static hook::thiscall_stub<void(intptr_t, int)> setSubShaderUnk([] ()
{
// there's 3 in the current game, but this part matches for all
return hook::get_call(hook::pattern("33 FF 33 C0 E8 ? ? ? ? A1 ? ? ? ? 8B 0D").get(0).get<void>(0x1A + 12));
});
static intptr_t* gtaImShader;
static intptr_t* gtaImTechnique;
static HookFunction shaderIdHookFunc([] ()
{
gtaImShader = *hook::pattern("33 FF 33 C0 E8 ? ? ? ? A1 ? ? ? ? 8B 0D").get(0).get<intptr_t*>(16);
gtaImTechnique = *hook::pattern("33 FF 33 C0 E8 ? ? ? ? A1 ? ? ? ? 8B 0D").get(0).get<intptr_t*>(10);
});
void PushDrawBlitImShader()
{
// set screen space stuff
setScreenSpaceMatrix();
// shader methods: set subshader?
setSubShader(*gtaImShader, 0, 0, *gtaImTechnique);
setSubShaderUnk(*gtaImShader, 0);
}
static hook::thiscall_stub<void(intptr_t)> popSubShader([] ()
{
return hook::get_call(hook::pattern("5F 5E 75 05 E8 ? ? ? ? 8B 0D").get(0).get<void>(15));
});
static hook::thiscall_stub<void(intptr_t)> popSubShaderUnk([] ()
{
return hook::get_call(hook::pattern("5F 5E 75 05 E8 ? ? ? ? 8B 0D").get(0).get<void>(15 + 0xB));
});
void PopDrawBlitImShader()
{
popSubShaderUnk(*gtaImShader);
popSubShader(*gtaImShader);
}
static hook::cdecl_stub<void(rage::grcTexture*)> setTextureGtaIm([] ()
{
return hook::get_call(hook::pattern("6A 17 E8 ? ? ? ? 83 C4 10 8B 56 38 52 E8").count(1).get(0).get<void>(14));
});
void SetTextureGtaIm(rage::grcTexture* texture)
{
setTextureGtaIm(texture);
}
//void WRAPPER DrawImSprite(float x1, float y1, float x2, float y2, float z, float u1, float v1, float u2, float v2, uint32_t* color, int subShader) { EAXJMP(0x852CE0); }
void DrawImSprite(float x1, float y1, float x2, float y2, float z, float u1, float v1, float u2, float v2, uint32_t* colorPtr, int subShader)
{
SetRenderState(0, 0);
SetRenderState(2, 0);
PushDrawBlitImShader();
uint32_t color = *colorPtr;
// this swaps ABGR (as CRGBA is ABGR in little-endian) to ARGB by rotating left
color = (color & 0xFF00FF00) | _rotl(color & 0x00FF00FF, 16);
CRect rect(x1, y1, x2, y2);
BeginImVertices(4, 4);
AddImVertex(rect.fX1, rect.fY1, z, 0.0f, 0.0f, -1.0f, color, u1, v1);
AddImVertex(rect.fX2, rect.fY1, z, 0.0f, 0.0f, -1.0f, color, u2, v1);
AddImVertex(rect.fX1, rect.fY2, z, 0.0f, 0.0f, -1.0f, color, u1, v2);
AddImVertex(rect.fX2, rect.fY2, z, 0.0f, 0.0f, -1.0f, color, u2, v2);
DrawImVertices();
PopDrawBlitImShader();
}
void GetGameResolution(int& resX, int& resY)
{
//resX = *(int*)0xFDCEAC;
//resY = *(int*)0xFDCEB0;
resX = 2560;
resY = 1440;
}
static hook::cdecl_stub<void(int, int)> setRenderState([] ()
{
// NOTE WHEN IMPLEMENTING THIS:
// THERE IS A DIFFERENCE BETWEEN INTERNAL SETTER (E.G. CULLSTATE = 6) AND EXTERNAL SETTER (E.G. CULLSTATE = 0 -> 6)
// this is internal setter in payne
//return hook::get_call(hook::pattern("6A 01 6A 17 E8 ? ? ? ? 6A 01 6A 18 E8").count(2).get(0).get<void>(4));
// external setter
return hook::get_call(hook::pattern("6A 01 00 00 6A 08 6A 10 E8").count(1).get(0).get<void>(8));
});
//void WRAPPER SetRenderState(int rs, int val) { EAXJMP(0x62D2D0); }
void SetRenderState(int rs, int val)
{
return setRenderState(rs, val);
}
| 2,559 |
435 |
<filename>pydx-2016/videos/pydx-2016-ansible-101.json
{
"copyright_text": "Standard YouTube License",
"description": "PyDX 2016 talk by <NAME>\n\nWanna use an automation platform written in Python? Of course you do. And I say \"automation platform\" rather than \"configuration management\" because Ansible isn't just about configuration.\n\nThis all-demo, no-slide talk will teach you by example how to get started with Ansible automating all the things you need automated.",
"duration": 2017,
"language": "eng",
"recorded": "2016-12-30",
"related_urls": [],
"speakers": [
"<NAME>"
],
"tags": [
"ansible"
],
"thumbnail_url": "https://i.ytimg.com/vi/97dSHRrcKE0/maxresdefault.jpg",
"title": "Ansible 101",
"videos": [
{
"type": "youtube",
"url": "https://www.youtube.com/watch?v=97dSHRrcKE0"
}
]
}
| 312 |
302 |
#include "iresourcemodel.h"
#include "every_cpp.h"
namespace BrowserAutomationStudioFramework
{
IResourceModel::IResourceModel(QObject *parent) :
QObject(parent)
{
}
}
| 76 |
332 |
<filename>plugins/plugin_metadata/python/plugin_metadata.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""A simple module that checks if the Plugin Metadata file was sourced correctly."""
# IMPORT THIRD-PARTY LIBRARIES
from pxr import Sdf, Vt
def main():
"""Run the main execution of the current script."""
layer = Sdf.Layer.CreateAnonymous()
message = "Plugin Metadata was not sourced correctly"
primspec = Sdf.CreatePrimInLayer(layer, "/SomePrim")
assert (
"my_custom_double" in primspec.GetMetaDataInfoKeys()
), message
assert layer.pseudoRoot.GetFallbackForInfo("another_metadata") == Vt.DoubleArray(
[5, 13]
), message
if __name__ == "__main__":
main()
| 255 |
971 |
<reponame>adamliheng/DataLink
package com.ucar.datalink.worker.core.boot;
import com.alibaba.fastjson.parser.ParserConfig;
import com.ucar.datalink.biz.service.*;
import com.ucar.datalink.common.utils.IPUtils;
import com.ucar.datalink.domain.worker.WorkerInfo;
import com.ucar.datalink.biz.utils.DataLinkFactory;
import com.ucar.datalink.common.errors.DatalinkException;
import com.ucar.datalink.common.zookeeper.ZkConfig;
import com.ucar.datalink.common.zookeeper.DLinkZkUtils;
import com.ucar.datalink.worker.api.probe.ProbeManager;
import com.ucar.datalink.worker.core.runtime.*;
import com.ucar.datalink.worker.core.runtime.coordinate.WorkerKeeper;
import com.ucar.datalink.worker.core.runtime.rest.RestServer;
import com.ucar.datalink.worker.core.runtime.standalone.StandaloneWorkerKeeper;
import org.apache.commons.lang.StringUtils;
import org.apache.kafka.clients.CommonClientConfigs;
import org.apache.kafka.common.utils.SystemTime;
import org.apache.kafka.common.utils.Time;
import org.apache.kafka.common.utils.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URI;
import java.util.Collections;
import java.util.Map;
import java.util.Properties;
/**
* Worker启动引导类
* Created by lubiao on 2016/12/6.
*/
public class WorkerBootStrap {
private static final Logger logger = LoggerFactory.getLogger(WorkerBootStrap.class);
private static final String CLASSPATH_URL_PREFIX = "classpath:";
static{
ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
}
public void boot(String[] args) {
try {
//boot spring
final ApplicationContextBootStrap appContextBootStrap = new ApplicationContextBootStrap("worker/spring/datalink-worker.xml");
appContextBootStrap.boot();
//initial WorkerConfig
Map<String, String> workerProps;
if (args.length > 0) {
String workerPropsFile = args[0];//if assigned,use the assigned file
workerProps = !workerPropsFile.isEmpty() ?
Utils.propsToStringMap(Utils.loadProps(workerPropsFile)) : Collections.<String, String>emptyMap();
} else {
workerProps = Utils.propsToStringMap(buildWorkerProps());
}
WorkerConfig config = WorkerConfig.fromProps(workerProps, true);
//get boot mode
String bootMode = config.getString(WorkerConfig.WORKER_BOOT_MODE_CONFIG);
//initial plugin EventBus(Listener)
PluginListenersBootStrap.boot(config);
SigarBootStrap.boot();
//initial zkclient
if (BootMode.DISTRIBUTED.equals(bootMode)) {
DLinkZkUtils.init(new ZkConfig(
config.getString(WorkerConfig.ZK_SERVER_CONFIG),
config.getInt(WorkerConfig.ZK_SESSION_TIMEOUT_MS_CONFIG),
config.getInt(WorkerConfig.ZK_CONNECTION_TIMEOUT_MS_CONFIG)), config.getString(WorkerConfig.ZK_ROOT_CONFIG));
}
//initial restserver
RestServer rest = new RestServer(config);
URI advertisedUrl = rest.advertisedUrl();
String restUrl = advertisedUrl.getHost() + ":" + advertisedUrl.getPort();
String workerId = config.getString(CommonClientConfigs.CLIENT_ID_CONFIG);
//initial worker
Time time = new SystemTime();
Worker worker = new Worker(
workerId,
time,
config,
new TaskPositionManager(buildTaskPositionService(bootMode), config),
new TaskSyncStatusManager(DataLinkFactory.getObject(TaskSyncStatusService.class), config),
ProbeManager.getInstance()
);
//initial Keeper
Keeper keeper = buildKeeper(
config,
worker,
time,
restUrl,
bootMode
);
//start datalink worker
logger.info("## start the datalink worker.");
final WorkerController controller = new WorkerController(keeper, rest);
controller.startup();
logger.info("## the datalink worker is running now ......");
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
try {
logger.info("## stop the datalink worker");
controller.shutdown();
appContextBootStrap.close();
} catch (Throwable e) {
logger.warn("##something goes wrong when stopping datalink worker", e);
} finally {
logger.info("## datalink worker is down.");
}
}
});
} catch (Throwable e) {
logger.error("## Something goes wrong when starting up the datalink worker:", e);
System.exit(1);
}
}
private Properties buildWorkerProps() throws IOException {
Properties properties = new Properties();
String conf = System.getProperty("worker.conf");
if (!StringUtils.isEmpty(conf)) {
if (conf.startsWith(CLASSPATH_URL_PREFIX)) {
conf = StringUtils.substringAfter(conf, CLASSPATH_URL_PREFIX);
properties.load(WorkerBootStrap.class.getClassLoader().getResourceAsStream(conf));
} else {
properties.load(new FileInputStream(conf));
}
WorkerInfo workerInfo;
WorkerService service = DataLinkFactory.getObject(WorkerService.class);
String clientId = properties.getProperty(CommonClientConfigs.CLIENT_ID_CONFIG);
if (!StringUtils.isBlank(clientId)) {
workerInfo = service.getById(Long.valueOf(clientId));
} else {
workerInfo = service.getByAddress(IPUtils.getHostIp());
}
if (workerInfo != null) {
properties.setProperty(WorkerConfig.GROUP_ID_CONFIG, String.valueOf(workerInfo.getGroupId()));
properties.setProperty(WorkerConfig.REST_PORT_CONFIG, workerInfo.getRestPort().toString());
if (StringUtils.isBlank(clientId)) {
properties.setProperty(CommonClientConfigs.CLIENT_ID_CONFIG, String.valueOf(workerInfo.getId()));
}
} else {
throw new DatalinkException(String.format("Worker is not found for client id [%s] or ip [%s] ", clientId, IPUtils.getHostIp()));
}
//ddl_sync、sync_auto_addcolumn参数从数据库中读取
SysPropertiesService propertiesService = DataLinkFactory.getObject(SysPropertiesService.class);
Map<String,String> map = propertiesService.map();
properties.setProperty(WorkerConfig.DDL_SYNC_CONFIG,StringUtils.isNotBlank((map.get(WorkerConfig.DDL_SYNC_CONFIG))) ? map.get(WorkerConfig.DDL_SYNC_CONFIG) : String.valueOf(WorkerConfig.DDL_SYNC_DEFAULT));
properties.setProperty(WorkerConfig.SYNC_AUTO_ADD_COLUMN_CONFIG,StringUtils.isNotBlank((map.get(WorkerConfig.SYNC_AUTO_ADD_COLUMN_CONFIG))) ? map.get(WorkerConfig.SYNC_AUTO_ADD_COLUMN_CONFIG) : String.valueOf(WorkerConfig.SYNC_AUTO_ADD_COLUMN_DEFAULT));
}
return properties;
}
private Keeper buildKeeper(WorkerConfig config, Worker worker, Time time, String restUrl, String bootMode) {
Keeper keeper;
if (BootMode.DISTRIBUTED.equals(bootMode)) {
keeper = new WorkerKeeper(
config,
time,
worker,
new TaskStatusManager(DataLinkFactory.getObject(TaskStatusService.class)),
new TaskConfigManager(config.getString(WorkerConfig.GROUP_ID_CONFIG), DataLinkFactory.getObject(TaskConfigService.class)),
restUrl
);
} else if (BootMode.STANDALONE.equals(bootMode)) {
keeper = new StandaloneWorkerKeeper(
config,
worker,
time,
new TaskConfigManager(config.getString(WorkerConfig.GROUP_ID_CONFIG), DataLinkFactory.getObject(TaskConfigService.class))
);
} else {
throw new DatalinkException("invalid boot mode : " + bootMode);
}
return keeper;
}
private TaskPositionService buildTaskPositionService(String bootMode) {
if (BootMode.DISTRIBUTED.equals(bootMode)) {
return DataLinkFactory.getObject("taskPositionServiceZkImpl");
} else {
return DataLinkFactory.getObject("taskPositionServiceDbImpl");
}
}
public static void main(String[] args) {
WorkerBootStrap bootStrap = new WorkerBootStrap();
bootStrap.boot(args);
}
}
| 4,151 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.