max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
595 |
<gh_stars>100-1000
/******************************************************************************
* Copyright (c) 2020 Xilinx, Inc. All rights reserved.
* SPDX-License-Identifier: MIT
******************************************************************************/
/****************************************************************************/
/**
*
* @file psu_init.h
*
* This file is automatically generated
*
*****************************************************************************/
/*
* Divisor value for this clock.
*/
#undef CRL_APB_IOPLL_CFG_OFFSET
#define CRL_APB_IOPLL_CFG_OFFSET (0XFF5E0024U)
#undef CRL_APB_IOPLL_CTRL_OFFSET
#define CRL_APB_IOPLL_CTRL_OFFSET (0XFF5E0020U)
#undef CRF_APB_APLL_CFG_OFFSET
#define CRF_APB_APLL_CFG_OFFSET (0XFD1A0024U)
#undef CRF_APB_APLL_CTRL_OFFSET
#define CRF_APB_APLL_CTRL_OFFSET (0XFD1A0020U)
#undef CRL_APB_I2C1_REF_CTRL_OFFSET
#define CRL_APB_I2C1_REF_CTRL_OFFSET (0XFF5E0124U)
#undef CRL_APB_UART1_REF_CTRL_OFFSET
#define CRL_APB_UART1_REF_CTRL_OFFSET (0XFF5E0078U)
#undef CRL_APB_QSPI_REF_CTRL_OFFSET
#define CRL_APB_QSPI_REF_CTRL_OFFSET (0XFF5E0068U)
#undef IOU_SLCR_MIO_PIN_0_OFFSET
#define IOU_SLCR_MIO_PIN_0_OFFSET (0XFF180000U)
#undef IOU_SLCR_MIO_PIN_1_OFFSET
#define IOU_SLCR_MIO_PIN_1_OFFSET (0XFF180004U)
#undef IOU_SLCR_MIO_PIN_2_OFFSET
#define IOU_SLCR_MIO_PIN_2_OFFSET (0XFF180008U)
#undef IOU_SLCR_MIO_PIN_3_OFFSET
#define IOU_SLCR_MIO_PIN_3_OFFSET (0XFF18000CU)
#undef IOU_SLCR_MIO_PIN_4_OFFSET
#define IOU_SLCR_MIO_PIN_4_OFFSET (0XFF180010U)
#undef IOU_SLCR_MIO_PIN_5_OFFSET
#define IOU_SLCR_MIO_PIN_5_OFFSET (0XFF180014U)
#undef IOU_SLCR_MIO_PIN_12_OFFSET
#define IOU_SLCR_MIO_PIN_12_OFFSET (0XFF180030U)
#undef IOU_SLCR_MIO_PIN_16_OFFSET
#define IOU_SLCR_MIO_PIN_16_OFFSET (0XFF180040U)
#undef IOU_SLCR_MIO_PIN_17_OFFSET
#define IOU_SLCR_MIO_PIN_17_OFFSET (0XFF180044U)
#undef IOU_SLCR_MIO_PIN_18_OFFSET
#define IOU_SLCR_MIO_PIN_18_OFFSET (0XFF180048U)
#undef IOU_SLCR_MIO_PIN_19_OFFSET
#define IOU_SLCR_MIO_PIN_19_OFFSET (0XFF18004CU)
#undef IOU_SLCR_MIO_PIN_36_OFFSET
#define IOU_SLCR_MIO_PIN_36_OFFSET (0xFF180090U)
#undef IOU_SLCR_MIO_PIN_37_OFFSET
#define IOU_SLCR_MIO_PIN_37_OFFSET (0xFF180094U)
#undef IOU_SLCR_MIO_MST_TRI0_OFFSET
#define IOU_SLCR_MIO_MST_TRI0_OFFSET (0XFF180204U)
#undef IOU_SLCR_MIO_MST_TRI1_OFFSET
#define IOU_SLCR_MIO_MST_TRI1_OFFSET (0XFF180208U)
#undef IOU_SLCR_IOU_TAPDLY_BYPASS_OFFSET
#define IOU_SLCR_IOU_TAPDLY_BYPASS_OFFSET (0XFF180390U)
#undef IOU_SECURE_SLCR_IOU_AXI_WPRTCN_OFFSET
#define IOU_SECURE_SLCR_IOU_AXI_WPRTCN_OFFSET (0XFF240000U)
#undef CRL_APB_RST_LPD_IOU2_OFFSET
#define CRL_APB_RST_LPD_IOU2_OFFSET (0XFF5E0238U)
#define CRL_APB_PLL_STATUS_OFFSET (0XFF5E0040U)
#define CRF_APB_PLL_STATUS_OFFSET (0XFD1A0044U)
#define PSU_MASK_POLL_TIME (1100000U)
#ifdef __cplusplus
extern "C" {
#endif
int Psu_Init ();
#ifdef __cplusplus
}
#endif
| 2,684 |
3,651 |
<filename>core/src/main/java/com/orientechnologies/orient/core/sql/executor/DistributedExecutionStep.java<gh_stars>1000+
package com.orientechnologies.orient.core.sql.executor;
import com.orientechnologies.common.concur.OTimeoutException;
import com.orientechnologies.orient.core.command.OCommandContext;
import com.orientechnologies.orient.core.db.ODatabaseDocumentInternal;
import java.util.Map;
import java.util.Optional;
/** Created by luigidellaquila on 08/05/17. */
public class DistributedExecutionStep extends AbstractExecutionStep {
private final OSelectExecutionPlan subExecuitonPlan;
private final String nodeName;
private boolean inited;
private OResultSet remoteResultSet;
public DistributedExecutionStep(
OSelectExecutionPlan subExecutionPlan,
String nodeName,
OCommandContext ctx,
boolean profilingEnabled) {
super(ctx, profilingEnabled);
this.subExecuitonPlan = subExecutionPlan;
this.nodeName = nodeName;
}
@Override
public OResultSet syncPull(OCommandContext ctx, int nRecords) throws OTimeoutException {
init(ctx);
getPrev().ifPresent(x -> x.syncPull(ctx, nRecords));
return new OResultSet() {
@Override
public boolean hasNext() {
throw new UnsupportedOperationException("Implement distributed execution step!");
}
@Override
public OResult next() {
throw new UnsupportedOperationException("Implement distributed execution step!");
}
@Override
public void close() {
DistributedExecutionStep.this.close();
}
@Override
public Optional<OExecutionPlan> getExecutionPlan() {
return Optional.empty();
}
@Override
public Map<String, Long> getQueryStats() {
return null;
}
};
}
public void init(OCommandContext ctx) {
if (!inited) {
inited = true;
this.remoteResultSet = sendSerializedExecutionPlan(nodeName, subExecuitonPlan, ctx);
}
}
private OResultSet sendSerializedExecutionPlan(
String nodeName, OExecutionPlan serializedExecutionPlan, OCommandContext ctx) {
ODatabaseDocumentInternal db = (ODatabaseDocumentInternal) ctx.getDatabase();
return db.queryOnNode(nodeName, serializedExecutionPlan, ctx.getInputParameters());
}
@Override
public void close() {
super.close();
if (this.remoteResultSet != null) {
this.remoteResultSet.close();
}
}
@Override
public String prettyPrint(int depth, int indent) {
StringBuilder builder = new StringBuilder();
String ind = OExecutionStepInternal.getIndent(depth, indent);
builder.append(ind);
builder.append("+ EXECUTE ON NODE " + nodeName + "----------- \n");
builder.append(subExecuitonPlan.prettyPrint(depth + 1, indent));
builder.append(" ------------------------------------------- \n");
builder.append(" |\n");
builder.append(" V\n");
return builder.toString();
}
}
| 1,014 |
605 |
// RUN: %clangxx_tsan -O1 %s -o %t
// RUN: %env_tsan_opts=flush_memory_ms=1:flush_symbolizer_ms=1:memory_limit_mb=1 not %run %t 2>&1 | FileCheck %s
#include "test.h"
long X, Y;
void *Thread(void *arg) {
__atomic_fetch_add(&X, 1, __ATOMIC_SEQ_CST);
barrier_wait(&barrier);
barrier_wait(&barrier);
Y = 1;
return &Y;
}
int main() {
__tsan_flush_memory();
barrier_init(&barrier, 2);
__atomic_fetch_add(&X, 1, __ATOMIC_SEQ_CST);
pthread_t t;
pthread_create(&t, NULL, Thread, NULL);
barrier_wait(&barrier);
__tsan_flush_memory();
// Trigger a race to test flushing of the symbolizer cache.
Y = 2;
barrier_wait(&barrier);
pthread_join(t, NULL);
__atomic_fetch_add(&X, 1, __ATOMIC_SEQ_CST);
// Background runtime thread should do some flushes meanwhile.
sleep(2);
__tsan_flush_memory();
fprintf(stderr, "DONE\n");
// The race may not be detected since we are doing aggressive flushes
// (if the state flush happens between racing accesses, tsan won't
// detect the race). So return 1 to make the test deterministic.
return 1;
}
// CHECK: DONE
| 426 |
4,756 |
<reponame>wynr/libphonenumber
/*
* Copyright (C) 2010 The Libphonenumber 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.i18n.phonenumbers;
import java.util.Iterator;
/**
* A sequence of elements representing a JavaScript Array. The principal operation on a
* JSArrayBuilder is the append method that appends an element to the array. To facilitate nesting
* beginArray and endArray are also supported. Example of a JSArray: ["a", ["b', "c"]].
*
* @author <NAME>
*/
public class JSArrayBuilder implements CharSequence {
// Internal representation.
private StringBuilder data = new StringBuilder();
// Flag that keeps track whether the element being added to the array is the first element.
private boolean isFirstElement = true;
/**
* Begin a new element.
*/
private void beginElement() {
if (!isFirstElement) {
data.append(',');
}
isFirstElement = false;
}
/**
* Begin a new array.
*/
public JSArrayBuilder beginArray() {
beginElement();
data.append('[');
isFirstElement = true;
return this;
}
/**
* End an array.
*/
public JSArrayBuilder endArray() {
trimTrailingCommas();
data.append("]\n");
isFirstElement = false;
return this;
}
/**
* Add a number to the array.
*/
public JSArrayBuilder append(int number) {
return append(Integer.toString(number), false);
}
/**
* Add a string to the array.
*/
public JSArrayBuilder append(String string) {
return append(string, true);
}
/**
* Add a boolean to the array.
*/
public JSArrayBuilder append(boolean b) {
return append(b ? 1 : 0);
}
/**
* Add a collection of strings to the array.
*/
public final JSArrayBuilder appendIterator(Iterator<String> iterator) {
while (iterator.hasNext()) {
append(iterator.next());
}
return this;
}
// Adds a string to the array with an option to escape the string or not.
private JSArrayBuilder append(String string, boolean escapeString) {
beginElement();
if (string != null) {
if (escapeString) {
escape(string, data);
} else {
data.append(string);
}
}
return this;
}
// Returns a string representing the data in this JSArray.
@Override public String toString() {
return data.toString();
}
// Double quotes a string and replaces "\" with "\\".
private static void escape(String str, StringBuilder out) {
out.append('"');
out.append(str.replaceAll("\\\\", "\\\\\\\\"));
out.append('"');
}
// Trims trailing commas.
private void trimTrailingCommas() {
int i = data.length();
while (i > 0 && data.charAt(i - 1) == ',') {
i--;
}
if (i < data.length()) {
data.delete(i, data.length());
}
}
public char charAt(int index) {
return data.charAt(index);
}
public int length() {
return data.length();
}
public CharSequence subSequence(int start, int end) {
return data.subSequence(start, end);
}
}
| 1,160 |
1,755 |
/*=========================================================================
Program: Visualization Toolkit
Module: vtkElevationFilter.cxx
Copyright (c) <NAME>, <NAME>, <NAME>
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkElevationFilter.h"
#include "vtkArrayDispatch.h"
#include "vtkCellData.h"
#include "vtkDataArrayRange.h"
#include "vtkDataSet.h"
#include "vtkFloatArray.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkMath.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkPointSet.h"
#include "vtkSMPTools.h"
#include "vtkSmartPointer.h"
vtkStandardNewMacro(vtkElevationFilter);
namespace
{
// The heart of the algorithm plus interface to the SMP tools.
template <class PointArrayT>
struct vtkElevationAlgorithm
{
vtkIdType NumPts;
double LowPoint[3];
double HighPoint[3];
double ScalarRange[2];
PointArrayT* PointArray;
float* Scalars;
const double* V;
double L2;
vtkElevationAlgorithm(
PointArrayT* pointArray, vtkElevationFilter* filter, float* scalars, const double* v, double l2)
: NumPts{ pointArray->GetNumberOfTuples() }
, PointArray{ pointArray }
, Scalars{ scalars }
, V{ v }
, L2{ l2 }
{
filter->GetLowPoint(this->LowPoint);
filter->GetHighPoint(this->HighPoint);
filter->GetScalarRange(this->ScalarRange);
}
// Interface implicit function computation to SMP tools.
void operator()(vtkIdType begin, vtkIdType end)
{
const double* range = this->ScalarRange;
const double diffScalar = range[1] - range[0];
const double* v = this->V;
const double l2 = this->L2;
const double* lp = this->LowPoint;
// output scalars:
float* s = this->Scalars + begin;
// input points:
const auto pointRange = vtk::DataArrayTupleRange<3>(this->PointArray, begin, end);
for (const auto point : pointRange)
{
double vec[3];
vec[0] = point[0] - lp[0];
vec[1] = point[1] - lp[1];
vec[2] = point[2] - lp[2];
const double ns = vtkMath::ClampValue(vtkMath::Dot(vec, v) / l2, 0., 1.);
// Store the resulting scalar value.
*s = static_cast<float>(range[0] + ns * diffScalar);
++s;
}
}
};
//------------------------------------------------------------------------------
// Templated class is glue between VTK and templated algorithms.
struct Elevate
{
template <typename PointArrayT>
void operator()(
PointArrayT* pointArray, vtkElevationFilter* filter, double* v, double l2, float* scalars)
{
// Okay now generate samples using SMP tools
vtkElevationAlgorithm<PointArrayT> algo{ pointArray, filter, scalars, v, l2 };
vtkSMPTools::For(0, pointArray->GetNumberOfTuples(), algo);
}
};
} // end anon namespace
//------------------------------------------------------------------------------
// Begin the class proper
vtkElevationFilter::vtkElevationFilter()
{
this->LowPoint[0] = 0.0;
this->LowPoint[1] = 0.0;
this->LowPoint[2] = 0.0;
this->HighPoint[0] = 0.0;
this->HighPoint[1] = 0.0;
this->HighPoint[2] = 1.0;
this->ScalarRange[0] = 0.0;
this->ScalarRange[1] = 1.0;
}
//------------------------------------------------------------------------------
vtkElevationFilter::~vtkElevationFilter() = default;
//------------------------------------------------------------------------------
void vtkElevationFilter::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "Low Point: (" << this->LowPoint[0] << ", " << this->LowPoint[1] << ", "
<< this->LowPoint[2] << ")\n";
os << indent << "High Point: (" << this->HighPoint[0] << ", " << this->HighPoint[1] << ", "
<< this->HighPoint[2] << ")\n";
os << indent << "Scalar Range: (" << this->ScalarRange[0] << ", " << this->ScalarRange[1]
<< ")\n";
}
//------------------------------------------------------------------------------
int vtkElevationFilter::RequestData(
vtkInformation*, vtkInformationVector** inputVector, vtkInformationVector* outputVector)
{
// Get the input and output data objects.
vtkDataSet* input = vtkDataSet::GetData(inputVector[0]);
vtkDataSet* output = vtkDataSet::GetData(outputVector);
// Check the size of the input.
vtkIdType numPts = input->GetNumberOfPoints();
if (numPts < 1)
{
vtkDebugMacro("No input!");
return 1;
}
// Allocate space for the elevation scalar data.
vtkSmartPointer<vtkFloatArray> newScalars = vtkSmartPointer<vtkFloatArray>::New();
newScalars->SetNumberOfTuples(numPts);
// Set up 1D parametric system and make sure it is valid.
double diffVector[3] = { this->HighPoint[0] - this->LowPoint[0],
this->HighPoint[1] - this->LowPoint[1], this->HighPoint[2] - this->LowPoint[2] };
double length2 = vtkMath::Dot(diffVector, diffVector);
if (length2 <= 0)
{
vtkErrorMacro("Bad vector, using (0,0,1).");
diffVector[0] = 0;
diffVector[1] = 0;
diffVector[2] = 1;
length2 = 1.0;
}
vtkDebugMacro("Generating elevation scalars!");
// Create a fast path for point set input
//
vtkPointSet* ps = vtkPointSet::SafeDownCast(input);
if (ps)
{
float* scalars = newScalars->GetPointer(0);
vtkPoints* points = ps->GetPoints();
vtkDataArray* pointsArray = points->GetData();
Elevate worker; // Entry point to vtkElevationAlgorithm
// Generate an optimized fast-path for float/double
using FastValueTypes = vtkArrayDispatch::Reals;
using Dispatcher = vtkArrayDispatch::DispatchByValueType<FastValueTypes>;
if (!Dispatcher::Execute(pointsArray, worker, this, diffVector, length2, scalars))
{ // fallback for unknown arrays and integral value types:
worker(pointsArray, this, diffVector, length2, scalars);
}
} // fast path
else
{
// Too bad, got to take the scenic route.
// Support progress and abort.
vtkIdType tenth = (numPts >= 10 ? numPts / 10 : 1);
double numPtsInv = 1.0 / numPts;
int abort = 0;
// Compute parametric coordinate and map into scalar range.
double diffScalar = this->ScalarRange[1] - this->ScalarRange[0];
for (vtkIdType i = 0; i < numPts && !abort; ++i)
{
// Periodically update progress and check for an abort request.
if (i % tenth == 0)
{
this->UpdateProgress((i + 1) * numPtsInv);
abort = this->GetAbortExecute();
}
// Project this input point into the 1D system.
double x[3];
input->GetPoint(i, x);
double v[3] = { x[0] - this->LowPoint[0], x[1] - this->LowPoint[1],
x[2] - this->LowPoint[2] };
double s = vtkMath::Dot(v, diffVector) / length2;
s = (s < 0.0 ? 0.0 : s > 1.0 ? 1.0 : s);
// Store the resulting scalar value.
newScalars->SetValue(i, this->ScalarRange[0] + s * diffScalar);
}
}
// Copy all the input geometry and data to the output.
output->CopyStructure(input);
output->GetPointData()->PassData(input->GetPointData());
output->GetCellData()->PassData(input->GetCellData());
// Add the new scalars array to the output.
newScalars->SetName("Elevation");
output->GetPointData()->AddArray(newScalars);
output->GetPointData()->SetActiveScalars("Elevation");
return 1;
}
| 2,720 |
3,212 |
<gh_stars>1000+
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.nifi.remote;
import java.io.IOException;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import org.apache.nifi.remote.protocol.CommunicationsSession;
public class Peer implements Communicant {
private final PeerDescription description;
private final CommunicationsSession commsSession;
private final String url;
private final String clusterUrl;
private final Map<String, Long> penaltyExpirationMap = new HashMap<>();
private boolean closed = false;
public Peer(final PeerDescription description, final CommunicationsSession commsSession, final String peerUrl, final String clusterUrl) {
this.description = description;
this.commsSession = commsSession;
this.url = peerUrl;
this.clusterUrl = clusterUrl;
try {
// Parse peerUrl to validate it.
new URI(peerUrl);
} catch (final Exception e) {
throw new IllegalArgumentException("Invalid URL: " + peerUrl);
}
}
public PeerDescription getDescription() {
return description;
}
@Override
public String getUrl() {
return url;
}
public String getClusterUrl() {
return clusterUrl;
}
public CommunicationsSession getCommunicationsSession() {
return commsSession;
}
public void close() throws IOException {
this.closed = true;
// Consume the InputStream so that it doesn't linger on the Peer's outgoing socket buffer
try {
commsSession.getInput().consume();
} finally {
commsSession.close();
}
}
/**
* Penalizes this peer for the given destination only for the provided
* number of milliseconds
*
* @param destinationId id of destination
* @param millis period of time to penalize peer
*/
public void penalize(final String destinationId, final long millis) {
final Long currentPenalty = penaltyExpirationMap.get(destinationId);
final long proposedPenalty = System.currentTimeMillis() + millis;
if (currentPenalty == null || proposedPenalty > currentPenalty) {
penaltyExpirationMap.put(destinationId, proposedPenalty);
}
}
public boolean isPenalized(final String destinationId) {
final Long currentPenalty = penaltyExpirationMap.get(destinationId);
return (currentPenalty != null && currentPenalty > System.currentTimeMillis());
}
public boolean isClosed() {
return closed;
}
@Override
public String getHost() {
return description.getHostname();
}
@Override
public int hashCode() {
return 8320 + url.hashCode();
}
@Override
public boolean equals(final Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (!(obj instanceof Peer)) {
return false;
}
final Peer other = (Peer) obj;
return this.url.equals(other.url);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("Peer[url=").append(url);
if (closed) {
sb.append(",CLOSED");
}
sb.append("]");
return sb.toString();
}
@Override
public int getPort() {
return description.getPort();
}
@Override
public String getDistinguishedName() {
return commsSession.getUserDn();
}
@Override
public String createTransitUri(String sourceFlowFileIdentifier) {
return commsSession.createTransitUri(url, sourceFlowFileIdentifier);
}
}
| 1,633 |
997 |
<gh_stars>100-1000
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import os
import json
import time
import jwt
import requests
import base64
import functools
from jwt.algorithms import RSAAlgorithm
from hmalib.aws_secrets import AWSSecrets
from hmalib.common.logging import get_logger
USER_POOL_URL = os.environ["USER_POOL_URL"]
CLIENT_ID = os.environ["CLIENT_ID"]
# https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-verifying-a-jwt.html
KEYS_URL = f"{USER_POOL_URL}/.well-known/jwks.json"
logger = get_logger(__name__)
def generatePolicy(principal_id: str, effect: str, method_arn: str):
# https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-lambda-authorizer-output.html
# break up method_arn to build resource_arn (we do not have layer auth right now so it is Deny or Allow all)
tmp = method_arn.split(":")
api_gw_arn_tmp = tmp[5].split("/")
aws_account_id = tmp[4]
rest_api_id = api_gw_arn_tmp[0]
region = tmp[3]
stage = api_gw_arn_tmp[1]
resource_arn = (
"arn:aws:execute-api:"
+ region
+ ":"
+ aws_account_id
+ ":"
+ rest_api_id
+ "/"
+ stage
+ "/"
+ "*" # allow ANY Method
+ "/"
+ "*" # allow any subpath (important for Auth caching reasons)
)
statement = {
"Action": "execute-api:Invoke",
"Effect": effect,
"Resource": [resource_arn],
}
version = "2012-10-17" # default
policy = {
"principalId": principal_id,
"policyDocument": {"Version": version, "Statement": [statement]},
}
return policy
@functools.lru_cache(maxsize=1)
def _get_public_keys():
response = requests.get(KEYS_URL)
key_list = json.loads(response.text).get("keys", [])
return {key["kid"]: RSAAlgorithm.from_jwk(json.dumps(key)) for key in key_list}
def validate_jwt(token: str):
keys = _get_public_keys()
try:
if not keys:
logger.error("No JWT public keys found. User auth will always fail.")
kid = jwt.get_unverified_header(token)["kid"]
key = keys[kid]
# Decode does verify_signature
decoded = jwt.decode(token, key, algorithms=["RS256"], issuer=USER_POOL_URL)
# Congnito JWT use 'client_id' instead of 'aud' e.g. audience
if decoded["client_id"] == CLIENT_ID and decoded["token_use"] == "access":
# Because we don't require username as part of the request,
# we don't check it beyond making sure it exists.
username = decoded["username"]
logger.debug(f"User: {username} JWT verified.")
return True
except Exception as e:
logger.exception(e)
logger.debug("JWT verification failed.")
return False
# 10 is ~arbitrary: maxsize > 1 because it is possible for their to be more than one
# access token in use that we want to cache, however a large number is unlikely.
@functools.lru_cache(maxsize=10)
def validate_access_token(token: str) -> bool:
access_tokens = AWSSecrets().hma_api_tokens()
if not access_tokens or not token:
logger.debug("No access tokens found")
return False
if token in access_tokens:
return True
return False
def validate_jwt_token(token: str) -> bool:
try:
# try to decode without any validation just to see if it is a JWT
jwt.decode(token, algorithms=["RS256"], options={"verify_signature": False})
return validate_jwt(token)
except jwt.DecodeError:
logger.debug("JWT decode failed.")
return False
def lambda_handler(event, context):
case_insensitive_headers = {k.lower(): v for k, v in event["headers"].items()}
token = case_insensitive_headers["authorization"]
if validate_access_token(token) or validate_jwt_token(token):
policy = generatePolicy("user", "Allow", event["methodArn"])
return policy
else:
policy = generatePolicy("user", "Deny", event["methodArn"])
return policy
if __name__ == "__main__":
token = "text_token"
event = {
"headers": {"Authorization": token},
"methodArn": "arn:aws:execute-api:us-east-1:123456789012:abcdefg123/api/GET/",
}
print(lambda_handler(event, None))
| 1,769 |
2,072 |
# Copyright Contributors to the Amundsen project.
# SPDX-License-Identifier: Apache-2.0
from http import HTTPStatus
import pytest
from metadata_service.exception import NotFoundException
from tests.unit.api.table.table_test_case import TableTestCase
TABLE_URI = 'wizards'
STATS = [{'stat_type': 'requests', 'stat_val': '10', 'start_epoch': 1570581861, 'end_epoch': 1570581861}]
READER = {'email': '<EMAIL>', 'first_name': 'severus', 'last_name': 'snape'}
BASE = {
'database': 'postgres',
'cluster': 'postgres',
'schema': 'hogwarts',
'tags': [{'tag_type': 'table', 'tag_name': 'wizards'}],
'badges': [{'badge_name': 'badge', 'category': 'table_status'}],
'owners': [{'email': '<EMAIL>', 'first_name': 'minerva', 'last_name': 'mcgonagall'}],
'watermarks': [
{'watermark_type': 'type', 'partition_key': 'key', 'partition_value': 'value', 'create_time': '1570581861'}],
'table_writer': {'application_url': 'table_writer_rul', 'name': 'table_writer_name', 'id': 'table_writer_id',
'description': 'table_writer_description'},
'last_updated_timestamp': 1570581861,
'source': {'source_type': 'type', 'source': 'source'},
'is_view': True
}
QUERY_RESPONSE = {
**BASE,
'name': 'wizards',
'description': 'all wizards at hogwarts',
'table_readers': [{
'user': READER,
'read_count': 10
}],
'columns': [{
'name': 'wizard_name',
'description': 'full name of wizard',
'col_type': 'String',
'sort_order': 0,
'stats': STATS
}],
'programmatic_descriptions': []
}
API_RESPONSE = {
**BASE,
'name': 'wizards',
'description': 'all wizards at hogwarts',
'table_readers': [{
'user': READER,
'read_count': 10
}],
'columns': [{
'name': 'wizard_name',
'description': 'full name of wizard',
'col_type': 'String',
'sort_order': 0,
'stats': STATS
}],
'programmatic_descriptions': []
}
class TestTableDetailAPI(TableTestCase):
@pytest.mark.skip(reason='The test is flaky in CI')
def test_should_get_column_details(self) -> None:
self.mock_proxy.get_table.return_value = QUERY_RESPONSE
response = self.app.test_client().get(f'/table/{TABLE_URI}')
self.assertEqual(response.json, API_RESPONSE)
self.assertEqual(response.status_code, HTTPStatus.OK)
self.mock_proxy.get_table.assert_called_with(table_uri=TABLE_URI)
def test_should_fail_to_get_column_details_when_table_not_foubd(self) -> None:
self.mock_proxy.get_table.side_effect = NotFoundException(message='table not found')
response = self.app.test_client().get(f'/table/{TABLE_URI}')
self.assertEqual(response.status_code, HTTPStatus.NOT_FOUND)
| 1,205 |
399 |
# 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.
from __future__ import print_function
import mxnet as mx
x = mx.th.randn(2, 2, ctx=mx.cpu(0))
print(x.asnumpy())
y = mx.th.abs(x)
print(y.asnumpy())
x = mx.th.randn(2, 2, ctx=mx.cpu(0))
print(x.asnumpy())
mx.th.abs(x, x) # in-place
print(x.asnumpy())
x = mx.th.ones(2, 2, ctx=mx.cpu(0))
y = mx.th.ones(2, 2, ctx=mx.cpu(0))*2
print(mx.th.cdiv(x,y).asnumpy())
| 389 |
30,023 |
<reponame>MrDelik/core<gh_stars>1000+
"""Helper methods to search for Plex media."""
from __future__ import annotations
import logging
from plexapi.base import PlexObject
from plexapi.exceptions import BadRequest, NotFound
from plexapi.library import LibrarySection
from .errors import MediaNotFound
LEGACY_PARAM_MAPPING = {
"show_name": "show.title",
"season_number": "season.index",
"episode_name": "episode.title",
"episode_number": "episode.index",
"artist_name": "artist.title",
"album_name": "album.title",
"track_name": "track.title",
"track_number": "track.index",
"video_name": "movie.title",
}
PREFERRED_LIBTYPE_ORDER = (
"episode",
"season",
"show",
"track",
"album",
"artist",
)
_LOGGER = logging.getLogger(__name__)
def search_media(
media_type: str,
library_section: LibrarySection,
allow_multiple: bool = False,
**kwargs,
) -> PlexObject | list[PlexObject]:
"""Search for specified Plex media in the provided library section.
Returns a media item or a list of items if `allow_multiple` is set.
Raises MediaNotFound if the search was unsuccessful.
"""
original_query = kwargs.copy()
search_query = {}
libtype = kwargs.pop("libtype", None)
# Preserve legacy service parameters
for legacy_key, key in LEGACY_PARAM_MAPPING.items():
if value := kwargs.pop(legacy_key, None):
_LOGGER.debug(
"Legacy parameter '%s' used, consider using '%s'", legacy_key, key
)
search_query[key] = value
search_query.update(**kwargs)
if not libtype:
# Default to a sane libtype if not explicitly provided
for preferred_libtype in PREFERRED_LIBTYPE_ORDER:
if any(key.startswith(preferred_libtype) for key in search_query):
libtype = preferred_libtype
break
search_query.update(libtype=libtype)
_LOGGER.debug("Processed search query: %s", search_query)
try:
results = library_section.search(**search_query)
except (BadRequest, NotFound) as exc:
raise MediaNotFound(f"Problem in query {original_query}: {exc}") from exc
if not results:
raise MediaNotFound(
f"No {media_type} results in '{library_section.title}' for {original_query}"
)
if len(results) > 1:
if allow_multiple:
return results
if title := search_query.get("title") or search_query.get("movie.title"):
exact_matches = [x for x in results if x.title.lower() == title.lower()]
if len(exact_matches) == 1:
return exact_matches[0]
raise MediaNotFound(
f"Multiple matches, make content_id more specific or use `allow_multiple`: {results}"
)
return results[0]
| 1,138 |
2,279 |
<gh_stars>1000+
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import six
from six.moves import zip, map, range
import tensorflow as tf
import numpy as np
from zhusuan.utils import merge_dicts
from zhusuan.variational import ImportanceWeightedObjective
__all__ = [
'is_loglikelihood',
]
def is_loglikelihood(meta_bn, observed, latent=None, axis=None,
proposal=None):
"""
Marginal log likelihood (:math:`\log p(x)`) estimates using self-normalized
importance sampling.
:param meta_bn: A :class:`~zhusuan.framework.meta_bn.MetaBayesianNet`
instance or a log joint probability function.
For the latter, it must accepts a dictionary argument of
``(string, Tensor)`` pairs, which are mappings from all
node names in the model to their observed values. The
function should return a Tensor, representing the log joint likelihood
of the model.
:param observed: A dictionary of ``(string, Tensor)`` pairs. Mapping from
names of observed stochastic nodes to their values.
:param latent: A dictionary of ``(string, (Tensor, Tensor))`` pairs.
Mapping from names of latent stochastic nodes to their samples and
log probabilities. `latent` and `proposal` are mutually exclusive.
:param axis: The sample dimension(s) to reduce when computing the
outer expectation in the objective. If ``None``, no dimension is
reduced.
:param proposal: A :class:`~zhusuan.framework.bn.BayesianNet` instance
that defines the proposal distributions of latent nodes.
`proposal` and `latent` are mutually exclusive.
:return: A Tensor. The estimated log likelihood of observed data.
"""
return ImportanceWeightedObjective(
meta_bn,
observed,
latent=latent,
axis=axis,
variational=proposal).tensor
class AIS:
"""
Estimates a stochastic lower bound of the marginal log likelihood
using annealed importance sampling (AIS) (Neal, 2001).
:param meta_bn: A :class:`~zhusuan.framework.meta_bn.MetaBayesianNet`
instance representing the model.
:param proposal_meta_bn: A
:class:`~zhusuan.framework.meta_bn.MetaBayesianNet` instance
representing the proposal distributions.
:param hmc: A :class:`~zhusuan.hmc.HMC` instance.
:param observed: A dictionary of ``(string, Tensor)`` pairs. Mapping from
names of observed stochastic nodes to their values.
:param latent: A dictionary of ``(string, Variable)`` pairs.
Mapping from names of latent `StochasticTensor` s to corresponding
tensorflow Variables for storing their initial values and samples.
:param n_temperatures: An int. Number of temperatures used in AIS.
:param n_adapt: An int. Number of iterations for adapting HMC acceptance
rate.
:param verbose: A bool. Whether to print verbose information.
"""
def __init__(self, meta_bn, proposal_meta_bn, hmc, observed, latent,
n_temperatures=1000, n_adapt=30, verbose=False):
# Shape of latent: [chain_axis, num_data, data dims]
# Construct the tempered objective
self._n_temperatures = n_temperatures
self._n_adapt = n_adapt
self._verbose = verbose
with tf.name_scope("AIS"):
if callable(meta_bn):
log_joint = meta_bn
else:
log_joint = lambda obs: meta_bn.observe(**obs).log_joint()
latent_k, latent_v = zip(*six.iteritems(latent))
prior_samples = proposal_meta_bn.observe().get(latent_k)
log_prior = lambda obs: proposal_meta_bn.observe(**obs).log_joint()
self.temperature = tf.placeholder(tf.float32, shape=[],
name="temperature")
def log_fn(observed):
return log_prior(observed) * (1 - self.temperature) + \
log_joint(observed) * self.temperature
self.log_fn = log_fn
self.log_fn_val = log_fn(merge_dicts(observed, latent))
self.sample_op, self.hmc_info = hmc.sample(
log_fn, observed, latent)
self.init_latent = [tf.assign(z, z_s)
for z, z_s in zip(latent_v, prior_samples)]
def _map_t(self, t):
return 1. / (1. + np.exp(-4 * (2 * t / self._n_temperatures - 1)))
def _get_schedule_t(self, t):
return (self._map_t(t) - self._map_t(0)) / (
self._map_t(self._n_temperatures) - self._map_t(0))
def run(self, sess, feed_dict):
"""
Run the AIS loop.
:param sess: A Tensorflow session.
:param feed_dict: The `feed_dict` argument for ``session.run``.
:return: The log marginal likelihood estimate.
"""
# Help adapt the hmc size
adp_num_t = 2 if self._n_temperatures > 1 else 1
adp_t = self._get_schedule_t(adp_num_t)
sess.run(self.init_latent, feed_dict=feed_dict)
for i in range(self._n_adapt):
_, acc = sess.run([self.sample_op, self.hmc_info.acceptance_rate],
feed_dict=merge_dicts(feed_dict,
{self.temperature: adp_t}))
if self._verbose:
print('Adapt iter {}, acc = {:.3f}'.format(i, np.mean(acc)))
# Draw a sample from the prior
sess.run(self.init_latent, feed_dict=feed_dict)
prior_density = sess.run(self.log_fn_val,
feed_dict=merge_dicts(
feed_dict, {self.temperature: 0}))
log_weights = -prior_density
for num_t in range(self._n_temperatures):
# current_temperature = 1.0 / self._n_temperatures * (num_t + 1)
current_temperature = self._get_schedule_t(num_t + 1)
_, old_log_p, new_log_p, acc = sess.run(
[self.sample_op, self.hmc_info.orig_log_prob,
self.hmc_info.log_prob, self.hmc_info.acceptance_rate],
feed_dict=merge_dicts(feed_dict,
{self.temperature: current_temperature}))
if num_t + 1 < self._n_temperatures:
log_weights += old_log_p - new_log_p
else:
log_weights += old_log_p
if self._verbose:
print('Finished step {}, Temperature = {:.4f}, acc = {:.3f}'
.format(num_t + 1, current_temperature, np.mean(acc)))
return np.mean(self._get_lower_bound(log_weights))
def _get_lower_bound(self, log_weights):
max_log_weights = np.max(log_weights, axis=0)
offset_log_weights = np.mean(np.exp(log_weights - max_log_weights),
axis=0)
log_weights = np.log(offset_log_weights) + max_log_weights
return log_weights
| 3,187 |
1,235 |
/*
* Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.serverless.proxy;
import com.amazonaws.serverless.proxy.internal.jaxrs.AwsHttpApiV2SecurityContext;
import com.amazonaws.serverless.proxy.model.HttpApiV2ProxyRequest;
import com.amazonaws.services.lambda.runtime.Context;
import javax.ws.rs.core.SecurityContext;
public class AwsHttpApiV2SecurityContextWriter implements SecurityContextWriter<HttpApiV2ProxyRequest> {
@Override
public SecurityContext writeSecurityContext(HttpApiV2ProxyRequest event, Context lambdaContext) {
return new AwsHttpApiV2SecurityContext(lambdaContext, event);
}
}
| 330 |
793 |
# coding: utf-8
import unittest
from os import path
import zipfile
import rarfile
from tests.unit import assets_path
from getsub.util import P7ZIP
from getsub.util import get_file_list
class TestGetFileList(unittest.TestCase):
def test_zip_archive(self):
with open(path.join(assets_path, "archive.zip"), "rb") as f:
data = f.read()
sub_lists = get_file_list(data, ".zip")
result = {
"archive/sub4.sub": zipfile.ZipFile,
"dir1/sub1.ass": zipfile.ZipFile,
"dir2/sub2.ass": zipfile.ZipFile,
"dir3/sub.srt": zipfile.ZipFile,
"dir3/dir4/sub.ass": zipfile.ZipFile,
}
for sub, handler in sub_lists.items():
self.assertTrue(isinstance(handler, result[sub]))
def test_rar_archive(self):
with open(path.join(assets_path, "archive.rar"), "rb") as f:
data = f.read()
sub_lists = get_file_list(data, ".rar")
result = {
"dir3/sub.srt": rarfile.RarFile,
"dir3/dir4/sub.ass": rarfile.RarFile,
"archive/sub4.sub": rarfile.RarFile,
"dir1/sub1.ass": zipfile.ZipFile,
"dir2/sub2.ass": zipfile.ZipFile,
}
for sub, handler in sub_lists.items():
self.assertTrue(isinstance(handler, result[sub]))
def test_7z_archive(self):
with open(path.join(assets_path, "archive.7z"), "rb") as f:
data = f.read()
sub_lists = get_file_list(data, ".7z")
result = {
"dir1/sub1.ass": zipfile.ZipFile,
"dir2/sub2.ass": zipfile.ZipFile,
path.join("dir3", "dir4", "sub.ass"): P7ZIP,
path.join("dir3", "sub.srt"): P7ZIP,
path.join("archive", "sub4.sub"): P7ZIP,
}
for sub, handler in sub_lists.items():
self.assertTrue(isinstance(handler, result[sub]))
if __name__ == "__main__":
unittest.main()
| 979 |
672 |
<gh_stars>100-1000
#include "stats.h"
#include <chrono>
Stats::Stats() {
for (int i = 0; i < STATS_METRIC_COUNT; i++) {
struct inst_metric im;
im.last_sample_time = 0;
im.last_sample_count = 0;
im.idx = 0;
for (int j = 0; j < STATS_METRIC_SAMPLES; j++) {
im.samples[j] = 0;
}
inst_metrics.push_back(im);
}
}
#if defined(__APPLE__)
#include <mach/task.h>
#include <mach/mach_init.h>
int64_t Stats::GetMemoryRSS() {
task_t task = MACH_PORT_NULL;
struct task_basic_info t_info;
mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT;
if (task_for_pid(current_task(), getpid(), &task) != KERN_SUCCESS) return 0;
task_info(task, TASK_BASIC_INFO, (task_info_t)&t_info, &t_info_count);
return static_cast<int64_t>(t_info.resident_size);
}
#else
#include <fcntl.h>
#include <string>
#include <cstdio>
#include <cstring>
int64_t Stats::GetMemoryRSS() {
int fd, count;
char buf[4096], filename[256];
snprintf(filename, sizeof(filename), "/proc/%d/stat", getpid());
if ((fd = open(filename, O_RDONLY)) == -1) return 0;
if (read(fd, buf, sizeof(buf)) <= 0) {
close(fd);
return 0;
}
close(fd);
char *start = buf;
count = 23; // RSS is the 24th field in /proc/<pid>/stat
while (start && count--) {
start = strchr(start, ' ');
if (start) start++;
}
if (!start) return 0;
char *stop = strchr(start, ' ');
if (!stop) return 0;
*stop = '\0';
int rss = std::atoi(start);
return static_cast<int64_t>(rss * sysconf(_SC_PAGESIZE));
}
#endif
void Stats::IncrCalls(const std::string &command_name) {
total_calls.fetch_add(1, std::memory_order_relaxed);
commands_stats[command_name].calls.fetch_add(1, std::memory_order_relaxed);
}
void Stats::IncrLatency(uint64_t latency, const std::string &command_name) {
commands_stats[command_name].latency.fetch_add(latency, std::memory_order_relaxed);
}
uint64_t Stats::GetTimeStamp(void) {
auto tp = std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now());
auto ts = std::chrono::duration_cast<std::chrono::milliseconds>(tp.time_since_epoch());
return ts.count();
}
void Stats::TrackInstantaneousMetric(int metric, uint64_t current_reading) {
uint64_t t = GetTimeStamp() - inst_metrics[metric].last_sample_time;
uint64_t ops = current_reading - inst_metrics[metric].last_sample_count;
uint64_t ops_sec = t > 0 ? (ops*1000/t) : 0;
inst_metrics[metric].samples[inst_metrics[metric].idx] = ops_sec;
inst_metrics[metric].idx++;
inst_metrics[metric].idx %= STATS_METRIC_SAMPLES;
inst_metrics[metric].last_sample_time = GetTimeStamp();
inst_metrics[metric].last_sample_count = current_reading;
}
uint64_t Stats::GetInstantaneousMetric(int metric) {
uint64_t sum = 0;
for (int j = 0; j < STATS_METRIC_SAMPLES; j++)
sum += inst_metrics[metric].samples[j];
return sum / STATS_METRIC_SAMPLES;
}
| 1,200 |
652 |
<reponame>pyparallel/pyparallel
#!C:\Users\Trent\Home\src\pyparallel\PCbuild\amd64\python.exe
# EASY-INSTALL-SCRIPT: 'numpy==1.10.1','f2py.py'
__requires__ = 'numpy==1.10.1'
__import__('pkg_resources').run_script('numpy==1.10.1', 'f2py.py')
| 111 |
324 |
<gh_stars>100-1000
{
"kid": "https://kvvaultapilivetest.vault.azure.net/keys/myKey/<KEY>",
"value": "<KEY>"
}
| 53 |
2,151 |
<reponame>tingshao/catapult
# Copyright 2014 <NAME>. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
import unittest
from typ import test_case
from typ.host import Host
from typ.pool import make_pool, _MessageType, _ProcessPool, _loop
def _pre(host, worker_num, context): # pylint: disable=W0613
context['pre'] = True
return context
def _post(context):
context['post'] = True
return context
def _echo(context, msg):
return '%s/%s/%s' % (context['pre'], context['post'], msg)
def _error(context, msg): # pylint: disable=W0613
raise Exception('_error() raised Exception')
def _interrupt(context, msg): # pylint: disable=W0613
raise KeyboardInterrupt()
def _stub(*args): # pylint: disable=W0613
return None
class TestPool(test_case.TestCase):
def run_basic_test(self, jobs):
host = Host()
context = {'pre': False, 'post': False}
pool = make_pool(host, jobs, _echo, context, _pre, _post)
pool.send('hello')
pool.send('world')
msg1 = pool.get()
msg2 = pool.get()
pool.close()
final_contexts = pool.join()
self.assertEqual(set([msg1, msg2]),
set(['True/False/hello',
'True/False/world']))
expected_context = {'pre': True, 'post': True}
expected_final_contexts = [expected_context for _ in range(jobs)]
self.assertEqual(final_contexts, expected_final_contexts)
def run_through_loop(self, callback=None, pool=None):
callback = callback or _stub
if pool:
host = pool.host
else:
host = Host()
pool = _ProcessPool(host, 0, _stub, None, _stub, _stub)
pool.send('hello')
worker_num = 1
_loop(pool.requests, pool.responses, host, worker_num, callback,
None, _stub, _stub, should_loop=False)
return pool
def test_async_close(self):
host = Host()
pool = make_pool(host, 1, _echo, None, _stub, _stub)
pool.join()
def test_basic_one_job(self):
self.run_basic_test(1)
def test_basic_two_jobs(self):
self.run_basic_test(2)
def test_join_discards_messages(self):
host = Host()
context = {'pre': False, 'post': False}
pool = make_pool(host, 2, _echo, context, _pre, _post)
pool.send('hello')
pool.close()
pool.join()
self.assertEqual(len(pool.discarded_responses), 1)
@unittest.skipIf(sys.version_info.major == 3, 'fails under python3')
def test_join_gets_an_error(self):
host = Host()
pool = make_pool(host, 2, _error, None, _stub, _stub)
pool.send('hello')
pool.close()
try:
pool.join()
except Exception as e:
self.assertIn('_error() raised Exception', str(e))
def test_join_gets_an_interrupt(self):
host = Host()
pool = make_pool(host, 2, _interrupt, None, _stub, _stub)
pool.send('hello')
pool.close()
self.assertRaises(KeyboardInterrupt, pool.join)
def test_loop(self):
pool = self.run_through_loop()
resp = pool.get()
self.assertEqual(resp, None)
pool.requests.put((_MessageType.Close, None))
pool.close()
self.run_through_loop(pool=pool)
pool.join()
def test_loop_fails_to_respond(self):
# This tests what happens if _loop() tries to send a response
# on a closed queue; we can't simulate this directly through the
# api in a single thread.
pool = self.run_through_loop()
pool.requests.put((_MessageType.Request, None))
pool.requests.put((_MessageType.Close, None))
self.run_through_loop(pool=pool)
pool.join()
@unittest.skipIf(sys.version_info.major == 3, 'fails under python3')
def test_loop_get_raises_error(self):
pool = self.run_through_loop(_error)
self.assertRaises(Exception, pool.get)
pool.requests.put((_MessageType.Close, None))
pool.close()
pool.join()
def test_loop_get_raises_interrupt(self):
pool = self.run_through_loop(_interrupt)
self.assertRaises(KeyboardInterrupt, pool.get)
pool.requests.put((_MessageType.Close, None))
pool.close()
pool.join()
def test_pickling_errors(self):
def unpicklable_fn(): # pragma: no cover
pass
host = Host()
jobs = 2
self.assertRaises(Exception, make_pool,
host, jobs, _stub, unpicklable_fn, None, None)
self.assertRaises(Exception, make_pool,
host, jobs, _stub, None, unpicklable_fn, None)
self.assertRaises(Exception, make_pool,
host, jobs, _stub, None, None, unpicklable_fn)
def test_no_close(self):
host = Host()
context = {'pre': False, 'post': False}
pool = make_pool(host, 2, _echo, context, _pre, _post)
final_contexts = pool.join()
self.assertEqual(final_contexts, [])
| 2,471 |
360 |
<reponame>marcobambini/c-ray<gh_stars>100-1000
//
// map_range.h
// C-Ray
//
// Created by <NAME> on 11/08/2021.
// Copyright © 2021 <NAME>. All rights reserved.
//
#pragma once
const struct valueNode *newMapRange(const struct world *world,
const struct valueNode *input_value,
const struct valueNode *from_min,
const struct valueNode *from_max,
const struct valueNode *to_min,
const struct valueNode *to_max);
| 191 |
412 |
//Copyright 2018 Author: <NAME> <<EMAIL>>
/// \file
/// This example deals with cyclic data structures,
/// see comment in example2.h explaining why this is necessary.
/// add_element is just declared as a helper method for cycle construction.
/// process_buffer isn't supposed to do meaningfull stuff.
/// It is the hook for the gdb breakpoint used in the test.
/// free_buffer just does clean up, if you run this.
#include "cycles.h"
void add_element(char *content)
{
cycle_buffer_entry_t *new_entry = malloc(sizeof(cycle_buffer_entry_t));
new_entry->data = content;
if(buffer.end && buffer.start)
{
new_entry->next = buffer.start;
buffer.end->next = new_entry;
buffer.end = new_entry;
}
else
{
new_entry->next = new_entry;
buffer.end = new_entry;
buffer.start = new_entry;
}
}
int process_buffer()
{
return 0;
}
void free_buffer()
{
cycle_buffer_entry_t *current;
cycle_buffer_entry_t *free_next;
if(buffer.start)
{
current = buffer.start->next;
while(current != buffer.start)
{
free_next = current;
current = current->next;
free(free_next);
}
free(current);
}
}
int main()
{
add_element("snow");
add_element("sun");
add_element("rain");
add_element("thunder storm");
process_buffer();
free_buffer();
}
| 473 |
1,405 |
<gh_stars>1000+
package QQPIM;
public final class ECategorySignType {
public static final ECategorySignType CSIGN_HOT = new ECategorySignType(3, 3, "CSIGN_HOT");
public static final ECategorySignType CSIGN_NEW = new ECategorySignType(1, 1, "CSIGN_NEW");
public static final ECategorySignType CSIGN_NONE = new ECategorySignType(0, 0, "CSIGN_NONE");
public static final ECategorySignType CSIGN_REC = new ECategorySignType(2, 2, "CSIGN_REC");
public static final int _CSIGN_HOT = 3;
public static final int _CSIGN_NEW = 1;
public static final int _CSIGN_NONE = 0;
public static final int _CSIGN_REC = 2;
static final /* synthetic */ boolean a = (!ECategorySignType.class.desiredAssertionStatus());
private static ECategorySignType[] b = new ECategorySignType[4];
private int c;
private String d = new String();
private ECategorySignType(int i, int i2, String str) {
this.d = str;
this.c = i2;
b[i] = this;
}
public static ECategorySignType convert(int i) {
for (int i2 = 0; i2 < b.length; i2++) {
if (b[i2].value() == i) {
return b[i2];
}
}
if (a) {
return null;
}
throw new AssertionError();
}
public static ECategorySignType convert(String str) {
for (int i = 0; i < b.length; i++) {
if (b[i].toString().equals(str)) {
return b[i];
}
}
if (a) {
return null;
}
throw new AssertionError();
}
public final String toString() {
return this.d;
}
public final int value() {
return this.c;
}
}
| 755 |
521 |
<reponame>Fimbure/icebox-1
#ifndef ETHERBOOT_ENDIAN_H
#define ETHERBOOT_ENDIAN_H
FILE_LICENCE ( GPL2_OR_LATER );
/* Definitions for byte order, according to significance of bytes,
from low addresses to high addresses. The value is what you get by
putting '4' in the most significant byte, '3' in the second most
significant byte, '2' in the second least significant byte, and '1'
in the least significant byte, and then writing down one digit for
each byte, starting with the byte at the lowest address at the left,
and proceeding to the byte with the highest address at the right. */
#define __LITTLE_ENDIAN 1234
#define __BIG_ENDIAN 4321
#define __PDP_ENDIAN 3412
#include "bits/endian.h"
#endif /* ETHERBOOT_ENDIAN_H */
| 248 |
4,949 |
<reponame>BBArikL/tenacity
/**********************************************************************
Audacity: A Digital Audio Editor
SliderTextCtrl.h
<NAME>
This class is a custom slider.
**********************************************************************/
#ifndef __AUDACITY_SLIDERTEXTCTRL__
#define __AUDACITY_SLIDERTEXTCTRL__
#include "wxPanelWrapper.h" // to inherit
class wxSizer;
class wxSlider;
class wxTextCtrl;
wxDECLARE_EVENT(cEVT_SLIDERTEXT, wxCommandEvent);
#define EVT_SLIDERTEXT(winid, func) wx__DECLARE_EVT1( \
cEVT_SLIDERTEXT, winid, wxCommandEventHandler(func))
class SliderTextCtrl : public wxPanelWrapper
{
public:
enum Styles
{
HORIZONTAL = 1,
VERTICAL = 2,
LOG = 4,
INT = 8,
};
SliderTextCtrl(wxWindow *parent, wxWindowID winid,
double value, double min, double max, int precision = 2,
double scale = 0, double offset = 0,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize, long style = HORIZONTAL,
double* varValue = NULL);
void SetMinTextboxWidth(int width);
double GetValue() const;
void SetValue(double value);
private:
void OnTextChange(wxCommandEvent& event);
void OnSlider(wxCommandEvent& event);
void OnKillFocus(wxFocusEvent& event);
wxString FormatValue() const;
enum
{
ID_SLIDER = 1,
ID_TEXTBOX
};
wxSizer* m_sizer;
wxSlider* m_slider;
wxTextCtrl* m_textbox;
bool m_log;
bool m_int;
double m_value;
double m_scale;
double m_min;
double m_max;
double m_zero;
double m_offset;
wxString m_format;
DECLARE_EVENT_TABLE()
};
#endif
| 769 |
1,652 |
# FIXME: need to break down config manager testing a bit more
# @pytest.mark.parametrize('pass_del_cfg', (True, False))
# def test_config_manager_init(mocker, pass_del_cfg):
# """NOTE: unlike other configs this one validates itself on creation
# """
# # Mocks
# patch_del_cfg = mocker.patch('jobfunnel.config.manager.DelayConfig')
# patch_os = mocker.patch('jobfunnel.config.manager.os')
# patch_os.path.exists.return_value = False # check it makes all paths
# mock_master_csv = mocker.Mock()
# mock_block_list = mocker.Mock()
# mock_dupe_list = mocker.Mock()
# mock_cache_folder = mocker.Mock()
# mock_search_cfg = mocker.Mock()
# mock_proxy_cfg = mocker.Mock()
# mock_del_cfg = mocker.Mock()
# # FUT
# cfg = JobFunnelConfigManager(
# master_csv_file=mock_master_csv,
# user_block_list_file=mock_block_list,
# duplicates_list_file=mock_dupe_list,
# cache_folder=mock_cache_folder,
# search_config=mock_search_cfg,
# delay_config=mock_del_cfg if pass_del_cfg else None,
# proxy_config=mock_proxy_cfg,
# log_file='', # TODO optional?
# )
# # Assertions
| 531 |
348 |
<filename>docs/data/leg-t2/041/04101002.json<gh_stars>100-1000
{"nom":"Angé","circ":"1ère circonscription","dpt":"Loir-et-Cher","inscrits":670,"abs":379,"votants":291,"blancs":20,"nuls":10,"exp":261,"res":[{"nuance":"MDM","nom":"<NAME>","voix":157},{"nuance":"FN","nom":"<NAME>","voix":104}]}
| 120 |
389 |
<filename>gosu-lab/src/main/java/editor/util/ContainerMoverSizer.java
package editor.util;
import editor.Scheme;
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
/**
*/
public class ContainerMoverSizer extends JComponent
{
//
// Hit test codes
//
public final static int PART_NONE = 0;
public final static int PART_BORDER = 1;
public final static int PART_BOTTOM = 2;
public final static int PART_BOTTOMLEFT = 3;
public final static int PART_BOTTOMRIGHT = 4;
public final static int PART_CAPTION = 5;
public final static int PART_CLIENT = 6;
public final static int PART_HSCROLL = 9;
public final static int PART_LEFT = 10;
public final static int PART_MENU = 11;
public final static int PART_NOWHERE = 12;
public final static int PART_REDUCE = 13;
public final static int PART_RIGHT = 14;
public final static int PART_SYSMENU = 15;
public final static int PART_TOP = 16;
public final static int PART_TOPLEFT = 17;
public final static int PART_TOPRIGHT = 18;
public final static int PART_TRANSPARENT = 19;
public final static int PART_VSCROLL = 20;
public final static int PART_ZOOM = 21;
public final static int PART_CLOSEBTN = 22;
public final static int PART_MINBTN = 23;
public final static int PART_MAXBTN = 24;
public ContainerMoverSizer( Border border )
{
super();
setBorder( border );
configUi();
}
public Rectangle getClientRect()
{
Insets borderInsets = getBorderInsets();
return new Rectangle( borderInsets.left, borderInsets.top,
getWidth() - (borderInsets.left + borderInsets.right),
getHeight() - (borderInsets.top + borderInsets.bottom) + 1 );
}
public Insets getBorderInsets()
{
return getBorder() == null ? new Insets( 3, 3, 3, 3 ) : getBorder().getBorderInsets( this );
}
@Override
protected void paintComponent( Graphics g )
{
super.paintComponent( g );
g.setColor( getBackground() );
g.fillRect( 0, 0, getWidth(), getHeight() );
}
private void configUi()
{
setOpaque( true );
setBackground( Scheme.active().getControl() );
DragController controller = new DragController();
addMouseListener( controller );
addMouseMotionListener( controller );
}
public synchronized int hitTest( Point pt )
{
if( (pt == null) || (getParent() == null) )
{
return PART_NOWHERE;
}
Point ptPos = getLocation();
ptPos.x += pt.x;
ptPos.y += pt.y;
if( getParent().getComponentAt( ptPos.x, ptPos.y ) != this )
{
return PART_NONE;
}
if( getClientRect().contains( pt ) )
{
return PART_CLIENT;
}
int iFrameW = getWidth();
int iFrameH = getHeight();
Insets borderInsets = getBorderInsets();
Rectangle rcBorder = new Rectangle( 0, 10, borderInsets.left, iFrameH - 2 * 10 );
if( rcBorder.contains( pt ) )
{
return PART_LEFT;
}
rcBorder.setBounds( 10, 0, iFrameW - 2 * 10, borderInsets.top );
if( rcBorder.contains( pt ) )
{
return PART_TOP;
}
rcBorder.setBounds( iFrameW - borderInsets.right, 10, borderInsets.right, iFrameH - 2 * 10 );
if( rcBorder.contains( pt ) )
{
return PART_RIGHT;
}
rcBorder.setBounds( 10, iFrameH - borderInsets.bottom, iFrameW - 2 * 10, borderInsets.bottom );
if( rcBorder.contains( pt ) )
{
return PART_BOTTOM;
}
rcBorder.setBounds( 0, 0, 10, 10 );
if( rcBorder.contains( pt ) )
{
return PART_TOPLEFT;
}
rcBorder.setBounds( iFrameW - 10, 0, 10, 10 );
if( rcBorder.contains( pt ) )
{
return PART_TOPRIGHT;
}
rcBorder.setBounds( 0, iFrameH - 10, 10, 10 );
if( rcBorder.contains( pt ) )
{
return PART_BOTTOMLEFT;
}
rcBorder.setBounds( iFrameW - 10, iFrameH - 10, 10, 10 );
if( rcBorder.contains( pt ) )
{
return PART_BOTTOMRIGHT;
}
return PART_NOWHERE;
}
private void updateCursor( int iDragPart )
{
Cursor cursor = getCursor();
switch( iDragPart )
{
case PART_LEFT:
{
if( cursor == null || cursor.getType() != Cursor.W_RESIZE_CURSOR )
{
setCursor( Cursor.getPredefinedCursor( Cursor.W_RESIZE_CURSOR ) );
}
break;
}
case PART_RIGHT:
{
if( cursor == null || cursor.getType() != Cursor.E_RESIZE_CURSOR )
{
setCursor( Cursor.getPredefinedCursor( Cursor.E_RESIZE_CURSOR ) );
}
break;
}
case PART_TOP:
{
if( cursor == null || cursor.getType() != Cursor.N_RESIZE_CURSOR )
{
setCursor( Cursor.getPredefinedCursor( Cursor.N_RESIZE_CURSOR ) );
}
break;
}
case PART_BOTTOM:
{
if( cursor == null || cursor.getType() != Cursor.S_RESIZE_CURSOR )
{
setCursor( Cursor.getPredefinedCursor( Cursor.S_RESIZE_CURSOR ) );
}
break;
}
case PART_TOPLEFT:
{
if( cursor == null || cursor.getType() != Cursor.NW_RESIZE_CURSOR )
{
setCursor( Cursor.getPredefinedCursor( Cursor.NW_RESIZE_CURSOR ) );
}
break;
}
case PART_TOPRIGHT:
{
if( cursor == null || cursor.getType() != Cursor.NE_RESIZE_CURSOR )
{
setCursor( Cursor.getPredefinedCursor( Cursor.NE_RESIZE_CURSOR ) );
}
break;
}
case PART_BOTTOMLEFT:
{
if( cursor == null || cursor.getType() != Cursor.SW_RESIZE_CURSOR )
{
setCursor( Cursor.getPredefinedCursor( Cursor.SW_RESIZE_CURSOR ) );
}
break;
}
case PART_BOTTOMRIGHT:
{
if( cursor == null || cursor.getType() != Cursor.SE_RESIZE_CURSOR )
{
setCursor( Cursor.getPredefinedCursor( Cursor.SE_RESIZE_CURSOR ) );
}
break;
}
default:
{
if( cursor == null || cursor.getType() != Cursor.DEFAULT_CURSOR )
{
setCursor( Cursor.getPredefinedCursor( Cursor.DEFAULT_CURSOR ) );
}
break;
}
}
}
private class DragController extends MouseAdapter implements MouseMotionListener
{
private boolean _bDragging;
private Point _ptInitialDragLocation;
private Container _container;
private int _iDragPart;
@Override
public void mousePressed( MouseEvent e )
{
setInitialDragLocation( e.getPoint() );
setDragging( true );
}
@Override
public void mouseReleased( MouseEvent e )
{
if( !isDragging() )
{
return;
}
setDragging( false );
}
@Override
public void mouseDragged( MouseEvent e )
{
move( e.getPoint() );
}
@Override
public void mouseMoved( MouseEvent e )
{
setDragPart( hitTest( e.getPoint() ) );
updateCursor( getDragPart() );
}
@Override
public void mouseExited( MouseEvent e )
{
updateCursor( hitTest( e.getPoint() ) );
}
public int getDragPart()
{
return _iDragPart;
}
private void setDragPart( int iDragPart )
{
_iDragPart = iDragPart;
}
private void move( Point pt )
{
Container container = getContainer();
int iXDiff = pt.x - getInitialDragLocation().x;
int iYDiff = pt.y - getInitialDragLocation().y;
if( (iXDiff == 0) && (iYDiff == 0) )
{
return;
}
Rectangle rcBounds = container.getBounds();
Rectangle rcOldBounds = new Rectangle( rcBounds );
switch( getDragPart() )
{
case PART_CAPTION:
case PART_CLIENT:
{
rcBounds.x += iXDiff;
rcBounds.y += iYDiff;
break;
}
case PART_LEFT:
{
rcBounds.width -= iXDiff;
rcBounds.x += iXDiff;
break;
}
case PART_RIGHT:
{
rcBounds.width += iXDiff;
setInitialDragLocation( pt );
break;
}
case PART_TOP:
{
rcBounds.y += iYDiff;
rcBounds.height -= iYDiff;
break;
}
case PART_BOTTOM:
{
rcBounds.height += iYDiff;
setInitialDragLocation( pt );
break;
}
case PART_TOPLEFT:
{
rcBounds.height -= iYDiff;
rcBounds.y += iYDiff;
rcBounds.width -= iXDiff;
rcBounds.x += iXDiff;
break;
}
case PART_TOPRIGHT:
{
rcBounds.height -= iYDiff;
rcBounds.y += iYDiff;
rcBounds.width += iXDiff;
getInitialDragLocation().x = pt.x;
break;
}
case PART_BOTTOMLEFT:
{
rcBounds.width -= iXDiff;
rcBounds.x += iXDiff;
rcBounds.height += iYDiff;
getInitialDragLocation().y = pt.y;
break;
}
case PART_BOTTOMRIGHT:
{
rcBounds.height += iYDiff;
rcBounds.width += iXDiff;
setInitialDragLocation( pt );
break;
}
default:
return;
}
if( rcBounds.equals( rcOldBounds ) )
{
return;
}
Dimension sizeMinimum = container.getMinimumSize();
if( (rcBounds.width < sizeMinimum.width) || (rcBounds.height < sizeMinimum.height) )
{
return;
}
if( getDragPart() == PART_CLIENT || getDragPart() == PART_CAPTION )
{
container.setLocation( rcBounds.x, rcBounds.y );
}
else
{
container.setBounds( rcBounds );
}
container.validate();
}
private Container getContainer()
{
if( _container != null )
{
return _container;
}
for( Container p = getParent(); p != null; p = p.getParent() )
{
if( p.getParent() instanceof JLayeredPane && p.getParent().getWidth() > p.getWidth() )
{
_container = p;
break;
}
else if( p instanceof Window )
{
_container = p;
break;
}
}
return _container;
}
private boolean isDragging()
{
return _bDragging;
}
private void setDragging( boolean bDragging )
{
_bDragging = bDragging;
}
private void setInitialDragLocation( Point ptInitialDragLocation )
{
_ptInitialDragLocation = ptInitialDragLocation;
}
private Point getInitialDragLocation()
{
return _ptInitialDragLocation;
}
}
}
| 4,955 |
992 |
<filename>navigation/common/src/main/java/androidx/navigation/SimpleNavigatorProvider.java
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.navigation;
import android.annotation.SuppressLint;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RestrictTo;
import java.util.HashMap;
import java.util.Map;
/**
* Simple implementation of a {@link NavigatorProvider} that stores instances of
* {@link Navigator navigators} by name, using the {@link Navigator.Name} when given a class name.
*
* @hide
*/
@SuppressLint("TypeParameterUnusedInFormals")
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public class SimpleNavigatorProvider implements NavigatorProvider {
private static final HashMap<Class, String> sAnnotationNames = new HashMap<>();
private final HashMap<String, Navigator<? extends NavDestination>> mNavigators =
new HashMap<>();
@NonNull
private String getNameForNavigator(@NonNull Class<? extends Navigator> navigatorClass) {
String name = sAnnotationNames.get(navigatorClass);
if (name == null) {
Navigator.Name annotation = navigatorClass.getAnnotation(Navigator.Name.class);
name = annotation != null ? annotation.value() : null;
if (!validateName(name)) {
throw new IllegalArgumentException("No @Navigator.Name annotation found for "
+ navigatorClass.getSimpleName());
}
sAnnotationNames.put(navigatorClass, name);
}
return name;
}
@NonNull
@Override
public <D extends NavDestination, T extends Navigator<? extends D>> T getNavigator(
@NonNull Class<T> navigatorClass) {
String name = getNameForNavigator(navigatorClass);
return getNavigator(name);
}
@SuppressWarnings("unchecked")
@NonNull
@Override
public <D extends NavDestination, T extends Navigator<? extends D>> T getNavigator(
@NonNull String name) {
if (!validateName(name)) {
throw new IllegalArgumentException("navigator name cannot be an empty string");
}
Navigator<? extends NavDestination> navigator = mNavigators.get(name);
if (navigator == null) {
throw new IllegalStateException("Could not find Navigator with name \"" + name
+ "\". You must call NavController.addNavigator() for each navigation type.");
}
return (T) navigator;
}
@Nullable
@Override
public Navigator<? extends NavDestination> addNavigator(
@NonNull Navigator<? extends NavDestination> navigator) {
String name = getNameForNavigator(navigator.getClass());
return addNavigator(name, navigator);
}
@Nullable
@Override
public Navigator<? extends NavDestination> addNavigator(@NonNull String name,
@NonNull Navigator<? extends NavDestination> navigator) {
if (!validateName(name)) {
throw new IllegalArgumentException("navigator name cannot be an empty string");
}
return mNavigators.put(name, navigator);
}
Map<String, Navigator<? extends NavDestination>> getNavigators() {
return mNavigators;
}
private boolean validateName(String name) {
return name != null && !name.isEmpty();
}
}
| 1,400 |
21,382 |
import logging
import numpy as np
from ray.tune.automl.search_policy import AutoMLSearcher
logger = logging.getLogger(__name__)
LOGGING_PREFIX = "[GENETIC SEARCH] "
class GeneticSearch(AutoMLSearcher):
"""Implement the genetic search.
Keep a collection of top-K parameter permutations as base genes,
then apply selection, crossover, and mutation to them to generate
new genes (a.k.a new generation). Hopefully, the performance of
the top population would increase generation by generation.
"""
def __init__(self,
search_space,
reward_attr,
max_generation=2,
population_size=10,
population_decay=0.95,
keep_top_ratio=0.2,
selection_bound=0.4,
crossover_bound=0.4):
"""
Initialize GeneticSearcher.
Args:
search_space (SearchSpace): The space to search.
reward_attr: The attribute name of the reward in the result.
max_generation: Max iteration number of genetic search.
population_size: Number of trials of the initial generation.
population_decay: Decay ratio of population size for the
next generation.
keep_top_ratio: Ratio of the top performance population.
selection_bound: Threshold for performing selection.
crossover_bound: Threshold for performing crossover.
"""
super(GeneticSearch, self).__init__(search_space, reward_attr)
self._cur_generation = 1
self._max_generation = max_generation
self._population_size = population_size
self._population_decay = population_decay
self._keep_top_ratio = keep_top_ratio
self._selection_bound = selection_bound
self._crossover_bound = crossover_bound
self._cur_config_list = []
self._cur_encoding_list = []
for _ in range(population_size):
one_hot = self.search_space.generate_random_one_hot_encoding()
self._cur_encoding_list.append(one_hot)
self._cur_config_list.append(
self.search_space.apply_one_hot_encoding(one_hot))
def _select(self):
population_size = len(self._cur_config_list)
logger.info(
LOGGING_PREFIX + "Generate the %sth generation, population=%s",
self._cur_generation, population_size)
return self._cur_config_list, self._cur_encoding_list
def _feedback(self, trials):
self._cur_generation += 1
if self._cur_generation > self._max_generation:
return AutoMLSearcher.TERMINATE
sorted_trials = sorted(
trials,
key=lambda t: t.best_result[self.reward_attr],
reverse=True)
self._cur_encoding_list = self._next_generation(sorted_trials)
self._cur_config_list = []
for one_hot in self._cur_encoding_list:
self._cur_config_list.append(
self.search_space.apply_one_hot_encoding(one_hot))
return AutoMLSearcher.CONTINUE
def _next_generation(self, sorted_trials):
"""Generate genes (encodings) for the next generation.
Use the top K (_keep_top_ratio) trials of the last generation
as candidates to generate the next generation. The action could
be selection, crossover and mutation according corresponding
ratio (_selection_bound, _crossover_bound).
Args:
sorted_trials: List of finished trials with top
performance ones first.
Returns:
A list of new genes (encodings)
"""
candidate = []
next_generation = []
num_population = self._next_population_size(len(sorted_trials))
top_num = int(max(num_population * self._keep_top_ratio, 2))
for i in range(top_num):
candidate.append(sorted_trials[i].extra_arg)
next_generation.append(sorted_trials[i].extra_arg)
for i in range(top_num, num_population):
flip_coin = np.random.uniform()
if flip_coin < self._selection_bound:
next_gen = GeneticSearch._selection(candidate)
else:
if flip_coin < self._selection_bound + self._crossover_bound:
next_gen = GeneticSearch._crossover(candidate)
else:
next_gen = GeneticSearch._mutation(candidate)
next_generation.append(next_gen)
return next_generation
def _next_population_size(self, last_population_size):
"""Calculate the population size of the next generation.
Intuitively, the population should decay after each iteration since
it should converge. It can also decrease the total resource required.
Args:
last_population_size: The last population size.
Returns:
The new population size.
"""
# TODO: implement an generic resource allocate algorithm.
return int(max(last_population_size * self._population_decay, 3))
@staticmethod
def _selection(candidate):
"""Perform selection action to candidates.
For example, new gene = sample_1 + the 5th bit of sample2.
Args:
candidate: List of candidate genes (encodings).
Examples:
>>> # Genes that represent 3 parameters
>>> gene1 = np.array([[0, 0, 1], [0, 1], [1, 0]])
>>> gene2 = np.array([[0, 1, 0], [1, 0], [0, 1]])
>>> new_gene = _selection([gene1, gene2])
>>> # new_gene could be gene1 overwritten with the
>>> # 2nd parameter of gene2
>>> # in which case:
>>> # new_gene[0] = gene1[0]
>>> # new_gene[1] = gene2[1]
>>> # new_gene[2] = gene1[0]
Returns:
New gene (encoding)
"""
sample_index1 = np.random.choice(len(candidate))
sample_index2 = np.random.choice(len(candidate))
sample_1 = candidate[sample_index1]
sample_2 = candidate[sample_index2]
select_index = np.random.choice(len(sample_1))
logger.info(
LOGGING_PREFIX + "Perform selection from %sth to %sth at index=%s",
sample_index2, sample_index1, select_index)
next_gen = []
for i in range(len(sample_1)):
sample = sample_2[i] if i is select_index else sample_1[i]
next_gen.append(sample)
return next_gen
@staticmethod
def _crossover(candidate):
"""Perform crossover action to candidates.
For example, new gene = 60% sample_1 + 40% sample_2.
Args:
candidate: List of candidate genes (encodings).
Examples:
>>> # Genes that represent 3 parameters
>>> gene1 = np.array([[0, 0, 1], [0, 1], [1, 0]])
>>> gene2 = np.array([[0, 1, 0], [1, 0], [0, 1]])
>>> new_gene = _crossover([gene1, gene2])
>>> # new_gene could be the first [n=1] parameters of
>>> # gene1 + the rest of gene2
>>> # in which case:
>>> # new_gene[0] = gene1[0]
>>> # new_gene[1] = gene2[1]
>>> # new_gene[2] = gene1[1]
Returns:
New gene (encoding)
"""
sample_index1 = np.random.choice(len(candidate))
sample_index2 = np.random.choice(len(candidate))
sample_1 = candidate[sample_index1]
sample_2 = candidate[sample_index2]
cross_index = int(len(sample_1) * np.random.uniform(low=0.3, high=0.7))
logger.info(
LOGGING_PREFIX +
"Perform crossover between %sth and %sth at index=%s",
sample_index1, sample_index2, cross_index)
next_gen = []
for i in range(len(sample_1)):
sample = sample_2[i] if i > cross_index else sample_1[i]
next_gen.append(sample)
return next_gen
@staticmethod
def _mutation(candidate, rate=0.1):
"""Perform mutation action to candidates.
For example, randomly change 10% of original sample
Args:
candidate: List of candidate genes (encodings).
rate: Percentage of mutation bits
Examples:
>>> # Genes that represent 3 parameters
>>> gene1 = np.array([[0, 0, 1], [0, 1], [1, 0]])
>>> new_gene = _mutation([gene1])
>>> # new_gene could be the gene1 with the 3rd parameter changed
>>> # new_gene[0] = gene1[0]
>>> # new_gene[1] = gene1[1]
>>> # new_gene[2] = [0, 1] != gene1[2]
Returns:
New gene (encoding)
"""
sample_index = np.random.choice(len(candidate))
sample = candidate[sample_index]
idx_list = []
for i in range(int(max(len(sample) * rate, 1))):
idx = np.random.choice(len(sample))
idx_list.append(idx)
field = sample[idx] # one-hot encoding
field[np.argmax(field)] = 0
bit = np.random.choice(field.shape[0])
field[bit] = 1
logger.info(LOGGING_PREFIX + "Perform mutation on %sth at index=%s",
sample_index, str(idx_list))
return sample
| 4,265 |
715 |
<filename>Dynamic Programming/kadane/C/kadane.c
#include <stdio.h>
/*
Kadane's algorithm finds the maximum subarray(contigious subsequence) sum.
let f(i) be the maximum sum of any non-empty subarray ending at i.
f(i) = {
max(arr[i], f[i-1] + arr[i]) otherwise
arr[0] when i = 0
}
*/
int max(int a,int b){
//returns the maximum of two
return a>b?a:b;
}
//kadane's algorithm
//Time Complexity = O(n)
//Space Complexity = O(n)
int max_subarray_sum(int arr[], int size){
int f[size];
int maximum_sum;
f[0] = arr[0];
maximum_sum = arr[0];
for(int i=1; i< size; i++){
f[i] = max(arr[i], f[i-1]+ arr[i]);
//keep track of maximum sum ending at ith position found so far.
maximum_sum = max(f[i],maximum_sum);
}
return maximum_sum;
}
//Time Complexity = O(n)
//Space Complexity = O(1)
//Space Complexity can be reduced by thinking that we really don't need to store all the values of f[i]
//we need to track arr[i] and f[i-1] only
int max_subarray_sum2(int arr[], int size){
int sum;
int maximum_sum;
sum = arr[0];
maximum_sum = arr[0];
for(int i=1; i< size; i++){
sum = max(arr[i],sum + arr[i]);
maximum_sum = max(sum, maximum_sum);
}
return maximum_sum;
}
int main(){
int arr[10000];
int size;
int T;
scanf("%d",&T);
while(T--){
scanf("%d",&size);
for(int i=0;i < size; i++)
scanf("%d",&arr[i]);
printf("%d\n",max_subarray_sum2(arr,size));
// printf("%d\n",max_subarray_sum(arr,size));
}
}
| 866 |
322 |
<filename>nodejs/scripts/tests/GH56/value-0.standard.json
{
"name" : { "localPart" : "value", "namespaceURI" : "", "prefix" : "", "key" : "value", "string" : "value" },
"value" : {
"value" : "test",
"attribute" : "check",
"TYPE_NAME" : "Zero.ValueType"
}
}
| 114 |
434 |
<gh_stars>100-1000
package example;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.events.KinesisAnalyticsInputPreprocessingResponse;
import com.amazonaws.services.lambda.runtime.events.KinesisFirehoseEvent;
import com.amazonaws.services.lambda.runtime.tests.annotations.Event;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.params.ParameterizedTest;
import static java.nio.charset.StandardCharsets.UTF_8;
public class KinesisFirehoseEventHandlerTest {
private Context context; // intentionally null as it's not used in the test
@ParameterizedTest
@Event(value = "event.json", type = KinesisFirehoseEvent.class)
public void testEventHandler(KinesisFirehoseEvent event) {
KinesisFirehoseEventHandler kinesisFirehoseEventHandler = new KinesisFirehoseEventHandler();
KinesisAnalyticsInputPreprocessingResponse response = kinesisFirehoseEventHandler.handleRequest(event, context);
String expectedString = "\n!dlroW olleH";
KinesisAnalyticsInputPreprocessingResponse.Record firstRecord = response.getRecords().get(0);
Assertions.assertEquals(expectedString, UTF_8.decode(firstRecord.getData()).toString());
Assertions.assertEquals(KinesisAnalyticsInputPreprocessingResponse.Result.Ok, firstRecord.getResult());
}
}
| 440 |
643 |
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import contextlib
import os
import sys
from pylib import constants
DIR_SOURCE_ROOT = os.environ.get(
'CHECKOUT_SOURCE_ROOT',
os.path.abspath(os.path.join(os.path.dirname(__file__),
os.pardir, os.pardir, os.pardir, os.pardir)))
BUILD_COMMON_PATH = os.path.join(
DIR_SOURCE_ROOT, 'build', 'util', 'lib', 'common')
# third-party libraries
ANDROID_PLATFORM_DEVELOPMENT_SCRIPTS_PATH = os.path.join(
DIR_SOURCE_ROOT, 'third_party', 'android_platform', 'development',
'scripts')
BUILD_PATH = os.path.join(DIR_SOURCE_ROOT, 'build')
DEVIL_PATH = os.path.join(
DIR_SOURCE_ROOT, 'third_party', 'catapult', 'devil')
TRACING_PATH = os.path.join(
DIR_SOURCE_ROOT, 'third_party', 'catapult', 'tracing')
@contextlib.contextmanager
def SysPath(path, position=None):
if position is None:
sys.path.append(path)
else:
sys.path.insert(position, path)
try:
yield
finally:
if sys.path[-1] == path:
sys.path.pop()
else:
sys.path.remove(path)
# Map of CPU architecture name to (toolchain_name, binprefix) pairs.
# TODO(digit): Use the build_vars.txt file generated by gn.
_TOOL_ARCH_MAP = {
'arm': ('arm-linux-androideabi-4.9', 'arm-linux-androideabi'),
'arm64': ('aarch64-linux-android-4.9', 'aarch64-linux-android'),
'x86': ('x86-4.9', 'i686-linux-android'),
'x86_64': ('x86_64-4.9', 'x86_64-linux-android'),
'x64': ('x86_64-4.9', 'x86_64-linux-android'),
'mips': ('mipsel-linux-android-4.9', 'mipsel-linux-android'),
}
# Cache used to speed up the results of ToolPath()
# Maps (arch, tool_name) pairs to fully qualified program paths.
# Useful because ToolPath() is called repeatedly for demangling C++ symbols.
_cached_tool_paths = {}
def ToolPath(tool, cpu_arch):
"""Return a fully qualifed path to an arch-specific toolchain program.
Args:
tool: Unprefixed toolchain program name (e.g. 'objdump')
cpu_arch: Target CPU architecture (e.g. 'arm64')
Returns:
Fully qualified path (e.g. ..../aarch64-linux-android-objdump')
Raises:
Exception if the toolchain could not be found.
"""
tool_path = _cached_tool_paths.get((tool, cpu_arch))
if tool_path:
return tool_path
toolchain_source, toolchain_prefix = _TOOL_ARCH_MAP.get(
cpu_arch, (None, None))
if not toolchain_source:
raise Exception('Could not find tool chain for ' + cpu_arch)
toolchain_subdir = (
'toolchains/%s/prebuilt/linux-x86_64/bin' % toolchain_source)
tool_path = os.path.join(constants.ANDROID_NDK_ROOT,
toolchain_subdir,
toolchain_prefix + '-' + tool)
_cached_tool_paths[(tool, cpu_arch)] = tool_path
return tool_path
def GetAaptPath():
"""Returns the path to the 'aapt' executable."""
return os.path.join(constants.ANDROID_SDK_TOOLS, 'aapt')
| 1,205 |
2,329 |
/*
* 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.shenyu.admin.utils;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.util.DigestUtils;
/**
* Shenyu Signature tool.
*/
public class ShenyuSignatureUtils {
/**
* At present, it is positioned as 1.0.0 write dead, string type.
*/
public static final String VERSION = "1.0.0";
/**
* generate Sign.
* @param sign sign
* @return String
*/
public static String generateSign(final String sign) {
return DigestUtils.md5DigestAsHex(sign.getBytes()).toUpperCase();
}
/**
* getSignContent.
* @param secureKey secureKey
* @param timestamp timestamp
* @param path path
* @return String
*/
public static String getSignContent(final String secureKey, final String timestamp, final String path) {
Map<String, String> map = new HashMap<>(3);
map.put("timestamp", timestamp);
map.put("path", path);
map.put("version", VERSION);
List<String> storedKeys = Arrays.stream(map.keySet()
.toArray(new String[] {}))
.sorted(Comparator.naturalOrder())
.collect(Collectors.toList());
final String signContent = storedKeys.stream()
.map(key -> String.join("", key, map.get(key)))
.collect(Collectors.joining()).trim()
.concat(secureKey);
return signContent;
}
}
| 806 |
6,717 |
//******************************************************************************
//
// Copyright (c) 2016 Microsoft Corporation. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// 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.
//
//******************************************************************************
#pragma once
#import <CoreVideo/CoreVideoExport.h>
#import <CoreFoundation/CFDictionary.h>
#import <CoreFoundation/CFBase.h>
#import <CoreFoundation/CFArray.h>
#import <CoreVideo/CVPixelBuffer.h>
#import <CoreFoundation/CFString.h>
typedef Boolean (*CVFillExtendedPixelsCallBack)(CVPixelBufferRef pixelBuffer, void* refCon);
typedef struct {
CFIndex version;
CVFillExtendedPixelsCallBack fillCallBack;
void* refCon;
} CVFillExtendedPixelsCallBackData;
COREVIDEO_EXPORT void CVPixelFormatDescriptionRegisterDescriptionWithPixelFormatType(CFDictionaryRef description,
OSType pixelFormat) STUB_METHOD;
COREVIDEO_EXPORT CFDictionaryRef CVPixelFormatDescriptionCreateWithPixelFormatType(CFAllocatorRef allocator,
OSType pixelFormat) STUB_METHOD;
COREVIDEO_EXPORT CFArrayRef CVPixelFormatDescriptionArrayCreateWithAllPixelFormatTypes(CFAllocatorRef allocator) STUB_METHOD;
COREVIDEO_EXPORT const CFStringRef kCVPixelFormatName;
COREVIDEO_EXPORT const CFStringRef kCVPixelFormatConstant;
COREVIDEO_EXPORT const CFStringRef kCVPixelFormatCodecType;
COREVIDEO_EXPORT const CFStringRef kCVPixelFormatFourCC;
COREVIDEO_EXPORT const CFStringRef kCVPixelFormatContainsAlpha;
COREVIDEO_EXPORT const CFStringRef kCVPixelFormatPlanes;
COREVIDEO_EXPORT const CFStringRef kCVPixelFormatBlockWidth;
COREVIDEO_EXPORT const CFStringRef kCVPixelFormatBlockHeight;
COREVIDEO_EXPORT const CFStringRef kCVPixelFormatBitsPerBlock;
COREVIDEO_EXPORT const CFStringRef kCVPixelFormatBlockHorizontalAlignment;
COREVIDEO_EXPORT const CFStringRef kCVPixelFormatBlockVerticalAlignment;
COREVIDEO_EXPORT const CFStringRef kCVPixelFormatBlackBlock;
COREVIDEO_EXPORT const CFStringRef kCVPixelFormatHorizontalSubsampling;
COREVIDEO_EXPORT const CFStringRef kCVPixelFormatVerticalSubsampling;
COREVIDEO_EXPORT const CFStringRef kCVPixelFormatOpenGLFormat;
COREVIDEO_EXPORT const CFStringRef kCVPixelFormatOpenGLType;
COREVIDEO_EXPORT const CFStringRef kCVPixelFormatOpenGLInternalFormat;
COREVIDEO_EXPORT const CFStringRef kCVPixelFormatCGBitmapInfo;
COREVIDEO_EXPORT const CFStringRef kCVPixelFormatQDCompatibility;
COREVIDEO_EXPORT const CFStringRef kCVPixelFormatCGBitmapContextCompatibility;
COREVIDEO_EXPORT const CFStringRef kCVPixelFormatCGImageCompatibility;
COREVIDEO_EXPORT const CFStringRef kCVPixelFormatOpenGLCompatibility;
COREVIDEO_EXPORT const CFStringRef kCVPixelFormatOpenGLESCompatibility;
COREVIDEO_EXPORT const CFStringRef kCVPixelFormatFillExtendedPixelsCallback;
enum {
kCVPixelFormatType_1Monochrome = 0x00000001,
kCVPixelFormatType_2Indexed = 0x00000002,
kCVPixelFormatType_4Indexed = 0x00000004,
kCVPixelFormatType_8Indexed = 0x00000008,
kCVPixelFormatType_1IndexedGray_WhiteIsZero = 0x00000021,
kCVPixelFormatType_2IndexedGray_WhiteIsZero = 0x00000022,
kCVPixelFormatType_4IndexedGray_WhiteIsZero = 0x00000024,
kCVPixelFormatType_8IndexedGray_WhiteIsZero = 0x00000028,
kCVPixelFormatType_16BE555 = 0x00000010,
kCVPixelFormatType_16LE555 = 'L555',
kCVPixelFormatType_16LE5551 = '5551',
kCVPixelFormatType_16BE565 = 'B565',
kCVPixelFormatType_16LE565 = 'L565',
kCVPixelFormatType_24RGB = 0x00000018,
kCVPixelFormatType_24BGR = '24BG',
kCVPixelFormatType_32ARGB = 0x00000020,
kCVPixelFormatType_32BGRA = 'BGRA',
kCVPixelFormatType_32ABGR = 'ABGR',
kCVPixelFormatType_32RGBA = 'RGBA',
kCVPixelFormatType_64ARGB = 'b64a',
kCVPixelFormatType_48RGB = 'b48r',
kCVPixelFormatType_32AlphaGray = 'b32a',
kCVPixelFormatType_16Gray = 'b16g',
kCVPixelFormatType_30RGB = 'R10k',
kCVPixelFormatType_422YpCbCr8 = '2vuy',
kCVPixelFormatType_4444YpCbCrA8 = 'v408',
kCVPixelFormatType_4444YpCbCrA8R = 'r408',
kCVPixelFormatType_4444AYpCbCr8 = 'y408',
kCVPixelFormatType_4444AYpCbCr16 = 'y416',
kCVPixelFormatType_444YpCbCr8 = 'v308',
kCVPixelFormatType_422YpCbCr16 = 'v216',
kCVPixelFormatType_422YpCbCr10 = 'v210',
kCVPixelFormatType_444YpCbCr10 = 'v410',
kCVPixelFormatType_420YpCbCr8Planar = 'y420',
kCVPixelFormatType_420YpCbCr8PlanarFullRange = 'f420',
kCVPixelFormatType_422YpCbCr_4A_8BiPlanar = 'a2vy',
kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange = '420v',
kCVPixelFormatType_420YpCbCr8BiPlanarFullRange = '420f',
kCVPixelFormatType_422YpCbCr8_yuvs = 'yuvs',
kCVPixelFormatType_422YpCbCr8FullRange = 'yuvf',
kCVPixelFormatType_OneComponent8 = 'L008',
kCVPixelFormatType_TwoComponent8 = '2C08',
kCVPixelFormatType_OneComponent16Half = 'L00h',
kCVPixelFormatType_OneComponent32Float = 'L00f',
kCVPixelFormatType_TwoComponent16Half = '2C0h',
kCVPixelFormatType_TwoComponent32Float = '2C0f',
kCVPixelFormatType_64RGBAHalf = 'RGhA',
kCVPixelFormatType_128RGBAFloat = 'RGfA',
};
| 2,206 |
1,169 |
<reponame>Biangkerok32/punya
// -*- mode: java; c-basic-offset: 2; -*-
// Copyright 2015 MIT, All rights reserved
// Released under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0
package com.google.appinventor.client.editor.youngandroid.properties;
import static com.google.appinventor.client.Ode.MESSAGES;
import com.google.appinventor.client.widgets.properties.ChoicePropertyEditor;
/**
* Property editor for Sizing property of Screen1
*/
public class YoungAndroidSizingChoicePropertyEditor extends ChoicePropertyEditor {
// Accelerometer sensitivity choices
private static final Choice[] sizing = new Choice[] {
new Choice(MESSAGES.fixedSizing(), "Fixed"),
new Choice(MESSAGES.responsiveSizing(), "Responsive")
};
public YoungAndroidSizingChoicePropertyEditor() {
super(sizing);
}
}
| 260 |
6,989 |
<filename>env/lib/python3.7/site-packages/sklearn/utils/stats.py
import numpy as np
from .extmath import stable_cumsum
def _weighted_percentile(array, sample_weight, percentile=50):
"""
Compute the weighted ``percentile`` of ``array`` with ``sample_weight``.
"""
sorted_idx = np.argsort(array)
# Find index of median prediction for each sample
weight_cdf = stable_cumsum(sample_weight[sorted_idx])
percentile_idx = np.searchsorted(
weight_cdf, (percentile / 100.) * weight_cdf[-1])
# in rare cases, percentile_idx equals to len(sorted_idx)
percentile_idx = np.clip(percentile_idx, 0, len(sorted_idx)-1)
return array[sorted_idx[percentile_idx]]
| 266 |
437 |
<filename>src/test/java/com/fasterxml/jackson/dataformat/xml/fuzz/FuzzXXX_32969_UTF32Test.java
package com.fasterxml.jackson.dataformat.xml.fuzz;
import com.fasterxml.jackson.core.exc.StreamReadException;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.dataformat.xml.XmlTestBase;
// [dataformat-xml#???]
// (but root cause of https://github.com/FasterXML/woodstox/issues/125)
//
// NOTE! Not reproducible for some reason with these settings (probably
// has different buffer sizes or... something
public class FuzzXXX_32969_UTF32Test extends XmlTestBase
{
private final XmlMapper MAPPER = newMapper();
public void testUTF32() throws Exception
{
final byte[] doc = readResource("/data/fuzz-32906.xml");
try {
MAPPER.readTree(doc, 0, doc.length);
fail("Should not pass");
} catch (StreamReadException e) {
verifyException(e, "Unexpected EOF in CDATA");
} catch (RuntimeException e) {
fail("Should fail with specific `StreamReadException` but got: "+e);
}
}
}
| 422 |
353 |
<reponame>JayjeetAtGithub/ceph-deploy
import configparser
import contextlib
from ceph_deploy import exc
class _TrimIndentFile(object):
def __init__(self, fp):
self.fp = fp
def readline(self):
line = self.fp.readline()
return line.lstrip(' \t')
def __iter__(self):
return iter(self.readline, '')
class CephConf(configparser.RawConfigParser):
def __init__(self):
# super() cannot be used with an old-style class
configparser.RawConfigParser.__init__(self, strict=False)
def optionxform(self, s):
s = s.replace('_', ' ')
s = '_'.join(s.split())
return s
def safe_get(self, section, key):
"""
Attempt to get a configuration value from a certain section
in a ``cfg`` object but returning None if not found. Avoids the need
to be doing try/except {ConfigParser Exceptions} every time.
"""
try:
#Use full parent function so we can replace it in the class
# if desired
return configparser.RawConfigParser.get(self, section, key)
except (configparser.NoSectionError,
configparser.NoOptionError):
return None
def parse(fp):
cfg = CephConf()
ifp = _TrimIndentFile(fp)
cfg.read_file(ifp)
return cfg
def load(args):
"""
:param args: Will be used to infer the proper configuration name, or
if args.ceph_conf is passed in, that will take precedence
"""
path = args.ceph_conf or '{cluster}.conf'.format(cluster=args.cluster)
try:
f = open(path)
except IOError as e:
raise exc.ConfigError(
"%s; has `ceph-deploy new` been run in this directory?" % e
)
else:
with contextlib.closing(f):
return parse(f)
def load_raw(args):
"""
Read the actual file *as is* without parsing/modifiying it
so that it can be written maintaining its same properties.
:param args: Will be used to infer the proper configuration name
:paran path: alternatively, use a path for any configuration file loading
"""
path = args.ceph_conf or '{cluster}.conf'.format(cluster=args.cluster)
try:
with open(path) as ceph_conf:
return ceph_conf.read()
except (IOError, OSError) as e:
raise exc.ConfigError(
"%s; has `ceph-deploy new` been run in this directory?" % e
)
def write_conf(cluster, conf, overwrite):
""" write cluster configuration to /etc/ceph/{cluster}.conf """
import os
path = '/etc/ceph/{cluster}.conf'.format(cluster=cluster)
tmp = '{path}.{pid}.tmp'.format(path=path, pid=os.getpid())
if os.path.exists(path):
with open(path) as f:
old = f.read()
if old != conf and not overwrite:
raise RuntimeError('config file %s exists with different content; use --overwrite-conf to overwrite' % path)
with open(tmp, 'w') as f:
f.write(conf)
f.flush()
os.fsync(f)
os.rename(tmp, path)
| 1,285 |
2,659 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2021 4Paradigm
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# -*- coding: utf-8 -*-
import unittest
import commands
import random
import os
import time
import sys
import threading
import shlex
import subprocess
import collections
sys.path.append(os.getenv('testpath'))
from libs.logger import infoLogger
import libs.conf as conf
import libs.utils as utils
from libs.clients.ns_cluster import NsCluster
import traceback
import copy
import re
class TestCaseBase(unittest.TestCase):
@staticmethod
def skip(msg):
return unittest.skip(msg)
@classmethod
def setUpClass(cls):
infoLogger.info('\n' + '|' * 50 + ' TEST {} STARTED '.format(cls) + '|' * 50 + '\n')
cls.welcome = 'Welcome to fedb with version {}\n'.format(os.getenv('rtidbver'))
cls.testpath = os.getenv('testpath')
cls.rtidb_path = os.getenv('rtidbpath')
cls.conf_path = os.getenv('confpath')
cls.data_path = os.getenv('datapath')
cls.ns_leader = utils.exe_shell('head -n 1 {}/ns_leader'.format(cls.testpath))
cls.ns_leader_path = utils.exe_shell('tail -n 1 {}/ns_leader'.format(cls.testpath))
cls.ns_slaver = [i for i in conf.ns_endpoints if i != cls.ns_leader][0]
cls.leader, cls.slave1, cls.slave2 = (i for i in conf.tb_endpoints)
cls.multidimension = conf.multidimension
cls.multidimension_vk = conf.multidimension_vk
cls.multidimension_scan_vk = conf.multidimension_scan_vk
cls.failfast = conf.failfast
cls.ns_path_dict = {conf.ns_endpoints[0]: cls.testpath + '/ns1',
conf.ns_endpoints[1]: cls.testpath + '/ns2'}
cls.node_path_dict = {cls.leader: cls.testpath + '/tablet1',
cls.slave1: cls.testpath + '/tablet2',
cls.slave2: cls.testpath + '/tablet3',
cls.ns_leader: cls.ns_path_dict[cls.ns_leader],
cls.ns_slaver: cls.ns_path_dict[cls.ns_slaver]}
cls.leaderpath = cls.node_path_dict[cls.leader]
cls.slave1path = cls.node_path_dict[cls.slave1]
cls.slave2path = cls.node_path_dict[cls.slave2]
infoLogger.info('*'*88)
infoLogger.info([i for i in conf.ns_endpoints])
infoLogger.info(cls.ns_slaver)
infoLogger.info(conf.cluster_mode)
# remote env
cls.ns_leader_r = utils.exe_shell('head -n 1 {}/ns_leader_remote'.format(cls.testpath))
cls.ns_leader_path_r = utils.exe_shell('tail -n 1 {}/ns_leader_remote'.format(cls.testpath))
cls.ns_slaver_r = [i for i in conf.ns_endpoints_r if i != cls.ns_leader_r][0]
cls.leader_r, cls.slave1_r, cls.slave2_r = (i for i in conf.tb_endpoints_r)
cls.ns_path_dict_r = {conf.ns_endpoints_r[0]: cls.testpath + '/ns1remote',
conf.ns_endpoints_r[1]: cls.testpath + '/ns2remote'}
cls.node_path_dict_r = {cls.leader_r: cls.testpath + '/tablet1remote',
cls.slave1_r: cls.testpath + '/tablet2remote',
cls.slave2_r: cls.testpath + '/tablet3remote',
cls.ns_leader_r: cls.ns_path_dict_r[cls.ns_leader_r],
cls.ns_slaver_r: cls.ns_path_dict_r[cls.ns_slaver_r]}
infoLogger.info('*'*88)
infoLogger.info([i for i in conf.ns_endpoints_r])
infoLogger.info(cls.ns_slaver_r)
@classmethod
def tearDownClass(cls):
for edp in conf.tb_endpoints:
utils.exe_shell('rm -rf {}/recycle/*'.format(cls.node_path_dict[edp]))
utils.exe_shell('rm -rf {}/db/*'.format(cls.node_path_dict[edp]))
for edp in conf.tb_endpoints_r:
utils.exe_shell('rm -rf {}/recycle/*'.format(cls.node_path_dict_r[edp]))
utils.exe_shell('rm -rf {}/db/*'.format(cls.node_path_dict_r[edp]))
infoLogger.info('\n' + '=' * 50 + ' TEST {} FINISHED '.format(cls) + '=' * 50 + '\n' * 5)
def setUp(self):
infoLogger.info('\nTEST CASE NAME: {} {} {}'.format(
self, self._testMethodDoc, '\n' + '|' * 50 + ' SETUP STARTED ' + '|' * 50 + '\n'))
try:
self.ns_leader = utils.exe_shell('head -n 1 {}/ns_leader'.format(self.testpath))
nss = copy.deepcopy(conf.ns_endpoints)
nss.remove(self.ns_leader)
self.ns_slaver = nss[0]
self.ns_leader_path = utils.exe_shell('tail -n 1 {}/ns_leader'.format(self.testpath))
self.tid = random.randint(1, 1000)
self.pid = random.randint(1, 1000)
if conf.cluster_mode == "cluster":
self.clear_ns_table(self.ns_leader)
else:
for edp in conf.tb_endpoints:
self.clear_tb_table(edp)
#remote env
self.alias = 'rem'
self.ns_leader_r = utils.exe_shell('head -n 1 {}/ns_leader_remote'.format(self.testpath))
nss_r = copy.deepcopy(conf.ns_endpoints_r)
nss_r.remove(self.ns_leader_r)
self.ns_slaver_r = nss_r[0]
self.ns_leader_path_r = utils.exe_shell('tail -n 1 {}/ns_leader_remote'.format(self.testpath))
self.clear_ns_table(self.ns_leader_r)
for edp in conf.tb_endpoints_r:
self.clear_tb_table(edp)
except Exception as e:
traceback.print_exc(file=sys.stdout)
infoLogger.info('\n\n' + '=' * 50 + ' SETUP FINISHED ' + '=' * 50 + '\n')
def tearDown(self):
infoLogger.info('\n\n' + '|' * 50 + ' TEARDOWN STARTED ' + '|' * 50 + '\n')
try:
rs = self.showtablet(self.ns_leader)
for edp in conf.tb_endpoints:
if rs[edp][0] != 'kTabletHealthy':
infoLogger.info("Endpoint offline !!!! " * 10 + edp)
self.stop_client(edp)
time.sleep(1)
self.start_client(edp)
time.sleep(10)
if conf.cluster_mode == "cluster":
self.clear_ns_table(self.ns_leader)
#remote env
rs_r = self.showtablet(self.ns_leader_r)
for edp in conf.tb_endpoints_r:
if rs_r[edp][0] != 'kTabletHealthy':
infoLogger.info("Endpoint offline !!!! " * 10 + edp)
self.stop_client(edp)
time.sleep(1)
self.start_client(edp)
time.sleep(10)
if conf.cluster_mode == "cluster":
self.clear_ns_table(self.ns_leader_r)
except Exception as e:
traceback.print_exc(file=sys.stdout)
infoLogger.info('\n\n' + '=' * 50 + ' TEARDOWN FINISHED ' + '=' * 50 + '\n' * 5)
def now(self):
return int(time.time() * 1000000 / 1000)
def start_client(self, endpoint, role='tablet'):
client_path = self.node_path_dict[endpoint]
if role == 'tablet' or role == 'nameserver':
conf = role
else:
pass
cmd = '{}/fedb --flagfile={}/conf/{}.flags'.format(self.testpath, client_path, conf)
infoLogger.info(cmd)
args = shlex.split(cmd)
need_start = False
for _ in range(20):
rs = utils.exe_shell('lsof -i:{}|grep -v "PID"'.format(endpoint.split(':')[1]))
if 'fedb' not in rs:
need_start = True
time.sleep(1)
subprocess.Popen(args, stdout=open('{}/info.log'.format(client_path), 'a'),
stderr=open('{}/warning.log'.format(client_path), 'a'))
else:
time.sleep(1)
rs = utils.exe_shell('lsof -i:{}|grep -v "PID"'.format(endpoint.split(':')[1]))
if 'fedb' in rs:
return True, need_start
return False, need_start
def stop_client(self, endpoint):
port = endpoint.split(':')[1]
cmd = "lsof -i:{}".format(port) + "|grep '(LISTEN)'|awk '{print $2}'|xargs kill -9"
utils.exe_shell(cmd)
rs = utils.exe_shell('lsof -i:{}|grep -v "PID"'.format(port))
if 'CLOSE_WAIT' in rs:
time.sleep(2)
#infoLogger.error('Kill failed because of CLOSE_WAIT !!!!!!!!!!!!!!!!')
#cmd = "lsof -i:{}".format(port) + "|grep '(CLOSE_WAIT)'|awk '{print $2}'|xargs kill -9"
#utils.exe_shell(cmd)
def get_new_ns_leader(self):
nsc = NsCluster(conf.zk_endpoint, *(i for i in conf.ns_endpoints))
nsc.get_ns_leader()
infoLogger.info(conf.ns_endpoints)
nss = copy.deepcopy(conf.ns_endpoints)
self.ns_leader = utils.exe_shell('head -n 1 {}/ns_leader'.format(self.testpath))
self.ns_leader_path = utils.exe_shell('tail -n 1 {}/ns_leader'.format(self.testpath))
self.node_path_dict[self.ns_leader] = utils.exe_shell('tail -n 1 {}/ns_leader'.format(self.testpath))
nss.remove(self.ns_leader)
self.ns_slaver = nss[0]
infoLogger.info("*" * 88)
infoLogger.info("ns_leader: " + self.ns_leader)
infoLogger.info("ns_slaver: " + self.ns_slaver)
infoLogger.info("*" * 88)
def run_client(self, endpoint, cmd, role='client'):
cmd = cmd.strip()
rs = utils.exe_shell('{} --endpoint={} --role={} --interactive=false --request_timeout_ms=200000 --cmd="{}"'.format(
self.rtidb_path, endpoint, role, cmd))
return rs.replace(self.welcome, '').replace('>', '')
@staticmethod
def get_manifest_by_realpath(realpath, tid, pid):
manifest_dict = {}
with open('{}/{}_{}/snapshot/MANIFEST'.format(realpath, tid, pid)) as f:
for l in f:
if 'offset: ' in l:
manifest_dict['offset'] = l.split(':')[1].strip()
elif 'name: ' in l:
manifest_dict['name'] = l.split(':')[1][2:-2].strip()
elif 'count: ' in l:
manifest_dict['count'] = l.split(':')[1].strip()
elif 'term: ' in l:
manifest_dict['term'] = l.split(':')[1].strip()
return manifest_dict
@staticmethod
def get_manifest(nodepath, tid, pid):
realpath = nodepath + "/db"
return TestCaseBase.get_manifest_by_realpath(realpath, tid, pid)
@staticmethod
def get_table_meta_no_db(nodepath, tid, pid):
table_meta_dict = {}
with open('{}/{}_{}/table_meta.txt'.format(nodepath, tid, pid)) as f:
for l in f:
if 'tid: ' in l:
table_meta_dict['tid'] = l.split(':')[1].strip()
elif 'name: ' in l:
table_meta_dict['name'] = l.split(':')[1][2:-2].strip()
elif 'compress_type: ' in l:
table_meta_dict['compress_type'] = l.split(':')[1].strip()
elif 'key_entry_max_height: ' in l:
table_meta_dict['key_entry_max_height'] = l.split(':')[1].strip()
return table_meta_dict
@staticmethod
def get_table_meta(nodepath, tid, pid):
table_meta_dict = {}
with open('{}/db/{}_{}/table_meta.txt'.format(nodepath, tid, pid)) as f:
for l in f:
if 'tid: ' in l:
table_meta_dict['tid'] = l.split(':')[1].strip()
elif 'name: ' in l:
table_meta_dict['name'] = l.split(':')[1][2:-2].strip()
elif 'compress_type: ' in l:
table_meta_dict['compress_type'] = l.split(':')[1].strip()
elif 'key_entry_max_height: ' in l:
table_meta_dict['key_entry_max_height'] = l.split(':')[1].strip()
return table_meta_dict
def create(self, endpoint, tname, tid, pid, ttl=144000, segment=8, isleader='true', *slave_endpoints, **schema):
if not schema:
if self.multidimension:
infoLogger.debug('create with default multi dimension')
cmd = 'screate'
schema = {k: v[0] for k, v in self.multidimension_vk.items()} # default schema
else:
cmd = 'create'
else:
cmd = 'screate'
return self.run_client(endpoint, '{} {} {} {} {} {} {} {} {}'.format(
cmd, tname, tid, pid, ttl, segment, isleader, ' '.join(slave_endpoints),
' '.join(['{}:{}'.format(k, v) for k, v in schema.items() if k != ''])))
def execute_gc(self, endpoint, tid, pid):
cmd = "curl -d \'{\"tid\":%s, \"pid\":%s}\' http://%s/TabletServer/ExecuteGc" % (tid, pid, endpoint)
utils.exe_shell(cmd)
time.sleep(2)
def ns_switch_mode(self, endpoint, mode):
cmd = 'switchmode ' + mode
return self.run_client(endpoint, cmd, 'ns_client')
def add_replica_cluster(self, endpoint, zk_endpoints, zk_root_path, alias):
cmd = 'addrepcluster {} {} {}'.format(zk_endpoints, zk_root_path, alias)
return self.run_client(endpoint, cmd, 'ns_client')
def remove_replica_cluster(self, endpoint, alias):
cmd = 'removerepcluster ' + alias
return self.run_client(endpoint, cmd, 'ns_client')
def ns_create(self, endpoint, metadata_path):
return self.run_client(endpoint, 'create ' + metadata_path, 'ns_client')
def ns_create_cmd(self, endpoint, name, ttl, partition_num, replica_num, schema = ''):
cmd = 'create {} {} {} {} {}'.format(name, ttl, partition_num, replica_num, schema)
return self.run_client(endpoint, cmd, 'ns_client')
def ns_add_table_field(self, endpoint, name ,col_name, col_type):
cmd = 'addtablefield {} {} {}'.format(name, col_name, col_type);
return self.run_client(endpoint, cmd, 'ns_client')
def ns_addindex(self, endpoint, name, index_name, col_name='', ts_name=''):
cmd = 'addindex {} {} {} {}'.format(name, index_name, col_name, ts_name)
return self.run_client(endpoint, cmd, 'ns_client')
def parse_scan_result(self, result):
arr = result.split("\n")
key_arr = re.sub(' +', ' ', arr[0]).strip().split(" ")
value = []
for i in range(2, len(arr)):
record = re.sub(' +', ' ', arr[i]).strip().split(" ")
cur_map = {}
for idx in range(len(key_arr)):
cur_map[key_arr[idx]] = record[idx]
value.append(cur_map)
return value
def ns_preview(self, endpoint, name, limit = ''):
cmd = 'preview {} {}'.format(name, limit)
result = self.run_client(endpoint, cmd, 'ns_client')
return self.parse_scan_result(result)
def ns_count(self, endpoint, name, key, idx_name, filter_expired_data = 'false'):
cmd = 'count {} {} {} {}'.format(name, key, idx_name, filter_expired_data)
result = self.run_client(endpoint, cmd, 'ns_client')
infoLogger.debug(result)
return result
def ns_count_with_pair(self, endpoint, name, key, idx_name, ts_name, filter_expired_data = 'false'):
cmd = 'count {} {} {} {} {}'.format('table_name='+name, 'key='+key, 'index_name='+idx_name, 'ts_name='+ts_name, 'filter_expired_data='+filter_expired_data)
result = self.run_client(endpoint, cmd, 'ns_client')
infoLogger.debug(result)
return result
def ns_scan_kv(self, endpoint, name, pk, start_time, end_time, limit = ''):
cmd = 'scan {} {} {} {} {}'.format(name, pk, start_time, end_time, limit)
result = self.run_client(endpoint, cmd, 'ns_client')
return self.parse_scan_result(result)
def ns_scan_multi(self, endpoint, name, pk, idx_name, start_time, end_time, limit = ''):
cmd = 'scan {} {} {} {} {} {}'.format(name, pk, idx_name, start_time, end_time, limit)
result = self.run_client(endpoint, cmd, 'ns_client')
return self.parse_scan_result(result)
def ns_scan_multi_with_pair(self, endpoint, name, pk, idx_name, start_time, end_time, ts_name, limit = '0', atleast = '0'):
cmd = 'scan {} {} {} {} {} {} {} {}'.format('table_name='+name, 'key='+pk, 'index_name='+idx_name, 'st='+start_time, 'et='+end_time, 'ts_name='+ts_name, 'limit='+limit, 'atleast='+atleast)
result = self.run_client(endpoint, cmd, 'ns_client')
return self.parse_scan_result(result)
def ns_delete(self, endpoint, name, key, idx_name = ''):
cmd = 'delete {} {} {}'.format(name, key, idx_name);
return self.run_client(endpoint, cmd, 'ns_client')
def ns_info(self, endpoint, name):
cmd = 'info {}'.format(name);
result = self.run_client(endpoint, cmd, 'ns_client')
lines = result.split("\n")
kv = {}
for line_num in xrange(2, len(lines)):
arr = lines[line_num].strip().split(" ")
key = arr[0]
value = lines[line_num].strip().lstrip(key).strip()
kv[key] = value
return kv
def ns_get_kv(self, endpoint, name, key, ts):
cmd = 'get ' + name + ' ' + key+ ' ' + ts
return self.run_client(endpoint, cmd, 'ns_client')
def ns_get_multi(self, endpoint, name, key, idx_name, ts):
cmd = 'get {} {} {} {}'.format(name, key, idx_name, ts)
result = self.run_client(endpoint, cmd, 'ns_client')
arr = result.split("\n")
key_arr = re.sub(' +', ' ', arr[0]).replace("# ts", "").strip().split(" ")
value = {}
record = re.sub(' +', ' ', arr[2]).strip().split(" ")
for idx in range(len(key_arr)):
value[key_arr[idx]] = record[idx+2]
return value
def ns_get_multi_with_pair(self, endpoint, name, key, idx_name, ts, ts_name):
cmd = 'get {} {} {} {} {}'.format('table_name='+name,'key='+ key, 'index_name='+idx_name,'ts='+ts,'ts_name='+ts_name)
result = self.run_client(endpoint, cmd, 'ns_client')
value = {}
if result.find("Fail to get value") != -1:
return value
arr = result.split("\n")
key_arr = re.sub(' +', ' ', arr[0]).replace("# ts", "").strip().split(" ")
record = re.sub(' +', ' ', arr[2]).strip().split(" ")
for idx in range(len(key_arr)):
value[key_arr[idx]] = record[idx+2]
return value
def ns_put_kv(self, endpoint, name, pk, ts, value):
cmd = 'put {} {} {} {}'.format(name, pk, ts, value)
return self.run_client(endpoint, cmd, 'ns_client')
def ns_put_multi(self, endpoint, name, ts, row):
cmd = 'put {} {} {}'.format(name, ts, ' '.join(row))
return self.run_client(endpoint, cmd, 'ns_client')
def ns_put_multi_with_pair(self, endpoint, name, row):
cmd = 'put {} {}'.format(name, ' '.join(row))
return self.run_client(endpoint, cmd, 'ns_client')
def ns_query(self, endpoint, name, row):
cmd = 'query {} {}'.format('table_name=' + name, row)
result = self.run_client(endpoint, cmd, 'ns_client')
return self.parse_scan_result(result)
def ns_update(self, endpoint, name, row):
cmd = 'update {} {}'.format('table_name=' + name, row)
return self.run_client(endpoint, cmd, 'ns_client')
def ns_drop(self, endpoint, tname):
infoLogger.debug(tname)
return self.run_client(endpoint, 'drop {}'.format(tname), 'ns_client')
def ns_update_table_alive_cmd(self, ns_endpoint, updatetablealive, table_name, pid, endpoint, is_alive):
cmd = '{} {} {} {} {}'.format(updatetablealive, table_name, pid, endpoint, is_alive)
return self.run_client(ns_endpoint, cmd, 'ns_client')
def ns_synctable(self, ns_endpoint, table_name, alias, pid = ''):
cmd = '{} {} {} {} '.format('synctable', table_name, alias, pid)
return self.run_client(ns_endpoint, cmd, 'ns_client')
def ns_recover_table_cmd(self, ns_endpoint, recovertable, table_name, pid, endpoint):
cmd = '{} {} {} {}'.format(recovertable, table_name, pid, endpoint)
return self.run_client(ns_endpoint, cmd, 'ns_client')
def ns_addreplica(self, ns_endpoint, name, pid, replica_endpoint):
cmd = 'addreplica {} {} {}'.format(name, pid, replica_endpoint)
return self.run_client(ns_endpoint, cmd, 'ns_client')
def ns_gettablepartition(self, ns_endpoint, gettablepartition, name, pid):
cmd = '{} {} {}'.format(gettablepartition, name, pid)
return self.run_client(ns_endpoint, cmd, 'ns_client')
def ns_showns(self, ns_endpoint, showns):
cmd = '{}'.format(showns)
return self.run_client(ns_endpoint, cmd, 'ns_client')
def ns_showopstatus(self, endpoint):
rs = self.run_client(endpoint, 'showopstatus', 'ns_client')
return rs
def put(self, endpoint, tid, pid, key, ts, *values):
if len(values) == 1:
if self.multidimension and key is not '':
infoLogger.debug('put with default multi dimension')
default_values = [str(v[1]) for v in self.multidimension_vk.values()]
return self.run_client(endpoint, 'sput {} {} {} {}'.format(
tid, pid, ts, ' '.join(default_values)))
elif not self.multidimension and key is not '':
return self.run_client(endpoint, 'put {} {} {} {} {}'.format(
tid, pid, key, ts, values[0]))
return self.run_client(endpoint, 'sput {} {} {} {}'.format(
tid, pid, ts, ' '.join(values)))
def sput(self, endpoint, tid, pid, ts, *values):
return self.run_client(endpoint, 'sput {} {} {} {}'.format(
tid, pid, ts, ' '.join(values[0])))
def scan(self, endpoint, tid, pid, vk, ts_from, ts_to):
"""
:param endpoint:
:param tid:
:param pid:
:param vk: e.g. {'card': 0001, 'merchant': 0002} or 'naysakey'
:param ts_from:
:param ts_to:
:return:
"""
if not isinstance(vk, dict):
if self.multidimension:
infoLogger.debug('scan with default multi dimension')
default_vk = self.multidimension_scan_vk
value_key = ['{} {}'.format(v, k) for k, v in default_vk.items()]
return self.run_client(endpoint, 'sscan {} {} {} {} {}'.format(
tid, pid, ' '.join(value_key), ts_from, ts_to))
else:
return self.run_client(endpoint, 'scan {} {} {} {} {}'.format(
tid, pid, vk, ts_from, ts_to))
else:
value_key = ['{} {}'.format(v, k) for k, v in vk.items()]
return self.run_client(endpoint, 'sscan {} {} {} {} {}'.format(
tid, pid, ' '.join(value_key), ts_from, ts_to))
def preview(self, endpoint, tid, pid, limit = ''):
cmd = 'preview {} {} {}'.format(tid, pid, limit)
result = self.run_client(endpoint, cmd, 'client')
return self.parse_scan_result(result)
def get(self, endpoint, tid, pid, vk, ts):
"""
:param endpoint:
:param tid:
:param pid:
:param vk: e.g. {'card': 0001, 'merchant': 0002} or 'naysakey'
:param ts:
:return:
"""
if self.multidimension:
print(self.multidimension_scan_vk.keys()[0])
print(self.multidimension_scan_vk.values()[0])
return self.run_client(endpoint, 'sget {} {} {} {} {}'.format(
tid, pid, self.multidimension_scan_vk.values()[0], self.multidimension_scan_vk.keys()[0], ts))
else:
return self.run_client(endpoint, 'get {} {} {} {}'.format(
tid, pid, vk, ts))
def drop(self, endpoint, tid, pid):
return self.run_client(endpoint, 'drop {} {}'.format(tid, pid))
def makesnapshot(self, endpoint, tid_or_tname, pid, role='client', wait=2):
rs = self.run_client(endpoint, 'makesnapshot {} {}'.format(tid_or_tname, pid), role)
time.sleep(wait)
return rs
def pausesnapshot(self, endpoint, tid, pid):
rs = self.run_client(endpoint, 'pausesnapshot {} {}'.format(tid, pid))
time.sleep(1)
return rs
def recoversnapshot(self, endpoint, tid, pid):
rs = self.run_client(endpoint, 'recoversnapshot {} {}'.format(tid, pid))
time.sleep(1)
return rs
def addreplica(self, endpoint, tid, pid, role='client', *slave_endpoints):
rs = self.run_client(endpoint, 'addreplica {} {} {}'.format(tid, pid, ' '.join(slave_endpoints)), role)
time.sleep(1)
return rs
def delreplica(self, endpoint, tid, pid, role='client', *slave_endpoints):
rs = self.run_client(endpoint, 'delreplica {} {} {}'.format(tid, pid, ' '.join(slave_endpoints)), role)
time.sleep(1)
return rs
def loadtable(self, endpoint, tname, tid, pid, ttl=144000, segment=8, isleader='false', *slave_endpoints):
rs = self.run_client(endpoint, 'loadtable {} {} {} {} {} {} {}'.format(
tname, tid, pid, ttl, segment, isleader, ' '.join(slave_endpoints)))
time.sleep(2)
return rs
def changerole(self, endpoint, tid, pid, role):
return self.run_client(endpoint, 'changerole {} {} {}'.format(tid, pid, role))
def sendsnapshot(self, endpoint, tid, pid, slave_endpoint):
return self.run_client(endpoint, 'sendsnapshot {} {} {}'.format(tid, pid, slave_endpoint))
def setexpire(self, endpoint, tid, pid, ttl):
return self.run_client(endpoint, 'setexpire {} {} {}'.format(tid, pid, ttl))
def confset(self, endpoint, conf, value):
return self.run_client(endpoint, 'confset {} {}'.format(conf, value), 'ns_client')
def confget(self, endpoint, conf):
return self.run_client(endpoint, 'confget {}'.format(conf), 'ns_client')
def offlineendpoint(self, endpoint, offline_endpoint, concurrency=''):
return self.run_client(endpoint, 'offlineendpoint {} {}'.format(offline_endpoint, concurrency), 'ns_client')
def recoverendpoint(self, endpoint, offline_endpoint, need_restore='', concurrency=''):
return self.run_client(endpoint, 'recoverendpoint {} {} {}'.format(offline_endpoint, need_restore, concurrency), 'ns_client')
def recovertable(self, endpoint, name, pid, offline_endpoint):
return self.run_client(endpoint, 'recovertable {} {} {}'.format(name, pid, offline_endpoint), 'ns_client')
def changeleader(self, endpoint, tname, pid, candidate_leader=''):
if candidate_leader != '':
return self.run_client(endpoint, 'changeleader {} {} {}'.format(tname, pid, candidate_leader), 'ns_client')
else:
return self.run_client(endpoint, 'changeleader {} {}'.format(tname, pid), 'ns_client')
def settablepartition(self, endpoint, name, partition_file):
return self.run_client(endpoint, 'settablepartition {} {}'.format(name, partition_file), 'ns_client')
def updatetablealive(self, endpoint, name, pid, des_endpint, is_alive):
return self.run_client(endpoint, 'updatetablealive {} {} {} {}'.format(name, pid, des_endpint, is_alive), 'ns_client')
def connectzk(self, endpoint, role='client'):
return self.run_client(endpoint, 'connectzk', role)
def disconnectzk(self, endpoint, role='client'):
return self.run_client(endpoint, 'disconnectzk', role)
def migrate(self, endpoint, src, tname, pid_group, des):
return self.run_client(endpoint, 'migrate {} {} {} {}'.format(src, tname, pid_group, des), 'ns_client')
@staticmethod
def parse_tb(rs, splitor, key_cols_index, value_cols_index):
"""
parse table format response msg
:param rs:
:param splitor:
:param key_cols_index:
:param value_cols_index:
:return:
"""
table_dict = {}
rs_tb = rs.split('\n')
real_conent_flag = False
for line in rs_tb:
if '------' in line:
real_conent_flag = True
continue
if real_conent_flag:
elements = line.split(splitor)
elements = [x for x in elements if x != '']
try:
k = [elements[x] for x in key_cols_index]
v = [elements[x] for x in value_cols_index]
if len(key_cols_index) <= 1:
key = k[0]
else:
key = tuple(k)
table_dict[key] = v
except Exception as e:
traceback.print_exc(file=sys.stdout)
infoLogger.error(e)
if real_conent_flag is False:
return rs
return table_dict
def get_table_status(self, endpoint, tid='', pid=''):
try:
rs = self.run_client(endpoint, 'gettablestatus {} {}'.format(tid, pid))
tablestatus = self.parse_tb(rs, ' ', [0, 1], [2, 3, 4, 5, 6, 7, 8])
tableststus_d = {(int(k[0]), int(k[1])): v for k, v in tablestatus.items()}
if tid != '':
return tableststus_d[(int(tid), int(pid))]
else:
return tableststus_d
except KeyError, e:
traceback.print_exc(file=sys.stdout)
infoLogger.error('table {} is not exist!'.format(e))
def gettablestatus(self, endpoint, tid='', pid=''):
rs = self.run_client(endpoint, 'gettablestatus {} {}'.format(tid, pid))
return rs
@staticmethod
def parse_schema(rs):
arr = rs.strip().split("\n")
schema = []
column_key = []
parts = 0;
for line in arr:
line = line.strip()
if line.find("--------------") != -1:
parts += 1
continue
if parts == 0:
continue
item = line.split(" ")
elements = [x for x in item if x != '']
if parts == 1 and (len(elements) == 3 or len(elements) == 4):
schema.append(elements)
elif parts == 2 and len(elements) == 5:
column_key.append(elements)
return (schema, column_key)
@staticmethod
def parse_db(rs):
arr = rs.strip().split("\n")
dbs = []
start = False
for line in arr:
if line.find("----") != -1:
start = True
continue
if not start:
continue
items = line.split(" ")
for db in items:
if db != '':
dbs.append(db)
break
return dbs
def showschema(self, endpoint, tid='', pid=''):
rs = self.run_client(endpoint, 'showschema {} {}'.format(tid, pid))
return self.parse_schema(rs)
def ns_showschema(self, endpoint, name):
rs = self.run_client(endpoint, 'showschema {}'.format(name), 'ns_client')
return self.parse_schema(rs)
def ns_usedb(self, endpoint, name=''):
rs = self.run_client(endpoint, 'use {}'.format(name), 'ns_client')
return rs
def ns_showdb(self, endpoint):
rs = self.run_client(endpoint, 'showdb', 'ns_client')
return self.parse_db(rs)
def ns_createdb(self, endpoint, name=''):
rs = self.run_client(endpoint, 'createdb {}'.format(name), 'ns_client')
return rs
def ns_dropdb(self, endpoint, name=''):
rs = self.run_client(endpoint, 'dropdb {}'.format(name), 'ns_client')
return rs
def showtablet(self, endpoint):
rs = self.run_client(endpoint, 'showtablet', 'ns_client')
return self.parse_tb(rs, ' ', [0], [2, 3])
def showopstatus(self, endpoint, name='', pid=''):
rs = self.run_client(endpoint, 'showopstatus {} {}'.format(name, pid), 'ns_client')
tablestatus = self.parse_tb(rs, ' ', [0], [1, 4, 8])
tablestatus_d = {(int(k)): v for k, v in tablestatus.items()}
return tablestatus_d
def showtable(self, endpoint, table_name = ''):
cmd = 'showtable {}'.format(table_name)
rs = self.run_client(endpoint, cmd, 'ns_client')
return self.parse_tb(rs, ' ', [0, 1, 2, 3], [4, 5, 6, 7])
def showtable_with_tablename(self, endpoint, table = ''):
cmd = 'showtable {}'.format(table)
return self.run_client(endpoint, cmd, 'ns_client')
def ns_deleteindex(self, endpoint, table_name, index_name):
cmd = 'deleteindex {} {}'.format(table_name, index_name)
return self.run_client(endpoint, cmd, 'ns_client')
@staticmethod
def get_table_meta(nodepath, tid, pid):
table_meta = {}
with open('{}/db/{}_{}/table_meta.txt'.format(nodepath, tid, pid)) as f:
for l in f:
arr = l.split(":")
if (len(arr) < 2):
continue
k = arr[0]
v = arr[1].strip()
if k in table_meta:
v += '|' + table_meta[k]
table_meta[k] = v
return table_meta
def clear_tb_table(self, endpoint):
table_dict = self.get_table_status(endpoint)
if isinstance(table_dict, dict):
for tid_pid in table_dict:
self.drop(endpoint, tid_pid[0], tid_pid[1])
else:
infoLogger.info('gettablestatus empty.')
def clear_ns_table(self, endpoint):
table_dict = self.showtable(endpoint)
if isinstance(table_dict, dict):
tname_tids = table_dict.keys()
tnames = set([i[0] for i in tname_tids])
for tname in tnames:
self.ns_drop(endpoint, tname)
else:
infoLogger.info('showtable empty.')
def cp_db(self, from_node, to_node, tid, pid):
utils.exe_shell('cp -r {from_node}/db/{tid}_{pid} {to_node}/db/'.format(
from_node=from_node, tid=tid, pid=pid, to_node=to_node))
def put_large_datas(self, data_count, thread_count, data='testvalue' * 200):
count = data_count
def put():
for i in range(0, count):
self.put(self.leader, self.tid, self.pid, 'testkey', self.now() - i, data)
threads = []
for _ in range(0, thread_count):
threads.append(threading.Thread(
target=put, args=()))
for t in threads:
t.start()
for t in threads:
t.join()
def get_ns_leader(self):
return utils.exe_shell('cat {}/ns_leader'.format(self.testpath))
def find_new_tb_leader(self, tname, tid, pid):
rs = self.showtable(self.ns_leader, tname)
infoLogger.info(rs)
for (key, value) in rs.items():
if key[1] == str(tid) and key[2] == str(pid):
infoLogger.info(value)
if value[0] == "leader" and value[2] == "yes":
new_leader = key[3]
infoLogger.debug('------new leader:' + new_leader + '-----------')
self.new_tb_leader = new_leader
return new_leader
@staticmethod
def update_conf(nodepath, conf_item, conf_value, role='client'):
conf_file = ''
if role == 'client':
conf_file = 'tablet.flags'
elif role == 'ns_client':
conf_file = 'nameserver.flags'
utils.exe_shell("sed -i '/{}/d' {}/conf/{}".format(conf_item, nodepath, conf_file))
if conf_value is not None:
utils.exe_shell("sed -i '1i--{}={}' {}/conf/{}".format(conf_item, conf_value, nodepath, conf_file))
def get_latest_opid_by_tname_pid(self, tname, pid):
rs = self.run_client(self.ns_leader, 'showopstatus {} {}'.format(tname, pid), 'ns_client')
opstatus = self.parse_tb(rs, ' ', [0], [1, 4, 8])
op_id_arr = []
for op_id in opstatus.keys():
op_id_arr.append(int(op_id))
self.latest_opid = sorted(op_id_arr)[-1]
infoLogger.debug('------latest_opid:' + str(self.latest_opid) + '---------------')
return self.latest_opid
def check_op_done(self, tname):
rs = self.run_client(self.ns_leader, 'showopstatus {} '.format(tname), 'ns_client')
infoLogger.info(rs)
opstatus = self.parse_tb(rs, ' ', [0], [1, 4, 8])
infoLogger.info(opstatus)
for op_id in opstatus.keys():
if opstatus[op_id][1] == "kDoing" or opstatus[op_id][1] == "kInited":
return False
return True
def wait_op_done(self, tname):
for cnt in xrange(10):
if self.check_op_done(tname):
return
time.sleep(2)
def get_op_by_opid(self, op_id):
rs = self.showopstatus(self.ns_leader)
return rs[op_id][0]
def get_task_dict_by_opid(self, tname, opid):
time.sleep(1)
task_dict = collections.OrderedDict()
cmd = "cat {}/warning.log |grep -a -A 10000 '{}'|grep -a \"op_id\[{}\]\"|grep task_type".format(
self.ns_leader_path, tname, opid) \
+ "|awk -F '\\\\[' '{print $3\"]\"$4\"]\"$5}'" \
"|awk -F '\\\\]' '{print $1\",\"$3\",\"$5}'"
infoLogger.info(cmd)
rs = utils.exe_shell(cmd).split('\n')
infoLogger.info(rs)
for x in rs:
x = x.split(',')
task_dict[(int(x[1]), x[2])] = x[0]
self.task_dict = task_dict
def get_tablet_endpoints(self):
return set(conf.tb_endpoints)
def check_tasks(self, op_id, exp_task_list):
self.get_task_dict_by_opid(self.tname, op_id)
tasks = [k[1] for k, v in self.task_dict.items() if k[0] == int(op_id) and v == 'kDone']
infoLogger.info(self.task_dict)
infoLogger.info(op_id)
infoLogger.info([k[1] for k, v in self.task_dict.items()])
infoLogger.info(tasks)
infoLogger.info(exp_task_list)
self.assertEqual(exp_task_list, tasks)
def check_re_add_replica_op(self, op_id):
self.check_tasks(op_id,
['kPauseSnapshot', 'kSendSnapshot', 'kLoadTable', 'kAddReplica',
'kRecoverSnapshot', 'kCheckBinlogSyncProgress', 'kUpdatePartitionStatus'])
def check_re_add_replica_no_send_op(self, op_id):
self.check_tasks(op_id,
['kPauseSnapshot', 'kLoadTable', 'kAddReplica',
'kRecoverSnapshot', 'kCheckBinlogSyncProgress', 'kUpdatePartitionStatus'])
def check_re_add_replica_with_drop_op(self, op_id):
self.check_tasks(op_id,
['kPauseSnapshot', 'kDropTable', 'kSendSnapshot', 'kLoadTable', 'kAddReplica',
'kRecoverSnapshot', 'kCheckBinlogSyncProgress', 'kUpdatePartitionStatus'])
def check_re_add_replica_simplify_op(self, op_id):
self.check_tasks(op_id, ['kAddReplica', 'kCheckBinlogSyncProgress', 'kUpdatePartitionStatus'])
def check_migrate_op(self, op_id):
self.check_tasks(op_id, ['kPauseSnapshot', 'kSendSnapshot', 'kRecoverSnapshot', 'kLoadTable',
'kAddReplica', 'kAddTableInfo', 'kCheckBinlogSyncProgress', 'kDelReplica',
'kUpdateTableInfo', 'kDropTable'])
def ns_setttl(self, endpoint, setttl, table_name, ttl_type, ttl, ts_name = ''):
cmd = '{} {} {} {} {}'.format(setttl, table_name, ttl_type, ttl, ts_name)
return self.run_client(endpoint, cmd, 'ns_client')
def setttl(self, endpoint, setttl, table_name, ttl_type, ttl):
cmd = '{} {} {} {}'.format(setttl, table_name, ttl_type, ttl)
return self.run_client(endpoint, cmd)
def print_table(self, endpoint = '', name = ''):
infoLogger.info('*' * 50)
rs_show = ''
if endpoint != '':
rs_show = self.showtable_with_tablename(endpoint, name)
else:
rs_show = self.showtable_with_tablename(self.ns_leader, name)
infoLogger.info(rs_show)
rs_show = self.parse_tb(rs_show, ' ', [0, 1, 2, 3], [4, 5, 6, 7, 8, 9, 10])
for table_info in rs_show:
infoLogger.info('{} = {}'.format(table_info, rs_show[table_info]))
infoLogger.info('*' * 50)
| 19,787 |
356 |
package com.playtika.test.redis;
import lombok.experimental.UtilityClass;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.testcontainers.containers.GenericContainer;
import java.util.LinkedHashMap;
import java.util.Map;
@UtilityClass
class EnvUtils {
static Map<String, Object> registerRedisEnvironment(ConfigurableEnvironment environment, GenericContainer redis,
RedisProperties properties, int port) {
String host = redis.getContainerIpAddress();
LinkedHashMap<String, Object> map = new LinkedHashMap<>();
map.put("embedded.redis.port", port);
map.put("embedded.redis.host", host);
map.put("embedded.redis.password", properties.getPassword());
map.put("embedded.redis.user", properties.getUser());
MapPropertySource propertySource = new MapPropertySource("embeddedRedisInfo", map);
environment.getPropertySources().addFirst(propertySource);
return map;
}
}
| 402 |
460 |
/*
# This file is part of the Astrometry.net suite.
# Licensed under a 3-clause BSD style license - see LICENSE
*/
#ifndef QUADFILE_H
#define QUADFILE_H
#include <sys/types.h>
#include <stdint.h>
#include "astrometry/qfits_header.h"
#include "astrometry/fitsbin.h"
#include "astrometry/anqfits.h"
typedef struct {
unsigned int numquads;
unsigned int numstars;
int dimquads;
// upper bound of AB distance of quads in this index
double index_scale_upper;
// lower bound
double index_scale_lower;
// unique ID of this index
int indexid;
// healpix covered by this index
int healpix;
// Nside of the healpixelization
int hpnside;
fitsbin_t* fb;
// when reading:
uint32_t* quadarray;
} quadfile_t;
quadfile_t* quadfile_open(const char* fname);
quadfile_t* quadfile_open_fits(anqfits_t* fits);
char* quadfile_get_filename(const quadfile_t* qf);
quadfile_t* quadfile_open_for_writing(const char* quadfname);
quadfile_t* quadfile_open_in_memory(void);
int quadfile_switch_to_reading(quadfile_t* qf);
int quadfile_close(quadfile_t* qf);
// Look at each quad, and ensure that the star ids it contains are all
// less than the number of stars ("numstars"). Returns 0=ok, -1=problem
int quadfile_check(const quadfile_t* qf);
// Copies the star ids of the stars that comprise quad "quadid".
// There will be qf->dimquads such stars.
// (this will be less than starutil.h : DQMAX, for ease of static
// allocation of arrays that will hold quads of stars)
int quadfile_get_stars(const quadfile_t* qf, unsigned int quadid,
unsigned int* stars);
int quadfile_write_quad(quadfile_t* qf, unsigned int* stars);
int quadfile_dimquads(const quadfile_t* qf);
int quadfile_nquads(const quadfile_t* qf);
int quadfile_fix_header(quadfile_t* qf);
int quadfile_write_header(quadfile_t* qf);
double quadfile_get_index_scale_upper_arcsec(const quadfile_t* qf);
double quadfile_get_index_scale_lower_arcsec(const quadfile_t* qf);
qfits_header* quadfile_get_header(const quadfile_t* qf);
int quadfile_write_header_to(quadfile_t* qf, FILE* fid);
int quadfile_write_all_quads_to(quadfile_t* qf, FILE* fid);
#endif
| 835 |
1,424 |
from __future__ import print_function
import argparse
import os
import numpy
from scipy.stats import chi
import torch.utils.data
from torch.autograd import Variable
from networks import NetG
from PIL import Image
parser = argparse.ArgumentParser()
parser.add_argument('--nz', type=int, default=100, help='size of the latent z vector')
parser.add_argument('--niter', type=int, default=10, help='how many paths')
parser.add_argument('--n_steps', type=int, default=23, help='steps to walk')
parser.add_argument('--ngf', type=int, default=64)
parser.add_argument('--ngpu', type=int, default=1, help='number of GPUs to use')
parser.add_argument('--netG', default='netG_epoch_49.pth', help="trained params for G")
opt = parser.parse_args()
output_dir = 'gcircle-walk'
os.system('mkdir -p {}'.format(output_dir))
print(opt)
ngpu = int(opt.ngpu)
nz = int(opt.nz)
ngf = int(opt.ngf)
nc = 3
netG = NetG(ngf, nz, nc, ngpu)
netG.load_state_dict(torch.load(opt.netG, map_location=lambda storage, loc: storage))
netG.eval()
print(netG)
for j in range(opt.niter):
# step 1
r = chi.rvs(df=100)
# step 2
u = numpy.random.normal(0, 1, nz)
w = numpy.random.normal(0, 1, nz)
u /= numpy.linalg.norm(u)
w /= numpy.linalg.norm(w)
v = w - numpy.dot(u, w) * u
v /= numpy.linalg.norm(v)
ndimgs = []
for i in range(opt.n_steps):
t = float(i) / float(opt.n_steps)
# step 3
z = numpy.cos(t * 2 * numpy.pi) * u + numpy.sin(t * 2 * numpy.pi) * v
z *= r
noise_t = z.reshape((1, nz, 1, 1))
noise_t = torch.FloatTensor(noise_t)
noisev = Variable(noise_t)
fake = netG(noisev)
timg = fake[0]
timg = timg.data
timg.add_(1).div_(2)
ndimg = timg.mul(255).clamp(0, 255).byte().permute(1, 2, 0).numpy()
ndimgs.append(ndimg)
print('exporting {} ...'.format(j))
ndimg = numpy.hstack(ndimgs)
im = Image.fromarray(ndimg)
filename = os.sep.join([output_dir, 'gc-{:0>6d}.png'.format(j)])
im.save(filename)
| 916 |
442 |
<reponame>AndreyNudko/ClickHouse-Native-JDBC<filename>clickhouse-native-jdbc/src/test/java/com/github/housepower/jdbc/benchmark/AbstractIBenchmark.java
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.housepower.jdbc.benchmark;
import com.github.housepower.jdbc.AbstractITest;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import org.testcontainers.containers.ClickHouseContainer;
import java.sql.*;
import java.util.Enumeration;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@State(Scope.Thread)
public class AbstractIBenchmark {
public static final ClickHouseContainer container;
static {
container = new ClickHouseContainer(AbstractITest.CLICKHOUSE_IMAGE);
container.start();
}
private final Driver httpDriver = new ru.yandex.clickhouse.ClickHouseDriver();
private final Driver nativeDriver = new com.github.housepower.jdbc.ClickHouseDriver();
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(".*")
.warmupIterations(0)
.measurementIterations(1)
.forks(2)
.build();
new Runner(opt).run();
}
protected void withConnection(WithConnection withConnection, ConnectionType connectionType) throws Exception {
Enumeration<Driver> drivers = DriverManager.getDrivers();
while (drivers.hasMoreElements()) {
DriverManager.deregisterDriver(drivers.nextElement());
}
int port;
switch (connectionType) {
case NATIVE:
Class.forName("com.github.housepower.jdbc.ClickHouseDriver");
DriverManager.registerDriver(nativeDriver);
port = container.getMappedPort(ClickHouseContainer.NATIVE_PORT);
break;
case HTTP:
Class.forName("ru.yandex.clickhouse.ClickHouseDriver");
DriverManager.registerDriver(httpDriver);
port = container.getMappedPort(ClickHouseContainer.HTTP_PORT);
break;
default:
throw new RuntimeException("Never happen");
}
try (Connection connection = DriverManager.getConnection("jdbc:clickhouse://" + container.getHost() + ":" + port)) {
withConnection.apply(connection);
}
}
protected void withStatement(Connection connection, AbstractITest.WithStatement withStatement) throws Exception {
try (Statement stmt = connection.createStatement()) {
withStatement.apply(stmt);
}
}
protected void withPreparedStatement(Connection connection,
String sql,
AbstractITest.WithPreparedStatement withPreparedStatement) throws Exception {
try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
withPreparedStatement.apply(pstmt);
}
}
@FunctionalInterface
public interface WithConnection {
void apply(Connection connection) throws Exception;
}
@FunctionalInterface
public interface WithStatement {
void apply(Statement stmt) throws Exception;
}
@FunctionalInterface
public interface WithPreparedStatement {
void apply(PreparedStatement pstmt) throws Exception;
}
public enum ConnectionType {
NATIVE, HTTP
}
}
| 1,592 |
543 |
/*
* Copyright 2017 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.mirkosertic.bytecoder.classlib.java.nio.charset;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.util.HashMap;
import java.util.Map;
public class CharsetEncoderDecoderCache {
private static final Map<String, CharsetEncoder> encoders = new HashMap<>();
private static final Map<String, CharsetDecoder> decoders = new HashMap<>();
public static CharsetEncoder encoderFor(final Charset charset) {
CharsetEncoder e = encoders.get(charset.name());
if (e == null) {
e = charset.newEncoder();
encoders.put(charset.name(), e);
}
return e;
}
public static CharsetDecoder decoderFor(final Charset charset) {
CharsetDecoder e = decoders.get(charset.name());
if (e == null) {
e = charset.newDecoder();
decoders.put(charset.name(), e);
}
return e;
}
}
| 591 |
504 |
/*-
* host.c --
* Program to test the host request function of customs.
*
* Copyright (c) 1988, 1989 by the Regents of the University of California
* Copyright (c) 1988, 1989 by <NAME>
* Copyright (c) 1989 by Berkeley Softworks
*
* Permission to use, copy, modify, and distribute this
* software and its documentation for any non-commercial purpose
* and without fee is hereby granted, provided that the above copyright
* notice appears in all copies. The University of California,
* Berkeley Softworks and <NAME> make no representations about
* the suitability of this software for any purpose. It is provided
* "as is" without express or implied warranty.
*/
#ifndef lint
static char rcsid[] =
"$Id: host.c,v 1.5 89/11/14 13:46:04 adam Exp $ SPRITE (Berkeley)";
#endif lint
#include "customs.h"
#include <sys/time.h>
main(argc, argv)
int argc;
char **argv;
{
ExportPermit permit;
struct timeval start,
end;
int i;
int max;
max = atoi(argv[1]);
(void)gettimeofday(&start, (struct timezone *)0);
for (i = 0; i < max; i++) {
if (Customs_Host(&permit) != RPC_SUCCESS) {
Customs_PError("HOST");
} else {
printf ("response: id %d, host %x\n", permit.id,
permit.addr.s_addr);
}
}
gettimeofday(&end, (struct timezone *)0);
end.tv_usec -= start.tv_usec;
if (end.tv_usec < 0) {
end.tv_usec += 1000000;
end.tv_sec -= 1;
}
end.tv_sec -= start.tv_sec;
printf ("elapsed time: %d.%06d\n%.6f seconds per rpc\n",
end.tv_sec, end.tv_usec,
((end.tv_sec+end.tv_usec/1e6)/max));
}
| 684 |
312 |
<filename>compliance/model/src/test/java/org/eclipse/rdf4j/model/util/Main.java<gh_stars>100-1000
/*******************************************************************************
* Copyright (c) 2019 Eclipse RDF4J contributors.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Distribution License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*******************************************************************************/
package org.eclipse.rdf4j.model.util;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
public class Main {
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder().include(IsomorphicBenchmark.class.getSimpleName()).forks(1).build();
new Runner(opt).run();
}
}
| 284 |
14,668 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This defines helpful methods for dealing with Callbacks. Because Callbacks
// are implemented using templates, with a class per callback signature, adding
// methods to Callback<> itself is unattractive (lots of extra code gets
// generated). Instead, consider adding methods here.
#ifndef BASE_CALLBACK_HELPERS_H_
#define BASE_CALLBACK_HELPERS_H_
#include <memory>
#include <type_traits>
#include <utility>
#include "base/atomicops.h"
#include "base/bind.h"
#include "base/callback.h"
#include "base/compiler_specific.h"
namespace base {
namespace internal {
template <typename T>
struct IsBaseCallbackImpl : std::false_type {};
template <typename R, typename... Args>
struct IsBaseCallbackImpl<OnceCallback<R(Args...)>> : std::true_type {};
template <typename R, typename... Args>
struct IsBaseCallbackImpl<RepeatingCallback<R(Args...)>> : std::true_type {};
template <typename T>
struct IsOnceCallbackImpl : std::false_type {};
template <typename R, typename... Args>
struct IsOnceCallbackImpl<OnceCallback<R(Args...)>> : std::true_type {};
} // namespace internal
// IsBaseCallback<T>::value is true when T is any of the Closure or Callback
// family of types.
template <typename T>
using IsBaseCallback = internal::IsBaseCallbackImpl<std::decay_t<T>>;
// IsOnceCallback<T>::value is true when T is a OnceClosure or OnceCallback
// type.
template <typename T>
using IsOnceCallback = internal::IsOnceCallbackImpl<std::decay_t<T>>;
// SFINAE friendly enabler allowing to overload methods for both Repeating and
// OnceCallbacks.
//
// Usage:
// template <template <typename> class CallbackType,
// ... other template args ...,
// typename = EnableIfIsBaseCallback<CallbackType>>
// void DoStuff(CallbackType<...> cb, ...);
template <template <typename> class CallbackType>
using EnableIfIsBaseCallback =
std::enable_if_t<IsBaseCallback<CallbackType<void()>>::value>;
namespace internal {
template <typename... Args>
class OnceCallbackHolder final {
public:
OnceCallbackHolder(OnceCallback<void(Args...)> callback,
bool ignore_extra_runs)
: callback_(std::move(callback)), ignore_extra_runs_(ignore_extra_runs) {
DCHECK(callback_);
}
OnceCallbackHolder(const OnceCallbackHolder&) = delete;
OnceCallbackHolder& operator=(const OnceCallbackHolder&) = delete;
void Run(Args... args) {
if (subtle::NoBarrier_AtomicExchange(&has_run_, 1)) {
CHECK(ignore_extra_runs_) << "Both OnceCallbacks returned by "
"base::SplitOnceCallback() were run. "
"At most one of the pair should be run.";
return;
}
DCHECK(callback_);
std::move(callback_).Run(std::forward<Args>(args)...);
}
private:
volatile subtle::Atomic32 has_run_ = 0;
base::OnceCallback<void(Args...)> callback_;
const bool ignore_extra_runs_;
};
} // namespace internal
// Wraps the given OnceCallback and returns two OnceCallbacks with an identical
// signature. On first invokation of either returned callbacks, the original
// callback is invoked. Invoking the remaining callback results in a crash.
template <typename... Args>
std::pair<OnceCallback<void(Args...)>, OnceCallback<void(Args...)>>
SplitOnceCallback(OnceCallback<void(Args...)> callback) {
if (!callback) {
// Empty input begets two empty outputs.
return std::make_pair(OnceCallback<void(Args...)>(),
OnceCallback<void(Args...)>());
}
using Helper = internal::OnceCallbackHolder<Args...>;
auto wrapped_once = base::BindRepeating(
&Helper::Run, std::make_unique<Helper>(std::move(callback),
/*ignore_extra_runs=*/false));
return std::make_pair(wrapped_once, wrapped_once);
}
// ScopedClosureRunner is akin to std::unique_ptr<> for Closures. It ensures
// that the Closure is executed no matter how the current scope exits.
// If you are looking for "ScopedCallback", "CallbackRunner", or
// "CallbackScoper" this is the class you want.
class BASE_EXPORT ScopedClosureRunner {
public:
ScopedClosureRunner();
explicit ScopedClosureRunner(OnceClosure closure);
ScopedClosureRunner(ScopedClosureRunner&& other);
// Runs the current closure if it's set, then replaces it with the closure
// from |other|. This is akin to how unique_ptr frees the contained pointer in
// its move assignment operator. If you need to explicitly avoid running any
// current closure, use ReplaceClosure().
ScopedClosureRunner& operator=(ScopedClosureRunner&& other);
~ScopedClosureRunner();
explicit operator bool() const { return !!closure_; }
// Calls the current closure and resets it, so it wont be called again.
void RunAndReset();
// Replaces closure with the new one releasing the old one without calling it.
void ReplaceClosure(OnceClosure closure);
// Releases the Closure without calling.
OnceClosure Release() WARN_UNUSED_RESULT;
private:
OnceClosure closure_;
};
// Returns a placeholder type that will implicitly convert into a null callback,
// similar to how absl::nullopt / std::nullptr work in conjunction with
// absl::optional and various smart pointer types.
constexpr auto NullCallback() {
return internal::NullCallbackTag();
}
// Returns a placeholder type that will implicitly convert into a callback that
// does nothing, similar to how absl::nullopt / std::nullptr work in conjunction
// with absl::optional and various smart pointer types.
constexpr auto DoNothing() {
return internal::DoNothingCallbackTag();
}
// Similar to the above, but with a type hint. Useful for disambiguating
// among multiple function overloads that take callbacks with different
// signatures:
//
// void F(base::OnceCallback<void()> callback); // 1
// void F(base::OnceCallback<void(int)> callback); // 2
//
// F(base::NullCallbackAs<void()>()); // calls 1
// F(base::DoNothingAs<void(int)>()); // calls 2
template <typename Signature>
constexpr auto NullCallbackAs() {
return internal::NullCallbackTag::WithSignature<Signature>();
}
template <typename Signature>
constexpr auto DoNothingAs() {
return internal::DoNothingCallbackTag::WithSignature<Signature>();
}
// Useful for creating a Closure that will delete a pointer when invoked. Only
// use this when necessary. In most cases MessageLoop::DeleteSoon() is a better
// fit.
template <typename T>
void DeletePointer(T* obj) {
delete obj;
}
} // namespace base
#endif // BASE_CALLBACK_HELPERS_H_
| 2,133 |
319 |
/**
* Copyright (c) 2011, The University of Southampton and the individual 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:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the University of Southampton nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openimaj.math.geometry.shape.util.polygon;
import org.openimaj.math.geometry.shape.util.PolygonUtils;
/**
* Internal contour / tristrip type
*/
public class PolygonNode
{
int active; /* Active flag / vertex count */
boolean hole; /* Hole / external contour flag */
VertexNode[] v = new VertexNode[2]; /* Left and right vertex list ptrs */
PolygonNode next; /* Pointer to next polygon contour */
PolygonNode proxy; /* Pointer to actual structure used */
/**
* @param next
* @param x
* @param y
*/
public PolygonNode( PolygonNode next, double x, double y )
{
/* Make v[LEFT] and v[RIGHT] point to new vertex */
VertexNode vn = new VertexNode( x, y );
this.v[PolygonUtils.LEFT] = vn;
this.v[PolygonUtils.RIGHT] = vn;
this.next = next;
this.proxy = this; /* Initialise proxy to point to p itself */
this.active = 1; // TRUE
}
/**
* @param x
* @param y
*/
public void add_right( double x, double y )
{
VertexNode nv = new VertexNode( x, y );
/* Add vertex nv to the right end of the polygon's vertex list */
proxy.v[PolygonUtils.RIGHT].next = nv;
/* Update proxy->v[RIGHT] to point to nv */
proxy.v[PolygonUtils.RIGHT] = nv;
}
/**
* @param x
* @param y
*/
public void add_left( double x, double y )
{
VertexNode nv = new VertexNode( x, y );
/* Add vertex nv to the left end of the polygon's vertex list */
nv.next = proxy.v[PolygonUtils.LEFT];
/* Update proxy->[LEFT] to point to nv */
proxy.v[PolygonUtils.LEFT] = nv;
}
}
| 1,134 |
1,711 |
/// @brief Include to use 2d array textures.
/// @file gli/texture2d_array.hpp
#pragma once
#include "texture2d.hpp"
namespace gli
{
/// 2d array texture
class texture2d_array : public texture
{
public:
typedef extent2d extent_type;
public:
/// Create an empty texture 2D array
texture2d_array();
/// Create a texture2d_array and allocate a new storage_linear
texture2d_array(
format_type Format,
extent_type const& Extent,
size_type Layers,
size_type Levels,
swizzles_type const& Swizzles = swizzles_type(SWIZZLE_RED, SWIZZLE_GREEN, SWIZZLE_BLUE, SWIZZLE_ALPHA));
/// Create a texture2d_array and allocate a new storage_linear with a complete mipmap chain
texture2d_array(
format_type Format,
extent_type const& Extent,
size_type Layers,
swizzles_type const& Swizzles = swizzles_type(SWIZZLE_RED, SWIZZLE_GREEN, SWIZZLE_BLUE, SWIZZLE_ALPHA));
/// Create a texture2d_array view with an existing storage_linear
explicit texture2d_array(
texture const& Texture);
/// Create a texture2d_array view with an existing storage_linear
texture2d_array(
texture const& Texture,
format_type Format,
size_type BaseLayer, size_type MaxLayer,
size_type BaseFace, size_type MaxFace,
size_type BaseLevel, size_type MaxLevel,
swizzles_type const& Swizzles = swizzles_type(SWIZZLE_RED, SWIZZLE_GREEN, SWIZZLE_BLUE, SWIZZLE_ALPHA));
/// Create a texture view, reference a subset of an exiting texture2d_array instance
texture2d_array(
texture2d_array const& Texture,
size_type BaseLayer, size_type MaxLayer,
size_type BaseLevel, size_type MaxLevel);
/// Create a view of the texture identified by Layer in the texture array
texture2d operator[](size_type Layer) const;
/// Return the dimensions of a texture instance: width and height
extent_type extent(size_type Level = 0) const;
/// Fetch a texel from a texture. The texture format must be uncompressed.
template <typename gen_type>
gen_type load(extent_type const& TexelCoord, size_type Layer, size_type Level) const;
/// Write a texel to a texture. The texture format must be uncompressed.
template <typename gen_type>
void store(extent_type const& TexelCoord, size_type Layer, size_type Level, gen_type const& Texel);
};
}//namespace gli
#include "./core/texture2d_array.inl"
| 838 |
5,169 |
{
"name": "NSObjectCoder",
"version": "1.0",
"summary": "NSObjectCoder is an efficient library that automatically encodes and decodes all attributes of NSObject instance.",
"homepage": "https://github.com/Eric-LeiYang/NSObjectCoder",
"license": {
"type": "MIT"
},
"authors": {
"Eric-LeiYang": "<EMAIL>"
},
"source": {
"git": "https://github.com/Eric-LeiYang/NSObjectCoder.git",
"tag": "1.0"
},
"source_files": "NSObjectCoder/NSObjectCoder/NSObjectCoder/NSObjectCoder.{h,m}",
"requires_arc": true
}
| 210 |
2,003 |
<filename>src/observer/executor/scanner_impl.cc
// Copyright (c) 2015-2017, Baidu.com, Inc. All Rights Reserved
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "observer/executor/scanner_impl.h"
#include <functional>
#include <assert.h>
#include <signal.h>
#include <sys/time.h>
#include "gflags/gflags.h"
#include "common/base/string_number.h"
#include "common/this_thread.h"
#include "observer/executor/random_key_selector.h"
#include "observer/executor/tablet_bucket_key_selector.h"
#include "observer/executor/notification_impl.h"
#include "observer/notification.h"
#include "sdk/rowlock_client.h"
#include "sdk/sdk_utils.h"
#include "sdk/table_impl.h"
#include "types.h"
DECLARE_int32(observer_proc_thread_num);
DECLARE_int32(observer_scanner_thread_num);
DECLARE_int32(observer_ack_conflict_timeout);
DECLARE_int64(observer_max_pending_limit);
DECLARE_int64(observer_ack_timeout_time);
DECLARE_string(flagfile);
DECLARE_string(rowlock_server_ip);
DECLARE_string(rowlock_server_port);
DECLARE_int32(observer_rowlock_client_thread_num);
DECLARE_int32(observer_random_access_thread_num);
DECLARE_bool(mock_rowlock_enable);
using namespace std::placeholders;
namespace tera {
namespace observer {
Scanner* Scanner::GetScanner() { return ScannerImpl::GetInstance(); }
ScannerImpl* ScannerImpl::GetInstance() {
static ScannerImpl instance;
return &instance;
}
ScannerImpl::ScannerImpl()
: table_observe_info_(new std::map<std::string, TableObserveInfo>),
scan_table_threads_(new common::ThreadPool(FLAGS_observer_scanner_thread_num)),
observer_threads_(new common::ThreadPool(FLAGS_observer_proc_thread_num)),
transaction_callback_threads_(
new common::ThreadPool(FLAGS_observer_random_access_thread_num)),
quit_(false),
semaphore_(FLAGS_observer_max_pending_limit) {
VLOG(13) << "FLAGS_observer_proc_thread_num = " << FLAGS_observer_proc_thread_num;
VLOG(13) << "FLAGS_observer_scanner_thread_num = " << FLAGS_observer_scanner_thread_num;
VLOG(13) << "FLAGS_observer_max_pending_limit = " << FLAGS_observer_max_pending_limit;
VLOG(13) << "FLAGS_observer_random_access_thread_num = "
<< FLAGS_observer_random_access_thread_num;
profiling_thread_ = std::thread{&ScannerImpl::Profiling, this};
}
void ScannerImpl::SetOptions(const ScannerOptions& options) { options_ = options; }
void ScannerImpl::SetScanHook(const std::shared_ptr<ScanHook>& hook) { scan_hook_ = hook; }
ScannerImpl::~ScannerImpl() {
Exit();
scan_table_threads_->Stop(true);
transaction_callback_threads_->Stop(false);
observer_threads_->Stop(true);
profiling_thread_.join();
MutexLock locker(&table_mutex_);
// close table
for (auto it = table_observe_info_->begin(); it != table_observe_info_->end(); ++it) {
if (it->second.table) {
delete it->second.table;
}
}
for (auto it = observers_.begin(); it != observers_.end(); ++it) {
delete *it;
}
}
ErrorCode ScannerImpl::Observe(const std::string& table_name, const std::string& column_family,
const std::string& qualifier, Observer* observer) {
// Observe before init
tera::ErrorCode err;
if (!tera_client_) {
LOG(ERROR) << "Init scanner first!";
err.SetFailed(ErrorCode::kSystem, "observe before scanner init");
return err;
}
Column column = {table_name, column_family, qualifier};
{
MutexLock locker(&table_mutex_);
if (!table_observe_info_.unique()) {
// Shared_ptr construct a new copy from the original one.
// Former requests still reading the original shared_ptr
// Write operation executed on the new copy, so as the later requests
table_observe_info_.reset(new std::map<std::string, TableObserveInfo>(*table_observe_info_));
}
if (!(*table_observe_info_)[table_name].table) {
// init table
tera::Table* table = tera_client_->OpenTable(table_name, &err);
if (tera::ErrorCode::kOK != err.GetType()) {
LOG(ERROR) << "open tera table [" << table_name << "] failed, " << err.ToString();
return err;
}
LOG(INFO) << "open tera table [" << table_name << "] succ";
// build map<table_name, table>
(*table_observe_info_)[table_name].table = table;
(*table_observe_info_)[table_name].type = GetTableTransactionType(table);
}
if (!CheckTransactionTypeLegalForTable(observer->GetTransactionType(),
(*table_observe_info_)[table_name].type)) {
LOG(ERROR) << "Transaction type does not match table. table_name: " << table_name
<< " type: " << (*table_observe_info_)[table_name].type
<< " , observer name: " << observer->GetObserverName()
<< " type: " << observer->GetTransactionType();
err.SetFailed(ErrorCode::kSystem, "Transaction type does not match table");
return err;
}
auto it = (*table_observe_info_)[table_name].observe_columns[column].insert(observer);
if (!it.second) {
LOG(ERROR) << "Observer " << observer->GetObserverName() << " observe " << table_name << ":"
<< column_family << ":" << qualifier << " more than once!";
err.SetFailed(ErrorCode::kSystem, "the same observer observe the same column more than once");
return err;
}
observers_.insert(observer);
}
err = key_selector_->Observe(table_name);
LOG(INFO) << "Observer start. table: " << table_name << " cf:qu " << column_family << ":"
<< qualifier << " observer: " << observer->GetObserverName();
return err;
}
bool ScannerImpl::Init() {
tera::ErrorCode err;
if (!tera_client_) {
tera_client_.reset(tera::Client::NewClient(FLAGS_flagfile, &err));
if (tera::ErrorCode::kOK != err.GetType()) {
LOG(ERROR) << "init tera client [" << FLAGS_flagfile << "] failed, " << err.ToString();
return false;
}
}
// init key_selector_
// different selector started by different flags
if (options_.strategy == ScanStrategy::kRandom) {
LOG(INFO) << "random key";
key_selector_.reset(new RandomKeySelector());
} else if (options_.strategy == ScanStrategy::kTabletBucket) {
LOG(INFO) << "tablet bucket key";
key_selector_.reset(new TabletBucketKeySelector(options_.bucket_id, options_.bucket_cnt));
}
return true;
}
bool ScannerImpl::Start() {
for (int32_t idx = 0; idx < FLAGS_observer_scanner_thread_num; ++idx) {
scan_table_threads_->AddTask(std::bind(&ScannerImpl::ScanTable, this));
}
return true;
}
void ScannerImpl::Exit() { quit_ = true; }
tera::Client* ScannerImpl::GetTeraClient() const { return tera_client_.get(); }
void ScannerImpl::ScanTable() {
std::string start_key;
std::string end_key;
std::string table_name;
std::set<Column> observe_columns;
tera::Table* table = nullptr;
ScanHook::Columns filter_columns;
// table and start key will be refreshed.
while (!quit_) {
// when random select strategy this scanner will scan all range of
// table, but tablet bucket strategy will scan range [start_key, end_key)
// again and again
if (key_selector_->SelectRange(&table_name, &start_key, &end_key)) {
LOG(INFO) << "table_name=" << table_name << " start_key=[" << start_key << "] end_key=["
<< end_key << "]";
GetObserveColumns(table_name, &observe_columns);
for (const auto& col : observe_columns) {
filter_columns.insert({col.family, col.qualifier});
}
table = GetTable(table_name);
BeforeScanTable(table_name, filter_columns);
bool scan_ret = DoScanTable(table, observe_columns, start_key, end_key);
AfterScanTable(table_name, filter_columns, scan_ret);
if (scan_ret) {
if (options_.strategy == ScanStrategy::kRandom) {
BeforeScanTable(table_name, filter_columns);
scan_ret = DoScanTable(table, observe_columns, end_key, start_key);
AfterScanTable(table_name, filter_columns, scan_ret);
} else if (options_.strategy == ScanStrategy::kTabletBucket) {
BeforeScanTable(table_name, filter_columns);
scan_ret = DoScanTable(table, observe_columns, start_key, end_key);
AfterScanTable(table_name, filter_columns, scan_ret);
} else {
abort();
}
}
}
}
}
void ScannerImpl::BeforeScanTable(const std::string& table_name, const ScanHook::Columns& columns) {
if (scan_hook_) {
scan_hook_->Before(table_name, columns);
}
}
void ScannerImpl::AfterScanTable(const std::string& table_name, const ScanHook::Columns& columns,
bool scan_ret) {
if (scan_hook_) {
scan_hook_->After(table_name, columns, scan_ret);
}
}
bool ScannerImpl::DoScanTable(tera::Table* table, const std::set<Column>& observe_columns,
const std::string& start_key, const std::string& end_key) {
if (table == nullptr) {
LOG(ERROR) << "table not opened or closed";
return false;
}
LOG(INFO) << "Start scan table. Table name: [" << table->GetName() << "]. Start key: ["
<< start_key << "]";
tera::ScanDescriptor desc(start_key);
desc.SetEnd(end_key);
// Notify stores in single lg
desc.AddColumnFamily(kNotifyColumnFamily);
tera::ErrorCode err;
std::unique_ptr<tera::ResultStream> result_stream(table->Scan(desc, &err));
if (tera::ErrorCode::kOK != err.GetType()) {
LOG(ERROR) << "table scan failed, " << err.ToString();
return false;
}
if (result_stream->Done(&err)) {
return !quit_;
}
bool finished = false;
while (true) {
std::string rowkey;
std::vector<Column> notify_columns;
if (!NextRow(result_stream.get(), table->GetName(), &finished, &rowkey, ¬ify_columns)) {
return finished;
}
if (!TryLockRow(table->GetName(), rowkey)) {
// collision
LOG(INFO) << "[rowlock failed] table=" << table->GetName() << " row=" << rowkey;
return false;
}
VLOG(12) << "[time] read value start. [row] " << rowkey;
std::shared_ptr<AutoRowUnlocker> unlocker(new AutoRowUnlocker(table->GetName(), rowkey));
std::vector<std::shared_ptr<NotifyCell>> notify_cells;
PrepareNotifyCell(table, rowkey, observe_columns, notify_columns, unlocker, ¬ify_cells);
for (uint32_t i = 0; i < notify_cells.size(); ++i) {
AsyncReadCell(notify_cells[i]);
}
}
return true;
}
void ScannerImpl::PrepareNotifyCell(tera::Table* table, const std::string& rowkey,
const std::set<Column>& observe_columns,
const std::vector<Column>& notify_columns,
std::shared_ptr<AutoRowUnlocker> unlocker,
std::vector<std::shared_ptr<NotifyCell>>* notify_cells) {
std::shared_ptr<std::map<std::string, TableObserveInfo>> table_observe_info_read_copy;
{
MutexLock locker(&table_mutex_);
// shared_ptr ref +1
table_observe_info_read_copy = table_observe_info_;
}
for (auto notify_column = notify_columns.begin(); notify_column != notify_columns.end();
++notify_column) {
if (observe_columns.find(*notify_column) == observe_columns.end()) {
LOG(WARNING) << "miss observed column, table_name" << table->GetName()
<< " cf=" << notify_column->family << " qu=" << notify_column->qualifier;
continue;
}
std::map<Column, std::set<Observer*>>& observe_columns =
(*table_observe_info_read_copy)[table->GetName()].observe_columns;
TransactionType type = (*table_observe_info_read_copy)[table->GetName()].type;
for (auto observer = observe_columns[*notify_column].begin();
observer != observe_columns[*notify_column].end(); ++observer) {
semaphore_.Acquire();
std::shared_ptr<NotifyCell> notify_cell(new NotifyCell(semaphore_));
switch (type) {
case kGlobalTransaction:
notify_cell->notify_transaction.reset(tera_client_->NewGlobalTransaction());
if (!notify_cell->notify_transaction) {
LOG(ERROR) << "NewGlobalTransaction failed. Notify cell ignored. table: "
<< table->GetName() << " row: " << rowkey
<< " family: " << notify_column->family
<< " qualifier: " << notify_column->qualifier;
continue;
}
break;
case kSingleRowTransaction:
notify_cell->notify_transaction.reset(table->StartRowTransaction(rowkey));
if (!notify_cell->notify_transaction) {
LOG(ERROR) << "StartRowTransaction failed. Notify cell ignored. table: "
<< table->GetName() << " row: " << rowkey
<< " family: " << notify_column->family
<< " qualifier: " << notify_column->qualifier;
continue;
}
break;
default:
break;
}
notify_cell->table = table;
notify_cell->row = rowkey;
notify_cell->observed_column = *notify_column;
notify_cell->unlocker = unlocker;
notify_cell->observer = *observer;
notify_cells->push_back(notify_cell);
}
}
}
bool ScannerImpl::NextRow(tera::ResultStream* result_stream, const std::string& table_name,
bool* finished, std::string* row, std::vector<Column>* notify_columns) {
tera::ErrorCode err;
// check finish
if (result_stream->Done(&err)) {
*finished = true;
return false;
}
if (tera::ErrorCode::kOK != err.GetType()) {
LOG(ERROR) << "scanning failed" << err.ToString();
return false;
}
notify_columns->clear();
*row = result_stream->RowName();
// scan cell
while (!result_stream->Done(&err) && result_stream->RowName() == *row) {
std::string observe_cf;
std::string observe_qu;
if (quit_) {
return false;
}
if (!ParseNotifyQualifier(result_stream->Qualifier(), &observe_cf, &observe_qu)) {
LOG(WARNING) << "parse notify qualifier failed: " << result_stream->Qualifier();
result_stream->Next();
continue;
}
Column notify_column = {table_name, observe_cf, observe_qu};
notify_columns->push_back(notify_column);
result_stream->Next();
}
return true;
}
// example qualifier: C:url
// C: cf; column: url;
bool ScannerImpl::ParseNotifyQualifier(const std::string& notify_qualifier,
std::string* data_family, std::string* data_qualifier) {
std::vector<std::string> frags;
std::size_t pos = std::string::npos;
std::size_t start_pos = 0;
std::string frag;
// parse cf
pos = notify_qualifier.find_first_of(':', start_pos);
if (pos == std::string::npos) {
LOG(ERROR) << "Parse notify qualifier error: " << notify_qualifier;
return false;
}
frag = notify_qualifier.substr(start_pos, pos - start_pos);
frags.push_back(frag);
start_pos = pos + 1;
pos = notify_qualifier.size();
frag = notify_qualifier.substr(start_pos, pos - start_pos);
frags.push_back(frag);
if (2 != frags.size()) {
return false;
}
if (frags[0] == "" || frags[1] == "") {
return false;
}
*data_family = frags[0];
*data_qualifier = frags[1];
return true;
}
void ScannerImpl::AsyncReadCell(std::shared_ptr<NotifyCell> notify_cell) {
VLOG(12) << "[time] do read value start. [row] " << notify_cell->row << " cf:qu "
<< notify_cell->observed_column.family << ":" << notify_cell->observed_column.qualifier;
tera::RowReader* value_reader = notify_cell->table->NewRowReader(notify_cell->row);
assert(value_reader != NULL);
value_reader->AddColumn(notify_cell->observed_column.family,
notify_cell->observed_column.qualifier);
// transaction read
NotificationContext* context = new NotificationContext();
context->notify_cell = notify_cell;
context->scanner_impl = this;
value_reader->SetContext(context);
value_reader->SetCallBack([](RowReader* value_reader) {
NotificationContext* context = (NotificationContext*)(value_reader->GetContext());
if (!context->scanner_impl->quit_) {
context->scanner_impl->transaction_callback_threads_->AddTask(
std::bind(&ScannerImpl::ValidateCellValue, context->scanner_impl, value_reader));
} else {
// call auto unlocker
delete context;
context = NULL;
delete value_reader;
}
});
if (notify_cell->notify_transaction.get()) {
notify_cell->notify_transaction->Get(value_reader);
} else {
notify_cell->table->Get(value_reader);
}
}
void ScannerImpl::GetObserveColumns(const std::string& table_name,
std::set<Column>* observe_columns) {
observe_columns->clear();
std::shared_ptr<std::map<std::string, TableObserveInfo>> table_observe_info_read_copy;
{
MutexLock locker(&table_mutex_);
// shared_ptr ref +1
table_observe_info_read_copy = table_observe_info_;
}
for (auto it : (*table_observe_info_read_copy)[table_name].observe_columns) {
observe_columns->insert(it.first);
}
}
tera::Table* ScannerImpl::GetTable(const std::string table_name) {
std::shared_ptr<std::map<std::string, TableObserveInfo>> table_observe_info_read_copy;
{
MutexLock locker(&table_mutex_);
table_observe_info_read_copy = table_observe_info_;
}
return (*table_observe_info_read_copy)[table_name].table;
}
void ScannerImpl::Profiling() {
while (!quit_) {
LOG(INFO) << "[Observer Profiling Info] total: " << total_counter_.Get()
<< " failed: " << fail_counter_.Get()
<< " transaction pending: " << observer_threads_->PendingNum();
ThisThread::Sleep(1000);
total_counter_.Clear();
fail_counter_.Clear();
}
}
void ScannerImpl::AsyncReadAck(std::shared_ptr<NotifyCell> notify_cell) {
VLOG(12) << "[time] Check ACK start. [cf:qu] " << notify_cell->observed_column.family
<< notify_cell->observed_column.qualifier;
const std::string& ack_qualifier_prefix = GetAckQualifierPrefix(
notify_cell->observed_column.family, notify_cell->observed_column.qualifier);
// use transaction to read column Ack
std::shared_ptr<tera::Transaction> row_transaction(
notify_cell->table->StartRowTransaction(notify_cell->row));
NotificationContext* context = new NotificationContext();
// read Acks
tera::RowReader* row_reader = notify_cell->table->NewRowReader(notify_cell->row);
const std::string& ack_qualifier =
GetAckQualifier(ack_qualifier_prefix, notify_cell->observer->GetObserverName());
context->ack_qualifier = ack_qualifier;
row_reader->AddColumn(notify_cell->observed_column.family, ack_qualifier);
context->notify_cell = notify_cell;
context->scanner_impl = this;
context->ack_transaction = row_transaction;
row_reader->SetContext(context);
row_reader->SetCallBack([](RowReader* ack_reader) {
NotificationContext* context = (NotificationContext*)(ack_reader->GetContext());
if (!context->scanner_impl->quit_) {
context->scanner_impl->transaction_callback_threads_->AddTask(
std::bind(&ScannerImpl::ValidateAckConfict, context->scanner_impl, ack_reader));
} else {
// call auto unlocker
delete context;
context = NULL;
delete ack_reader;
}
});
row_transaction->Get(row_reader);
}
std::string ScannerImpl::GetAckQualifierPrefix(const std::string& family,
const std::string& qualifier) const {
return family + ":" + qualifier;
}
std::string ScannerImpl::GetAckQualifier(const std::string& prefix,
const std::string& observer_name) const {
return prefix + "+ack_" + observer_name;
}
bool ScannerImpl::TryLockRow(const std::string& table_name, const std::string& row) const {
VLOG(12) << "[time] trylock wait " << table_name << " " << row;
RowlockRequest request;
RowlockResponse response;
std::shared_ptr<RowlockClient> rowlock_client;
if (FLAGS_mock_rowlock_enable == true) {
rowlock_client.reset(new FakeRowlockClient());
} else {
rowlock_client.reset(new RowlockClient());
}
request.set_table_name(table_name);
request.set_row(row);
VLOG(12) << "[time] trylock " << table_name << " " << row;
if (!rowlock_client->TryLock(&request, &response)) {
LOG(ERROR) << "TryLock rpc fail, row: " << row;
return false;
}
if (response.lock_status() != kLockSucc) {
LOG(INFO) << "Lock row fail, row: " << request.row();
return false;
}
VLOG(12) << "[time] lock success " << request.table_name() << " " << request.row();
return true;
}
bool ScannerImpl::CheckTransactionTypeLegalForTable(TransactionType transaction_type,
TransactionType table_type) {
if (transaction_type == table_type) {
return true;
}
if (transaction_type == kNoneTransaction && table_type == kSingleRowTransaction) {
return true;
}
return false;
}
TransactionType ScannerImpl::GetTableTransactionType(tera::Table* table) {
tera::ErrorCode err;
std::shared_ptr<Table> table_ptr;
table_ptr.reset(tera_client_->OpenTable(table->GetName(), &err));
std::shared_ptr<TableImpl> table_impl(
static_cast<TableWrapper*>(table_ptr.get())->GetTableImpl());
TableSchema schema = table_impl->GetTableSchema();
if (IsTransactionTable(schema)) {
std::set<std::string> gtxn_cfs;
FindGlobalTransactionCfs(schema, >xn_cfs);
if (gtxn_cfs.size() > 0) {
return kGlobalTransaction;
}
return kSingleRowTransaction;
}
return kNoneTransaction;
}
void ScannerImpl::ValidateCellValue(RowReader* value_reader) {
std::unique_ptr<NotificationContext> context((NotificationContext*)(value_reader->GetContext()));
std::shared_ptr<NotifyCell> notify_cell = context->notify_cell;
VLOG(12) << "[time] do read value finish. [row] " << notify_cell->row;
std::unique_ptr<RowReader> cell_reader(value_reader);
if (cell_reader->Done()) {
LOG(WARNING) << "No read value, row: " << notify_cell->row;
return;
}
if (tera::ErrorCode::kOK == cell_reader->GetError().GetType()) {
notify_cell->value = cell_reader->Value();
notify_cell->timestamp = cell_reader->Timestamp();
std::shared_ptr<std::map<std::string, TableObserveInfo>> table_observe_info_read_copy;
{
MutexLock locker(&table_mutex_);
table_observe_info_read_copy = table_observe_info_;
}
auto it = table_observe_info_read_copy->find(notify_cell->observed_column.table_name);
if (it == table_observe_info_read_copy->end()) {
LOG(WARNING) << "table not found: " << notify_cell->observed_column.table_name;
return;
}
if (it->second.observe_columns.find(notify_cell->observed_column) ==
it->second.observe_columns.end()) {
LOG(WARNING) << "column not found. cf: " << notify_cell->observed_column.family
<< " qu: " << notify_cell->observed_column.qualifier;
return;
}
if (it->second.observe_columns[notify_cell->observed_column].size() == 0) {
LOG(WARNING) << "no match observers, table=" << notify_cell->observed_column.table_name
<< " cf=" << notify_cell->observed_column.family
<< " qu=" << notify_cell->observed_column.qualifier;
return;
}
if (notify_cell->observer->GetTransactionType() != kGlobalTransaction) {
ObserveCell(notify_cell);
} else {
AsyncReadAck(notify_cell);
}
} else {
LOG(WARNING) << "[read failed] table=" << notify_cell->table->GetName()
<< " cf=" << notify_cell->observed_column.family
<< " qu=" << notify_cell->observed_column.qualifier << " row=" << notify_cell->row
<< " err=" << cell_reader->GetError().GetType()
<< cell_reader->GetError().GetReason();
return;
}
}
void ScannerImpl::ObserveCell(std::shared_ptr<NotifyCell> notify_cell) {
observer_threads_->AddTask([=](int64_t) {
Notification* notification = GetNotification(notify_cell);
notify_cell->observer->OnNotify(notify_cell->notify_transaction.get(), tera_client_.get(),
notify_cell->observed_column.table_name,
notify_cell->observed_column.family,
notify_cell->observed_column.qualifier, notify_cell->row,
notify_cell->value, notify_cell->timestamp, notification);
total_counter_.Inc();
});
}
void ScannerImpl::ValidateAckConfict(RowReader* ack_reader) {
NotificationContext* context = (NotificationContext*)(ack_reader->GetContext());
std::shared_ptr<NotifyCell> notify_cell = context->notify_cell;
std::unique_ptr<RowReader> ack_row_reader(ack_reader);
bool is_collision = false;
if (tera::ErrorCode::kOK == ack_row_reader->GetError().GetType()) {
while (!ack_reader->Done()) {
int64_t latest_observer_start_ts = 0;
if (!StringToNumber(ack_row_reader->Value(), &latest_observer_start_ts)) {
LOG(INFO) << "Convert string to timestamp failed! String: " << ack_row_reader->Value()
<< " row=" << notify_cell->row << " cf=" << notify_cell->observed_column.family
<< " qu=" << notify_cell->observed_column.qualifier;
is_collision = true;
break;
}
// collision check ack ts later than notify ts
if (latest_observer_start_ts >= notify_cell->timestamp &&
notify_cell->notify_transaction->GetStartTimestamp() - latest_observer_start_ts <
FLAGS_observer_ack_conflict_timeout) {
// time too short, collisision, ignore
is_collision = true;
LOG(INFO) << "own collision. row=" << notify_cell->row
<< " cf=" << notify_cell->observed_column.family
<< " qu=" << notify_cell->observed_column.qualifier
<< ", latest observer start_ts=" << latest_observer_start_ts
<< ", observer start_ts=" << notify_cell->notify_transaction->GetStartTimestamp()
<< ", data commit_ts=" << notify_cell->timestamp;
break;
}
ack_row_reader->Next();
}
} else {
LOG(INFO) << "read Acks failed, err=" << ack_row_reader->GetError().GetReason()
<< " row=" << notify_cell->row << " cf=" << notify_cell->observed_column.family
<< " qu=" << notify_cell->observed_column.qualifier;
}
if (!is_collision) {
context->scanner_impl->SetAckVersion(context);
} else {
delete context;
context = NULL;
}
}
void ScannerImpl::SetAckVersion(NotificationContext* ack_context) {
std::shared_ptr<Transaction> row_transaction = ack_context->ack_transaction;
std::shared_ptr<NotifyCell> notify_cell = ack_context->notify_cell;
// set Acks
std::unique_ptr<tera::RowMutation> set_ack_version(
notify_cell->table->NewRowMutation(notify_cell->row));
set_ack_version->Put(notify_cell->observed_column.family, ack_context->ack_qualifier,
std::to_string(notify_cell->notify_transaction->GetStartTimestamp()),
FLAGS_observer_ack_conflict_timeout);
row_transaction->SetContext(ack_context);
row_transaction->SetCommitCallback([](Transaction* ack_transaction) {
NotificationContext* ack_context = (NotificationContext*)(ack_transaction->GetContext());
if (!ack_context->scanner_impl->quit_) {
ack_context->scanner_impl->transaction_callback_threads_->AddTask(std::bind(
&ScannerImpl::SetAckVersionCallBack, ack_context->scanner_impl, ack_transaction));
} else {
delete ack_context;
ack_context = NULL;
}
});
row_transaction->ApplyMutation(set_ack_version.get());
row_transaction->Commit();
}
void ScannerImpl::SetAckVersionCallBack(Transaction* ack_transaction) {
std::unique_ptr<NotificationContext> ack_context(
(NotificationContext*)(ack_transaction->GetContext()));
std::shared_ptr<NotifyCell> notify_cell = ack_context->notify_cell;
if (ack_transaction->GetError().GetType() != tera::ErrorCode::kOK) {
LOG(INFO) << "write Ack failed, row=" << notify_cell->row
<< " err=" << ack_transaction->GetError().GetReason()
<< " cf=" << notify_cell->observed_column.family
<< " qu=" << notify_cell->observed_column.qualifier;
return;
}
VLOG(12) << "[time] ACK mutation finish. [cf:qu] " << notify_cell->observed_column.family
<< notify_cell->observed_column.qualifier;
ObserveCell(notify_cell);
}
} // namespace observer
} // namespace tera
| 11,490 |
407 |
<filename>paas/appmanager/tesla-appmanager-api/src/main/java/com/alibaba/tesla/appmanager/api/provider/AppMetaProvider.java
package com.alibaba.tesla.appmanager.api.provider;
import com.alibaba.tesla.appmanager.common.pagination.Pagination;
import com.alibaba.tesla.appmanager.domain.dto.AppMetaDTO;
import com.alibaba.tesla.appmanager.domain.req.AppMetaQueryReq;
import com.alibaba.tesla.appmanager.domain.req.AppMetaUpdateReq;
/**
* 应用元信息接口
*
* @author <EMAIL>
*/
public interface AppMetaProvider {
/**
* 分页查询应用元信息
*/
Pagination<AppMetaDTO> list(AppMetaQueryReq request);
/**
* 通过应用 ID 查询应用元信息
*/
AppMetaDTO get(String appId);
/**
* 通过应用 ID 删除应用元信息
*/
boolean delete(String appId);
/**
* 保存应用元信息
*/
AppMetaDTO save(AppMetaUpdateReq request);
}
| 421 |
1,123 |
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
#include <quic/api/IoBufQuicBatch.h>
#include <gtest/gtest.h>
#include <quic/client/state/ClientStateMachine.h>
#include <quic/common/test/TestUtils.h>
#include <quic/fizz/client/handshake/FizzClientQuicHandshakeContext.h>
#include <quic/state/StateData.h>
constexpr const auto kNumLoops = 64;
constexpr const auto kMaxBufs = 10;
namespace quic {
namespace testing {
void RunTest(int numBatch) {
folly::EventBase evb;
folly::AsyncUDPSocket sock(&evb);
auto batchWriter = BatchWriterPtr(new test::TestPacketBatchWriter(numBatch));
folly::SocketAddress peerAddress{"127.0.0.1", 1234};
QuicClientConnectionState conn(
FizzClientQuicHandshakeContext::Builder().build());
QuicClientConnectionState::HappyEyeballsState happyEyeballsState;
IOBufQuicBatch ioBufBatch(
std::move(batchWriter),
false,
sock,
peerAddress,
conn.statsCallback,
nullptr /* happyEyeballsState */);
std::string strTest("Test");
for (size_t i = 0; i < kNumLoops; i++) {
auto buf = folly::IOBuf::copyBuffer(strTest.c_str(), strTest.length());
CHECK(ioBufBatch.write(std::move(buf), strTest.length()));
}
// check flush is successful
CHECK(ioBufBatch.flush());
// check we sent all the packets
CHECK_EQ(ioBufBatch.getPktSent(), kNumLoops);
}
TEST(QuicBatch, TestBatchingNone) {
RunTest(1);
}
TEST(QuicBatch, TestBatchingNoFlush) {
RunTest(-1);
}
TEST(QuicBatch, TestBatching) {
RunTest(kMaxBufs);
}
} // namespace testing
} // namespace quic
| 636 |
339 |
<reponame>titusmaxentius/Embroidermodder
#ifndef EMBROIDERMODDER_H
#define EMBROIDERMODDER_H
extern "C" {
#include "embroidery.h"
}
#include <QList>
#include <QHash>
#include <QDir>
#include <QJSEngine>
#include <QFileDialog>
#include <QMdiArea>
#include <QPixmap>
#include <QObject>
#include <QMainWindow>
#include <QMdiSubWindow>
#include <QScrollBar>
#include <QGridLayout>
#include <QLineEdit>
#include <QTextBrowser>
#include <QSplitter>
#include <QTextLayout>
#include <QDialog>
#include <QApplication>
#include <QPainter>
#include <QImage>
#include <QWidget>
#include <QPainterPath>
#include <QPen>
#include <QGraphicsPathItem>
#include <QtCore/qmath.h>
#include <QDockWidget>
#include <QDialog>
#include <QRubberBand>
#include <QBrush>
#include <QToolButton>
#include <QStatusBar>
#include <QUndoCommand>
#include <QPointF>
#include <QTransform>
#include <QDockWidget>
#include <QGraphicsView>
#include <QObject>
#include <QGraphicsScene>
#if QT_VERSION >= 0x050000
//Qt5
#include <QtPrintSupport>
#else
//Qt4
#include <QPrinter>
#endif
class MainWindow;
class BaseObject;
class SelectBox;
class StatusBar;
class StatusBarButton;
class BaseObject;
class View;
class MdiArea;
class MdiWindow;
class StatusBar;
class StatusBarButton;
class CmdPrompt;
class PropertyEditor;
class UndoEditor;
class ArcObject;
class BlockObject;
class CircleObject;
class DimAlignedObject;
class DimAngularObject;
class DimArcLengthObject;
class DimDiameterObject;
class DimLeaderObject;
class DimLinearObject;
class DimOrdinateObject;
class DimRadiusObject;
class EllipseObject;
class EllipseArcObject;
class HatchObject;
class ImageObject;
class InfiniteLineObject;
class LineObject;
class PathObject;
class PointObject;
class PolygonObject;
class PolylineObject;
class RayObject;
class RectObject;
class SplineObject;
class TextMultiObject;
class TextSingleObject;
QT_BEGIN_NAMESPACE
class QAbstractItemModel;
class QAction;
class QCheckBox;
class QComboBox;
class QFileInfo;
class QFontComboBox;
class QGroupBox;
class QLabel;
class QLineEdit;
class QSortFilterProxyModel;
class QTreeView;
class QStandardItemModel;
class QGraphicsScene;
class QUndoStack;
class QUndoGroup;
class QUndoStack;
class QUndoView;
class QDialogButtonBox;
class QTabWidget;
class QComboBox;
class QToolButton;
class QGraphicsItem;
class QSignalMapper;
class QGraphicsItem;
class QGraphicsScene;
class QComboBox;
class QToolBar;
class QCloseEvent;
class QMenu;
class QScriptEngine;
class QScriptEngineDebugger;
class QScriptProgram;
class QUndoStack;
class QDialogButtonBox;
class QGraphicsScene;
class QMdiArea;
class QGraphicsScene;
class QGraphicsView;
class QPainter;
class QImage;
class QString;
class QTextBrowser;
class QVBoxLayout;
class QAction;
class QMenu;
class QContextMenuEvent;
class QSplitter;
class QTimer;
QT_END_NAMESPACE
class LayerManager : public QDialog
{
Q_OBJECT
public:
LayerManager(MainWindow* mw, QWidget *parent = 0);
~LayerManager();
void addLayer(const QString& name,
const bool visible,
const bool frozen,
const qreal zValue,
const QRgb color,
const QString& lineType,
const QString& lineWeight,
const bool print);
private slots:
private:
QStandardItemModel* layerModel;
QSortFilterProxyModel* layerModelSorted;
QTreeView* treeView;
};
// On Mac, if the user drops a file on the app's Dock icon, or uses Open As, then this is how the app actually opens the file.
class Application : public QApplication
{
Q_OBJECT
public:
Application(int argc, char **argv);
void setMainWin(MainWindow* mainWin) { _mainWin = mainWin; }
protected:
virtual bool event(QEvent *e);
private:
MainWindow* _mainWin;
};
class CmdPromptInput : public QLineEdit
{
Q_OBJECT
public:
CmdPromptInput(QWidget* parent = 0);
~CmdPromptInput();
QString curText;
QString defaultPrefix;
QString prefix;
QString lastCmd;
QString curCmd;
bool cmdActive;
bool rapidFireEnabled;
bool isBlinking;
protected:
void contextMenuEvent(QContextMenuEvent *event);
bool eventFilter(QObject *obj, QEvent *event);
signals:
void appendHistory(const QString& txt, int prefixLength);
//These connect to the CmdPrompt signals
void startCommand(const QString& cmd);
void runCommand(const QString& cmd, const QString& cmdtxt);
void deletePressed();
void tabPressed();
void escapePressed();
void upPressed();
void downPressed();
void F1Pressed();
void F2Pressed();
void F3Pressed();
void F4Pressed();
void F5Pressed();
void F6Pressed();
void F7Pressed();
void F8Pressed();
void F9Pressed();
void F10Pressed();
void F11Pressed();
void F12Pressed();
void cutPressed();
void copyPressed();
void pastePressed();
void selectAllPressed();
void undoPressed();
void redoPressed();
void shiftPressed();
void shiftReleased();
void showSettings();
void stopBlinking();
public slots:
void addCommand(const QString& alias, const QString& cmd);
void endCommand();
void processInput(const Qt::Key& rapidChar = Qt::Key_yen);
void checkSelection();
void updateCurrentText(const QString& txt);
void checkEditedText(const QString& txt);
void checkChangedText(const QString& txt);
void checkCursorPosition(int oldpos, int newpos);
private slots:
void copyClip();
void pasteClip();
private:
QHash<QString, QString>* aliasHash;
void changeFormatting(const QList<QTextLayout::FormatRange>& formats);
void clearFormatting();
void applyFormatting();
};
//==========================================================================
class CmdPromptHistory : public QTextBrowser
{
Q_OBJECT
public:
CmdPromptHistory(QWidget* parent = 0);
~CmdPromptHistory();
protected:
void contextMenuEvent(QContextMenuEvent* event);
public slots:
void appendHistory(const QString& txt, int prefixLength);
void startResizeHistory(int y);
void stopResizeHistory(int y);
void resizeHistory(int y);
signals:
void historyAppended(const QString& txt);
private:
int tmpHeight;
QString applyFormatting(const QString& txt, int prefixLength);
};
//==========================================================================
class CmdPromptSplitter : public QSplitter
{
Q_OBJECT
public:
CmdPromptSplitter(QWidget* parent = 0);
~CmdPromptSplitter();
protected:
QSplitterHandle* createHandle();
signals:
void pressResizeHistory(int y);
void releaseResizeHistory(int y);
void moveResizeHistory(int y);
};
//==========================================================================
class CmdPromptHandle : public QSplitterHandle
{
Q_OBJECT
public:
CmdPromptHandle(Qt::Orientation orientation, QSplitter* parent);
~CmdPromptHandle();
protected:
void mousePressEvent(QMouseEvent* e);
void mouseReleaseEvent(QMouseEvent* e);
void mouseMoveEvent(QMouseEvent* e);
signals:
void handlePressed(int y);
void handleReleased(int y);
void handleMoved(int y);
private:
int pressY;
int releaseY;
int moveY;
};
//==========================================================================
class CmdPrompt : public QWidget
{
Q_OBJECT
public:
CmdPrompt(QWidget* parent = 0);
~CmdPrompt();
protected:
public slots:
QString getHistory() { return promptHistory->toHtml(); }
QString getPrefix() { return promptInput->prefix; }
QString getCurrentText() { return promptInput->curText; }
void setCurrentText(const QString& txt) { promptInput->curText = promptInput->prefix + txt; promptInput->setText(promptInput->curText); }
void setHistory(const QString& txt) { promptHistory->setHtml(txt); promptHistory->moveCursor(QTextCursor::End, QTextCursor::MoveAnchor); }
void setPrefix(const QString& txt);
void appendHistory(const QString& txt);
void startResizingTheHistory(int y) { promptHistory->startResizeHistory(y); }
void stopResizingTheHistory(int y) { promptHistory->stopResizeHistory(y); }
void resizeTheHistory(int y) { promptHistory->resizeHistory(y); }
void addCommand(const QString& alias, const QString& cmd) { promptInput->addCommand(alias, cmd); }
void endCommand() { promptInput->endCommand(); }
bool isCommandActive() { return promptInput->cmdActive; }
QString activeCommand() { return promptInput->curCmd; }
QString lastCommand() { return promptInput->lastCmd; }
void processInput() { promptInput->processInput(); }
void enableRapidFire() { promptInput->rapidFireEnabled = true; }
void disableRapidFire() { promptInput->rapidFireEnabled = false; }
bool isRapidFireEnabled() { return promptInput->rapidFireEnabled; }
void alert(const QString& txt);
void startBlinking();
void stopBlinking();
void blink();
void setPromptTextColor(const QColor&);
void setPromptBackgroundColor(const QColor&);
void setPromptFontFamily(const QString&);
void setPromptFontStyle(const QString&);
void setPromptFontSize(int);
void floatingChanged(bool);
void saveHistory(const QString& fileName, bool html);
private slots:
signals:
void appendTheHistory(const QString& txt, int prefixLength);
//For connecting outside of command prompt
void startCommand(const QString& cmd);
void runCommand(const QString& cmd, const QString& cmdtxt);
void deletePressed();
void tabPressed();
void escapePressed();
void upPressed();
void downPressed();
void F1Pressed();
void F2Pressed();
void F3Pressed();
void F4Pressed();
void F5Pressed();
void F6Pressed();
void F7Pressed();
void F8Pressed();
void F9Pressed();
void F10Pressed();
void F11Pressed();
void F12Pressed();
void cutPressed();
void copyPressed();
void pastePressed();
void selectAllPressed();
void undoPressed();
void redoPressed();
void shiftPressed();
void shiftReleased();
void showSettings();
void historyAppended(const QString& txt);
private:
CmdPromptInput* promptInput;
CmdPromptHistory* promptHistory;
QVBoxLayout* promptVBoxLayout;
QFrame* promptDivider;
CmdPromptSplitter* promptSplitter;
QHash<QString, QString>* styleHash;
void updateStyle();
QTimer* blinkTimer;
bool blinkState;
};
class ImageWidget : public QWidget
{
Q_OBJECT
public:
ImageWidget(const QString &filename, QWidget* parent = 0);
~ImageWidget();
bool load(const QString &fileName);
bool save(const QString &fileName);
protected:
void paintEvent(QPaintEvent* event);
private:
QImage img;
};
class MdiWindow: public QMdiSubWindow
{
Q_OBJECT
public:
MdiWindow(const int theIndex, MainWindow* mw, QMdiArea* parent, Qt::WindowFlags wflags);
~MdiWindow();
virtual QSize sizeHint() const;
QString getCurrentFile() { return curFile; }
QString getShortCurrentFile();
View* getView() { return gview; }
QGraphicsScene* getScene() { return gscene; }
QString getCurrentLayer() { return curLayer; }
QRgb getCurrentColor() { return curColor; }
QString getCurrentLineType() { return curLineType; }
QString getCurrentLineWeight() { return curLineWeight; }
void setCurrentLayer(const QString& layer) { curLayer = layer; }
void setCurrentColor(const QRgb& color) { curColor = color; }
void setCurrentLineType(const QString& lineType) { curLineType = lineType; }
void setCurrentLineWeight(const QString& lineWeight) { curLineWeight = lineWeight; }
void designDetails();
bool loadFile(const QString &fileName);
bool saveFile(const QString &fileName);
signals:
void sendCloseMdiWin(MdiWindow*);
public slots:
void closeEvent(QCloseEvent* e);
void onWindowActivated();
void currentLayerChanged(const QString& layer);
void currentColorChanged(const QRgb& color);
void currentLinetypeChanged(const QString& type);
void currentLineweightChanged(const QString& weight);
void updateColorLinetypeLineweight();
void deletePressed();
void escapePressed();
void showViewScrollBars(bool val);
void setViewCrossHairColor(QRgb color);
void setViewBackgroundColor(QRgb color);
void setViewSelectBoxColors(QRgb colorL, QRgb fillL, QRgb colorR, QRgb fillR, int alpha);
void setViewGridColor(QRgb color);
void setViewRulerColor(QRgb color);
void print();
void saveBMC();
void promptHistoryAppended(const QString& txt);
void logPromptInput(const QString& txt);
void promptInputPrevious();
void promptInputNext();
protected:
private:
MainWindow* mainWin;
QMdiArea* mdiArea;
QGraphicsScene* gscene;
View* gview;
bool fileWasLoaded;
QString promptHistory;
QList<QString> promptInputList;
int promptInputNum;
QPrinter printer;
QString curFile;
void setCurrentFile(const QString& fileName);
QString fileExtension(const QString& fileName);
int myIndex;
QString curLayer;
QRgb curColor;
QString curLineType;
QString curLineWeight;
void promptInputPrevNext(bool prev);
};
void initMainWinPointer(MainWindow* mw);
MainWindow* mainWin();
class EmbDetailsDialog : public QDialog
{
Q_OBJECT
public:
EmbDetailsDialog(QGraphicsScene* theScene, QWidget *parent = 0);
~EmbDetailsDialog();
private:
QWidget* mainWidget;
void getInfo();
QWidget* createMainWidget();
QWidget* createHistogram();
QDialogButtonBox* buttonBox;
quint32 stitchesTotal;
quint32 stitchesReal;
quint32 stitchesJump;
quint32 stitchesTrim;
quint32 colorTotal;
quint32 colorChanges;
QRectF boundingRect;
};
class MdiArea : public QMdiArea
{
Q_OBJECT
public:
MdiArea(MainWindow* mw, QWidget* parent = 0);
~MdiArea();
void useBackgroundLogo(bool use);
void useBackgroundTexture(bool use);
void useBackgroundColor(bool use);
void setBackgroundLogo(const QString& fileName);
void setBackgroundTexture(const QString& fileName);
void setBackgroundColor(const QColor& color);
public slots:
void cascade();
void tile();
protected:
virtual void mouseDoubleClickEvent(QMouseEvent* e);
virtual void paintEvent(QPaintEvent* e);
private:
MainWindow* mainWin;
bool useLogo;
bool useTexture;
bool useColor;
QPixmap bgLogo;
QPixmap bgTexture;
QColor bgColor;
void zoomExtentsAllSubWindows();
void forceRepaint();
};
enum COMMAND_ACTIONS
{
ACTION_donothing,
ACTION_new,
ACTION_open,
ACTION_save,
ACTION_saveas,
ACTION_print,
ACTION_designdetails,
ACTION_exit,
ACTION_cut,
ACTION_copy,
ACTION_paste,
ACTION_undo,
ACTION_redo,
// Window Menu
ACTION_windowclose,
ACTION_windowcloseall,
ACTION_windowcascade,
ACTION_windowtile,
ACTION_windownext,
ACTION_windowprevious,
// Help Menu
ACTION_help,
ACTION_changelog,
ACTION_tipoftheday,
ACTION_about,
ACTION_whatsthis,
// Icons
ACTION_icon16,
ACTION_icon24,
ACTION_icon32,
ACTION_icon48,
ACTION_icon64,
ACTION_icon128,
ACTION_settingsdialog,
// Layer ToolBar
ACTION_makelayercurrent,
ACTION_layers,
ACTION_layerselector,
ACTION_layerprevious,
ACTION_colorselector,
ACTION_linetypeselector,
ACTION_lineweightselector,
ACTION_hidealllayers,
ACTION_showalllayers,
ACTION_freezealllayers,
ACTION_thawalllayers,
ACTION_lockalllayers,
ACTION_unlockalllayers,
//Text ToolBar
ACTION_textbold,
ACTION_textitalic,
ACTION_textunderline,
ACTION_textstrikeout,
ACTION_textoverline,
// Zoom ToolBar
ACTION_zoomrealtime,
ACTION_zoomprevious,
ACTION_zoomwindow,
ACTION_zoomdynamic,
ACTION_zoomscale,
ACTION_zoomcenter,
ACTION_zoomin,
ACTION_zoomout,
ACTION_zoomselected,
ACTION_zoomall,
ACTION_zoomextents,
// Pan SubMenu
ACTION_panrealtime,
ACTION_panpoint,
ACTION_panleft,
ACTION_panright,
ACTION_panup,
ACTION_pandown,
ACTION_day,
ACTION_night,
//TODO: ACTION_spellcheck,
//TODO: ACTION_quickselect,
ACTION_null
};
class MainWindow: public QMainWindow
{
Q_OBJECT
public:
MainWindow();
~MainWindow();
MdiArea* getMdiArea();
MainWindow* getApplication();
MdiWindow* activeMdiWindow();
View* activeView();
QGraphicsScene* activeScene();
QUndoStack* activeUndoStack();
void setUndoCleanIcon(bool opened);
virtual void updateMenuToolbarStatusbar();
MainWindow* mainWin;
MdiArea* mdiArea;
CmdPrompt* prompt;
PropertyEditor* dockPropEdit;
UndoEditor* dockUndoEdit;
StatusBar* statusbar;
QList<QGraphicsItem*> cutCopyObjectList;
QString getSettingsGeneralLanguage() { return settings_general_language; }
QString getSettingsGeneralIconTheme() { return settings_general_icon_theme; }
int getSettingsGeneralIconSize() { return settings_general_icon_size; }
bool getSettingsGeneralMdiBGUseLogo() { return settings_general_mdi_bg_use_logo; }
bool getSettingsGeneralMdiBGUseTexture() { return settings_general_mdi_bg_use_texture; }
bool getSettingsGeneralMdiBGUseColor() { return settings_general_mdi_bg_use_color; }
QString getSettingsGeneralMdiBGLogo() { return settings_general_mdi_bg_logo; }
QString getSettingsGeneralMdiBGTexture() { return settings_general_mdi_bg_texture; }
QRgb getSettingsGeneralMdiBGColor() { return settings_general_mdi_bg_color; }
bool getSettingsGeneralTipOfTheDay() { return settings_general_tip_of_the_day; }
int getSettingsGeneralCurrentTip() { return settings_general_current_tip; }
bool getSettingsGeneralSystemHelpBrowser() { return settings_general_system_help_browser; }
bool getSettingsGeneralCheckForUpdates() { return settings_general_check_for_updates; }
bool getSettingsDisplayUseOpenGL() { return settings_display_use_opengl; }
bool getSettingsDisplayRenderHintAA() { return settings_display_renderhint_aa; }
bool getSettingsDisplayRenderHintTextAA() { return settings_display_renderhint_text_aa; }
bool getSettingsDisplayRenderHintSmoothPix() { return settings_display_renderhint_smooth_pix; }
bool getSettingsDisplayRenderHintHighAA() { return settings_display_renderhint_high_aa; }
bool getSettingsDisplayRenderHintNonCosmetic() { return settings_display_renderhint_noncosmetic; }
bool getSettingsDisplayShowScrollBars() { return settings_display_show_scrollbars; }
int getSettingsDisplayScrollBarWidgetNum() { return settings_display_scrollbar_widget_num; }
QRgb getSettingsDisplayCrossHairColor() { return settings_display_crosshair_color; }
QRgb getSettingsDisplayBGColor() { return settings_display_bg_color; }
QRgb getSettingsDisplaySelectBoxLeftColor() { return settings_display_selectbox_left_color; }
QRgb getSettingsDisplaySelectBoxLeftFill() { return settings_display_selectbox_left_fill; }
QRgb getSettingsDisplaySelectBoxRightColor() { return settings_display_selectbox_right_color; }
QRgb getSettingsDisplaySelectBoxRightFill() { return settings_display_selectbox_right_fill; }
quint8 getSettingsDisplaySelectBoxAlpha() { return settings_display_selectbox_alpha; }
qreal getSettingsDisplayZoomScaleIn() { return settings_display_zoomscale_in; }
qreal getSettingsDisplayZoomScaleOut() { return settings_display_zoomscale_out; }
quint8 getSettingsDisplayCrossHairPercent() { return settings_display_crosshair_percent; }
QString getSettingsDisplayUnits() { return settings_display_units; }
QRgb getSettingsPromptTextColor() { return settings_prompt_text_color; }
QRgb getSettingsPromptBGColor() { return settings_prompt_bg_color; }
QString getSettingsPromptFontFamily() { return settings_prompt_font_family; }
QString getSettingsPromptFontStyle() { return settings_prompt_font_style; }
quint8 getSettingsPromptFontSize() { return settings_prompt_font_size; }
bool getSettingsPromptSaveHistory() { return settings_prompt_save_history; }
bool getSettingsPromptSaveHistoryAsHtml() { return settings_prompt_save_history_as_html; }
QString getSettingsPromptSaveHistoryFilename() { return settings_prompt_save_history_filename; }
QString getSettingsCustomFilter() { return settings_opensave_custom_filter; }
QString getSettingsOpenFormat() { return settings_opensave_open_format; }
bool getSettingsOpenThumbnail() { return settings_opensave_open_thumbnail; }
QString getSettingsSaveFormat() { return settings_opensave_save_format; }
bool getSettingsSaveThumbnail() { return settings_opensave_save_thumbnail; }
quint8 getSettingsRecentMaxFiles() { return settings_opensave_recent_max_files; }
quint8 getSettingsOpenSaveTrimDstNumJumps() { return settings_opensave_trim_dst_num_jumps; }
QString getSettingsPrintingDefaultDevice() { return settings_printing_default_device; }
bool getSettingsPrintingUseLastDevice() { return settings_printing_use_last_device; }
bool getSettingsPrintingDisableBG() { return settings_printing_disable_bg; }
bool getSettingsGridShowOnLoad() { return settings_grid_show_on_load; }
bool getSettingsGridShowOrigin() { return settings_grid_show_origin; }
bool getSettingsGridColorMatchCrossHair() { return settings_grid_color_match_crosshair; }
QRgb getSettingsGridColor() { return settings_grid_color; }
bool getSettingsGridLoadFromFile() { return settings_grid_load_from_file; }
QString getSettingsGridType() { return settings_grid_type; }
bool getSettingsGridCenterOnOrigin() { return settings_grid_center_on_origin; }
qreal getSettingsGridCenterX() { return settings_grid_center_x; }
qreal getSettingsGridCenterY() { return settings_grid_center_y; }
qreal getSettingsGridSizeX() { return settings_grid_size_x; }
qreal getSettingsGridSizeY() { return settings_grid_size_y; }
qreal getSettingsGridSpacingX() { return settings_grid_spacing_x; }
qreal getSettingsGridSpacingY() { return settings_grid_spacing_y; }
qreal getSettingsGridSizeRadius() { return settings_grid_size_radius; }
qreal getSettingsGridSpacingRadius() { return settings_grid_spacing_radius; }
qreal getSettingsGridSpacingAngle() { return settings_grid_spacing_angle; }
bool getSettingsRulerShowOnLoad() { return settings_ruler_show_on_load; }
bool getSettingsRulerMetric() { return settings_ruler_metric; }
QRgb getSettingsRulerColor() { return settings_ruler_color; }
quint8 getSettingsRulerPixelSize() { return settings_ruler_pixel_size; }
bool getSettingsQSnapEnabled() { return settings_qsnap_enabled; }
QRgb getSettingsQSnapLocatorColor() { return settings_qsnap_locator_color; }
quint8 getSettingsQSnapLocatorSize() { return settings_qsnap_locator_size; }
quint8 getSettingsQSnapApertureSize() { return settings_qsnap_aperture_size; }
bool getSettingsQSnapEndPoint() { return settings_qsnap_endpoint; }
bool getSettingsQSnapMidPoint() { return settings_qsnap_midpoint; }
bool getSettingsQSnapCenter() { return settings_qsnap_center; }
bool getSettingsQSnapNode() { return settings_qsnap_node; }
bool getSettingsQSnapQuadrant() { return settings_qsnap_quadrant; }
bool getSettingsQSnapIntersection() { return settings_qsnap_intersection; }
bool getSettingsQSnapExtension() { return settings_qsnap_extension; }
bool getSettingsQSnapInsertion() { return settings_qsnap_insertion; }
bool getSettingsQSnapPerpendicular() { return settings_qsnap_perpendicular; }
bool getSettingsQSnapTangent() { return settings_qsnap_tangent; }
bool getSettingsQSnapNearest() { return settings_qsnap_nearest; }
bool getSettingsQSnapApparent() { return settings_qsnap_apparent; }
bool getSettingsQSnapParallel() { return settings_qsnap_parallel; }
bool getSettingsLwtShowLwt() { return settings_lwt_show_lwt; }
bool getSettingsLwtRealRender() { return settings_lwt_real_render; }
qreal getSettingsLwtDefaultLwt() { return settings_lwt_default_lwt; }
bool getSettingsSelectionModePickFirst() { return settings_selection_mode_pickfirst; }
bool getSettingsSelectionModePickAdd() { return settings_selection_mode_pickadd; }
bool getSettingsSelectionModePickDrag() { return settings_selection_mode_pickdrag; }
QRgb getSettingsSelectionCoolGripColor() { return settings_selection_coolgrip_color; }
QRgb getSettingsSelectionHotGripColor() { return settings_selection_hotgrip_color; }
quint8 getSettingsSelectionGripSize() { return settings_selection_grip_size; }
quint8 getSettingsSelectionPickBoxSize() { return settings_selection_pickbox_size; }
QString getSettingsTextFont() { return settings_text_font; }
qreal getSettingsTextSize() { return settings_text_size; }
qreal getSettingsTextAngle() { return settings_text_angle; }
bool getSettingsTextStyleBold() { return settings_text_style_bold; }
bool getSettingsTextStyleItalic() { return settings_text_style_italic; }
bool getSettingsTextStyleUnderline() { return settings_text_style_underline; }
bool getSettingsTextStyleStrikeOut() { return settings_text_style_strikeout; }
bool getSettingsTextStyleOverline() { return settings_text_style_overline; }
void setSettingsGeneralLanguage(const QString& newValue) { settings_general_language = newValue; }
void setSettingsGeneralIconTheme(const QString& newValue) { settings_general_icon_theme = newValue; }
void setSettingsGeneralIconSize(int newValue) { settings_general_icon_size = newValue; }
void setSettingsGeneralMdiBGUseLogo(bool newValue) { settings_general_mdi_bg_use_logo = newValue; }
void setSettingsGeneralMdiBGUseTexture(bool newValue) { settings_general_mdi_bg_use_texture = newValue; }
void setSettingsGeneralMdiBGUseColor(bool newValue) { settings_general_mdi_bg_use_color = newValue; }
void setSettingsGeneralMdiBGLogo(const QString& newValue) { settings_general_mdi_bg_logo = newValue; }
void setSettingsGeneralMdiBGTexture(const QString& newValue) { settings_general_mdi_bg_texture = newValue; }
void setSettingsGeneralMdiBGColor(QRgb newValue) { settings_general_mdi_bg_color = newValue; }
void setSettingsGeneralTipOfTheDay(bool newValue) { settings_general_tip_of_the_day = newValue; }
void setSettingsGeneralCurrentTip(int newValue) { settings_general_current_tip = newValue; }
void setSettingsGeneralSystemHelpBrowser(bool newValue) { settings_general_system_help_browser = newValue; }
void setSettingsGeneralCheckForUpdates(bool newValue) { settings_general_check_for_updates = newValue; }
void setSettingsDisplayUseOpenGL(bool newValue) { settings_display_use_opengl = newValue; }
void setSettingsDisplayRenderHintAA(bool newValue) { settings_display_renderhint_aa = newValue; }
void setSettingsDisplayRenderHintTextAA(bool newValue) { settings_display_renderhint_text_aa = newValue; }
void setSettingsDisplayRenderHintSmoothPix(bool newValue) { settings_display_renderhint_smooth_pix = newValue; }
void setSettingsDisplayRenderHintHighAA(bool newValue) { settings_display_renderhint_high_aa = newValue; }
void setSettingsDisplayRenderHintNonCosmetic(bool newValue) { settings_display_renderhint_noncosmetic = newValue; }
void setSettingsDisplayShowScrollBars(bool newValue) { settings_display_show_scrollbars = newValue; }
void setSettingsDisplayScrollBarWidgetNum(int newValue) { settings_display_scrollbar_widget_num = newValue; }
void setSettingsDisplayCrossHairColor(QRgb newValue) { settings_display_crosshair_color = newValue; }
void setSettingsDisplayBGColor(QRgb newValue) { settings_display_bg_color = newValue; }
void setSettingsDisplaySelectBoxLeftColor(QRgb newValue) { settings_display_selectbox_left_color = newValue; }
void setSettingsDisplaySelectBoxLeftFill(QRgb newValue) { settings_display_selectbox_left_fill = newValue; }
void setSettingsDisplaySelectBoxRightColor(QRgb newValue) { settings_display_selectbox_right_color = newValue; }
void setSettingsDisplaySelectBoxRightFill(QRgb newValue) { settings_display_selectbox_right_fill = newValue; }
void setSettingsDisplaySelectBoxAlpha(quint8 newValue) { settings_display_selectbox_alpha = newValue; }
void setSettingsDisplayZoomScaleIn(qreal newValue) { settings_display_zoomscale_in = newValue; }
void setSettingsDisplayZoomScaleOut(qreal newValue) { settings_display_zoomscale_out = newValue; }
void setSettingsDisplayCrossHairPercent(quint8 newValue) { settings_display_crosshair_percent = newValue; }
void setSettingsDisplayUnits(const QString& newValue) { settings_display_units = newValue; }
void setSettingsPromptTextColor(QRgb newValue) { settings_prompt_text_color = newValue; }
void setSettingsPromptBGColor(QRgb newValue) { settings_prompt_bg_color = newValue; }
void setSettingsPromptFontFamily(const QString& newValue) { settings_prompt_font_family = newValue; }
void setSettingsPromptFontStyle(const QString& newValue) { settings_prompt_font_style = newValue; }
void setSettingsPromptFontSize(quint8 newValue) { settings_prompt_font_size = newValue; }
void setSettingsPromptSaveHistory(bool newValue) { settings_prompt_save_history = newValue; }
void setSettingsPromptSaveHistoryAsHtml(bool newValue) { settings_prompt_save_history_as_html = newValue; }
void setSettingsPromptSaveHistoryFilename(const QString& newValue) { settings_prompt_save_history_filename = newValue; }
void setSettingsCustomFilter(const QString& newValue) { settings_opensave_custom_filter = newValue; }
void setSettingsOpenFormat(const QString& newValue) { settings_opensave_open_format = newValue; }
void setSettingsOpenThumbnail(bool newValue) { settings_opensave_open_thumbnail = newValue; }
void setSettingsSaveFormat(const QString& newValue) { settings_opensave_save_format = newValue; }
void setSettingsSaveThumbnail(bool newValue) { settings_opensave_save_thumbnail = newValue; }
void setSettingsRecentMaxFiles(quint8 newValue) { settings_opensave_recent_max_files = newValue; }
void setSettingsOpenSaveTrimDstNumJumps(quint8 newValue) { settings_opensave_trim_dst_num_jumps = newValue; }
void setSettingsPrintingDefaultDevice(const QString& newValue) { settings_printing_default_device = newValue; }
void setSettingsPrintingUseLastDevice(bool newValue) { settings_printing_use_last_device = newValue; }
void setSettingsPrintingDisableBG(bool newValue) { settings_printing_disable_bg = newValue; }
void setSettingsGridShowOnLoad(bool newValue) { settings_grid_show_on_load = newValue; }
void setSettingsGridShowOrigin(bool newValue) { settings_grid_show_origin = newValue; }
void setSettingsGridColorMatchCrossHair(bool newValue) { settings_grid_color_match_crosshair = newValue; }
void setSettingsGridColor(QRgb newValue) { settings_grid_color = newValue; }
void setSettingsGridLoadFromFile(bool newValue) { settings_grid_load_from_file = newValue; }
void setSettingsGridType(const QString& newValue) { settings_grid_type = newValue; }
void setSettingsGridCenterOnOrigin(bool newValue) { settings_grid_center_on_origin = newValue; }
void setSettingsGridCenterX(qreal newValue) { settings_grid_center_x = newValue; }
void setSettingsGridCenterY(qreal newValue) { settings_grid_center_y = newValue; }
void setSettingsGridSizeX(qreal newValue) { settings_grid_size_x = newValue; }
void setSettingsGridSizeY(qreal newValue) { settings_grid_size_y = newValue; }
void setSettingsGridSpacingX(qreal newValue) { settings_grid_spacing_x = newValue; }
void setSettingsGridSpacingY(qreal newValue) { settings_grid_spacing_y = newValue; }
void setSettingsGridSizeRadius(qreal newValue) { settings_grid_size_radius = newValue; }
void setSettingsGridSpacingRadius(qreal newValue) { settings_grid_spacing_radius = newValue; }
void setSettingsGridSpacingAngle(qreal newValue) { settings_grid_spacing_angle = newValue; }
void setSettingsRulerShowOnLoad(bool newValue) { settings_ruler_show_on_load = newValue; }
void setSettingsRulerMetric(bool newValue) { settings_ruler_metric = newValue; }
void setSettingsRulerColor(QRgb newValue) { settings_ruler_color = newValue; }
void setSettingsRulerPixelSize(quint8 newValue) { settings_ruler_pixel_size = newValue; }
void setSettingsQSnapEnabled(bool newValue) { settings_qsnap_enabled = newValue; }
void setSettingsQSnapLocatorColor(QRgb newValue) { settings_qsnap_locator_color = newValue; }
void setSettingsQSnapLocatorSize(quint8 newValue) { settings_qsnap_locator_size = newValue; }
void setSettingsQSnapApertureSize(quint8 newValue) { settings_qsnap_aperture_size = newValue; }
void setSettingsQSnapEndPoint(bool newValue) { settings_qsnap_endpoint = newValue; }
void setSettingsQSnapMidPoint(bool newValue) { settings_qsnap_midpoint = newValue; }
void setSettingsQSnapCenter(bool newValue) { settings_qsnap_center = newValue; }
void setSettingsQSnapNode(bool newValue) { settings_qsnap_node = newValue; }
void setSettingsQSnapQuadrant(bool newValue) { settings_qsnap_quadrant = newValue; }
void setSettingsQSnapIntersection(bool newValue) { settings_qsnap_intersection = newValue; }
void setSettingsQSnapExtension(bool newValue) { settings_qsnap_extension = newValue; }
void setSettingsQSnapInsertion(bool newValue) { settings_qsnap_insertion = newValue; }
void setSettingsQSnapPerpendicular(bool newValue) { settings_qsnap_perpendicular = newValue; }
void setSettingsQSnapTangent(bool newValue) { settings_qsnap_tangent = newValue; }
void setSettingsQSnapNearest(bool newValue) { settings_qsnap_nearest = newValue; }
void setSettingsQSnapApparent(bool newValue) { settings_qsnap_apparent = newValue; }
void setSettingsQSnapParallel(bool newValue) { settings_qsnap_parallel = newValue; }
void setSettingsLwtShowLwt(bool newValue) { settings_lwt_show_lwt = newValue; }
void setSettingsLwtRealRender(bool newValue) { settings_lwt_real_render = newValue; }
void setSettingsLwtDefaultLwt(qreal newValue) { settings_lwt_default_lwt = newValue; }
void setSettingsSelectionModePickFirst(bool newValue) { settings_selection_mode_pickfirst = newValue; }
void setSettingsSelectionModePickAdd(bool newValue) { settings_selection_mode_pickadd = newValue; }
void setSettingsSelectionModePickDrag(bool newValue) { settings_selection_mode_pickdrag = newValue; }
void setSettingsSelectionCoolGripColor(QRgb newValue) { settings_selection_coolgrip_color = newValue; }
void setSettingsSelectionHotGripColor(QRgb newValue) { settings_selection_hotgrip_color = newValue; }
void setSettingsSelectionGripSize(quint8 newValue) { settings_selection_grip_size = newValue; }
void setSettingsSelectionPickBoxSize(quint8 newValue) { settings_selection_pickbox_size = newValue; }
void setSettingsTextFont(const QString& newValue) { settings_text_font = newValue; }
void setSettingsTextSize(qreal newValue) { settings_text_size = newValue; }
void setSettingsTextAngle(qreal newValue) { settings_text_angle = newValue; }
void setSettingsTextStyleBold(bool newValue) { settings_text_style_bold = newValue; }
void setSettingsTextStyleItalic(bool newValue) { settings_text_style_italic = newValue; }
void setSettingsTextStyleUnderline(bool newValue) { settings_text_style_underline = newValue; }
void setSettingsTextStyleStrikeOut(bool newValue) { settings_text_style_strikeout = newValue; }
void setSettingsTextStyleOverline(bool newValue) { settings_text_style_overline = newValue; }
QHash<int, QAction*> actionHash;
QHash<QString, QToolBar*> toolbarHash;
QHash<QString, QMenu*> menuHash;
QString formatFilterOpen;
QString formatFilterSave;
bool isCommandActive() { return prompt->isCommandActive(); }
QString activeCommand() { return prompt->activeCommand(); }
QString platformString();
public slots:
void enablePromptRapidFire();
void disablePromptRapidFire();
void enableMoveRapidFire();
void disableMoveRapidFire();
void onCloseWindow();
virtual void onCloseMdiWin(MdiWindow*);
void recentMenuAboutToShow();
void onWindowActivated (QMdiSubWindow* w);
void windowMenuAboutToShow();
void windowMenuActivated( bool checked/*int id*/ );
QAction* getAction(int actionEnum);
void updateAllViewScrollBars(bool val);
void updateAllViewCrossHairColors(QRgb color);
void updateAllViewBackgroundColors(QRgb color);
void updateAllViewSelectBoxColors(QRgb colorL, QRgb fillL, QRgb colorR, QRgb fillR, int alpha);
void updateAllViewGridColors(QRgb color);
void updateAllViewRulerColors(QRgb color);
void updatePickAddMode(bool val);
void pickAddModeToggled();
void settingsPrompt();
void settingsDialog(const QString& showTab = QString());
void readSettings();
void writeSettings();
static bool validFileFormat(const QString &fileName);
protected:
virtual void resizeEvent(QResizeEvent*);
void closeEvent(QCloseEvent *event);
QAction* getFileSeparator();
void loadFormats();
private:
QString settings_general_language;
QString settings_general_icon_theme;
int settings_general_icon_size;
bool settings_general_mdi_bg_use_logo;
bool settings_general_mdi_bg_use_texture;
bool settings_general_mdi_bg_use_color;
QString settings_general_mdi_bg_logo;
QString settings_general_mdi_bg_texture;
QRgb settings_general_mdi_bg_color;
bool settings_general_tip_of_the_day;
quint16 settings_general_current_tip;
bool settings_general_system_help_browser;
bool settings_general_check_for_updates;
bool settings_display_use_opengl;
bool settings_display_renderhint_aa;
bool settings_display_renderhint_text_aa;
bool settings_display_renderhint_smooth_pix;
bool settings_display_renderhint_high_aa;
bool settings_display_renderhint_noncosmetic;
bool settings_display_show_scrollbars;
int settings_display_scrollbar_widget_num;
QRgb settings_display_crosshair_color;
QRgb settings_display_bg_color;
QRgb settings_display_selectbox_left_color;
QRgb settings_display_selectbox_left_fill;
QRgb settings_display_selectbox_right_color;
QRgb settings_display_selectbox_right_fill;
quint8 settings_display_selectbox_alpha;
qreal settings_display_zoomscale_in;
qreal settings_display_zoomscale_out;
quint8 settings_display_crosshair_percent;
QString settings_display_units;
QRgb settings_prompt_text_color;
QRgb settings_prompt_bg_color;
QString settings_prompt_font_family;
QString settings_prompt_font_style;
quint8 settings_prompt_font_size;
bool settings_prompt_save_history;
bool settings_prompt_save_history_as_html;
QString settings_prompt_save_history_filename;
QString settings_opensave_custom_filter;
QString settings_opensave_open_format;
bool settings_opensave_open_thumbnail;
QString settings_opensave_save_format;
bool settings_opensave_save_thumbnail;
quint8 settings_opensave_recent_max_files;
QStringList settings_opensave_recent_list_of_files;
QString settings_opensave_recent_directory;
quint8 settings_opensave_trim_dst_num_jumps;
QString settings_printing_default_device;
bool settings_printing_use_last_device;
bool settings_printing_disable_bg;
bool settings_grid_show_on_load;
bool settings_grid_show_origin;
bool settings_grid_color_match_crosshair;
QRgb settings_grid_color;
bool settings_grid_load_from_file;
QString settings_grid_type;
bool settings_grid_center_on_origin;
qreal settings_grid_center_x;
qreal settings_grid_center_y;
qreal settings_grid_size_x;
qreal settings_grid_size_y;
qreal settings_grid_spacing_x;
qreal settings_grid_spacing_y;
qreal settings_grid_size_radius;
qreal settings_grid_spacing_radius;
qreal settings_grid_spacing_angle;
bool settings_ruler_show_on_load;
bool settings_ruler_metric;
QRgb settings_ruler_color;
quint8 settings_ruler_pixel_size;
bool settings_qsnap_enabled;
QRgb settings_qsnap_locator_color;
quint8 settings_qsnap_locator_size;
quint8 settings_qsnap_aperture_size;
bool settings_qsnap_endpoint;
bool settings_qsnap_midpoint;
bool settings_qsnap_center;
bool settings_qsnap_node;
bool settings_qsnap_quadrant;
bool settings_qsnap_intersection;
bool settings_qsnap_extension;
bool settings_qsnap_insertion;
bool settings_qsnap_perpendicular;
bool settings_qsnap_tangent;
bool settings_qsnap_nearest;
bool settings_qsnap_apparent;
bool settings_qsnap_parallel;
bool settings_lwt_show_lwt;
bool settings_lwt_real_render;
qreal settings_lwt_default_lwt;
bool settings_selection_mode_pickfirst;
bool settings_selection_mode_pickadd;
bool settings_selection_mode_pickdrag;
QRgb settings_selection_coolgrip_color;
QRgb settings_selection_hotgrip_color;
quint8 settings_selection_grip_size;
quint8 settings_selection_pickbox_size;
QString settings_text_font;
qreal settings_text_size;
qreal settings_text_angle;
bool settings_text_style_bold;
bool settings_text_style_italic;
bool settings_text_style_underline;
bool settings_text_style_overline;
bool settings_text_style_strikeout;
bool shiftKeyPressedState;
QByteArray layoutState;
int numOfDocs;
int docIndex;
QList<MdiWindow*> listMdiWin;
QMdiSubWindow* findMdiWindow(const QString &fileName);
QString openFilesPath;
QAction* myFileSeparator;
QWizard* wizardTipOfTheDay;
QLabel* labelTipOfTheDay;
QCheckBox* checkBoxTipOfTheDay;
QStringList listTipOfTheDay;
void createAllActions();
QAction* createAction(const QString icon, const QString toolTip, const QString statusTip, bool scripted = false);
//====================================================
//Toolbars
//====================================================
void createAllToolbars();
void createFileToolbar();
void createEditToolbar();
void createViewToolbar();
void createZoomToolbar();
void createPanToolbar();
void createIconToolbar();
void createHelpToolbar();
void createLayerToolbar();
void createPropertiesToolbar();
void createTextToolbar();
void createPromptToolbar();
QToolBar* toolbarFile;
QToolBar* toolbarEdit;
QToolBar* toolbarView;
QToolBar* toolbarZoom;
QToolBar* toolbarPan;
QToolBar* toolbarIcon;
QToolBar* toolbarHelp;
QToolBar* toolbarLayer;
QToolBar* toolbarText;
QToolBar* toolbarProperties;
QToolBar* toolbarPrompt;
//====================================================
//Selectors
//====================================================
QComboBox* layerSelector;
QComboBox* colorSelector;
QComboBox* linetypeSelector;
QComboBox* lineweightSelector;
QFontComboBox* textFontSelector;
QComboBox* textSizeSelector;
//====================================================
//Menus
//====================================================
void createAllMenus();
void createFileMenu();
void createEditMenu();
void createViewMenu();
void createSettingsMenu();
void createWindowMenu();
void createHelpMenu();
QMenu* fileMenu;
QMenu* editMenu;
QMenu* viewMenu;
QMenu* settingsMenu;
QMenu* windowMenu;
QMenu* helpMenu;
//====================================================
//SubMenus
//====================================================
QMenu* recentMenu;
QMenu* zoomMenu;
QMenu* panMenu;
private slots:
void hideUnimplemented();
public slots:
void stub_implement(QString txt);
void stub_testing();
void promptHistoryAppended(const QString& txt);
void logPromptInput(const QString& txt);
void promptInputPrevious();
void promptInputNext();
void runCommand();
void runCommandMain(const QString& cmd);
void runCommandClick(const QString& cmd, qreal x, qreal y);
void runCommandMove(const QString& cmd, qreal x, qreal y);
void runCommandContext(const QString& cmd, const QString& str);
void runCommandPrompt(const QString& cmd, const QString& str);
void newFile();
void openFile(bool recent = false, const QString& recentFile = "");
void openFilesSelected(const QStringList&);
void openrecentfile();
void savefile();
void saveasfile();
void print();
void designDetails();
void exit();
void quit();
void checkForUpdates();
// Help Menu
void tipOfTheDay();
void buttonTipOfTheDayClicked(int);
void checkBoxTipOfTheDayStateChanged(int);
void help();
void changelog();
void about();
void whatsThisContextHelp();
void cut();
void copy();
void paste();
void selectAll();
void closeToolBar(QAction*);
void floatingChangedToolBar(bool);
void toggleGrid();
void toggleRuler();
void toggleLwt();
// Icons
void iconResize(int iconSize);
void icon16();
void icon24();
void icon32();
void icon48();
void icon64();
void icon128();
//Selectors
void layerSelectorIndexChanged(int index);
void colorSelectorIndexChanged(int index);
void linetypeSelectorIndexChanged(int index);
void lineweightSelectorIndexChanged(int index);
void textFontSelectorCurrentFontChanged(const QFont& font);
void textSizeSelectorIndexChanged(int index);
QString textFont();
qreal textSize();
qreal textAngle();
bool textBold();
bool textItalic();
bool textUnderline();
bool textStrikeOut();
bool textOverline();
void setTextFont(const QString& str);
void setTextSize(qreal num);
void setTextAngle(qreal num);
void setTextBold(bool val);
void setTextItalic(bool val);
void setTextUnderline(bool val);
void setTextStrikeOut(bool val);
void setTextOverline(bool val);
QString getCurrentLayer();
QRgb getCurrentColor();
QString getCurrentLineType();
QString getCurrentLineWeight();
// Standard Slots
void undo();
void redo();
bool isShiftPressed();
void setShiftPressed();
void setShiftReleased();
void deletePressed();
void escapePressed();
// Layer Toolbar
void makeLayerActive();
void layerManager();
void layerPrevious();
// Zoom Toolbar
void zoomRealtime();
void zoomPrevious();
void zoomWindow();
void zoomDynamic();
void zoomScale();
void zoomCenter();
void zoomIn();
void zoomOut();
void zoomSelected();
void zoomAll();
void zoomExtents();
// Pan SubMenu
void panrealtime();
void panpoint();
void panLeft();
void panRight();
void panUp();
void panDown();
void dayVision();
void nightVision();
void doNothing();
private:
QJSEngine* engine;
QScriptEngineDebugger* debugger;
void javaInitNatives(QJSEngine* engine);
void javaLoadCommand(const QString& cmdName);
public:
//Natives
void nativeAlert (const QString& txt);
void nativeBlinkPrompt ();
void nativeSetPromptPrefix (const QString& txt);
void nativeAppendPromptHistory (const QString& txt);
void nativeEnablePromptRapidFire ();
void nativeDisablePromptRapidFire ();
void nativeInitCommand ();
void nativeEndCommand ();
void nativeEnableMoveRapidFire ();
void nativeDisableMoveRapidFire ();
void nativeNewFile ();
void nativeOpenFile ();
void nativeExit ();
void nativeHelp ();
void nativeAbout ();
void nativeTipOfTheDay ();
void nativeWindowCascade ();
void nativeWindowTile ();
void nativeWindowClose ();
void nativeWindowCloseAll ();
void nativeWindowNext ();
void nativeWindowPrevious ();
QString nativePlatformString ();
void nativeMessageBox (const QString& type, const QString& title, const QString& text);
void nativeUndo ();
void nativeRedo ();
void nativeIcon16 ();
void nativeIcon24 ();
void nativeIcon32 ();
void nativeIcon48 ();
void nativeIcon64 ();
void nativeIcon128 ();
void nativePanLeft ();
void nativePanRight ();
void nativePanUp ();
void nativePanDown ();
void nativeZoomIn ();
void nativeZoomOut ();
void nativeZoomExtents ();
void nativePrintArea (qreal x, qreal y, qreal w, qreal h);
void nativeDayVision ();
void nativeNightVision ();
void nativeSetBackgroundColor (quint8 r, quint8 g, quint8 b);
void nativeSetCrossHairColor (quint8 r, quint8 g, quint8 b);
void nativeSetGridColor (quint8 r, quint8 g, quint8 b);
QString nativeTextFont ();
qreal nativeTextSize ();
qreal nativeTextAngle ();
bool nativeTextBold ();
bool nativeTextItalic ();
bool nativeTextUnderline ();
bool nativeTextStrikeOut ();
bool nativeTextOverline ();
void nativeSetTextFont (const QString& str);
void nativeSetTextSize (qreal num);
void nativeSetTextAngle (qreal num);
void nativeSetTextBold (bool val);
void nativeSetTextItalic (bool val);
void nativeSetTextUnderline (bool val);
void nativeSetTextStrikeOut (bool val);
void nativeSetTextOverline (bool val);
void nativePreviewOn (int clone, int mode, qreal x, qreal y, qreal data);
void nativePreviewOff ();
void nativeVulcanize ();
void nativeClearRubber ();
bool nativeAllowRubber ();
void nativeSpareRubber (qint64 id);
//TODO: void nativeSetRubberFilter(qint64 id); //TODO: This is so more than 1 rubber object can exist at one time without updating all rubber objects at once
void nativeSetRubberMode (int mode);
void nativeSetRubberPoint (const QString& key, qreal x, qreal y);
void nativeSetRubberText (const QString& key, const QString& txt);
void nativeAddTextMulti (const QString& str, qreal x, qreal y, qreal rot, bool fill, int rubberMode);
void nativeAddTextSingle (const QString& str, qreal x, qreal y, qreal rot, bool fill, int rubberMode);
void nativeAddInfiniteLine (qreal x1, qreal y1, qreal x2, qreal y2, qreal rot);
void nativeAddRay (qreal x1, qreal y1, qreal x2, qreal y2, qreal rot);
void nativeAddLine (qreal x1, qreal y1, qreal x2, qreal y2, qreal rot, int rubberMode);
void nativeAddTriangle (qreal x1, qreal y1, qreal x2, qreal y2, qreal x3, qreal y3, qreal rot, bool fill);
void nativeAddRectangle (qreal x, qreal y, qreal w, qreal h, qreal rot, bool fill, int rubberMode);
void nativeAddRoundedRectangle (qreal x, qreal y, qreal w, qreal h, qreal rad, qreal rot, bool fill);
void nativeAddArc (qreal startX, qreal startY, qreal midX, qreal midY, qreal endX, qreal endY, int rubberMode);
void nativeAddCircle (qreal centerX, qreal centerY, qreal radius, bool fill, int rubberMode);
void nativeAddSlot (qreal centerX, qreal centerY, qreal diameter, qreal length, qreal rot, bool fill, int rubberMode);
void nativeAddEllipse (qreal centerX, qreal centerY, qreal width, qreal height, qreal rot, bool fill, int rubberMode);
void nativeAddPoint (qreal x, qreal y);
void nativeAddRegularPolygon (qreal centerX, qreal centerY, quint16 sides, quint8 mode, qreal rad, qreal rot, bool fill);
void nativeAddPolygon (qreal startX, qreal startY, const QPainterPath& p, int rubberMode);
void nativeAddPolyline (qreal startX, qreal startY, const QPainterPath& p, int rubberMode);
void nativeAddPath (qreal startX, qreal startY, const QPainterPath& p, int rubberMode);
void nativeAddHorizontalDimension (qreal x1, qreal y1, qreal x2, qreal y2, qreal legHeight);
void nativeAddVerticalDimension (qreal x1, qreal y1, qreal x2, qreal y2, qreal legHeight);
void nativeAddImage (const QString& img, qreal x, qreal y, qreal w, qreal h, qreal rot);
void nativeAddDimLeader (qreal x1, qreal y1, qreal x2, qreal y2, qreal rot, int rubberMode);
void nativeSetCursorShape (const QString& str);
qreal nativeCalculateAngle (qreal x1, qreal y1, qreal x2, qreal y2);
qreal nativeCalculateDistance (qreal x1, qreal y1, qreal x2, qreal y2);
qreal nativePerpendicularDistance (qreal px, qreal py, qreal x1, qreal y1, qreal x2, qreal y2);
int nativeNumSelected ();
void nativeSelectAll ();
void nativeAddToSelection (const QPainterPath path, Qt::ItemSelectionMode mode);
void nativeClearSelection ();
void nativeDeleteSelected ();
void nativeCutSelected (qreal x, qreal y);
void nativeCopySelected (qreal x, qreal y);
void nativePasteSelected (qreal x, qreal y);
void nativeMoveSelected (qreal dx, qreal dy);
void nativeScaleSelected (qreal x, qreal y, qreal factor);
void nativeRotateSelected (qreal x, qreal y, qreal rot);
void nativeMirrorSelected (qreal x1, qreal y1, qreal x2, qreal y2);
qreal nativeQSnapX ();
qreal nativeQSnapY ();
qreal nativeMouseX ();
qreal nativeMouseY ();
};
class ImageWidget;
class PreviewDialog : public QFileDialog
{
Q_OBJECT
public:
PreviewDialog(QWidget* parent = 0,
const QString& caption = QString(),
const QString& directory = QString(),
const QString& filter = QString());
~PreviewDialog();
private:
ImageWidget* imgWidget;
};
//Custom Data used in QGraphicsItems
// ( int, const QVariant)
//I.E. object.setData(OBJ_TYPE, OBJ_TYPE_LINE);
//I.E. object.setData(OBJ_LAYER, "OUTLINE");
//I.E. object.setData(OBJ_COLOR, 123);
//I.E. object.setData(OBJ_LTYPE, OBJ_LTYPE_CONT);
//Keys
enum OBJ_KEYS {
OBJ_TYPE = 0, //value type - int: See OBJ_TYPE_VALUES
OBJ_NAME = 1, //value type - str: See OBJ_NAME_VALUES
OBJ_LAYER = 2, //value type - str: "USER", "DEFINED", "STRINGS", etc...
OBJ_COLOR = 3, //value type - int: 0-255 //TODO: Use color chart in formats/format-dxf.h for this
OBJ_LTYPE = 4, //value type - int: See OBJ_LTYPE_VALUES
OBJ_LWT = 5, //value type - int: 0-27
OBJ_RUBBER = 6 //value type - int: See OBJ_RUBBER_VALUES
};
//Values
enum OBJ_TYPE_VALUES {
OBJ_TYPE_NULL = 0, //NOTE: Allow this enum to evaluate false
OBJ_TYPE_BASE = 100000, //NOTE: Values >= 65536 ensure compatibility with qgraphicsitem_cast()
OBJ_TYPE_ARC = 100001,
OBJ_TYPE_BLOCK = 100002,
OBJ_TYPE_CIRCLE = 100003,
OBJ_TYPE_DIMALIGNED = 100004,
OBJ_TYPE_DIMANGULAR = 100005,
OBJ_TYPE_DIMARCLENGTH = 100006,
OBJ_TYPE_DIMDIAMETER = 100007,
OBJ_TYPE_DIMLEADER = 100008,
OBJ_TYPE_DIMLINEAR = 100009,
OBJ_TYPE_DIMORDINATE = 100010,
OBJ_TYPE_DIMRADIUS = 100011,
OBJ_TYPE_ELLIPSE = 100012,
OBJ_TYPE_ELLIPSEARC = 100013,
OBJ_TYPE_RUBBER = 100014,
OBJ_TYPE_GRID = 100015,
OBJ_TYPE_HATCH = 100016,
OBJ_TYPE_IMAGE = 100017,
OBJ_TYPE_INFINITELINE = 100018,
OBJ_TYPE_LINE = 100019,
OBJ_TYPE_PATH = 100020,
OBJ_TYPE_POINT = 100021,
OBJ_TYPE_POLYGON = 100022,
OBJ_TYPE_POLYLINE = 100023,
OBJ_TYPE_RAY = 100024,
OBJ_TYPE_RECTANGLE = 100025,
OBJ_TYPE_SLOT = 100026,
OBJ_TYPE_SPLINE = 100027,
OBJ_TYPE_TEXTMULTI = 100028,
OBJ_TYPE_TEXTSINGLE = 100029
};
//OBJ_NAME_VALUES
const char* const OBJ_NAME_NULL = "Unknown";
const char* const OBJ_NAME_BASE = "Base";
const char* const OBJ_NAME_ARC = "Arc";
const char* const OBJ_NAME_BLOCK = "Block";
const char* const OBJ_NAME_CIRCLE = "Circle";
const char* const OBJ_NAME_DIMALIGNED = "Aligned Dimension";
const char* const OBJ_NAME_DIMANGULAR = "Angular Dimension";
const char* const OBJ_NAME_DIMARCLENGTH = "Arc Length Dimension";
const char* const OBJ_NAME_DIMDIAMETER = "Diameter Dimension";
const char* const OBJ_NAME_DIMLEADER = "Leader Dimension";
const char* const OBJ_NAME_DIMLINEAR = "Linear Dimension";
const char* const OBJ_NAME_DIMORDINATE = "Ordinate Dimension";
const char* const OBJ_NAME_DIMRADIUS = "Radius Dimension";
const char* const OBJ_NAME_ELLIPSE = "Ellipse";
const char* const OBJ_NAME_ELLIPSEARC = "Elliptical Arc";
const char* const OBJ_NAME_RUBBER = "Rubber";
const char* const OBJ_NAME_GRID = "Grid";
const char* const OBJ_NAME_HATCH = "Hatch";
const char* const OBJ_NAME_IMAGE = "Image";
const char* const OBJ_NAME_INFINITELINE = "Infinite Line";
const char* const OBJ_NAME_LINE = "Line";
const char* const OBJ_NAME_PATH = "Path";
const char* const OBJ_NAME_POINT = "Point";
const char* const OBJ_NAME_POLYGON = "Polygon";
const char* const OBJ_NAME_POLYLINE = "Polyline";
const char* const OBJ_NAME_RAY = "Ray";
const char* const OBJ_NAME_RECTANGLE = "Rectangle";
const char* const OBJ_NAME_SLOT = "Slot";
const char* const OBJ_NAME_SPLINE = "Spline";
const char* const OBJ_NAME_TEXTMULTI = "Multi Line Text";
const char* const OBJ_NAME_TEXTSINGLE = "Single Line Text";
enum OBJ_LTYPE_VALUES {
//CAD Linetypes
OBJ_LTYPE_CONT = 0,
OBJ_LTYPE_CENTER = 1,
OBJ_LTYPE_DOT = 2,
OBJ_LTYPE_HIDDEN = 3,
OBJ_LTYPE_PHANTOM = 4,
OBJ_LTYPE_ZIGZAG = 5,
//Embroidery Stitchtypes
OBJ_LTYPE_RUNNING = 6, // __________
OBJ_LTYPE_SATIN = 7, // vvvvvvvvvv
OBJ_LTYPE_FISHBONE = 8, // >>>>>>>>>>
};
enum OBJ_LWT_VALUES {
OBJ_LWT_BYLAYER = -2,
OBJ_LWT_BYBLOCK = -1,
OBJ_LWT_DEFAULT = 0,
OBJ_LWT_01 = 1,
OBJ_LWT_02 = 2,
OBJ_LWT_03 = 3,
OBJ_LWT_04 = 4,
OBJ_LWT_05 = 5,
OBJ_LWT_06 = 6,
OBJ_LWT_07 = 7,
OBJ_LWT_08 = 8,
OBJ_LWT_09 = 9,
OBJ_LWT_10 = 10,
OBJ_LWT_11 = 11,
OBJ_LWT_12 = 12,
OBJ_LWT_13 = 13,
OBJ_LWT_14 = 14,
OBJ_LWT_15 = 15,
OBJ_LWT_16 = 16,
OBJ_LWT_17 = 17,
OBJ_LWT_18 = 18,
OBJ_LWT_19 = 19,
OBJ_LWT_20 = 20,
OBJ_LWT_21 = 21,
OBJ_LWT_22 = 22,
OBJ_LWT_23 = 23,
OBJ_LWT_24 = 24
};
enum OBJ_SNAP_VALUES {
OBJ_SNAP_NULL = 0, //NOTE: Allow this enum to evaluate false
OBJ_SNAP_ENDPOINT = 1,
OBJ_SNAP_MIDPOINT = 2,
OBJ_SNAP_CENTER = 3,
OBJ_SNAP_NODE = 4,
OBJ_SNAP_QUADRANT = 5,
OBJ_SNAP_INTERSECTION = 6,
OBJ_SNAP_EXTENSION = 7,
OBJ_SNAP_INSERTION = 8,
OBJ_SNAP_PERPENDICULAR = 9,
OBJ_SNAP_TANGENT = 10,
OBJ_SNAP_NEAREST = 11,
OBJ_SNAP_APPINTERSECTION = 12,
OBJ_SNAP_PARALLEL = 13
};
enum OBJ_RUBBER_VALUES {
OBJ_RUBBER_OFF = 0, //NOTE: Allow this enum to evaluate false
OBJ_RUBBER_ON = 1, //NOTE: Allow this enum to evaluate true
OBJ_RUBBER_CIRCLE_1P_RAD,
OBJ_RUBBER_CIRCLE_1P_DIA,
OBJ_RUBBER_CIRCLE_2P,
OBJ_RUBBER_CIRCLE_3P,
OBJ_RUBBER_CIRCLE_TTR,
OBJ_RUBBER_CIRCLE_TTT,
OBJ_RUBBER_DIMLEADER_LINE,
OBJ_RUBBER_ELLIPSE_LINE,
OBJ_RUBBER_ELLIPSE_MAJORDIAMETER_MINORRADIUS,
OBJ_RUBBER_ELLIPSE_MAJORRADIUS_MINORRADIUS,
OBJ_RUBBER_ELLIPSE_ROTATION,
OBJ_RUBBER_GRIP,
OBJ_RUBBER_LINE,
OBJ_RUBBER_POLYGON,
OBJ_RUBBER_POLYGON_INSCRIBE,
OBJ_RUBBER_POLYGON_CIRCUMSCRIBE,
OBJ_RUBBER_POLYLINE,
OBJ_RUBBER_IMAGE,
OBJ_RUBBER_RECTANGLE,
OBJ_RUBBER_TEXTSINGLE
};
enum SPARE_RUBBER_VALUES {
SPARE_RUBBER_OFF = 0, //NOTE: Allow this enum to evaluate false
SPARE_RUBBER_PATH,
SPARE_RUBBER_POLYGON,
SPARE_RUBBER_POLYLINE
};
enum PREVIEW_CLONE_VALUES {
PREVIEW_CLONE_NULL = 0, //NOTE: Allow this enum to evaluate false
PREVIEW_CLONE_SELECTED,
PREVIEW_CLONE_RUBBER
};
enum PREVIEW_MODE_VALUES {
PREVIEW_MODE_NULL = 0, //NOTE: Allow this enum to evaluate false
PREVIEW_MODE_MOVE,
PREVIEW_MODE_ROTATE,
PREVIEW_MODE_SCALE
};
const char* const ENABLE_SNAP = "ENABLE_SNAP";
const char* const ENABLE_GRID = "ENABLE_GRID";
const char* const ENABLE_RULER = "ENABLE_RULER";
const char* const ENABLE_ORTHO = "ENABLE_ORTHO";
const char* const ENABLE_POLAR = "ENABLE_POLAR";
const char* const ENABLE_QSNAP = "ENABLE_QSNAP";
const char* const ENABLE_QTRACK = "ENABLE_QTRACK";
const char* const ENABLE_LWT = "ENABLE_LWT";
const char* const ENABLE_REAL = "ENABLE_REAL";
const char* const SCENE_QSNAP_POINT = "SCENE_QSNAP_POINT";
const char* const SCENE_MOUSE_POINT = "SCENE_MOUSE_POINT";
const char* const VIEW_MOUSE_POINT = "VIEW_MOUSE_POINT";
const char* const RUBBER_ROOM = "RUBBER_ROOM";
const char* const VIEW_COLOR_BACKGROUND = "VIEW_COLOR_BACKGROUND";
const char* const VIEW_COLOR_CROSSHAIR = "VIEW_COLOR_CROSSHAIR";
const char* const VIEW_COLOR_GRID = "VIEW_COLOR_GRID";
class BaseObject : public QGraphicsPathItem
{
public:
BaseObject(QGraphicsItem* parent = 0);
virtual ~BaseObject();
enum { Type = OBJ_TYPE_BASE };
virtual int type() const { return Type; }
qint64 objectID() const { return objID; }
QPen objectPen() const { return objPen; }
QColor objectColor() const { return objPen.color(); }
QRgb objectColorRGB() const { return objPen.color().rgb(); }
Qt::PenStyle objectLineType() const { return objPen.style(); }
qreal objectLineWeight() const { return lwtPen.widthF(); }
QPainterPath objectPath() const { return path(); }
int objectRubberMode() const { return objRubberMode; }
QPointF objectRubberPoint(const QString& key) const;
QString objectRubberText(const QString& key) const;
QRectF rect() const { return path().boundingRect(); }
void setRect(const QRectF& r) { QPainterPath p; p.addRect(r); setPath(p); }
void setRect(qreal x, qreal y, qreal w, qreal h) { QPainterPath p; p.addRect(x,y,w,h); setPath(p); }
QLineF line() const { return objLine; }
void setLine(const QLineF& li) { QPainterPath p; p.moveTo(li.p1()); p.lineTo(li.p2()); setPath(p); objLine = li; }
void setLine(qreal x1, qreal y1, qreal x2, qreal y2) { QPainterPath p; p.moveTo(x1,y1); p.lineTo(x2,y2); setPath(p); objLine.setLine(x1,y1,x2,y2); }
void setObjectColor(const QColor& color);
void setObjectColorRGB(QRgb rgb);
void setObjectLineType(Qt::PenStyle lineType);
void setObjectLineWeight(qreal lineWeight);
void setObjectPath(const QPainterPath& p) { setPath(p); }
void setObjectRubberMode(int mode) { objRubberMode = mode; }
void setObjectRubberPoint(const QString& key, const QPointF& point) { objRubberPoints.insert(key, point); }
void setObjectRubberText(const QString& key, const QString& txt) { objRubberTexts.insert(key, txt); }
virtual QRectF boundingRect() const;
virtual QPainterPath shape() const { return path(); }
void drawRubberLine(const QLineF& rubLine, QPainter* painter = 0, const char* colorFromScene = 0);
virtual void vulcanize() = 0;
virtual QPointF mouseSnapPoint(const QPointF& mousePoint) = 0;
virtual QList<QPointF> allGripPoints() = 0;
virtual void gripEdit(const QPointF& before, const QPointF& after) = 0;
protected:
QPen lineWeightPen() const { return lwtPen; }
inline qreal pi() const { return (qAtan(1.0)*4.0); }
inline qreal radians(qreal degree) const { return (degree*pi()/180.0); }
inline qreal degrees(qreal radian) const { return (radian*180.0/pi()); }
void realRender(QPainter* painter, const QPainterPath& renderPath);
private:
QPen objPen;
QPen lwtPen;
QLineF objLine;
int objRubberMode;
QHash<QString, QPointF> objRubberPoints;
QHash<QString, QString> objRubberTexts;
qint64 objID;
};
class ArcObject : public BaseObject
{
public:
ArcObject(qreal startX, qreal startY, qreal midX, qreal midY, qreal endX, qreal endY, QRgb rgb, QGraphicsItem* parent = 0);
ArcObject(ArcObject* obj, QGraphicsItem* parent = 0);
~ArcObject();
enum { Type = OBJ_TYPE_ARC };
virtual int type() const { return Type; }
QPointF objectCenter() const { return scenePos(); }
qreal objectCenterX() const { return scenePos().x(); }
qreal objectCenterY() const { return scenePos().y(); }
qreal objectRadius() const { return rect().width()/2.0*scale(); }
qreal objectStartAngle() const;
qreal objectEndAngle() const;
QPointF objectStartPoint() const;
qreal objectStartX() const;
qreal objectStartY() const;
QPointF objectMidPoint() const;
qreal objectMidX() const;
qreal objectMidY() const;
QPointF objectEndPoint() const;
qreal objectEndX() const;
qreal objectEndY() const;
qreal objectArea() const;
qreal objectArcLength() const;
qreal objectChord() const;
qreal objectIncludedAngle() const;
bool objectClockwise() const;
void setObjectCenter(const QPointF& point);
void setObjectCenter(qreal pointX, qreal pointY);
void setObjectCenterX(qreal pointX);
void setObjectCenterY(qreal pointY);
void setObjectRadius(qreal radius);
void setObjectStartAngle(qreal angle);
void setObjectEndAngle(qreal angle);
void setObjectStartPoint(const QPointF& point);
void setObjectStartPoint(qreal pointX, qreal pointY);
void setObjectMidPoint(const QPointF& point);
void setObjectMidPoint(qreal pointX, qreal pointY);
void setObjectEndPoint(const QPointF& point);
void setObjectEndPoint(qreal pointX, qreal pointY);
void updateRubber(QPainter* painter = 0);
virtual void vulcanize();
virtual QPointF mouseSnapPoint(const QPointF& mousePoint);
virtual QList<QPointF> allGripPoints();
virtual void gripEdit(const QPointF& before, const QPointF& after);
protected:
void paint(QPainter*, const QStyleOptionGraphicsItem*, QWidget*);
private:
void init(qreal startX, qreal startY, qreal midX, qreal midY, qreal endX, qreal endY, QRgb rgb, Qt::PenStyle lineType);
void updatePath();
void calculateArcData(qreal startX, qreal startY, qreal midX, qreal midY, qreal endX, qreal endY);
void updateArcRect(qreal radius);
QPointF arcStartPoint;
QPointF arcMidPoint;
QPointF arcEndPoint;
};
class CircleObject : public BaseObject
{
public:
CircleObject(qreal centerX, qreal centerY, qreal radius, QRgb rgb, QGraphicsItem* parent = 0);
CircleObject(CircleObject* obj, QGraphicsItem* parent = 0);
~CircleObject();
enum { Type = OBJ_TYPE_CIRCLE };
virtual int type() const { return Type; }
QPainterPath objectSavePath() const;
QPointF objectCenter() const { return scenePos(); }
qreal objectCenterX() const { return scenePos().x(); }
qreal objectCenterY() const { return scenePos().y(); }
qreal objectRadius() const { return rect().width()/2.0*scale(); }
qreal objectDiameter() const { return rect().width()*scale(); }
qreal objectArea() const { return pi()*objectRadius()*objectRadius(); }
qreal objectCircumference() const { return pi()*objectDiameter(); }
QPointF objectQuadrant0() const { return objectCenter() + QPointF(objectRadius(), 0); }
QPointF objectQuadrant90() const { return objectCenter() + QPointF(0,-objectRadius()); }
QPointF objectQuadrant180() const { return objectCenter() + QPointF(-objectRadius(),0); }
QPointF objectQuadrant270() const { return objectCenter() + QPointF(0, objectRadius()); }
void setObjectCenter(const QPointF& center);
void setObjectCenter(qreal centerX, qreal centerY);
void setObjectCenterX(qreal centerX);
void setObjectCenterY(qreal centerY);
void setObjectRadius(qreal radius);
void setObjectDiameter(qreal diameter);
void setObjectArea(qreal area);
void setObjectCircumference(qreal circumference);
void updateRubber(QPainter* painter = 0);
virtual void vulcanize();
virtual QPointF mouseSnapPoint(const QPointF& mousePoint);
virtual QList<QPointF> allGripPoints();
virtual void gripEdit(const QPointF& before, const QPointF& after);
protected:
void paint(QPainter*, const QStyleOptionGraphicsItem*, QWidget*);
private:
void init(qreal centerX, qreal centerY, qreal radius, QRgb rgb, Qt::PenStyle lineType);
void updatePath();
};
class DimLeaderObject : public BaseObject
{
public:
DimLeaderObject(qreal x1, qreal y1, qreal x2, qreal y2, QRgb rgb, QGraphicsItem* parent = 0);
DimLeaderObject(DimLeaderObject* obj, QGraphicsItem* parent = 0);
~DimLeaderObject();
enum ArrowStyle
{
NoArrow, //NOTE: Allow this enum to evaluate false
Open,
Closed,
Dot,
Box,
Tick
};
enum lineStyle
{
NoLine, //NOTE: Allow this enum to evaluate false
Flared,
Fletching
};
enum { Type = OBJ_TYPE_DIMLEADER };
virtual int type() const { return Type; }
QPointF objectEndPoint1() const;
QPointF objectEndPoint2() const;
QPointF objectMidPoint() const;
qreal objectX1() const { return objectEndPoint1().x(); }
qreal objectY1() const { return objectEndPoint1().y(); }
qreal objectX2() const { return objectEndPoint2().x(); }
qreal objectY2() const { return objectEndPoint2().y(); }
qreal objectDeltaX() const { return (objectX2() - objectX1()); }
qreal objectDeltaY() const { return (objectY2() - objectY1()); }
qreal objectAngle() const;
qreal objectLength() const { return line().length(); }
void setObjectEndPoint1(const QPointF& endPt1);
void setObjectEndPoint1(qreal x1, qreal y1);
void setObjectEndPoint2(const QPointF& endPt2);
void setObjectEndPoint2(qreal x2, qreal y2);
void setObjectX1(qreal x) { setObjectEndPoint1(x, objectY1()); }
void setObjectY1(qreal y) { setObjectEndPoint1(objectX1(), y); }
void setObjectX2(qreal x) { setObjectEndPoint2(x, objectY2()); }
void setObjectY2(qreal y) { setObjectEndPoint2(objectX2(), y); }
void updateRubber(QPainter* painter = 0);
virtual void vulcanize();
virtual QPointF mouseSnapPoint(const QPointF& mousePoint);
virtual QList<QPointF> allGripPoints();
virtual void gripEdit(const QPointF& before, const QPointF& after);
protected:
void paint(QPainter*, const QStyleOptionGraphicsItem*, QWidget*);
private:
void init(qreal x1, qreal y1, qreal x2, qreal y2, QRgb rgb, Qt::PenStyle lineType);
bool curved;
bool filled;
void updateLeader();
QPainterPath lineStylePath;
QPainterPath arrowStylePath;
qreal arrowStyleAngle;
qreal arrowStyleLength;
qreal lineStyleAngle;
qreal lineStyleLength;
};
class EllipseObject : public BaseObject
{
public:
EllipseObject(qreal centerX, qreal centerY, qreal width, qreal height, QRgb rgb, QGraphicsItem* parent = 0);
EllipseObject(EllipseObject* obj, QGraphicsItem* parent = 0);
~EllipseObject();
enum { Type = OBJ_TYPE_ELLIPSE };
virtual int type() const { return Type; }
QPainterPath objectSavePath() const;
QPointF objectCenter() const { return scenePos(); }
qreal objectCenterX() const { return scenePos().x(); }
qreal objectCenterY() const { return scenePos().y(); }
qreal objectRadiusMajor() const { return qMax(rect().width(), rect().height())/2.0*scale(); }
qreal objectRadiusMinor() const { return qMin(rect().width(), rect().height())/2.0*scale(); }
qreal objectDiameterMajor() const { return qMax(rect().width(), rect().height())*scale(); }
qreal objectDiameterMinor() const { return qMin(rect().width(), rect().height())*scale(); }
qreal objectWidth() const { return rect().width()*scale(); }
qreal objectHeight() const { return rect().height()*scale(); }
QPointF objectQuadrant0() const;
QPointF objectQuadrant90() const;
QPointF objectQuadrant180() const;
QPointF objectQuadrant270() const;
void setObjectSize(qreal width, qreal height);
void setObjectCenter(const QPointF& center);
void setObjectCenter(qreal centerX, qreal centerY);
void setObjectCenterX(qreal centerX);
void setObjectCenterY(qreal centerY);
void setObjectRadiusMajor(qreal radius);
void setObjectRadiusMinor(qreal radius);
void setObjectDiameterMajor(qreal diameter);
void setObjectDiameterMinor(qreal diameter);
void updateRubber(QPainter* painter = 0);
virtual void vulcanize();
virtual QPointF mouseSnapPoint(const QPointF& mousePoint);
virtual QList<QPointF> allGripPoints();
virtual void gripEdit(const QPointF& before, const QPointF& after);
protected:
void paint(QPainter*, const QStyleOptionGraphicsItem*, QWidget*);
private:
void init(qreal centerX, qreal centerY, qreal width, qreal height, QRgb rgb, Qt::PenStyle lineType);
void updatePath();
};
class ImageObject : public BaseObject
{
public:
ImageObject(qreal x, qreal y, qreal w, qreal h, QRgb rgb, QGraphicsItem* parent = 0);
ImageObject(ImageObject* obj, QGraphicsItem* parent = 0);
~ImageObject();
enum { Type = OBJ_TYPE_IMAGE };
virtual int type() const { return Type; }
QPointF objectTopLeft() const;
QPointF objectTopRight() const;
QPointF objectBottomLeft() const;
QPointF objectBottomRight() const;
qreal objectWidth() const { return rect().width()*scale(); }
qreal objectHeight() const { return rect().height()*scale(); }
qreal objectArea() const { return qAbs(objectWidth()*objectHeight()); }
void setObjectRect(qreal x, qreal y, qreal w, qreal h);
void updateRubber(QPainter* painter = 0);
virtual void vulcanize();
virtual QPointF mouseSnapPoint(const QPointF& mousePoint);
virtual QList<QPointF> allGripPoints();
virtual void gripEdit(const QPointF& before, const QPointF& after);
protected:
void paint(QPainter*, const QStyleOptionGraphicsItem*, QWidget*);
private:
void init(qreal x, qreal y, qreal w, qreal h, QRgb rgb, Qt::PenStyle lineType);
void updatePath();
};
class LineObject : public BaseObject
{
public:
LineObject(qreal x1, qreal y1, qreal x2, qreal y2, QRgb rgb, QGraphicsItem* parent = 0);
LineObject(LineObject* obj, QGraphicsItem* parent = 0);
~LineObject();
enum { Type = OBJ_TYPE_LINE };
virtual int type() const { return Type; }
QPainterPath objectSavePath() const;
QPointF objectEndPoint1() const { return scenePos(); }
QPointF objectEndPoint2() const;
QPointF objectMidPoint() const;
qreal objectX1() const { return objectEndPoint1().x(); }
qreal objectY1() const { return objectEndPoint1().y(); }
qreal objectX2() const { return objectEndPoint2().x(); }
qreal objectY2() const { return objectEndPoint2().y(); }
qreal objectDeltaX() const { return (objectX2() - objectX1()); }
qreal objectDeltaY() const { return (objectY2() - objectY1()); }
qreal objectAngle() const;
qreal objectLength() const { return line().length()*scale(); }
void setObjectEndPoint1(const QPointF& endPt1);
void setObjectEndPoint1(qreal x1, qreal y1);
void setObjectEndPoint2(const QPointF& endPt2);
void setObjectEndPoint2(qreal x2, qreal y2);
void setObjectX1(qreal x) { setObjectEndPoint1(x, objectY1()); }
void setObjectY1(qreal y) { setObjectEndPoint1(objectX1(), y); }
void setObjectX2(qreal x) { setObjectEndPoint2(x, objectY2()); }
void setObjectY2(qreal y) { setObjectEndPoint2(objectX2(), y); }
void updateRubber(QPainter* painter = 0);
virtual void vulcanize();
virtual QPointF mouseSnapPoint(const QPointF& mousePoint);
virtual QList<QPointF> allGripPoints();
virtual void gripEdit(const QPointF& before, const QPointF& after);
protected:
void paint(QPainter*, const QStyleOptionGraphicsItem*, QWidget*);
private:
void init(qreal x1, qreal y1, qreal x2, qreal y2, QRgb rgb, Qt::PenStyle lineType);
};
class PathObject : public BaseObject
{
public:
PathObject(qreal x, qreal y, const QPainterPath p, QRgb rgb, QGraphicsItem* parent = 0);
PathObject(PathObject* obj, QGraphicsItem* parent = 0);
~PathObject();
enum { Type = OBJ_TYPE_PATH };
virtual int type() const { return Type; }
QPainterPath objectCopyPath() const;
QPainterPath objectSavePath() const;
QPointF objectPos() const { return scenePos(); }
qreal objectX() const { return scenePos().x(); }
qreal objectY() const { return scenePos().y(); }
void setObjectPos(const QPointF& point) { setPos(point.x(), point.y()); }
void setObjectPos(qreal x, qreal y) { setPos(x, y); }
void setObjectX(qreal x) { setObjectPos(x, objectY()); }
void setObjectY(qreal y) { setObjectPos(objectX(), y); }
void updateRubber(QPainter* painter = 0);
virtual void vulcanize();
virtual QPointF mouseSnapPoint(const QPointF& mousePoint);
virtual QList<QPointF> allGripPoints();
virtual void gripEdit(const QPointF& before, const QPointF& after);
protected:
void paint(QPainter*, const QStyleOptionGraphicsItem*, QWidget*);
private:
void init(qreal x, qreal y, const QPainterPath& p, QRgb rgb, Qt::PenStyle lineType);
void updatePath(const QPainterPath& p);
QPainterPath normalPath;
//TODO: make paths similar to polylines. Review and implement any missing functions/members.
};
class PointObject : public BaseObject
{
public:
PointObject(qreal x, qreal y, QRgb rgb, QGraphicsItem* parent = 0);
PointObject(PointObject* obj, QGraphicsItem* parent = 0);
~PointObject();
enum { Type = OBJ_TYPE_POINT };
virtual int type() const { return Type; }
QPainterPath objectSavePath() const;
QPointF objectPos() const { return scenePos(); }
qreal objectX() const { return scenePos().x(); }
qreal objectY() const { return scenePos().y(); }
void setObjectPos(const QPointF& point) { setPos(point.x(), point.y()); }
void setObjectPos(qreal x, qreal y) { setPos(x, y); }
void setObjectX(qreal x) { setObjectPos(x, objectY()); }
void setObjectY(qreal y) { setObjectPos(objectX(), y); }
void updateRubber(QPainter* painter = 0);
virtual void vulcanize();
virtual QPointF mouseSnapPoint(const QPointF& mousePoint);
virtual QList<QPointF> allGripPoints();
virtual void gripEdit(const QPointF& before, const QPointF& after);
protected:
void paint(QPainter*, const QStyleOptionGraphicsItem*, QWidget*);
private:
void init(qreal x, qreal y, QRgb rgb, Qt::PenStyle lineType);
};
class PolygonObject : public BaseObject
{
public:
PolygonObject(qreal x, qreal y, const QPainterPath& p, QRgb rgb, QGraphicsItem* parent = 0);
PolygonObject(PolygonObject* obj, QGraphicsItem* parent = 0);
~PolygonObject();
enum { Type = OBJ_TYPE_POLYGON };
virtual int type() const { return Type; }
QPainterPath objectCopyPath() const;
QPainterPath objectSavePath() const;
QPointF objectPos() const { return scenePos(); }
qreal objectX() const { return scenePos().x(); }
qreal objectY() const { return scenePos().y(); }
void setObjectPos(const QPointF& point) { setPos(point.x(), point.y()); }
void setObjectPos(qreal x, qreal y) { setPos(x, y); }
void setObjectX(qreal x) { setObjectPos(x, objectY()); }
void setObjectY(qreal y) { setObjectPos(objectX(), y); }
void updateRubber(QPainter* painter = 0);
virtual void vulcanize();
virtual QPointF mouseSnapPoint(const QPointF& mousePoint);
virtual QList<QPointF> allGripPoints();
virtual void gripEdit(const QPointF& before, const QPointF& after);
protected:
void paint(QPainter*, const QStyleOptionGraphicsItem*, QWidget*);
private:
void init(qreal x, qreal y, const QPainterPath& p, QRgb rgb, Qt::PenStyle lineType);
void updatePath(const QPainterPath& p);
QPainterPath normalPath;
int findIndex(const QPointF& point);
int gripIndex;
};
class PolylineObject : public BaseObject
{
public:
PolylineObject(qreal x, qreal y, const QPainterPath& p, QRgb rgb, QGraphicsItem* parent = 0);
PolylineObject(PolylineObject* obj, QGraphicsItem* parent = 0);
~PolylineObject();
enum { Type = OBJ_TYPE_POLYLINE };
virtual int type() const { return Type; }
QPainterPath objectCopyPath() const;
QPainterPath objectSavePath() const;
QPointF objectPos() const { return scenePos(); }
qreal objectX() const { return scenePos().x(); }
qreal objectY() const { return scenePos().y(); }
void setObjectPos(const QPointF& point) { setPos(point.x(), point.y()); }
void setObjectPos(qreal x, qreal y) { setPos(x, y); }
void setObjectX(qreal x) { setObjectPos(x, objectY()); }
void setObjectY(qreal y) { setObjectPos(objectX(), y); }
void updateRubber(QPainter* painter = 0);
virtual void vulcanize();
virtual QPointF mouseSnapPoint(const QPointF& mousePoint);
virtual QList<QPointF> allGripPoints();
virtual void gripEdit(const QPointF& before, const QPointF& after);
protected:
void paint(QPainter*, const QStyleOptionGraphicsItem*, QWidget*);
private:
void init(qreal x, qreal y, const QPainterPath& p, QRgb rgb, Qt::PenStyle lineType);
void updatePath(const QPainterPath& p);
QPainterPath normalPath;
int findIndex(const QPointF& point);
int gripIndex;
};
class RectObject : public BaseObject
{
public:
RectObject(qreal x, qreal y, qreal w, qreal h, QRgb rgb, QGraphicsItem* parent = 0);
RectObject(RectObject* obj, QGraphicsItem* parent = 0);
~RectObject();
enum { Type = OBJ_TYPE_RECTANGLE };
virtual int type() const { return Type; }
QPainterPath objectSavePath() const;
QPointF objectPos() const { return scenePos(); }
QPointF objectTopLeft() const;
QPointF objectTopRight() const;
QPointF objectBottomLeft() const;
QPointF objectBottomRight() const;
qreal objectWidth() const { return rect().width()*scale(); }
qreal objectHeight() const { return rect().height()*scale(); }
qreal objectArea() const { return qAbs(objectWidth()*objectHeight()); }
void setObjectRect(qreal x, qreal y, qreal w, qreal h);
void updateRubber(QPainter* painter = 0);
virtual void vulcanize();
virtual QPointF mouseSnapPoint(const QPointF& mousePoint);
virtual QList<QPointF> allGripPoints();
virtual void gripEdit(const QPointF& before, const QPointF& after);
protected:
void paint(QPainter*, const QStyleOptionGraphicsItem*, QWidget*);
private:
void init(qreal x, qreal y, qreal w, qreal h, QRgb rgb, Qt::PenStyle lineType);
void updatePath();
};
class SaveObject : public QObject
{
Q_OBJECT
public:
SaveObject(QGraphicsScene* theScene, QObject* parent = 0);
~SaveObject();
bool save(const QString &fileName);
void addArc (EmbPattern* pattern, QGraphicsItem* item);
void addBlock (EmbPattern* pattern, QGraphicsItem* item);
void addCircle (EmbPattern* pattern, QGraphicsItem* item);
void addDimAligned (EmbPattern* pattern, QGraphicsItem* item);
void addDimAngular (EmbPattern* pattern, QGraphicsItem* item);
void addDimArcLength (EmbPattern* pattern, QGraphicsItem* item);
void addDimDiameter (EmbPattern* pattern, QGraphicsItem* item);
void addDimLeader (EmbPattern* pattern, QGraphicsItem* item);
void addDimLinear (EmbPattern* pattern, QGraphicsItem* item);
void addDimOrdinate (EmbPattern* pattern, QGraphicsItem* item);
void addDimRadius (EmbPattern* pattern, QGraphicsItem* item);
void addEllipse (EmbPattern* pattern, QGraphicsItem* item);
void addEllipseArc (EmbPattern* pattern, QGraphicsItem* item);
void addGrid (EmbPattern* pattern, QGraphicsItem* item);
void addHatch (EmbPattern* pattern, QGraphicsItem* item);
void addImage (EmbPattern* pattern, QGraphicsItem* item);
void addInfiniteLine (EmbPattern* pattern, QGraphicsItem* item);
void addLine (EmbPattern* pattern, QGraphicsItem* item);
void addPath (EmbPattern* pattern, QGraphicsItem* item);
void addPoint (EmbPattern* pattern, QGraphicsItem* item);
void addPolygon (EmbPattern* pattern, QGraphicsItem* item);
void addPolyline (EmbPattern* pattern, QGraphicsItem* item);
void addRay (EmbPattern* pattern, QGraphicsItem* item);
void addRectangle (EmbPattern* pattern, QGraphicsItem* item);
void addSlot (EmbPattern* pattern, QGraphicsItem* item);
void addSpline (EmbPattern* pattern, QGraphicsItem* item);
void addTextMulti (EmbPattern* pattern, QGraphicsItem* item);
void addTextSingle (EmbPattern* pattern, QGraphicsItem* item);
private:
QGraphicsScene* gscene;
int formatType;
void toPolyline(EmbPattern* pattern, const QPointF& objPos, const QPainterPath& objPath, const QString& layer, const QColor& color, const QString& lineType, const QString& lineWeight);
};
class TextSingleObject : public BaseObject
{
public:
TextSingleObject(const QString& str, qreal x, qreal y, QRgb rgb, QGraphicsItem* parent = 0);
TextSingleObject(TextSingleObject* obj, QGraphicsItem* parent = 0);
~TextSingleObject();
enum { Type = OBJ_TYPE_TEXTSINGLE };
virtual int type() const { return Type; }
QList<QPainterPath> objectSavePathList() const { return subPathList(); }
QList<QPainterPath> subPathList() const;
QString objectText() const { return objText; }
QString objectTextFont() const { return objTextFont; }
QString objectTextJustify() const { return objTextJustify; }
qreal objectTextSize() const { return objTextSize; }
bool objectTextBold() const { return objTextBold; }
bool objectTextItalic() const { return objTextItalic; }
bool objectTextUnderline() const { return objTextUnderline; }
bool objectTextStrikeOut() const { return objTextStrikeOut; }
bool objectTextOverline() const { return objTextOverline; }
bool objectTextBackward() const { return objTextBackward; }
bool objectTextUpsideDown() const { return objTextUpsideDown; }
QPointF objectPos() const { return scenePos(); }
qreal objectX() const { return scenePos().x(); }
qreal objectY() const { return scenePos().y(); }
QStringList objectTextJustifyList() const;
void setObjectText(const QString& str);
void setObjectTextFont(const QString& font);
void setObjectTextJustify(const QString& justify);
void setObjectTextSize(qreal size);
void setObjectTextStyle(bool bold, bool italic, bool under, bool strike, bool over);
void setObjectTextBold(bool val);
void setObjectTextItalic(bool val);
void setObjectTextUnderline(bool val);
void setObjectTextStrikeOut(bool val);
void setObjectTextOverline(bool val);
void setObjectTextBackward(bool val);
void setObjectTextUpsideDown(bool val);
void setObjectPos(const QPointF& point) { setPos(point.x(), point.y()); }
void setObjectPos(qreal x, qreal y) { setPos(x, y); }
void setObjectX(qreal x) { setObjectPos(x, objectY()); }
void setObjectY(qreal y) { setObjectPos(objectX(), y); }
void updateRubber(QPainter* painter = 0);
virtual void vulcanize();
virtual QPointF mouseSnapPoint(const QPointF& mousePoint);
virtual QList<QPointF> allGripPoints();
virtual void gripEdit(const QPointF& before, const QPointF& after);
protected:
void paint(QPainter*, const QStyleOptionGraphicsItem*, QWidget*);
private:
void init(const QString& str, qreal x, qreal y, QRgb rgb, Qt::PenStyle lineType);
QString objText;
QString objTextFont;
QString objTextJustify;
qreal objTextSize;
bool objTextBold;
bool objTextItalic;
bool objTextUnderline;
bool objTextStrikeOut;
bool objTextOverline;
bool objTextBackward;
bool objTextUpsideDown;
QPainterPath objTextPath;
};
class PropertyEditor : public QDockWidget
{
Q_OBJECT
public:
PropertyEditor(const QString& iconDirectory = QString(), bool pickAddMode = true, QWidget* widgetToFocus = 0, QWidget* parent = 0, Qt::WindowFlags flags = Qt::Widget);
~PropertyEditor();
protected:
bool eventFilter(QObject *obj, QEvent *event);
signals:
void pickAddModeToggled();
public slots:
void setSelectedItems(QList<QGraphicsItem*> itemList);
void updatePickAddModeButton(bool pickAddMode);
private slots:
void fieldEdited(QObject* fieldObj);
void showGroups(int objType);
void showOneType(int index);
void hideAllGroups();
void clearAllFields();
void togglePickAddMode();
private:
QWidget* focusWidget;
QString iconDir;
int iconSize;
Qt::ToolButtonStyle propertyEditorButtonStyle;
bool pickAdd;
QList<QGraphicsItem*> selectedItemList;
ArcObject* tempArcObj;
BlockObject* tempBlockObj;
CircleObject* tempCircleObj;
DimAlignedObject* tempDimAlignedObj;
DimAngularObject* tempDimAngularObj;
DimArcLengthObject* tempDimArcLenObj;
DimDiameterObject* tempDimDiamObj;
DimLeaderObject* tempDimLeaderObj;
DimLinearObject* tempDimLinearObj;
DimOrdinateObject* tempDimOrdObj;
DimRadiusObject* tempDimRadiusObj;
EllipseObject* tempEllipseObj;
EllipseArcObject* tempEllipseArcObj;
HatchObject* tempHatchObj;
ImageObject* tempImageObj;
InfiniteLineObject* tempInfLineObj;
LineObject* tempLineObj;
PathObject* tempPathObj;
PointObject* tempPointObj;
PolygonObject* tempPolygonObj;
PolylineObject* tempPolylineObj;
RayObject* tempRayObj;
RectObject* tempRectObj;
SplineObject* tempSplineObj;
TextMultiObject* tempTextMultiObj;
TextSingleObject* tempTextSingleObj;
//Helper functions
QToolButton* createToolButton(const QString& iconName, const QString& txt);
QLineEdit* createLineEdit(const QString& validatorType = QString(), bool readOnly = false);
QComboBox* createComboBox(bool disable = false);
QFontComboBox* createFontComboBox(bool disable = false);
int precisionAngle;
int precisionLength;
//Used when checking if fields vary
QString fieldOldText;
QString fieldNewText;
QString fieldVariesText;
QString fieldYesText;
QString fieldNoText;
QString fieldOnText;
QString fieldOffText;
void updateLineEditStrIfVaries(QLineEdit* lineEdit, const QString& str);
void updateLineEditNumIfVaries(QLineEdit* lineEdit, qreal num, bool useAnglePrecision);
void updateFontComboBoxStrIfVaries(QFontComboBox* fontComboBox, const QString& str);
void updateComboBoxStrIfVaries(QComboBox* comboBox, const QString& str, const QStringList& strList);
void updateComboBoxBoolIfVaries(QComboBox* comboBox, bool val, bool yesOrNoText);
QSignalMapper* signalMapper;
void mapSignal(QObject* fieldObj, const QString& name, QVariant value);
//====================
//Selection
//====================
QComboBox* createComboBoxSelected();
QToolButton* createToolButtonQSelect();
QToolButton* createToolButtonPickAdd();
QComboBox* comboBoxSelected;
QToolButton* toolButtonQSelect;
QToolButton* toolButtonPickAdd;
//TODO: Alphabetic/Categorized TabWidget
//====================
//General
//====================
QGroupBox* createGroupBoxGeneral();
QGroupBox* groupBoxGeneral;
QToolButton* toolButtonGeneralLayer;
QToolButton* toolButtonGeneralColor;
QToolButton* toolButtonGeneralLineType;
QToolButton* toolButtonGeneralLineWeight;
QComboBox* comboBoxGeneralLayer;
QComboBox* comboBoxGeneralColor;
QComboBox* comboBoxGeneralLineType;
QComboBox* comboBoxGeneralLineWeight;
//====================
//Geometry
//====================
//Arc
QGroupBox* createGroupBoxGeometryArc();
QGroupBox* groupBoxGeometryArc;
QToolButton* toolButtonArcCenterX;
QToolButton* toolButtonArcCenterY;
QToolButton* toolButtonArcRadius;
QToolButton* toolButtonArcStartAngle;
QToolButton* toolButtonArcEndAngle;
QToolButton* toolButtonArcStartX;
QToolButton* toolButtonArcStartY;
QToolButton* toolButtonArcEndX;
QToolButton* toolButtonArcEndY;
QToolButton* toolButtonArcArea;
QToolButton* toolButtonArcLength;
QToolButton* toolButtonArcChord;
QToolButton* toolButtonArcIncAngle;
QLineEdit* lineEditArcCenterX;
QLineEdit* lineEditArcCenterY;
QLineEdit* lineEditArcRadius;
QLineEdit* lineEditArcStartAngle;
QLineEdit* lineEditArcEndAngle;
QLineEdit* lineEditArcStartX;
QLineEdit* lineEditArcStartY;
QLineEdit* lineEditArcEndX;
QLineEdit* lineEditArcEndY;
QLineEdit* lineEditArcArea;
QLineEdit* lineEditArcLength;
QLineEdit* lineEditArcChord;
QLineEdit* lineEditArcIncAngle;
QGroupBox* createGroupBoxMiscArc();
QGroupBox* groupBoxMiscArc;
QToolButton* toolButtonArcClockwise;
QComboBox* comboBoxArcClockwise;
//Block
QGroupBox* createGroupBoxGeometryBlock();
QGroupBox* groupBoxGeometryBlock;
QToolButton* toolButtonBlockX;
QToolButton* toolButtonBlockY;
QLineEdit* lineEditBlockX;
QLineEdit* lineEditBlockY;
//Circle
QGroupBox* createGroupBoxGeometryCircle();
QGroupBox* groupBoxGeometryCircle;
QToolButton* toolButtonCircleCenterX;
QToolButton* toolButtonCircleCenterY;
QToolButton* toolButtonCircleRadius;
QToolButton* toolButtonCircleDiameter;
QToolButton* toolButtonCircleArea;
QToolButton* toolButtonCircleCircumference;
QLineEdit* lineEditCircleCenterX;
QLineEdit* lineEditCircleCenterY;
QLineEdit* lineEditCircleRadius;
QLineEdit* lineEditCircleDiameter;
QLineEdit* lineEditCircleArea;
QLineEdit* lineEditCircleCircumference;
//DimAligned
QGroupBox* createGroupBoxGeometryDimAligned();
QGroupBox* groupBoxGeometryDimAligned;
//TODO: toolButtons and lineEdits for DimAligned
//DimAngular
QGroupBox* createGroupBoxGeometryDimAngular();
QGroupBox* groupBoxGeometryDimAngular;
//TODO: toolButtons and lineEdits for DimAngular
//DimArcLength
QGroupBox* createGroupBoxGeometryDimArcLength();
QGroupBox* groupBoxGeometryDimArcLength;
//TODO: toolButtons and lineEdits for DimArcLength
//DimDiameter
QGroupBox* createGroupBoxGeometryDimDiameter();
QGroupBox* groupBoxGeometryDimDiameter;
//TODO: toolButtons and lineEdits for DimDiameter
//DimLeader
QGroupBox* createGroupBoxGeometryDimLeader();
QGroupBox* groupBoxGeometryDimLeader;
//TODO: toolButtons and lineEdits for DimLeader
//DimLinear
QGroupBox* createGroupBoxGeometryDimLinear();
QGroupBox* groupBoxGeometryDimLinear;
//TODO: toolButtons and lineEdits for DimLinear
//DimOrdinate
QGroupBox* createGroupBoxGeometryDimOrdinate();
QGroupBox* groupBoxGeometryDimOrdinate;
//TODO: toolButtons and lineEdits for DimOrdinate
//DimRadius
QGroupBox* createGroupBoxGeometryDimRadius();
QGroupBox* groupBoxGeometryDimRadius;
//TODO: toolButtons and lineEdits for DimRadius
//Ellipse
QGroupBox* createGroupBoxGeometryEllipse();
QGroupBox* groupBoxGeometryEllipse;
QToolButton* toolButtonEllipseCenterX;
QToolButton* toolButtonEllipseCenterY;
QToolButton* toolButtonEllipseRadiusMajor;
QToolButton* toolButtonEllipseRadiusMinor;
QToolButton* toolButtonEllipseDiameterMajor;
QToolButton* toolButtonEllipseDiameterMinor;
QLineEdit* lineEditEllipseCenterX;
QLineEdit* lineEditEllipseCenterY;
QLineEdit* lineEditEllipseRadiusMajor;
QLineEdit* lineEditEllipseRadiusMinor;
QLineEdit* lineEditEllipseDiameterMajor;
QLineEdit* lineEditEllipseDiameterMinor;
//Image
QGroupBox* createGroupBoxGeometryImage();
QGroupBox* groupBoxGeometryImage;
QToolButton* toolButtonImageX;
QToolButton* toolButtonImageY;
QToolButton* toolButtonImageWidth;
QToolButton* toolButtonImageHeight;
QLineEdit* lineEditImageX;
QLineEdit* lineEditImageY;
QLineEdit* lineEditImageWidth;
QLineEdit* lineEditImageHeight;
QGroupBox* createGroupBoxMiscImage();
QGroupBox* groupBoxMiscImage;
QToolButton* toolButtonImageName;
QToolButton* toolButtonImagePath;
QLineEdit* lineEditImageName;
QLineEdit* lineEditImagePath;
//Infinite Line
QGroupBox* createGroupBoxGeometryInfiniteLine();
QGroupBox* groupBoxGeometryInfiniteLine;
QToolButton* toolButtonInfiniteLineX1;
QToolButton* toolButtonInfiniteLineY1;
QToolButton* toolButtonInfiniteLineX2;
QToolButton* toolButtonInfiniteLineY2;
QToolButton* toolButtonInfiniteLineVectorX;
QToolButton* toolButtonInfiniteLineVectorY;
QLineEdit* lineEditInfiniteLineX1;
QLineEdit* lineEditInfiniteLineY1;
QLineEdit* lineEditInfiniteLineX2;
QLineEdit* lineEditInfiniteLineY2;
QLineEdit* lineEditInfiniteLineVectorX;
QLineEdit* lineEditInfiniteLineVectorY;
//Line
QGroupBox* createGroupBoxGeometryLine();
QGroupBox* groupBoxGeometryLine;
QToolButton* toolButtonLineStartX;
QToolButton* toolButtonLineStartY;
QToolButton* toolButtonLineEndX;
QToolButton* toolButtonLineEndY;
QToolButton* toolButtonLineDeltaX;
QToolButton* toolButtonLineDeltaY;
QToolButton* toolButtonLineAngle;
QToolButton* toolButtonLineLength;
QLineEdit* lineEditLineStartX;
QLineEdit* lineEditLineStartY;
QLineEdit* lineEditLineEndX;
QLineEdit* lineEditLineEndY;
QLineEdit* lineEditLineDeltaX;
QLineEdit* lineEditLineDeltaY;
QLineEdit* lineEditLineAngle;
QLineEdit* lineEditLineLength;
//Path
QGroupBox* createGroupBoxGeometryPath();
QGroupBox* groupBoxGeometryPath;
QToolButton* toolButtonPathVertexNum;
QToolButton* toolButtonPathVertexX;
QToolButton* toolButtonPathVertexY;
QToolButton* toolButtonPathArea;
QToolButton* toolButtonPathLength;
QComboBox* comboBoxPathVertexNum;
QLineEdit* lineEditPathVertexX;
QLineEdit* lineEditPathVertexY;
QLineEdit* lineEditPathArea;
QLineEdit* lineEditPathLength;
QGroupBox* createGroupBoxMiscPath();
QGroupBox* groupBoxMiscPath;
QToolButton* toolButtonPathClosed;
QComboBox* comboBoxPathClosed;
//Point
QGroupBox* createGroupBoxGeometryPoint();
QGroupBox* groupBoxGeometryPoint;
QToolButton* toolButtonPointX;
QToolButton* toolButtonPointY;
QLineEdit* lineEditPointX;
QLineEdit* lineEditPointY;
//Polygon
QGroupBox* createGroupBoxGeometryPolygon();
QGroupBox* groupBoxGeometryPolygon;
QToolButton* toolButtonPolygonCenterX;
QToolButton* toolButtonPolygonCenterY;
QToolButton* toolButtonPolygonRadiusVertex;
QToolButton* toolButtonPolygonRadiusSide;
QToolButton* toolButtonPolygonDiameterVertex;
QToolButton* toolButtonPolygonDiameterSide;
QToolButton* toolButtonPolygonInteriorAngle;
QLineEdit* lineEditPolygonCenterX;
QLineEdit* lineEditPolygonCenterY;
QLineEdit* lineEditPolygonRadiusVertex;
QLineEdit* lineEditPolygonRadiusSide;
QLineEdit* lineEditPolygonDiameterVertex;
QLineEdit* lineEditPolygonDiameterSide;
QLineEdit* lineEditPolygonInteriorAngle;
//Polyline
QGroupBox* createGroupBoxGeometryPolyline();
QGroupBox* groupBoxGeometryPolyline;
QToolButton* toolButtonPolylineVertexNum;
QToolButton* toolButtonPolylineVertexX;
QToolButton* toolButtonPolylineVertexY;
QToolButton* toolButtonPolylineArea;
QToolButton* toolButtonPolylineLength;
QComboBox* comboBoxPolylineVertexNum;
QLineEdit* lineEditPolylineVertexX;
QLineEdit* lineEditPolylineVertexY;
QLineEdit* lineEditPolylineArea;
QLineEdit* lineEditPolylineLength;
QGroupBox* createGroupBoxMiscPolyline();
QGroupBox* groupBoxMiscPolyline;
QToolButton* toolButtonPolylineClosed;
QComboBox* comboBoxPolylineClosed;
//Ray
QGroupBox* createGroupBoxGeometryRay();
QGroupBox* groupBoxGeometryRay;
QToolButton* toolButtonRayX1;
QToolButton* toolButtonRayY1;
QToolButton* toolButtonRayX2;
QToolButton* toolButtonRayY2;
QToolButton* toolButtonRayVectorX;
QToolButton* toolButtonRayVectorY;
QLineEdit* lineEditRayX1;
QLineEdit* lineEditRayY1;
QLineEdit* lineEditRayX2;
QLineEdit* lineEditRayY2;
QLineEdit* lineEditRayVectorX;
QLineEdit* lineEditRayVectorY;
//Rectangle
QGroupBox* createGroupBoxGeometryRectangle();
QGroupBox* groupBoxGeometryRectangle;
QToolButton* toolButtonRectangleCorner1X;
QToolButton* toolButtonRectangleCorner1Y;
QToolButton* toolButtonRectangleCorner2X;
QToolButton* toolButtonRectangleCorner2Y;
QToolButton* toolButtonRectangleCorner3X;
QToolButton* toolButtonRectangleCorner3Y;
QToolButton* toolButtonRectangleCorner4X;
QToolButton* toolButtonRectangleCorner4Y;
QToolButton* toolButtonRectangleWidth;
QToolButton* toolButtonRectangleHeight;
QToolButton* toolButtonRectangleArea;
QLineEdit* lineEditRectangleCorner1X;
QLineEdit* lineEditRectangleCorner1Y;
QLineEdit* lineEditRectangleCorner2X;
QLineEdit* lineEditRectangleCorner2Y;
QLineEdit* lineEditRectangleCorner3X;
QLineEdit* lineEditRectangleCorner3Y;
QLineEdit* lineEditRectangleCorner4X;
QLineEdit* lineEditRectangleCorner4Y;
QLineEdit* lineEditRectangleWidth;
QLineEdit* lineEditRectangleHeight;
QLineEdit* lineEditRectangleArea;
//Text Multi
QGroupBox* createGroupBoxGeometryTextMulti();
QGroupBox* groupBoxGeometryTextMulti;
QToolButton* toolButtonTextMultiX;
QToolButton* toolButtonTextMultiY;
QLineEdit* lineEditTextMultiX;
QLineEdit* lineEditTextMultiY;
//Text Single
QGroupBox* createGroupBoxTextTextSingle();
QGroupBox* groupBoxTextTextSingle;
QToolButton* toolButtonTextSingleContents;
QToolButton* toolButtonTextSingleFont;
QToolButton* toolButtonTextSingleJustify;
QToolButton* toolButtonTextSingleHeight;
QToolButton* toolButtonTextSingleRotation;
QLineEdit* lineEditTextSingleContents;
QFontComboBox* comboBoxTextSingleFont;
QComboBox* comboBoxTextSingleJustify;
QLineEdit* lineEditTextSingleHeight;
QLineEdit* lineEditTextSingleRotation;
QGroupBox* createGroupBoxGeometryTextSingle();
QGroupBox* groupBoxGeometryTextSingle;
QToolButton* toolButtonTextSingleX;
QToolButton* toolButtonTextSingleY;
QLineEdit* lineEditTextSingleX;
QLineEdit* lineEditTextSingleY;
QGroupBox* createGroupBoxMiscTextSingle();
QGroupBox* groupBoxMiscTextSingle;
QToolButton* toolButtonTextSingleBackward;
QToolButton* toolButtonTextSingleUpsideDown;
QComboBox* comboBoxTextSingleBackward;
QComboBox* comboBoxTextSingleUpsideDown;
};
class SelectBox : public QRubberBand
{
Q_OBJECT
public:
SelectBox(Shape s, QWidget* parent = 0);
public slots:
void setDirection(int dir);
void setColors(const QColor& colorL, const QColor& fillL, const QColor& colorR, const QColor& fillR, int newAlpha);
protected:
void paintEvent(QPaintEvent*);
private:
QColor leftBrushColor;
QColor rightBrushColor;
QColor leftPenColor;
QColor rightPenColor;
quint8 alpha;
QBrush dirBrush;
QBrush leftBrush;
QBrush rightBrush;
QPen dirPen;
QPen leftPen;
QPen rightPen;
bool boxDir;
void forceRepaint();
};
class Settings_Dialog : public QDialog
{
Q_OBJECT
public:
Settings_Dialog(MainWindow* mw, const QString& showTab = QString(), QWidget *parent = 0);
~Settings_Dialog();
private:
MainWindow* mainWin;
QTabWidget* tabWidget;
QWidget* createTabGeneral();
QWidget* createTabFilesPaths();
QWidget* createTabDisplay();
QWidget* createTabPrompt();
QWidget* createTabOpenSave();
QWidget* createTabPrinting();
QWidget* createTabSnap();
QWidget* createTabGridRuler();
QWidget* createTabOrthoPolar();
QWidget* createTabQuickSnap();
QWidget* createTabQuickTrack();
QWidget* createTabLineWeight();
QWidget* createTabSelection();
QDialogButtonBox* buttonBox;
void addColorsToComboBox(QComboBox* comboBox);
//Temporary for instant preview
bool preview_general_mdi_bg_use_logo;
bool preview_general_mdi_bg_use_texture;
bool preview_general_mdi_bg_use_color;
QString accept_general_mdi_bg_logo;
QString accept_general_mdi_bg_texture;
QRgb preview_general_mdi_bg_color;
QRgb accept_general_mdi_bg_color;
bool preview_display_show_scrollbars;
QRgb preview_display_crosshair_color;
QRgb accept_display_crosshair_color;
QRgb preview_display_bg_color;
QRgb accept_display_bg_color;
QRgb preview_display_selectbox_left_color;
QRgb accept_display_selectbox_left_color;
QRgb preview_display_selectbox_left_fill;
QRgb accept_display_selectbox_left_fill;
QRgb preview_display_selectbox_right_color;
QRgb accept_display_selectbox_right_color;
QRgb preview_display_selectbox_right_fill;
QRgb accept_display_selectbox_right_fill;
quint8 preview_display_selectbox_alpha;
QRgb preview_prompt_text_color;
QRgb accept_prompt_text_color;
QRgb preview_prompt_bg_color;
QRgb accept_prompt_bg_color;
QString preview_prompt_font_family;
QString preview_prompt_font_style;
quint8 preview_prompt_font_size;
QRgb preview_grid_color;
QRgb accept_grid_color;
QRgb preview_ruler_color;
QRgb accept_ruler_color;
bool preview_lwt_show_lwt;
bool preview_lwt_real_render;
//Temporary until changes are accepted
QString dialog_general_language;
QString dialog_general_icon_theme;
int dialog_general_icon_size;
bool dialog_general_mdi_bg_use_logo;
bool dialog_general_mdi_bg_use_texture;
bool dialog_general_mdi_bg_use_color;
QString dialog_general_mdi_bg_logo;
QString dialog_general_mdi_bg_texture;
QRgb dialog_general_mdi_bg_color;
bool dialog_general_tip_of_the_day;
bool dialog_general_system_help_browser;
bool dialog_display_use_opengl;
bool dialog_display_renderhint_aa;
bool dialog_display_renderhint_text_aa;
bool dialog_display_renderhint_smooth_pix;
bool dialog_display_renderhint_high_aa;
bool dialog_display_renderhint_noncosmetic;
bool dialog_display_show_scrollbars;
int dialog_display_scrollbar_widget_num;
QRgb dialog_display_crosshair_color;
QRgb dialog_display_bg_color;
QRgb dialog_display_selectbox_left_color;
QRgb dialog_display_selectbox_left_fill;
QRgb dialog_display_selectbox_right_color;
QRgb dialog_display_selectbox_right_fill;
quint8 dialog_display_selectbox_alpha;
qreal dialog_display_zoomscale_in;
qreal dialog_display_zoomscale_out;
quint8 dialog_display_crosshair_percent;
QString dialog_display_units;
QRgb dialog_prompt_text_color;
QRgb dialog_prompt_bg_color;
QString dialog_prompt_font_family;
QString dialog_prompt_font_style;
quint8 dialog_prompt_font_size;
bool dialog_prompt_save_history;
bool dialog_prompt_save_history_as_html;
QString dialog_prompt_save_history_filename;
QString dialog_opensave_custom_filter;
QString dialog_opensave_open_format;
bool dialog_opensave_open_thumbnail;
QString dialog_opensave_save_format;
bool dialog_opensave_save_thumbnail;
quint8 dialog_opensave_recent_max_files;
quint8 dialog_opensave_trim_dst_num_jumps;
QString dialog_printing_default_device;
bool dialog_printing_use_last_device;
bool dialog_printing_disable_bg;
bool dialog_grid_show_on_load;
bool dialog_grid_show_origin;
bool dialog_grid_color_match_crosshair;
QRgb dialog_grid_color;
bool dialog_grid_load_from_file;
QString dialog_grid_type;
bool dialog_grid_center_on_origin;
qreal dialog_grid_center_x;
qreal dialog_grid_center_y;
qreal dialog_grid_size_x;
qreal dialog_grid_size_y;
qreal dialog_grid_spacing_x;
qreal dialog_grid_spacing_y;
qreal dialog_grid_size_radius;
qreal dialog_grid_spacing_radius;
qreal dialog_grid_spacing_angle;
bool dialog_ruler_show_on_load;
bool dialog_ruler_metric;
QRgb dialog_ruler_color;
quint8 dialog_ruler_pixel_size;
bool dialog_qsnap_enabled;
QRgb dialog_qsnap_locator_color;
quint8 dialog_qsnap_locator_size;
quint8 dialog_qsnap_aperture_size;
bool dialog_qsnap_endpoint;
bool dialog_qsnap_midpoint;
bool dialog_qsnap_center;
bool dialog_qsnap_node;
bool dialog_qsnap_quadrant;
bool dialog_qsnap_intersection;
bool dialog_qsnap_extension;
bool dialog_qsnap_insertion;
bool dialog_qsnap_perpendicular;
bool dialog_qsnap_tangent;
bool dialog_qsnap_nearest;
bool dialog_qsnap_apparent;
bool dialog_qsnap_parallel;
bool dialog_lwt_show_lwt;
bool dialog_lwt_real_render;
qreal dialog_lwt_default_lwt;
bool dialog_selection_mode_pickfirst;
bool dialog_selection_mode_pickadd;
bool dialog_selection_mode_pickdrag;
QRgb dialog_selection_coolgrip_color;
QRgb dialog_selection_hotgrip_color;
quint8 dialog_selection_grip_size;
quint8 dialog_selection_pickbox_size;
private slots:
void comboBoxLanguageCurrentIndexChanged(const QString&);
void comboBoxIconThemeCurrentIndexChanged(const QString&);
void comboBoxIconSizeCurrentIndexChanged(int);
void checkBoxGeneralMdiBGUseLogoStateChanged(int);
void chooseGeneralMdiBackgroundLogo();
void checkBoxGeneralMdiBGUseTextureStateChanged(int);
void chooseGeneralMdiBackgroundTexture();
void checkBoxGeneralMdiBGUseColorStateChanged(int);
void chooseGeneralMdiBackgroundColor();
void currentGeneralMdiBackgroundColorChanged(const QColor&);
void checkBoxTipOfTheDayStateChanged(int);
void checkBoxUseOpenGLStateChanged(int);
void checkBoxRenderHintAAStateChanged(int);
void checkBoxRenderHintTextAAStateChanged(int);
void checkBoxRenderHintSmoothPixStateChanged(int);
void checkBoxRenderHintHighAAStateChanged(int);
void checkBoxRenderHintNonCosmeticStateChanged(int);
void checkBoxShowScrollBarsStateChanged(int);
void comboBoxScrollBarWidgetCurrentIndexChanged(int);
void spinBoxZoomScaleInValueChanged(double);
void spinBoxZoomScaleOutValueChanged(double);
void checkBoxDisableBGStateChanged(int);
void chooseDisplayCrossHairColor();
void currentDisplayCrossHairColorChanged(const QColor&);
void chooseDisplayBackgroundColor();
void currentDisplayBackgroundColorChanged(const QColor&);
void chooseDisplaySelectBoxLeftColor();
void currentDisplaySelectBoxLeftColorChanged(const QColor&);
void chooseDisplaySelectBoxLeftFill();
void currentDisplaySelectBoxLeftFillChanged(const QColor&);
void chooseDisplaySelectBoxRightColor();
void currentDisplaySelectBoxRightColorChanged(const QColor&);
void chooseDisplaySelectBoxRightFill();
void currentDisplaySelectBoxRightFillChanged(const QColor&);
void spinBoxDisplaySelectBoxAlphaValueChanged(int);
void choosePromptTextColor();
void currentPromptTextColorChanged(const QColor&);
void choosePromptBackgroundColor();
void currentPromptBackgroundColorChanged(const QColor&);
void comboBoxPromptFontFamilyCurrentIndexChanged(const QString&);
void comboBoxPromptFontStyleCurrentIndexChanged(const QString&);
void spinBoxPromptFontSizeValueChanged(int);
void checkBoxPromptSaveHistoryStateChanged(int);
void checkBoxPromptSaveHistoryAsHtmlStateChanged(int);
void checkBoxCustomFilterStateChanged(int);
void buttonCustomFilterSelectAllClicked();
void buttonCustomFilterClearAllClicked();
void spinBoxRecentMaxFilesValueChanged(int);
void spinBoxTrimDstNumJumpsValueChanged(int);
void checkBoxGridShowOnLoadStateChanged(int);
void checkBoxGridShowOriginStateChanged(int);
void checkBoxGridColorMatchCrossHairStateChanged(int);
void chooseGridColor();
void currentGridColorChanged(const QColor&);
void checkBoxGridLoadFromFileStateChanged(int);
void comboBoxGridTypeCurrentIndexChanged(const QString&);
void checkBoxGridCenterOnOriginStateChanged(int);
void spinBoxGridCenterXValueChanged(double);
void spinBoxGridCenterYValueChanged(double);
void spinBoxGridSizeXValueChanged(double);
void spinBoxGridSizeYValueChanged(double);
void spinBoxGridSpacingXValueChanged(double);
void spinBoxGridSpacingYValueChanged(double);
void spinBoxGridSizeRadiusValueChanged(double);
void spinBoxGridSpacingRadiusValueChanged(double);
void spinBoxGridSpacingAngleValueChanged(double);
void checkBoxRulerShowOnLoadStateChanged(int);
void comboBoxRulerMetricCurrentIndexChanged(int);
void chooseRulerColor();
void currentRulerColorChanged(const QColor&);
void spinBoxRulerPixelSizeValueChanged(double);
void checkBoxQSnapEndPointStateChanged(int);
void checkBoxQSnapMidPointStateChanged(int);
void checkBoxQSnapCenterStateChanged(int);
void checkBoxQSnapNodeStateChanged(int);
void checkBoxQSnapQuadrantStateChanged(int);
void checkBoxQSnapIntersectionStateChanged(int);
void checkBoxQSnapExtensionStateChanged(int);
void checkBoxQSnapInsertionStateChanged(int);
void checkBoxQSnapPerpendicularStateChanged(int);
void checkBoxQSnapTangentStateChanged(int);
void checkBoxQSnapNearestStateChanged(int);
void checkBoxQSnapApparentStateChanged(int);
void checkBoxQSnapParallelStateChanged(int);
void buttonQSnapSelectAllClicked();
void buttonQSnapClearAllClicked();
void comboBoxQSnapLocatorColorCurrentIndexChanged(int);
void sliderQSnapLocatorSizeValueChanged(int);
void sliderQSnapApertureSizeValueChanged(int);
void checkBoxLwtShowLwtStateChanged(int);
void checkBoxLwtRealRenderStateChanged(int);
void checkBoxSelectionModePickFirstStateChanged(int);
void checkBoxSelectionModePickAddStateChanged(int);
void checkBoxSelectionModePickDragStateChanged(int);
void comboBoxSelectionCoolGripColorCurrentIndexChanged(int);
void comboBoxSelectionHotGripColorCurrentIndexChanged(int);
void sliderSelectionGripSizeValueChanged(int);
void sliderSelectionPickBoxSizeValueChanged(int);
void acceptChanges();
void rejectChanges();
signals:
void buttonCustomFilterSelectAll(bool);
void buttonCustomFilterClearAll(bool);
void buttonQSnapSelectAll(bool);
void buttonQSnapClearAll(bool);
};
class StatusBarButton : public QToolButton
{
Q_OBJECT
public:
StatusBarButton(QString buttonText, MainWindow* mw, StatusBar* statbar, QWidget *parent = 0);
protected:
void contextMenuEvent(QContextMenuEvent *event = 0);
private slots:
void settingsSnap();
void settingsGrid();
void settingsRuler();
void settingsOrtho();
void settingsPolar();
void settingsQSnap();
void settingsQTrack();
void settingsLwt();
void toggleSnap(bool on);
void toggleGrid(bool on);
void toggleRuler(bool on);
void toggleOrtho(bool on);
void togglePolar(bool on);
void toggleQSnap(bool on);
void toggleQTrack(bool on);
void toggleLwt(bool on);
public slots:
void enableLwt();
void disableLwt();
void enableReal();
void disableReal();
private:
MainWindow* mainWin;
StatusBar* statusbar;
};
class StatusBar : public QStatusBar
{
Q_OBJECT
public:
StatusBar(MainWindow* mw, QWidget* parent = 0);
StatusBarButton* statusBarSnapButton;
StatusBarButton* statusBarGridButton;
StatusBarButton* statusBarRulerButton;
StatusBarButton* statusBarOrthoButton;
StatusBarButton* statusBarPolarButton;
StatusBarButton* statusBarQSnapButton;
StatusBarButton* statusBarQTrackButton;
StatusBarButton* statusBarLwtButton;
QLabel* statusBarMouseCoord;
void setMouseCoord(qreal x, qreal y);
protected:
private slots:
private:
};
class UndoableAddCommand : public QUndoCommand
{
public:
UndoableAddCommand(const QString& text, BaseObject* obj, View* v, QUndoCommand* parent = 0);
void undo();
void redo();
private:
BaseObject* object;
View* gview;
};
class UndoableDeleteCommand : public QUndoCommand
{
public:
UndoableDeleteCommand(const QString& text, BaseObject* obj, View* v, QUndoCommand* parent = 0);
void undo();
void redo();
private:
BaseObject* object;
View* gview;
};
class UndoableMoveCommand : public QUndoCommand
{
public:
UndoableMoveCommand(qreal deltaX, qreal deltaY, const QString& text, BaseObject* obj, View* v, QUndoCommand* parent = 0);
void undo();
void redo();
private:
BaseObject* object;
View* gview;
qreal dx;
qreal dy;
};
class UndoableRotateCommand : public QUndoCommand
{
public:
UndoableRotateCommand(qreal pivotPointX, qreal pivotPointY, qreal rotAngle, const QString& text, BaseObject* obj, View* v, QUndoCommand* parent = 0);
void undo();
void redo();
private:
void rotate(qreal x, qreal y, qreal rot);
inline qreal pi() { return (qAtan(1.0)*4.0); };
inline qreal radians(qreal degrees) { return (degrees*pi()/180.0); };
BaseObject* object;
View* gview;
qreal pivotX;
qreal pivotY;
qreal angle;
};
class UndoableScaleCommand : public QUndoCommand
{
public:
UndoableScaleCommand(qreal x, qreal y, qreal scaleFactor, const QString& text, BaseObject* obj, View* v, QUndoCommand* parent = 0);
void undo();
void redo();
private:
BaseObject* object;
View* gview;
qreal dx;
qreal dy;
qreal factor;
};
class UndoableNavCommand : public QUndoCommand
{
public:
UndoableNavCommand(const QString& type, View* v, QUndoCommand* parent = 0);
int id() const { return 1234; }
bool mergeWith(const QUndoCommand* command);
void undo();
void redo();
private:
QString navType;
QTransform fromTransform;
QTransform toTransform;
QPointF fromCenter;
QPointF toCenter;
bool done;
View* gview;
};
class UndoableGripEditCommand : public QUndoCommand
{
public:
UndoableGripEditCommand(const QPointF beforePoint, const QPointF afterPoint, const QString& text, BaseObject* obj, View* v, QUndoCommand* parent = 0);
void undo();
void redo();
private:
BaseObject* object;
View* gview;
QPointF before;
QPointF after;
};
class UndoableMirrorCommand : public QUndoCommand
{
public:
UndoableMirrorCommand(qreal x1, qreal y1, qreal x2, qreal y2, const QString& text, BaseObject* obj, View* v, QUndoCommand* parent = 0);
void undo();
void redo();
private:
void mirror();
BaseObject* object;
View* gview;
QLineF mirrorLine;
};
class UndoEditor : public QDockWidget
{
Q_OBJECT
public:
UndoEditor(const QString& iconDirectory = QString(), QWidget* widgetToFocus = 0, QWidget* parent = 0, Qt::WindowFlags flags = Qt::Widget);
~UndoEditor();
void addStack(QUndoStack* stack);
bool canUndo() const;
bool canRedo() const;
QString undoText() const;
QString redoText() const;
protected:
public slots:
void undo();
void redo();
void updateCleanIcon(bool opened);
private:
QWidget* focusWidget;
QString iconDir;
int iconSize;
QUndoGroup* undoGroup;
QUndoView* undoView;
};
class View : public QGraphicsView
{
Q_OBJECT
public:
View(MainWindow* mw, QGraphicsScene* theScene, QWidget* parent);
~View();
bool allowZoomIn();
bool allowZoomOut();
void recalculateLimits();
void zoomToPoint(const QPoint& mousePoint, int zoomDir);
void centerAt(const QPointF& centerPoint);
QPointF center() { return mapToScene(rect().center()); }
QUndoStack* getUndoStack() { return undoStack; }
void addObject(BaseObject* obj);
void deleteObject(BaseObject* obj);
void vulcanizeObject(BaseObject* obj);
public slots:
void zoomIn();
void zoomOut();
void zoomWindow();
void zoomSelected();
void zoomExtents();
void panRealTime();
void panPoint();
void panLeft();
void panRight();
void panUp();
void panDown();
void selectAll();
void selectionChanged();
void clearSelection();
void deleteSelected();
void moveSelected(qreal dx, qreal dy);
void cut();
void copy();
void paste();
void repeatAction();
void moveAction();
void scaleAction();
void scaleSelected(qreal x, qreal y, qreal factor);
void rotateAction();
void rotateSelected(qreal x, qreal y, qreal rot);
void mirrorSelected(qreal x1, qreal y1, qreal x2, qreal y2);
int numSelected();
void deletePressed();
void escapePressed();
void cornerButtonClicked();
void showScrollBars(bool val);
void setCornerButton();
void setCrossHairColor(QRgb color);
void setCrossHairSize(quint8 percent);
void setBackgroundColor(QRgb color);
void setSelectBoxColors(QRgb colorL, QRgb fillL, QRgb colorR, QRgb fillR, int alpha);
void toggleSnap(bool on);
void toggleGrid(bool on);
void toggleRuler(bool on);
void toggleOrtho(bool on);
void togglePolar(bool on);
void toggleQSnap(bool on);
void toggleQTrack(bool on);
void toggleLwt(bool on);
void toggleReal(bool on);
bool isLwtEnabled();
bool isRealEnabled();
void setGridColor(QRgb color);
void createGrid(const QString& gridType);
void setRulerColor(QRgb color);
void previewOn(int clone, int mode, qreal x, qreal y, qreal data);
void previewOff();
void enableMoveRapidFire();
void disableMoveRapidFire();
bool allowRubber();
void addToRubberRoom(QGraphicsItem* item);
void vulcanizeRubberRoom();
void clearRubberRoom();
void spareRubber(qint64 id);
void setRubberMode(int mode);
void setRubberPoint(const QString& key, const QPointF& point);
void setRubberText(const QString& key, const QString& txt);
protected:
void mouseDoubleClickEvent(QMouseEvent* event);
void mousePressEvent(QMouseEvent* event);
void mouseMoveEvent(QMouseEvent* event);
void mouseReleaseEvent(QMouseEvent* event);
void wheelEvent(QWheelEvent* event);
void contextMenuEvent(QContextMenuEvent* event);
void drawBackground(QPainter* painter, const QRectF& rect);
void drawForeground(QPainter* painter, const QRectF& rect);
void enterEvent(QEvent* event);
private:
QHash<qint64, QGraphicsItem*> hashDeletedObjects;
QList<qint64> spareRubberList;
QColor gridColor;
QPainterPath gridPath;
void createGridRect();
void createGridPolar();
void createGridIso();
QPainterPath originPath;
void createOrigin();
bool rulerMetric;
QColor rulerColor;
quint8 rulerPixelSize;
void loadRulerSettings();
bool willUnderflowInt32(qint64 a, qint64 b);
bool willOverflowInt32(qint64 a, qint64 b);
int roundToMultiple(bool roundUp, int numToRound, int multiple);
QPainterPath createRulerTextPath(float x, float y, QString str, float height);
QList<QGraphicsItem*> previewObjectList;
QGraphicsItemGroup* previewObjectItemGroup;
QPointF previewPoint;
qreal previewData;
int previewMode;
QList<QGraphicsItem*> createObjectList(QList<QGraphicsItem*> list);
QPointF cutCopyMousePoint;
QGraphicsItemGroup* pasteObjectItemGroup;
QPointF pasteDelta;
QList<QGraphicsItem*> rubberRoomList;
void copySelected();
bool grippingActive;
bool rapidMoveActive;
bool previewActive;
bool pastingActive;
bool movingActive;
bool selectingActive;
bool zoomWindowActive;
bool panningRealTimeActive;
bool panningPointActive;
bool panningActive;
bool qSnapActive;
bool qSnapToggle;
void startGripping(BaseObject* obj);
void stopGripping(bool accept = false);
BaseObject* gripBaseObj;
BaseObject* tempBaseObj;
MainWindow* mainWin;
QGraphicsScene* gscene;
QUndoStack* undoStack;
SelectBox* selectBox;
QPointF scenePressPoint;
QPoint pressPoint;
QPointF sceneMovePoint;
QPoint movePoint;
QPointF sceneReleasePoint;
QPoint releasePoint;
QPointF sceneGripPoint;
void updateMouseCoords(int x, int y);
QPoint viewMousePoint;
QPointF sceneMousePoint;
QRgb qsnapLocatorColor;
quint8 qsnapLocatorSize;
quint8 qsnapApertureSize;
QRgb gripColorCool;
QRgb gripColorHot;
quint8 gripSize;
quint8 pickBoxSize;
QRgb crosshairColor;
quint32 crosshairSize;
void panStart(const QPoint& point);
int panDistance;
int panStartX;
int panStartY;
void alignScenePointWithViewPoint(const QPointF& scenePoint, const QPoint& viewPoint);
inline qreal pi() { return (qAtan(1.0)*4.0); };
inline qreal radians(qreal degrees) { return (degrees*pi()/180.0); };
};
#endif /* EMBROIDERMODDER_H */
| 58,629 |
346 |
<reponame>FluffyQuack/ja2-stracciatella
#include "Dialogs.h"
#include "Directories.h"
#include "MercProfile.h"
#include "Soldier_Profile.h"
#include <string_theory/format>
ST::string Content::GetDialogueTextFilename(const MercProfile &profile,
bool useAlternateDialogueFile,
bool isCurrentlyTalking)
{
ST::string zFileName;
uint8_t ubFileNumID;
// Are we an NPC OR an RPC that has not been recruited?
// ATE: Did the || clause here to allow ANY RPC that talks while the talking menu is up to use an npc quote file
if ( useAlternateDialogueFile )
{
{
// assume EDT files are in EDT directory on HARD DRIVE
zFileName = ST::format("{}/d_{03d}.edt", NPCDATADIR, profile.getID());
}
}
else if (profile.isNPCorRPC()
&& ( !profile.isRecruited()
|| isCurrentlyTalking
|| profile.isForcedNPCQuote()))
{
ubFileNumID = profile.getID();
// ATE: If we are merc profile ID #151-154, all use 151's data....
if (profile.getID() >= HERVE && profile.getID() <= CARLO)
{
ubFileNumID = HERVE;
}
{
// assume EDT files are in EDT directory on HARD DRIVE
zFileName = ST::format("{}/{03d}.edt", NPCDATADIR, ubFileNumID);
}
}
else
{
{
// assume EDT files are in EDT directory on HARD DRIVE
zFileName = ST::format("{}/{03d}.edt", MERCEDTDIR, profile.getID());
}
}
return zFileName;
}
ST::string Content::GetDialogueVoiceFilename(const MercProfile &profile, uint16_t usQuoteNum,
bool useAlternateDialogueFile,
bool isCurrentlyTalking,
bool isRussianVersion)
{
ST::string zFileName;
uint8_t ubFileNumID;
// Are we an NPC OR an RPC that has not been recruited?
// ATE: Did the || clause here to allow ANY RPC that talks while the talking menu is up to use an npc quote file
if ( useAlternateDialogueFile )
{
{
// build name of wav file (characternum + quotenum)
zFileName = ST::format("{}/d_{03d}_{03d}.wav", NPC_SPEECHDIR, profile.getID(), usQuoteNum);
}
}
else if (profile.isNPCorRPC()
&& ( !profile.isRecruited()
|| isCurrentlyTalking
|| profile.isForcedNPCQuote()))
{
ubFileNumID = profile.getID();
// ATE: If we are merc profile ID #151-154, all use 151's data....
if (profile.getID() >= HERVE && profile.getID() <= CARLO)
{
ubFileNumID = HERVE;
}
zFileName = ST::format("{}/{03d}_{03d}.wav", NPC_SPEECHDIR, ubFileNumID, usQuoteNum);
}
else
{
{
if(isRussianVersion)
{
if (profile.isNPCorRPC() && profile.isRecruited())
{
zFileName = ST::format("{}/r_{03d}_{03d}.wav", SPEECHDIR, profile.getID(), usQuoteNum);
}
else
{
// build name of wav file (characternum + quotenum)
zFileName = ST::format("{}/{03d}_{03d}.wav", SPEECHDIR, profile.getID(), usQuoteNum);
}
}
else
{
// build name of wav file (characternum + quotenum)
zFileName = ST::format("{}/{03d}_{03d}.wav", SPEECHDIR, profile.getID(), usQuoteNum);
}
}
}
return zFileName;
}
| 1,216 |
854 |
<gh_stars>100-1000
__________________________________________________________________________________________________
sample 80 ms submission
class Solution:
def characterReplacement(self, s, k):
from collections import defaultdict
d = defaultdict(int)
l = 0
maxn = 0
for r in range(len(s)):
d[s[r]] += 1
maxn = max(maxn, d[s[r]])
if r - l + 1 > maxn + k: # bc it is for loop, r += 1 is later than if clause
d[s[l]] -= 1
l += 1
return len(s) - l
__________________________________________________________________________________________________
sample 13052 kb submission
class Solution:
def characterReplacement(self, s: str, k: int) -> int:
chars = set(s)
ans = 0
for c in chars:
i = j = 0
k1 = k
while j < len(s):
while j < len(s) and k1 >= 0:
if s[j] != c:
k1 -= 1
j += 1
# print(s, c, i, j)
ans = max(ans, j - i - (k1 < 0))
while i < j and k1 < 0:
if s[i] != c:
k1 += 1
i += 1
return ans
__________________________________________________________________________________________________
| 753 |
12,278 |
<reponame>189569400/ClickHouse
#ifndef BOOST_MPL_AUX_CONFIG_BCC_HPP_INCLUDED
#define BOOST_MPL_AUX_CONFIG_BCC_HPP_INCLUDED
// Copyright <NAME> 2008
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Id$
// $Date: 2004-09-02 10:41:37 -0500 (Thu, 02 Sep 2004) $
// $Revision: 24874 $
#include <boost/mpl/aux_/config/workaround.hpp>
#if !defined(BOOST_MPL_CFG_BCC590_WORKAROUNDS) \
&& !defined(BOOST_MPL_PREPROCESSING_MODE) \
&& BOOST_WORKAROUND(__BORLANDC__, >= 0x590) \
&& BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x610))
# define BOOST_MPL_CFG_BCC590_WORKAROUNDS
#endif
#endif // BOOST_MPL_AUX_CONFIG_BCC_HPP_INCLUDED
| 382 |
5,193 |
<filename>AriaCompiler/src/main/java/com/arialyy/compiler/ValuesUtil.java
/*
* Copyright (C) 2016 AriaLyy(https://github.com/AriaLyy/Aria)
*
* 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.arialyy.compiler;
import com.arialyy.annotations.Download;
import com.arialyy.annotations.DownloadGroup;
import com.arialyy.annotations.M3U8;
import com.arialyy.annotations.Upload;
import javax.lang.model.element.ExecutableElement;
/**
* Created by lyy on 2017/9/6.
* 获取注解value工具
*/
final class ValuesUtil {
/**
* 获取m3u8切片注解信息
*/
static String[] getM3U8PeerValues(ExecutableElement method, int annotationType) {
String[] values = null;
switch (annotationType) {
case ProxyConstance.TASK_START:
values = method.getAnnotation(M3U8.onPeerStart.class).value();
break;
case ProxyConstance.TASK_COMPLETE:
values = method.getAnnotation(M3U8.onPeerComplete.class).value();
break;
case ProxyConstance.TASK_FAIL:
values = method.getAnnotation(M3U8.onPeerFail.class).value();
break;
}
return values;
}
/**
* 获取下载任务组子任务的的注解数据
*/
static String[] getDownloadGroupSubValues(ExecutableElement method, int annotationType) {
String[] values = null;
switch (annotationType) {
case ProxyConstance.TASK_PRE:
values = method.getAnnotation(DownloadGroup.onSubTaskPre.class).value();
break;
case ProxyConstance.TASK_START:
values = method.getAnnotation(DownloadGroup.onSubTaskStart.class).value();
break;
case ProxyConstance.TASK_RUNNING:
values = method.getAnnotation(DownloadGroup.onSubTaskRunning.class).value();
break;
case ProxyConstance.TASK_STOP:
values = method.getAnnotation(DownloadGroup.onSubTaskStop.class).value();
break;
case ProxyConstance.TASK_COMPLETE:
values = method.getAnnotation(DownloadGroup.onSubTaskComplete.class).value();
break;
case ProxyConstance.TASK_CANCEL:
//values = method.getAnnotation(DownloadGroup.onSubTaskCancel.class).value();
break;
case ProxyConstance.TASK_FAIL:
values = method.getAnnotation(DownloadGroup.onSubTaskFail.class).value();
break;
}
return values;
}
/**
* 获取下载任务组的注解数据
*/
static String[] getDownloadGroupValues(ExecutableElement method, int annotationType) {
String[] values = null;
switch (annotationType) {
case ProxyConstance.PRE:
values = method.getAnnotation(DownloadGroup.onPre.class).value();
break;
case ProxyConstance.TASK_PRE:
values = method.getAnnotation(DownloadGroup.onTaskPre.class).value();
break;
case ProxyConstance.TASK_RESUME:
values = method.getAnnotation(DownloadGroup.onTaskResume.class).value();
break;
case ProxyConstance.TASK_START:
values = method.getAnnotation(DownloadGroup.onTaskStart.class).value();
break;
case ProxyConstance.TASK_RUNNING:
values = method.getAnnotation(DownloadGroup.onTaskRunning.class).value();
break;
case ProxyConstance.TASK_STOP:
values = method.getAnnotation(DownloadGroup.onTaskStop.class).value();
break;
case ProxyConstance.TASK_COMPLETE:
values = method.getAnnotation(DownloadGroup.onTaskComplete.class).value();
break;
case ProxyConstance.TASK_CANCEL:
values = method.getAnnotation(DownloadGroup.onTaskCancel.class).value();
break;
case ProxyConstance.TASK_FAIL:
values = method.getAnnotation(DownloadGroup.onTaskFail.class).value();
break;
}
return values;
}
/**
* 获取上传的注解数据
*/
static String[] getUploadValues(ExecutableElement method, int annotationType) {
String[] values = null;
switch (annotationType) {
case ProxyConstance.PRE:
values = method.getAnnotation(Upload.onPre.class).value();
break;
case ProxyConstance.TASK_PRE:
//values = method.getAnnotation(Upload.onTaskPre.class).value();
break;
case ProxyConstance.TASK_RESUME:
values = method.getAnnotation(Upload.onTaskResume.class).value();
break;
case ProxyConstance.TASK_START:
values = method.getAnnotation(Upload.onTaskStart.class).value();
break;
case ProxyConstance.TASK_RUNNING:
values = method.getAnnotation(Upload.onTaskRunning.class).value();
break;
case ProxyConstance.TASK_STOP:
values = method.getAnnotation(Upload.onTaskStop.class).value();
break;
case ProxyConstance.TASK_COMPLETE:
values = method.getAnnotation(Upload.onTaskComplete.class).value();
break;
case ProxyConstance.TASK_CANCEL:
values = method.getAnnotation(Upload.onTaskCancel.class).value();
break;
case ProxyConstance.TASK_FAIL:
values = method.getAnnotation(Upload.onTaskFail.class).value();
break;
case ProxyConstance.TASK_NO_SUPPORT_BREAKPOINT:
//values = method.getAnnotation(Upload.onNoSupportBreakPoint.class).value();
break;
}
return values;
}
/**
* 获取下载的注解数据
*/
static String[] getDownloadValues(ExecutableElement method, int annotationType) {
String[] values = null;
switch (annotationType) {
case ProxyConstance.PRE:
values = method.getAnnotation(Download.onPre.class).value();
break;
case ProxyConstance.TASK_PRE:
values = method.getAnnotation(Download.onTaskPre.class).value();
break;
case ProxyConstance.TASK_RESUME:
values = method.getAnnotation(Download.onTaskResume.class).value();
break;
case ProxyConstance.TASK_START:
values = method.getAnnotation(Download.onTaskStart.class).value();
break;
case ProxyConstance.TASK_RUNNING:
values = method.getAnnotation(Download.onTaskRunning.class).value();
break;
case ProxyConstance.TASK_STOP:
values = method.getAnnotation(Download.onTaskStop.class).value();
break;
case ProxyConstance.TASK_COMPLETE:
values = method.getAnnotation(Download.onTaskComplete.class).value();
break;
case ProxyConstance.TASK_CANCEL:
values = method.getAnnotation(Download.onTaskCancel.class).value();
break;
case ProxyConstance.TASK_FAIL:
values = method.getAnnotation(Download.onTaskFail.class).value();
break;
case ProxyConstance.TASK_NO_SUPPORT_BREAKPOINT:
values = method.getAnnotation(Download.onNoSupportBreakPoint.class).value();
break;
}
return values;
}
}
| 2,942 |
903 |
<filename>deps/qt-4.8.0/win32/ia32/src/gui/styles/qstylehelper_p.h<gh_stars>100-1000
/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (<EMAIL>)
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtCore/qglobal.h>
#include <QtCore/qpoint.h>
#include <QtCore/qstring.h>
#include <QtGui/qpolygon.h>
#include <QtCore/qstringbuilder.h>
#ifndef QSTYLEHELPER_P_H
#define QSTYLEHELPER_P_H
//
// W A R N I N G
// -------------
//
// This file is not part of the Qt API. It exists purely as an
// implementation detail. This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//
QT_BEGIN_NAMESPACE
class QPainter;
class QPixmap;
class QStyleOptionSlider;
class QStyleOption;
namespace QStyleHelper
{
QString uniqueName(const QString &key, const QStyleOption *option, const QSize &size);
qreal dpiScaled(qreal value);
#ifndef QT_NO_DIAL
qreal angle(const QPointF &p1, const QPointF &p2);
QPolygonF calcLines(const QStyleOptionSlider *dial);
int calcBigLineSize(int radius);
void drawDial(const QStyleOptionSlider *dial, QPainter *painter);
#endif //QT_NO_DIAL
void drawBorderPixmap(const QPixmap &pixmap, QPainter *painter, const QRect &rect,
int left = 0, int top = 0, int right = 0,
int bottom = 0);
}
// internal helper. Converts an integer value to an unique string token
template <typename T>
struct HexString
{
inline HexString(const T t)
: val(t)
{}
inline void write(QChar *&dest) const
{
const ushort hexChars[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
const char *c = reinterpret_cast<const char *>(&val);
for (uint i = 0; i < sizeof(T); ++i) {
*dest++ = hexChars[*c & 0xf];
*dest++ = hexChars[(*c & 0xf0) >> 4];
++c;
}
}
const T val;
};
// specialization to enable fast concatenating of our string tokens to a string
template <typename T>
struct QConcatenable<HexString<T> >
{
typedef HexString<T> type;
enum { ExactSize = true };
static int size(const HexString<T> &) { return sizeof(T) * 2; }
static inline void appendTo(const HexString<T> &str, QChar *&out) { str.write(out); }
typedef QString ConvertTo;
};
QT_END_NAMESPACE
#endif // QSTYLEHELPER_P_H
| 1,517 |
1,350 |
<gh_stars>1000+
[{"id":"NAME","type":"alpha","calc":true,"value":""},{"id":"SSN","type":"ssn","calc":true,"value":""},{"id":"NAMEB_1_","type":"alpha","calc":false,"value":""},{"id":"SSNB_1_","type":"ssn","calc":false,"value":""},{"id":"CONTRIBT_1_","type":"number","calc":false,"value":""},{"id":"CONTRIBS_1_","type":"number","calc":false,"value":""},{"id":"NAMEB_2_","type":"alpha","calc":false,"value":""},{"id":"SSNB_2_","type":"ssn","calc":false,"value":""},{"id":"CONTRIBT_2_","type":"number","calc":false,"value":""},{"id":"CONTRIBS_2_","type":"number","calc":false,"value":""},{"id":"NAMEB_3_","type":"alpha","calc":false,"value":""},{"id":"SSNB_3_","type":"ssn","calc":false,"value":""},{"id":"CONTRIBT_3_","type":"number","calc":false,"value":""},{"id":"CONTRIBS_3_","type":"number","calc":false,"value":""},{"id":"NAMEB_4_","type":"alpha","calc":false,"value":""},{"id":"SSNB_4_","type":"ssn","calc":false,"value":""},{"id":"CONTRIBT_4_","type":"number","calc":false,"value":""},{"id":"CONTRIBS_4_","type":"number","calc":false,"value":""},{"id":"NAMEB_5_","type":"alpha","calc":false,"value":""},{"id":"SSNB_5_","type":"ssn","calc":false,"value":""},{"id":"CONTRIBT_5_","type":"number","calc":false,"value":""},{"id":"CONTRIBS_5_","type":"number","calc":false,"value":""},{"id":"NAMEB_6_","type":"alpha","calc":false,"value":""},{"id":"SSNB_6_","type":"ssn","calc":false,"value":""},{"id":"CONTRIBT_6_","type":"number","calc":false,"value":""},{"id":"CONTRIBS_6_","type":"number","calc":false,"value":""},{"id":"NAMEB_7_","type":"alpha","calc":false,"value":""},{"id":"SSNB_7_","type":"ssn","calc":false,"value":""},{"id":"CONTRIBT_7_","type":"number","calc":false,"value":""},{"id":"CONTRIBS_7_","type":"number","calc":false,"value":""},{"id":"NAMEB_8_","type":"alpha","calc":false,"value":""},{"id":"SSNB_8_","type":"ssn","calc":false,"value":""},{"id":"CONTRIBT_8_","type":"number","calc":false,"value":""},{"id":"CONTRIBS_8_","type":"number","calc":false,"value":""},{"id":"NAMEB_9_","type":"alpha","calc":false,"value":""},{"id":"SSNB_9_","type":"ssn","calc":false,"value":""},{"id":"CONTRIBT_9_","type":"number","calc":false,"value":""},{"id":"CONTRIBS_9_","type":"number","calc":false,"value":""},{"id":"NAMEB_10_","type":"alpha","calc":false,"value":""},{"id":"SSNB_10_","type":"ssn","calc":false,"value":""},{"id":"CONTRIBT_10_","type":"number","calc":false,"value":""},{"id":"CONTRIBS_10_","type":"number","calc":false,"value":""},{"id":"CONTTTL","type":"number","calc":false,"value":""},{"id":"CONTSTL","type":"number","calc":false,"value":""},{"id":"MSAT","type":"number","calc":false,"value":""},{"id":"MSAS","type":"number","calc":false,"value":""},{"id":"HSAT","type":"number","calc":false,"value":""},{"id":"HSAS","type":"number","calc":false,"value":""},{"id":"DEDNT","type":"number","calc":true,"value":""},{"id":"DEDNS","type":"number","calc":true,"value":""},{"id":"INCT","type":"number","calc":false,"value":""},{"id":"INCS","type":"number","calc":false,"value":""},{"id":"LESST","type":"number","calc":true,"value":""},{"id":"LESSS","type":"number","calc":true,"value":""},{"id":"TOTDEDNS","type":"number","calc":true,"value":""}]
| 1,069 |
2,044 |
<filename>grpc-spring-boot-starter-demo/src/test/java/org/lognet/springboot/grpc/DemoAppTest.java
package org.lognet.springboot.grpc;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.grpc.ServerInterceptor;
import io.grpc.examples.CalculatorGrpc;
import io.grpc.examples.CalculatorOuterClass;
import io.grpc.examples.GreeterGrpc;
import io.grpc.examples.GreeterOuterClass;
import io.grpc.reflection.v1alpha.ServerReflectionGrpc;
import io.grpc.reflection.v1alpha.ServerReflectionRequest;
import io.grpc.reflection.v1alpha.ServerReflectionResponse;
import io.grpc.reflection.v1alpha.ServiceResponse;
import io.grpc.stub.StreamObserver;
import io.micrometer.prometheus.PrometheusConfig;
import org.awaitility.Awaitility;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.lognet.springboot.grpc.demo.DemoApp;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.system.OutputCaptureRule;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
/**
* Created by alexf on 28-Jan-16.
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {DemoApp.class, TestConfig.class}, webEnvironment = RANDOM_PORT
, properties = {"grpc.enableReflection=true",
"grpc.shutdownGrace=-1",
"spring.main.web-application-type=servlet"
})
@ActiveProfiles({"disable-security", "measure"})
public class DemoAppTest extends GrpcServerTestBase {
@Autowired
private PrometheusConfig prometheusConfig;
@Autowired
private TestRestTemplate restTemplate;
@Rule
public OutputCaptureRule outputCapture = new OutputCaptureRule();
@Autowired
@Qualifier("globalInterceptor")
private ServerInterceptor globalInterceptor;
@Test
public void disabledServerTest() throws Throwable {
assertNotNull(grpcServerRunner);
assertNull(grpcInprocessServerRunner);
}
@Test
public void interceptorsTest() throws ExecutionException, InterruptedException {
GreeterGrpc.newFutureStub(channel)
.sayHello(GreeterOuterClass.HelloRequest.newBuilder().setName("name").build())
.get().getMessage();
CalculatorGrpc.newFutureStub(channel)
.calculate(CalculatorOuterClass.CalculatorRequest.newBuilder().setNumber1(1).setNumber2(1).build())
.get().getResult();
// global interceptor should be invoked once on each service
Mockito.verify(globalInterceptor, Mockito.times(2)).interceptCall(Mockito.any(), Mockito.any(), Mockito.any());
// log interceptor should be invoked only on GreeterService and not CalculatorService
outputCapture.expect(containsString(GreeterGrpc.getSayHelloMethod().getFullMethodName()));
outputCapture.expect(not(containsString(CalculatorGrpc.getCalculateMethod().getFullMethodName())));
outputCapture.expect(containsString("I'm not Spring bean interceptor and still being invoked..."));
}
@Test
public void actuatorTest() throws ExecutionException, InterruptedException {
ResponseEntity<String> response = restTemplate.getForEntity("/actuator/env", String.class);
assertEquals(HttpStatus.OK, response.getStatusCode());
}
@Test
public void testDefaultConfigurer() {
Assert.assertEquals("Default configurer should be picked up",
context.getBean(GRpcServerBuilderConfigurer.class).getClass(),
GRpcServerBuilderConfigurer.class);
}
@Test
public void testReflection() throws InterruptedException {
List<String> discoveredServiceNames = new ArrayList<>();
ServerReflectionRequest request = ServerReflectionRequest.newBuilder().setListServices("services").setHost("localhost").build();
CountDownLatch latch = new CountDownLatch(1);
ServerReflectionGrpc.newStub(channel).serverReflectionInfo(new StreamObserver<ServerReflectionResponse>() {
@Override
public void onNext(ServerReflectionResponse value) {
List<ServiceResponse> serviceList = value.getListServicesResponse().getServiceList();
for (ServiceResponse serviceResponse : serviceList) {
discoveredServiceNames.add(serviceResponse.getName());
}
}
@Override
public void onError(Throwable t) {
}
@Override
public void onCompleted() {
latch.countDown();
}
}).onNext(request);
latch.await(3, TimeUnit.SECONDS);
assertFalse(discoveredServiceNames.isEmpty());
}
@Override
protected void afterGreeting() throws Exception {
ResponseEntity<ObjectNode> metricsResponse = restTemplate.getForEntity("/actuator/metrics", ObjectNode.class);
assertEquals(HttpStatus.OK, metricsResponse.getStatusCode());
final String metricName = "grpc.server.calls";
final Optional<String> containsGrpcServerCallsMetric = StreamSupport.stream(Spliterators.spliteratorUnknownSize(metricsResponse.getBody().withArray("names")
.elements(), Spliterator.NONNULL), false)
.map(JsonNode::asText)
.filter(metricName::equals)
.findFirst();
assertThat("Should contain " + metricName,containsGrpcServerCallsMetric.isPresent());
Callable<Long> getPrometheusMetrics = () -> {
ResponseEntity<String> response = restTemplate.getForEntity("/actuator/prometheus", String.class);
assertEquals(HttpStatus.OK, response.getStatusCode());
return Stream.of(response.getBody().split(System.lineSeparator()))
.filter(s -> s.contains(metricName.replace('.','_')))
.count();
};
Awaitility
.waitAtMost(Duration.ofMillis(prometheusConfig.step().toMillis() * 2))
.until(getPrometheusMetrics,Matchers.greaterThan(0L));
}
}
| 2,714 |
373 |
<reponame>ADLINK/edk2-platforms
/** @file
Copyright (c) 2017 - 2019, Intel Corporation. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#include <Uefi.h>
#include <PiDxe.h>
#include <Library/TestPointCheckLib.h>
#include <Library/TestPointLib.h>
#include <Library/DebugLib.h>
#include <Library/UefiLib.h>
#include <Library/PrintLib.h>
#include <Library/MemoryAllocationLib.h>
#include <Guid/GlobalVariable.h>
#include <Guid/ImageAuthentication.h>
typedef struct {
CHAR16 *Name;
EFI_GUID *Guid;
UINT8 ExpectedSize;
UINT8 ExpectedData;
} VARIABLE_LIST;
VARIABLE_LIST mUefiSecureBootVariable[] = {
{EFI_PLATFORM_KEY_NAME, &gEfiGlobalVariableGuid},
{EFI_KEY_EXCHANGE_KEY_NAME, &gEfiGlobalVariableGuid},
{EFI_IMAGE_SECURITY_DATABASE, &gEfiImageSecurityDatabaseGuid},
{EFI_IMAGE_SECURITY_DATABASE1, &gEfiImageSecurityDatabaseGuid},
};
VARIABLE_LIST mUefiSecureBootModeVariable[] = {
{EFI_SECURE_BOOT_MODE_NAME, &gEfiGlobalVariableGuid, sizeof(UINT8), 1},
{EFI_SETUP_MODE_NAME, &gEfiGlobalVariableGuid, sizeof(UINT8), 0},
};
EFI_STATUS
EFIAPI
TestPointCheckUefiSecureBoot (
VOID
)
{
VOID *Variable;
UINTN Size;
UINTN Index;
EFI_STATUS Status;
EFI_STATUS ReturnStatus;
DEBUG ((DEBUG_INFO, "==== TestPointCheckUefiSecureBoot - Enter\n"));
ReturnStatus = EFI_SUCCESS;
for (Index = 0; Index < sizeof(mUefiSecureBootVariable)/sizeof(mUefiSecureBootVariable[0]); Index++) {
Status = GetVariable2 (mUefiSecureBootVariable[Index].Name, mUefiSecureBootVariable[Index].Guid, &Variable, &Size);
if(Variable == NULL) {
return EFI_NOT_FOUND;
}
if (EFI_ERROR(Status)) {
DEBUG ((DEBUG_ERROR, "Variable - %S not found\n", mUefiSecureBootVariable[Index].Name));
ReturnStatus = Status;
TestPointLibAppendErrorString (
PLATFORM_TEST_POINT_ROLE_PLATFORM_IBV,
NULL,
TEST_POINT_BYTE5_READY_TO_BOOT_UEFI_SECURE_BOOT_ENABLED_ERROR_CODE \
TEST_POINT_READY_TO_BOOT \
TEST_POINT_BYTE5_READY_TO_BOOT_UEFI_SECURE_BOOT_ENABLED_ERROR_STRING
);
} else {
FreePool (Variable);
}
}
for (Index = 0; Index < sizeof(mUefiSecureBootModeVariable)/sizeof(mUefiSecureBootModeVariable[0]); Index++) {
Status = GetVariable2 (mUefiSecureBootModeVariable[Index].Name, mUefiSecureBootModeVariable[Index].Guid, &Variable, &Size);
if(Variable == NULL) {
return EFI_NOT_FOUND;
}
if (EFI_ERROR(Status)) {
DEBUG ((DEBUG_ERROR, "Variable - %S not found\n", mUefiSecureBootModeVariable[Index].Name));
ReturnStatus = Status;
TestPointLibAppendErrorString (
PLATFORM_TEST_POINT_ROLE_PLATFORM_IBV,
NULL,
TEST_POINT_BYTE5_READY_TO_BOOT_UEFI_SECURE_BOOT_ENABLED_ERROR_CODE \
TEST_POINT_READY_TO_BOOT \
TEST_POINT_BYTE5_READY_TO_BOOT_UEFI_SECURE_BOOT_ENABLED_ERROR_STRING
);
} else {
if ((Size != mUefiSecureBootModeVariable[Index].ExpectedSize) ||
(*(UINT8 *)Variable != mUefiSecureBootModeVariable[Index].ExpectedData)) {
DEBUG ((DEBUG_ERROR, "Variable - %S is not expected (0x%x)\n", mUefiSecureBootModeVariable[Index].Name, *(UINT8 *)Variable));
ReturnStatus = EFI_SECURITY_VIOLATION;
TestPointLibAppendErrorString (
PLATFORM_TEST_POINT_ROLE_PLATFORM_IBV,
NULL,
TEST_POINT_BYTE5_READY_TO_BOOT_UEFI_SECURE_BOOT_ENABLED_ERROR_CODE \
TEST_POINT_READY_TO_BOOT \
TEST_POINT_BYTE5_READY_TO_BOOT_UEFI_SECURE_BOOT_ENABLED_ERROR_STRING
);
}
FreePool (Variable);
}
}
DEBUG ((DEBUG_INFO, "==== TestPointCheckUefiSecureBoot - Exit\n"));
return ReturnStatus;
}
| 1,803 |
335 |
{
"word": "Virus",
"definitions": [
"an infective agent that typically consists of a nucleic acid molecule in a protein coat, is too small to be seen by light microscopy, and is able to multiply only within the living cells of a host",
"an infection or disease caused by a virus",
"a harmful or corrupting influence",
"a piece of code that is capable of copying itself and typically has a detrimental effect, such as corrupting the system or destroying data"
],
"parts-of-speech": "Noun"
}
| 165 |
460 |
<filename>trunk/win/Source/Includes/QtIncludes/src/scripttools/debugging/qscriptdebuggercodefinderwidget_p.h
/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (<EMAIL>)
**
** This file is part of the QtSCriptTools module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QSCRIPTDEBUGGERCODEFINDERWIDGET_P_H
#define QSCRIPTDEBUGGERCODEFINDERWIDGET_P_H
//
// W A R N I N G
// -------------
//
// This file is not part of the Qt API. It exists purely as an
// implementation detail. This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//
#include "qscriptdebuggercodefinderwidgetinterface_p.h"
QT_BEGIN_NAMESPACE
class QScriptDebuggerCodeFinderWidgetPrivate;
class Q_AUTOTEST_EXPORT QScriptDebuggerCodeFinderWidget:
public QScriptDebuggerCodeFinderWidgetInterface
{
Q_OBJECT
public:
QScriptDebuggerCodeFinderWidget(QWidget *parent = 0);
~QScriptDebuggerCodeFinderWidget();
int findOptions() const;
QString text() const;
void setText(const QString &text);
void setOK(bool ok);
void setWrapped(bool wrapped);
protected:
void keyPressEvent(QKeyEvent *e);
private:
Q_DECLARE_PRIVATE(QScriptDebuggerCodeFinderWidget)
Q_DISABLE_COPY(QScriptDebuggerCodeFinderWidget)
Q_PRIVATE_SLOT(d_func(), void _q_updateButtons())
Q_PRIVATE_SLOT(d_func(), void _q_onTextChanged(const QString &))
Q_PRIVATE_SLOT(d_func(), void _q_next())
Q_PRIVATE_SLOT(d_func(), void _q_previous())
};
QT_END_NAMESPACE
#endif
| 1,034 |
14,668 |
<filename>components/sync_sessions/local_session_event_router.h
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_SYNC_SESSIONS_LOCAL_SESSION_EVENT_ROUTER_H_
#define COMPONENTS_SYNC_SESSIONS_LOCAL_SESSION_EVENT_ROUTER_H_
#include "url/gurl.h"
namespace sync_sessions {
class SyncedTabDelegate;
// An interface defining the ways in which local open tab events can interact
// with session sync. All local tab events flow to sync via this interface.
// In that way it is analogous to sync changes flowing to the local model
// via ProcessSyncChanges, just with a more granular breakdown.
class LocalSessionEventHandler {
public:
LocalSessionEventHandler(const LocalSessionEventHandler&) = delete;
LocalSessionEventHandler& operator=(const LocalSessionEventHandler&) = delete;
virtual ~LocalSessionEventHandler() {}
// Called when asynchronous session restore has completed. On Android, this
// can be called multiple times (e.g. transition from a CCT without tabbed
// window to actually starting a tabbed activity).
virtual void OnSessionRestoreComplete() = 0;
// A local navigation event took place that affects the synced session
// for this instance of Chrome.
virtual void OnLocalTabModified(SyncedTabDelegate* modified_tab) = 0;
protected:
LocalSessionEventHandler() {}
};
// The LocalSessionEventRouter is responsible for hooking itself up to various
// notification sources in the browser process and forwarding relevant
// events to a handler as defined in the LocalSessionEventHandler contract.
class LocalSessionEventRouter {
public:
LocalSessionEventRouter(const LocalSessionEventRouter&) = delete;
LocalSessionEventRouter& operator=(const LocalSessionEventRouter&) = delete;
virtual ~LocalSessionEventRouter() {}
virtual void StartRoutingTo(LocalSessionEventHandler* handler) = 0;
virtual void Stop() = 0;
protected:
LocalSessionEventRouter() {}
};
} // namespace sync_sessions
#endif // COMPONENTS_SYNC_SESSIONS_LOCAL_SESSION_EVENT_ROUTER_H_
| 587 |
892 |
<gh_stars>100-1000
{
"schema_version": "1.2.0",
"id": "GHSA-f4ww-w2w8-hp7w",
"modified": "2022-05-13T01:01:08Z",
"published": "2022-05-13T01:01:08Z",
"aliases": [
"CVE-2016-8721"
],
"details": "An exploitable OS Command Injection vulnerability exists in the web application 'ping' functionality of Moxa AWK-3131A Wireless Access Points running firmware 1.1. Specially crafted web form input can cause an OS Command Injection resulting in complete compromise of the vulnerable device. An attacker can exploit this vulnerability remotely.",
"severity": [
{
"type": "CVSS_V3",
"score": "CVSS:3.0/AV:N/AC:L/PR:H/UI:N/S:C/C:H/I:H/A:H"
}
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2016-8721"
},
{
"type": "WEB",
"url": "http://www.talosintelligence.com/reports/TALOS-2016-0235/"
}
],
"database_specific": {
"cwe_ids": [
"CWE-78"
],
"severity": "CRITICAL",
"github_reviewed": false
}
}
| 460 |
4,145 |
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import tempfile
import numpy as np
import pytest
import torch
from omegaconf import DictConfig, OmegaConf
from nemo.collections.asr.models import EncDecCTCModel
try:
from eff.cookbooks import NeMoCookbook
_EFF_PRESENT_ = True
except ImportError:
_EFF_PRESENT_ = False
# A decorator marking the EFF requirement.
requires_eff = pytest.mark.skipif(not _EFF_PRESENT_, reason="Export File Format library required to run test")
@pytest.fixture()
def asr_model():
preprocessor = {'cls': 'nemo.collections.asr.modules.AudioToMelSpectrogramPreprocessor', 'params': dict({})}
encoder = {
'cls': 'nemo.collections.asr.modules.ConvASREncoder',
'params': {
'feat_in': 64,
'activation': 'relu',
'conv_mask': True,
'jasper': [
{
'filters': 1024,
'repeat': 1,
'kernel': [1],
'stride': [1],
'dilation': [1],
'dropout': 0.0,
'residual': False,
'separable': True,
'se': True,
'se_context_size': -1,
}
],
},
}
decoder = {
'cls': 'nemo.collections.asr.modules.ConvASRDecoder',
'params': {
'feat_in': 1024,
'num_classes': 28,
'vocabulary': [
' ',
'a',
'b',
'c',
'd',
'e',
'f',
'g',
'h',
'i',
'j',
'k',
'l',
'm',
'n',
'o',
'p',
'q',
'r',
's',
't',
'u',
'v',
'w',
'x',
'y',
'z',
"'",
],
},
}
modelConfig = DictConfig(
{'preprocessor': DictConfig(preprocessor), 'encoder': DictConfig(encoder), 'decoder': DictConfig(decoder)}
)
model_instance = EncDecCTCModel(cfg=modelConfig)
return model_instance
class TestFileIO:
@pytest.mark.unit
def test_to_from_config_file(self, asr_model):
"""" Test makes sure that the second instance created with the same configuration (BUT NOT checkpoint)
has different weights. """
with tempfile.NamedTemporaryFile() as fp:
yaml_filename = fp.name
asr_model.to_config_file(path2yaml_file=yaml_filename)
next_instance = EncDecCTCModel.from_config_file(path2yaml_file=yaml_filename)
assert isinstance(next_instance, EncDecCTCModel)
assert len(next_instance.decoder.vocabulary) == 28
assert asr_model.num_weights == next_instance.num_weights
w1 = asr_model.encoder.encoder[0].mconv[0].conv.weight.data.detach().cpu().numpy()
w2 = next_instance.encoder.encoder[0].mconv[0].conv.weight.data.detach().cpu().numpy()
assert not np.array_equal(w1, w2)
@pytest.mark.unit
def test_save_restore_from_nemo_file(self, asr_model):
"""" Test makes sure that the second instance created from the same configuration AND checkpoint
has the same weights. """
with tempfile.NamedTemporaryFile() as fp:
filename = fp.name
# Save model (with random artifact).
with tempfile.NamedTemporaryFile() as artifact:
asr_model.register_artifact(config_path="abc", src=artifact.name)
asr_model.save_to(save_path=filename)
# Restore the model.
asr_model2 = EncDecCTCModel.restore_from(restore_path=filename)
assert len(asr_model.decoder.vocabulary) == len(asr_model2.decoder.vocabulary)
assert asr_model.num_weights == asr_model2.num_weights
w1 = asr_model.encoder.encoder[0].mconv[0].conv.weight.data.detach().cpu().numpy()
w2 = asr_model2.encoder.encoder[0].mconv[0].conv.weight.data.detach().cpu().numpy()
assert np.array_equal(w1, w2)
@requires_eff
@pytest.mark.unit
def test_eff_save_restore_from_nemo_file_encrypted(self, asr_model):
"""" Test makes sure that after encrypted save-restore the model has the same weights. """
with tempfile.NamedTemporaryFile() as fp:
filename = fp.name
# Set key - use checkpoint encryption.
NeMoCookbook.set_encryption_key("test_key")
# Save model (with random artifact).
with tempfile.NamedTemporaryFile() as artifact:
asr_model.register_artifact(config_path="abc", src=artifact.name)
asr_model.save_to(save_path=filename)
# Try to restore the encrypted archive (weights) without the encryption key.
NeMoCookbook.set_encryption_key(None)
with pytest.raises(PermissionError):
# Restore the model.
asr_model2 = EncDecCTCModel.restore_from(restore_path=filename)
# Restore the model.
NeMoCookbook.set_encryption_key("test_key")
asr_model3 = EncDecCTCModel.restore_from(restore_path=filename)
# Reset encryption so it won't mess up with other save/restore.
NeMoCookbook.set_encryption_key(None)
assert asr_model.num_weights == asr_model3.num_weights
@pytest.mark.unit
def test_save_restore_from_nemo_file_with_override(self, asr_model, tmpdir):
"""" Test makes sure that the second instance created from the same configuration AND checkpoint
has the same weights.
Args:
tmpdir: fixture providing a temporary directory unique to the test invocation.
"""
# Name of the archive in tmp folder.
filename = os.path.join(tmpdir, "eff.nemo")
# Get path where the command is executed - the artifacts will be "retrieved" there.
# (original .nemo behavior)
cwd = os.getcwd()
with tempfile.NamedTemporaryFile(mode='a+') as conf_fp:
# Create a "random artifact".
with tempfile.NamedTemporaryFile(mode="w", delete=False) as artifact:
artifact.write("magic content 42")
# Remember the filename of the artifact.
_, artifact_filename = os.path.split(artifact.name)
# Add artifact to model.
asr_model.register_artifact(config_path="abc", src=artifact.name)
# Save model (with "random artifact").
asr_model.save_to(save_path=filename)
# Modify config slightly
cfg = asr_model.cfg
cfg.encoder.activation = 'swish'
yaml_cfg = OmegaConf.to_yaml(cfg)
conf_fp.write(yaml_cfg)
conf_fp.seek(0)
# Restore the model.
asr_model2 = EncDecCTCModel.restore_from(restore_path=filename, override_config_path=conf_fp.name)
assert len(asr_model.decoder.vocabulary) == len(asr_model2.decoder.vocabulary)
assert asr_model.num_weights == asr_model2.num_weights
w1 = asr_model.encoder.encoder[0].mconv[0].conv.weight.data.detach().cpu().numpy()
w2 = asr_model2.encoder.encoder[0].mconv[0].conv.weight.data.detach().cpu().numpy()
assert np.array_equal(w1, w2)
assert asr_model2.cfg.encoder.activation == 'swish'
@pytest.mark.unit
def test_save_model_level_pt_ckpt(self, asr_model):
with tempfile.TemporaryDirectory() as ckpt_dir:
nemo_file = os.path.join(ckpt_dir, 'asr.nemo')
asr_model.save_to(nemo_file)
# Save model level PT checkpoint
asr_model.extract_state_dict_from(nemo_file, ckpt_dir)
ckpt_path = os.path.join(ckpt_dir, 'model_weights.ckpt')
assert os.path.exists(ckpt_path)
# Restore the model.
asr_model2 = EncDecCTCModel.restore_from(restore_path=nemo_file)
assert len(asr_model.decoder.vocabulary) == len(asr_model2.decoder.vocabulary)
assert asr_model.num_weights == asr_model2.num_weights
# Change weights values
asr_model2.encoder.encoder[0].mconv[0].conv.weight.data += 1.0
w1 = asr_model.encoder.encoder[0].mconv[0].conv.weight.data.detach().cpu().numpy()
w2 = asr_model2.encoder.encoder[0].mconv[0].conv.weight.data.detach().cpu().numpy()
assert not np.array_equal(w1, w2)
# Restore from checkpoint
asr_model2.load_state_dict(torch.load(ckpt_path))
w1 = asr_model.encoder.encoder[0].mconv[0].conv.weight.data.detach().cpu().numpy()
w2 = asr_model2.encoder.encoder[0].mconv[0].conv.weight.data.detach().cpu().numpy()
assert np.array_equal(w1, w2)
@pytest.mark.unit
def test_save_module_level_pt_ckpt(self, asr_model):
with tempfile.TemporaryDirectory() as ckpt_dir:
nemo_file = os.path.join(ckpt_dir, 'asr.nemo')
asr_model.save_to(nemo_file)
# Save model level PT checkpoint
asr_model.extract_state_dict_from(nemo_file, ckpt_dir, split_by_module=True)
encoder_path = os.path.join(ckpt_dir, 'encoder.ckpt')
decoder_path = os.path.join(ckpt_dir, 'decoder.ckpt')
preprocessor_path = os.path.join(ckpt_dir, 'preprocessor.ckpt')
assert os.path.exists(encoder_path)
assert os.path.exists(decoder_path)
assert os.path.exists(preprocessor_path)
# Restore the model.
asr_model2 = EncDecCTCModel.restore_from(restore_path=nemo_file)
assert len(asr_model.decoder.vocabulary) == len(asr_model2.decoder.vocabulary)
assert asr_model.num_weights == asr_model2.num_weights
# Change weights values
asr_model2.encoder.encoder[0].mconv[0].conv.weight.data += 1.0
w1 = asr_model.encoder.encoder[0].mconv[0].conv.weight.data.detach().cpu().numpy()
w2 = asr_model2.encoder.encoder[0].mconv[0].conv.weight.data.detach().cpu().numpy()
assert not np.array_equal(w1, w2)
# Restore from checkpoint
asr_model2.encoder.load_state_dict(torch.load(encoder_path))
w1 = asr_model.encoder.encoder[0].mconv[0].conv.weight.data.detach().cpu().numpy()
w2 = asr_model2.encoder.encoder[0].mconv[0].conv.weight.data.detach().cpu().numpy()
assert np.array_equal(w1, w2)
| 5,474 |
1,383 |
// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: <NAME>, <NAME>
// =============================================================================
//
// Chrono::Multicore unit test for MPR collision detection
// =============================================================================
#include "unit_testing.h"
using namespace chrono;
TEST(ChronoMulticore, other_math) {
uvec4 a = _make_uvec4(1, 2, 3, 4);
uvec4 r = Sort(a);
Assert_eq(a, r);
uvec4 b;
b = _make_uvec4(4, 3, 2, 1);
r = Sort(b);
Assert_eq(a, r);
b = _make_uvec4(4, 2, 3, 1);
r = Sort(b);
Assert_eq(a, r);
b = _make_uvec4(3, 4, 2, 1);
r = Sort(b);
Assert_eq(a, r);
b = _make_uvec4(1, 3, 2, 4);
r = Sort(b);
Assert_eq(a, r);
}
| 407 |
341 |
<filename>tests/conftest.py
import os
import pytest
const_fixtures = {
'v': '5.131',
'lang': 'en'
}
env_fixtures = (
'VK_ACCESS_TOKEN',
'VK_USER_LOGIN',
'VK_USER_PASSWORD'
)
def const_fixture(value):
@pytest.fixture(scope='session')
def fixture():
return value
return fixture
def env_fixture(var):
@pytest.fixture(scope='session')
def fixture():
if os.getenv(var):
return os.environ[var]
pytest.skip(f'{var} env var not defined') # pragma: no cover
return fixture
for name, value in const_fixtures.items():
globals()[name] = const_fixture(value)
for var in env_fixtures:
globals()[var[var.startswith('VK_') * 3:].lower()] = env_fixture(var)
| 327 |
918 |
/*
* 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.gobblin.metrics.reporter;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Histogram;
import com.codahale.metrics.Meter;
import com.google.common.collect.Lists;
import org.apache.gobblin.metrics.Measurements;
import org.apache.gobblin.metrics.Metric;
import org.apache.gobblin.metrics.MetricContext;
import org.apache.gobblin.metrics.MetricReport;
import org.apache.gobblin.metrics.Tag;
import org.apache.gobblin.metrics.kafka.KafkaReporter;
import org.apache.gobblin.metrics.kafka.Pusher;
import org.apache.gobblin.metrics.reporter.util.MetricReportUtils;
@Test(groups = { "gobblin.metrics" })
public class KafkaReporterTest {
public KafkaReporterTest() throws IOException, InterruptedException {}
/**
* Get builder for KafkaReporter (override if testing an extension of KafkaReporter)
* @return KafkaReporter builder
*/
public KafkaReporter.Builder<? extends KafkaReporter.Builder> getBuilder(Pusher pusher) {
return KafkaReporter.BuilderFactory.newBuilder().withKafkaPusher(pusher);
}
public KafkaReporter.Builder<? extends KafkaReporter.Builder> getBuilderFromContext(Pusher pusher) {
return KafkaReporter.BuilderFactory.newBuilder().withKafkaPusher(pusher);
}
@Test
public void testKafkaReporter() throws IOException {
MetricContext metricContext =
MetricContext.builder(this.getClass().getCanonicalName() + ".testKafkaReporter").build();
Counter counter = metricContext.counter("com.linkedin.example.counter");
Meter meter = metricContext.meter("com.linkedin.example.meter");
Histogram histogram = metricContext.histogram("com.linkedin.example.histogram");
MockKafkaPusher pusher = new MockKafkaPusher();
KafkaReporter kafkaReporter = getBuilder(pusher).build("localhost:0000", "topic", new Properties());
counter.inc();
meter.mark(2);
histogram.update(1);
histogram.update(1);
histogram.update(2);
kafkaReporter.report(metricContext);
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
Map<String, Double> expected = new HashMap<>();
expected.put("com.linkedin.example.counter." + Measurements.COUNT, 1.0);
expected.put("com.linkedin.example.meter." + Measurements.COUNT, 2.0);
expected.put("com.linkedin.example.histogram." + Measurements.COUNT, 3.0);
MetricReport nextReport = nextReport(pusher.messageIterator());
expectMetricsWithValues(nextReport, expected);
kafkaReporter.report(metricContext);
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
Set<String> expectedSet = new HashSet<>();
expectedSet.add("com.linkedin.example.counter." + Measurements.COUNT);
expectedSet.add("com.linkedin.example.meter." + Measurements.COUNT);
expectedSet.add("com.linkedin.example.meter." + Measurements.MEAN_RATE);
expectedSet.add("com.linkedin.example.meter." + Measurements.RATE_1MIN);
expectedSet.add("com.linkedin.example.meter." + Measurements.RATE_5MIN);
expectedSet.add("com.linkedin.example.meter." + Measurements.RATE_15MIN);
expectedSet.add("com.linkedin.example.histogram." + Measurements.MEAN);
expectedSet.add("com.linkedin.example.histogram." + Measurements.MIN);
expectedSet.add("com.linkedin.example.histogram." + Measurements.MAX);
expectedSet.add("com.linkedin.example.histogram." + Measurements.MEDIAN);
expectedSet.add("com.linkedin.example.histogram." + Measurements.PERCENTILE_75TH);
expectedSet.add("com.linkedin.example.histogram." + Measurements.PERCENTILE_95TH);
expectedSet.add("com.linkedin.example.histogram." + Measurements.PERCENTILE_99TH);
expectedSet.add("com.linkedin.example.histogram." + Measurements.PERCENTILE_999TH);
expectedSet.add("com.linkedin.example.histogram." + Measurements.COUNT);
nextReport = nextReport(pusher.messageIterator());
expectMetrics(nextReport, expectedSet, true);
kafkaReporter.close();
}
@Test
public void kafkaReporterTagsTest() throws IOException {
MetricContext metricContext =
MetricContext.builder(this.getClass().getCanonicalName() + ".kafkaReporterTagsTest").build();
Counter counter = metricContext.counter("com.linkedin.example.counter");
Tag<?> tag1 = new Tag<>("tag1", "value1");
Tag<?> tag2 = new Tag<>("tag2", 2);
MockKafkaPusher pusher = new MockKafkaPusher();
KafkaReporter kafkaReporter =
getBuilder(pusher).withTags(Lists.newArrayList(tag1, tag2)).build("localhost:0000", "topic", new Properties());
counter.inc();
kafkaReporter.report(metricContext);
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
MetricReport metricReport = nextReport(pusher.messageIterator());
Assert.assertEquals(4, metricReport.getTags().size());
Assert.assertTrue(metricReport.getTags().containsKey(tag1.getKey()));
Assert.assertEquals(metricReport.getTags().get(tag1.getKey()), tag1.getValue().toString());
Assert.assertTrue(metricReport.getTags().containsKey(tag2.getKey()));
Assert.assertEquals(metricReport.getTags().get(tag2.getKey()), tag2.getValue().toString());
}
@Test
public void kafkaReporterContextTest() throws IOException {
Tag<?> tag1 = new Tag<>("tag1", "value1");
MetricContext context = MetricContext.builder("context").addTag(tag1).build();
Counter counter = context.counter("com.linkedin.example.counter");
MockKafkaPusher pusher = new MockKafkaPusher();
KafkaReporter kafkaReporter = getBuilderFromContext(pusher).build("localhost:0000", "topic", new Properties());
counter.inc();
kafkaReporter.report(context);
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
MetricReport metricReport = nextReport(pusher.messageIterator());
Assert.assertEquals(3, metricReport.getTags().size());
Assert.assertTrue(metricReport.getTags().containsKey(tag1.getKey()));
Assert.assertEquals(metricReport.getTags().get(tag1.getKey()), tag1.getValue().toString());
}
/**
* Expect a list of metrics with specific values.
* Fail if not all metrics are received, or some metric has the wrong value.
* @param report MetricReport.
* @param expected map of expected metric names and their values
* @throws IOException
*/
private void expectMetricsWithValues(MetricReport report, Map<String, Double> expected) throws IOException {
List<Metric> metricIterator = report.getMetrics();
for (Metric metric : metricIterator) {
if (expected.containsKey(metric.getName())) {
Assert.assertEquals(expected.get(metric.getName()), metric.getValue());
expected.remove(metric.getName());
}
}
Assert.assertTrue(expected.isEmpty());
}
/**
* Expect a set of metric names. Will fail if not all of these metrics are received.
* @param report MetricReport
* @param expected set of expected metric names
* @param strict if set to true, will fail if receiving any metric that is not expected
* @throws IOException
*/
private void expectMetrics(MetricReport report, Set<String> expected, boolean strict) throws IOException {
List<Metric> metricIterator = report.getMetrics();
for (Metric metric : metricIterator) {
//System.out.println(String.format("expectedSet.add(\"%s\")", metric.name));
if (expected.contains(metric.getName())) {
expected.remove(metric.getName());
} else if (strict && !metric.getName().contains(MetricContext.GOBBLIN_METRICS_NOTIFICATIONS_TIMER_NAME)) {
Assert.assertTrue(false, "Metric present in report not expected: " + metric.toString());
}
}
Assert.assertTrue(expected.isEmpty());
}
/**
* Extract the next metric from the Kafka iterator
* Assumes existence of the metric has already been checked.
* @param it Kafka ConsumerIterator
* @return next metric in the stream
* @throws IOException
*/
protected MetricReport nextReport(Iterator<byte[]> it) throws IOException {
Assert.assertTrue(it.hasNext());
return MetricReportUtils.deserializeReportFromJson(new MetricReport(), it.next());
}
}
| 3,128 |
386 |
<filename>include/IECoreNuke/ParameterHandler.h
//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2010-2013, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#ifndef IECORENUKE_PARAMETERHANDLER_H
#define IECORENUKE_PARAMETERHANDLER_H
#include "IECoreNuke/Export.h"
#include "IECore/Parameter.h"
#include "DDImage/Op.h"
namespace IECoreNuke
{
IE_CORE_FORWARDDECLARE( ParameterHandler )
/// ParameterHandlers are responsible for mapping between IECore::Parameters
/// and DD::Image::Knobs and DD::Image::Op inputs.
class IECORENUKE_API ParameterHandler : public IECore::RefCounted
{
public :
enum ValueSource
{
Knob,
Storage
};
typedef std::vector<DD::Image::Op *>::const_iterator InputIterator;
/// Returns the minimum number of inputs this Parameter needs to represent itself.
/// Defaults to 0, as most ParameterHandlers will instead use the knobs() mechanism
/// below.
virtual int minimumInputs( const IECore::Parameter *parameter );
/// Returns the maximum number of inputs this Parameter needs to represent itself, also
/// defaulting to 0. Please note that it is only possible for the last Parameter on
/// any given node to have min!=max - warnings will be issued if this is not the case.
virtual int maximumInputs( const IECore::Parameter *parameter );
/// Returns true if the specified op is suitable for connection for the specified input.
/// Here the input number is relative to the ParameterHandler rather than being absolute for
/// the Node. Default implementation returns false.
virtual bool testInput( const IECore::Parameter *parameter, int input, const DD::Image::Op *op );
/// Sets the value of the parameter from the inputs created based on the result of minimumInputs()
/// and maximumInputs().
virtual void setParameterValue( IECore::Parameter *parameter, InputIterator first, InputIterator last );
/// Declares knobs to represent the Parameter.
virtual void knobs( const IECore::Parameter *parameter, const char *knobName, DD::Image::Knob_Callback f );
/// Transfers the value from Nuke onto the Parameter. ValueSource may be passed
/// a value of Knob if it is known that Nuke hasn't stored knob
/// values yet - for instance in a knob_changed() method with
/// a KNOB_CHANGED_ALWAYS knob. This causes the value to be retrieved
/// directly from the knob at the current time, rather than from the
/// value stored by the knob.
virtual void setParameterValue( IECore::Parameter *parameter, ValueSource valueSource = Storage );
/// Transfers the value from the Parameter back onto the nuke knob at the current time.
virtual void setKnobValue( const IECore::Parameter *parameter );
/// ParameterHandlers may need to store state separately from the knobs they create,
/// so that it is available to the first knobs() call when scripts are loaded. This
/// function may be implemented to return such state, and the client must make sure
/// it is restored via setState() before knobs() is called.
virtual IECore::ObjectPtr getState( const IECore::Parameter *parameter );
/// Restore state previously retrieved by getState().
virtual void setState( IECore::Parameter *parameter, const IECore::Object *state );
/// Factory function to create a ParameterHandler suitable for a given Parameter.
static ParameterHandlerPtr create( const IECore::Parameter *parameter );
protected :
ParameterHandler();
/// Should be called by derived classes to get a good label for the main knob
std::string knobLabel( const IECore::Parameter *parameter ) const;
/// Should be called by derived classes to set the properties for the main knob based
/// on userData on the parameter. This sets visibility and tooltip and applies any default
/// expressions.
void setKnobProperties( const IECore::Parameter *parameter, DD::Image::Knob_Callback f, DD::Image::Knob *knob ) const;
template<typename T>
class Description
{
public :
Description( IECore::TypeId parameterType )
{
creatorFns()[parameterType] = creator;
}
private :
static ParameterHandlerPtr creator()
{
return new T();
}
};
private :
typedef ParameterHandlerPtr (*CreatorFn)();
typedef std::map<IECore::TypeId, CreatorFn> CreatorFnMap;
static CreatorFnMap &creatorFns();
};
} // namespace IECoreNuke
#endif // IECORENUKE_PARAMETERHANDLER_H
| 1,783 |
451 |
<filename>Haxe/Templates/Source/HaxeRuntime/Shared/uhx/Defines.h
#pragma once
#ifndef UHX_FAT_VARIANTPTR
// For now we default to use fat pointers if we're not on a 64-bit platform
// However the trick for 64-bit platforms is not universal and depends on the fact
// that in both Linux and Windows, negative pointers are reserved for kernel memory
// so we can be sure that these addresses are unused
#if defined(_WIN32) || defined(_WIN64)
#if defined(_WIN64) && _WIN64
#define UHX_FAT_VARIANTPTR 0
#else
#define UHX_FAT_VARIANTPTR 1
#endif
#elif defined(__x86_64__) && __x86_64__
#define UHX_FAT_VARIANTPTR 0
#else
#define UHX_FAT_VARIANTPTR 1
#endif
#endif
#ifndef UHX_IGNORE_POD
// this was an optimization we used to do to make POD struct wrappers smaller,
// but it causes issues when we try to extend POD structs
#define UHX_IGNORE_POD 1
#endif
#ifndef UHX_DEBUG
#if defined(UE_BUILD_SHIPPING)
#define UHX_DEBUG !UE_BUILD_SHIPPING
#elif defined(HXCPP_DEBUG)
#define UHX_DEBUG HXCPP_DEBUG
#else
#define UHX_DEBUG 0
#endif
#endif
| 424 |
834 |
<reponame>nathanawmk/fboss
/*
* Copyright (c) 2004-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include "fboss/agent/hw/sai/tracer/run/SaiLog.h"
// This file will be replaced by the generated code from SAI tracer.
// It will contain API initialization steps as well as the SAI API calls.
// Once replaced, we'll build the target and then copy it to switch
// so that it can replay all SAI API calls.
namespace facebook::fboss {
void run_trace() {}
} // namespace facebook::fboss
| 213 |
3,102 |
// RUN: %clang_cc1 -fsyntax-only -verify %s
template<typename T>
void f(T);
template<typename T>
struct A { };
struct X {
template<> friend void f<int>(int); // expected-error{{in a friend}}
template<> friend class A<int>; // expected-error{{cannot be a friend}}
friend void f<float>(float); // okay
friend class A<float>; // okay
};
| 127 |
575 |
<filename>content/browser/media/capture/frame_test_util.cc
// 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 "content/browser/media/capture/frame_test_util.h"
#include <stdint.h>
#include <cmath>
#include "base/numerics/safe_conversions.h"
#include "media/base/video_frame.h"
#include "ui/gfx/color_space.h"
#include "ui/gfx/color_transform.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/rect_conversions.h"
#include "ui/gfx/geometry/rect_f.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/transform.h"
namespace content {
namespace {
using TriStim = gfx::ColorTransform::TriStim;
// Copies YUV row data into an array of TriStims, mapping [0,255]⇒[0.0,1.0]. The
// chroma planes are assumed to be half-width.
void LoadStimsFromYUV(const uint8_t y_src[],
const uint8_t u_src[],
const uint8_t v_src[],
int width,
TriStim stims[]) {
for (int i = 0; i < width; ++i) {
stims[i].SetPoint(y_src[i] / 255.0f, u_src[i / 2] / 255.0f,
v_src[i / 2] / 255.0f);
}
}
// Maps [0.0,1.0]⇒[0,255], rounding to the nearest integer.
uint8_t QuantizeAndClamp(float value) {
return base::saturated_cast<uint8_t>(
std::fma(value, 255.0f, 0.5f /* rounding */));
}
// Copies the array of TriStims to the BGRA/RGBA output, mapping
// [0.0,1.0]⇒[0,255].
void StimsToN32Row(const TriStim row[], int width, uint8_t bgra_out[]) {
for (int i = 0; i < width; ++i) {
bgra_out[(i * 4) + (SK_R32_SHIFT / 8)] = QuantizeAndClamp(row[i].x());
bgra_out[(i * 4) + (SK_G32_SHIFT / 8)] = QuantizeAndClamp(row[i].y());
bgra_out[(i * 4) + (SK_B32_SHIFT / 8)] = QuantizeAndClamp(row[i].z());
bgra_out[(i * 4) + (SK_A32_SHIFT / 8)] = 255;
}
}
} // namespace
// static
SkBitmap FrameTestUtil::ConvertToBitmap(const media::VideoFrame& frame) {
CHECK(frame.ColorSpace().IsValid());
SkBitmap bitmap;
bitmap.allocPixels(SkImageInfo::MakeN32Premul(frame.visible_rect().width(),
frame.visible_rect().height(),
SkColorSpace::MakeSRGB()));
// Note: The hand-optimized libyuv::H420ToARGB() would be more-desirable for
// runtime performance. However, while it claims to convert from the REC709
// color space to sRGB, as of this writing, it does not do so accurately. For
// example, a YUV triplet that should become almost exactly yellow (0xffff01)
// is converted as 0xfeff0c (the blue channel has a difference of 11!). Since
// one goal of these tests is to confirm color space correctness, the
// following color transformation code is provided:
// Construct the ColorTransform.
const auto transform = gfx::ColorTransform::NewColorTransform(
frame.ColorSpace(), gfx::ColorSpace::CreateSRGB(),
gfx::ColorTransform::Intent::INTENT_ABSOLUTE);
CHECK(transform);
// Convert one row at a time.
std::vector<gfx::ColorTransform::TriStim> stims(bitmap.width());
for (int row = 0; row < bitmap.height(); ++row) {
LoadStimsFromYUV(frame.visible_data(media::VideoFrame::kYPlane) +
row * frame.stride(media::VideoFrame::kYPlane),
frame.visible_data(media::VideoFrame::kUPlane) +
(row / 2) * frame.stride(media::VideoFrame::kUPlane),
frame.visible_data(media::VideoFrame::kVPlane) +
(row / 2) * frame.stride(media::VideoFrame::kVPlane),
bitmap.width(), stims.data());
transform->Transform(stims.data(), stims.size());
StimsToN32Row(stims.data(), bitmap.width(),
reinterpret_cast<uint8_t*>(bitmap.getAddr32(0, row)));
}
return bitmap;
}
// static
gfx::Rect FrameTestUtil::ToSafeIncludeRect(const gfx::RectF& rect_f,
int fuzzy_border) {
gfx::Rect result = gfx::ToEnclosedRect(rect_f);
CHECK_GT(result.width(), 2 * fuzzy_border);
CHECK_GT(result.height(), 2 * fuzzy_border);
result.Inset(fuzzy_border, fuzzy_border, fuzzy_border, fuzzy_border);
return result;
}
// static
gfx::Rect FrameTestUtil::ToSafeExcludeRect(const gfx::RectF& rect_f,
int fuzzy_border) {
gfx::Rect result = gfx::ToEnclosingRect(rect_f);
result.Inset(-fuzzy_border, -fuzzy_border, -fuzzy_border, -fuzzy_border);
return result;
}
// static
FrameTestUtil::RGB FrameTestUtil::ComputeAverageColor(
SkBitmap frame,
const gfx::Rect& raw_include_rect,
const gfx::Rect& raw_exclude_rect) {
// Clip the rects to the valid region within |frame|. Also, only the subregion
// of |exclude_rect| within |include_rect| is relevant.
gfx::Rect include_rect = raw_include_rect;
include_rect.Intersect(gfx::Rect(0, 0, frame.width(), frame.height()));
gfx::Rect exclude_rect = raw_exclude_rect;
exclude_rect.Intersect(include_rect);
// Sum up the color values in each color channel for all pixels in
// |include_rect| not contained by |exclude_rect|.
int64_t include_sums[3] = {0};
for (int y = include_rect.y(), bottom = include_rect.bottom(); y < bottom;
++y) {
for (int x = include_rect.x(), right = include_rect.right(); x < right;
++x) {
const SkColor color = frame.getColor(x, y);
if (exclude_rect.Contains(x, y)) {
continue;
}
include_sums[0] += SkColorGetR(color);
include_sums[1] += SkColorGetG(color);
include_sums[2] += SkColorGetB(color);
}
}
// Divide the sums by the area to compute the average color.
const int include_area =
include_rect.size().GetArea() - exclude_rect.size().GetArea();
if (include_area <= 0) {
return RGB{NAN, NAN, NAN};
} else {
const auto include_area_f = static_cast<double>(include_area);
return RGB{include_sums[0] / include_area_f,
include_sums[1] / include_area_f,
include_sums[2] / include_area_f};
}
}
// static
bool FrameTestUtil::IsApproximatelySameColor(SkColor color,
const RGB& rgb,
int max_diff) {
const double r_diff = std::abs(SkColorGetR(color) - rgb.r);
const double g_diff = std::abs(SkColorGetG(color) - rgb.g);
const double b_diff = std::abs(SkColorGetB(color) - rgb.b);
return r_diff < max_diff && g_diff < max_diff && b_diff < max_diff;
}
// static
gfx::RectF FrameTestUtil::TransformSimilarly(const gfx::Rect& original,
const gfx::RectF& transformed,
const gfx::Rect& rect) {
if (original.IsEmpty()) {
return gfx::RectF(transformed.x() - original.x(),
transformed.y() - original.y(), 0.0f, 0.0f);
}
// The following is the scale-then-translate 2D matrix.
const gfx::Transform transform(transformed.width() / original.width(), 0.0f,
0.0f, transformed.height() / original.height(),
transformed.x() - original.x(),
transformed.y() - original.y());
gfx::RectF result(rect);
transform.TransformRect(&result);
return result;
}
std::ostream& operator<<(std::ostream& out, const FrameTestUtil::RGB& rgb) {
return (out << "{r=" << rgb.r << ",g=" << rgb.g << ",b=" << rgb.b << '}');
}
} // namespace content
| 3,330 |
543 |
<gh_stars>100-1000
/**
* Copyright 2016 Twitter. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.twitter.graphjet.hashing;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import com.google.common.collect.Lists;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import it.unimi.dsi.fastutil.ints.IntIterator;
public final class IntToIntArrayMapConcurrentTestHelper {
private IntToIntArrayMapConcurrentTestHelper() {
// Utility class
}
/**
* Helper class to allow reading from a {@link IntToIntArrayMap} in a controlled manner.
*/
public static class IntToIntArrayMapReader implements Runnable {
private final IntToIntArrayMap intToIntArrayMap;
private final CountDownLatch startSignal;
private final CountDownLatch doneSignal;
private final int key;
private final int sleepTimeInMilliseconds;
private ArrayList<Integer> value;
public IntToIntArrayMapReader(
IntToIntArrayMap intToIntArrayMap,
CountDownLatch startSignal,
CountDownLatch doneSignal,
int key,
int sleepTimeInMilliseconds) {
this.intToIntArrayMap = intToIntArrayMap;
this.startSignal = startSignal;
this.doneSignal = doneSignal;
this.key = key;
this.sleepTimeInMilliseconds = sleepTimeInMilliseconds;
this.value = new ArrayList<Integer>();
}
@Override
public void run() {
try {
startSignal.await();
Thread.sleep(sleepTimeInMilliseconds);
} catch (InterruptedException e) {
throw new RuntimeException("Unable to start waiting: ", e);
}
IntIterator iter = intToIntArrayMap.get(key);
while (iter.hasNext()) {
value.add(iter.next());
}
doneSignal.countDown();
}
public ArrayList<Integer> getValue() {
return value;
}
}
/**
* Helper class to allow writing to a {@link LongToInternalIntBiMap} in a controlled manner.
*/
public static class IntToIntArrayMapWriter implements Runnable {
private final IntToIntArrayMap intToIntArrayMap;
private final MapWriterInfo mapWriterInfo;
public IntToIntArrayMapWriter(
IntToIntArrayMap intToIntArrayMap, MapWriterInfo mapWriterInfo) {
this.intToIntArrayMap = intToIntArrayMap;
this.mapWriterInfo = mapWriterInfo;
}
@Override
public void run() {
Iterator<Map.Entry<Integer, ArrayList<Integer>>> iterator =
mapWriterInfo.entries.entrySet().iterator();
while (iterator.hasNext()) {
try {
mapWriterInfo.startSignal.await();
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted while waiting: ", e);
}
Map.Entry<Integer, ArrayList<Integer>> entry = iterator.next();
int[] value = null;
if (entry.getValue() != null) {
value = new int[entry.getValue().size()];
for (int i = 0; i < entry.getValue().size(); i++) {
value[i] = entry.getValue().get(i);
}
}
intToIntArrayMap.put(entry.getKey(), value);
mapWriterInfo.doneSignal.countDown();
}
}
}
/**
* This class encapsulates information needed by a writer to add to a map.
*/
public static class MapWriterInfo {
private final Map<Integer, ArrayList<Integer>> entries;
private final CountDownLatch startSignal;
private final CountDownLatch doneSignal;
public MapWriterInfo(
Map<Integer, ArrayList<Integer>> entries,
CountDownLatch startSignal,
CountDownLatch doneSignal
) {
this.entries = entries;
this.startSignal = startSignal;
this.doneSignal = doneSignal;
}
}
/**
* This helper method sets up a concurrent read-write situation with a single writer and multiple
* readers that access the same underlying map, and tests for correct recovery of entries after
* every single entry insertion, via the use of latches. This helps test write flushing after
* every entry insertion.
*
* @param map is the underlying {@link IntToIntArrayMap}
* @param keysToValueMap contains all the keysAndValues to add to the map
*/
public static void testConcurrentReadWrites(
IntToIntArrayMap map,
Map<Integer, ArrayList<Integer>> keysToValueMap
) {
int numReaders = keysToValueMap.size(); // start reading after first edge is written
ExecutorService executor = Executors.newFixedThreadPool(numReaders + 1); // single writer
List<CountDownLatch> readerStartLatches = Lists.newArrayListWithCapacity(numReaders);
List<CountDownLatch> readerDoneLatches = Lists.newArrayListWithCapacity(numReaders);
List<IntToIntArrayMapReader> readers = Lists.newArrayListWithCapacity(numReaders);
Iterator<Map.Entry<Integer, ArrayList<Integer>>> iterator =
keysToValueMap.entrySet().iterator();
while (iterator.hasNext()) {
CountDownLatch startLatch = new CountDownLatch(1);
CountDownLatch doneLatch = new CountDownLatch(1);
// Each time, get edges for the node added in the previous step
IntToIntArrayMapReader mapReader =
new IntToIntArrayMapReader(
map,
startLatch,
doneLatch,
iterator.next().getKey(),
0);
readers.add(mapReader);
executor.submit(mapReader);
readerStartLatches.add(startLatch);
readerDoneLatches.add(doneLatch);
}
Iterator<Map.Entry<Integer, ArrayList<Integer>>> writerIterator =
keysToValueMap.entrySet().iterator();
/**
* The start/done latches achieve the following execution order: writer, then reader 1, then
* writer, then reader 2, and so on. As a concrete example, suppose we have two readers and a
* writer, then the start/done latches are used as follows:
* Initial latches state:
* s1 = 1, d1 = 1
* s2 = 1, d2 = 1
* Execution steps:
* - writer writes edge 1, sets s1 = 0 and waits on d1
* - reader 1 reads since s1 == 0 and sets d1 = 0
* - writer writes edge 2, sets s2 = 0 and waits on d2
* - reader 2 reads since s2 == 0 and sets d2 = 0
*/
for (int i = 0; i < numReaders; i++) {
// Start writing immediately at first, but then write an edge once the reader finishes reading
// the previous edge
CountDownLatch startLatch = (i > 0) ? readerDoneLatches.get(i - 1) : new CountDownLatch(0);
// Release the next reader
CountDownLatch doneLatch = readerStartLatches.get(i);
Map.Entry<Integer, ArrayList<Integer>> entry = writerIterator.next();
Map<Integer, ArrayList<Integer>> writerKeysToValueMap =
new TreeMap<Integer, ArrayList<Integer>>();
writerKeysToValueMap.put(entry.getKey(), entry.getValue());
executor.submit(
new IntToIntArrayMapWriter(
map,
new MapWriterInfo(writerKeysToValueMap, startLatch, doneLatch))
);
}
// Wait for all the processes to finish and then confirm that they did what they worked as
// expected
try {
readerDoneLatches.get(numReaders - 1).await();
} catch (InterruptedException e) {
throw new RuntimeException("Execution for last reader was interrupted: ", e);
}
// Check that all readers' read info is consistent with the map
for (IntToIntArrayMapReader reader : readers) {
IntIterator iter = map.get(reader.key);
ArrayList<Integer> expectedValue = new ArrayList<Integer>();
while (iter.hasNext()) {
expectedValue.add(iter.next());
}
// Check we get the right value
assertTrue(reader.getValue().equals(expectedValue));
}
}
/**
* This helper method sets up a concurrent read-write situation with a single writer and multiple
* readers that access the same underlying LongToInternalIntBiMap, and tests for correct entry
* access during simultaneous entry reads. This helps test read consistency during arbitrary
* points of inserting entries. Note that the exact read-write sequence here is non-deterministic
* and would vary depending on the machine, but the hope is that given the large number of readers
* the reads would be done at many different points of edge insertion. The test itself checks only
* for partial correctness (it could have false positives) so this should only be used as a
* supplement to other testing.
*
* @param map is the underlying {@link IntToIntArrayMap}
* @param defaultValue is the default value returned by the map for a non-entry
* @param numReaders is the number of reader threads to use
* @param keysToValueMap contains all the keysAndValues to add to the map
* @param random is the random number generator to use
*/
public static void testRandomConcurrentReadWriteThreads(
IntToIntArrayMap map,
ArrayList<Integer> defaultValue,
int numReaders,
Map<Integer, ArrayList<Integer>> keysToValueMap,
Random random) {
int maxWaitingTimeForThreads = 100; // in milliseconds
CountDownLatch readersDoneLatch = new CountDownLatch(numReaders);
List<IntToIntArrayMapReader> readers = Lists.newArrayListWithCapacity(numReaders);
// Create a bunch of readers that'll read from the map at random
Iterator<Map.Entry<Integer, ArrayList<Integer>>> iterator =
keysToValueMap.entrySet().iterator();
for (int i = 0; i < numReaders; i++) {
readers.add(new IntToIntArrayMapReader(
map,
new CountDownLatch(0),
readersDoneLatch,
iterator.next().getKey(),
random.nextInt(maxWaitingTimeForThreads)));
}
// Create a single writer that will insert these edges in random order
CountDownLatch writerDoneLatch = new CountDownLatch(keysToValueMap.size());
MapWriterInfo mapWriterInfo =
new MapWriterInfo(keysToValueMap, new CountDownLatch(0), writerDoneLatch);
ExecutorService executor =
Executors.newFixedThreadPool(numReaders + 1); // single writer
List<Callable<Integer>> allThreads = Lists.newArrayListWithCapacity(numReaders + 1);
// First, we add the writer
allThreads.add(Executors.callable(
new IntToIntArrayMapWriter(map, mapWriterInfo), 1));
// then the readers
for (int i = 0; i < numReaders; i++) {
allThreads.add(Executors.callable(readers.get(i), 1));
}
// these will execute in some non-deterministic order
Collections.shuffle(allThreads, random);
// Wait for all the processes to finish
try {
List<Future<Integer>> results = executor.invokeAll(allThreads, 10, TimeUnit.SECONDS);
for (Future<Integer> result : results) {
assertTrue(result.isDone());
assertEquals(1, result.get().intValue());
}
} catch (InterruptedException e) {
throw new RuntimeException("Execution for a thread was interrupted: ", e);
} catch (ExecutionException e) {
throw new RuntimeException("Execution issue in an executor thread: ", e);
}
// confirm that these worked as expected
try {
readersDoneLatch.await();
writerDoneLatch.await();
} catch (InterruptedException e) {
throw new RuntimeException("Execution for last reader was interrupted: ", e);
}
// Check that all readers' read info is consistent with the map
for (IntToIntArrayMapReader reader : readers) {
IntIterator iter = map.get(reader.key);
ArrayList<Integer> expectedValue = new ArrayList<Integer>();
while (iter.hasNext()) {
expectedValue.add(iter.next());
}
// either the entry was not written at the time it was read or we get the right value
assertTrue((reader.getValue().equals(defaultValue))
|| (reader.getValue().equals(expectedValue)));
}
}
}
| 4,451 |
1,900 |
<reponame>Goldwood1024/ehcache3
/*
* Copyright Terracotta, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ehcache.xml.service;
import org.ehcache.config.CacheConfiguration;
import org.ehcache.event.EventType;
import org.ehcache.impl.config.event.DefaultCacheEventListenerConfiguration;
import org.ehcache.xml.XmlConfiguration;
import org.ehcache.xml.exceptions.XmlConfigurationException;
import org.ehcache.xml.model.CacheType;
import org.ehcache.xml.model.EventFiringType;
import org.ehcache.xml.model.EventOrderingType;
import org.ehcache.xml.model.ListenersType;
import org.junit.Test;
import com.pany.ehcache.integration.TestCacheEventListener;
import java.util.EnumSet;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.ehcache.config.builders.CacheConfigurationBuilder.newCacheConfigurationBuilder;
import static org.ehcache.config.builders.ResourcePoolsBuilder.heap;
import static org.ehcache.core.spi.service.ServiceUtils.findSingletonAmongst;
import static org.ehcache.event.EventFiring.SYNCHRONOUS;
import static org.ehcache.event.EventOrdering.UNORDERED;
import static org.ehcache.event.EventType.CREATED;
import static org.ehcache.event.EventType.REMOVED;
public class DefaultCacheEventListenerConfigurationParserTest {
@Test
public void parseServiceConfiguration() throws Exception {
CacheConfiguration<?, ?> cacheConfiguration = new XmlConfiguration(getClass().getResource("/configs/ehcache-cacheEventListener.xml")).getCacheConfigurations().get("bar");
DefaultCacheEventListenerConfiguration listenerConfig =
findSingletonAmongst(DefaultCacheEventListenerConfiguration.class, cacheConfiguration.getServiceConfigurations());
assertThat(listenerConfig).isNotNull();
assertThat(listenerConfig.getClazz()).isEqualTo(TestCacheEventListener.class);
assertThat(listenerConfig.firingMode()).isEqualTo(SYNCHRONOUS);
assertThat(listenerConfig.orderingMode()).isEqualTo(UNORDERED);
assertThat(listenerConfig.fireOn()).containsExactlyInAnyOrder(EventType.values());
}
@Test
public void unparseServiceConfiguration() {
DefaultCacheEventListenerConfiguration listenerConfig =
new DefaultCacheEventListenerConfiguration(EnumSet.of(CREATED, REMOVED), TestCacheEventListener.class);
listenerConfig.setEventFiringMode(SYNCHRONOUS);
listenerConfig.setEventOrderingMode(UNORDERED);
CacheConfiguration<?, ?> cacheConfig = newCacheConfigurationBuilder(Object.class, Object.class, heap(10)).withService(listenerConfig).build();
CacheType cacheType = new CacheType();
cacheType = new DefaultCacheEventListenerConfigurationParser().unparseServiceConfiguration(cacheConfig, cacheType);
List<ListenersType.Listener> listeners = cacheType.getListeners().getListener();
assertThat(listeners).hasSize(1);
ListenersType.Listener listener = listeners.get(0);
assertThat(listener.getEventFiringMode()).isEqualTo(EventFiringType.SYNCHRONOUS);
assertThat(listener.getEventOrderingMode()).isEqualTo(EventOrderingType.UNORDERED);
assertThat(listener.getEventsToFireOn()).contains(org.ehcache.xml.model.EventType.CREATED, org.ehcache.xml.model.EventType.REMOVED);
}
@Test
public void unparseServiceConfigurationWithInstance() {
TestCacheEventListener testCacheEventListener = new TestCacheEventListener();
DefaultCacheEventListenerConfiguration listenerConfig =
new DefaultCacheEventListenerConfiguration(EnumSet.of(CREATED, REMOVED), testCacheEventListener);
listenerConfig.setEventFiringMode(SYNCHRONOUS);
listenerConfig.setEventOrderingMode(UNORDERED);
CacheConfiguration<?, ?> cacheConfig = newCacheConfigurationBuilder(Object.class, Object.class, heap(10)).withService(listenerConfig).build();
CacheType cacheType = new CacheType();
assertThatExceptionOfType(XmlConfigurationException.class).isThrownBy(() ->
new DefaultCacheEventListenerConfigurationParser().unparseServiceConfiguration(cacheConfig, cacheType))
.withMessage("%s", "XML translation for instance based initialization for " +
"DefaultCacheEventListenerConfiguration is not supported");
}
}
| 1,411 |
2,542 |
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
using namespace Common;
using namespace ServiceModel;
using namespace std;
using namespace Management::FaultAnalysisService;
StringLiteral const TraceComponent("RestartDeployedCodePackageStatus");
RestartDeployedCodePackageStatus::RestartDeployedCodePackageStatus()
: deployedCodePackageResultSPtr_()
{
}
RestartDeployedCodePackageStatus::RestartDeployedCodePackageStatus(
shared_ptr<Management::FaultAnalysisService::DeployedCodePackageResult> && deployedCodePackageResultSPtr)
: deployedCodePackageResultSPtr_(std::move(deployedCodePackageResultSPtr))
{
}
RestartDeployedCodePackageStatus::RestartDeployedCodePackageStatus(RestartDeployedCodePackageStatus && other)
: deployedCodePackageResultSPtr_(move(other.deployedCodePackageResultSPtr_))
{
}
RestartDeployedCodePackageStatus & RestartDeployedCodePackageStatus::operator=(RestartDeployedCodePackageStatus && other)
{
if (this != &other)
{
deployedCodePackageResultSPtr_ = move(other.deployedCodePackageResultSPtr_);
}
return *this;
}
shared_ptr<DeployedCodePackageResult> const & RestartDeployedCodePackageStatus::GetRestartDeployedCodePackageResult()
{
return deployedCodePackageResultSPtr_;
}
| 406 |
956 |
# from __future__ import division
import astf_path
from trex.astf.api import *
import json
import argparse
import sys
import time
import math
import imp
from copy import deepcopy
class MultiplierDomain:
def __init__(self, low_bound, high_bound):
"""
A class that represents the multiplier domain received by the user.
:parameters:
high_bound:
Higher bound of the interval in which the ndr point is found.
low_bound:
Lower bound of the interval in which the ndr point is found.
"""
self.high_bound = high_bound
self.low_bound = low_bound
self.domain_size = high_bound - low_bound
def convert_percent_to_mult(self, percent):
"""
Converts percent in the domain to an actual multiplier.
:parameters:
percent: float
Percentage in between high and low bound. Low is 0% and High is 100%/
:returns:
Multiplier of cps
"""
return int(self.low_bound + (percent * self.domain_size / 100))
def convert_mult_to_percent(self, mult):
"""
Converts a multiplier to percentage of the domain that was defined in init.
:parameters:
mult: int
CPS multiplier.
:returns:
float, percentage
"""
assert(mult >= self.low_bound and mult <= self.high_bound), "Invalid multiplier"
return (mult - self.lower_bound) * 100 / self.domain_size
class ASTFNdrBenchConfig:
def __init__(self, high_mult, low_mult, title='Title', iteration_duration=20.00,
q_full_resolution=2.00, allowed_error=1.0, max_iterations=10,
latency_pps=0, max_latency=0, lat_tolerance=0, verbose=False,
plugin_file=None, tunables={}, **kwargs):
"""
Configuration parameters for the benchmark.
:parameters:
high_mult: int
Higher bound of the interval in which the ndr point is found.
low_mult: int
Lower bound of the interval in which the ndr point is found.
title: string
Title of the benchmark.
iteration_duration: float
Duration of the iteration.
q_full_resolution: float
Percent of queue full allowed.
allowed_error: float
Percentage of allowed error.
max_iterations: int
Max number of iterations allowed.
latency_pps: int (uint32_t)
Rate of latency packets. Zero value means disable.
max_latency: int
Max value of latency allowed in msec.
lat_tolerance: int
Percentage of latency packets allowed above max latency. Default value is 0 %. (Max Latency will be compared against total max)
verbose: boolean
Verbose mode
plugin_file: string
Path to the plugin file.
tunables: dict
Tunables for the plugin file.
kwargs: dict
"""
self.high_mult = high_mult
self.low_mult = low_mult
self.iteration_duration = iteration_duration
self.q_full_resolution = q_full_resolution
self.allowed_error = allowed_error
self.max_iterations = max_iterations
self.verbose = verbose
self.title = title
self.plugin_file = plugin_file
self.plugin_enabled = False
if self.plugin_file is not None:
self.plugin_enabled = True
self.plugin = self.load_plugin(self.plugin_file)
self.tunables = tunables
self.latency_pps = latency_pps
self.max_latency = max_latency
self.lat_tolerance = lat_tolerance
self.max_latency_set = True if self.max_latency != 0 else False
@classmethod
def load_plugin(cls, plugin_file):
"""
Load dynamically a plugin module so that we can provide the user with pre and post iteration API.
:parameters:
plugin_file: string
Path to the plugin file.
"""
# check filename
if not os.path.isfile(plugin_file):
raise TRexError("File '{0}' does not exist".format(plugin_file))
basedir = os.path.dirname(plugin_file)
sys.path.insert(0, basedir)
try:
file = os.path.basename(plugin_file).split('.')[0]
module = __import__(file, globals(), locals(), [], 0)
imp.reload(module) # reload the update
plugin = module.register()
return plugin
except Exception as e:
a, b, tb = sys.exc_info()
x =''.join(traceback.format_list(traceback.extract_tb(tb)[1:])) + a.__name__ + ": " + str(b) + "\n"
summary = "\nPython Traceback follows:\n\n" + x
raise TRexError(summary)
finally:
sys.path.remove(basedir)
def config_to_dict(self):
"""
Create a dictionary of the configuration.
:returns:
Dictionary of configurations
"""
config_dict = {'high_mult': self.high_mult, 'low_mult': self.low_mult,
'iteration_duration': self.iteration_duration, 'q_full_resolution': self.q_full_resolution,
'allowed_error': self.allowed_error, 'max_iterations': self.max_iterations,
'verbose': self.verbose, 'title': self.title,
'plugin_file': self.plugin_file, 'tunables': self.tunables,
'latency_pps': self.latency_pps, 'max_latency':self.max_latency,
'lat_tolerance': self.lat_tolerance}
return config_dict
class ASTFNdrBenchResults:
def __init__(self, config=None, results={}):
"""
NDR Bench Results
:parameters:
config: :class:`.ASTFNdrBenchConfig`
User configuration of parameters. Default value is none.
results: dict
A dictionary containing partial or full results from a run.
"""
self.stats = dict(results)
self.init_time = float(time.time())
self.config = config
self.stats['total_iterations'] = 0
def update(self, updated_dict):
"""
Updates the elapsed time, and the stats of the class with the parameter
:parameters:
updated_dict: dict
Dictionary that we use as an reference to update our stats.
"""
updated_dict['Elapsed Time'] = (float(time.time()) - self.init_time)
self.stats.update(updated_dict)
def convert_rate(self, rate_bps, packet=False):
"""
Converts rate from bps or pps to a string.
:parameters:
rate_bps: float
Value of of rate in bps or pps based on the packet parameter.
packet: boolean
If true then the rate is PPS, else bps.
:returns:
Rate as a formatted string.
"""
converted = float(rate_bps)
magnitude = 0
while converted > 1000.00:
magnitude += 1
converted /= 1000.00
converted = round(converted, 2)
if packet:
postfix = "PPS"
else:
postfix = "bps"
if magnitude == 0:
return str(converted) + postfix
elif magnitude == 1:
converted = round(converted)
return str(converted) + " K" + postfix
elif magnitude == 2:
return str(converted) + " M" + postfix
elif magnitude == 3:
return str(converted) + " G" + postfix
def print_latency(self):
"""
Prints the latency stats in case there are any.
"""
try:
for k in self.stats['latency'].keys():
print("Latency stats on port :%d" % k)
print (" Average :%0.2f" % self.stats['latency'][k]['s_avg'])
print (" Total Max (usec) :%d" % self.stats['latency'][k]['max_usec'])
print (" Min Delta (usec) :%d" % self.stats['latency'][k]['min_usec'])
print (" Packets > threash hold :%d" % self.stats['latency'][k]['high_cnt'])
print (" Histogram :%s " % self.stats['latency'][k]['histogram'])
except TypeError:
pass
def print_run_stats(self):
"""
Prints the TRex stats after a run (transmission).
"""
print("Elapsed Time :%0.2f seconds" % self.stats['Elapsed Time'])
print("BW Per Core :%0.2f Gbit/Sec @100%% per core" % float(self.stats['bw_per_core']))
print("TX PPS :%s" % (self.convert_rate(float(self.stats['tx_pps']), True)))
print("RX PPS :%s" % (self.convert_rate(float(self.stats['rx_pps']), True)))
print("TX Utilization :%0.2f %%" % self.stats['tx_util'])
print("TRex CPU :%0.2f %%" % self.stats['cpu_util'])
print("Total TX L1 :%s " % (self.convert_rate(float(self.stats['total_tx_L1']))))
print("Total RX L1 :%s " % (self.convert_rate(float(self.stats['total_rx_L1']))))
print("Total TX L2 :%s " % (self.convert_rate(float(self.stats['tx_bps']))))
print("Total RX L2 :%s " % (self.convert_rate(float(self.stats['rx_bps']))))
if 'mult_difference' in self.stats:
print("Distance from current Optimum :%0.2f %%" % self.stats['mult_difference'])
if self.config.latency_pps > 0:
self.print_latency()
def print_iteration_data(self):
"""
Prints data regarding the current iteration.
"""
if 'title' in self.stats:
print("\nTitle :%s" % self.stats['title'])
if 'iteration' in self.stats:
print("Iteration :%s" % self.stats['iteration'])
print("Multiplier :%s" % self.stats['mult'])
print("Multiplier Percentage :%0.2f %%" % self.stats['mult_p'])
print("Max Multiplier :%s" % self.config.high_mult)
print("Min Multiplier :%s" % self.config.low_mult)
print("Queue Full :%0.2f %% of oPackets" % self.stats['queue_full_percentage'])
print("Errors :%s" % ("Yes" if self.stats['error_flag'] else "No"))
if self.config.max_latency_set:
print("Valid Latency :%s" % self.stats['valid_latency'])
self.print_run_stats()
def print_final(self):
"""
Prints the final data regarding where the NDR is found.
"""
print("\nTitle :%s" % self.stats['title'])
if 'iteration' in self.stats:
print("Total Iterations :%s " % self.stats['total_iterations'])
print("Max Multiplier :%s" % self.config.high_mult)
print("Min Multiplier :%s" % self.config.low_mult)
print("Optimal P-Drop Mult :%s" % self.stats['mult'])
print("P-Drop Percentage :%0.2f %%" % self.stats['mult_p'])
print("Queue Full at Optimal P-Drop Mult :%0.2f %% of oPackets" % self.stats['queue_full_percentage'])
print("Errors at Optimal P-Drop Mult :%s" % ("Yes" if self.stats['error_flag'] else "No"))
if self.config.max_latency_set:
print("Valid Latency at Opt. P-Drop Mult :%s" % self.stats['valid_latency'])
self.print_run_stats()
def to_json(self):
"""
Output the results to a json.
"""
total_output = {'results': self.stats, 'config': self.config.config_to_dict()}
return json.dumps(total_output)
@staticmethod
def print_state(state, high_bound, low_bound):
print("\n\nStatus :%s" % state)
if high_bound:
print("Interval :[%d,%d]" % (low_bound, high_bound))
def human_readable_dict(self):
"""
Return a human readable dictionary of the results.
"""
hu_dict = {'Queue Full [%]': str(round(self.stats['queue_full_percentage'], 2)) + "%",
'BW per core [Gbit/sec @100% per core]': str(
round(float(self.stats['bw_per_core']), 2)) + 'Gbit/Sec @100% per core',
'RX [MPPS]': self.convert_rate(float(self.stats['rx_pps']), True),
'TX [MPPS]': self.convert_rate(float(self.stats['tx_pps']), True),
'Line Utilization [%]': str(round(self.stats['tx_util'], 2)),
'CPU Utilization [%]': str(round(self.stats['cpu_util'],2)),
'Total TX L1': self.convert_rate(float(self.stats['total_tx_L1'])),
'Total RX L1': self.convert_rate(float(self.stats['total_rx_L1'])),
'TX [bps]': self.convert_rate(float(self.stats['tx_bps'])),
'RX [bps]': self.convert_rate(float(self.stats['rx_bps'])),
'OPT TX Rate [bps]': self.convert_rate(float(self.stats['rate_tx_bps'])),
'OPT RX Rate [bps]': self.convert_rate(float(self.stats['rate_rx_bps'])),
'OPT Multiplier [%]': self.stats['mult_p'],
'Max Multiplier ': self.config.high_mult,
'Elapsed Time [Sec]': str(round(self.stats['Elapsed Time'], 2)),
'Total Iterations': self.stats.get('total_iterations', None),
'Title': self.stats['title'],
'Latency': dict(self.stats['latency']),
'Valid Latency': "Yes" if self.stats['valid_latency'] else "No",
"Error Status": ("Yes" if self.stats['error_flag'] else "No"),
'Errors': self.stats["errors"]}
return hu_dict
class ASTFNdrBench:
def __init__(self, astf_client, config):
"""
ASTFNDRBench class object
:parameters:
astf_client: :class:`.ASTFClient`
ASTF Client
config: :class:`.ASTFNdrBenchConfig`
Configurations and parameters for the benchmark
"""
self.config = config
self.results = ASTFNdrBenchResults(config)
self.astf_client = astf_client
self.results.update({'title': self.config.title})
self.mult_domain = MultiplierDomain(self.config.low_mult, self.config.high_mult)
self.opt_run_stats = {}
self.opt_run_stats['mult_p'] = 0 # percent
def plugin_pre_iteration(self, run_results=None, **kwargs):
"""
Plugin pre iteration wrapper in order to pass the plugin a deep copy of the run results,
since the user might change the actual run results. Consult the Plugin API for more information.
"""
self.config.plugin.pre_iteration(deepcopy(run_results), **kwargs)
def plugin_post_iteration(self, run_results, **kwargs):
"""
Plugin pre iteration wrapper in order to pass the plugin a deep copy of the run results,
since the user might change the actual run results. Consult the Plugin API for more information.
"""
return self.config.plugin.post_iteration(deepcopy(run_results), **kwargs)
def max_iterations_reached(self, current_run_stats, high_bound, low_bound):
if current_run_stats['iteration'] == self.config.max_iterations:
self.opt_run_stats.update(current_run_stats)
if self.config.verbose:
self.results.print_state("Max Iterations reached. Results might not be fully accurate", high_bound,
low_bound)
return True
return False
def calculate_max_latency_received(self, latency_data):
"""
Calculates the max latency of a run.
Call this only if latency tolerance is 0%.
:parameters:
latency_data: dict
The latency field of get_stats() of the :class:`.ASTFClient`
:returns:
The max latency in that run.
"""
max_latency = 0
for port in latency_data.keys():
if type(port) != int:
continue
max_key = 0
for entry in latency_data[port]['hist']['histogram']:
max_key = max(entry['key'], max_key)
max_latency = max(latency_data[port]['hist']['max_usec'], max_latency, max_key)
return max_latency
def calculate_latency_percentage(self, latency_data):
"""
Calculates the percentage of latency packets beyond the max latency parameter.
The percentage is calculated independently for each port and the maximal percentage is returned.
Call this only if latency tolerance is more than 0%.
:parameters:
latency_data: dict
The latency field of get_stats() of the :class:`.ASTFClient`
:returns:
A float represeting the percentage of latency packets above max latency.
"""
latency_percentage = 0
for port in latency_data.keys():
total_packets = 0
packets_above_max_latency = 0
if type(port) != int:
continue
port_histogram = latency_data[port]['hist']['histogram']
for entry in port_histogram:
total_packets += entry['val']
if entry['key'] >= self.config.max_latency:
packets_above_max_latency += entry['val']
total_packets = 1 if total_packets == 0 else total_packets
packets_above_max_latency_percentage = float(packets_above_max_latency) / total_packets * 100
latency_percentage = max(latency_percentage, packets_above_max_latency_percentage)
return latency_percentage
def is_valid_latency(self, latency_data):
"""
Returns a boolean flag indicating if the latency of a run is valid.
In case latency was not set then it returns True.
:parameters:
latency_data: dict
The latency field of get_stats() of the :class:`.ASTFClient`
:returns:
A boolean flag indiciating the latency was valid.
"""
if self.config.latency_pps > 0 and self.config.max_latency_set:
if self.config.lat_tolerance == 0:
return self.config.max_latency >= self.calculate_max_latency_received(latency_data)
else:
return self.config.lat_tolerance >= self.calculate_latency_percentage(latency_data)
else:
return True
def update_opt_stats(self, new_stats):
"""
Updates the optimal stats if the new_stats are better.
:parameters:
new_stats: dict
Statistics of some run.
"""
if new_stats['queue_full_percentage'] <= self.config.q_full_resolution and new_stats['valid_latency'] and not new_stats['error_flag']:
if new_stats['mult_p'] > self.opt_run_stats['mult_p']:
self.opt_run_stats.update(new_stats)
def perf_run(self, mult):
"""
Transmits traffic through the ASTF client object in the class.
:parameters:
mult: int
Multiply total CPS of profile by this value.
:returns:
Dictionary with the results of the run.
"""
self.astf_client.stop()
# allow time for counters to settle from previous runs
time.sleep(10)
self.astf_client.clear_stats()
self.astf_client.start(mult=mult, nc=True, latency_pps=self.config.latency_pps)
time_slept = 0
sleep_interval = 1 # in seconds
error_flag = False
while time_slept < self.config.iteration_duration:
time.sleep(sleep_interval)
time_slept += sleep_interval
stats = self.astf_client.get_stats()
error_flag, errors = self.astf_client.is_traffic_stats_error(stats['traffic'])
if error_flag:
break
self.astf_client.stop()
opackets = stats['total']['opackets']
ipackets = stats['total']['ipackets']
q_full_packets = stats['global']['queue_full']
q_full_percentage = float((q_full_packets / float(opackets)) * 100.000)
latency_stats = stats['latency']
latency_groups = {}
if latency_stats:
for i in latency_stats.keys():
if type(i) != int:
continue
latency_dict = latency_stats[i]['hist']
latency_groups[i] = latency_dict
tx_bps = stats['total']['tx_bps']
rx_bps = stats['total']['rx_bps']
tx_util_norm = stats['total']['tx_util'] / self.astf_client.get_port_count()
self.results.stats['total_iterations'] += 1
run_results = {'error_flag': error_flag, 'errors': errors, 'queue_full_percentage': q_full_percentage,
'valid_latency': self.is_valid_latency(latency_stats),
'rate_tx_bps': tx_bps,
'rate_rx_bps': rx_bps,
'tx_util': tx_util_norm, 'latency': latency_groups,
'cpu_util': stats['global']['cpu_util'], 'tx_pps': stats['total']['tx_pps'],
'bw_per_core': stats['global']['bw_per_core'], 'rx_pps': stats['total']['rx_pps'],
'total_tx_L1': stats['total']['tx_bps_L1'],
'total_rx_L1': stats['total']['rx_bps_L1'], 'tx_bps': stats['total']['tx_bps'],
'rx_bps': stats['total']['rx_bps'],
'total_iterations': self.results.stats['total_iterations']}
return run_results
def perf_run_interval(self, high_bound, low_bound):
"""
Searches for NDR in an given interval bounded by the two parameters. Based on the number of iterations which is supplied in the :class:`.ASTFNdrBenchConfig`
object of the class will perform multiple transmitting runs until one of the stopping conditions is met.
:parameters:
high_bound: float
In percents of :class:`.MultiplierDomain`
low_bound: float
In percents of :class:`.MultiplierDomain`
:returns:
Dictionary of the optimal run stats found in the interval, based on the criterions defined in :class:`.ASTFNdrBenchConfig`,
"""
current_run_results = ASTFNdrBenchResults(self.config)
current_run_stats = self.results.stats
current_run_stats['iteration'] = 0
plugin_enabled = self.config.plugin_enabled
plugin_stop = False
while current_run_stats['iteration'] <= self.config.max_iterations:
current_run_stats['mult_p'] = float((high_bound + low_bound)) / 2.00
current_run_stats['mult'] = self.mult_domain.convert_percent_to_mult(current_run_stats['mult_p'])
if plugin_enabled:
self.plugin_pre_iteration(run_results=current_run_stats, **self.config.tunables)
current_run_stats.update(self.perf_run(current_run_stats['mult']))
error_flag = current_run_stats['error_flag']
q_full_percentage = current_run_stats['queue_full_percentage']
valid_latency = current_run_stats['valid_latency']
current_run_stats['mult_difference'] = abs(current_run_stats['mult_p'] - self.opt_run_stats['mult_p'])
current_run_results.update(current_run_stats)
if plugin_enabled:
plugin_stop, error_flag = self.plugin_post_iteration(run_results=current_run_stats, **self.config.tunables)
if self.config.verbose:
if error_flag:
current_run_results.print_state("Errors Occurred", high_bound, low_bound)
elif q_full_percentage > self.config.q_full_resolution:
current_run_results.print_state("Queue Full Occurred", high_bound, low_bound)
elif not valid_latency:
current_run_results.print_state("Invalid Latency", high_bound, low_bound)
else:
current_run_results.print_state("Looking for NDR", high_bound, low_bound)
current_run_results.print_iteration_data()
if plugin_stop:
if self.config.verbose:
current_run_results.print_state("Plugin decided to stop after the iteration!", high_bound, low_bound)
self.update_opt_stats(current_run_stats)
break
if q_full_percentage <= self.config.q_full_resolution and valid_latency and not error_flag:
if current_run_stats['mult_p'] > self.opt_run_stats['mult_p']:
self.opt_run_stats.update(current_run_stats)
if current_run_stats['mult_difference'] <= self.config.allowed_error:
break
low_bound = current_run_stats['mult_p']
current_run_stats['iteration'] += 1
if self.max_iterations_reached(current_run_stats, high_bound, low_bound):
break
else:
continue
else:
break
else:
if current_run_stats['mult_difference'] <= self.config.allowed_error:
break
high_bound = current_run_stats['mult_p']
current_run_stats['iteration'] += 1
if self.max_iterations_reached(current_run_stats, high_bound, low_bound):
break
self.opt_run_stats['iteration'] = current_run_stats['iteration']
self.opt_run_stats['total_iterations'] = current_run_stats['total_iterations']
self.opt_run_stats['rate_difference'] = 0
return self.opt_run_stats
def find_ndr(self):
"""
Wrapper function, runs the binary search between 0% and 100% of the :class:`.MultiplierDomain`
"""
self.perf_run_interval(high_bound=100, low_bound=0)
if __name__ == '__main__':
print('Designed to be imported, not as stand-alone script.')
| 13,334 |
1,338 |
/*
* Copyright 2013, <NAME>, <EMAIL>. All rights reserved.
* Distributed under the terms of the MIT License.
*/
#ifndef PSD_WRITER_H
#define PSD_WRITER_H
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <Translator.h>
#include <TranslatorFormats.h>
#include <TranslationDefs.h>
#include <GraphicsDefs.h>
#include <InterfaceDefs.h>
#include <String.h>
#include <DataIO.h>
#include <File.h>
#include <ByteOrder.h>
#include <List.h>
#include "PSDLoader.h"
#include "DataArray.h"
class PSDWriter {
public:
PSDWriter(BPositionIO *stream);
~PSDWriter();
bool IsReady(void);
void SetCompression(int16 compression);
void SetVersion(int16 version);
status_t Encode(BPositionIO *target);
private:
void _WriteInt64ToStream(BPositionIO *stream, int64);
void _WriteUInt64ToStream(BPositionIO *stream, uint64);
void _WriteInt32ToStream(BPositionIO *stream, int32);
void _WriteUInt32ToStream(BPositionIO *stream, uint32);
void _WriteInt16ToStream(BPositionIO *stream, int16);
void _WriteUInt16ToStream(BPositionIO *stream, uint16);
void _WriteInt8ToStream(BPositionIO *stream, int8);
void _WriteUInt8ToStream(BPositionIO *stream, uint8);
void _WriteFillBlockToStream(BPositionIO *stream,
uint8 val, size_t count);
void _WriteBlockToStream(BPositionIO *stream,
uint8 *block, size_t count);
BDataArray* _PackBits(uint8 *buff, int32 len);
status_t _LoadChannelsFromRGBA32(void);
BPositionIO *fStream;
size_t fBitmapDataPos;
BDataArray psdChannel[4];
BDataArray psdByteCounts[4];
color_space fColorSpace;
int32 fInRowBytes;
int16 fChannels;
int16 fAlphaChannel;
int32 fWidth;
int32 fHeight;
int16 fCompression;
int16 fVersion;
bool fReady;
};
#endif /* PSD_WRITER_H */
| 753 |
354 |
/*-------------------------------------------------------------------------
* drawElements Quality Program OpenGL ES 2.0 Module
* -------------------------------------------------
*
* Copyright 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*//*!
* \file
* \brief Invariance tests.
*//*--------------------------------------------------------------------*/
#include "es2fShaderInvarianceTests.hpp"
#include "deStringUtil.hpp"
#include "deRandom.hpp"
#include "gluContextInfo.hpp"
#include "gluRenderContext.hpp"
#include "gluShaderProgram.hpp"
#include "gluPixelTransfer.hpp"
#include "glwFunctions.hpp"
#include "glwEnums.hpp"
#include "tcuRenderTarget.hpp"
#include "tcuTestLog.hpp"
#include "tcuSurface.hpp"
#include "tcuTextureUtil.hpp"
#include "tcuStringTemplate.hpp"
namespace deqp
{
namespace gles2
{
namespace Functional
{
namespace
{
class FormatArgumentList;
static tcu::Vec4 genRandomVector (de::Random& rnd)
{
tcu::Vec4 retVal;
retVal.x() = rnd.getFloat(-1.0f, 1.0f);
retVal.y() = rnd.getFloat(-1.0f, 1.0f);
retVal.z() = rnd.getFloat(-1.0f, 1.0f);
retVal.w() = rnd.getFloat( 0.2f, 1.0f);
return retVal;
}
class FormatArgument
{
public:
FormatArgument (const char* name, const std::string& value);
private:
friend class FormatArgumentList;
const char* const m_name;
const std::string m_value;
};
FormatArgument::FormatArgument (const char* name, const std::string& value)
: m_name (name)
, m_value (value)
{
}
class FormatArgumentList
{
public:
FormatArgumentList (void);
FormatArgumentList& operator<< (const FormatArgument&);
const std::map<std::string, std::string>& getArguments (void) const;
private:
std::map<std::string, std::string> m_formatArguments;
};
FormatArgumentList::FormatArgumentList (void)
{
}
FormatArgumentList& FormatArgumentList::operator<< (const FormatArgument& arg)
{
m_formatArguments[arg.m_name] = arg.m_value;
return *this;
}
const std::map<std::string, std::string>& FormatArgumentList::getArguments (void) const
{
return m_formatArguments;
}
static std::string formatGLSL (const char* templateString, const FormatArgumentList& args)
{
const std::map<std::string, std::string>& params = args.getArguments();
return tcu::StringTemplate(std::string(templateString)).specialize(params);
}
/*--------------------------------------------------------------------*//*!
* \brief Vertex shader invariance test
*
* Test vertex shader invariance by drawing a test pattern two times, each
* time with a different shader. Shaders have set identical values to
* invariant gl_Position using identical expressions. No fragments from the
* first pass using should remain visible.
*//*--------------------------------------------------------------------*/
class InvarianceTest : public TestCase
{
public:
struct ShaderPair
{
std::string vertexShaderSource0;
std::string fragmentShaderSource0;
std::string vertexShaderSource1;
std::string fragmentShaderSource1;
};
InvarianceTest (Context& ctx, const char* name, const char* desc);
~InvarianceTest (void);
void init (void);
void deinit (void);
IterateResult iterate (void);
private:
virtual ShaderPair genShaders (void) const = DE_NULL;
bool checkImage (const tcu::Surface&) const;
glu::ShaderProgram* m_shader0;
glu::ShaderProgram* m_shader1;
glw::GLuint m_arrayBuf;
int m_verticesInPattern;
const int m_renderSize;
};
InvarianceTest::InvarianceTest (Context& ctx, const char* name, const char* desc)
: TestCase (ctx, name, desc)
, m_shader0 (DE_NULL)
, m_shader1 (DE_NULL)
, m_arrayBuf (0)
, m_verticesInPattern (0)
, m_renderSize (256)
{
}
InvarianceTest::~InvarianceTest (void)
{
deinit();
}
void InvarianceTest::init (void)
{
// Invariance tests require drawing to the screen and reading back results.
// Tests results are not reliable if the resolution is too small
{
if (m_context.getRenderTarget().getWidth() < m_renderSize ||
m_context.getRenderTarget().getHeight() < m_renderSize)
throw tcu::NotSupportedError(std::string("Render target size must be at least ") + de::toString(m_renderSize) + "x" + de::toString(m_renderSize));
}
// Gen shaders
{
ShaderPair vertexShaders = genShaders();
m_shader0 = new glu::ShaderProgram(m_context.getRenderContext(), glu::ProgramSources() << glu::VertexSource(vertexShaders.vertexShaderSource0) << glu::FragmentSource(vertexShaders.fragmentShaderSource0));
if (!m_shader0->isOk())
{
m_testCtx.getLog() << *m_shader0;
throw tcu::TestError("Test shader compile failed.");
}
m_shader1 = new glu::ShaderProgram(m_context.getRenderContext(), glu::ProgramSources() << glu::VertexSource(vertexShaders.vertexShaderSource1) << glu::FragmentSource(vertexShaders.fragmentShaderSource1));
if (!m_shader1->isOk())
{
m_testCtx.getLog() << *m_shader1;
throw tcu::TestError("Test shader compile failed.");
}
// log
m_testCtx.getLog()
<< tcu::TestLog::Message << "Shader 1:" << tcu::TestLog::EndMessage
<< *m_shader0
<< tcu::TestLog::Message << "Shader 2:" << tcu::TestLog::EndMessage
<< *m_shader1;
}
// Gen test pattern
{
const int numTriangles = 72;
de::Random rnd (123);
std::vector<tcu::Vec4> triangles (numTriangles * 3 * 2);
const glw::Functions& gl = m_context.getRenderContext().getFunctions();
// Narrow triangle pattern
for (int triNdx = 0; triNdx < numTriangles; ++triNdx)
{
const tcu::Vec4 vertex1 = genRandomVector(rnd);
const tcu::Vec4 vertex2 = genRandomVector(rnd);
const tcu::Vec4 vertex3 = vertex2 + genRandomVector(rnd) * 0.01f; // generate narrow triangles
triangles[triNdx*3 + 0] = vertex1;
triangles[triNdx*3 + 1] = vertex2;
triangles[triNdx*3 + 2] = vertex3;
}
// Normal triangle pattern
for (int triNdx = 0; triNdx < numTriangles; ++triNdx)
{
triangles[(numTriangles + triNdx)*3 + 0] = genRandomVector(rnd);
triangles[(numTriangles + triNdx)*3 + 1] = genRandomVector(rnd);
triangles[(numTriangles + triNdx)*3 + 2] = genRandomVector(rnd);
}
// upload
gl.genBuffers(1, &m_arrayBuf);
gl.bindBuffer(GL_ARRAY_BUFFER, m_arrayBuf);
gl.bufferData(GL_ARRAY_BUFFER, (int)(triangles.size() * sizeof(tcu::Vec4)), &triangles[0], GL_STATIC_DRAW);
GLU_EXPECT_NO_ERROR(gl.getError(), "buffer gen");
m_verticesInPattern = numTriangles * 3;
}
}
void InvarianceTest::deinit (void)
{
delete m_shader0;
delete m_shader1;
m_shader0 = DE_NULL;
m_shader1 = DE_NULL;
if (m_arrayBuf)
{
m_context.getRenderContext().getFunctions().deleteBuffers(1, &m_arrayBuf);
m_arrayBuf = 0;
}
}
InvarianceTest::IterateResult InvarianceTest::iterate (void)
{
const glw::Functions& gl = m_context.getRenderContext().getFunctions();
const bool depthBufferExists = m_context.getRenderTarget().getDepthBits() != 0;
tcu::Surface resultSurface (m_renderSize, m_renderSize);
bool error = false;
// Prepare draw
gl.clearColor (0.0f, 0.0f, 0.0f, 1.0f);
gl.clear (GL_COLOR_BUFFER_BIT);
gl.viewport (0, 0, m_renderSize, m_renderSize);
gl.bindBuffer (GL_ARRAY_BUFFER, m_arrayBuf);
GLU_EXPECT_NO_ERROR (gl.getError(), "setup draw");
m_testCtx.getLog() << tcu::TestLog::Message << "Testing position invariance." << tcu::TestLog::EndMessage;
// Draw position check passes
for (int passNdx = 0; passNdx < 2; ++passNdx)
{
const glu::ShaderProgram& shader = (passNdx == 0) ? (*m_shader0) : (*m_shader1);
const glw::GLint positionLoc = gl.getAttribLocation(shader.getProgram(), "a_input");
const glw::GLint colorLoc = gl.getUniformLocation(shader.getProgram(), "u_color");
const tcu::Vec4 red = tcu::Vec4(1.0f, 0.0f, 0.0f, 1.0f);
const tcu::Vec4 green = tcu::Vec4(0.0f, 1.0f, 0.0f, 1.0f);
const tcu::Vec4 color = (passNdx == 0) ? (red) : (green);
const char* const colorStr = (passNdx == 0) ? ("red - purple") : ("green");
m_testCtx.getLog() << tcu::TestLog::Message << "Drawing position test pattern using shader " << (passNdx+1) << ". Primitive color: " << colorStr << "." << tcu::TestLog::EndMessage;
gl.useProgram (shader.getProgram());
gl.uniform4fv (colorLoc, 1, color.getPtr());
gl.enableVertexAttribArray (positionLoc);
gl.vertexAttribPointer (positionLoc, 4, GL_FLOAT, GL_FALSE, sizeof(tcu::Vec4), DE_NULL);
gl.drawArrays (GL_TRIANGLES, 0, m_verticesInPattern);
gl.disableVertexAttribArray (positionLoc);
GLU_EXPECT_NO_ERROR (gl.getError(), "draw pass");
}
// Read result
glu::readPixels(m_context.getRenderContext(), 0, 0, resultSurface.getAccess());
// Check there are no red pixels
m_testCtx.getLog() << tcu::TestLog::Message << "Verifying output. Expecting only green or background colored pixels." << tcu::TestLog::EndMessage;
error |= !checkImage(resultSurface);
if (!depthBufferExists)
{
m_testCtx.getLog() << tcu::TestLog::Message << "Depth buffer not available, skipping z-test." << tcu::TestLog::EndMessage;
}
else
{
// Test with Z-test
gl.clearDepthf (1.0f);
gl.clear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
gl.enable (GL_DEPTH_TEST);
m_testCtx.getLog() << tcu::TestLog::Message << "Testing position invariance with z-test. Enabling GL_DEPTH_TEST." << tcu::TestLog::EndMessage;
// Draw position check passes
for (int passNdx = 0; passNdx < 2; ++passNdx)
{
const glu::ShaderProgram& shader = (passNdx == 0) ? (*m_shader0) : (*m_shader1);
const glw::GLint positionLoc = gl.getAttribLocation(shader.getProgram(), "a_input");
const glw::GLint colorLoc = gl.getUniformLocation(shader.getProgram(), "u_color");
const tcu::Vec4 red = tcu::Vec4(1.0f, 0.0f, 0.0f, 1.0f);
const tcu::Vec4 green = tcu::Vec4(0.0f, 1.0f, 0.0f, 1.0f);
const tcu::Vec4 color = (passNdx == 0) ? (red) : (green);
const glw::GLenum depthFunc = (passNdx == 0) ? (GL_ALWAYS) : (GL_EQUAL);
const char* const depthFuncStr = (passNdx == 0) ? ("GL_ALWAYS") : ("GL_EQUAL");
const char* const colorStr = (passNdx == 0) ? ("red - purple") : ("green");
m_testCtx.getLog() << tcu::TestLog::Message << "Drawing Z-test pattern using shader " << (passNdx+1) << ". Primitive color: " << colorStr << ". DepthFunc: " << depthFuncStr << tcu::TestLog::EndMessage;
gl.useProgram (shader.getProgram());
gl.uniform4fv (colorLoc, 1, color.getPtr());
gl.depthFunc (depthFunc);
gl.enableVertexAttribArray (positionLoc);
gl.vertexAttribPointer (positionLoc, 4, GL_FLOAT, GL_FALSE, sizeof(tcu::Vec4), DE_NULL);
gl.drawArrays (GL_TRIANGLES, m_verticesInPattern, m_verticesInPattern); // !< buffer contains 2 m_verticesInPattern-sized patterns
gl.disableVertexAttribArray (positionLoc);
GLU_EXPECT_NO_ERROR (gl.getError(), "draw pass");
}
// Read result
glu::readPixels(m_context.getRenderContext(), 0, 0, resultSurface.getAccess());
// Check there are no red pixels
m_testCtx.getLog() << tcu::TestLog::Message << "Verifying output. Expecting only green or background colored pixels." << tcu::TestLog::EndMessage;
error |= !checkImage(resultSurface);
}
// Report result
if (error)
m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Detected variance between two invariant values");
else
m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Pass");
return STOP;
}
bool InvarianceTest::checkImage (const tcu::Surface& surface) const
{
const tcu::IVec4 okColor = tcu::IVec4(0, 255, 0, 255);
const tcu::RGBA errColor = tcu::RGBA(255, 0, 0, 255);
bool error = false;
tcu::Surface errorMask (m_renderSize, m_renderSize);
tcu::clear(errorMask.getAccess(), okColor);
for (int y = 0; y < m_renderSize; ++y)
for (int x = 0; x < m_renderSize; ++x)
{
const tcu::RGBA col = surface.getPixel(x, y);
if (col.getRed() != 0)
{
errorMask.setPixel(x, y, errColor);
error = true;
}
}
// report error
if (error)
{
m_testCtx.getLog() << tcu::TestLog::Message << "Invalid pixels found (fragments from first render pass found). Variance detected." << tcu::TestLog::EndMessage;
m_testCtx.getLog()
<< tcu::TestLog::ImageSet("Results", "Result verification")
<< tcu::TestLog::Image("Result", "Result", surface)
<< tcu::TestLog::Image("Error mask", "Error mask", errorMask)
<< tcu::TestLog::EndImageSet;
return false;
}
else
{
m_testCtx.getLog() << tcu::TestLog::Message << "No variance found." << tcu::TestLog::EndMessage;
m_testCtx.getLog()
<< tcu::TestLog::ImageSet("Results", "Result verification")
<< tcu::TestLog::Image("Result", "Result", surface)
<< tcu::TestLog::EndImageSet;
return true;
}
}
class BasicInvarianceTest : public InvarianceTest
{
public:
BasicInvarianceTest (Context& ctx, const char* name, const char* desc, const std::string& vertexShader1, const std::string& vertexShader2);
ShaderPair genShaders (void) const;
private:
const std::string m_vertexShader1;
const std::string m_vertexShader2;
const std::string m_fragmentShader;
static const char* const s_basicFragmentShader;
};
const char* const BasicInvarianceTest::s_basicFragmentShader = "uniform mediump vec4 u_color;\n"
"varying mediump vec4 v_unrelated;\n"
"void main ()\n"
"{\n"
" mediump float blue = dot(v_unrelated, vec4(1.0, 1.0, 1.0, 1.0));\n"
" gl_FragColor = vec4(u_color.r, u_color.g, blue, u_color.a);\n"
"}\n";
BasicInvarianceTest::BasicInvarianceTest (Context& ctx, const char* name, const char* desc, const std::string& vertexShader1, const std::string& vertexShader2)
: InvarianceTest (ctx, name, desc)
, m_vertexShader1 (vertexShader1)
, m_vertexShader2 (vertexShader2)
, m_fragmentShader (s_basicFragmentShader)
{
}
BasicInvarianceTest::ShaderPair BasicInvarianceTest::genShaders (void) const
{
ShaderPair retVal;
retVal.vertexShaderSource0 = m_vertexShader1;
retVal.vertexShaderSource1 = m_vertexShader2;
retVal.fragmentShaderSource0 = m_fragmentShader;
retVal.fragmentShaderSource1 = m_fragmentShader;
return retVal;
}
} // anonymous
ShaderInvarianceTests::ShaderInvarianceTests (Context& context)
: TestCaseGroup(context, "invariance", "Invariance tests")
{
}
ShaderInvarianceTests::~ShaderInvarianceTests (void)
{
}
void ShaderInvarianceTests::init (void)
{
static const struct PrecisionCase
{
glu::Precision prec;
const char* name;
// set literals in the glsl to be in the representable range
const char* highValue; // !< highValue < maxValue
const char* invHighValue;
const char* mediumValue; // !< mediumValue^2 < maxValue
const char* lowValue; // !< lowValue^4 < maxValue
const char* invlowValue;
int loopIterations;
int loopPartialIterations;
int loopNormalizationExponent;
const char* loopNormalizationConstantLiteral;
const char* loopMultiplier;
const char* sumLoopNormalizationConstantLiteral;
} precisions[] =
{
{ glu::PRECISION_HIGHP, "highp", "1.0e20", "1.0e-20", "1.0e14", "1.0e9", "1.0e-9", 14, 11, 2, "1.0e4", "1.9", "1.0e3" },
{ glu::PRECISION_MEDIUMP, "mediump", "1.0e4", "1.0e-4", "1.0e2", "1.0e1", "1.0e-1", 13, 11, 2, "1.0e4", "1.9", "1.0e3" },
{ glu::PRECISION_LOWP, "lowp", "0.9", "1.1", "1.1", "1.15", "0.87", 6, 2, 0, "2.0", "1.1", "1.0" },
};
for (int precNdx = 0; precNdx < DE_LENGTH_OF_ARRAY(precisions); ++precNdx)
{
const char* const precisionName = precisions[precNdx].name;
const glu::Precision precision = precisions[precNdx].prec;
tcu::TestCaseGroup* const group = new tcu::TestCaseGroup(m_testCtx, precisionName, "Invariance tests using the given precision.");
const FormatArgumentList args = FormatArgumentList()
<< FormatArgument("VERSION", "")
<< FormatArgument("IN", "attribute")
<< FormatArgument("OUT", "varying")
<< FormatArgument("IN_PREC", precisionName)
<< FormatArgument("HIGH_VALUE", de::toString(precisions[precNdx].highValue))
<< FormatArgument("HIGH_VALUE_INV", de::toString(precisions[precNdx].invHighValue))
<< FormatArgument("MEDIUM_VALUE", de::toString(precisions[precNdx].mediumValue))
<< FormatArgument("LOW_VALUE", de::toString(precisions[precNdx].lowValue))
<< FormatArgument("LOW_VALUE_INV", de::toString(precisions[precNdx].invlowValue))
<< FormatArgument("LOOP_ITERS", de::toString(precisions[precNdx].loopIterations))
<< FormatArgument("LOOP_ITERS_PARTIAL", de::toString(precisions[precNdx].loopPartialIterations))
<< FormatArgument("LOOP_NORM_FRACT_EXP", de::toString(precisions[precNdx].loopNormalizationExponent))
<< FormatArgument("LOOP_NORM_LITERAL", precisions[precNdx].loopNormalizationConstantLiteral)
<< FormatArgument("LOOP_MULTIPLIER", precisions[precNdx].loopMultiplier)
<< FormatArgument("SUM_LOOP_NORM_LITERAL", precisions[precNdx].sumLoopNormalizationConstantLiteral);
addChild(group);
// subexpression cases
{
// First shader shares "${HIGH_VALUE}*a_input.x*a_input.xxxx + ${HIGH_VALUE}*a_input.y*a_input.yyyy" with unrelated output variable. Reordering might result in accuracy loss
// due to the high exponent. In the second shader, the high exponent may be removed during compilation.
group->addChild(new BasicInvarianceTest(m_context, "common_subexpression_0", "Shader shares a subexpression with an unrelated variable.",
formatGLSL( "${VERSION}"
"${IN} ${IN_PREC} vec4 a_input;\n"
"${OUT} mediump vec4 v_unrelated;\n"
"invariant gl_Position;\n"
"void main ()\n"
"{\n"
" v_unrelated = a_input.xzxz + (${HIGH_VALUE}*a_input.x*a_input.xxxx + ${HIGH_VALUE}*a_input.y*a_input.yyyy) * (1.08 * a_input.zyzy * a_input.xzxz) * ${HIGH_VALUE_INV} * (a_input.z * a_input.zzxz - a_input.z * a_input.zzxz) + (${HIGH_VALUE}*a_input.x*a_input.xxxx + ${HIGH_VALUE}*a_input.y*a_input.yyyy) / ${HIGH_VALUE};\n"
" gl_Position = a_input + (${HIGH_VALUE}*a_input.x*a_input.xxxx + ${HIGH_VALUE}*a_input.y*a_input.yyyy) * ${HIGH_VALUE_INV};\n"
"}\n", args),
formatGLSL( "${VERSION}"
"${IN} ${IN_PREC} vec4 a_input;\n"
"${OUT} mediump vec4 v_unrelated;\n"
"invariant gl_Position;\n"
"void main ()\n"
"{\n"
" v_unrelated = vec4(0.0, 0.0, 0.0, 0.0);\n"
" gl_Position = a_input + (${HIGH_VALUE}*a_input.x*a_input.xxxx + ${HIGH_VALUE}*a_input.y*a_input.yyyy) * ${HIGH_VALUE_INV};\n"
"}\n", args)));
// In the first shader, the unrelated variable "d" has mathematically the same expression as "e", but the different
// order of calculation might cause different results.
group->addChild(new BasicInvarianceTest(m_context, "common_subexpression_1", "Shader shares a subexpression with an unrelated variable.",
formatGLSL( "${VERSION}"
"${IN} ${IN_PREC} vec4 a_input;\n"
"${OUT} mediump vec4 v_unrelated;\n"
"invariant gl_Position;\n"
"void main ()\n"
"{\n"
" ${IN_PREC} vec4 a = ${HIGH_VALUE} * a_input.zzxx + a_input.xzxy - ${HIGH_VALUE} * a_input.zzxx;\n"
" ${IN_PREC} vec4 b = ${HIGH_VALUE} * a_input.zzxx;\n"
" ${IN_PREC} vec4 c = b - ${HIGH_VALUE} * a_input.zzxx + a_input.xzxy;\n"
" ${IN_PREC} vec4 d = (${LOW_VALUE} * a_input.yzxx) * (${LOW_VALUE} * a_input.yzzw) * (1.1*${LOW_VALUE_INV} * a_input.yzxx) * (${LOW_VALUE_INV} * a_input.xzzy);\n"
" ${IN_PREC} vec4 e = ((${LOW_VALUE} * a_input.yzxx) * (1.1*${LOW_VALUE_INV} * a_input.yzxx)) * ((${LOW_VALUE_INV} * a_input.xzzy) * (${LOW_VALUE} * a_input.yzzw));\n"
" v_unrelated = a + b + c + d + e;\n"
" gl_Position = a_input + fract(c) + e;\n"
"}\n", args),
formatGLSL( "${VERSION}"
"${IN} ${IN_PREC} vec4 a_input;\n"
"${OUT} mediump vec4 v_unrelated;\n"
"invariant gl_Position;\n"
"void main ()\n"
"{\n"
" ${IN_PREC} vec4 b = ${HIGH_VALUE} * a_input.zzxx;\n"
" ${IN_PREC} vec4 c = b - ${HIGH_VALUE} * a_input.zzxx + a_input.xzxy;\n"
" ${IN_PREC} vec4 e = ((${LOW_VALUE} * a_input.yzxx) * (1.1*${LOW_VALUE_INV} * a_input.yzxx)) * ((${LOW_VALUE_INV} * a_input.xzzy) * (${LOW_VALUE} * a_input.yzzw));\n"
" v_unrelated = vec4(0.0, 0.0, 0.0, 0.0);\n"
" gl_Position = a_input + fract(c) + e;\n"
"}\n", args)));
// Intermediate values used by an unrelated output variable
group->addChild(new BasicInvarianceTest(m_context, "common_subexpression_2", "Shader shares a subexpression with an unrelated variable.",
formatGLSL( "${VERSION}"
"${IN} ${IN_PREC} vec4 a_input;\n"
"${OUT} mediump vec4 v_unrelated;\n"
"invariant gl_Position;\n"
"void main ()\n"
"{\n"
" ${IN_PREC} vec4 a = ${MEDIUM_VALUE} * (a_input.xxxx + a_input.yyyy);\n"
" ${IN_PREC} vec4 b = (${MEDIUM_VALUE} * (a_input.xxxx + a_input.yyyy)) * (${MEDIUM_VALUE} * (a_input.xxxx + a_input.yyyy)) / ${MEDIUM_VALUE} / ${MEDIUM_VALUE};\n"
" ${IN_PREC} vec4 c = a * a;\n"
" ${IN_PREC} vec4 d = c / ${MEDIUM_VALUE} / ${MEDIUM_VALUE};\n"
" v_unrelated = a + b + c + d;\n"
" gl_Position = a_input + d;\n"
"}\n", args),
formatGLSL( "${VERSION}"
"${IN} ${IN_PREC} vec4 a_input;\n"
"${OUT} mediump vec4 v_unrelated;\n"
"invariant gl_Position;\n"
"void main ()\n"
"{\n"
" ${IN_PREC} vec4 a = ${MEDIUM_VALUE} * (a_input.xxxx + a_input.yyyy);\n"
" ${IN_PREC} vec4 c = a * a;\n"
" ${IN_PREC} vec4 d = c / ${MEDIUM_VALUE} / ${MEDIUM_VALUE};\n"
" v_unrelated = vec4(0.0, 0.0, 0.0, 0.0);\n"
" gl_Position = a_input + d;\n"
"}\n", args)));
// Invariant value can be calculated using unrelated value
group->addChild(new BasicInvarianceTest(m_context, "common_subexpression_3", "Shader shares a subexpression with an unrelated variable.",
formatGLSL( "${VERSION}"
"${IN} ${IN_PREC} vec4 a_input;\n"
"${OUT} mediump vec4 v_unrelated;\n"
"invariant gl_Position;\n"
"void main ()\n"
"{\n"
" ${IN_PREC} float x = a_input.x * 0.2;\n"
" ${IN_PREC} vec4 a = a_input.xxyx * 0.7;\n"
" ${IN_PREC} vec4 b = a_input.yxyz * 0.7;\n"
" ${IN_PREC} vec4 c = a_input.zxyx * 0.5;\n"
" ${IN_PREC} vec4 f = x*a + x*b + x*c;\n"
" v_unrelated = f;\n"
" ${IN_PREC} vec4 g = x * (a + b + c);\n"
" gl_Position = a_input + g;\n"
"}\n", args),
formatGLSL( "${VERSION}"
"${IN} ${IN_PREC} vec4 a_input;\n"
"${OUT} mediump vec4 v_unrelated;\n"
"invariant gl_Position;\n"
"void main ()\n"
"{\n"
" ${IN_PREC} float x = a_input.x * 0.2;\n"
" ${IN_PREC} vec4 a = a_input.xxyx * 0.7;\n"
" ${IN_PREC} vec4 b = a_input.yxyz * 0.7;\n"
" ${IN_PREC} vec4 c = a_input.zxyx * 0.5;\n"
" v_unrelated = vec4(0.0, 0.0, 0.0, 0.0);\n"
" ${IN_PREC} vec4 g = x * (a + b + c);\n"
" gl_Position = a_input + g;\n"
"}\n", args)));
}
// shared subexpression of different precision
{
for (int precisionOther = glu::PRECISION_LOWP; precisionOther != glu::PRECISION_LAST; ++precisionOther)
{
const char* const unrelatedPrec = glu::getPrecisionName((glu::Precision)precisionOther);
const glu::Precision minPrecision = (precisionOther < (int)precision) ? ((glu::Precision)precisionOther) : (precision);
const char* const multiplierStr = (minPrecision == glu::PRECISION_LOWP) ? ("0.8, 0.4, -0.2, 0.3") : ("1.0e1, 5.0e2, 2.0e2, 1.0");
const char* const normalizationStrUsed = (minPrecision == glu::PRECISION_LOWP) ? ("vec4(fract(used2).xyz, 0.0)") : ("vec4(fract(used2 / 1.0e2).xyz - fract(used2 / 1.0e3).xyz, 0.0)");
const char* const normalizationStrUnrelated = (minPrecision == glu::PRECISION_LOWP) ? ("vec4(fract(unrelated2).xyz, 0.0)") : ("vec4(fract(unrelated2 / 1.0e2).xyz - fract(unrelated2 / 1.0e3).xyz, 0.0)");
group->addChild(new BasicInvarianceTest(m_context, ("subexpression_precision_" + std::string(unrelatedPrec)).c_str(), "Shader shares subexpression of different precision with an unrelated variable.",
formatGLSL( "${VERSION}"
"${IN} ${IN_PREC} vec4 a_input;\n"
"${OUT} ${UNRELATED_PREC} vec4 v_unrelated;\n"
"invariant gl_Position;\n"
"void main ()\n"
"{\n"
" ${UNRELATED_PREC} vec4 unrelated0 = a_input + vec4(0.1, 0.2, 0.3, 0.4);\n"
" ${UNRELATED_PREC} vec4 unrelated1 = vec4(${MULTIPLIER}) * unrelated0.xywz + unrelated0;\n"
" ${UNRELATED_PREC} vec4 unrelated2 = refract(unrelated1, unrelated0, distance(unrelated0, unrelated1));\n"
" v_unrelated = a_input + 0.02 * ${NORMALIZE_UNRELATED};\n"
" ${IN_PREC} vec4 used0 = a_input + vec4(0.1, 0.2, 0.3, 0.4);\n"
" ${IN_PREC} vec4 used1 = vec4(${MULTIPLIER}) * used0.xywz + used0;\n"
" ${IN_PREC} vec4 used2 = refract(used1, used0, distance(used0, used1));\n"
" gl_Position = a_input + 0.02 * ${NORMALIZE_USED};\n"
"}\n", FormatArgumentList(args)
<< FormatArgument("UNRELATED_PREC", unrelatedPrec)
<< FormatArgument("MULTIPLIER", multiplierStr)
<< FormatArgument("NORMALIZE_USED", normalizationStrUsed)
<< FormatArgument("NORMALIZE_UNRELATED", normalizationStrUnrelated)),
formatGLSL( "${VERSION}"
"${IN} ${IN_PREC} vec4 a_input;\n"
"${OUT} ${UNRELATED_PREC} vec4 v_unrelated;\n"
"invariant gl_Position;\n"
"void main ()\n"
"{\n"
" v_unrelated = vec4(0.0, 0.0, 0.0, 0.0);\n"
" ${IN_PREC} vec4 used0 = a_input + vec4(0.1, 0.2, 0.3, 0.4);\n"
" ${IN_PREC} vec4 used1 = vec4(${MULTIPLIER}) * used0.xywz + used0;\n"
" ${IN_PREC} vec4 used2 = refract(used1, used0, distance(used0, used1));\n"
" gl_Position = a_input + 0.02 * ${NORMALIZE_USED};\n"
"}\n", FormatArgumentList(args)
<< FormatArgument("UNRELATED_PREC", unrelatedPrec)
<< FormatArgument("MULTIPLIER", multiplierStr)
<< FormatArgument("NORMALIZE_USED", normalizationStrUsed)
<< FormatArgument("NORMALIZE_UNRELATED", normalizationStrUnrelated))));
}
}
// loops
{
group->addChild(new BasicInvarianceTest(m_context, "loop_0", "Invariant value set using a loop",
formatGLSL( "${VERSION}"
"${IN} ${IN_PREC} vec4 a_input;\n"
"${OUT} highp vec4 v_unrelated;\n"
"invariant gl_Position;\n"
"void main ()\n"
"{\n"
" ${IN_PREC} vec4 value = a_input;\n"
" v_unrelated = vec4(0.0, 0.0, 0.0, 0.0);\n"
" for (mediump int i = 0; i < ${LOOP_ITERS}; ++i)\n"
" {\n"
" value *= ${LOOP_MULTIPLIER};\n"
" v_unrelated += value;\n"
" }\n"
" gl_Position = vec4(value.xyz / ${LOOP_NORM_LITERAL} + a_input.xyz * 0.1, 1.0);\n"
"}\n", args),
formatGLSL( "${VERSION}"
"${IN} ${IN_PREC} vec4 a_input;\n"
"${OUT} highp vec4 v_unrelated;\n"
"invariant gl_Position;\n"
"void main ()\n"
"{\n"
" ${IN_PREC} vec4 value = a_input;\n"
" v_unrelated = vec4(0.0, 0.0, 0.0, 0.0);\n"
" for (mediump int i = 0; i < ${LOOP_ITERS}; ++i)\n"
" {\n"
" value *= ${LOOP_MULTIPLIER};\n"
" }\n"
" gl_Position = vec4(value.xyz / ${LOOP_NORM_LITERAL} + a_input.xyz * 0.1, 1.0);\n"
"}\n", args)));
group->addChild(new BasicInvarianceTest(m_context, "loop_1", "Invariant value set using a loop",
formatGLSL( "${VERSION}"
"${IN} ${IN_PREC} vec4 a_input;\n"
"${OUT} mediump vec4 v_unrelated;\n"
"invariant gl_Position;\n"
"void main ()\n"
"{\n"
" ${IN_PREC} vec4 value = a_input;\n"
" for (mediump int i = 0; i < ${LOOP_ITERS}; ++i)\n"
" {\n"
" value *= ${LOOP_MULTIPLIER};\n"
" if (i == ${LOOP_ITERS_PARTIAL})\n"
" v_unrelated = value;\n"
" }\n"
" gl_Position = vec4(value.xyz / ${LOOP_NORM_LITERAL} + a_input.xyz * 0.1, 1.0);\n"
"}\n", args),
formatGLSL( "${VERSION}"
"${IN} ${IN_PREC} vec4 a_input;\n"
"${OUT} mediump vec4 v_unrelated;\n"
"invariant gl_Position;\n"
"void main ()\n"
"{\n"
" ${IN_PREC} vec4 value = a_input;\n"
" v_unrelated = vec4(0.0, 0.0, 0.0, 0.0);\n"
" for (mediump int i = 0; i < ${LOOP_ITERS}; ++i)\n"
" {\n"
" value *= ${LOOP_MULTIPLIER};\n"
" }\n"
" gl_Position = vec4(value.xyz / ${LOOP_NORM_LITERAL} + a_input.xyz * 0.1, 1.0);\n"
"}\n", args)));
group->addChild(new BasicInvarianceTest(m_context, "loop_2", "Invariant value set using a loop",
formatGLSL( "${VERSION}"
"${IN} ${IN_PREC} vec4 a_input;\n"
"${OUT} mediump vec4 v_unrelated;\n"
"invariant gl_Position;\n"
"void main ()\n"
"{\n"
" ${IN_PREC} vec4 value = a_input;\n"
" v_unrelated = vec4(0.0, 0.0, -1.0, 1.0);\n"
" for (mediump int i = 0; i < ${LOOP_ITERS}; ++i)\n"
" {\n"
" value *= ${LOOP_MULTIPLIER};\n"
" if (i == ${LOOP_ITERS_PARTIAL})\n"
" gl_Position = a_input + 0.05 * vec4(fract(value.xyz / 1.0e${LOOP_NORM_FRACT_EXP}), 1.0);\n"
" else\n"
" v_unrelated = value + a_input;\n"
" }\n"
"}\n", args),
formatGLSL( "${VERSION}"
"${IN} ${IN_PREC} vec4 a_input;\n"
"${OUT} mediump vec4 v_unrelated;\n"
"invariant gl_Position;\n"
"void main ()\n"
"{\n"
" ${IN_PREC} vec4 value = a_input;\n"
" v_unrelated = vec4(0.0, 0.0, -1.0, 1.0);\n"
" for (mediump int i = 0; i < ${LOOP_ITERS}; ++i)\n"
" {\n"
" value *= ${LOOP_MULTIPLIER};\n"
" if (i == ${LOOP_ITERS_PARTIAL})\n"
" gl_Position = a_input + 0.05 * vec4(fract(value.xyz / 1.0e${LOOP_NORM_FRACT_EXP}), 1.0);\n"
" else\n"
" v_unrelated = vec4(0.0, 0.0, 0.0, 0.0);\n"
" }\n"
"}\n", args)));
group->addChild(new BasicInvarianceTest(m_context, "loop_3", "Invariant value set using a loop",
formatGLSL( "${VERSION}"
"${IN} ${IN_PREC} vec4 a_input;\n"
"${OUT} mediump vec4 v_unrelated;\n"
"invariant gl_Position;\n"
"void main ()\n"
"{\n"
" ${IN_PREC} vec4 value = a_input;\n"
" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);\n"
" v_unrelated = vec4(0.0, 0.0, 0.0, 0.0);\n"
" for (mediump int i = 0; i < ${LOOP_ITERS}; ++i)\n"
" {\n"
" value *= ${LOOP_MULTIPLIER};\n"
" gl_Position += vec4(value.xyz / ${SUM_LOOP_NORM_LITERAL} + a_input.xyz * 0.1, 1.0);\n"
" v_unrelated = gl_Position.xyzx * a_input;\n"
" }\n"
"}\n", args),
formatGLSL( "${VERSION}"
"${IN} ${IN_PREC} vec4 a_input;\n"
"${OUT} mediump vec4 v_unrelated;\n"
"invariant gl_Position;\n"
"void main ()\n"
"{\n"
" ${IN_PREC} vec4 value = a_input;\n"
" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);\n"
" v_unrelated = vec4(0.0, 0.0, 0.0, 0.0);\n"
" for (mediump int i = 0; i < ${LOOP_ITERS}; ++i)\n"
" {\n"
" value *= ${LOOP_MULTIPLIER};\n"
" gl_Position += vec4(value.xyz / ${SUM_LOOP_NORM_LITERAL} + a_input.xyz * 0.1, 1.0);\n"
" }\n"
"}\n", args)));
group->addChild(new BasicInvarianceTest(m_context, "loop_4", "Invariant value set using a loop",
formatGLSL( "${VERSION}"
"${IN} ${IN_PREC} vec4 a_input;\n"
"${OUT} mediump vec4 v_unrelated;\n"
"invariant gl_Position;\n"
"void main ()\n"
"{\n"
" ${IN_PREC} vec4 position = vec4(0.0, 0.0, 0.0, 0.0);\n"
" ${IN_PREC} vec4 value1 = a_input;\n"
" ${IN_PREC} vec4 value2 = a_input;\n"
" v_unrelated = vec4(0.0, 0.0, 0.0, 0.0);\n"
" for (mediump int i = 0; i < ${LOOP_ITERS}; ++i)\n"
" {\n"
" value1 *= ${LOOP_MULTIPLIER};\n"
" v_unrelated = v_unrelated*1.3 + a_input.xyzx * value1.xyxw;\n"
" }\n"
" for (mediump int i = 0; i < ${LOOP_ITERS}; ++i)\n"
" {\n"
" value2 *= ${LOOP_MULTIPLIER};\n"
" position = position*1.3 + a_input.xyzx * value2.xyxw;\n"
" }\n"
" gl_Position = a_input + 0.05 * vec4(fract(position.xyz / 1.0e${LOOP_NORM_FRACT_EXP}), 1.0);\n"
"}\n", args),
formatGLSL( "${VERSION}"
"${IN} ${IN_PREC} vec4 a_input;\n"
"${OUT} mediump vec4 v_unrelated;\n"
"invariant gl_Position;\n"
"void main ()\n"
"{\n"
" ${IN_PREC} vec4 position = vec4(0.0, 0.0, 0.0, 0.0);\n"
" ${IN_PREC} vec4 value2 = a_input;\n"
" v_unrelated = vec4(0.0, 0.0, 0.0, 0.0);\n"
" for (mediump int i = 0; i < ${LOOP_ITERS}; ++i)\n"
" {\n"
" value2 *= ${LOOP_MULTIPLIER};\n"
" position = position*1.3 + a_input.xyzx * value2.xyxw;\n"
" }\n"
" gl_Position = a_input + 0.05 * vec4(fract(position.xyz / 1.0e${LOOP_NORM_FRACT_EXP}), 1.0);\n"
"}\n", args)));
}
}
}
} // Functional
} // gles2
} // deqp
| 16,192 |
488 |
class PR12656_base
{
public static void main(String[] args)
{
System.out.println("Maude");
}
}
public class PR12656 extends PR12656_base
{
}
| 58 |
485 |
/*
* The MIT License
*
* Copyright (c) 2015, CloudBees, 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.
*/
package org.jenkinsci.plugins.docker.workflow;
import hudson.EnvVars;
import org.jenkinsci.plugins.docker.workflow.client.DockerClient;
import hudson.Launcher;
import hudson.util.StreamTaskListener;
import hudson.util.VersionNumber;
import org.junit.Assume;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.jenkinsci.plugins.docker.commons.tools.DockerTool;
/**
* @author <a href="mailto:<EMAIL>"><EMAIL></a>
*/
public class DockerTestUtil {
public static String DEFAULT_MINIMUM_VERSION = "1.3";
public static void assumeDocker() throws Exception {
assumeDocker(new VersionNumber(DEFAULT_MINIMUM_VERSION));
}
public static void assumeDocker(VersionNumber minimumVersion) throws Exception {
Launcher.LocalLauncher localLauncher = new Launcher.LocalLauncher(StreamTaskListener.NULL);
try {
int status = localLauncher
.launch()
.cmds(DockerTool.getExecutable(null, null, null, null), "ps")
.start()
.joinWithTimeout(DockerClient.CLIENT_TIMEOUT, TimeUnit.SECONDS, localLauncher.getListener());
Assume.assumeTrue("Docker working", status == 0);
} catch (IOException x) {
Assume.assumeNoException("have Docker installed", x);
}
DockerClient dockerClient = new DockerClient(localLauncher, null, null);
Assume.assumeFalse("Docker version not < " + minimumVersion.toString(), dockerClient.version().isOlderThan(minimumVersion));
}
public static void assumeNotWindows() throws Exception {
Assume.assumeFalse(System.getProperty("os.name").toLowerCase().contains("windows"));
}
public static EnvVars newDockerLaunchEnv() {
// Create the KeyMaterial for connecting to the docker host/server.
// E.g. currently need to add something like the following to your env
// -DDOCKER_HOST_FOR_TEST="tcp://192.168.x.y:2376"
// -DDOCKER_HOST_KEY_DIR_FOR_TEST="/Users/tfennelly/.boot2docker/certs/boot2docker-vm"
final String docker_host_for_test = System.getProperty("DOCKER_HOST_FOR_TEST");
final String docker_host_key_dir_for_test = System.getProperty("DOCKER_HOST_KEY_DIR_FOR_TEST");
EnvVars env = new EnvVars();
if (docker_host_for_test != null) {
env.put("DOCKER_HOST", docker_host_for_test);
}
if (docker_host_key_dir_for_test != null) {
env.put("DOCKER_TLS_VERIFY", "1");
env.put("DOCKER_CERT_PATH", docker_host_key_dir_for_test);
}
return env;
}
private DockerTestUtil() {}
}
| 1,378 |
1,595 |
<reponame>GenericP3rson/pygraphistry
#Enable when we drop 3.6
#from __future__ import annotations
from typing import List, Optional
import io, logging, pyarrow as pa, requests, sys
from .ArrowFileUploader import ArrowFileUploader
logger = logging.getLogger('ArrowUploader')
class ArrowUploader:
@property
def token(self) -> str:
if self.__token is None:
raise Exception("Not logged in")
return self.__token
@token.setter
def token(self, token: str):
self.__token = token
@property
def dataset_id(self) -> str:
if self.__dataset_id is None:
raise Exception("Must first create a dataset")
return self.__dataset_id
@dataset_id.setter
def dataset_id(self, dataset_id: str):
self.__dataset_id = dataset_id
@property
def server_base_path(self) -> str:
return self.__server_base_path
@server_base_path.setter
def server_base_path(self, server_base_path: str):
self.__server_base_path = server_base_path
@property
def view_base_path(self) -> str:
return self.__view_base_path
@view_base_path.setter
def view_base_path(self, view_base_path: str):
self.__view_base_path = view_base_path
@property
def edges(self) -> pa.Table:
return self.__edges
@edges.setter
def edges(self, edges: pa.Table):
self.__edges = edges
@property
def nodes(self) -> pa.Table:
return self.__nodes
@nodes.setter
def nodes(self, nodes: pa.Table):
self.__nodes = nodes
@property
def node_encodings(self):
if self.__node_encodings is None:
return {'bindings': {}}
return self.__node_encodings
@node_encodings.setter
def node_encodings(self, node_encodings):
self.__node_encodings = node_encodings
@property
def edge_encodings(self):
if self.__edge_encodings is None:
return {'bindings': {}}
return self.__edge_encodings
@edge_encodings.setter
def edge_encodings(self, edge_encodings):
self.__edge_encodings = edge_encodings
@property
def name(self) -> str:
if self.__name is None:
return "untitled"
return self.__name
@name.setter
def name(self, name):
self.__name = name
@property
def description(self) -> str:
if self.__description is None:
return ""
return self.__description
@description.setter
def description(self, description):
self.__description = description
@property
def metadata(self):
return {
#'usertag': PyGraphistry._tag,
#'key': PyGraphistry.api_key()
'agent': 'pygraphistry',
'apiversion' : '3',
'agentversion': sys.modules['graphistry'].__version__,
**(self.__metadata if not (self.__metadata is None) else {})
}
@metadata.setter
def metadata(self, metadata):
self.__metadata = metadata
#########################################################################
@property
def certificate_validation(self):
return self.__certificate_validation
@certificate_validation.setter
def certificate_validation(self, certificate_validation):
self.__certificate_validation = certificate_validation
########################################################################3
def __init__(self,
server_base_path='http://nginx', view_base_path='http://localhost',
name = None,
description = None,
edges = None, nodes = None,
node_encodings = None, edge_encodings = None,
token = None, dataset_id = None,
metadata = None,
certificate_validation = True):
self.__name = name
self.__description = description
self.__server_base_path = server_base_path
self.__view_base_path = view_base_path
self.__token = token
self.__dataset_id = dataset_id
self.__edges = edges
self.__nodes = nodes
self.__node_encodings = node_encodings
self.__edge_encodings = edge_encodings
self.__metadata = metadata
self.__certificate_validation = certificate_validation
def login(self, username, password):
base_path = self.server_base_path
out = requests.post(
f'{base_path}/api-token-auth/',
verify=self.certificate_validation,
json={'username': username, 'password': password})
json_response = None
try:
json_response = out.json()
if not ('token' in json_response):
raise Exception(out.text)
except Exception:
logger.error('Error: %s', out, exc_info=True)
raise Exception(out.text)
self.token = out.json()['token']
return self
def refresh(self, token=None):
if token is None:
token = self.token
base_path = self.server_base_path
out = requests.post(
f'{base_path}/api-token-refresh/',
verify=self.certificate_validation,
json={'token': token})
json_response = None
try:
json_response = out.json()
if not ('token' in json_response):
raise Exception(out.text)
except Exception:
logger.error('Error: %s', out, exc_info=True)
raise Exception(out.text)
self.token = out.json()['token']
return self
def verify(self, token=None) -> bool:
if token is None:
token = self.token
base_path = self.server_base_path
out = requests.post(
f'{base_path}/api-token-verify/',
verify=self.certificate_validation,
json={'token': token})
return out.status_code == requests.codes.ok
def create_dataset(self, json): # noqa: F811
tok = self.token
res = requests.post(
self.server_base_path + '/api/v2/upload/datasets/',
verify=self.certificate_validation,
headers={'Authorization': f'Bearer {tok}'},
json=json)
try:
out = res.json()
if not out['success']:
raise Exception(out)
except Exception as e:
logger.error('Failed creating dataset: %s', res.text, exc_info=True)
raise e
self.dataset_id = out['data']['dataset_id']
return out
#PyArrow's table.getvalues().to_pybytes() fails to hydrate some reason,
# so work around by consolidate into a virtual file and sending that
def arrow_to_buffer(self, table: pa.Table):
b = io.BytesIO()
writer = pa.RecordBatchFileWriter(b, table.schema)
writer.write_table(table)
writer.close()
return b.getvalue()
def maybe_bindings(self, g, bindings, base = {}):
out = { **base }
for old_field_name, new_field_name in bindings:
try:
val = getattr(g, old_field_name)
if val is None:
continue
else:
out[new_field_name] = val
except AttributeError:
continue
logger.debug('bindings: %s', out)
return out
def g_to_node_bindings(self, g):
bindings = self.maybe_bindings( # noqa: E126
g, # noqa: E126
[
['_node', 'node'],
['_point_color', 'node_color'],
['_point_label', 'node_label'],
['_point_opacity', 'node_opacity'],
['_point_size', 'node_size'],
['_point_title', 'node_title'],
['_point_weight', 'node_weight'],
['_point_icon', 'node_icon'],
['_point_x', 'node_x'],
['_point_y', 'node_y']
])
return bindings
def g_to_node_encodings(self, g):
encodings = {
'bindings': self.g_to_node_bindings(g)
}
for mode in ['current', 'default']:
if len(g._complex_encodings['node_encodings'][mode].keys()) > 0:
if not ('complex' in encodings):
encodings['complex'] = {}
encodings['complex'][mode] = g._complex_encodings['node_encodings'][mode]
return encodings
def g_to_edge_bindings(self, g):
bindings = self.maybe_bindings( # noqa: E126
g, # noqa: E126
[
['_source', 'source'],
['_destination', 'destination'],
['_edge_color', 'edge_color'],
['_edge_source_color', 'edge_source_color'],
['_edge_destination_color', 'edge_destination_color'],
['_edge_label', 'edge_label'],
['_edge_opacity', 'edge_opacity'],
['_edge_size', 'edge_size'],
['_edge_title', 'edge_title'],
['_edge_weight', 'edge_weight'],
['_edge_icon', 'edge_icon']
])
return bindings
def g_to_edge_encodings(self, g):
encodings = {
'bindings': self.g_to_edge_bindings(g)
}
for mode in ['current', 'default']:
if len(g._complex_encodings['edge_encodings'][mode].keys()) > 0:
if not ('complex' in encodings):
encodings['complex'] = {}
encodings['complex'][mode] = g._complex_encodings['edge_encodings'][mode]
return encodings
def post(self, as_files: bool = True, memoize: bool = True):
"""
Note: likely want to pair with self.maybe_post_share_link(g)
"""
if as_files:
file_uploader = ArrowFileUploader(self)
e_file_id, _ = file_uploader.create_and_post_file(self.edges, file_opts={'name': self.name + ' edges'})
if not (self.nodes is None):
n_file_id, _ = file_uploader.create_and_post_file(self.nodes, file_opts={'name': self.name + ' nodes'})
self.create_dataset({
"node_encodings": self.node_encodings,
"edge_encodings": self.edge_encodings,
"metadata": self.metadata,
"name": self.name,
"description": self.description,
"edge_files": [ e_file_id ],
**({"node_files": [ n_file_id ] if not (self.nodes is None) else []})
})
else:
self.create_dataset({
"node_encodings": self.node_encodings,
"edge_encodings": self.edge_encodings,
"metadata": self.metadata,
"name": self.name,
"description": self.description
})
self.post_edges_arrow()
if not (self.nodes is None):
self.post_nodes_arrow()
return self
###########################################
def cascade_privacy_settings(
self,
mode: Optional[str] = None,
notify: Optional[bool] = None,
invited_users: Optional[List] = None,
message: Optional[str] = None
):
"""
Cascade:
- local (passed in)
- global
- hard-coded
"""
from .pygraphistry import PyGraphistry
global_privacy = PyGraphistry._config['privacy']
if global_privacy is not None:
if mode is None:
mode = global_privacy['mode']
if notify is None:
notify = global_privacy['notify']
if invited_users is None:
invited_users = global_privacy['invited_users']
if message is None:
message = global_privacy['message']
if mode is None:
mode = 'private'
if notify is None:
notify = False
if invited_users is None:
invited_users = []
if message is None:
message = ''
return mode, notify, invited_users, message
def post_share_link(
self,
obj_pk: str,
obj_type: str = 'dataset',
privacy: Optional[dict] = None
):
"""
Set sharing settings. Any settings not passed here will cascade from PyGraphistry or defaults
"""
mode, notify, invited_users, message = self.cascade_privacy_settings(**(privacy or {}))
path = self.server_base_path + '/api/v2/share/link/'
tok = self.token
res = requests.post(
path,
verify=self.certificate_validation,
headers={'Authorization': f'Bearer {tok}'},
json={
'obj_pk': obj_pk,
'obj_type': obj_type,
'mode': mode,
'notify': notify,
'invited_users': invited_users,
'message': message
})
if res.status_code != requests.codes.ok:
logger.error('Failed setting sharing status (code %s): %s', res.status_code, res.text, exc_info=True)
if res.status_code == 404:
raise Exception(f'Code not find resource {path}; is your server location correct and does it support sharing?')
if res.status_code == 403:
raise Exception(f'Permission denied ({path}); do you have edit access and does your account having sharing enabled?')
try:
out = res.json()
logger.debug('Server create file response: %s', out)
if res.status_code != requests.codes.ok:
res.raise_for_status()
except Exception as e:
logger.error('Unexpected error setting sharing settings: %s', res.text, exc_info=True)
raise e
logger.debug('Set privacy: mode %s, notify %s, users %s, message: %s', mode, notify, invited_users, message)
return out
###########################################
def post_edges_arrow(self, arr=None, opts=''):
if arr is None:
arr = self.edges
return self.post_arrow(arr, 'edges', opts)
def post_nodes_arrow(self, arr=None, opts=''):
if arr is None:
arr = self.nodes
return self.post_arrow(arr, 'nodes', opts)
def post_arrow(self, arr: pa.Table, graph_type: str, opts: str = ''):
dataset_id = self.dataset_id
tok = self.token
sub_path = f'api/v2/upload/datasets/{dataset_id}/{graph_type}/arrow'
try:
resp = self.post_arrow_generic(sub_path, tok, arr, opts)
out = resp.json()
if not ('success' in out) or not out['success']:
raise Exception('No success indicator in server response')
return out
except requests.exceptions.HTTPError as e:
logger.error('Failed to post arrow to %s (%s)', sub_path, e.request.url, exc_info=True)
logger.error('%s', e)
logger.error('%s', e.response.text)
raise e
except Exception as e:
logger.error('Failed to post arrow to %s', sub_path, exc_info=True)
raise e
def post_arrow_generic(self, sub_path: str, tok: str, arr: pa.Table, opts='') -> requests.Response:
buf = self.arrow_to_buffer(arr)
base_path = self.server_base_path
url = f'{base_path}/{sub_path}'
if len(opts) > 0:
url = f'{url}?{opts}'
resp = requests.post(
url,
verify=self.certificate_validation,
headers={'Authorization': f'Bearer {tok}'},
data=buf)
if resp.status_code != requests.codes.ok:
resp.raise_for_status()
return resp
###########################################
#TODO refactor to be part of post()
def maybe_post_share_link(self, g) -> bool:
"""
Skip if never called .privacy()
Return True/False based on whether called
"""
from .pygraphistry import PyGraphistry
logger.debug('Privacy: global (%s), local (%s)', PyGraphistry._config['privacy'] or 'None', g._privacy or 'None')
if PyGraphistry._config['privacy'] is not None or g._privacy is not None:
self.post_share_link(self.dataset_id, 'dataset', g._privacy)
return True
return False
def post_g(self, g, name=None, description=None):
"""
Warning: main post() does not call this
"""
self.edge_encodings = self.g_to_edge_encodings(g)
self.node_encodings = self.g_to_node_encodings(g)
if not (name is None):
self.name = name
if not (description is None):
self.description = description
self.edges = pa.Table.from_pandas(g._edges, preserve_index=False).replace_schema_metadata({})
if not (g._nodes is None):
self.nodes = pa.Table.from_pandas(g._nodes, preserve_index=False).replace_schema_metadata({})
out = self.post()
self.maybe_post_share_link(g)
return out
def post_edges_file(self, file_path, file_type='csv'):
return self.post_file(file_path, 'edges', file_type)
def post_nodes_file(self, file_path, file_type='csv'):
return self.post_file(file_path, 'nodes', file_type)
def post_file(self, file_path, graph_type='edges', file_type='csv'):
dataset_id = self.dataset_id
tok = self.token
base_path = self.server_base_path
with open(file_path, 'rb') as file:
out = requests.post(
f'{base_path}/api/v2/upload/datasets/{dataset_id}/{graph_type}/{file_type}',
verify=self.certificate_validation,
headers={'Authorization': f'Bearer {tok}'},
data=file.read()).json()
if not out['success']:
raise Exception(out)
return out
| 8,855 |
320 |
#include "src/cpp/basic/edgetpu_resource_manager.h"
#include "absl/memory/memory.h"
#include "absl/strings/substitute.h"
#include "glog/logging.h"
namespace coral {
EdgeTpuResource::~EdgeTpuResource() {
EdgeTpuResourceManager::GetSingleton()->ReclaimEdgeTpuResource(path_);
}
EdgeTpuResourceManager* EdgeTpuResourceManager::GetSingleton() {
// Such static local variable's initialization is thread-safe.
// https://stackoverflow.com/questions/8102125/is-local-static-variable-initialization-thread-safe-in-c11.
static auto* const manager = new EdgeTpuResourceManager();
return manager;
}
EdgeTpuResourceManager::EdgeTpuResourceManager() {
error_reporter_ = absl::make_unique<EdgeTpuErrorReporter>();
}
EdgeTpuApiStatus EdgeTpuResourceManager::CreateEdgeTpuResource(
const edgetpu::DeviceType type, const std::string& path,
std::unique_ptr<EdgeTpuResource>* resource) {
CHECK(resource);
std::unordered_map<std::string, std::string> options = {
{"Usb.MaxBulkInQueueLength", "8"},
};
auto tpu_context =
edgetpu::EdgeTpuManager::GetSingleton()->OpenDevice(type, path, options);
if (!tpu_context) {
error_reporter_->Report(
absl::Substitute("Error in device opening ($0)!", path));
return kEdgeTpuApiError;
}
resource_map_[path].usage_count = 1;
resource_map_[path].context = tpu_context;
// Using `new` to access a non-public constructor.
*resource =
absl::WrapUnique(new EdgeTpuResource(path, resource_map_[path].context));
return kEdgeTpuApiOk;
}
EdgeTpuApiStatus EdgeTpuResourceManager::GetEdgeTpuResource(
std::unique_ptr<EdgeTpuResource>* resource) {
const auto& tpu_devices =
edgetpu::EdgeTpuManager::GetSingleton()->EnumerateEdgeTpu();
if (tpu_devices.empty()) {
error_reporter_->Report("No Edge TPU device detected!");
return kEdgeTpuApiError;
} else if (tpu_devices.size() == 1) {
return GetEdgeTpuResource(tpu_devices[0].path, resource);
} else {
return GetEdgeTpuResourceMultipleDetected(resource);
}
}
EdgeTpuApiStatus EdgeTpuResourceManager::GetEdgeTpuResource(
const std::string& path, std::unique_ptr<EdgeTpuResource>* resource) {
absl::MutexLock lock(&mu_);
// Call to EnumerateEdgeTpu() is relatively expensive (10+ ms), Search
// `resource_map_` first to see if there's cache-hit.
auto it = resource_map_.find(path);
if (it != resource_map_.end()) {
it->second.usage_count++;
// Using `new` to access a non-public constructor.
*resource = absl::WrapUnique(new EdgeTpuResource(path, it->second.context));
return kEdgeTpuApiOk;
}
// No cache-hit, create EdgeTpuResource from scratch.
const auto& tpu_devices =
edgetpu::EdgeTpuManager::GetSingleton()->EnumerateEdgeTpu();
for (const auto& device : tpu_devices) {
if (device.path == path) {
CHECK(resource_map_.find(path) == resource_map_.end());
return CreateEdgeTpuResource(device.type, device.path, resource);
}
}
error_reporter_->Report(
absl::Substitute("Path $0 does not map to an Edge TPU device.", path));
return kEdgeTpuApiError;
}
EdgeTpuApiStatus EdgeTpuResourceManager::GetEdgeTpuResourceMultipleDetected(
std::unique_ptr<EdgeTpuResource>* resource) {
absl::MutexLock lock(&mu_);
const auto& tpu_devices =
edgetpu::EdgeTpuManager::GetSingleton()->EnumerateEdgeTpu();
// Always prefer to use PCIe version of EdgeTpu.
for (const auto& device : tpu_devices) {
if (device.type != edgetpu::DeviceType::kApexPci) continue;
if (resource_map_.find(device.path) == resource_map_.end()) {
return CreateEdgeTpuResource(device.type, device.path, resource);
}
}
// Check USB version of EdgeTpu.
for (const auto& device : tpu_devices) {
if (device.type != edgetpu::DeviceType::kApexUsb) continue;
if (resource_map_.find(device.path) == resource_map_.end()) {
return CreateEdgeTpuResource(device.type, device.path, resource);
}
}
error_reporter_->Report(
"Multiple Edge TPUs detected and all have been mapped to at least one "
"model. If you want to share one Edge TPU with multiple models, specify "
"`device_path` name.");
return kEdgeTpuApiError;
}
EdgeTpuApiStatus EdgeTpuResourceManager::ReclaimEdgeTpuResource(
const std::string& path) {
absl::MutexLock lock(&mu_);
auto it = resource_map_.find(path);
if (it != resource_map_.end()) {
it->second.usage_count--;
if (it->second.usage_count == 0) {
it->second.context.reset();
resource_map_.erase(it);
}
} else {
error_reporter_->Report(
absl::Substitute("Trying to reclaim unassigned device: $0.", path));
return kEdgeTpuApiError;
}
return kEdgeTpuApiOk;
}
std::vector<std::string> EdgeTpuResourceManager::ListEdgeTpuPaths(
const EdgeTpuState& state) {
std::vector<std::string> result;
const auto& edgetpu_devices =
edgetpu::EdgeTpuManager::GetSingleton()->EnumerateEdgeTpu();
switch (state) {
case EdgeTpuState::kNone: {
for (const auto& device : edgetpu_devices) {
result.push_back(device.path);
}
break;
}
case EdgeTpuState::kAssigned:
case EdgeTpuState::kUnassigned: {
// Return true when
// *) `state` is `kAssigned` and is recorded in `resource_map_`;
// *) `state` is `kUnassigned` and is NOT recorded in `resource_map_`;
auto should_return = [this, &state](const std::string& path) -> bool {
absl::ReaderMutexLock lock(&mu_);
const bool assigned = (state == EdgeTpuState::kAssigned);
const bool recorded = (resource_map_.find(path) != resource_map_.end());
return (assigned && recorded) || ((!assigned) && (!recorded));
};
for (const auto& device : edgetpu_devices) {
if (should_return(device.path)) {
result.push_back(device.path);
}
}
break;
}
}
return result;
}
} // namespace coral
| 2,216 |
303 |
{"id":9589,"line-1":"Sanlúcar la Mayor","line-2":"Spain","attribution":"©2016 DigitalGlobe, IGP/DGRF, Instituto de Cartografía de Andalucía","url":"https://www.google.com/maps/@37.40504,-6.256647,17z/data=!3m1!1e3"}
| 89 |
311 |
/**
* Copyright 2019 The JoyQueue Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.joyqueue.domain;
import java.io.Serializable;
import java.util.Objects;
/**
* @author wylixiaobin
* Date: 2018/8/20
*/
public class Replica implements Serializable {
private String id;
/**
* 主题
*/
protected TopicName topic;
/**
* partition 分组
*/
protected int group;
/**
* Broker ID
*/
protected int brokerId;
public Replica() {
}
public Replica(String id, TopicName topic, int group, int brokerId) {
this.id = id;
this.topic = topic;
this.group = group;
this.brokerId = brokerId;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public TopicName getTopic() {
return topic;
}
public void setTopic(TopicName topic) {
this.topic = topic;
}
public int getGroup() {
return group;
}
public void setGroup(int group) {
this.group = group;
}
public int getBrokerId() {
return brokerId;
}
public void setBrokerId(int brokerId) {
this.brokerId = brokerId;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || !(o instanceof Replica)) return false;
Replica replica = (Replica) o;
return group == replica.group &&
brokerId == replica.brokerId &&
Objects.equals(topic, replica.topic);
}
@Override
public int hashCode() {
return Objects.hash(id, topic, group, brokerId);
}
@Override
public String toString() {
return "Replica{" +
"id='" + id + '\'' +
", topic=" + topic +
", group=" + group +
", brokerId=" + brokerId +
'}';
}
}
| 1,004 |
900 |
<filename>tests/test_reinstall_dotfiles.py
import os
import sys
from .testing_utility_functions import FAKE_HOME_DIR, setup_dirs_and_env_vars_and_create_config, clean_up_dirs_and_env_vars
sys.path.insert(0, "../shallow_backup")
from shallow_backup.reinstall import reinstall_dots_sb
TEST_TEXT_CONTENT = 'THIS IS TEST CONTENT FOR THE DOTFILES'
DOTFILES_PATH = os.path.join(FAKE_HOME_DIR, "dotfiles/")
class TestReinstallDotfiles:
"""
Test the functionality of reinstalling dotfiles
"""
@staticmethod
def setup_method():
def create_nested_dir(parent, name):
new_dir = os.path.join(parent, name)
print(f"Creating {new_dir}")
if not os.path.isdir(new_dir):
os.makedirs(new_dir)
return new_dir
def create_file(parent, name):
file = os.path.join(parent, name)
print(f"Creating {file}")
with open(file, "w+") as f:
f.write(TEST_TEXT_CONTENT)
def create_git_dir(parent):
git_dir = create_nested_dir(parent, ".git/")
git_objects = create_nested_dir(git_dir, "objects/")
create_file(git_dir, "config")
create_file(git_objects, "obj1")
return git_dir
setup_dirs_and_env_vars_and_create_config()
# Dotfiles / dirs to NOT reinstall
create_git_dir(DOTFILES_PATH) # Should NOT reinstall DOTFILES_PATH/.git
img_dir_should_not_reinstall = create_nested_dir(DOTFILES_PATH, "img")
create_file(img_dir_should_not_reinstall, "test.png")
create_file(DOTFILES_PATH, "README.md")
create_file(DOTFILES_PATH, ".gitignore")
# Dotfiles / dirs to reinstall
testfolder = create_nested_dir(DOTFILES_PATH, ".config/tmux/")
testfolder2 = create_nested_dir(testfolder, "testfolder2/")
create_file(testfolder2, "test.sh")
create_git_dir(testfolder2)
git_config = create_nested_dir(DOTFILES_PATH, ".config/git")
create_file(git_config, "test")
create_file(testfolder2, ".gitignore")
create_file(DOTFILES_PATH, ".zshenv")
@staticmethod
def teardown_method():
clean_up_dirs_and_env_vars()
def test_reinstall_dotfiles(self):
"""
Test reinstalling dotfiles to fake home dir
"""
reinstall_dots_sb(dots_path=DOTFILES_PATH, home_path=FAKE_HOME_DIR, dry_run=False)
assert os.path.isfile(os.path.join(FAKE_HOME_DIR, '.zshenv'))
testfolder2 = os.path.join(os.path.join(FAKE_HOME_DIR, '.config/tmux/'), 'testfolder2')
assert os.path.isdir(testfolder2)
assert os.path.isfile(os.path.join(testfolder2, 'test.sh'))
assert os.path.isdir(os.path.join(FAKE_HOME_DIR, '.config/git/'))
# Do reinstall other git files
assert os.path.isdir(os.path.join(testfolder2, ".git"))
assert os.path.isfile(os.path.join(testfolder2, ".gitignore"))
# Don't reinstall root-level git files
assert not os.path.isdir(os.path.join(FAKE_HOME_DIR, ".git"))
assert not os.path.isfile(os.path.join(FAKE_HOME_DIR, ".gitignore"))
# Don't reinstall img or README.md
assert not os.path.isdir(os.path.join(FAKE_HOME_DIR, "img"))
assert not os.path.isfile(os.path.join(FAKE_HOME_DIR, "README.md"))
| 1,543 |
1,373 |
<reponame>sgrj/stream-lib
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.clearspring.analytics.stream.quantile;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import com.google.common.collect.Lists;
import org.apache.mahout.common.RandomUtils;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
public class GroupTreeTest {
@Test
public void testSimpleAdds() {
GroupTree x = new GroupTree();
assertNull(x.floor(new TDigest.Group(34)));
assertNull(x.ceiling(new TDigest.Group(34)));
assertEquals(0, x.size());
assertEquals(0, x.sum());
x.add(new TDigest.Group(1));
TDigest.Group group = new TDigest.Group(2);
group.add(3, 1);
group.add(4, 1);
x.add(group);
assertEquals(2, x.size());
assertEquals(4, x.sum());
}
@Test
public void testBalancing() {
GroupTree x = new GroupTree();
for (int i = 0; i < 101; i++) {
x.add(new TDigest.Group(i));
}
assertEquals(101, x.sum());
assertEquals(101, x.size());
x.checkBalance();
}
@Test
public void testIterators() {
GroupTree x = new GroupTree();
for (int i = 0; i < 101; i++) {
x.add(new TDigest.Group(i / 2));
}
assertEquals(0, x.first().mean(), 0);
assertEquals(50, x.last().mean(), 0);
Iterator<TDigest.Group> ix = x.iterator();
for (int i = 0; i < 101; i++) {
assertTrue(ix.hasNext());
TDigest.Group z = ix.next();
assertEquals(i / 2, z.mean(), 0);
}
assertFalse(ix.hasNext());
// 34 is special since it is the smallest element of the right hand sub-tree
Iterable<TDigest.Group> z = x.tailSet(new TDigest.Group(34, 0));
ix = z.iterator();
for (int i = 68; i < 101; i++) {
assertTrue(ix.hasNext());
TDigest.Group v = ix.next();
assertEquals(i / 2, v.mean(), 0);
}
assertFalse(ix.hasNext());
ix = z.iterator();
for (int i = 68; i < 101; i++) {
TDigest.Group v = ix.next();
assertEquals(i / 2, v.mean(), 0);
}
z = x.tailSet(new TDigest.Group(33, 0));
ix = z.iterator();
for (int i = 66; i < 101; i++) {
assertTrue(ix.hasNext());
TDigest.Group v = ix.next();
assertEquals(i / 2, v.mean(), 0);
}
assertFalse(ix.hasNext());
z = x.tailSet(x.ceiling(new TDigest.Group(34, 0)));
ix = z.iterator();
for (int i = 68; i < 101; i++) {
assertTrue(ix.hasNext());
TDigest.Group v = ix.next();
assertEquals(i / 2, v.mean(), 0);
}
assertFalse(ix.hasNext());
z = x.tailSet(x.floor(new TDigest.Group(34, 0)));
ix = z.iterator();
for (int i = 67; i < 101; i++) {
assertTrue(ix.hasNext());
TDigest.Group v = ix.next();
assertEquals(i / 2, v.mean(), 0);
}
assertFalse(ix.hasNext());
}
@Test
public void testFloor() {
// mostly tested in other tests
GroupTree x = new GroupTree();
for (int i = 0; i < 101; i++) {
x.add(new TDigest.Group(i / 2));
}
assertNull(x.floor(new TDigest.Group(-30)));
}
@Test
public void testRemoveAndSums() {
GroupTree x = new GroupTree();
for (int i = 0; i < 101; i++) {
x.add(new TDigest.Group(i / 2));
}
TDigest.Group g = x.ceiling(new TDigest.Group(2, 0));
x.remove(g);
g.add(3, 1);
x.add(g);
assertEquals(0, x.headCount(new TDigest.Group(-1)));
assertEquals(0, x.headSum(new TDigest.Group(-1)));
assertEquals(0, x.headCount(new TDigest.Group(0, 0)));
assertEquals(0, x.headSum(new TDigest.Group(0, 0)));
assertEquals(0, x.headCount(x.ceiling(new TDigest.Group(0, 0))));
assertEquals(0, x.headSum(x.ceiling(new TDigest.Group(0, 0))));
assertEquals(2, x.headCount(new TDigest.Group(1, 0)));
assertEquals(2, x.headSum(new TDigest.Group(1, 0)));
g = x.tailSet(new TDigest.Group(2.1)).iterator().next();
assertEquals(2.5, g.mean(), 1e-9);
int i = 0;
for (TDigest.Group gx : x) {
if (i > 10) {
break;
}
System.out.printf("%d:%.1f(%d)\t", i++, gx.mean(), gx.count());
}
assertEquals(5, x.headCount(new TDigest.Group(2.1, 0)));
assertEquals(5, x.headSum(new TDigest.Group(2.1, 0)));
assertEquals(6, x.headCount(new TDigest.Group(2.7, 0)));
assertEquals(7, x.headSum(new TDigest.Group(2.7, 0)));
assertEquals(101, x.headCount(new TDigest.Group(200)));
assertEquals(102, x.headSum(new TDigest.Group(200)));
}
@Before
public void setUp() {
RandomUtils.useTestSeed();
}
@Test
public void testRandomRebalance() {
Random gen = RandomUtils.getRandom();
GroupTree x = new GroupTree();
List<Double> y = Lists.newArrayList();
for (int i = 0; i < 1000; i++) {
double v = gen.nextDouble();
x.add(new TDigest.Group(v));
y.add(v);
x.checkBalance();
}
Collections.sort(y);
Iterator<Double> i = y.iterator();
for (TDigest.Group group : x) {
assertEquals(i.next(), group.mean(), 0.0);
}
for (int j = 0; j < 100; j++) {
double v = y.get(gen.nextInt(y.size()));
y.remove(v);
x.remove(x.floor(new TDigest.Group(v)));
}
Collections.sort(y);
i = y.iterator();
for (TDigest.Group group : x) {
assertEquals(i.next(), group.mean(), 0.0);
}
for (int j = 0; j < y.size(); j++) {
double v = y.get(j);
y.set(j, v + 10);
TDigest.Group g = x.floor(new TDigest.Group(v));
x.remove(g);
x.checkBalance();
g.add(g.mean() + 20, 1);
x.add(g);
x.checkBalance();
}
i = y.iterator();
for (TDigest.Group group : x) {
assertEquals(i.next(), group.mean(), 0.0);
}
}
}
| 3,551 |
1,014 |
<filename>nn-core/src/main/java/com/github/neuralnetworks/training/events/LinearLearnRateDecrListener.java
package com.github.neuralnetworks.training.events;
import static org.slf4j.LoggerFactory.getLogger;
import org.slf4j.Logger;
import com.github.neuralnetworks.architecture.WeightsConnections;
import com.github.neuralnetworks.events.TrainingEvent;
import com.github.neuralnetworks.events.TrainingEventListener;
import com.github.neuralnetworks.training.Hyperparameters;
import com.github.neuralnetworks.training.Trainer;
/**
* @author tmey
*/
public class LinearLearnRateDecrListener implements TrainingEventListener
{
private static final long serialVersionUID = 3701545154187049754L;
private static final Logger logger = getLogger(LinearLearnRateDecrListener.class);
private int changeInterval = 1;
private float reductionFactor = 10;
@Override
public void handleEvent(TrainingEvent event)
{
if (event instanceof EpochFinishedEvent)
{
int epoch = ((EpochFinishedEvent) event).getEpoch();
if (epoch % 8 == 0)
{
logger.info("Change hyperparameters");
Trainer<?> t = (Trainer<?>) event.getSource();
Hyperparameters hp = t.getHyperparameters();
t.getNeuralNetwork().getConnections().stream().filter(c -> c instanceof WeightsConnections && hp.getLearningRate(c) > 0.00001f)
.forEach(c -> {
hp.setLearningRate(c, hp.getLearningRate(c) / reductionFactor);
});
hp.setDefaultLearningRate(hp.getDefaultLearningRate() / reductionFactor);
}
}
}
public int getChangeInterval()
{
return changeInterval;
}
public float getReductionFactor()
{
return reductionFactor;
}
public void setChangeInterval(int changeInterval)
{
this.changeInterval = changeInterval;
}
public void setReductionFactor(float reductionFactor)
{
this.reductionFactor = reductionFactor;
}
}
| 627 |
470 |
<filename>HotPatcher/Source/HotPatcherRuntime/Public/HotPatcherLog.h
#pragma once
// engine header
#include "CoreMinimal.h"
#include "Logging/LogMacros.h"
HOTPATCHERRUNTIME_API DECLARE_LOG_CATEGORY_EXTERN(LogHotPatcher, Log, All);
| 94 |
2,023 |
from threading import Thread
from time import sleep
from PythonCard import model
import urllib
import re
def get_quote(symbol):
global quote
base_url = 'http://finance.google.com/finance?q='
content = urllib.urlopen(base_url + symbol).read()
m = re.search('class="pr".*?>(.*?)<', content)
if m:
quote = m.group(1)
else:
quote = 'N/A'
return quote
def get_change(symbol):
global change
base_url = 'http://finance.google.com/finance?q='
content = urllib.urlopen(base_url + symbol).read()
m = re.search('class="chg".*?>(.*?)<', content)
if m:
change = m.group(1)
else:
change = 'N/A'
return change
def get_open(symbol):
global opens
base_url = 'http://finance.google.com/finance?q='
content = urllib.urlopen(base_url + symbol).read()
m = re.search('".*?op".*?>(.*?)<', content)
if m:
opens = m.group(1)
else:
opens = 'N/A'
return opens
def get_high(symbol):
global high
base_url = 'http://finance.google.com/finance?q='
content = urllib.urlopen(base_url + symbol).read()
m = re.search('".*?hi".*?>(.*?)<', content)
if m:
high = m.group(1)
else:
high = 'N/A'
return high
def get_high52(symbol):
global high52
base_url = 'http://finance.google.com/finance?q='
content = urllib.urlopen(base_url + symbol).read()
m = re.search('".*?hi52".*?>(.*?)<', content)
if m:
high52 = m.group(1)
else:
high52 = 'N/A'
return high52
def get_low(symbol):
global low
base_url = 'http://finance.google.com/finance?q='
content = urllib.urlopen(base_url + symbol).read()
m = re.search('".*?lo".*?>(.*?)<', content)
if m:
low = m.group(1)
else:
low = 'N/A'
return low
def get_vol(symbol):
global vol
base_url = 'http://finance.google.com/finance?q='
content = urllib.urlopen(base_url + symbol).read()
m = re.search('".*?vo".*?>(.*?)<', content)
if m:
vol = m.group(1)
else:
vol = 'N/A'
return vol
def get_mc(symbol):
global mc
base_url = 'http://finance.google.com/finance?q='
content = urllib.urlopen(base_url + symbol).read()
m = re.search('".*?mc".*?>(.*?)<', content)
if m:
mc = m.group(1)
else:
mc = 'N/A'
return mc
def get_lo52(symbol):
global lo52
base_url = 'http://finance.google.com/finance?q='
content = urllib.urlopen(base_url + symbol).read()
m = re.search('".*?lo52".*?>(.*?)<', content)
if m:
lo52 = m.group(1)
else:
lo52 = 'N/A'
return lo52
def get_pe(symbol):
global pe
base_url = 'http://finance.google.com/finance?q='
content = urllib.urlopen(base_url + symbol).read()
m = re.search('".*?lo52".*?>(.*?)<', content)
if m:
pe = m.group(1)
else:
pe = 'N/A'
return pe
def get_beta(symbol):
global beta
base_url = 'http://finance.google.com/finance?q='
content = urllib.urlopen(base_url + symbol).read()
m = re.search('".*?beta".*?>(.*?)<', content)
if m:
beta = m.group(1)
else:
beta = 'N/A'
return beta
def get_div(symbol):
global div
base_url = 'http://finance.google.com/finance?q='
content = urllib.urlopen(base_url + symbol).read()
m = re.search('".*?div".*?>(.*?)<', content)
if m:
div = m.group(1)
else:
div = 'N/A'
return div
def get_yield(symbol):
global yield1
base_url = 'http://finance.google.com/finance?q='
content = urllib.urlopen(base_url + symbol).read()
m = re.search('".*?yield".*?>(.*?)<', content)
if m:
yield1 = m.group(1)
else:
yield1 = N/A
return yield1
def get_shares(symbol):
global shares
base_url = 'http://finance.google.com/finance?q='
content = urllib.urlopen(base_url + symbol).read()
m = re.search('".*?shares".*?>(.*?)<', content)
if m:
shares = m.group(1)
else:
shares = N/A
return shares
def get_own(symbol):
global own
base_url = 'http://finance.google.com/finance?q='
content = urllib.urlopen(base_url + symbol).read()
m = re.search('".*?own".*?>(.*?)<', content)
if m:
own = m.group(1)
else:
own = N/A
return own
class stock(model.Background):
def on_getQuote_mouseClick(self, event):
global symbol
symbol = self.components.quotese.text
class Repeater(Thread):
def __init__(self,interval,fun,*args,**kw):
Thread.__init__(self)
self.interval=interval
self.fun=fun
self.args=args
self.kw=kw
self.keep_going=True
def run(self):
while(self.keep_going):
sleep(self.interval)
self.fun(*self.args,**self.kw)
def Refresh(*a):
get_quote(symbol)
get_change(symbol)
self.components.current.text = quote
self.components.change.text = change
r=Repeater(1.0, Refresh)
r.start()
def on_stockinfo_mouseClick(self, event):
global symbol
symbol = self.components.quotese.text
get_open(symbol)
get_high(symbol)
get_high52(symbol)
get_low(symbol)
get_vol(symbol)
get_mc(symbol)
get_lo52(symbol)
get_pe(symbol)
get_beta(symbol)
get_div(symbol)
get_yield(symbol)
get_shares(symbol)
get_own(symbol)
self.components.inst.text = own
self.components.shares.text = shares
self.components.yield1.text = yield1
self.components.div.text = div
self.components.beta.text = beta
self.components.pe.text = pe
self.components.lo52.text = lo52
self.components.mkt.text = mc
self.components.vol.text = vol
self.components.opens.text = opens
self.components.high.text = high
self.components.hi52.text = high52
self.components.low.text = low
def on_save_mouseClick(self, event):
stock1 = open('stock1.txt', 'w')
stock1.write(self.components.stock1.text)
stock1.close()
stock2 = open('stock2.txt', 'w')
stock2.write(self.components.stock2.text)
stock2.close()
stock3 = open('stock3.txt', 'w')
stock3.write(self.components.stock3.text)
stock3.close()
stock4 = open('stock4.txt', 'w')
stock4.write(self.components.stock4.text)
stock4.close()
def on_load_mouseClick(self, event):
load1 = open('stock1.txt' , 'r').read()
self.components.stock1.text = load1
load2 = open('stock2.txt' , 'r').read()
self.components.stock2.text = load2
load3 = open('stock3.txt' , 'r').read()
self.components.stock3.text = load3
load4 = open('stock4.txt' , 'r').read()
self.components.stock4.text = load4
def on_update_mouseClick(self, event):
symbol = self.components.stock1.text
get_quote(symbol)
self.components.change1.text = quote
symbol = self.components.stock2.text
get_quote(symbol)
self.components.change2.text = quote
symbol = self.components.stock3.text
get_quote(symbol)
self.components.change3.text = quote
symbol = self.components.stock4.text
get_quote(symbol)
self.components.change4.text = quote
def on_clear_mouseClick(self, event):
self.components.stock1.text = ""
self.components.stock2.text = ""
self.components.stock3.text = ""
self.components.stock4.text = ""
self.components.change1.text = ""
self.components.change2.text = ""
self.components.change3.text = ""
self.components.change4.text = ""
if __name__ == '__main__':
app = model.Application(stock)
app.MainLoop()
_______________________________________________________________________________
save following as stock.rsrc.py
{'application':{'type':'Application',
'name':'Template',
'backgrounds': [
{'type':'Background',
'name':'bgTemplate',
'title':'Standard Template with File->Exit menu',
'size':(711, 634),
'style':['resizeable'],
'menubar': {'type':'MenuBar',
'menus': [
{'type':'Menu',
'name':'menuFile',
'label':'&File',
'items': [
{'type':'MenuItem',
'name':'save',
'label':u'Save',
},
{'type':'MenuItem',
'name':'menuFileExit',
'label':'E&xit',
'command':'exit',
},
]
},
]
},
'components': [
{'type':'Button',
'name':'clear',
'position':(333, 555),
'label':u'Clear',
},
{'type':'Button',
'name':'save',
'position':(523, 444),
'size':(117, -1),
'label':u'Save',
},
{'type':'StaticText',
'name':'statictext10',
'position':(40, 510),
'font':{'faceName': u'Tahoma', 'family': 'sansSerif', 'size': 12},
'foregroundColor':(0, 0, 160, 255),
'text':u'Update to show price',
},
{'type':'Button',
'name':'load',
'position':(523, 420),
'size':(117, -1),
'label':u'Load',
},
{'type':'StaticText',
'name':'StaticText5',
'position':(26, 488),
'font':{'faceName': u'Tahoma', 'family': 'sansSerif', 'size': 12},
'foregroundColor':(0, 0, 160, 255),
'text':u'Or load to load previous',
},
{'type':'Button',
'name':'update',
'position':(522, 470),
'size':(120, 80),
'font':{'faceName': u'Tahoma', 'family': 'sansSerif', 'size': 11},
'label':u'Update',
},
{'type':'StaticText',
'name':'StaticText4',
'position':(31, 465),
'font':{'faceName': u'Tahoma', 'family': 'sansSerif', 'size': 12},
'foregroundColor':(0, 0, 160, 255),
'text':u'Then click save to save',
},
{'type':'StaticText',
'name':'StaticText3',
'position':(10, 445),
'font':{'faceName': u'Tahoma', 'family': 'sansSerif', 'size': 12},
'foregroundColor':(0, 0, 160, 255),
'text':u'Enter name of stocks to monitor',
},
{'type':'StaticBox',
'name':'StaticBox1',
'position':(343, 109),
'size':(349, 242),
},
{'type':'StaticLine',
'name':'StaticLine1',
'position':(2, 400),
'size':(697, -1),
'layout':'horizontal',
},
{'type':'StaticText',
'name':'StaticText2',
'position':(395, 414),
'text':u'Current Price',
},
{'type':'StaticText',
'name':'StaticText1',
'position':(268, 414),
'text':u'Name Of Stock',
},
{'type':'TextField',
'name':'change4',
'position':(378, 530),
'editable':False,
},
{'type':'TextField',
'name':'stock4',
'position':(258, 530),
},
{'type':'TextField',
'name':'change3',
'position':(378, 500),
'editable':False,
},
{'type':'TextField',
'name':'stock3',
'position':(258, 500),
},
{'type':'TextField',
'name':'change2',
'position':(378, 471),
'editable':False,
},
{'type':'TextField',
'name':'stock2',
'position':(258, 470),
},
{'type':'TextField',
'name':'change1',
'position':(378, 440),
'editable':False,
},
{'type':'TextField',
'name':'stock1',
'position':(258, 440),
},
{'type':'Button',
'name':'stockinfo',
'position':(170, 92),
'label':u'Get Info',
},
{'type':'HtmlWindow',
'name':'HtmlWindow1',
'position':(348, 120),
'size':(339, 225),
'backgroundColor':(255, 255, 255, 255),
'text':u'tickers.html',
},
{'type':'StaticText',
'name':'stockCheckversion',
'position':(213, 0),
'font':{'faceName': u'Tahoma', 'family': 'sansSerif', 'size': 36},
'foregroundColor':(255, 128, 0, 255),
'text':u'Stock Check V2.0',
},
{'type':'StaticText',
'name':'Changelbl',
'position':(14, 84),
'foregroundColor':(128, 0, 0, 255),
'text':u'Change',
},
{'type':'TextField',
'name':'change',
'position':(53, 74),
'size':(-1, 21),
'border':'none',
'editable':False,
'font':{'faceName': u'Tahoma', 'family': 'sansSerif', 'size': 10},
'foregroundColor':(128, 0, 0, 255),
},
{'type':'TextField',
'name':'current',
'position':(12, 33),
'size':(194, 33),
'border':'none',
'editable':False,
'font':{'faceName': u'Tahoma', 'family': 'sansSerif', 'size': 24},
'foregroundColor':(0, 128, 0, 255),
},
{'type':'StaticText',
'name':'Currentlbl',
'position':(81, 10),
'font':{'faceName': u'Tahoma', 'family': 'sansSerif', 'size': 18},
'foregroundColor':(0, 128, 0, 255),
'text':u'Current',
},
{'type':'StaticText',
'name':'wkLowlbl',
'position':(8, 364),
'text':u'52Wk Low',
},
{'type':'StaticText',
'name':'instOwnlbl',
'position':(183, 325),
'text':u'Inst. Own',
},
{'type':'StaticText',
'name':'Shareslbl',
'position':(186, 284),
'text':u'Shares',
},
{'type':'StaticText',
'name':'PElbl',
'position':(193, 124),
'text':u'P/E',
},
{'type':'StaticText',
'name':'Openlbl',
'position':(12, 124),
'text':u'Open',
},
{'type':'StaticText',
'name':'Highlbl',
'position':(16, 164),
'text':u'High',
},
{'type':'TextField',
'name':'pe',
'position':(260, 120),
'size':(81, -1),
'editable':False,
},
{'type':'TextField',
'name':'opens',
'position':(80, 120),
'size':(81, -1),
'editable':False,
},
{'type':'TextField',
'name':'high',
'position':(80, 160),
'size':(80, -1),
'editable':False,
},
{'type':'TextField',
'name':'inst',
'position':(260, 320),
'size':(81, -1),
'editable':False,
},
{'type':'TextField',
'name':'shares',
'position':(260, 280),
'size':(81, -1),
'editable':False,
},
{'type':'StaticText',
'name':'Yieldlbl',
'position':(191, 244),
'text':u'Yield',
},
{'type':'StaticText',
'name':'Dividendlbl',
'position':(183, 163),
'text':u'Dividend',
},
{'type':'TextField',
'name':'lo52',
'position':(80, 360),
'size':(81, -1),
'editable':False,
},
{'type':'TextField',
'name':'yield1',
'position':(260, 240),
'size':(81, -1),
'editable':False,
},
{'type':'TextField',
'name':'div',
'position':(260, 160),
'size':(81, -1),
'editable':False,
},
{'type':'StaticText',
'name':'Betalbl',
'position':(193, 204),
'text':u'Beta',
},
{'type':'TextField',
'name':'beta',
'position':(260, 200),
'size':(81, -1),
'editable':False,
},
{'type':'StaticText',
'name':'wkHighlbl',
'position':(6, 323),
'text':u'52Wk High',
},
{'type':'TextField',
'name':'hi52',
'position':(80, 320),
'size':(80, -1),
'editable':False,
},
{'type':'StaticText',
'name':'mktCaplbl',
'position':(11, 283),
'size':(-1, 16),
'text':u'Mkt Cap',
},
{'type':'TextField',
'name':'mkt',
'position':(80, 280),
'size':(80, -1),
'editable':False,
},
{'type':'StaticText',
'name':'Vollbl',
'position':(19, 244),
'text':u'Vol',
},
{'type':'StaticText',
'name':'Lowlbl',
'position':(16, 204),
'text':u'Low',
},
{'type':'TextField',
'name':'vol',
'position':(80, 240),
'size':(80, -1),
'editable':False,
},
{'type':'TextField',
'name':'low',
'position':(80, 200),
'size':(80, -1),
'editable':False,
},
{'type':'Button',
'name':'getQuote',
'position':(313, 63),
'label':u'Get Quote',
},
{'type':'TextField',
'name':'quotese',
'position':(209, 64),
},
] # end components
} # end background
] # end backgrounds
} }
| 8,311 |
778 |
<reponame>yunzhi-jake/tuplex
//--------------------------------------------------------------------------------------------------------------------//
// //
// Tuplex: Blazing Fast Python Data Science //
// //
// //
// (c) 2017 - 2021, Tuplex team //
// Created by <NAME> on 1/1/2021 //
// License: Apache 2.0 //
//--------------------------------------------------------------------------------------------------------------------//
#ifndef TUPLEX_MAPOPERATOR_H
#define TUPLEX_MAPOPERATOR_H
#include <UDF.h>
#include "UDFOperator.h"
namespace tuplex {
class MapOperator : public UDFOperator {
private:
std::vector<std::string> _outputColumns;
std::string _name;
public:
LogicalOperator *clone() override;
MapOperator(LogicalOperator *parent,
const UDF& udf,
const std::vector<std::string>& columnNames);
// needs a parent
/*!
* set name of operator. Because map Operator is an umbrella for select/rename, use this here to give it more precise meaning.
*/
void setName(const std::string& name) { _name = name; }
std::string name() override { return _name; }
LogicalOperatorType type() const override { return LogicalOperatorType::MAP; }
bool isActionable() override { return false; }
bool isDataSource() override { return false; }
bool good() const override;
void setDataSet(DataSet* dsptr) override;
std::vector<Row> getSample(const size_t num) const override;
std::vector<std::string> inputColumns() const override { return UDFOperator::columns(); }
std::vector<std::string> columns() const override { return _outputColumns; }
/*!
* assign names to the output columns (order matters here...)
* @param columns
*/
void setOutputColumns(const std::vector<std::string>& columns) {
assert(_outputColumns.empty() || _outputColumns.size() == columns.size());
_outputColumns = columns;
}
/*!
* projection pushdown, update UDF and schema...
* @param rewriteMap
*/
void rewriteParametersInAST(const std::unordered_map<size_t, size_t>& rewriteMap) override;
bool retype(const std::vector<python::Type>& rowTypes) override;
};
}
#endif //TUPLEX_MAPOPERATOR_H
| 1,550 |
1,738 |
from __future__ import print_function, absolute_import, division
import numpy as np
from numba import unittest_support as unittest
from numba import roc
from numba.errors import TypingError
import operator as oper
_WAVESIZE = roc.get_context().agent.wavefront_size
@roc.jit(device=True)
def shuffle_up(val, width):
tid = roc.get_local_id(0)
roc.wavebarrier()
idx = (tid + width) % _WAVESIZE
res = roc.ds_permute(idx, val)
return res
@roc.jit(device=True)
def shuffle_down(val, width):
tid = roc.get_local_id(0)
roc.wavebarrier()
idx = (tid - width) % _WAVESIZE
res = roc.ds_permute(idx, val)
return res
@roc.jit(device=True)
def broadcast(val, from_lane):
tid = roc.get_local_id(0)
roc.wavebarrier()
res = roc.ds_bpermute(from_lane, val)
return res
def gen_kernel(shuffunc):
@roc.jit
def kernel(inp, outp, amount):
tid = roc.get_local_id(0)
val = inp[tid]
outp[tid] = shuffunc(val, amount)
return kernel
class TestDsPermute(unittest.TestCase):
def test_ds_permute(self):
inp = np.arange(_WAVESIZE).astype(np.int32)
outp = np.zeros_like(inp)
for shuffler, op in [(shuffle_down, oper.neg), (shuffle_up, oper.pos)]:
kernel = gen_kernel(shuffler)
for shuf in range(-_WAVESIZE, _WAVESIZE):
kernel[1, _WAVESIZE](inp, outp, shuf)
np.testing.assert_allclose(outp, np.roll(inp, op(shuf)))
def test_ds_permute_random_floats(self):
inp = np.linspace(0, 1, _WAVESIZE).astype(np.float32)
outp = np.zeros_like(inp)
for shuffler, op in [(shuffle_down, oper.neg), (shuffle_up, oper.pos)]:
kernel = gen_kernel(shuffler)
for shuf in range(-_WAVESIZE, _WAVESIZE):
kernel[1, _WAVESIZE](inp, outp, shuf)
np.testing.assert_allclose(outp, np.roll(inp, op(shuf)))
def test_ds_permute_type_safety(self):
""" Checks that float64's are not being downcast to float32"""
kernel = gen_kernel(shuffle_down)
inp = np.linspace(0, 1, _WAVESIZE).astype(np.float64)
outp = np.zeros_like(inp)
with self.assertRaises(TypingError) as e:
kernel[1, _WAVESIZE](inp, outp, 1)
errmsg = e.exception.msg
self.assertIn('Invalid use of Function', errmsg)
self.assertIn('with argument(s) of type(s): (float64, int64)', errmsg)
def test_ds_bpermute(self):
@roc.jit
def kernel(inp, outp, lane):
tid = roc.get_local_id(0)
val = inp[tid]
outp[tid] = broadcast(val, lane)
inp = np.arange(_WAVESIZE).astype(np.int32)
outp = np.zeros_like(inp)
for lane in range(0, _WAVESIZE):
kernel[1, _WAVESIZE](inp, outp, lane)
np.testing.assert_allclose(outp, lane)
def test_ds_bpermute_random_floats(self):
@roc.jit
def kernel(inp, outp, lane):
tid = roc.get_local_id(0)
val = inp[tid]
outp[tid] = broadcast(val, lane)
inp = np.linspace(0, 1, _WAVESIZE).astype(np.float32)
outp = np.zeros_like(inp)
for lane in range(0, _WAVESIZE):
kernel[1, _WAVESIZE](inp, outp, lane)
np.testing.assert_allclose(outp, inp[lane])
if __name__ == '__main__':
unittest.main()
| 1,663 |
575 |
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/file_system_access/file_system_access_handle_base.h"
#include "base/files/scoped_temp_dir.h"
#include "base/test/bind.h"
#include "base/test/gmock_callback_support.h"
#include "base/test/task_environment.h"
#include "content/browser/file_system_access/mock_file_system_access_permission_grant.h"
#include "content/public/test/browser_task_environment.h"
#include "storage/browser/blob/blob_storage_context.h"
#include "storage/browser/test/test_file_system_context.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace content {
using base::test::RunOnceCallback;
using blink::mojom::PermissionStatus;
using storage::FileSystemURL;
using UserActivationState =
FileSystemAccessPermissionGrant::UserActivationState;
class TestFileSystemAccessHandle : public FileSystemAccessHandleBase {
public:
TestFileSystemAccessHandle(FileSystemAccessManagerImpl* manager,
const BindingContext& context,
const storage::FileSystemURL& url,
const SharedHandleState& handle_state)
: FileSystemAccessHandleBase(manager, context, url, handle_state) {}
private:
base::WeakPtr<FileSystemAccessHandleBase> AsWeakPtr() override {
return weak_factory_.GetWeakPtr();
}
base::WeakPtrFactory<TestFileSystemAccessHandle> weak_factory_{this};
};
class FileSystemAccessHandleBaseTest : public testing::Test {
public:
FileSystemAccessHandleBaseTest()
: task_environment_(base::test::TaskEnvironment::MainThreadType::IO) {}
void SetUp() override {
ASSERT_TRUE(dir_.CreateUniqueTempDir());
file_system_context_ = storage::CreateFileSystemContextForTesting(
/*quota_manager_proxy=*/nullptr, dir_.GetPath());
chrome_blob_context_ = base::MakeRefCounted<ChromeBlobStorageContext>();
chrome_blob_context_->InitializeOnIOThread(base::FilePath(),
base::FilePath(), nullptr);
manager_ = base::MakeRefCounted<FileSystemAccessManagerImpl>(
file_system_context_, chrome_blob_context_,
/*permission_context=*/nullptr,
/*off_the_record=*/false);
}
protected:
const GURL kTestURL = GURL("https://example.com/test");
const url::Origin kTestOrigin = url::Origin::Create(kTestURL);
BrowserTaskEnvironment task_environment_;
base::ScopedTempDir dir_;
scoped_refptr<storage::FileSystemContext> file_system_context_;
scoped_refptr<ChromeBlobStorageContext> chrome_blob_context_;
scoped_refptr<MockFileSystemAccessPermissionGrant> read_grant_ =
base::MakeRefCounted<
testing::StrictMock<MockFileSystemAccessPermissionGrant>>();
scoped_refptr<MockFileSystemAccessPermissionGrant> write_grant_ =
base::MakeRefCounted<
testing::StrictMock<MockFileSystemAccessPermissionGrant>>();
scoped_refptr<FileSystemAccessManagerImpl> manager_;
FileSystemAccessManagerImpl::SharedHandleState handle_state_ = {read_grant_,
write_grant_,
{}};
};
TEST_F(FileSystemAccessHandleBaseTest, GetReadPermissionStatus) {
auto url =
FileSystemURL::CreateForTest(kTestOrigin, storage::kFileSystemTypeTest,
base::FilePath::FromUTF8Unsafe("/test"));
TestFileSystemAccessHandle handle(
manager_.get(),
FileSystemAccessManagerImpl::BindingContext(kTestOrigin, kTestURL,
/*worker_process_id=*/1),
url, handle_state_);
EXPECT_CALL(*read_grant_, GetStatus())
.WillOnce(testing::Return(PermissionStatus::ASK));
EXPECT_EQ(PermissionStatus::ASK, handle.GetReadPermissionStatus());
EXPECT_CALL(*read_grant_, GetStatus())
.WillOnce(testing::Return(PermissionStatus::GRANTED));
EXPECT_EQ(PermissionStatus::GRANTED, handle.GetReadPermissionStatus());
}
TEST_F(FileSystemAccessHandleBaseTest,
GetWritePermissionStatus_ReadStatusNotGranted) {
auto url =
FileSystemURL::CreateForTest(kTestOrigin, storage::kFileSystemTypeTest,
base::FilePath::FromUTF8Unsafe("/test"));
TestFileSystemAccessHandle handle(
manager_.get(),
FileSystemAccessManagerImpl::BindingContext(kTestOrigin, kTestURL,
/*worker_process_id=*/1),
url, handle_state_);
EXPECT_CALL(*read_grant_, GetStatus())
.WillOnce(testing::Return(PermissionStatus::ASK));
EXPECT_EQ(PermissionStatus::ASK, handle.GetWritePermissionStatus());
EXPECT_CALL(*read_grant_, GetStatus())
.WillOnce(testing::Return(PermissionStatus::DENIED));
EXPECT_EQ(PermissionStatus::DENIED, handle.GetWritePermissionStatus());
}
TEST_F(FileSystemAccessHandleBaseTest,
GetWritePermissionStatus_ReadStatusGranted) {
auto url =
FileSystemURL::CreateForTest(kTestOrigin, storage::kFileSystemTypeTest,
base::FilePath::FromUTF8Unsafe("/test"));
TestFileSystemAccessHandle handle(
manager_.get(),
FileSystemAccessManagerImpl::BindingContext(kTestOrigin, kTestURL,
/*worker_process_id=*/1),
url, handle_state_);
EXPECT_CALL(*read_grant_, GetStatus())
.WillOnce(testing::Return(PermissionStatus::GRANTED));
EXPECT_CALL(*write_grant_, GetStatus())
.WillOnce(testing::Return(PermissionStatus::ASK));
EXPECT_EQ(PermissionStatus::ASK, handle.GetWritePermissionStatus());
}
TEST_F(FileSystemAccessHandleBaseTest, RequestWritePermission_AlreadyGranted) {
auto url =
FileSystemURL::CreateForTest(kTestOrigin, storage::kFileSystemTypeTest,
base::FilePath::FromUTF8Unsafe("/test"));
TestFileSystemAccessHandle handle(
manager_.get(),
FileSystemAccessManagerImpl::BindingContext(kTestOrigin, kTestURL,
/*worker_process_id=*/1),
url, handle_state_);
EXPECT_CALL(*read_grant_, GetStatus())
.WillOnce(testing::Return(PermissionStatus::GRANTED));
EXPECT_CALL(*write_grant_, GetStatus())
.WillOnce(testing::Return(PermissionStatus::GRANTED));
base::RunLoop loop;
handle.DoRequestPermission(
/*writable=*/true,
base::BindLambdaForTesting(
[&](blink::mojom::FileSystemAccessErrorPtr error,
PermissionStatus result) {
EXPECT_EQ(blink::mojom::FileSystemAccessStatus::kOk, error->status);
EXPECT_EQ(PermissionStatus::GRANTED, result);
loop.Quit();
}));
loop.Run();
}
TEST_F(FileSystemAccessHandleBaseTest, RequestWritePermission) {
const int kProcessId = 1;
const int kFrameRoutingId = 2;
const GlobalFrameRoutingId kFrameId(kProcessId, kFrameRoutingId);
auto url =
FileSystemURL::CreateForTest(kTestOrigin, storage::kFileSystemTypeTest,
base::FilePath::FromUTF8Unsafe("/test"));
TestFileSystemAccessHandle handle(manager_.get(),
FileSystemAccessManagerImpl::BindingContext(
kTestOrigin, kTestURL, kFrameId),
url, handle_state_);
EXPECT_CALL(*read_grant_, GetStatus())
.WillRepeatedly(testing::Return(PermissionStatus::GRANTED));
{
testing::InSequence sequence;
EXPECT_CALL(*write_grant_, GetStatus())
.WillOnce(testing::Return(PermissionStatus::ASK));
EXPECT_CALL(*write_grant_,
RequestPermission_(kFrameId, UserActivationState::kRequired,
testing::_))
.WillOnce(
RunOnceCallback<2>(FileSystemAccessPermissionGrant::
PermissionRequestOutcome::kUserGranted));
EXPECT_CALL(*write_grant_, GetStatus())
.WillOnce(testing::Return(PermissionStatus::GRANTED));
}
base::RunLoop loop;
handle.DoRequestPermission(
/*writable=*/true,
base::BindLambdaForTesting(
[&](blink::mojom::FileSystemAccessErrorPtr error,
PermissionStatus result) {
EXPECT_EQ(blink::mojom::FileSystemAccessStatus::kOk, error->status);
EXPECT_EQ(PermissionStatus::GRANTED, result);
loop.Quit();
}));
loop.Run();
}
} // namespace content
| 3,591 |
680 |
package org.ff4j.audit;
/*
* #%L
* ff4j-core
* %%
* Copyright (C) 2013 - 2016 FF4J
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.util.TreeSet;
/**
* Proposal of data structure to store a set of events.
*
* @author <NAME> (@clunven)
*/
public class EventSeries extends TreeSet< Event > {
/** Serial */
private static final long serialVersionUID = 7093204704994389688L;
/** Capacity -1 is infinite - Cause OutOfMemory. */
private long capacity = -1;
/**
* Default constructor.
*
* @param capacity
* capacity
*/
public EventSeries() {
this.capacity = 100000;
}
/**
* Compute average iteself.
*
* @return
*/
public double getAverageDuration() {
long totalDuration = 0;
for(Event evt : this) {
totalDuration+= evt.getDuration();
}
return totalDuration / size();
}
/**
* Default constructor.
*
* @param capacity
* capacity
*/
public EventSeries(final long capacity) {
super();
this.capacity = capacity;
}
/** {@inheritDoc} */
@Override
public boolean add(final Event e) {
if (capacity > 0 && size() >= capacity) {
return false;
}
return super.add(e);
}
}
| 724 |
32,544 |
<reponame>DBatOWL/tutorials
package com.baeldung.exceptions.exceptionhandling;
import java.io.IOException;
public class PlayerLoadException extends Exception {
public PlayerLoadException(IOException io) {
super(io);
}
}
| 85 |
1,389 |
"""Loader"""
import numpy as np
import math
from pgl.sample import extract_edges_from_nodes
def random_partition(num_clusters, graph, shuffle=True):
"""random partition"""
batch_size = int(math.ceil(graph.num_nodes / num_clusters))
perm = np.arange(0, graph.num_nodes)
if shuffle:
np.random.shuffle(perm)
batch_no = 0
while batch_no < graph.num_nodes:
batch_nodes = perm[batch_no:batch_no + batch_size]
batch_no += batch_size
eids = extract_edges_from_nodes(graph, batch_nodes)
sub_g = graph.subgraph(nodes=batch_nodes, eid=eids,
with_node_feat=True, with_edge_feat=False)
for key, value in graph.edge_feat.items():
sub_g.edge_feat[key] = graph.edge_feat[key][eids]
yield sub_g
def random_partition_v2(num_clusters, graph, shuffle=True, save_e=[]):
"""random partition v2"""
if shuffle:
cluster_id = np.random.randint(low=0, high=num_clusters, size=graph.num_nodes)
else:
if not save_e:
cluster_id = np.random.randint(low=0, high=num_clusters, size=graph.num_nodes)
save_e.append(cluster_id)
else:
cluster_id = save_e[0]
# assert cluster_id is not None
perm = np.arange(0, graph.num_nodes)
batch_no = 0
while batch_no < num_clusters:
batch_nodes = perm[cluster_id == batch_no]
batch_no += 1
eids = extract_edges_from_nodes(graph, batch_nodes)
sub_g = graph.subgraph(nodes=batch_nodes, eid=eids,
with_node_feat=True, with_edge_feat=False)
for key, value in graph.edge_feat.items():
sub_g.edge_feat[key] = graph.edge_feat[key][eids]
yield sub_g
| 831 |
386 |
<gh_stars>100-1000
/*********************************************************************************
* *
* The MIT License (MIT) *
* *
* Copyright (c) 2015-2021 aoju.org and other contributors. *
* *
* 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 org.aoju.bus.notify.provider.generic;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.SuperBuilder;
import org.aoju.bus.core.lang.Symbol;
import org.aoju.bus.core.toolkit.StringKit;
import org.aoju.bus.notify.magic.Property;
import java.io.File;
/**
* 电子邮件消息
*
* @author <NAME>
* @version 6.3.2
* @since JDK 1.8+
*/
@Getter
@Setter
@SuperBuilder
public class NativeEmailProperty extends Property {
private static final String SMTP_HOST = "mail.smtp.host";
private static final String SMTP_PORT = "mail.smtp.port";
private static final String SMTP_AUTH = "mail.smtp.auth";
private static final String SMTP_TIMEOUT = "mail.smtp.timeout";
private static final String SMTP_CONNECTION_TIMEOUT = "mail.smtp.connectiontimeout";
private static final String SOCKEY_FACTORY = "mail.smtp.socketFactory.class";
private static final String SOCKEY_FACTORY_PORT = "smtp.socketFactory.port";
private static final String SOCKET_FACTORY_FALLBACK = "mail.smtp.socketFactory.fallback";
private static final String MAIL_TLS_ENABLE = "mail.smtp.starttls.enable";
private static final String MAIL_PROTOCOL = "mail.transport.protocol";
private static final String SPLIT_LONG_PARAMS = "mail.mime.splitlongparameters";
private static final String MAIL_DEBUG = "mail.debug";
/**
* SMTP服务器域名
*/
private String host;
/**
* SMTP服务端口
*/
private Integer port;
/**
* 是否需要用户名密码验证
*/
private Boolean auth;
/**
* 用户名
*/
private String user;
/**
* 密码
*/
private String pass;
/**
* 是否打开调试模式,调试模式会显示与邮件服务器通信过程,默认不开启
*/
private boolean debug;
/**
* 编码用于编码邮件正文和发送人、收件人等中文
*/
private java.nio.charset.Charset charset;
/**
* 对于超长参数是否切分为多份,默认为false(国内邮箱附件不支持切分的附件名)
*/
private boolean splitlongparameters;
/**
* 使用 STARTTLS安全连接,STARTTLS是对纯文本通信协议的扩展 它将纯文本连接升级为加密连接(TLS或SSL), 而不是使用一个单独的加密通信端口
*/
private boolean startttlsEnable;
/**
* 使用 SSL安全连接
*/
private Boolean sslEnable;
/**
* 指定实现javax.net.SocketFactory接口的类的名称,这个类将被用于创建SMTP的套接字
*/
private String socketFactoryClass = "javax.net.ssl.SSLSocketFactory";
/**
* 如果设置为true,未能创建一个套接字使用指定的套接字工厂类将导致使用java.net.Socket创建的套接字类, 默认值为true
*/
private boolean socketFactoryFallback;
/**
* 指定的端口连接到在使用指定的套接字工厂 如果没有设置,将使用默认端口
*/
private int socketFactoryPort = 465;
/**
* SMTP超时时长,单位毫秒,缺省值不超时
*/
private long timeout;
/**
* Socket连接超时值,单位毫秒,缺省值不超时
*/
private long connectionTimeout;
/**
* 抄送人列表(carbon copy)
*/
private String ccs;
/**
* 密送人列表(blind carbon copy)
*/
private String bccs;
/**
* 标题
*/
private String title;
/**
* 内容
*/
private String content;
/**
* 附件列表
*/
private File[] attachments;
/**
* 是否使用全局会话,默认为true
*/
private boolean useGlobalSession;
/**
* 如果某些值为null,使用默认值
*
* @return this
*/
public NativeEmailProperty defaultIfEmpty() {
if (StringKit.isBlank(this.host)) {
// 如果SMTP地址为空,默认使用smtp.<发件人邮箱后缀>
this.host = StringKit.format("smtp.{}", StringKit.subSuf(this.sender, this.sender.indexOf(Symbol.C_AT) + 1));
}
if (StringKit.isBlank(user)) {
// 如果用户名为空,默认为发件人邮箱前缀
this.user = StringKit.subPre(this.sender, this.sender.indexOf(Symbol.C_AT));
}
if (null == this.auth) {
// 如果密码非空白,则使用认证模式
this.auth = (false == StringKit.isBlank(this.pass));
}
if (null == this.port) {
// 端口在SSL状态下默认与socketFactoryPort一致,非SSL状态下默认为25
this.port = (null != this.sslEnable && this.sslEnable) ? this.socketFactoryPort : 25;
}
if (null == this.charset) {
// 默认UTF-8编码
this.charset = org.aoju.bus.core.lang.Charset.UTF_8;
}
return this;
}
/**
* 获得SMTP相关信息
*
* @return {@link java.util.Properties}
*/
public java.util.Properties getSmtpProps() {
//全局系统参数
System.setProperty(SPLIT_LONG_PARAMS, String.valueOf(this.splitlongparameters));
final java.util.Properties p = new java.util.Properties();
p.put(MAIL_PROTOCOL, "smtp");
p.put(SMTP_HOST, this.host);
p.put(SMTP_PORT, String.valueOf(this.port));
p.put(SMTP_AUTH, String.valueOf(this.auth));
if (this.timeout > 0) {
p.put(SMTP_TIMEOUT, String.valueOf(this.timeout));
}
if (this.connectionTimeout > 0) {
p.put(SMTP_CONNECTION_TIMEOUT, String.valueOf(this.connectionTimeout));
}
p.put(MAIL_DEBUG, String.valueOf(this.debug));
if (this.startttlsEnable) {
//STARTTLS是对纯文本通信协议的扩展 它将纯文本连接升级为加密连接(TLS或SSL), 而不是使用一个单独的加密通信端口
p.put(MAIL_TLS_ENABLE, String.valueOf(this.startttlsEnable));
if (null == this.sslEnable) {
//为了兼容旧版本,当用户没有此项配置时,按照startttlsEnable开启状态时对待
this.sslEnable = true;
}
}
// SSL
if (null != this.sslEnable && this.sslEnable) {
p.put(SOCKEY_FACTORY, socketFactoryClass);
p.put(SOCKET_FACTORY_FALLBACK, String.valueOf(this.socketFactoryFallback));
p.put(SOCKEY_FACTORY_PORT, String.valueOf(this.socketFactoryPort));
}
return p;
}
}
| 4,431 |
310 |
{
"name": "Organelle",
"description": "An audio device.",
"url": "https://www.critterandguitari.com/pages/organelle"
}
| 47 |
525 |
#! /usr/bin/env python3
# This script is for running peru directly from the repo, mainly for
# development. This isn't what gets installed when you install peru. That would
# be a script generated by setup.py, which calls peru.main.main().
import os
import sys
repo_root = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, repo_root)
import peru.main # noqa: E402
sys.exit(peru.main.main())
| 139 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.