max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
416 | <reponame>Zi0P4tch0/sdks<filename>iPhoneOS14.2.sdk/System/Library/Frameworks/CoreML.framework/Headers/MLMultiArrayShapeConstraintType.h<gh_stars>100-1000
//
// MLMultiArrayShapeConstraintType.h
// CoreML
//
// Copyright © 2018 Apple Inc. All rights reserved.
#import <Foundation/Foundation.h>
API_AVAILABLE(macos(10.14), ios(12.0), watchos(5.0), tvos(12.0))
typedef NS_ENUM(NSInteger, MLMultiArrayShapeConstraintType) {
MLMultiArrayShapeConstraintTypeUnspecified = 1, // An unconstrained shape. Any multi array satisfies this constraint.
MLMultiArrayShapeConstraintTypeEnumerated = 2, // Limited to an enumerated set of shapes
MLMultiArrayShapeConstraintTypeRange = 3, // Allow full specified range per dimension
};
| 256 |
3,212 | <reponame>westdart/nifi
/*
* 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.security.util.crypto;
import org.apache.nifi.security.util.crypto.scrypt.Scrypt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.math.BigInteger;
import java.util.concurrent.TimeUnit;
/**
* Provides an implementation of {@code Scrypt} for secure password hashing.
* <p>
* One <strong>critical</strong> difference is that this implementation uses a
* <strong>static universal</strong> salt unless instructed otherwise, which provides
* strict determinism across nodes in a cluster. The purpose for this is to allow for
* blind equality comparison of sensitive values hashed on different nodes (with
* potentially different {@code nifi.sensitive.props.key} values) during flow inheritance
* (see {@code FingerprintFactory}).
* <p>
* The resulting output is referred to as a <em>hash</em> to be consistent with {@link SecureHasher} terminology,
* but the length parameter is clarified as the <em>derived key length</em> {@code dkLen} in Scrypt terms, not to be
* confused with the internal concept of <em>hash length</em> for the PBKDF2 cryptographic hash function (CHF) primitive (SHA-256).
*/
public class ScryptSecureHasher extends AbstractSecureHasher {
private static final Logger logger = LoggerFactory.getLogger(ScryptSecureHasher.class);
/**
* These values can be calculated automatically using the code {@see ScryptCipherProviderGroovyTest#calculateMinimumParameters} or manually updated by a maintainer
*/
private static final int DEFAULT_N = Double.valueOf(Math.pow(2, 14)).intValue();
private static final int DEFAULT_R = 8;
private static final int DEFAULT_P = 1;
private static final int DEFAULT_DK_LENGTH = 32;
private static final int DEFAULT_SALT_LENGTH = Scrypt.getDefaultSaltLength();
private static final int MIN_P = 1;
private static final int MIN_DK_LENGTH = 1;
private static final int MIN_N = 1;
private static final int MIN_R = 1;
private static final int MAX_R = Double.valueOf(Math.pow(2, 31)).intValue() - 1;
private static final int MIN_SALT_LENGTH = 8;
private static final int MAX_SALT_LENGTH = Double.valueOf(Math.pow(2, 31)).intValue() - 1;
private final int n;
private final int r;
private final int p;
private final int dkLength;
/**
* Instantiates an Scrypt secure hasher using the default cost parameters
* ({@code N = }{@link #DEFAULT_N},
* {@code r = }{@link #DEFAULT_R},
* {@code p = }{@link #DEFAULT_R},
* {@code dkLen = }{@link #DEFAULT_DK_LENGTH}). A static salt is also used.
*/
public ScryptSecureHasher() {
this(DEFAULT_N, DEFAULT_R, DEFAULT_P, DEFAULT_DK_LENGTH, 0);
}
/**
* Instantiates an Scrypt secure hasher using the default cost parameters and specified derived key length
* @param dkLength Derived Key Length
*/
public ScryptSecureHasher(final int dkLength) {
this(DEFAULT_N, DEFAULT_R, DEFAULT_P, dkLength, 0);
}
/**
* Instantiates an Scrypt secure hasher using the provided cost parameters. A static
* {@link #DEFAULT_SALT_LENGTH} byte salt will be generated on every hash request.
*
* @param n number of iterations (power of 2 from {@code 1 to 2^(128 * r / 8)})
* @param r the block size of memory ({@code > 0})
* @param p parallelization factor from ({@code 1 to ((2^32-1) * 32) / (128 * r)})
* @param dkLength the output length in bytes ({@code 1 to (2^32 - 1) * 32})
*/
public ScryptSecureHasher(int n, int r, int p, int dkLength) {
this(n, r, p, dkLength, 0);
}
/**
* Instantiates an Scrypt secure hasher using the provided cost parameters. A unique
* salt of the specified length will be generated on every hash request.
*
* @param n number of iterations (power of 2 from {@code 1 to 2^(128 * r / 8)})
* @param r the block size of memory ({@code > 0})
* @param p parallelization factor from ({@code 1 to ((2^32-1) * 32) / (128 * r)})
* @param dkLength the output length in bytes ({@code 1 to (2^32 - 1) * 32})
* @param saltLength the salt length in bytes {@code >= 8})
*/
public ScryptSecureHasher(int n, int r, int p, int dkLength, int saltLength) {
validateParameters(n, r, p, dkLength, saltLength);
this.n = n;
this.r = r;
this.p = p;
this.dkLength = dkLength;
this.saltLength = saltLength;
}
/**
* Enforces valid Scrypt secure hasher cost parameters are provided.
*
* @param n number of iterations (power of 2 from {@code 1 to 2^(128 * r / 8)})
* @param r the block size of memory ({@code > 0})
* @param p parallelization factor from ({@code 1 to ((2^32-1) * 32) / (128 * r)})
* @param dkLength the output length in bytes ({@code 1 to (2^32 - 1) * 32})
* @param saltLength the salt length in bytes {@code >= 8})
*/
private void validateParameters(Integer n, Integer r, int p, Integer dkLength, Integer saltLength) {
// Check r first because it is not dependent on other parameters
if (!isRValid(r)) {
logger.error("The provided block size r {} ( * 128 bytes) is outside the boundary of 1 to 2^31 - 1.", r);
throw new IllegalArgumentException("Invalid r is not within the memory boundary.");
}
if (!isNValid(n, r)) {
logger.error("The iteration count N {} is outside the boundary of powers of 2 from 1 to 2^(128 * r / 8).", n);
throw new IllegalArgumentException("Invalid N exceeds the iterations boundary.");
}
if (!isPValid(p, r)) {
logger.error("The provided parallelization factor {} is outside the boundary of 1 to ((2^32 - 1) * 32) / (128 * r).", p);
throw new IllegalArgumentException("Invalid p exceeds the parallelism boundary.");
}
if (!isDKLengthValid(dkLength)) {
logger.error("The provided hash length {} is outside the boundary of 1 to (2^32 - 1) * 32.", dkLength);
throw new IllegalArgumentException("Invalid hash length is not within the dkLength boundary.");
}
initializeSalt(saltLength);
}
/**
* Internal method to hash the raw bytes.
*
* @param input the raw bytes to hash (can be length 0)
* @return the generated hash
*/
byte[] hash(byte[] input) {
// Contains only the raw salt
byte[] rawSalt = getSalt();
return hash(input, rawSalt);
}
/**
* Internal method to hash the raw bytes.
*
* @param input the raw bytes to hash (can be length 0)
* @param rawSalt the raw bytes to salt
* @return the generated hash
*/
byte[] hash(byte[] input, byte[] rawSalt) {
logger.debug("Creating {} byte Scrypt hash with salt [{}]", dkLength, org.bouncycastle.util.encoders.Hex.toHexString(rawSalt));
if (!isSaltLengthValid(rawSalt.length)) {
throw new IllegalArgumentException("The salt length (" + rawSalt.length + " bytes) is invalid");
}
final long startNanos = System.nanoTime();
byte[] hash = Scrypt.scrypt(input, rawSalt, n, r, p, dkLength * 8);
final long generateNanos = System.nanoTime();
final long totalDurationMillis = TimeUnit.NANOSECONDS.toMillis(generateNanos - startNanos);
logger.debug("Generated Scrypt hash in {} ms", totalDurationMillis);
return hash;
}
/**
* Returns true if the provided iteration count N is within boundaries. The lower bound >= 1 and the
* upper bound <= 2^(128 * r / 8).
*
* @param n number of iterations
* @param r the blocksize parameter
* @return true if iterations is within boundaries
*/
protected static boolean isNValid(Integer n, int r) {
if (n < DEFAULT_N) {
logger.warn("The provided iteration count N {} is below the recommended minimum {}.", n, DEFAULT_N);
}
return n >= MIN_N && n <= Double.valueOf(Math.pow(2, (128 * r / 8.0))).intValue();
}
/**
* Returns true if the provided block size in bytes is within boundaries. The lower bound >= 1 and the
* upper bound <= 2^32 - 1.
*
* @param r the integer number * 128 B used
* @return true if r is within boundaries
*/
protected static boolean isRValid(int r) {
if (r < DEFAULT_R) {
logger.warn("The provided r size {} * 128 B is below the recommended minimum {}.", r, DEFAULT_R);
}
return r >= MIN_R && r <= MAX_R;
}
/**
* Returns true if the provided parallelization factor is within boundaries. The lower bound >= 1 and the
* upper bound <= ((2^32 - 1) * 32) / (128 * r).
*
* @param p degree of parallelism
* @param r the blocksize parameter
* @return true if parallelism is within boundaries
*/
protected static boolean isPValid(int p, int r) {
if (p < DEFAULT_P) {
logger.warn("The provided parallelization factor {} is below the recommended minimum {}.", p, DEFAULT_P);
}
long dividend = Double.valueOf((Math.pow(2, 32) - 1) * 32).longValue();
int divisor = 128 * r;
BigInteger MAX_P = new BigInteger(String.valueOf(dividend)).divide(new BigInteger(String.valueOf(divisor)));
logger.debug("Calculated maximum p value as (2^32 - 1) * 32 [{}] / (128 * r) [{}] = {}", dividend, divisor, MAX_P.intValue());
return p >= MIN_P && p <= MAX_P.intValue();
}
/**
* Returns whether the provided hash (derived key) length is within boundaries. The lower bound >= 1 and the
* upper bound <= (2^32 - 1) * 32.
*
* @param dkLength the output length in bytes
* @return true if dkLength is within boundaries
*/
protected static boolean isDKLengthValid(Integer dkLength) {
return dkLength >= MIN_DK_LENGTH && dkLength <= UPPER_BOUNDARY;
}
/**
* Returns the algorithm-specific default salt length in bytes.
*
* @return the Scrypt default salt length
*/
@Override
public int getDefaultSaltLength() {
return DEFAULT_SALT_LENGTH;
}
@Override
public int getMinSaltLength() {
return MIN_SALT_LENGTH;
}
@Override
public int getMaxSaltLength() {
return MAX_SALT_LENGTH;
}
@Override
String getAlgorithmName() {
return "Scrypt";
}
@Override
boolean acceptsEmptyInput() {
return false;
}
}
| 4,156 |
6,224 | /*
* Copyright (c) 2020 <NAME>
*
* SPDX-License-Identifier: Apache-2.0
*/
/**
* This header defines replacements for inline
* ARM Cortex-M CMSIS intrinsics.
*/
#ifndef BOARDS_POSIX_NRF52_BSIM_CMSIS_H
#define BOARDS_POSIX_NRF52_BSIM_CMSIS_H
#ifdef __cplusplus
extern "C" {
#endif
/* Implement the following ARM intrinsics as no-op:
* - ARM Data Synchronization Barrier
* - ARM Data Memory Synchronization Barrier
* - ARM Instruction Synchronization Barrier
* - ARM No Operation
*/
#ifndef __DMB
#define __DMB()
#endif
#ifndef __DSB
#define __DSB()
#endif
#ifndef __ISB
#define __ISB()
#endif
#ifndef __NOP
#define __NOP()
#endif
void __enable_irq(void);
void __disable_irq(void);
uint32_t __get_PRIMASK(void);
void __set_PRIMASK(uint32_t primask);
#ifdef __cplusplus
}
#endif
#endif /* BOARDS_POSIX_NRF52_BSIM_CMSIS_H */
| 338 |
14,668 | /*
* testFuzzer.c: Test program for the custom entity loader used to fuzz
* with multiple inputs.
*
* See Copyright for the status of this software.
*/
#include <string.h>
#include <glob.h>
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xmlstring.h>
#include "fuzz.h"
#ifdef HAVE_HTML_FUZZER
#define LLVMFuzzerInitialize fuzzHtmlInit
#define LLVMFuzzerTestOneInput fuzzHtml
#include "html.c"
#undef LLVMFuzzerInitialize
#undef LLVMFuzzerTestOneInput
#endif
#ifdef HAVE_REGEXP_FUZZER
#define LLVMFuzzerInitialize fuzzRegexpInit
#define LLVMFuzzerTestOneInput fuzzRegexp
#include "regexp.c"
#undef LLVMFuzzerInitialize
#undef LLVMFuzzerTestOneInput
#endif
#ifdef HAVE_SCHEMA_FUZZER
#define LLVMFuzzerInitialize fuzzSchemaInit
#define LLVMFuzzerTestOneInput fuzzSchema
#include "schema.c"
#undef LLVMFuzzerInitialize
#undef LLVMFuzzerTestOneInput
#endif
#ifdef HAVE_URI_FUZZER
#define LLVMFuzzerInitialize fuzzUriInit
#define LLVMFuzzerTestOneInput fuzzUri
#include "uri.c"
#undef LLVMFuzzerInitialize
#undef LLVMFuzzerTestOneInput
#endif
#ifdef HAVE_XML_FUZZER
#define LLVMFuzzerInitialize fuzzXmlInit
#define LLVMFuzzerTestOneInput fuzzXml
#include "xml.c"
#undef LLVMFuzzerInitialize
#undef LLVMFuzzerTestOneInput
#endif
#ifdef HAVE_XPATH_FUZZER
#define LLVMFuzzerInitialize fuzzXPathInit
#define LLVMFuzzerTestOneInput fuzzXPath
#include "xpath.c"
#undef LLVMFuzzerInitialize
#undef LLVMFuzzerTestOneInput
#endif
typedef int
(*initFunc)(int *argc, char ***argv);
typedef int
(*fuzzFunc)(const char *data, size_t size);
int numInputs;
static int
testFuzzer(initFunc init, fuzzFunc fuzz, const char *pattern) {
glob_t globbuf;
int ret = -1;
int i;
if (glob(pattern, 0, NULL, &globbuf) != 0) {
fprintf(stderr, "pattern %s matches no files\n", pattern);
return(-1);
}
if (init != NULL)
init(NULL, NULL);
for (i = 0; i < globbuf.gl_pathc; i++) {
const char *path = globbuf.gl_pathv[i];
char *data;
size_t size;
data = xmlSlurpFile(path, &size);
if (data == NULL) {
fprintf(stderr, "couldn't read %s\n", path);
goto error;
}
fuzz(data, size);
xmlFree(data);
numInputs++;
}
ret = 0;
error:
globfree(&globbuf);
return(ret);
}
#ifdef HAVE_XML_FUZZER
static int
testEntityLoader() {
static const char data[] =
"doc.xml\\\n"
"<!DOCTYPE doc SYSTEM \"doc.dtd\">\n"
"<doc>&ent;</doc>\\\n"
"doc.dtd\\\n"
"<!ELEMENT doc (#PCDATA)>\n"
"<!ENTITY ent SYSTEM \"ent.txt\">\\\n"
"ent.txt\\\n"
"Hello, world!\\\n";
static xmlChar expected[] =
"<?xml version=\"1.0\"?>\n"
"<!DOCTYPE doc SYSTEM \"doc.dtd\">\n"
"<doc>Hello, world!</doc>\n";
const char *docBuffer;
size_t docSize;
xmlDocPtr doc;
xmlChar *out;
int ret = 0;
xmlSetExternalEntityLoader(xmlFuzzEntityLoader);
xmlFuzzDataInit(data, sizeof(data) - 1);
xmlFuzzReadEntities();
docBuffer = xmlFuzzMainEntity(&docSize);
doc = xmlReadMemory(docBuffer, docSize, NULL, NULL,
XML_PARSE_NOENT | XML_PARSE_DTDLOAD);
xmlDocDumpMemory(doc, &out, NULL);
if (xmlStrcmp(out, expected) != 0) {
fprintf(stderr, "Expected:\n%sGot:\n%s", expected, out);
ret = 1;
}
xmlFree(out);
xmlFreeDoc(doc);
xmlFuzzDataCleanup();
return(ret);
}
#endif
int
main() {
int ret = 0;
#ifdef HAVE_XML_FUZZER
if (testEntityLoader() != 0)
ret = 1;
#endif
#ifdef HAVE_HTML_FUZZER
if (testFuzzer(fuzzHtmlInit, fuzzHtml, "seed/html/*") != 0)
ret = 1;
#endif
#ifdef HAVE_REGEXP_FUZZER
if (testFuzzer(fuzzRegexpInit, fuzzRegexp, "seed/regexp/*") != 0)
ret = 1;
#endif
#ifdef HAVE_SCHEMA_FUZZER
if (testFuzzer(fuzzSchemaInit, fuzzSchema, "seed/schema/*") != 0)
ret = 1;
#endif
#ifdef HAVE_URI_FUZZER
if (testFuzzer(NULL, fuzzUri, "seed/uri/*") != 0)
ret = 1;
#endif
#ifdef HAVE_XML_FUZZER
if (testFuzzer(fuzzXmlInit, fuzzXml, "seed/xml/*") != 0)
ret = 1;
#endif
#ifdef HAVE_XPATH_FUZZER
if (testFuzzer(fuzzXPathInit, fuzzXPath, "seed/xpath/*") != 0)
ret = 1;
#endif
if (ret == 0)
printf("Successfully tested %d inputs\n", numInputs);
return(ret);
}
| 2,030 |
402 | /*
* Copyright 2000-2021 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.vaadin.flow.component;
import org.junit.Assert;
import org.junit.Test;
public class HasComponentsTest {
@Tag("div")
private static class TestComponent extends Component
implements HasComponents {
}
@Test
public void addStringToComponent() {
String text = "Add text";
TestComponent component = new TestComponent();
component.add(text);
Assert.assertEquals(text, component.getElement().getText());
}
@Test
public void insertComponentAtFirst() {
TestComponent component = createTestStructure();
TestComponent innerComponent = new TestComponent();
innerComponent.setId("insert-component-first");
component.addComponentAsFirst(innerComponent);
checkChildren(4, component);
Assert.assertEquals(innerComponent.getId(),
component.getChildren().findFirst().get().getId());
}
@Test
public void insertComponentAtIndex() {
TestComponent component = createTestStructure();
TestComponent innerComponent = new TestComponent();
innerComponent.setId("insert-component-index");
component.addComponentAtIndex(2, innerComponent);
checkChildren(4, component);
Assert.assertEquals(innerComponent.getId(), component.getElement()
.getChild(2).getComponent().get().getId());
}
@Test(expected = IllegalArgumentException.class)
public void insertComponentIndexLessThanZero() {
TestComponent component = createTestStructure();
TestComponent innerComponent = new TestComponent();
innerComponent.setId("insert-component-index-less");
component.addComponentAtIndex(-5, innerComponent);
}
@Test(expected = IllegalArgumentException.class)
public void insertComponentIndexGreaterThanChildrenNumber() {
TestComponent component = createTestStructure();
TestComponent innerComponent = new TestComponent();
innerComponent.setId("insert-component-index-greater");
component.addComponentAtIndex(100, innerComponent);
}
@Test
public void remove_removeComponentWithNoParent() {
TestComponent component = createTestStructure();
TestComponent innerComponent = new TestComponent();
// No any exception is thrown
component.remove(innerComponent);
}
@Test
public void remove_removeSeveralComponents_oneHasParent_nothingRemovedAndThrows() {
TestComponent component = createTestStructure();
TestComponent child = new TestComponent();
component.add(child);
TestComponent another = createTestStructure();
TestComponent innerComponent = new TestComponent();
another.add(innerComponent);
try {
component.remove(child, innerComponent);
Assert.fail();
} catch (IllegalArgumentException exception) {
Assert.assertEquals(component, child.getParent().get());
}
}
@Test
public void remove_removeSeveralComponents_oneHasNoParent_childIsRemoved() {
TestComponent component = createTestStructure();
TestComponent child = new TestComponent();
component.add(child);
TestComponent notAChild = new TestComponent();
component.remove(notAChild, child);
Assert.assertFalse(child.getParent().isPresent());
Assert.assertFalse(component.getChildren()
.filter(comp -> comp.equals(child)).findAny().isPresent());
}
@Test
public void remove_removeComponentWithCorrectParent() {
TestComponent component = createTestStructure();
TestComponent innerComponent = new TestComponent();
long size = component.getChildren().count();
component.add(innerComponent);
component.remove(innerComponent);
Assert.assertEquals(size, component.getChildren().count());
}
@Test(expected = IllegalArgumentException.class)
public void remove_removeComponentWithDifferentParent() {
TestComponent component = createTestStructure();
TestComponent another = createTestStructure();
TestComponent innerComponent = new TestComponent();
another.add(innerComponent);
component.remove(innerComponent);
}
private TestComponent createTestStructure() {
TestComponent component = new TestComponent();
checkChildren(0, component);
component.add(new TestComponent(), new TestComponent(),
new TestComponent());
checkChildren(3, component);
return component;
}
private void checkChildren(int number, TestComponent component) {
Assert.assertEquals(number, component.getChildren().count());
}
}
| 1,811 |
3,084 | <filename>network/wlan/WDI/COMMON/QosGen.h
#ifndef __INC_QOSGEN_H
#define __INC_QOSGEN_H
//=============================================================================
// Prototype function for Debugging Qos.
//=============================================================================
#if DBG
//
// Description:
// Dump the TSPEC IE content.
//
VOID
QosParsingDebug_TspecIE(
IN PADAPTER Adapter,
IN POCTET_STRING pOsBuffer
);
VOID
QosParsingDebug_TsrsIE(
IN PADAPTER Adapter,
IN POCTET_STRING pOsBuffer
);
VOID
QosParsingDebug_MsduLifetimeIE(
IN PADAPTER Adapter,
IN POCTET_STRING pOsBuffer
);
#else
#define QosParsingDebug_TspecIE(__Adapter, __pOsBuffer)
#define QosParsingDebug_TsrsIE(__Adapter, __pOsBuffer)
#define QosParsingDebug_MsduLifetimeIE(__Adapter, __pOsBuffer)
#endif // #if DBG
//=============================================================================
// End of Prototype function for Debugging Qos.
//=============================================================================
VOID
QosInitializeSTA(
IN PADAPTER Adapter
);
VOID
QosDeinitializeSTA(
IN PADAPTER Adapter
);
VOID
QosInitializeBssDesc(
IN PBSS_QOS pBssQos
);
VOID
QosParsingQoSElement(
IN PADAPTER Adapter,
IN BOOLEAN bEDCAParms,
IN OCTET_STRING WMMElement,
OUT PRT_WLAN_BSS pBssDesc
);
VOID
QosSetLegacyWMMParamWithHT(
IN PADAPTER Adapter,
OUT PRT_WLAN_BSS pBssDesc
);
VOID
QosSetLegacyACParam(
IN PADAPTER Adapter
);
VOID
QosOnAssocRsp(
IN PADAPTER Adapter,
IN OCTET_STRING asocpdu
);
VOID
QosOnBeaconUpdateParameter(
IN PADAPTER Adapter,
IN PRT_WLAN_BSS pBssDesc
);
VOID
QosFillHeader(
IN PADAPTER Adapter,
IN PRT_TCB pTcb
);
BOOLEAN
QosDataCheck(
IN PADAPTER Adapter,
IN PRT_RFD pRfd,
IN POCTET_STRING pFrame
);
u1Byte
QosGetUserPriority(
IN PADAPTER Adapter,
IN PRT_RFD pRfd,
IN POCTET_STRING pFrame
);
VOID
QosParsingDebug_BssDesc(
IN PRT_WLAN_BSS pBssDesc
);
VOID
QosParsingDebug_STA(
IN PADAPTER Adapter
);
VOID
QosParsingDebug_ParaElement(
IN pu1Byte pWMMParaEle
);
VOID
QosParsingDebug_AcParam(
IN pu1Byte pAcParam
);
VOID
QosParsingDebug_QosCtrlField(
IN pu1Byte pFrameHeader
);
VOID
SendQoSNullFunctionData(
IN PADAPTER Adapter,
IN pu1Byte StaAddr,
IN u1Byte AC,
IN BOOLEAN bForcePowerSave
);
VOID
QosConstructEDCAParamElem(
IN PADAPTER Adapter,
OUT POCTET_STRING posBuffer
);
VOID
QosConstructTSPEC(
IN PADAPTER Adapter,
IN pu1Byte pBuffer,
OUT pu4Byte pLength,
IN u1Byte TID,
IN u1Byte Direction,
IN BOOLEAN bPSB,
IN BOOLEAN bSchedule,
IN u1Byte AccessPolicy,
IN BOOLEAN bAggregation,
IN u1Byte AckPolicy,
IN u1Byte TrafficType,
IN u1Byte UserPriority,
IN u2Byte NominalMsduSize,
IN u2Byte MaxMsduSize,
IN u4Byte MinServiceItv,
IN u4Byte MaxServiceItv,
IN u4Byte InactivityItv,
IN u4Byte SuspensionItv,
IN u4Byte ServiceStartTime,
IN u4Byte MinDataRate,
IN u4Byte MeanDataRate,
IN u4Byte PeakDataRate,
IN u4Byte MaxBurstSize,
IN u4Byte DelayBound,
IN u4Byte MinPhyRate,
IN u2Byte SurplusBandwithAllow,
IN u2Byte MediumTime
);
VOID
QosInitTs(
IN PADAPTER Adapter,
IN PQOS_TSTREAM pTs,
IN u1Byte TSID,
IN PWMM_TSPEC pTSpec
);
VOID
QosFlushTs(
IN PADAPTER Adapter,
IN PQOS_TSTREAM pTs
);
PQOS_TSTREAM
QosAddTs(
IN PADAPTER Adapter,
IN u1Byte TSID,
IN pu1Byte RA,
IN pu1Byte TA,
IN PWMM_TSPEC pTSpec
);
PQOS_TSTREAM
QosGetTs(
IN PADAPTER Adapter,
IN u1Byte TSID,
IN pu1Byte RA,
IN pu1Byte TA
);
VOID
QosUpdateTs(
IN PADAPTER Adapter,
IN PQOS_TSTREAM pTs,
IN PWMM_TSPEC pTSpec
);
VOID
QosSendAddTs(
IN PADAPTER Adapter,
IN PQOS_TSTREAM pTs,
IN u4Byte numTs
);
VOID
QosSendDelTs(
IN PADAPTER Adapter,
IN PQOS_TSTREAM pTs,
IN u4Byte numTs
);
UINT
QosTsHash(
IN RT_HASH_KEY Key
);
VOID
QosAddTsTimerCallback(
IN PRT_TIMER pTimer
);
VOID
QosRemoveTs(
IN PADAPTER Adapter,
IN PQOS_TSTREAM pTs
);
VOID
QosResetTs(
IN PADAPTER Adapter,
IN PQOS_TSTREAM pTs
);
BOOLEAN
QosResetAllTs(
IN PADAPTER Adapter
);
VOID
QosRemoveAllTs(
IN PADAPTER Adapter
);
VOID
QosRecvMsduLifetimeIE(
IN PADAPTER Adapter,
IN POCTET_STRING pOsBuffer,
IN QOSIE_SOURCE source,
IN BOOLEAN rspStatus
);
VOID
QosParsingTrafficStreamIE(
IN PADAPTER Adapter,
IN POCTET_STRING pOsBuffer,
IN u4Byte offset,
IN QOSIE_SOURCE source,
IN BOOLEAN rspStatus
);
VOID
QosRecvTspecIE(
IN PADAPTER Adapter,
IN POCTET_STRING pOsBuffer,
IN QOSIE_SOURCE source,
IN BOOLEAN rspStatus
);
VOID
QosRecvTsrsIE(
IN PADAPTER Adapter,
IN POCTET_STRING pOsBuffer,
IN QOSIE_SOURCE source,
IN BOOLEAN rspStatus
);
VOID
QosConstructTSRS(
IN PADAPTER Adapter,
IN PQOS_TSTREAM pTs,
IN POCTET_STRING pOsAddTsPkt
);
VOID
QosIncAdmittedTime(
IN PADAPTER Adapter,
IN PQOS_TSTREAM pTs
);
VOID
QosDecAdmittedTime(
IN PADAPTER Adapter,
IN PQOS_TSTREAM pTs
);
VOID
QosACMTimerCallback(
IN PRT_TIMER pTimer
);
u1Byte
QosGetNPR(
IN PADAPTER Adapter,
IN PQOS_TSTREAM pTs
);
VOID
QosSetNPR(
IN PADAPTER Adapter,
IN PQOS_TSTREAM pTs,
IN u1Byte rate
);
BOOLEAN
QosAdmissionControl(
IN PADAPTER Adapter,
IN PRT_TCB pTcb
);
BOOLEAN
QosCalcUsedTimeAndAdmitPacket(
IN PADAPTER Adapter,
IN PRT_TCB pTcb
);
VOID
QosReturnAllPendingTxMsdu(
IN PADAPTER Adapter
);
RT_STATUS
OnAddTsReq(
IN PADAPTER Adapter,
IN PRT_RFD pRfd,
IN POCTET_STRING posMpdu
);
RT_STATUS
OnAddTsRsp(
IN PADAPTER Adapter,
IN PRT_RFD pRfd,
IN POCTET_STRING posMpdu
);
RT_STATUS
OnDelTs(
IN PADAPTER Adapter,
IN PRT_RFD pRfd,
IN POCTET_STRING posMpdu
);
BOOLEAN
IsStaQosTriggerFrame(
IN POCTET_STRING pOSMpdu,
IN AC_UAPSD StaUapsd
);
VOID
QosResetRxTS(
IN PADAPTER Adapter
);
#endif // #ifndef __INC_QOSGEN_H
| 3,399 |
3,783 | <gh_stars>1000+
package problems.medium;
import java.util.TreeMap;
/**
* Why Did you create this class? what does it do?
*/
public class MyCalendarTwo {
public static void main(String[] args) {
}
TreeMap<Integer, Integer> twice = new TreeMap<>();
TreeMap<Integer, Integer> once = new TreeMap<>();
public MyCalendarTwo() {
}
public boolean book(int start, int end) {
return true;
}
}
| 158 |
2,542 | <gh_stars>1000+
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#pragma once
namespace Reliability
{
namespace FailoverManagerComponent
{
class StateMachineAction
{
DENY_COPY(StateMachineAction);
public:
virtual ~StateMachineAction() {}
int PerformAction(FailoverManager & failoverManager);
virtual int OnPerformAction(FailoverManager & failoverManager) = 0;
virtual void WriteTo(Common::TextWriter& w, Common::FormatOptions const&) const = 0;
virtual void WriteToEtw(uint16 contextSequenceId) const = 0;
protected:
StateMachineAction();
};
}
}
| 317 |
10,225 | package io.quarkus.grpc.common.runtime.graal;
import static io.grpc.InternalServiceProviders.getCandidatesViaHardCoded;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import com.oracle.svm.core.annotate.Alias;
import com.oracle.svm.core.annotate.Substitute;
import com.oracle.svm.core.annotate.TargetClass;
@SuppressWarnings("unused")
@TargetClass(className = "io.grpc.ServiceProviders")
final class Target_io_grpc_ServiceProviders { // NOSONAR
@Substitute
public static <T> List<T> loadAll(
Class<T> klass,
Iterable<Class<?>> hardcoded,
ClassLoader cl,
final Target_io_grpc_ServiceProviders_PriorityAccessor<T> priorityAccessor) {
// For loading classes directly instead of using SPI.
Iterable<T> candidates;
candidates = getCandidatesViaHardCoded(klass, hardcoded);
List<T> list = new ArrayList<>();
for (T current : candidates) {
if (!priorityAccessor.isAvailable(current)) {
continue;
}
list.add(current);
}
// DO NOT USE LAMBDA
//noinspection Java8ListSort,Convert2Lambda
Collections.sort(list, Collections.reverseOrder(new Comparator<T>() { // NOSONAR
@Override
public int compare(T f1, T f2) {
int pd = priorityAccessor.getPriority(f1) - priorityAccessor.getPriority(f2);
if (pd != 0) {
return pd;
}
return f1.getClass().getName().compareTo(f2.getClass().getName());
}
}));
return Collections.unmodifiableList(list);
}
}
@TargetClass(className = "io.grpc.ServiceProviders", innerClass = "PriorityAccessor")
interface Target_io_grpc_ServiceProviders_PriorityAccessor<T> { // NOSONAR
// Just provide access to "io.grpc.ServiceProviders.PriorityAccessor"
@Alias
boolean isAvailable(T provider);
@Alias
int getPriority(T provider);
}
@SuppressWarnings("unused")
class GrpcSubstitutions {
}
| 913 |
370 | <reponame>sungkyu-kim/keras-anomaly-detection
import zipfile
def unzip(path_to_zip_file, directory_to_extract_to):
zip_ref = zipfile.ZipFile(path_to_zip_file, 'r')
zip_ref.extractall(directory_to_extract_to)
zip_ref.close()
| 104 |
356 | <gh_stars>100-1000
package com.idrv.coach.bean;
/**
* time:2016/5/23
* description:相册
*
* @author sunjianfei
*/
public class Album {
//O:学员风采相册 1:教练风采相册
int albumType;
int pictureNumber;
String cover;
public int getAlbumType() {
return albumType;
}
public void setAlbumType(int albumType) {
this.albumType = albumType;
}
public int getPictureNumber() {
return pictureNumber;
}
public void setPictureNumber(int pictureNumber) {
this.pictureNumber = pictureNumber;
}
public String getCover() {
return cover;
}
public void setCover(String cover) {
this.cover = cover;
}
}
| 309 |
348 | <reponame>chamberone/Leaflet.PixiOverlay
{"nom":"Eschbach-au-Val","circ":"2ème circonscription","dpt":"Haut-Rhin","inscrits":312,"abs":172,"votants":140,"blancs":7,"nuls":0,"exp":133,"res":[{"nuance":"LR","nom":"<NAME>","voix":82},{"nuance":"REM","nom":"<NAME>","voix":51}]} | 114 |
777 | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "core/animation/AnimationEffectTiming.h"
#include "bindings/core/v8/ExceptionState.h"
#include "bindings/core/v8/UnrestrictedDoubleOrString.h"
#include "core/animation/AnimationEffectReadOnly.h"
#include "core/animation/AnimationEffectTimingReadOnly.h"
#include "core/animation/KeyframeEffect.h"
#include "core/animation/TimingInput.h"
#include "platform/animation/TimingFunction.h"
namespace blink {
AnimationEffectTiming* AnimationEffectTiming::create(
AnimationEffectReadOnly* parent) {
return new AnimationEffectTiming(parent);
}
AnimationEffectTiming::AnimationEffectTiming(AnimationEffectReadOnly* parent)
: AnimationEffectTimingReadOnly(parent) {}
void AnimationEffectTiming::setDelay(double delay) {
Timing timing = m_parent->specifiedTiming();
TimingInput::setStartDelay(timing, delay);
m_parent->updateSpecifiedTiming(timing);
}
void AnimationEffectTiming::setEndDelay(double endDelay) {
Timing timing = m_parent->specifiedTiming();
TimingInput::setEndDelay(timing, endDelay);
m_parent->updateSpecifiedTiming(timing);
}
void AnimationEffectTiming::setFill(String fill) {
Timing timing = m_parent->specifiedTiming();
TimingInput::setFillMode(timing, fill);
m_parent->updateSpecifiedTiming(timing);
}
void AnimationEffectTiming::setIterationStart(double iterationStart,
ExceptionState& exceptionState) {
Timing timing = m_parent->specifiedTiming();
if (TimingInput::setIterationStart(timing, iterationStart, exceptionState))
m_parent->updateSpecifiedTiming(timing);
}
void AnimationEffectTiming::setIterations(double iterations,
ExceptionState& exceptionState) {
Timing timing = m_parent->specifiedTiming();
if (TimingInput::setIterationCount(timing, iterations, exceptionState))
m_parent->updateSpecifiedTiming(timing);
}
void AnimationEffectTiming::setDuration(
const UnrestrictedDoubleOrString& duration,
ExceptionState& exceptionState) {
Timing timing = m_parent->specifiedTiming();
if (TimingInput::setIterationDuration(timing, duration, exceptionState))
m_parent->updateSpecifiedTiming(timing);
}
void AnimationEffectTiming::setPlaybackRate(double playbackRate) {
Timing timing = m_parent->specifiedTiming();
TimingInput::setPlaybackRate(timing, playbackRate);
m_parent->updateSpecifiedTiming(timing);
}
void AnimationEffectTiming::setDirection(String direction) {
Timing timing = m_parent->specifiedTiming();
TimingInput::setPlaybackDirection(timing, direction);
m_parent->updateSpecifiedTiming(timing);
}
void AnimationEffectTiming::setEasing(String easing,
ExceptionState& exceptionState) {
Timing timing = m_parent->specifiedTiming();
// The AnimationEffectTiming might not be attached to a document at this
// point, so we pass nullptr in to setTimingFunction. This means that these
// calls are not considered in the WebAnimationsEasingAsFunction*
// UseCounters, but the bug we are tracking there does not come through
// this interface.
if (TimingInput::setTimingFunction(timing, easing, nullptr, exceptionState))
m_parent->updateSpecifiedTiming(timing);
}
DEFINE_TRACE(AnimationEffectTiming) {
AnimationEffectTimingReadOnly::trace(visitor);
}
} // namespace blink
| 1,141 |
5,169 | <filename>Specs/9/5/2/MotionMachine/1.3.3/MotionMachine.podspec.json<gh_stars>1000+
{
"name": "MotionMachine",
"version": "1.3.3",
"swift_version": "4.2",
"license": {
"type": "MIT"
},
"summary": "An elegant, powerful, and modular animation library for Swift.",
"description": "MotionMachine provides a modular, generic platform for manipulating values. Its animation engine was built from the ground up to support not just UIKit values, but property values of any class you want to manipulate. It offers sensible default functionality that abstracts most of the hard work away, allowing you to focus on your work.",
"homepage": "https://github.com/poetmountain/MotionMachine",
"social_media_url": "https://twitter.com/petsound",
"authors": {
"<NAME>": "<EMAIL>"
},
"source": {
"git": "https://github.com/poetmountain/MotionMachine.git",
"tag": "1.3.3"
},
"source_files": "Sources/**/*.{m,h,swift}",
"frameworks": [
"CoreGraphics",
"QuartzCore"
],
"platforms": {
"ios": "8.0",
"tvos": "9.0"
},
"requires_arc": true
}
| 380 |
852 | <filename>Geometry/TrackerSimData/python/trackerSimGeometry_TwentyFivePercentXML_cfi.py
import FWCore.ParameterSet.Config as cms
XMLIdealGeometryESSource = cms.ESSource("XMLIdealGeometryESSource",
geomXMLFiles = cms.vstring('Geometry/CMSCommonData/data/normal/cmsextent.xml',
'Geometry/CMSCommonData/data/cms.xml',
'Geometry/CMSCommonData/data/cmsMother.xml',
'Geometry/CMSCommonData/data/cmsTracker.xml',
'Geometry/CMSCommonData/data/muonBase.xml',
'Geometry/CMSCommonData/data/muonMagnet.xml',
'Geometry/CMSCommonData/data/cmsBeam.xml',
'Geometry/CMSCommonData/data/beampipe.xml',
'Geometry/CMSCommonData/data/mgnt.xml',
'Geometry/CMSCommonData/data/materials.xml',
'Geometry/CMSCommonData/data/rotations.xml',
'Geometry/TwentyFivePercentTrackerCommonData/data/tib_twentyfivepercent.xml',
'Geometry/TrackerCommonData/data/tibstringpar.xml',
'Geometry/TwentyFivePercentTrackerCommonData/data/tibstring3_twentyfivepercent.xml',
'Geometry/TrackerCommonData/data/tibstring3ur.xml',
'Geometry/TrackerCommonData/data/tibstring3ul.xml',
'Geometry/TrackerCommonData/data/tibstring3lr.xml',
'Geometry/TrackerCommonData/data/tibstring3ll.xml',
'Geometry/TwentyFivePercentTrackerCommonData/data/tibstring2_twentyfivepercent.xml',
'Geometry/TrackerCommonData/data/tibstring2ur.xml',
'Geometry/TrackerCommonData/data/tibstring2ul.xml',
'Geometry/TrackerCommonData/data/tibstring2lr.xml',
'Geometry/TrackerCommonData/data/tibstring2ll.xml',
'Geometry/TwentyFivePercentTrackerCommonData/data/tibstring1_twentyfivepercent.xml',
'Geometry/TrackerCommonData/data/tibstring1ur.xml',
'Geometry/TrackerCommonData/data/tibstring1ul.xml',
'Geometry/TrackerCommonData/data/tibstring1lr.xml',
'Geometry/TrackerCommonData/data/tibstring1ll.xml',
'Geometry/TwentyFivePercentTrackerCommonData/data/tibstring0_twentyfivepercent.xml',
'Geometry/TrackerCommonData/data/tibstring0ur.xml',
'Geometry/TrackerCommonData/data/tibstring0ul.xml',
'Geometry/TrackerCommonData/data/tibstring0lr.xml',
'Geometry/TrackerCommonData/data/tibstring0ll.xml',
'Geometry/TrackerCommonData/data/tibmodule2.xml',
'Geometry/TrackerCommonData/data/tibmodule0.xml',
'Geometry/TrackerCommonData/data/tibmodule0b.xml',
'Geometry/TrackerCommonData/data/tibmodule0a.xml',
'Geometry/TrackerCommonData/data/tibmodpar.xml',
'Geometry/TrackerCommonData/data/tibmaterial.xml',
'Geometry/TrackerCommonData/data/tibtidcommonmaterial.xml',
'Geometry/TrackerCommonData/data/tiblayerpar.xml',
'Geometry/TwentyFivePercentTrackerCommonData/data/tiblayer3_twentyfivepercent.xml',
'Geometry/TwentyFivePercentTrackerCommonData/data/tiblayer2_twentyfivepercent.xml',
'Geometry/TwentyFivePercentTrackerCommonData/data/tiblayer1_twentyfivepercent.xml',
'Geometry/TwentyFivePercentTrackerCommonData/data/tiblayer0_twentyfivepercent.xml',
'Geometry/TrackerCommonData/data/tid.xml',
'Geometry/TrackerCommonData/data/tidringpar.xml',
'Geometry/TrackerCommonData/data/tidring2.xml',
'Geometry/TrackerCommonData/data/tidring1.xml',
'Geometry/TrackerCommonData/data/tidring1f.xml',
'Geometry/TrackerCommonData/data/tidring1b.xml',
'Geometry/TrackerCommonData/data/tidring0.xml',
'Geometry/TrackerCommonData/data/tidring0f.xml',
'Geometry/TrackerCommonData/data/tidring0b.xml',
'Geometry/TrackerCommonData/data/tidmodule2.xml',
'Geometry/TrackerCommonData/data/tidmodule1.xml',
'Geometry/TrackerCommonData/data/tidmodule1r.xml',
'Geometry/TrackerCommonData/data/tidmodule1l.xml',
'Geometry/TrackerCommonData/data/tidmodule0.xml',
'Geometry/TrackerCommonData/data/tidmodule0r.xml',
'Geometry/TrackerCommonData/data/tidmodule0l.xml',
'Geometry/TrackerCommonData/data/tidmodpar.xml',
'Geometry/TrackerCommonData/data/tidmaterial.xml',
'Geometry/TrackerCommonData/data/tidf.xml',
'Geometry/TrackerCommonData/data/tobmaterial.xml',
'Geometry/TrackerCommonData/data/tobmodpar.xml',
'Geometry/TrackerCommonData/data/tobmodule0.xml',
'Geometry/TrackerCommonData/data/tobmodule2.xml',
'Geometry/TrackerCommonData/data/tobmodule4.xml',
'Geometry/TrackerCommonData/data/tobrodpar.xml',
'Geometry/TrackerCommonData/data/tobrod0c.xml',
'Geometry/TrackerCommonData/data/tobrod0l.xml',
'Geometry/TrackerCommonData/data/tobrod0h.xml',
'Geometry/TwentyFivePercentTrackerCommonData/data/tobrod0_twentyfivepercent.xml',
'Geometry/TrackerCommonData/data/tobrod1l.xml',
'Geometry/TrackerCommonData/data/tobrod1h.xml',
'Geometry/TwentyFivePercentTrackerCommonData/data/tobrod1_twentyfivepercent.xml',
'Geometry/TrackerCommonData/data/tobrod2c.xml',
'Geometry/TrackerCommonData/data/tobrod2l.xml',
'Geometry/TrackerCommonData/data/tobrod2h.xml',
'Geometry/TwentyFivePercentTrackerCommonData/data/tobrod2_twentyfivepercent.xml',
'Geometry/TrackerCommonData/data/tobrod3l.xml',
'Geometry/TrackerCommonData/data/tobrod3h.xml',
'Geometry/TwentyFivePercentTrackerCommonData/data/tobrod3_twentyfivepercent.xml',
'Geometry/TrackerCommonData/data/tobrod4c.xml',
'Geometry/TrackerCommonData/data/tobrod4l.xml',
'Geometry/TrackerCommonData/data/tobrod4h.xml',
'Geometry/TwentyFivePercentTrackerCommonData/data/tobrod4_twentyfivepercent.xml',
'Geometry/TrackerCommonData/data/tobrod5l.xml',
'Geometry/TrackerCommonData/data/tobrod5h.xml',
'Geometry/TwentyFivePercentTrackerCommonData/data/tobrod5_twentyfivepercent.xml',
'Geometry/TwentyFivePercentTrackerCommonData/data/tob_twentyfivepercent.xml',
'Geometry/TrackerCommonData/data/trackermaterial.xml',
'Geometry/TwentyFivePercentTrackerCommonData/data/tracker_twentyfivepercent.xml',
'Geometry/TwentyFivePercentTrackerCommonData/data/trackerStructureTopology_twentyfivepercent.xml',
'Geometry/TrackerSimData/data/trackersens_twentyfivepercent.xml',
'Geometry/TrackerSimData/data/trackerProdCuts_twentyfivepercent.xml',
'Geometry/TrackerSimData/data/trackerProdCutsBEAM.xml',
'Geometry/CMSCommonData/data/FieldParameters.xml'),
rootNodeName = cms.string('cms:OCMS')
)
| 2,855 |
4,962 | /*
* Copyright 2014 - Present <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 net.bytebuddy.build.gradle.transform;
import org.objectweb.asm.*;
import org.objectweb.asm.commons.ClassRemapper;
import org.objectweb.asm.commons.SimpleRemapper;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;
import java.util.jar.JarOutputStream;
/**
* A transformer that removes classes in a package and substitutes all type names with the value of an annotation that
* is expected on these classes.
*/
public class GradleTypeTransformer {
/**
* The class file extension.
*/
private static final String CLASS_FILE = ".class";
/**
* The default API package path.
*/
private static final String API = "net/bytebuddy/build/gradle/api";
/**
* The default type name for a substitution annotation.
*/
private static final String TYPE = API + "/GradleType";
/**
* The internal package name for API being used.
*/
private final String api;
/**
* The internal type name for a substitution annotation being used.
*/
private final String type;
/**
* Creates a new Gradle type transformer using default values.
*/
public GradleTypeTransformer() {
this(API, TYPE);
}
/**
* Creates a new Gradle type transformer.
*
* @param api The internal package name for API being used.
* @param type The internal type name for a substitution annotation being used.
*/
protected GradleTypeTransformer(String api, String type) {
this.api = api;
this.type = type;
}
/**
* Transforms the supplied jar file.
*
* @param jar The jar file to transform.
* @throws IOException If an I/O exception occurs.
*/
public void transform(File jar) throws IOException {
Map<String, String> names = GradlePackageVisitor.toGradleTypeNames(api, type, jar);
File temporary = File.createTempFile("gradle-byte-buddy-plugin", ".jar");
JarInputStream jarInputStream = new JarInputStream(new FileInputStream(jar));
try {
JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(temporary));
try {
JarEntry entry;
while ((entry = jarInputStream.getNextJarEntry()) != null) {
if (!entry.getName().startsWith(api)) {
if (entry.getName().endsWith(CLASS_FILE)) {
ClassReader reader = new ClassReader(jarInputStream);
ClassWriter writer = new ClassWriter(0);
reader.accept(new ClassRemapper(writer, new SimpleRemapper(names)), 0);
jarOutputStream.putNextEntry(new JarEntry(entry.getName()));
jarOutputStream.write(writer.toByteArray());
} else {
jarOutputStream.putNextEntry(entry);
byte[] buffer = new byte[1024];
int length;
while ((length = jarInputStream.read(buffer)) != -1) {
jarOutputStream.write(buffer, 0, length);
}
}
jarOutputStream.closeEntry();
}
jarInputStream.closeEntry();
}
} finally {
jarOutputStream.close();
}
} finally {
jarInputStream.close();
}
if (!jar.delete()) {
throw new IllegalStateException("Could not delete " + jar);
} else if (!temporary.renameTo(jar)) { // copy file as a fallback
InputStream inputStream = new FileInputStream(temporary);
try {
FileOutputStream outputStream = new FileOutputStream(jar);
try {
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
} finally {
outputStream.close();
}
} finally {
inputStream.close();
}
if (!temporary.delete()) {
throw new IllegalStateException("Could not delete " + temporary);
}
}
}
/**
* A visitor that locates the substitution annotation's {@code value} property to
* extract a placeholder type's actual name.
*/
protected static class GradlePackageVisitor extends ClassVisitor {
/**
* The internal type name for a substitution annotation being used.
*/
private final String type;
/**
* The names being discovered.
*/
private final Map<String, String> names;
/**
* The source internal name or {@code null} if not discovered.
*/
private String source;
/**
* The target internal name or {@code null} if not discovered.
*/
private String target;
/**
* Creates a new Gradle package visitor.
*
* @param type The internal type name for a substitution annotation being used.
* @param names The names being discovered.
*/
protected GradlePackageVisitor(String type, Map<String, String> names) {
super(Opcodes.ASM9);
this.type = type;
this.names = names;
}
/**
* Extracts a mapping of internal names to actual internal names of the Gradle API.
*
* @param api The internal package name for API being used.
* @param type The internal package name for API being used.
* @param jar The jar file to scan.
* @return A mapping of internal names to actual internal names of the Gradle API.
* @throws IOException If an I/O exception occurs.
*/
protected static Map<String, String> toGradleTypeNames(String api, String type, File jar) throws IOException {
Map<String, String> names = new HashMap<String, String>();
JarInputStream jarInputStream = new JarInputStream(new FileInputStream(jar));
try {
JarEntry entry;
while ((entry = jarInputStream.getNextJarEntry()) != null) {
if (entry.getName().startsWith(api)
&& entry.getName().endsWith(CLASS_FILE)
&& !entry.getName().equals(type + CLASS_FILE)) {
new ClassReader(jarInputStream).accept(new GradlePackageVisitor(type, names), ClassReader.SKIP_CODE);
}
jarInputStream.closeEntry();
}
} finally {
jarInputStream.close();
}
return names;
}
@Override
public void visit(int version, int modifier, String name, String signature, String superClassName, String[] interfaceName) {
source = name;
}
@Override
public AnnotationVisitor visitAnnotation(String descriptor, boolean visible) {
return descriptor.equals("L" + type + ";")
? new GradleTypeAnnotationVisitor()
: null;
}
@Override
public void visitEnd() {
if (target == null) {
throw new IllegalStateException("Missing annotation value for " + source);
} else if (names.put(source, target) != null) {
throw new IllegalStateException("Unexpected duplicate for " + source);
}
}
/**
* An annotation visitor to extract the substitution annotation's {@code value} property.
*/
protected class GradleTypeAnnotationVisitor extends AnnotationVisitor {
/**
* Creates a new package annotation visitor.
*/
protected GradleTypeAnnotationVisitor() {
super(Opcodes.ASM9);
}
@Override
public void visit(String name, Object value) {
if (!name.equals("value") || !(value instanceof String)) {
throw new IllegalStateException("Unexpected property: " + name);
}
target = ((String) value).replace('.', '/');
}
}
}
}
| 4,019 |
2,542 | <filename>src/prod/src/api/wrappers/ComQueryResult.h
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#pragma once
namespace Api
{
class ComInternalQueryResult
: public IInternalFabricQueryResult2
, private Common::ComUnknownBase
{
DENY_COPY_ASSIGNMENT(ComInternalQueryResult)
BEGIN_COM_INTERFACE_LIST(ComInternalQueryResult)
COM_INTERFACE_ITEM(IID_IUnknown,IInternalFabricQueryResult)
COM_INTERFACE_ITEM(IID_IInternalFabricQueryResult,IInternalFabricQueryResult)
COM_INTERFACE_ITEM(IID_IInternalFabricQueryResult2,IInternalFabricQueryResult2)
END_COM_INTERFACE_LIST()
public:
explicit ComInternalQueryResult(ServiceModel::QueryResult && nativeResult);
//
// IInternalFabricQueryResult2 methods
//
const FABRIC_QUERY_RESULT * STDMETHODCALLTYPE get_Result(void);
//
// IInternalFabricQueryResult2 methods
//
const FABRIC_PAGING_STATUS *STDMETHODCALLTYPE get_PagingStatus(void);
private:
Common::ScopedHeap heap_;
Common::ReferencePointer<FABRIC_QUERY_RESULT> queryResult_;
Common::ReferencePointer<FABRIC_PAGING_STATUS> pagingStatus_;
};
}
| 584 |
4,538 | """
Testing si7006 python driver
The below i2c configuration is needed in your board.json.
"si7006": {
"type": "I2C",
"port": 1,
"addrWidth": 7,
"freq": 400000,
"mode": "master",
"devAddr": 64
}
"""
from si7006 import SI7006
print("Testing si7006 ...")
si7006Dev = SI7006()
si7006Dev.open("si7006")
version = si7006Dev.getVer()
print("si7006 version is: %d" % version)
chipID = si7006Dev.getID()
print("si7006 chip id is:", chipID)
temperature = si7006Dev.getTemperature()
print("The temperature is: %f" % temperature)
humidity = si7006Dev.getHumidity()
print("The humidity is: %f" % humidity)
si7006Dev.close()
print("Test si7006 success!")
| 254 |
373 | package com.dianrong.common.uniauth.server.data.entity.ext;
import com.dianrong.common.uniauth.server.data.entity.Permission;
public class PermissionExt extends Permission {
private Integer domainId;
protected Integer startIndex;
protected Integer wantCount;
public Integer getDomainId() {
return domainId;
}
public void setDomainId(Integer domainId) {
this.domainId = domainId;
}
public Integer getStartIndex() {
return startIndex;
}
public void setStartIndex(Integer startIndex) {
this.startIndex = startIndex;
}
public Integer getWantCount() {
return wantCount;
}
public void setWantCount(Integer wantCount) {
this.wantCount = wantCount;
}
}
| 224 |
2,151 | <gh_stars>1000+
// 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.
#ifndef NET_THIRD_PARTY_QUIC_PLATFORM_IMPL_QUIC_SLEEP_IMPL_H_
#define NET_THIRD_PARTY_QUIC_PLATFORM_IMPL_QUIC_SLEEP_IMPL_H_
#include "base/threading/platform_thread.h"
#include "base/time/time.h"
#include "net/third_party/quic/core/quic_time.h"
namespace net {
inline void QuicSleepImpl(QuicTime::Delta duration) {
base::PlatformThread::Sleep(
base::TimeDelta::FromMilliseconds(duration.ToMilliseconds()));
}
} // namespace net
#endif // NET_THIRD_PARTY_QUIC_PLATFORM_IMPL_QUIC_SLEEP_IMPL_H_
| 269 |
310 | {
"name": "NUC6i3SYK",
"description": "A tiny PC.",
"url": "https://ark.intel.com/products/89186/Intel-NUC-Kit-NUC6i3SYK"
}
| 62 |
327 | <reponame>yosianonymous31/MobileGuard<filename>app/src/main/java/com/ittianyu/mobileguard/domain/GridViewItemBean.java
package com.ittianyu.mobileguard.domain;
import com.ittianyu.mobileguard.strategy.OnClickListener;
/**
* Created by yu.
* gv_menu item bean
*/
public class GridViewItemBean {
private int iconId;
private int nameId;
private OnClickListener scheme;
public OnClickListener getScheme() {
return scheme;
}
public void setScheme(OnClickListener scheme) {
this.scheme = scheme;
}
public GridViewItemBean(int iconId, int nameId, OnClickListener scheme) {
this.iconId = iconId;
this.nameId = nameId;
this.scheme = scheme;
}
public GridViewItemBean() {
}
public int getIconId() {
return iconId;
}
public void setIconId(int iconId) {
this.iconId = iconId;
}
public int getNameId() {
return nameId;
}
public void setNameId(int nameId) {
this.nameId = nameId;
}
}
| 422 |
544 | import torch
import torch.nn as nn
import torch.nn.parallel
from torch.nn import functional
import torch.utils.data
import numpy as np
from utils.spectral_norm import spectral_norm
# Define a resnet block
class ResnetBlock(nn.Module):
def __init__(self, dim, padding_type, norm_layer, activation=nn.ReLU(True), use_dropout=False):
super(ResnetBlock, self).__init__()
self.conv_block = self.build_conv_block(dim, padding_type, norm_layer, activation, use_dropout)
def build_conv_block(self, dim, padding_type, norm_layer, activation, use_dropout):
conv_block = []
p = 0
if padding_type == 'reflect':
conv_block += [nn.ReflectionPad2d(1)]
elif padding_type == 'replicate':
conv_block += [nn.ReplicationPad2d(1)]
elif padding_type == 'zero':
p = 1
else:
raise NotImplementedError('padding [%s] is not implemented' % padding_type)
conv_block += [nn.Conv2d(dim, dim, kernel_size=3, padding=p),
norm_layer(dim),
activation]
if use_dropout:
conv_block += [nn.Dropout(0.5)]
p = 0
if padding_type == 'reflect':
conv_block += [nn.ReflectionPad2d(1)]
elif padding_type == 'replicate':
conv_block += [nn.ReplicationPad2d(1)]
elif padding_type == 'zero':
p = 1
else:
raise NotImplementedError('padding [%s] is not implemented' % padding_type)
conv_block += [nn.Conv2d(dim, dim, kernel_size=3, padding=p),
norm_layer(dim)]
return nn.Sequential(*conv_block)
def forward(self, x):
out = x + self.conv_block(x)
return out
# transported from pix2pixHD project
class GlobalGenerator(nn.Module):
def __init__(self, input_nc=3, output_nc=3, ngf=64, n_downsampling=3, n_blocks=9, norm_layer=nn.BatchNorm2d,
padding_type='reflect'):
assert (n_blocks >= 0)
super(GlobalGenerator, self).__init__()
activation = nn.ReLU(True)
model = [nn.ReflectionPad2d(3), nn.Conv2d(input_nc, ngf, kernel_size=7, padding=0), norm_layer(ngf), activation]
# downsample
for i in range(n_downsampling):
mult = 2 ** i
model += [nn.Conv2d(ngf * mult, ngf * mult * 2, kernel_size=3, stride=2, padding=1),
norm_layer(ngf * mult * 2), activation]
# resnet blocks
mult = 2 ** n_downsampling
for i in range(n_blocks):
model += [ResnetBlock(ngf * mult, padding_type=padding_type, activation=activation, norm_layer=norm_layer)]
# upsample
for i in range(n_downsampling):
mult = 2 ** (n_downsampling - i)
model += [nn.ConvTranspose2d(ngf * mult, int(ngf * mult / 2), kernel_size=3, stride=2, padding=1,
output_padding=1),
norm_layer(int(ngf * mult / 2)), activation]
model += [nn.ReflectionPad2d(3), nn.Conv2d(ngf, output_nc, kernel_size=7, padding=0), nn.Tanh()]
self.model = nn.Sequential(*model)
def forward(self, x):
return self.model(x)
"""
Use CycleGAN's NLayerDiscriminator as a starting point...
https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/models/networks.py
The discriminator is fixed to process 64*64 input.
params:
@ n_layers: You can change this param to control the receptive field size
n_layers output receptive field size
4 13*13 34
5 5*5 70
6 1*1 256
P.S. This implementation doesn't use sigmoid, so it must be trained with
nn.BCEWithLogitLoss() instead of nn.BCELoss()!
"""
class NLayerDiscriminator(nn.Module):
def __init__(self, input_nc, ndf=64, n_layers=4,
norm_layer=nn.BatchNorm2d,
use_sigmoid=True, use_bias=False):
super(NLayerDiscriminator, self).__init__()
kw = 4
padw = 1
sequence = [
nn.Conv2d(input_nc, ndf, kernel_size=kw, stride=2, padding=padw),
nn.LeakyReLU(0.2, True)
]
nf_mult = 1
for n in range(1, n_layers):
nf_mult_prev = nf_mult
nf_mult = min(2 ** n, 8)
sequence += [
nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult,
kernel_size=kw, stride=2, padding=padw, bias=use_bias),
spectral_norm(norm_layer(ndf * nf_mult)),
nn.LeakyReLU(0.2, True),
]
# modify this part for feature extraction
self.model = nn.Sequential(*sequence) # Extract feature here
nf_mult_prev = nf_mult
nf_mult = min(2 ** n_layers, 8)
sequence = [ # building a new sequence, not adding modules!
nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult,
kernel_size=kw, stride=1, padding=padw, bias=use_bias),
spectral_norm(norm_layer(ndf * nf_mult)),
nn.LeakyReLU(0.2, True),
# nn.Dropout(0.1),
nn.Conv2d(ndf * nf_mult, 1, kernel_size=3, stride=1, padding=0)
]
if use_sigmoid:
sequence += [nn.Sigmoid()]
self.predictor = nn.Sequential(*sequence)
# single label prediction
def forward(self, x):
return self.predictor(self.model(x)).squeeze()
# high-level feature matching
def extract_features(self, x):
return self.model(x).squeeze()
| 2,752 |
464 | <reponame>LuciusMos/DI-engine<gh_stars>100-1000
from collections import namedtuple
import numpy as np
from ding.envs.common import EnvElement
class GfootballReward(EnvElement):
_name = "gfootballReward"
_reward_keys = ['reward_value']
Reward = namedtuple('Action', _reward_keys)
MinReward = -1.0
MaxReward = 1.0
def _init(self, cfg) -> None:
self._default_val = 0.0
self.template = {
'reward_value': {
'name': 'reward_value',
'shape': (1, ),
'value': {
'min': -1.0,
'max': 1.0,
'dtype': float,
'dinfo': 'float value',
},
'env_value': 'reward of action',
'to_agent_processor': lambda x: x,
'from_agent_processor': lambda x: x,
'necessary': True,
}
}
self._shape = (1, )
self._value = {
'min': -1.0,
'max': 1.0,
'dtype': float,
'dinfo': 'float value',
}
def _to_agent_processor(self, reward: float) -> np.array:
return np.array([reward], dtype=float)
def _from_agent_processor(self, reward: float) -> float:
return reward
def _details(self):
return '\t'.join(self._reward_keys)
| 733 |
4,126 | <filename>src/LightingThread.h
// LightingThread.h
// Interfaces to the cLightingThread class representing the thread that processes requests for lighting
/*
Lighting is done on whole chunks. For each chunk to be lighted, the whole 3x3 chunk area around it is read,
then it is processed, so that the middle chunk area has valid lighting, and the lighting is copied into the ChunkMap.
Lighting is calculated in full char arrays instead of nibbles, so that accessing the arrays is fast.
Lighting is calculated in a flood-fill fashion:
1. Generate seeds from where the light spreads (full skylight / light-emitting blocks)
2. For each seed:
- Spread the light 1 block in each of the 6 cardinal directions, if the blocktype allows
- If the recipient block has had lower lighting value than that being spread, make it a new seed
3. Repeat step 2, until there are no more seeds
The seeds need two fast operations:
- Check if a block at [x, y, z] is already a seed
- Get the next seed in the row
For that reason it is stored in two arrays, one stores a bool saying a seed is in that position,
the other is an array of seed coords, encoded as a single int.
Step 2 needs two separate storages for old seeds and new seeds, so there are two actual storages for that purpose,
their content is swapped after each full step-2-cycle.
The thread has two queues of chunks that are to be lighted.
The first queue, m_Queue, is the only one that is publicly visible, chunks get queued there by external requests.
The second one, m_PostponedQueue, is for chunks that have been taken out of m_Queue and didn't have neighbors ready.
Chunks from m_PostponedQueue are moved back into m_Queue when their neighbors get valid, using the ChunkReady callback.
*/
#pragma once
#include "OSSupport/IsThread.h"
#include "ChunkStay.h"
// fwd: "cWorld.h"
class cWorld;
class cLightingThread:
public cIsThread
{
using Super = cIsThread;
public:
cLightingThread(cWorld & a_World);
virtual ~cLightingThread() override;
void Stop(void);
/** Queues the entire chunk for lighting.
The callback, if specified, is called after the lighting has been processed. */
void QueueChunk(int a_ChunkX, int a_ChunkZ, std::unique_ptr<cChunkCoordCallback> a_CallbackAfter);
/** Blocks until the queue is empty or the thread is terminated */
void WaitForQueueEmpty(void);
size_t GetQueueLength(void);
protected:
class cLightingChunkStay :
public cChunkStay
{
public:
cLightingThread & m_LightingThread;
int m_ChunkX;
int m_ChunkZ;
std::unique_ptr<cChunkCoordCallback> m_CallbackAfter;
cLightingChunkStay(cLightingThread & a_LightingThread, int a_ChunkX, int a_ChunkZ, std::unique_ptr<cChunkCoordCallback> a_CallbackAfter);
protected:
virtual void OnChunkAvailable(int a_ChunkX, int a_ChunkZ) override
{
UNUSED(a_ChunkX);
UNUSED(a_ChunkZ);
}
virtual bool OnAllChunksAvailable(void) override;
virtual void OnDisabled(void) override;
} ;
typedef std::list<cChunkStay *> cChunkStays;
cWorld & m_World;
/** The mutex to protect m_Queue and m_PendingQueue */
cCriticalSection m_CS;
/** The ChunkStays that are loaded and are waiting to be lit. */
cChunkStays m_Queue;
/** The ChunkStays that are waiting for load. Used for stopping the thread. */
cChunkStays m_PendingQueue;
cEvent m_evtItemAdded; // Set when queue is appended, or to stop the thread
cEvent m_evtQueueEmpty; // Set when the queue gets empty
/** The highest block in the current 3x3 chunk data */
HEIGHTTYPE m_MaxHeight;
// Buffers for the 3x3 chunk data
// These buffers alone are 1.7 MiB in size, therefore they cannot be located on the stack safely - some architectures may have only 1 MiB for stack, or even less
// Placing the buffers into the object means that this object can light chunks only in one thread!
// The blobs are XZY organized as a whole, instead of 3x3 XZY-organized subarrays ->
// -> This means data has to be scatterred when reading and gathered when writing!
static const int BlocksPerYLayer = cChunkDef::Width * cChunkDef::Width * 3 * 3;
BLOCKTYPE m_BlockTypes[BlocksPerYLayer * cChunkDef::Height];
NIBBLETYPE m_BlockLight[BlocksPerYLayer * cChunkDef::Height];
NIBBLETYPE m_SkyLight [BlocksPerYLayer * cChunkDef::Height];
HEIGHTTYPE m_HeightMap [BlocksPerYLayer];
// Seed management (5.7 MiB)
// Two buffers, in each calc step one is set as input and the other as output, then in the next step they're swapped
// Each seed is represented twice in this structure - both as a "list" and as a "position".
// "list" allows fast traversal from seed to seed
// "position" allows fast checking if a coord is already a seed
unsigned char m_IsSeed1 [BlocksPerYLayer * cChunkDef::Height];
unsigned int m_SeedIdx1[BlocksPerYLayer * cChunkDef::Height];
unsigned char m_IsSeed2 [BlocksPerYLayer * cChunkDef::Height];
unsigned int m_SeedIdx2[BlocksPerYLayer * cChunkDef::Height];
size_t m_NumSeeds;
virtual void Execute(void) override;
/** Lights the entire chunk. If neighbor chunks don't exist, touches them and re-queues the chunk */
void LightChunk(cLightingChunkStay & a_Item);
/** Prepares m_BlockTypes and m_HeightMap data; zeroes out the light arrays */
void ReadChunks(int a_ChunkX, int a_ChunkZ);
/** Uses m_HeightMap to initialize the m_SkyLight[] data; fills in seeds for the skylight */
void PrepareSkyLight(void);
/** Uses m_BlockTypes to initialize the m_BlockLight[] data; fills in seeds for the blocklight */
void PrepareBlockLight(void);
/** Calculates light in the light array specified, using stored seeds */
void CalcLight(NIBBLETYPE * a_Light);
/** Does one step in the light calculation - one seed propagation and seed recalculation */
void CalcLightStep(
NIBBLETYPE * a_Light,
size_t a_NumSeedsIn, unsigned char * a_IsSeedIn, unsigned int * a_SeedIdxIn,
size_t & a_NumSeedsOut, unsigned char * a_IsSeedOut, unsigned int * a_SeedIdxOut
);
/** Compresses from 1-block-per-byte (faster calc) into 2-blocks-per-byte (MC storage): */
void CompressLight(NIBBLETYPE * a_LightArray, NIBBLETYPE * a_ChunkLight);
void PropagateLight(
NIBBLETYPE * a_Light,
unsigned int a_SrcIdx, unsigned int a_DstIdx,
size_t & a_NumSeedsOut, unsigned char * a_IsSeedOut, unsigned int * a_SeedIdxOut
);
/** Queues a chunkstay that has all of its chunks loaded.
Called by cLightingChunkStay when all of its chunks are loaded. */
void QueueChunkStay(cLightingChunkStay & a_ChunkStay);
} ;
| 2,042 |
1,781 | <reponame>acety23/algorithms-sedgewick-wayne
package chapter6.eventdrivensimulation;
import chapter2.section4.PriorityQueueResize;
import edu.princeton.cs.algs4.StdRandom;
import util.StdDraw3D;
// 1-To run this class, make sure to import the following libraries to the project (they are in the lib/java3d folder):
// jogl-all.jar
// gluegen-rt.jar
// j3dcore-jar
// j3dutils.jar
// vecmath.jar
// 2-Native libraries are also needed. If you are using a Mac, import the libraries:
// libgluegen-rt.jnilib
// libjogl_desktop.jnilib
// libnativewindow_awt.jnilib
// libnativewindow_macosx.jnilib
// libnewt.jnilib
// 3-If you are using any other operating system, import the libraries mentioned in
// https://jogamp.org/wiki/index.php/Downloading_and_installing_JOGL
// 4-Finally, set the VM Options parameter to point java.library.path to the location of your libraries.
// -Djava.library.path=./lib/java3d
// After running the code, you can click and drag the screen to view the different dimensions.
/**
* Created by <NAME> on 28/05/18.
*/
public class Exercise3 {
public class Particle3D {
private double positionX;
private double positionY;
private double positionZ;
private double velocityX;
private double velocityY;
private double velocityZ;
private double radius;
private double mass;
private int numberOfCollisions;
Particle3D() {
positionX = StdRandom.uniform(0.0, 1.0);
positionY = StdRandom.uniform(0.0, 1.0);
positionZ = StdRandom.uniform(0.0, 1.0);
velocityX = StdRandom.uniform(-0.005, 0.005);
velocityY = StdRandom.uniform(-0.005, 0.005);
velocityZ = StdRandom.uniform(-0.005, 0.005);
radius = 0.01;
mass = 0.5;
}
Particle3D(double positionX, double positionY, double positionZ, double velocityX, double velocityY,
double velocityZ, double radius, double mass) {
this.positionX = positionX;
this.positionY = positionY;
this.positionZ = positionZ;
this.velocityX = velocityX;
this.velocityY = velocityY;
this.velocityZ = velocityZ;
this.radius = radius;
this.mass = mass;
}
public void draw() {
StdDraw3D.drawSphere(positionX, positionY, positionZ, radius);
}
public void move(double time) {
positionX = positionX + (velocityX * time);
positionY = positionY + (velocityY * time);
positionZ = positionZ + (velocityZ * time);
}
public int count() {
return numberOfCollisions;
}
// Based on the explanation at https://algs4.cs.princeton.edu/61event/
public double timeToHit(Particle3D otherParticle) {
if (this == otherParticle) {
return Double.POSITIVE_INFINITY;
}
double deltaPositionX = otherParticle.positionX - positionX;
double deltaPositionY = otherParticle.positionY - positionY;
double deltaPositionZ = otherParticle.positionZ - positionZ;
double deltaVelocityX = otherParticle.velocityX - velocityX;
double deltaVelocityY = otherParticle.velocityY - velocityY;
double deltaVelocityZ = otherParticle.velocityZ - velocityZ;
double deltaPositionByDeltaVelocity = deltaPositionX * deltaVelocityX + deltaPositionY * deltaVelocityY
+ deltaPositionZ * deltaVelocityZ;
if (deltaPositionByDeltaVelocity > 0) {
return Double.POSITIVE_INFINITY;
}
double deltaVelocitySquared = deltaVelocityX * deltaVelocityX + deltaVelocityY * deltaVelocityY
+ deltaVelocityZ * deltaVelocityZ;
double deltaPositionSquared = deltaPositionX * deltaPositionX + deltaPositionY * deltaPositionY
+ deltaPositionZ * deltaPositionZ;
double distanceBetweenCenters = radius + otherParticle.radius;
double distanceBetweenCentersSquared = distanceBetweenCenters * distanceBetweenCenters;
// Check if particles overlap
if (deltaPositionSquared < distanceBetweenCentersSquared) {
throw new IllegalStateException("Invalid state: overlapping particles. No two objects can occupy the same space " +
"at the same time.");
}
double distance = (deltaPositionByDeltaVelocity * deltaPositionByDeltaVelocity)
- deltaVelocitySquared * (deltaPositionSquared - distanceBetweenCentersSquared);
if (distance < 0) {
return Double.POSITIVE_INFINITY;
}
return -(deltaPositionByDeltaVelocity + Math.sqrt(distance)) / deltaVelocitySquared;
}
public double timeToHitHorizontalWall() {
double distance;
if (velocityY < 0) {
// Get the distance as a negative number
distance = radius - positionY;
} else if (velocityY > 0) {
distance = 1 - radius - positionY;
} else {
return Double.POSITIVE_INFINITY;
}
return distance / velocityY;
}
public double timeToHitVerticalWall() {
double distance;
if (velocityX < 0) {
// Get the distance as a negative number
distance = radius - positionX;
} else if (velocityX > 0) {
distance = 1 - radius - positionX;
} else {
return Double.POSITIVE_INFINITY;
}
return distance / velocityX;
}
public double timeToHitThirdDimensionWall() {
double distance;
if (velocityZ < 0) {
// Get the distance as a negative number
distance = radius - positionZ;
} else if (velocityZ > 0) {
distance = 1 - radius - positionZ;
} else {
return Double.POSITIVE_INFINITY;
}
return distance / velocityZ;
}
// Based on the explanation at https://algs4.cs.princeton.edu/61event/
public void bounceOff(Particle3D otherParticle) {
double deltaPositionX = otherParticle.positionX - positionX;
double deltaPositionY = otherParticle.positionY - positionY;
double deltaPositionZ = otherParticle.positionZ - positionZ;
double deltaVelocityX = otherParticle.velocityX - velocityX;
double deltaVelocityY = otherParticle.velocityY - velocityY;
double deltaVelocityZ = otherParticle.velocityZ - velocityZ;
double deltaPositionByDeltaVelocity = deltaPositionX * deltaVelocityX + deltaPositionY * deltaVelocityY
+ deltaPositionZ * deltaVelocityZ;
double distanceBetweenCenters = radius + otherParticle.radius;
// Compute normal force
double magnitudeOfNormalForce = 2 * mass * otherParticle.mass * deltaPositionByDeltaVelocity
/ ((mass + otherParticle.mass) * distanceBetweenCenters);
double normalForceInXDirection = magnitudeOfNormalForce * deltaPositionX / distanceBetweenCenters;
double normalForceInYDirection = magnitudeOfNormalForce * deltaPositionY / distanceBetweenCenters;
double normalForceInZDirection = magnitudeOfNormalForce * deltaPositionZ / distanceBetweenCenters;
// Update velocities according to the normal force
velocityX += normalForceInXDirection / mass;
velocityY += normalForceInYDirection / mass;
velocityZ += normalForceInZDirection / mass;
otherParticle.velocityX -= normalForceInXDirection / otherParticle.mass;
otherParticle.velocityY -= normalForceInYDirection / otherParticle.mass;
otherParticle.velocityZ -= normalForceInZDirection / otherParticle.mass;
// Update collision counts
numberOfCollisions++;
otherParticle.numberOfCollisions++;
}
public void bounceOffHorizontalWall() {
velocityY = -velocityY;
numberOfCollisions++;
}
public void bounceOffVerticalWall() {
velocityX = -velocityX;
numberOfCollisions++;
}
public void bounceOffThirdDimensionWall() {
velocityZ = -velocityZ;
numberOfCollisions++;
}
// Kinetic energy = 1/2 * mass * velocity^2
public double kineticEnergy() {
return 0.5 * mass * (velocityX * velocityX + velocityY * velocityY + velocityZ * velocityZ);
}
}
private enum EventType {
PARTICLE_COLLISION, HORIZONTAL_WALL_COLLISION, VERTICAL_WALL_COLLISION, THIRD_DIMENSION_WALL_COLLISION, DRAW
}
public class CollisionSystem3D {
private class Event implements Comparable<Event> {
private final double time;
private final Particle3D particleA;
private final Particle3D particleB;
private final int collisionsCountA;
private final int collisionsCountB;
private final EventType eventType;
public Event(double time, Particle3D particleA, Particle3D particleB, EventType eventType) {
this.time = time;
this.particleA = particleA;
this.particleB = particleB;
this.eventType = eventType;
if (particleA != null) {
collisionsCountA = particleA.count();
} else {
collisionsCountA = -1;
}
if (particleB != null) {
collisionsCountB = particleB.count();
} else {
collisionsCountB = -1;
}
}
public int compareTo(Event otherEvent) {
if (this.time < otherEvent.time) {
return -1;
} else if (this.time > otherEvent.time) {
return +1;
} else {
return 0;
}
}
public boolean isValid() {
if (particleA != null && particleA.count() != collisionsCountA) {
return false;
}
if (particleB != null && particleB.count() != collisionsCountB) {
return false;
}
return true;
}
}
private PriorityQueueResize<Event> priorityQueue;
private double time;
private Particle3D[] particles;
public CollisionSystem3D(Particle3D[] particles) {
this.particles = particles;
}
private void predictCollisions(Particle3D particle3D, double limit) {
if (particle3D == null) {
return;
}
for (int i = 0; i < particles.length; i++) {
double deltaTime = particle3D.timeToHit(particles[i]);
if (time + deltaTime <= limit) {
priorityQueue.insert(new Event(time + deltaTime, particle3D, particles[i],
EventType.PARTICLE_COLLISION));
}
}
double deltaTimeVerticalWall = particle3D.timeToHitVerticalWall();
if (time + deltaTimeVerticalWall <= limit) {
priorityQueue.insert(new Event(time + deltaTimeVerticalWall, particle3D, null,
EventType.VERTICAL_WALL_COLLISION));
}
double deltaTimeHorizontalWall = particle3D.timeToHitHorizontalWall();
if (time + deltaTimeHorizontalWall <= limit) {
priorityQueue.insert(new Event(time + deltaTimeHorizontalWall, particle3D, null,
EventType.HORIZONTAL_WALL_COLLISION));
}
double deltaTimeThirdDimensionWall = particle3D.timeToHitThirdDimensionWall();
if (time + deltaTimeThirdDimensionWall <= limit) {
priorityQueue.insert(new Event(time + deltaTimeThirdDimensionWall, particle3D, null,
EventType.THIRD_DIMENSION_WALL_COLLISION));
}
}
public void redraw(double limit, double hertz) {
StdDraw3D.clear();
for (int i = 0; i < particles.length; i++) {
particles[i].draw();
}
StdDraw3D.pause(20);
StdDraw3D.show();
if (time < limit) {
priorityQueue.insert(new Event(time + 1.0 / hertz, null, null, EventType.DRAW));
}
}
public void simulate(double limit, double hertz) {
priorityQueue = new PriorityQueueResize<>(PriorityQueueResize.Orientation.MIN);
// Using a range of 0.15 to 0.85 to better visualize all 3 dimensions
StdDraw3D.setScale(0.15, 0.85);
for (int i = 0; i < particles.length; i++) {
predictCollisions(particles[i], limit);
}
priorityQueue.insert(new Event(0, null, null, EventType.DRAW)); // Add redraw event
while (!priorityQueue.isEmpty()) {
Event event = priorityQueue.deleteTop();
if (!event.isValid()) {
continue;
}
// Update particle positions
for (int i = 0; i < particles.length; i++) {
particles[i].move(event.time - time);
}
// Update time
time = event.time;
Particle3D particleA = event.particleA;
Particle3D particleB = event.particleB;
switch (event.eventType) {
case PARTICLE_COLLISION:
particleA.bounceOff(particleB);
break;
case HORIZONTAL_WALL_COLLISION:
particleA.bounceOffHorizontalWall();
break;
case VERTICAL_WALL_COLLISION:
particleA.bounceOffVerticalWall();
break;
case THIRD_DIMENSION_WALL_COLLISION:
particleA.bounceOffThirdDimensionWall();
break;
case DRAW:
redraw(limit, hertz);
break;
}
predictCollisions(particleA, limit);
predictCollisions(particleB, limit);
}
}
}
public static void main(String[] args) {
Exercise3 exercise3 = new Exercise3();
int numberOfParticles = 10;
Particle3D[] particles = new Particle3D[numberOfParticles];
for (int i = 0; i < numberOfParticles; i++) {
particles[i] = exercise3.new Particle3D();
}
CollisionSystem3D collisionSystem3D = exercise3.new CollisionSystem3D(particles);
collisionSystem3D.simulate(10000, 0.5);
}
}
| 7,135 |
2,338 | //===- DWARFDebugInfoEntry.cpp --------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h"
#include "llvm/ADT/Optional.h"
#include "llvm/DebugInfo/DWARF/DWARFContext.h"
#include "llvm/DebugInfo/DWARF/DWARFDebugAbbrev.h"
#include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
#include "llvm/DebugInfo/DWARF/DWARFUnit.h"
#include "llvm/Support/DataExtractor.h"
#include <cstddef>
#include <cstdint>
using namespace llvm;
using namespace dwarf;
bool DWARFDebugInfoEntry::extractFast(const DWARFUnit &U, uint64_t *OffsetPtr,
const DWARFDataExtractor &DebugInfoData,
uint64_t UEndOffset, uint32_t ParentIdx) {
Offset = *OffsetPtr;
this->ParentIdx = ParentIdx;
if (Offset >= UEndOffset) {
U.getContext().getWarningHandler()(
createStringError(errc::invalid_argument,
"DWARF unit from offset 0x%8.8" PRIx64 " incl. "
"to offset 0x%8.8" PRIx64 " excl. "
"tries to read DIEs at offset 0x%8.8" PRIx64,
U.getOffset(), U.getNextUnitOffset(), *OffsetPtr));
return false;
}
assert(DebugInfoData.isValidOffset(UEndOffset - 1));
uint64_t AbbrCode = DebugInfoData.getULEB128(OffsetPtr);
if (0 == AbbrCode) {
// NULL debug tag entry.
AbbrevDecl = nullptr;
return true;
}
const auto *AbbrevSet = U.getAbbreviations();
if (!AbbrevSet) {
U.getContext().getWarningHandler()(
createStringError(errc::invalid_argument,
"DWARF unit at offset 0x%8.8" PRIx64 " "
"contains invalid abbreviation set offset 0x%" PRIx64,
U.getOffset(), U.getAbbreviationsOffset()));
// Restore the original offset.
*OffsetPtr = Offset;
return false;
}
AbbrevDecl = AbbrevSet->getAbbreviationDeclaration(AbbrCode);
if (!AbbrevDecl) {
U.getContext().getWarningHandler()(
createStringError(errc::invalid_argument,
"DWARF unit at offset 0x%8.8" PRIx64 " "
"contains invalid abbreviation %" PRIu64 " at "
"offset 0x%8.8" PRIx64 ", valid abbreviations are %s",
U.getOffset(), AbbrCode, *OffsetPtr,
AbbrevSet->getCodeRange().c_str()));
// Restore the original offset.
*OffsetPtr = Offset;
return false;
}
// See if all attributes in this DIE have fixed byte sizes. If so, we can
// just add this size to the offset to skip to the next DIE.
if (Optional<size_t> FixedSize = AbbrevDecl->getFixedAttributesByteSize(U)) {
*OffsetPtr += *FixedSize;
return true;
}
// Skip all data in the .debug_info for the attributes
for (const auto &AttrSpec : AbbrevDecl->attributes()) {
// Check if this attribute has a fixed byte size.
if (auto FixedSize = AttrSpec.getByteSize(U)) {
// Attribute byte size if fixed, just add the size to the offset.
*OffsetPtr += *FixedSize;
} else if (!DWARFFormValue::skipValue(AttrSpec.Form, DebugInfoData,
OffsetPtr, U.getFormParams())) {
// We failed to skip this attribute's value, restore the original offset
// and return the failure status.
U.getContext().getWarningHandler()(createStringError(
errc::invalid_argument,
"DWARF unit at offset 0x%8.8" PRIx64 " "
"contains invalid FORM_* 0x%" PRIx16 " at offset 0x%8.8" PRIx64,
U.getOffset(), AttrSpec.Form, *OffsetPtr));
*OffsetPtr = Offset;
return false;
}
}
return true;
}
| 1,749 |
852 | #include "FWCore/Utilities/interface/thread_safety_macros.h"
CMS_THREAD_SAFE extern int external_int;
| 38 |
734 | <filename>modules/3rd_party/rpmalloc/rpallocator.cpp<gh_stars>100-1000
/*
,--. ,--. ,--. ,--.
,-' '-.,--.--.,--,--.,---.| |,-.,-' '-.`--' ,---. ,--,--, Copyright 2018
'-. .-'| .--' ,-. | .--'| /'-. .-',--.| .-. || \ Tracktion Software
| | | | \ '-' \ `--.| \ \ | | | |' '-' '| || | Corporation
`---' `--' `--`--'`---'`--'`--' `---' `--' `---' `--''--' www.tracktion.com
Tracktion Engine uses a GPL/commercial licence - see LICENCE.md for details.
*/
#if defined (__clang__) || defined (__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wzero-as-null-pointer-constant"
#pragma GCC diagnostic ignored "-Wunused-variable"
#if ! defined (__clang__)
#if __GNUC__ >= 8
#pragma GCC diagnostic ignored "-Wclass-memaccess"
#endif
#endif
#endif
extern "C"
{
#include "../../3rd_party/rpmalloc/rpmalloc.c"
}
#if defined (__clang__) || defined (__GNUC__)
#pragma GCC diagnostic pop
#endif
| 459 |
1,882 | /*-
* <<
* task
* ==
* Copyright (C) 2019 - 2020 sia
* ==
* 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.sia.task.quartz.core;
import com.sia.task.quartz.exception.SchedulerException;
import java.util.Collection;
/**
* Provides a mechanism for obtaining client-usable handles to <code>Scheduler</code>
* instances.
*
* @see Scheduler
* @see StdSchedulerFactory
*
* @author @see Quartz
* @data 2019-06-24 17:08
* @version V1.0.0
**/
public interface SchedulerFactory {
/**
* <p>
* Returns a client-usable handle to a <code>Scheduler</code>.
* </p>
*
* @throws SchedulerException
* if there is a problem with the underlying <code>Scheduler</code>.
*/
Scheduler getScheduler() throws SchedulerException;
/**
* <p>
* Returns a handle to the Scheduler with the given name, if it exists.
* </p>
*/
Scheduler getScheduler(String schedName) throws SchedulerException;
/**
* <p>
* Returns handles to all known Schedulers (made by any SchedulerFactory
* within this jvm.).
* </p>
*/
Collection<Scheduler> getAllSchedulers() throws SchedulerException;
}
| 584 |
861 | package cn.springcloud.gray.decision.factory;
import org.springframework.beans.BeanUtils;
public abstract class AbstractGrayDecisionFactory<C> implements GrayDecisionFactory<C> {
private Class<C> configClass;
protected AbstractGrayDecisionFactory(Class<C> configClass) {
this.configClass = configClass;
}
public Class<C> getConfigClass() {
return configClass;
}
public C newConfig() {
return BeanUtils.instantiateClass(getConfigClass());
}
}
| 175 |
575 | <filename>chrome/browser/search_engines/chrome_template_url_service_client.h
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_SEARCH_ENGINES_CHROME_TEMPLATE_URL_SERVICE_CLIENT_H_
#define CHROME_BROWSER_SEARCH_ENGINES_CHROME_TEMPLATE_URL_SERVICE_CLIENT_H_
#include "base/macros.h"
#include "base/scoped_observer.h"
#include "components/history/core/browser/history_service.h"
#include "components/history/core/browser/history_service_observer.h"
#include "components/search_engines/template_url_service_client.h"
// ChromeTemplateURLServiceClient provides keyword related history
// functionality for TemplateURLService.
class ChromeTemplateURLServiceClient : public TemplateURLServiceClient,
public history::HistoryServiceObserver {
public:
explicit ChromeTemplateURLServiceClient(
history::HistoryService* history_service);
~ChromeTemplateURLServiceClient() override;
// TemplateURLServiceClient:
void Shutdown() override;
void SetOwner(TemplateURLService* owner) override;
void DeleteAllSearchTermsForKeyword(history::KeywordID keyword_Id) override;
void SetKeywordSearchTermsForURL(const GURL& url,
TemplateURLID id,
const std::u16string& term) override;
void AddKeywordGeneratedVisit(const GURL& url) override;
// history::HistoryServiceObserver:
void OnURLVisited(history::HistoryService* history_service,
ui::PageTransition transition,
const history::URLRow& row,
const history::RedirectList& redirects,
base::Time visit_time) override;
private:
TemplateURLService* owner_;
ScopedObserver<history::HistoryService, history::HistoryServiceObserver>
history_service_observer_{this};
history::HistoryService* history_service_;
DISALLOW_COPY_AND_ASSIGN(ChromeTemplateURLServiceClient);
};
#endif // CHROME_BROWSER_SEARCH_ENGINES_CHROME_TEMPLATE_URL_SERVICE_CLIENT_H_
| 803 |
436 | {
"id": "paste-that-shizz",
"name": "Paste That Shizz",
"version": "0.0.1pre1",
"minAppVersion": "0.9.12",
"description": "Adds a paste command for when pasting is hard",
"author": "shabegom",
"authorUrl": "https://shbgm.ca",
"isDesktopOnly": false
}
| 118 |
763 | package org.batfish.coordinator.resources;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import org.batfish.referencelibrary.ServiceEndpoint;
import org.junit.Test;
public class ServiceEndpointBeanTest {
@Test
public void conversionToAndFrom() {
ServiceEndpoint endpoint = new ServiceEndpoint("address", "sep", "service");
ServiceEndpointBean bean = new ServiceEndpointBean(endpoint);
assertThat(new ServiceEndpointBean(bean.toServiceEndpoint()), equalTo(bean));
}
}
| 167 |
346 | <reponame>FluffyQuack/ja2-stracciatella<gh_stars>100-1000
#include "JA2Types.h"
enum BloodKind
{
HUMAN = 0,
CREATURE_ON_FLOOR = 1,
CREATURE_ON_ROOF = 2
};
#define NORMAL_HUMAN_SMELL_STRENGTH 10
#define COW_SMELL_STRENGTH 15
#define NORMAL_CREATURE_SMELL_STRENGTH 20
#define SMELL_TYPE_NUM_BITS 2
#define SMELL_TYPE( s ) (s & 0x01)
#define SMELL_STRENGTH( s ) ((s & 0xFC) >> SMELL_TYPE_NUM_BITS)
#define MAXBLOODQUANTITY 7
#define BLOODDIVISOR 10
void DecaySmells();
void DecayBloodAndSmells( UINT32 uiTime );
void DropSmell(SOLDIERTYPE&);
void DropBlood(SOLDIERTYPE const&, UINT8 strength);
void UpdateBloodGraphics(GridNo, INT8 level);
void RemoveBlood(GridNo, INT8 level);
void InternalDropBlood(GridNo, INT8 level, BloodKind, UINT8 strength, INT8 visible);
| 352 |
335 | <reponame>OotinnyoO1/N64Wasm
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Mupen64plus - ri_controller.h *
* Mupen64Plus homepage: http://code.google.com/p/mupen64plus/ *
* Copyright (C) 2014 <NAME> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#ifndef M64P_RI_RI_CONTROLLER_H
#define M64P_RI_RI_CONTROLLER_H
#include <stdint.h>
#include "rdram.h"
#ifndef RI_REG
#define RI_REG(a) ((a & 0xffff) >> 2)
#endif
enum ri_registers
{
RI_MODE_REG,
RI_CONFIG_REG,
RI_CURRENT_LOAD_REG,
RI_SELECT_REG,
RI_REFRESH_REG,
RI_LATENCY_REG,
RI_ERROR_REG,
RI_WERROR_REG,
RI_REGS_COUNT
};
struct ri_controller
{
uint32_t regs[RI_REGS_COUNT];
struct rdram rdram;
};
void init_ri(struct ri_controller* ri,
uint32_t* dram,
size_t dram_size);
void poweron_ri(struct ri_controller* ri);
int read_ri_regs(void* opaque, uint32_t address, uint32_t* value);
int write_ri_regs(void* opaque, uint32_t address, uint32_t value, uint32_t mask);
#endif
| 1,202 |
1,338 | /*
* Copyright (c) 2002-2011, Haiku Project. All rights reserved.
* Distributed under the terms of the Haiku license.
*
* Author(s):
* <NAME> (<EMAIL>)
*/
#include <signal.h>
#include <errno.h>
#include <OS.h>
#include <syscall_utils.h>
int
raise(int sig)
{
RETURN_AND_SET_ERRNO(send_signal(find_thread(NULL), sig));
}
| 136 |
3,384 | //
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>.
//
#pragma mark Blocks
typedef void (^CDUnknownBlockType)(void); // return type and parameters are unknown
#pragma mark Named Structures
struct CGPoint {
double x;
double y;
};
struct CGRect {
struct CGPoint origin;
struct CGSize size;
};
struct CGSize {
double width;
double height;
};
struct DTBucketTag {
struct DTBucketTag *_field1;
struct DTBucketTag *_field2;
struct DTBucketTag *_field3;
id _field4;
};
struct _NSRange {
unsigned long long _field1;
unsigned long long _field2;
};
#pragma mark Typedef'd Structures
typedef struct {
unsigned long long _field1;
id *_field2;
unsigned long long *_field3;
unsigned long long _field4[5];
} CDStruct_70511ce9;
typedef struct {
double top;
double bottom;
double left;
double right;
} CDStruct_f6c3f719;
typedef struct {
long long version;
CDUnknownFunctionPointerType retain;
CDUnknownFunctionPointerType release;
CDUnknownFunctionPointerType copyDescription;
CDUnknownFunctionPointerType equal;
CDUnknownFunctionPointerType hash;
} CDStruct_f2932e27;
typedef struct {
long long version;
CDUnknownFunctionPointerType retain;
CDUnknownFunctionPointerType release;
CDUnknownFunctionPointerType copyDescription;
CDUnknownFunctionPointerType equal;
} CDStruct_b3b3fc87;
#pragma mark -
//
// File: /Applications/Xcode.app/Contents/OtherFrameworks/DevToolsKit.framework/Versions/A/DevToolsKit
// UUID: C6029188-C0C7-3A8C-8347-3E9DD7F1342F
//
// Arch: x86_64
// Current version: 6000.0.0
// Compatibility version: 1.0.0
// Source version: 6000.0.0.0.0
// Minimum Mac OS X version: 10.10.0
// SDK version: 10.10.0
//
// Objective-C Garbage Collection: Unsupported
//
@protocol DTDraggingInfo <NSDraggingInfo>
- (struct CGPoint)draggingLocationOnScreen;
- (NSDictionary *)draggingSourceContext;
- (void)setDraggedImageStateNeedsUpdate:(BOOL)arg1;
- (struct CGSize)draggingStickiness;
- (void)setDraggingStickiness:(struct CGSize)arg1;
- (DTDraggedImageState *)draggedImageState;
@end
@protocol NSAnimationDelegate <NSObject>
@optional
- (void)animation:(NSAnimation *)arg1 didReachProgressMark:(float)arg2;
- (float)animation:(NSAnimation *)arg1 valueForProgress:(float)arg2;
- (void)animationDidEnd:(NSAnimation *)arg1;
- (void)animationDidStop:(NSAnimation *)arg1;
- (BOOL)animationShouldStart:(NSAnimation *)arg1;
@end
@protocol NSCoding
- (id)initWithCoder:(NSCoder *)arg1;
- (void)encodeWithCoder:(NSCoder *)arg1;
@end
@protocol NSCopying
- (id)copyWithZone:(struct _NSZone *)arg1;
@end
@protocol NSDraggingInfo <NSObject>
@property long long numberOfValidItemsForDrop;
@property BOOL animatesToDestination;
@property long long draggingFormation;
- (void)enumerateDraggingItemsWithOptions:(unsigned long long)arg1 forView:(NSView *)arg2 classes:(NSArray *)arg3 searchOptions:(NSDictionary *)arg4 usingBlock:(void (^)(NSDraggingItem *, long long, char *))arg5;
- (NSArray *)namesOfPromisedFilesDroppedAtDestination:(NSURL *)arg1;
- (void)slideDraggedImageTo:(struct CGPoint)arg1;
- (long long)draggingSequenceNumber;
- (id)draggingSource;
- (NSPasteboard *)draggingPasteboard;
- (NSImage *)draggedImage;
- (struct CGPoint)draggedImageLocation;
- (struct CGPoint)draggingLocation;
- (unsigned long long)draggingSourceOperationMask;
- (NSWindow *)draggingDestinationWindow;
@end
@protocol NSObject
@property(readonly, copy) NSString *description;
@property(readonly) Class superclass;
@property(readonly) unsigned long long hash;
- (struct _NSZone *)zone;
- (unsigned long long)retainCount;
- (id)autorelease;
- (oneway void)release;
- (id)retain;
- (BOOL)respondsToSelector:(SEL)arg1;
- (BOOL)conformsToProtocol:(Protocol *)arg1;
- (BOOL)isMemberOfClass:(Class)arg1;
- (BOOL)isKindOfClass:(Class)arg1;
- (BOOL)isProxy;
- (id)performSelector:(SEL)arg1 withObject:(id)arg2 withObject:(id)arg3;
- (id)performSelector:(SEL)arg1 withObject:(id)arg2;
- (id)performSelector:(SEL)arg1;
- (id)self;
- (Class)class;
- (BOOL)isEqual:(id)arg1;
@optional
@property(readonly, copy) NSString *debugDescription;
@end
@protocol NSOutlineViewDataSource <NSObject>
@optional
- (NSArray *)outlineView:(NSOutlineView *)arg1 namesOfPromisedFilesDroppedAtDestination:(NSURL *)arg2 forDraggedItems:(NSArray *)arg3;
- (BOOL)outlineView:(NSOutlineView *)arg1 acceptDrop:(id <NSDraggingInfo>)arg2 item:(id)arg3 childIndex:(long long)arg4;
- (unsigned long long)outlineView:(NSOutlineView *)arg1 validateDrop:(id <NSDraggingInfo>)arg2 proposedItem:(id)arg3 proposedChildIndex:(long long)arg4;
- (void)outlineView:(NSOutlineView *)arg1 updateDraggingItemsForDrag:(id <NSDraggingInfo>)arg2;
- (BOOL)outlineView:(NSOutlineView *)arg1 writeItems:(NSArray *)arg2 toPasteboard:(NSPasteboard *)arg3;
- (void)outlineView:(NSOutlineView *)arg1 draggingSession:(NSDraggingSession *)arg2 endedAtPoint:(struct CGPoint)arg3 operation:(unsigned long long)arg4;
- (void)outlineView:(NSOutlineView *)arg1 draggingSession:(NSDraggingSession *)arg2 willBeginAtPoint:(struct CGPoint)arg3 forItems:(NSArray *)arg4;
- (id <NSPasteboardWriting>)outlineView:(NSOutlineView *)arg1 pasteboardWriterForItem:(id)arg2;
- (void)outlineView:(NSOutlineView *)arg1 sortDescriptorsDidChange:(NSArray *)arg2;
- (id)outlineView:(NSOutlineView *)arg1 persistentObjectForItem:(id)arg2;
- (id)outlineView:(NSOutlineView *)arg1 itemForPersistentObject:(id)arg2;
- (void)outlineView:(NSOutlineView *)arg1 setObjectValue:(id)arg2 forTableColumn:(NSTableColumn *)arg3 byItem:(id)arg4;
- (id)outlineView:(NSOutlineView *)arg1 objectValueForTableColumn:(NSTableColumn *)arg2 byItem:(id)arg3;
- (BOOL)outlineView:(NSOutlineView *)arg1 isItemExpandable:(id)arg2;
- (id)outlineView:(NSOutlineView *)arg1 child:(long long)arg2 ofItem:(id)arg3;
- (long long)outlineView:(NSOutlineView *)arg1 numberOfChildrenOfItem:(id)arg2;
@end
@interface DTAbstractAssetGroup : NSObject
{
NSString *displayName;
DTAbstractAssetGroup *parentGroup;
DTMutableOrderedSet *childGroups;
DTAssetCategory *category;
BOOL displayNameIsEditable;
NSImage *image;
}
+ (id)assetGroupWithPropertyListRepresentation:(id)arg1 assetCategory:(id)arg2 andIdentifiedAssets:(id)arg3;
+ (id)defaultImage;
- (id)description;
- (void)describeInto:(id)arg1 withDepth:(long long)arg2;
- (BOOL)containsAsset:(id)arg1;
- (void)removeAllAssets;
- (void)removeAsset:(id)arg1;
- (void)addAsset:(id)arg1;
- (void)insertAsset:(id)arg1 atIndex:(long long)arg2;
- (id)deepAssets;
- (id)assetsEnumerator;
- (id)assets;
- (long long)numberOfAssets;
- (BOOL)assetsAreEditable;
- (id)firstChildGroupWithDisplayName:(id)arg1;
- (id)deepChildGroups;
- (long long)depth;
- (id)ancestors;
- (id)lineage;
- (id)displayNamePath;
- (id)indexPath;
- (BOOL)isLeafGroup;
- (long long)numberOfChildGroups;
- (void)setChildGroups:(id)arg1;
- (id)childGroupsEnumerator;
- (id)childGroups;
- (long long)indexOfGroup:(id)arg1;
- (void)removeAllGroups;
- (void)removeChildGroup:(id)arg1;
- (void)addChildGroup:(id)arg1;
- (void)insertChildGroup:(id)arg1 atIndex:(long long)arg2;
- (id)parentGroup;
- (void)setParentGroup:(id)arg1;
- (BOOL)groupsAreEditable;
- (void)didChangeGroups;
- (void)willChangeGroups;
- (void)didChangeAssets;
- (void)willChangeAssets;
- (void)setDisplayNameIsEditable:(BOOL)arg1;
- (BOOL)displayNameIsEditable;
- (void)setDisplayName:(id)arg1;
- (id)displayName;
- (void)setImage:(id)arg1;
- (id)image;
- (id)assetCategory;
- (void)dealloc;
- (void)buildPropertyListRepresentation:(id)arg1;
- (id)propertyListRepresentation;
- (id)initWithPropertyListRepresentation:(id)arg1 assetCategory:(id)arg2 andIdentifiedAssets:(id)arg3;
- (id)initWithDisplayName:(id)arg1 andAssetCategory:(id)arg2;
@end
@interface DTAsset : NSObject
{
NSAttributedString *detailedDescription;
NSAttributedString *detailedLabel;
NSString *shortDescription;
NSString *label;
NSString *subtitle;
NSString *identifier;
NSImage *image;
id representedObject;
DTMutableOrderedSet *knownGroups;
NSDate *lastUsedDate;
DTAssetCategory *category;
BOOL selected;
}
- (id)searchTerms;
- (double)timeIntervalSinceUsed;
- (id)knownGroups;
- (void)setCategory:(id)arg1;
- (id)assetCategory;
- (void)setLastUsedDate:(id)arg1;
- (id)lastUsedDate;
- (void)setIdentifier:(id)arg1;
- (id)identifier;
- (BOOL)isSelected;
- (void)setSelected:(BOOL)arg1;
- (id)representedObject;
- (void)setRepresentedObject:(id)arg1;
- (void)setSubtitle:(id)arg1;
- (id)subtitle;
- (void)setLabel:(id)arg1;
- (id)label;
- (void)setShortDescription:(id)arg1;
- (id)shortDescription;
- (void)setImage:(id)arg1;
- (id)image;
- (void)setDetailedLabel:(id)arg1;
- (id)detailedLabel;
- (void)setDetailedDescription:(id)arg1;
- (id)detailedDescription;
- (void)dealloc;
- (id)initWithIdentifier:(id)arg1;
- (void)removeKnownGroup:(id)arg1;
- (void)addKnownGroup:(id)arg1;
@end
@interface DTAssetAndGroupSet : NSObject
{
NSSet *groups;
DTAssetView *view;
DTAsset *asset;
BOOL isObservingAsset;
}
+ (id)observedAsssetKeyPaths;
- (void)assetViewWillDraw:(id)arg1;
- (void)observeValueForKeyPath:(id)arg1 ofObject:(id)arg2 change:(id)arg3 context:(void *)arg4;
- (BOOL)isEqual:(id)arg1;
- (BOOL)isEqualToAssetAndGroupSet:(id)arg1;
- (unsigned long long)hash;
- (id)asset;
- (id)view;
- (id)groups;
- (void)dealloc;
- (id)initWithAsset:(id)arg1 andGroups:(id)arg2;
@end
@interface DTAssetCategory : NSObject
{
DTAbstractAssetGroup *rootGroup;
DTAbstractAssetGroup *everythingGroup;
NSMutableArray *orderedAssetSourceIdentifiers;
NSMutableDictionary *assetSourceGroupsByAssetSourceID;
NSMutableDictionary *identifiedAssets;
NSString *displayName;
NSString *identifier;
DTAssetCategoryController *assetCategoryController;
}
+ (BOOL)isiLifeAssetCategory:(id)arg1;
+ (id)iMovieAssetCategory;
+ (id)iPhotoAssetCategory;
+ (id)regularGroupImage;
+ (id)smartGroupImage;
+ (id)everythingGroupImage;
+ (id)assetSourceGroupImage;
- (void)removeAllAssets;
- (void)removeAsset:(id)arg1;
- (void)addAsset:(id)arg1 toAssetSourceWithIdentifier:(id)arg2 subpath:(id)arg3;
- (id)assetWithIdentifier:(id)arg1;
- (id)groupWithDisplayPath:(id)arg1 fromGroup:(id)arg2 create:(BOOL)arg3;
- (void)setImage:(id)arg1 forAssetSourceWithIdentifier:(id)arg2 subpath:(id)arg3;
- (void)setDisplayName:(id)arg1 forAssetSourceWithIdentifier:(id)arg2;
- (void)removeSubpath:(id)arg1 fromAssetSourceWithIdentifier:(id)arg2;
- (id)subpathsForAssetSourceWithIdentifier:(id)arg1;
- (void)setLibraryGroupImage:(id)arg1;
- (void)setLibraryGroupDisplayName:(id)arg1;
- (void)removeAssetSourceWithIdentifier:(id)arg1;
- (void)addAssetSourceWithIdentifier:(id)arg1 andDisplayName:(id)arg2;
- (void)insertAssetSourceWithIdentifier:(id)arg1 andDisplayName:(id)arg2 atIndex:(long long)arg3;
- (void)setOrderedAssetSourceIdentifiers:(id)arg1;
- (id)orderedAssetSourceIdentifiers;
- (BOOL)containsAssetSourceWithIdentifier:(id)arg1;
- (BOOL)containsAssetWithIdentifier:(id)arg1;
- (id)assetGroupForAssetSourceWithIdentifier:(id)arg1;
- (id)everythingGroup;
- (id)rootGroup;
- (id)assets;
- (id)identifiedAssets;
- (id)displayName;
- (id)identifier;
- (id)assetCategoryController;
- (void)setAssetCategoryController:(id)arg1;
- (void)dealloc;
- (id)initWithIdentifier:(id)arg1 andDisplayName:(id)arg2;
- (id)placeholderImage;
@end
@interface DTAssetCategoryController : NSObject <NSOutlineViewDataSource>
{
DTAssetDetailTextView *defaultAssetDetailView;
DTAssetCategory *assetCategory;
DTAssetLibrary *library;
NSArray *draggedPairs;
NSArray *draggedGroups;
BOOL acceptedDraggedAssets;
id delegate;
struct CGSize initialDraggingOffset;
}
- (void)refreshAssetDetailView:(id)arg1 withAsset:(id)arg2;
- (void)assetAndGroupSet:(id)arg1 willDisplayAsset:(id)arg2 inAssetView:(id)arg3;
- (void)sizeAssetDetailView:(id)arg1 toFitSuggestedSize:(struct CGSize)arg2 forAsset:(id)arg3;
- (id)assetDetailViewForAsset:(id)arg1;
- (id)defaultAssetDetailView;
- (id)defaultAssetDetailViewIfCreated;
- (void)performRemoveAssetsFromLibrary:(id)arg1;
- (BOOL)canPerformRemoveAssetFromLibrary:(id)arg1;
- (BOOL)canPerformEditAsset:(id)arg1;
- (void)performEditAsset:(id)arg1;
- (id)searchTermsForAsset:(id)arg1;
- (id)objectPasteboardTypes;
- (id)assetGroupPasteboardType;
- (id)assetPasteboardType;
- (void)setDraggedPairs:(id)arg1;
- (id)draggedPairs;
- (id)draggedAssets;
- (void)setDraggedGroups:(id)arg1;
- (id)draggedGroups;
- (void)setDelegate:(id)arg1;
- (id)delegate;
- (void)setLibrary:(id)arg1;
- (id)library;
- (id)assetCategory;
- (void)dealloc;
- (id)initWithAssetCategory:(id)arg1;
- (id)libraryWindow;
- (id)assetTileViewForceSynchronizedContent:(BOOL)arg1;
- (id)assetTileViewContent;
- (id)groupOutlineView;
- (id)groupedTileView:(id)arg1 draggedImageState:(id)arg2;
- (void)groupedTileView:(id)arg1 concludeDragOperation:(id)arg2;
- (BOOL)groupedTileView:(id)arg1 performDragOperation:(id)arg2;
- (BOOL)groupedTileView:(id)arg1 prepareForDragOperation:(id)arg2;
- (void)groupedTileView:(id)arg1 draggingExited:(id)arg2;
- (unsigned long long)groupedTileView:(id)arg1 draggingEntered:(id)arg2;
- (unsigned long long)groupedTileView:(id)arg1 draggingUpdated:(id)arg2;
- (unsigned long long)calculateAssetViewDragOperation:(id)arg1 targetGroup:(id *)arg2 targetIndex:(long long *)arg3;
- (id)outlineView:(id)arg1 draggedImageState:(id)arg2;
- (BOOL)outlineView:(id)arg1 acceptDrop:(id)arg2 item:(id)arg3 childIndex:(long long)arg4;
- (unsigned long long)outlineView:(id)arg1 validateDrop:(id)arg2 proposedItem:(id)arg3 proposedChildIndex:(long long)arg4;
- (id)deserializeGroupsFromPropertyLists:(id)arg1;
- (unsigned long long)draggingOperationForDragInfo:(id)arg1 withTargetGroup:(id)arg2 targetCanBeMoveWithinGroup:(BOOL)arg3;
- (void)addObjectsFromDraggingInfo:(id)arg1 toGroup:(id)arg2;
- (void)insertObjectsFromDraggingInfo:(id)arg1 intoGroup:(id)arg2 atIndex:(long long)arg3;
- (void)runImagePickerWithImage:(id)arg1 asset:(id)arg2 assetSourceIdentifier:(id)arg3 group:(id)arg4 andIndex:(long long)arg5;
- (void)assetEditorController:(id)arg1 finishedEditingAsset:(id)arg2 returnCode:(long long)arg3 context:(id)arg4;
- (id)addAssetsFromDraggingInfo:(id)arg1 toGroup:(id)arg2 copy:(BOOL)arg3;
- (id)insertAssetsFromDraggingInfo:(id)arg1 intoGroup:(id)arg2 atIndex:(long long)arg3 copy:(BOOL)arg4;
- (struct CGSize)window:(id)arg1 draggingStickiness:(id)arg2;
- (id)window:(id)arg1 draggedImageState:(id)arg2;
- (void)window:(id)arg1 draggingEnded:(id)arg2;
- (void)window:(id)arg1 concludeDragOperation:(id)arg2;
- (BOOL)window:(id)arg1 performDragOperation:(id)arg2;
- (BOOL)window:(id)arg1 prepareForDragOperation:(id)arg2;
- (void)window:(id)arg1 draggingExited:(id)arg2;
- (unsigned long long)window:(id)arg1 draggingUpdated:(id)arg2;
- (unsigned long long)window:(id)arg1 draggingEntered:(id)arg2;
- (void)registerForDropTypes;
- (void)assetDetailView:(id)arg1 beginDraggingWithMouseDownEvent:(id)arg2 andMouseDraggedEvent:(id)arg3;
- (void)groupedTileViewDragSelectedItems:(id)arg1 withMouseDownEvent:(id)arg2 andMouseDraggedEvent:(id)arg3;
- (id)draggedImageStateForAssetGroupPairs:(id)arg1 draggedPair:(id)arg2 referenceRectForClickedItem:(struct CGRect *)arg3;
- (BOOL)outlineView:(id)arg1 writeItems:(id)arg2 toPasteboard:(id)arg3;
- (id)representativesForDraggedGroups:(id)arg1;
- (id)groupsForOutlineItems:(id)arg1;
- (void)draggedImage:(id)arg1 endedAt:(struct CGPoint)arg2 operation:(unsigned long long)arg3 withException:(id)arg4 shouldSlideBack:(char *)arg5;
- (void)dragAssetPairs:(id)arg1 withMouseDownEvent:(id)arg2 mouseDraggedEvent:(id)arg3 initialDraggedImageState:(id)arg4 allowedOperations:(unsigned long long)arg5 imageLocationInWindow:(struct CGPoint)arg6;
- (void)populatePasteboard:(id)arg1 withAssetAndCategoryPairs:(id)arg2 defaultDraggedImageState:(id *)arg3 identifierMapTable:(id *)arg4;
- (id)defaultDragImageState:(id)arg1;
- (id)initialDragImageState:(id)arg1;
- (id)smartAssetGroupRuleEditorController:(id)arg1 createViewForSmartRuleViewID:(id)arg2;
- (id)smartAssetGroupRuleEditorControllerRuleDefinitionsPropertyList:(id)arg1;
- (id)createViewForSmartRuleViewID:(id)arg1;
- (id)smartGroupRuleDefinitionsPropertyList;
- (id)operatorsForType:(id)arg1;
- (id)inputFieldForType:(id)arg1;
// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;
@end
@interface DTAssetDetailImageView : NSImageView
{
NSString *_imagePath;
NSEvent *_downEvent;
DTFirstResponderDrawingStrategy *firstResponderDrawingStrategy;
BOOL showsFirstResponder;
}
- (unsigned long long)draggingSourceOperationMaskForLocal:(BOOL)arg1;
- (void)viewWillMoveToWindow:(id)arg1;
- (BOOL)resignFirstResponder;
- (BOOL)becomeFirstResponder;
- (BOOL)acceptsFirstResponder;
- (BOOL)showsFirstResponder;
- (void)setShowsFirstResponder:(BOOL)arg1;
- (id)imagePath;
- (void)setImagePath:(id)arg1;
- (void)mouseDragged:(id)arg1;
- (void)mouseDown:(id)arg1;
- (void)_setDownEvent:(id)arg1;
- (BOOL)acceptsFirstMouse:(id)arg1;
- (BOOL)validateMenuItem:(id)arg1;
- (void)copy:(id)arg1;
- (void)dealloc;
- (id)initWithCoder:(id)arg1;
- (id)initWithFrame:(struct CGRect)arg1;
@end
@interface DTAssetDetailTextView : NSTextView
{
DTFirstResponderDrawingStrategy *firstResponderDrawingStrategy;
BOOL showsFirstResponder;
}
- (void)viewWillMoveToWindow:(id)arg1;
- (BOOL)resignFirstResponder;
- (BOOL)becomeFirstResponder;
- (BOOL)showsFirstResponder;
- (void)setShowsFirstResponder:(BOOL)arg1;
- (void)dealloc;
- (id)initWithCoder:(id)arg1;
- (id)initWithFrame:(struct CGRect)arg1;
@end
@interface DTAssetDetailView : NSView
{
NSImage *image;
NSAttributedString *label;
NSString *helpIdentifier;
NSView *helpButton;
NSEvent *lastMouseDown;
NSView *contentView;
BOOL sizingToFit;
id delegate;
BOOL pressed;
}
- (void)mouseDragged:(id)arg1;
- (void)mouseUp:(id)arg1;
- (void)mouseDown:(id)arg1;
- (BOOL)acceptsFirstMouse:(id)arg1;
- (void)viewDidMoveToSuperview;
- (void)viewWillMoveToSuperview:(id)arg1;
- (void)superviewFrameDidChange:(id)arg1;
- (void)takeLabelFromString:(id)arg1;
- (id)basicLabelAttributes;
- (void)setFrameSize:(struct CGSize)arg1;
- (void)sizeToFit;
- (void)sizeToFitWidth:(double)arg1;
- (struct CGSize)suggestedSize;
- (double)headerHeight;
- (void)contentViewFrameDidChange:(id)arg1;
- (void)resizeSubviewsWithOldSize:(struct CGSize)arg1;
- (void)drawRect:(struct CGRect)arg1;
- (id)effectiveHeaderBorderColor;
- (id)effectiveHeaderBackgroundColor;
- (struct CGRect)headerRect;
- (struct CGRect)labelAreaBounds;
- (struct CGRect)imageRect;
- (struct CGRect)imageAreaBounds;
- (BOOL)isFlipped;
- (void)setHelpIdentifier:(id)arg1;
- (id)helpIdentifier;
- (void)takeLabelFromTitle:(id)arg1 andSubtitle:(id)arg2;
- (void)setLabel:(id)arg1;
- (id)label;
- (void)setImage:(id)arg1;
- (id)image;
- (BOOL)isPressed;
- (void)setPressed:(BOOL)arg1;
- (id)contentView;
- (void)setContentView:(id)arg1;
- (id)delegate;
- (void)setDelegate:(id)arg1;
- (void)setLastMouseDown:(id)arg1;
- (id)lastMouseDown;
- (void)dealloc;
- (id)initWithFrame:(struct CGRect)arg1;
@end
@interface DTAssetEditorController : NSObject
{
NSTextField *labelTextField;
NSTextField *subtitleTextField;
NSTextField *shortDescriptionTextField;
NSButton *cancelButton;
NSButton *okButton;
NSImageView *imageWell;
NSTextView *detailedDescriptionTextView;
NSPanel *editorPanel;
DTAsset *editedAsset;
id editedContext;
id delegate;
}
- (void)startEditingAsset:(id)arg1 inWindow:(id)arg2 context:(id)arg3;
- (void)didAssetEditorSheet:(id)arg1 returnCode:(long long)arg2 contextInfo:(void *)arg3;
- (void)okEditorSheet:(id)arg1;
- (void)cancelEditorSheet:(id)arg1;
- (void)configureInterfaceWithAsset:(id)arg1;
- (void)setEditedContext:(id)arg1;
- (id)editedContext;
- (void)setEditedAsset:(id)arg1;
- (id)editedAsset;
- (id)editedDetailedDescription;
- (id)editedImage;
- (id)editedShortDescription;
- (id)editedSubtitle;
- (id)editedLabel;
- (void)setDelegate:(id)arg1;
- (id)delegate;
- (void)dealloc;
- (id)init;
@end
@interface DTAssetGroup : DTAbstractAssetGroup
{
DTMutableOrderedSet *assets;
BOOL assetsAreEditable;
BOOL groupsAreEditable;
}
- (BOOL)containsAsset:(id)arg1;
- (id)assetsEnumerator;
- (id)assets;
- (long long)numberOfAssets;
- (void)insertAsset:(id)arg1 atIndex:(long long)arg2;
- (void)removeAsset:(id)arg1;
- (void)setGroupsAreEditable:(BOOL)arg1;
- (BOOL)groupsAreEditable;
- (void)setAssetsAreEditable:(BOOL)arg1;
- (BOOL)assetsAreEditable;
- (void)dealloc;
- (id)initWithPropertyListRepresentation:(id)arg1 assetCategory:(id)arg2 andIdentifiedAssets:(id)arg3;
- (void)buildPropertyListRepresentation:(id)arg1;
- (id)initWithDisplayName:(id)arg1 andAssetCategory:(id)arg2;
@end
@interface DTAssetGroupOutlineView : NSOutlineView
{
}
- (void)keyDown:(id)arg1;
- (BOOL)_shouldAbortMouseDownAfterDragAttempt:(id)arg1;
- (id)delegate;
- (void)setDelegate:(id)arg1;
@end
@interface DTAssetLibrary : NSObject
{
NSArray *visibleAssetCategories;
NSMutableDictionary *categoryControllersByID;
DTAssetCategoryController *activeAssetCategoryController;
NSSegmentedControl *categoryControl;
NSView *groupViewContainer;
DTAssetDetailView *assetDetailView;
NSWindow *libraryWindow;
DTGroupedTileView *assetTileView;
NSOutlineView *groupOutlineView;
NSScrollView *groupScrollView;
NSTreeController *groupController;
NSSearchField *assetFilterField;
NSSegmentedControl *actionControl;
NSMenu *actionMenu;
NSMenuItem *editMenuItem;
NSPopUpButton *groupPopUp;
long long assetViewStyle;
NSMenu *groupMenu;
DTSplitView *detailSplitter;
DTSplitView *groupSplitter;
NSMenuItem *viewAssetsAsIconsMenuItem;
NSMenuItem *viewAssetsAsIconsAndLabelsMenuItem;
NSMenuItem *viewAssetsAsSmallIconsAndLabelsMenuItem;
NSMenuItem *viewAssetsAsIconsLabelsAndDescriptionsMenuItem;
NSMenuItem *toggleGroupHeadersMenuItem;
DTAsset *assetDetailViewAsset;
double originalGroupPopUpHeight;
double originalWindowMinWidth;
double heightDeltaFromCategoryControlToMainSplitView;
NSSet *allowedAssetViewStyles;
NSString *libraryStorageSubpath;
NSMutableDictionary *persistencePoliciesByContext;
DTMutableOrderedDictionary *uiStatePersistencePoliciesByCategory;
DTSmartAssetGroupRuleEditorController *smartAssetGroupRuleEditorController;
BOOL synchronizingDetailViewContentViewWithAsset;
BOOL isIconContentValid;
BOOL isGroupMenuContentValid;
BOOL viewingLeafGroup;
BOOL identifiesAssetsPerGroup;
BOOL inFilterMethod;
BOOL restoredUserSettings;
BOOL switchingGroupView;
BOOL loadingInterface;
BOOL filterCallbackIsPending;
NSDate *lastFilterDate;
NSString *filterString;
NSArray *observedGroups;
NSIndexSet *selectedAssetGroupPairIndexes;
id delegate;
}
+ (id)synchronizedAssetKeyPathsForDetailView;
+ (BOOL)hasILMediaBrowser;
+ (id)assetLibraryImage;
+ (id)sharedInstance;
- (void)assetCategoryController:(id)arg1 willDisplayAsset:(id)arg2;
- (void)assetCategoryController:(id)arg1 sizeAssetDetailView:(id)arg2 toFitSuggestedSize:(struct CGSize)arg3 forAsset:(id)arg4;
- (void)assetCategoryController:(id)arg1 willDisplayAsset:(id)arg2 inAssetDetailView:(id)arg3;
- (id)assetCategoryController:(id)arg1 assetDetailViewForAsset:(id)arg2;
- (void)assetCategoryController:(id)arg1 removeAssets:(id)arg2;
- (id)assetCategoryControllerSmartGroupRuleDefinitionsPropertyList:(id)arg1;
- (id)assetCategoryController:(id)arg1 createViewForSmartRuleViewID:(id)arg2;
- (BOOL)assetCategoryController:(id)arg1 createAsset:(id *)arg2 andImage:(id *)arg3 forAssetSourceWithIdentifier:(id *)arg4 fromPasteboard:(id)arg5;
- (BOOL)assetCategoryController:(id)arg1 canCreateAssetsFromPasteboard:(id)arg2;
- (BOOL)assetCategoryController:(id)arg1 canCreateAssetsFromPasteboard:(id)arg2 targettingAssetSourceIdentifier:(id *)arg3;
- (void)assetCategoryController:(id)arg1 populatePasteboard:(id)arg2 withAssets:(id)arg3 defaultDraggedImageState:(id *)arg4 identifierMapTable:(id *)arg5;
- (void)assetCategoryController:(id)arg1 didFinishDraggingAssets:(id)arg2 info:(id)arg3 shouldSlideBack:(char *)arg4;
- (void)assetCategoryController:(id)arg1 willBeginDraggingAssets:(id)arg2;
- (BOOL)assetCategoryController:(id)arg1 isAssetUserEditable:(id)arg2;
- (void)assetCategoryController:(id)arg1 userDidEditAsset:(id)arg2;
- (BOOL)assetCategoryController:(id)arg1 canRemoveAsset:(id)arg2;
- (id)assetCategoryController:(id)arg1 searchTermsForAsset:(id)arg2;
- (id)assetCategoryControllerContentPasteboardTypes:(id)arg1;
- (void)userDidChooseGroupFromPopUp:(id)arg1;
- (void)outlineViewSelectionDidChange:(id)arg1;
- (BOOL)control:(id)arg1 textView:(id)arg2 doCommandBySelector:(SEL)arg3;
- (void)filterAssetsFromFilterField:(id)arg1;
- (void)cancelFiltering;
- (void)reallyFilter:(id)arg1;
- (void)assetDetailView:(id)arg1 sizeContentView:(id)arg2 toFitSuggestedSize:(struct CGSize)arg3;
- (void)assetDetailView:(id)arg1 wasDoubleClickedInHeader:(id)arg2;
- (void)assetDetailView:(id)arg1 beginDraggingWithMouseDownEvent:(id)arg2 andMouseDraggedEvent:(id)arg3;
- (void)refreshDetailView;
- (void)synchronizeDetailViewContentViewWithAsset;
- (id)assetDetailViewAsset;
- (void)setAssetDetailViewAsset:(id)arg1;
- (struct CGSize)draggingStickiness:(id)arg1;
- (id)draggedImageState:(id)arg1;
- (void)draggingEnded:(id)arg1;
- (void)concludeDragOperation:(id)arg1;
- (BOOL)performDragOperation:(id)arg1;
- (BOOL)prepareForDragOperation:(id)arg1;
- (void)draggingExited:(id)arg1;
- (unsigned long long)draggingUpdated:(id)arg1;
- (unsigned long long)draggingEntered:(id)arg1;
- (void)windowDidMove:(id)arg1;
- (void)windowDidResize:(id)arg1;
- (void)windowDidOrderOffScreen:(id)arg1;
- (void)windowDidOrderOnScreen:(id)arg1;
- (struct CGRect)windowWillUseStandardFrame:(id)arg1 defaultFrame:(struct CGRect)arg2;
- (void)tileView:(id)arg1 didChangeClickedObjectFrom:(id)arg2;
- (id)tileView:(id)arg1 typeCompletionStringForContentObject:(id)arg2;
- (id)groupedTileView:(id)arg1 draggedImageState:(id)arg2;
- (void)groupedTileView:(id)arg1 concludeDragOperation:(id)arg2;
- (BOOL)groupedTileView:(id)arg1 performDragOperation:(id)arg2;
- (BOOL)groupedTileView:(id)arg1 prepareForDragOperation:(id)arg2;
- (void)groupedTileView:(id)arg1 draggingExited:(id)arg2;
- (unsigned long long)groupedTileView:(id)arg1 draggingEntered:(id)arg2;
- (unsigned long long)groupedTileView:(id)arg1 draggingUpdated:(id)arg2;
- (void)groupedTileViewDragSelectedItems:(id)arg1 withMouseDownEvent:(id)arg2 andMouseDraggedEvent:(id)arg3;
- (BOOL)groupedTileView:(id)arg1 shouldDragLayoutItem:(id)arg2 withMouseDownEvent:(id)arg3;
- (id)groupedTileView:(id)arg1 layoutItemForRepresentedObject:(id)arg2;
- (id)groupedTileView:(id)arg1 labelForGroup:(id)arg2;
- (BOOL)groupedTileView:(id)arg1 shouldDrawAlternateHeaderColorForGroup:(id)arg2;
- (void)groupedTileViewDeleteSelectedItems:(id)arg1;
- (void)groupedTileViewUserPressedEnter:(id)arg1;
- (void)groupedTileView:(id)arg1 wasDoubleClicked:(id)arg2;
- (void)askDelegateToDepositeAssets:(id)arg1;
- (void)splitViewSplitterDidMove:(id)arg1;
- (double)splitView:(id)arg1 minSizeForView:(id)arg2;
- (void)groupViewDidResize:(id)arg1;
- (void)applyProperGroupView;
- (void)setGroupViewer:(id)arg1;
- (id)groupViewer;
- (void)scrollViewContentViewBoundsDidChange:(id)arg1;
- (id)toolTipManager:(id)arg1 toolTipForView:(id)arg2 location:(struct CGPoint)arg3 tipSourceRect:(struct CGRect *)arg4;
- (BOOL)assetViewShouldAllowAssetDrops;
- (void)resetIconContent;
- (BOOL)assetPassesFilter:(id)arg1;
- (void)applyAssetViewStyle;
- (void)applyAssetViewStyleToAssetView:(id)arg1;
- (BOOL)selectAsset:(id)arg1 inGroup:(id)arg2 bySwitchingCategories:(BOOL)arg3;
- (id)targetAssetsForActionMenu;
- (id)selectedAssets;
- (id)selectedAssetPairs;
- (BOOL)shouldShowGridLines;
- (void)outlineViewExpansionDidChange:(id)arg1;
- (id)currentSplitViewUIState;
- (void)applySplitViewUIState:(id)arg1;
- (id)currentGroupOutlineViewSelectionAndExpansionState;
- (void)applyGroupOutlineViewSelectionAndExpansionState:(id)arg1;
- (id)currentTileViewUIState;
- (void)applyTileViewUIState:(id)arg1;
- (id)makeItemForGroupVisible:(id)arg1 select:(BOOL)arg2 byExtendingSelection:(BOOL)arg3 edit:(BOOL)arg4;
- (id)outlineViewItemForGroupIfVisible:(id)arg1;
- (void)rebuildGroupMenu;
- (double)minimumGroupOutlineHeight;
- (double)groupPopUpHeight;
- (void)selectAssets:(id)arg1 inGroup:(id)arg2;
- (id)assetTileViewContent;
- (id)unsynchronizedAssetTileViewContent;
- (void)viewAssetsAs:(id)arg1;
- (void)takeCategoryFromSegmentedControl:(id)arg1;
- (void)assetGroupOutlineViewDeleteSelectedRows:(id)arg1;
- (void)outlineView:(id)arg1 willDisplayCell:(id)arg2 forTableColumn:(id)arg3 item:(id)arg4;
- (BOOL)outlineView:(id)arg1 acceptDrop:(id)arg2 item:(id)arg3 childIndex:(long long)arg4;
- (unsigned long long)outlineView:(id)arg1 validateDrop:(id)arg2 proposedItem:(id)arg3 proposedChildIndex:(long long)arg4;
- (BOOL)outlineView:(id)arg1 writeItems:(id)arg2 toPasteboard:(id)arg3;
- (id)outlineView:(id)arg1 objectValueForTableColumn:(id)arg2 byItem:(id)arg3;
- (long long)outlineView:(id)arg1 numberOfChildrenOfItem:(id)arg2;
- (BOOL)outlineView:(id)arg1 isItemExpandable:(id)arg2;
- (id)outlineView:(id)arg1 child:(long long)arg2 ofItem:(id)arg3;
- (id)imageForGroup:(id)arg1;
- (id)assetViewSourceGroups;
- (id)selectedGroups;
- (void)selectAssetSourceWithIdentifier:(id)arg1 subpath:(id)arg2 byExtendingSelection:(BOOL)arg3;
- (BOOL)isViewingGroupsThroughPopUp;
- (BOOL)isViewingGroupsThroughOutline;
- (void)rebuildCategoryControl;
- (void)orderLibraryWindowFrontAndMakeSearchFieldFirstResponder;
- (void)registerForDropTypes;
- (void)applyUIState:(id)arg1;
- (id)activeUIState;
- (void)menuNeedsUpdate:(id)arg1;
- (BOOL)validateUserInterfaceItem:(id)arg1;
- (void)removeAssetsFromLibrary:(id)arg1;
- (void)removeAssetsFromGroup:(id)arg1;
- (void)removeAssetGroups:(id)arg1;
- (BOOL)canPerformRemoveSelectedAssetGroups;
- (BOOL)canEditSelectedItems:(id *)arg1;
- (BOOL)canPerformRemoveSelectedAssetsFromGroup;
- (BOOL)canPerformRemoveSelectedAssetsFromLibrary;
- (void)performRemoveAssetsFromLibrary:(id)arg1;
- (void)performRemoveAssetsFromGroups:(id)arg1;
- (void)performRemoveSelectedAssetGroups;
- (void)makeNewSmartAssetGroup:(id)arg1;
- (void)makeNewAssetGroup:(id)arg1;
- (void)editSelectedItem:(id)arg1;
- (BOOL)firstResponderHasSelectedAsset:(id)arg1;
- (void)toggleShowGroupsWithIcons:(id)arg1;
- (id)parentForNewGroup;
- (id)smartAssetGroupRuleEditorControllerRuleDefinitionsPropertyList:(id)arg1;
- (id)smartAssetGroupRuleEditorController:(id)arg1 createViewForSmartRuleViewID:(id)arg2;
- (void)updateSmartAssetGroupEditorStatus;
- (void)observeValueForKeyPath:(id)arg1 ofObject:(id)arg2 change:(id)arg3 context:(void *)arg4;
- (void)abstractAssetGroupDidChangeName:(id)arg1;
- (void)assetDidChangeLastUsedDate:(id)arg1;
- (id)invalidationPolicyForContext:(void *)arg1;
- (CDUnknownBlockType)validateBlockForContext:(void *)arg1;
- (BOOL)isPersistenceContext:(void *)arg1;
- (void)userDidEditAsset:(id)arg1;
- (void)applyAssetSelectionIndexes;
- (void)forceGroupMenuContentValidation;
- (void)invalidateGroupMenuContent;
- (void)validateGroupMenuContent:(id)arg1;
- (void)forceIconContentValidation;
- (void)invalidateIconContent;
- (void)validateIconContent:(id)arg1;
- (void)stopObservingAssetGroupsForAssetCategory:(id)arg1;
- (void)startObservingAssetGroupsForAssetCategory:(id)arg1;
- (void)setObservedGroups:(id)arg1;
- (BOOL)isViewingLeafGroup;
- (id)smartAssetGroupRuleEditorController;
- (BOOL)isGroupDisplayedInAssetView:(id)arg1;
- (id)visibleAssetCategories;
- (void)setVisibleAssetCategories:(id)arg1;
- (id)assetCategoryWithIdentifier:(id)arg1;
- (id)assetCategoryControllerWithIdentifier:(id)arg1;
- (id)assetCategories;
- (id)identifiedCategories;
- (void)addAssetCategory:(id)arg1;
- (id)activeAssetCategoryController;
- (void)setActiveAssetCategoryController:(id)arg1;
- (void)persistUIStateOfActiveCategoryController;
- (void)persistUIStateOfCategoryController:(id)arg1;
- (void)persistUIStateOfCategoryController:(id)arg1 validateImmediately:(BOOL)arg2;
- (id)lastActiveUIStateForAssetCategoryController:(id)arg1;
- (id)userDefaultsKeyForPersistingUIStateOfCategoryController:(id)arg1;
- (id)userDefaultsKeyForRestoringUIStateOfCategoryController:(id)arg1;
- (id)userDefaultsKeyForUIStatePersistenceOfCategoryController:(id)arg1;
- (void)setActiveAssetCategory:(id)arg1;
- (id)activeRootGroup;
- (id)activeAssetCategory;
- (BOOL)identifiesAssetsPerGroup;
- (void)setIdentifiesAssetsPerGroup:(BOOL)arg1;
- (long long)assetViewStyle;
- (void)setAssetViewStyle:(long long)arg1;
- (void)setAllowedAssetViewStyles:(id)arg1;
- (id)allowedAssetViewStyles;
- (id)actionMenu;
- (id)categoryControl;
- (id)assetViewStyleMenuItems;
- (id)groupScrollView;
- (id)groupPopUp;
- (id)assetFilterField;
- (id)groupMenu;
- (id)groupController;
- (id)groupOutlineView;
- (id)assetScrollView;
- (id)assetTileViewForceSynchronizedContent:(BOOL)arg1;
- (struct CGSize)suggestedSizeForDetailView;
- (id)assetDetailView;
- (id)groupSplitter;
- (id)detailSplitter;
- (id)groupViewContainer;
- (id)libraryWindow;
- (void)setFilterString:(id)arg1;
- (id)filterString;
- (id)delegate;
- (void)setDelegate:(id)arg1;
- (void)didRestoreUserSettings;
- (void)ensureInterfaceIsLoaded;
- (BOOL)isInterfaceLoaded;
- (void)dealloc;
- (void)removeAsObserver;
- (id)init;
- (id)libraryStoragePath;
- (id)applicationSupportSubpath;
- (void)setApplicationSupportSubpath:(id)arg1;
- (id)defaultApplicationSupportSubpath;
- (void)restoreUserSettings;
- (void)saveUserSettings;
- (void)restoreAssetLastUsedDates;
- (void)saveAssetLastUsedDates;
- (id)assetLastUsedDates;
- (void)saveGroups;
- (void)restoreGroups;
- (id)defaultUserCategories;
- (id)assetLastUsedDatesPath;
- (id)userCategoriesPath;
- (id)serializedGroupsPerCategory;
- (void)rebuildGroupsFromPropertyListRepresentation:(id)arg1;
@end
@interface DTAssetView : NSView
{
NSImage *image;
NSString *label;
NSString *shortDescription;
long long style;
BOOL drawsWithSelectionHighlight;
BOOL showsFirstResponder;
BOOL drawsGrid;
BOOL showingGridLines;
id delegate;
BOOL drawsWithClickFrame;
}
+ (struct CGSize)maximumSizeForStyle:(long long)arg1;
+ (struct CGSize)minimumSizeForStyle:(long long)arg1;
- (BOOL)accessibilityIsAttributeSettable:(id)arg1;
- (id)accessibilityAttributeNames;
- (id)accessibilityAttributeValue:(id)arg1;
- (BOOL)accessibilityIsIgnored;
- (void)drawRect:(struct CGRect)arg1;
- (void)viewWillDraw;
- (BOOL)isOpaque;
- (id)effectiveBackgroundColor;
- (id)effectiveLightBorderColor;
- (id)effectiveBorderColor;
- (id)clickedBorderColor;
- (id)normalBorderColor;
- (id)selectedLightBorderColor;
- (id)normalLightBorderColor;
- (id)normalBackgroundColor;
- (id)primarySelectedBackgroundColor;
- (id)secondarySelectedBackgroundColor;
- (id)text;
- (id)effectiveShortDescriptionFont;
- (id)effectiveLabelFont;
- (BOOL)shouldBandSelectWithMouseDownEvent:(id)arg1;
- (struct CGRect)textAreaBounds;
- (struct CGRect)imageRect;
- (struct CGRect)imageAreaBounds;
- (BOOL)isFlipped;
- (void)setStyle:(long long)arg1;
- (long long)style;
- (void)setShortDescription:(id)arg1;
- (id)shortDescription;
- (void)setLabel:(id)arg1;
- (id)label;
- (void)setImage:(id)arg1;
- (id)image;
- (void)setShowingGridLines:(BOOL)arg1;
- (BOOL)isShowingGridLines;
- (BOOL)shouldDrawWithClickFrame;
- (void)setDrawsWithClickFrame:(BOOL)arg1;
- (BOOL)drawsWithClickFrame;
- (void)setDrawsWithSelectionHighlight:(BOOL)arg1;
- (BOOL)drawsWithSelectionHighlight;
- (void)setShowsFirstResponder:(BOOL)arg1;
- (BOOL)showsFirstResponder;
- (void)setNilValueForKey:(id)arg1;
- (void)setDelegate:(id)arg1;
- (id)delegate;
- (void)dealloc;
- (id)initWithFrame:(struct CGRect)arg1;
@end
@interface DTAssetiLifeDelegate : NSObject
{
DTAssetDetailImageView *_detailImageView;
NSMutableSet *_photoLoadingImagesSet;
NSMutableArray *_photoLoadingImagesQueue;
id _photoAssets;
unsigned long long _photoLoadIndex;
BOOL _photoHasWorkerLoadingImageThread;
}
+ (id)draggedImageForPhotoImage:(id)arg1;
+ (id)sharedInstance;
- (void)assetCategoryController:(id)arg1 sizeAssetDetailView:(id)arg2 toFitSuggestedSize:(struct CGSize)arg3 forAsset:(id)arg4;
- (void)assetCategoryController:(id)arg1 willDisplayAsset:(id)arg2 inAssetDetailView:(id)arg3;
- (void)assetCategoryController:(id)arg1 willDisplayAsset:(id)arg2;
- (id)assetCategoryController:(id)arg1 assetDetailViewForAsset:(id)arg2;
- (id)assetCategoryControllerSmartGroupRuleDefinitionsPropertyList:(id)arg1;
- (id)assetCategoryController:(id)arg1 createViewForSmartRuleViewID:(id)arg2;
- (BOOL)assetCategoryController:(id)arg1 createAsset:(id *)arg2 andImage:(id *)arg3 forAssetSourceWithIdentifier:(id *)arg4 fromPasteboard:(id)arg5;
- (BOOL)assetCategoryController:(id)arg1 canCreateAssetsFromPasteboard:(id)arg2 targettingAssetSourceIdentifier:(id *)arg3;
- (void)assetCategoryController:(id)arg1 populatePasteboard:(id)arg2 withAssets:(id)arg3 defaultDraggedImageState:(id *)arg4 identifierMapTable:(id *)arg5;
- (void)assetCategoryController:(id)arg1 didFinishDraggingAssets:(id)arg2 info:(id)arg3 shouldSlideBack:(char *)arg4;
- (void)assetCategoryController:(id)arg1 willBeginDraggingAssets:(id)arg2;
- (void)assetCategoryController:(id)arg1 userDidEditAsset:(id)arg2;
- (BOOL)assetCategoryController:(id)arg1 isAssetUserEditable:(id)arg2;
- (BOOL)assetCategoryController:(id)arg1 canRemoveAsset:(id)arg2;
- (id)assetCategoryController:(id)arg1 searchTermsForAsset:(id)arg2;
- (id)assetCategoryControllerContentPasteboardTypes:(id)arg1;
- (void)startLoadingImagesForPhotoAssets:(id)arg1;
- (void)_threadedPhotoLoadImages;
- (void)dealloc;
- (id)init;
- (void)_thumbnailForPhotoAsset:(id)arg1;
@end
@interface DTDragManager : NSObject
{
}
+ (BOOL)isUserDragging;
+ (id)sharedInstance;
- (unsigned long long)dragImage:(id)arg1 at:(struct CGPoint)arg2 offset:(struct CGSize)arg3 mouseDownEvent:(id)arg4 mouseDraggedEvent:(id)arg5 pasteboard:(id)arg6 allowedOperations:(unsigned long long)arg7 source:(id)arg8 slideBack:(BOOL)arg9 draggingSourceContext:(id)arg10;
@end
@interface DTDraggedImageState : NSObject
{
struct CGPoint anchorPoint;
BOOL isAnchorPointExplicit;
}
- (BOOL)isEqual:(id)arg1;
- (unsigned long long)hash;
- (BOOL)synthesizedAnchorPoint:(struct CGPoint *)arg1 forSubiquentState:(id)arg2;
- (void)synthesizeAnchorPointFromPreviousStates:(id)arg1;
- (id)image;
- (struct CGPoint)anchorPoint;
- (void)setAnchorPoint:(struct CGPoint)arg1;
- (BOOL)isAnchorPointExplicit;
@end
@interface DTDraggedImageStateTransitionRegistry : NSObject
{
NSMutableDictionary *registry;
}
+ (id)sharedInstance;
- (id)transitionFromState:(id)arg1 toState:(id)arg2;
- (void)registerTransition:(Class)arg1 fromImageStateClass:(Class)arg2 toImageStateClass:(Class)arg3;
- (id)init;
@end
@interface DTDraggedImageStateTransitionView : NSView
{
float progress;
DTDraggedImageState *fromState;
DTDraggedImageState *toState;
}
- (id)toState;
- (id)fromState;
- (float)progress;
- (void)setProgress:(float)arg1;
- (double)duration;
- (struct CGPoint)anchorPoint;
- (void)dealloc;
- (id)initWithFromState:(id)arg1 andToState:(id)arg2;
@end
@interface DTDraggedObjectsImageState : DTDraggedImageState
{
NSMutableDictionary *places;
NSMutableDictionary *views;
NSMutableDictionary *images;
NSMutableArray *identifiers;
NSImage *image;
NSString *name;
struct CGPoint frameOffset;
BOOL forcesImageScaling;
}
+ (id)draggedObjectStateWithIdentifiers:(id)arg1 views:(id)arg2 name:(id)arg3;
+ (id)draggedObjectStateWithIdentifiers:(id)arg1 images:(id)arg2 frames:(id)arg3 name:(id)arg4;
+ (id)draggedObjectStateWithImage:(id)arg1;
+ (id)draggedObjectStateWithIdentifier:(id)arg1 view:(id)arg2 name:(id)arg3;
+ (id)draggedObjectStateWithIdentifier:(id)arg1 image:(id)arg2 name:(id)arg3;
- (id)description;
- (void)setForcesImageScaling:(BOOL)arg1;
- (BOOL)forcesImageScaling;
- (BOOL)isEqual:(id)arg1;
- (unsigned long long)hash;
- (BOOL)synthesizedAnchorPoint:(struct CGPoint *)arg1 forSubiquentState:(id)arg2;
- (id)identifierForPoint:(struct CGPoint)arg1;
- (BOOL)containsIdentifier:(id)arg1;
- (struct CGPoint)anchorPoint;
- (id)name;
- (id)image;
- (id)identifiers;
- (id)views;
- (id)imageForIdentifier:(id)arg1;
- (id)viewForIdentifier:(id)arg1;
- (struct CGRect)frameForIdentifier:(id)arg1;
- (void)remapIdentifiers:(id)arg1;
- (void)dealloc;
- (id)initWithIdentifiers:(id)arg1 views:(id)arg2 name:(id)arg3;
- (id)initWithIdentifiers:(id)arg1 images:(id)arg2 frames:(id)arg3 name:(id)arg4;
@end
@interface DTDraggedObjectsTransitionView : DTDraggedImageStateTransitionView
{
NSAffineTransform *transformFromToState;
NSAffineTransform *transformFromFromState;
}
- (void)drawRect:(struct CGRect)arg1;
- (void)setProgress:(float)arg1;
- (id)toState;
- (id)fromState;
- (id)description;
- (void)dealloc;
- (id)initWithFromState:(id)arg1 andToState:(id)arg2;
@end
@interface DTDraggingContext : NSObject <DTDraggingInfo>
{
NSWindow *draggingDestinationWindow;
struct CGPoint draggingLocation;
struct CGPoint draggedImageLocation;
NSImage *draggedImage;
NSPasteboard *draggingPasteboard;
id draggingSource;
NSDictionary *draggingSourceContext;
long long draggingSequenceNumber;
long long draggingSourceOperationMask;
DTDraggedImageState *draggedImageState;
struct CGSize draggingStickiness;
BOOL draggedImageStateNeedsUpdate;
long long draggingFormation;
BOOL animatesToDestination;
long long numberOfValidItemsForDrop;
}
@property long long numberOfValidItemsForDrop; // @synthesize numberOfValidItemsForDrop;
@property BOOL animatesToDestination; // @synthesize animatesToDestination;
@property long long draggingFormation; // @synthesize draggingFormation;
- (void)enumerateDraggingItemsWithOptions:(unsigned long long)arg1 forView:(id)arg2 classes:(id)arg3 searchOptions:(id)arg4 usingBlock:(CDUnknownBlockType)arg5;
- (struct CGPoint)draggingLocationOnScreen;
- (void)setDraggedImageStateNeedsUpdate:(BOOL)arg1;
- (BOOL)draggedImageStateNeedsUpdate;
- (struct CGSize)draggingStickiness;
- (void)setDraggingStickiness:(struct CGSize)arg1;
- (id)namesOfPromisedFilesDroppedAtDestination:(id)arg1;
- (void)slideDraggedImageTo:(struct CGPoint)arg1;
- (long long)draggingSequenceNumber;
- (id)draggingSourceContext;
- (void)setDraggingSourceContext:(id)arg1;
- (void)setDraggingSequenceNumber:(long long)arg1;
- (id)draggingSource;
- (id)draggingPasteboard;
- (id)draggedImage;
- (void)setDraggedImage:(id)arg1;
- (struct CGPoint)draggedImageLocation;
- (void)setDraggedImageLocation:(struct CGPoint)arg1;
- (struct CGPoint)draggingLocation;
- (void)setDraggingLocation:(struct CGPoint)arg1;
- (void)setDraggingSourceOperationMask:(unsigned long long)arg1;
- (unsigned long long)draggingSourceOperationMask;
- (void)setDraggingDestinationWindow:(id)arg1;
- (id)draggingDestinationWindow;
- (void)setDraggedImageState:(id)arg1;
- (id)draggedImageState;
- (void)dealloc;
- (id)initWithSource:(id)arg1 andPasteboard:(id)arg2;
// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;
@end
@interface DTFirstResponderDrawingStrategy : NSObject
{
NSView *view;
BOOL viewIsFirstResponder;
BOOL windowIsKey;
}
- (void)viewWillMoveToWindow:(id)arg1;
- (void)windowDidChangeKeyStatus:(id)arg1;
- (void)resignedFirstResponder;
- (void)becameFirstResponder;
- (BOOL)viewSouldDrawLikeFirstResponder;
- (void)setWindowIsKey:(BOOL)arg1;
- (void)setViewIsFirstResponder:(BOOL)arg1;
- (void)dispose;
- (void)finishObservingWindow:(id)arg1;
- (void)beginObservingWindow:(id)arg1;
- (void)dealloc;
- (id)initWithView:(id)arg1;
@end
@interface DTFlippedView : NSView
{
}
- (BOOL)isFlipped;
@end
@interface DTFocusableScrollView : NSScrollView
{
BOOL drawsFocusRing;
}
- (void)setFrameOrigin:(struct CGPoint)arg1;
- (void)setFrameSize:(struct CGSize)arg1;
- (void)drawRect:(struct CGRect)arg1;
- (void)viewWillDraw;
- (void)setDrawsFocusRing:(BOOL)arg1;
- (BOOL)drawsFocusRing;
- (void)setNilValueForKey:(id)arg1;
@end
@interface DTGroupedAssetHilightView : NSView
{
}
- (void)drawRect:(struct CGRect)arg1;
@end
@interface DTTileView : NSView <NSAnimationDelegate>
{
void *_reserved;
void *_reserved2;
void *_reserved3;
void *_reserved4;
void *_reserved5;
DTTypeCompletionHandler *_typeCompletionHandler;
id _delegate;
id _clickedContentObject;
NSArray *_content;
NSIndexSet *selectionIndexes;
DTTileViewItem *_layoutItemPrototype;
struct CGSize _minGridSize;
struct CGSize _maxGridSize;
unsigned long long _minGridRows;
unsigned long long _maxGridRows;
unsigned long long _minGridColumns;
unsigned long long _maxGridColumns;
NSArray *_backgroundColors;
struct __tileViewanimationContainerFlags {
unsigned int _selectable:1;
unsigned int _allowsMultipleSelection:1;
unsigned int _avoidsEmptySelection:1;
unsigned int _superviewIsClipView:1;
unsigned int _gridParametersReadFromPrototype:1;
unsigned int _showsFirstResponder:1;
unsigned int _reservedAnimationContainer:26;
} _animationContainerFlags;
struct CGSize _targetFrameSize;
struct CGSize _targetGridSize;
struct CGSize _targetUnfilledViewSpace;
unsigned long long _targetNumberOfGridRows;
unsigned long long _targetNumberOfGridColumns;
NSMutableArray *_targetItems;
struct CGSize _appliedFrameSize;
struct CGSize _appliedGridSize;
struct CGSize _appliedUnfilledViewSpace;
unsigned long long _appliedNumberOfGridRows;
unsigned long long _appliedNumberOfGridColumns;
NSMutableArray *_appliedItems;
NSMutableSet *_appliedItemsAsSet;
NSMutableSet *_appliedRemovedItemsAsSet;
double _animationDuration;
NSViewAnimation *_animation;
NSMutableArray *_hideLayoutItems;
NSMutableArray *_showLayoutItems;
DTFirstResponderDrawingStrategy *_firstResponderDrawingStrategy;
BOOL animates;
}
- (void)rightMouseDown:(id)arg1;
- (void)setClickedContentObject:(id)arg1;
- (id)clickedContentObject;
- (id)_recursiveFindDefaultButtonCell;
- (void)moveWordLeftAndModifySelection:(id)arg1;
- (void)moveWordRightAndModifySelection:(id)arg1;
- (void)moveToEndOfParagraph:(id)arg1;
- (void)moveToBeginningOfParagraph:(id)arg1;
- (void)moveWordLeft:(id)arg1;
- (void)moveWordRight:(id)arg1;
- (void)moveDownAndModifySelection:(id)arg1;
- (void)moveUpAndModifySelection:(id)arg1;
- (void)moveLeftAndModifySelection:(id)arg1;
- (void)moveRightAndModifySelection:(id)arg1;
- (void)moveDown:(id)arg1;
- (void)moveUp:(id)arg1;
- (void)moveLeft:(id)arg1;
- (void)moveRight:(id)arg1;
- (unsigned long long)_indexForMoveDown;
- (unsigned long long)_indexForMoveUp;
- (unsigned long long)_indexForMoveLeft;
- (unsigned long long)_indexForMoveRight;
- (unsigned long long)_indexForIncrementMove:(unsigned long long)arg1;
- (unsigned long long)_indexForDecrementMove:(unsigned long long)arg1;
- (void)selectAll:(id)arg1;
- (void)_contentChanged:(BOOL)arg1 regenerate:(BOOL)arg2;
- (void)discardEditing;
- (void)gridGeometryChanged:(BOOL)arg1;
- (void)_animateAtEndOfEvent;
- (void)applyPendingChangesAndFinishAnimating;
- (void)_applyTargetConfiguration:(BOOL)arg1;
- (void)animationDidEnd:(id)arg1;
- (void)_itemRemovalCompleted:(id)arg1;
- (void)_itemAdditionCompleted:(id)arg1;
- (void)_stopAnimationCompletingOperations:(BOOL)arg1;
- (double)_animationDuration;
- (void)_setAnimationDuration:(double)arg1;
- (id)backgroundColors;
- (void)setBackgroundColors:(id)arg1;
- (struct _NSRange)columnCountRange;
- (void)setColumnCountRange:(struct _NSRange)arg1;
- (struct _NSRange)rowCountRange;
- (void)setRowCountRange:(struct _NSRange)arg1;
- (unsigned long long)maxNumberOfColumns;
- (void)setMaxNumberOfColumns:(unsigned long long)arg1;
- (unsigned long long)maxNumberOfRows;
- (void)setMaxNumberOfRows:(unsigned long long)arg1;
- (struct CGSize)maxGridSize;
- (void)setMaxGridSize:(struct CGSize)arg1;
- (struct CGSize)minGridSize;
- (void)setMinGridSize:(struct CGSize)arg1;
- (void)setTargetFrameSize:(struct CGSize)arg1;
- (struct CGSize)targetFrameSize;
- (struct CGSize)targetGridSize;
- (struct CGSize)appliedGridSize;
- (id)appliedItems;
- (unsigned long long)targetNumberOfGridColumns;
- (unsigned long long)appliedNumberOfGridColumns;
- (void)_computeTargetItemViewFrameRects;
- (struct CGRect)_frameRectForIndexInGrid:(unsigned long long)arg1 gridSize:(struct CGSize)arg2;
- (id)_mutableIndexSetInAppliedGridForRect:(struct CGRect)arg1;
- (unsigned long long)_indexInAppliedGridForPoint:(struct CGPoint)arg1;
- (void)_getRow:(unsigned long long *)arg1 column:(unsigned long long *)arg2 forPoint:(struct CGPoint)arg3;
- (void)_computeTargetItemsByRegenerating:(BOOL)arg1;
- (void)computeTargetGridGeometry;
- (BOOL)_allowsResizingHorizontally;
- (BOOL)_allowsResizingVertically;
- (void)_determineGridParametersFromItemPrototype;
- (void)_scrollSelectionToVisible;
- (void)_scrollToVisibleItemAtIndex:(unsigned long long)arg1;
- (id)layoutItemPrototype;
- (void)setLayoutItemPrototype:(id)arg1;
- (id)newLayoutItemForRepresentedObject:(id)arg1;
- (void)setDelegate:(id)arg1;
- (id)delegate;
- (BOOL)avoidsEmptySelection;
- (void)setAvoidsEmptySelection:(BOOL)arg1;
- (BOOL)allowsMultipleSelection;
- (void)setAllowsMultipleSelection:(BOOL)arg1;
- (BOOL)isSelectable;
- (void)setSelectable:(BOOL)arg1;
- (id)_layoutItemForRepresentedObject:(id)arg1;
- (id)content;
- (void)setContent:(id)arg1;
- (id)selectionIndexes;
- (void)setSelectionIndexes:(id)arg1;
- (void)validateSelectionIndexes;
- (void)_selectFromIndex:(unsigned long long)arg1 toIndex:(unsigned long long)arg2 scrollIndexToVisible:(unsigned long long)arg3;
- (void)_selectIndex:(unsigned long long)arg1 scrollToVisible:(BOOL)arg2;
- (void)_selectionStateChanged:(id)arg1;
- (void)viewWillMoveToWindow:(id)arg1;
- (BOOL)resignFirstResponder;
- (BOOL)becomeFirstResponder;
- (BOOL)acceptsFirstResponder;
- (BOOL)needsPanelToBecomeKey;
- (BOOL)showsFirstResponder;
- (void)setShowsFirstResponder:(BOOL)arg1;
- (void)mouseDown:(id)arg1;
- (id)_handleMouseEvent:(id)arg1 numberOfObjects:(unsigned long long)arg2 startingPoint:(struct CGPoint)arg3 commandKey:(BOOL)arg4 shiftKey:(BOOL)arg5 rubberband:(id)arg6;
- (struct CGPoint)_pointWithinBounds:(struct CGPoint)arg1;
- (void)keyDown:(id)arg1;
- (void)insertText:(id)arg1;
- (id)typeCompletionHandler:(id)arg1 typeCompletionStringForObject:(id)arg2;
- (void)insertBacktab:(id)arg1;
- (void)insertTab:(id)arg1;
- (BOOL)validateUserInterfaceItem:(id)arg1;
- (id)accessibilityHitTest:(struct CGPoint)arg1;
- (id)hitTest:(struct CGPoint)arg1;
- (void)drawRect:(struct CGRect)arg1;
- (BOOL)isFlipped;
- (void)viewDidMoveToSuperview;
- (void)viewWillMoveToSuperview:(id)arg1;
- (void)_superviewFrameChanged:(id)arg1;
- (void)setFrameSize:(struct CGSize)arg1;
- (void)setAnimates:(BOOL)arg1;
- (BOOL)animates;
- (void)dealloc;
- (void)_applySelectionToItems:(id)arg1;
- (void)_applySelectionIndexes:(id)arg1 toItems:(id)arg2;
- (void)_updateContainerReferenceCounterForArraysOfItems:(id)arg1 direction:(BOOL)arg2;
- (void)_updateContainerReferenceCounterForItems:(id)arg1 direction:(BOOL)arg2;
- (void)finalize;
- (void)encodeWithCoder:(id)arg1;
- (id)initWithCoder:(id)arg1;
- (id)initWithFrame:(struct CGRect)arg1;
- (void)_init;
// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;
@end
@interface DTGroupedTileView : DTTileView
{
void *reserved;
long long groupDragTargetIndex;
long long groupLocalDragTargetIndex;
BOOL dragInsertAfterInitialTarget;
BOOL dropOnGroup;
NSArray *groupCounts;
NSArray *groups;
DTGroupedAssetHilightView *overlayView;
NSEvent *activeMouseDown;
BOOL showingHeaders;
CDStruct_f6c3f719 itemInset;
}
+ (BOOL)eventWouldToggleSelection:(id)arg1;
+ (BOOL)eventWouldExtendSelection:(id)arg1;
- (void)drawRect:(struct CGRect)arg1;
- (void)drawRect:(struct CGRect)arg1 inDecoratedView:(id)arg2;
- (id)dropHighlightColor;
- (void)keyDown:(id)arg1;
- (void)deleteBackward:(id)arg1;
- (void)deleteForward:(id)arg1;
- (void)insertNewline:(id)arg1;
- (BOOL)acceptsFirstMouse:(id)arg1;
- (void)mouseUp:(id)arg1;
- (void)mouseDragged:(id)arg1;
- (void)mouseDown:(id)arg1;
- (BOOL)shouldTrackSelectionWithMouseDownEvent:(id)arg1;
- (void)selectItemWithEvent:(id)arg1;
- (id)toolTipForPoint:(struct CGPoint)arg1 sourceRect:(struct CGRect *)arg2;
- (void)dropGroup:(id *)arg1 andItemInsertionIndex:(long long *)arg2 atPoint:(struct CGPoint)arg3;
- (void)dropGroup:(id *)arg1 andItemInsertionIndex:(long long *)arg2 after:(char *)arg3 atPoint:(struct CGPoint)arg4;
- (unsigned long long)indexOfGroupAtPoint:(struct CGPoint)arg1;
- (id)contentObjectAtPoint:(struct CGPoint)arg1;
- (id)tileViewItemAtPoint:(struct CGPoint)arg1;
- (struct CGRect)headerRectForGroupWithIndex:(long long)arg1;
- (id)headerRects;
- (struct CGRect)titleRectForHeaderRect:(struct CGRect)arg1;
- (struct CGRect)titleBackgroundRectForHeaderRect:(struct CGRect)arg1;
- (id)_mutableIndexSetInAppliedGridForRect:(struct CGRect)arg1;
- (unsigned long long)_indexInAppliedGridForPoint:(struct CGPoint)arg1;
- (void)getGlobalIndex:(long long *)arg1 groupIndex:(long long *)arg2 andLocalIndex:(long long *)arg3 atPoint:(struct CGPoint)arg4;
- (void)_getRow:(unsigned long long *)arg1 column:(unsigned long long *)arg2 forPoint:(struct CGPoint)arg3;
- (void)computeTargetGridGeometry;
- (struct CGSize)recalculateTargetFrameSize;
- (id)attributedTitleForGroup:(id)arg1;
- (struct CGRect)rectForTileViewItemAtIndex:(long long)arg1;
- (struct CGRect)_frameRectForIndexInGrid:(unsigned long long)arg1 gridSize:(struct CGSize)arg2;
- (BOOL)isGroupLocalIndex:(long long)arg1 theFirstItemInAnyRowInGroupWithIndex:(long long)arg2;
- (BOOL)isGroupLocalIndex:(long long)arg1 theLastItemInAnyRowInGroupWithIndex:(long long)arg2;
- (long long)appliedColumnsInRow:(long long)arg1 ofGroup:(long long)arg2;
- (long long)appliedRowsInGroupWithIndex:(long long)arg1;
- (long long)targetRowsInGroupWithIndex:(long long)arg1;
- (double)headerHeight;
- (double)headerPostpadHeight;
- (double)headerPrepadHeight;
- (double)headerTitleHeight;
- (long long)numberOfColumns;
- (long long)localIndexForGlobalIndex:(unsigned long long)arg1;
- (long long)groupIndexForGlobalIndex:(unsigned long long)arg1;
- (long long)globalIndexForLocalIndex:(long long)arg1 inGroupWithIndex:(long long)arg2;
- (void)setDragInsertionPoint:(struct CGPoint)arg1;
- (void)setDropGroup:(id)arg1;
- (void)setDropGroup:(id)arg1 dropChildIndex:(long long)arg2 after:(BOOL)arg3 on:(BOOL)arg4;
- (void)clearDragInsertionPoint;
- (struct CGRect)dragInsertionRect;
- (id)dragInsertionPath;
- (void)setFrameSize:(struct CGSize)arg1;
- (void)setItemInset:(CDStruct_f6c3f719)arg1;
- (CDStruct_f6c3f719)itemInset;
- (void)orderOutOverlayView;
- (void)orderInOverlayView;
- (id)overlayView;
- (id)draggedImageState:(id)arg1;
- (void)concludeDragOperation:(id)arg1;
- (BOOL)performDragOperation:(id)arg1;
- (BOOL)prepareForDragOperation:(id)arg1;
- (void)draggingExited:(id)arg1;
- (unsigned long long)draggingEntered:(id)arg1;
- (unsigned long long)draggingUpdated:(id)arg1;
- (id)newLayoutItemForRepresentedObject:(id)arg1;
- (void)setSelectedContentObjects:(id)arg1;
- (id)indexesForContentObjects:(id)arg1;
- (void)setContent:(id)arg1;
- (void)setGroups:(id)arg1;
- (id)groups;
- (void)setActiveMouseDown:(id)arg1;
- (id)activeMouseDown;
- (void)setShowingHeaders:(BOOL)arg1;
- (BOOL)isShowingHeaders;
- (void)dealloc;
- (id)initWithCoder:(id)arg1;
- (id)initWithFrame:(struct CGRect)arg1;
@end
@interface DTIconAndTextCell : NSTextFieldCell
{
NSImage *icon;
BOOL shouldDrawActive;
struct CGSize preferedIconSize;
}
- (unsigned long long)hitTestForEvent:(id)arg1 inRect:(struct CGRect)arg2 ofView:(id)arg3;
- (void)selectWithFrame:(struct CGRect)arg1 inView:(id)arg2 editor:(id)arg3 delegate:(id)arg4 start:(long long)arg5 length:(long long)arg6;
- (void)editWithFrame:(struct CGRect)arg1 inView:(id)arg2 editor:(id)arg3 delegate:(id)arg4 event:(id)arg5;
- (struct CGRect)titleEditingRectForBounds:(struct CGRect)arg1;
- (void)drawInteriorWithFrame:(struct CGRect)arg1 inView:(id)arg2;
- (BOOL)isOpaque;
- (struct CGRect)titleRectForBounds:(struct CGRect)arg1;
- (struct CGRect)iconRectForBounds:(struct CGRect)arg1;
- (struct CGSize)titleSize;
- (id)attributedTitle;
- (id)textAttributes;
- (id)paragraphStyle;
- (id)foregroundColor;
- (id)effectiveFont;
- (double)textInsetForBounds:(struct CGRect)arg1;
- (double)iconInsetForBounds:(struct CGRect)arg1;
- (struct CGSize)iconSizeForBounds:(struct CGRect)arg1;
- (void)setPreferedIconSize:(struct CGSize)arg1;
- (struct CGSize)preferedIconSize;
- (id)icon;
- (void)setIcon:(id)arg1;
- (void)dealloc;
- (id)copyWithZone:(struct _NSZone *)arg1;
- (id)init;
- (id)initTextCell:(id)arg1;
@end
@interface DTIdentityDragImageStateTransition : DTDraggedImageStateTransitionView
{
}
- (double)duration;
- (void)drawRect:(struct CGRect)arg1;
@end
@interface DTInvalidationPolicy : NSObject
{
BOOL scheduledValidation;
SEL selector;
id target;
CDUnknownBlockType validateBlock;
id userInfo;
NSNumber *priority;
NSNumber *delay;
BOOL validatesWhenAppTerminates;
BOOL disablesSuddenTermination;
BOOL disabledSuddenTermination;
BOOL validating;
}
+ (id)invalidationPolicyForInstantOffWithBlock:(CDUnknownBlockType)arg1;
- (BOOL)disablesSuddenTermination;
- (void)setDisablesSuddenTermination:(BOOL)arg1;
- (BOOL)validatesWhenAppTerminates;
- (void)setValidatesWhenAppTerminates:(BOOL)arg1;
- (double)delay;
- (void)setDelay:(double)arg1;
- (unsigned long long)priority;
- (void)setPriority:(unsigned long long)arg1;
- (id)userInfo;
- (void)setUserInfo:(id)arg1;
- (void)appWillTerminate:(id)arg1;
- (void)forceValidate;
- (void)validate;
- (void)cancelValidation;
- (void)unscheduleValidation;
- (void)invalidate;
- (BOOL)isValid;
- (void)doValidation:(id)arg1;
- (void)setSuddenTerminationBlocked:(BOOL)arg1;
- (void)dealloc;
- (id)initWithBlock:(CDUnknownBlockType)arg1;
- (id)initWithTarget:(id)arg1 selector:(SEL)arg2;
@end
@interface DTMutableOrderedDictionary : NSMutableDictionary
{
DTMutableOrderedSet *set;
CDStruct_f2932e27 keyCallbacks;
CDStruct_b3b3fc87 objCallbacks;
}
+ (CDStruct_b3b3fc87)cocoaValueCallBacks;
+ (CDStruct_f2932e27)cocoaKeyCallBacks;
- (void)removeObjectForKey:(id)arg1;
- (void)setObject:(id)arg1 forKey:(id)arg2;
- (id)keyEnumerator;
- (id)objectForKey:(id)arg1;
- (unsigned long long)count;
- (Class)classForCoder;
- (void)encodeWithCoder:(id)arg1;
- (id)initWithCoder:(id)arg1;
- (id)initWithObjects:(id)arg1 forKeys:(id)arg2;
- (id)initWithCapacity:(unsigned long long)arg1;
- (id)init;
- (void)dealloc;
- (id)initWithKeyCallbacks:(CDStruct_f2932e27)arg1 andValueCallbacks:(CDStruct_b3b3fc87)arg2;
@end
@interface DTMutableOrderedSet : NSMutableSet
{
CDStruct_f2932e27 callbacks;
struct DTBucketTag *freelist;
struct DTBucketTag **buckets;
struct DTBucketTag *head;
long long breadth;
long long count;
unsigned long long changeCount;
}
+ (CDStruct_f2932e27)cocoaSetCallbacks;
+ (CDStruct_f2932e27)pointerSetCallbacks;
- (id)description;
- (id)firstObject;
- (id)lastObject;
- (unsigned long long)countByEnumeratingWithState:(CDStruct_70511ce9 *)arg1 objects:(id *)arg2 count:(unsigned long long)arg3;
- (id)objectEnumerator;
- (id)member:(id)arg1;
- (long long)indexOfObject:(id)arg1;
- (unsigned long long)count;
- (short)changeCount;
- (void)removeAllObjects;
- (void)removeObject:(id)arg1;
- (void)addObject:(id)arg1;
- (void)insertObject:(id)arg1 atIndex:(long long)arg2;
- (void)insertObject:(id)arg1 after:(struct DTBucketTag *)arg2;
- (void)setSet:(id)arg1;
- (void)unionSet:(id)arg1;
- (void)minusSet:(id)arg1;
- (void)intersectSet:(id)arg1;
- (void)addObjectsFromArray:(id)arg1;
- (void)resize:(long long)arg1;
- (void)dealloc;
- (void)encodeWithCoder:(id)arg1;
- (id)initWithCoder:(id)arg1;
- (id)mutableCopyWithZone:(struct _NSZone *)arg1;
- (id)copyWithZone:(struct _NSZone *)arg1;
- (id)initWithCapacity:(unsigned long long)arg1;
- (id)init;
- (id)initWithCallBacks:(CDStruct_f2932e27)arg1;
- (Class)classForCoder;
@end
@interface DTMutableOrderedSetEnumerator : NSEnumerator
{
DTMutableOrderedSet *set;
struct DTBucketTag *bucket;
struct DTBucketTag *head;
long long initialChangeCount;
}
- (id)nextObject;
- (void)dealloc;
- (id)initWithSet:(id)arg1 andHead:(struct DTBucketTag *)arg2;
@end
@interface DTOrderedDictionaryKeyEnumerator : NSEnumerator
{
NSEnumerator *setEnumerator;
}
- (id)nextObject;
- (void)dealloc;
- (id)initWithSetEnumerator:(id)arg1;
@end
@interface DTReverseDragImageStateTransitionPrototype : DTDraggedImageStateTransitionView
{
}
- (void)setProgress:(float)arg1;
@end
@interface DTSimpleDraggedImageState : DTDraggedImageState
{
NSImage *image;
}
- (id)image;
- (void)dealloc;
- (id)initWithImage:(id)arg1;
@end
@interface DTSmartAssetGroup : DTAbstractAssetGroup
{
NSPredicate *predicate;
NSDictionary *intermediatePredicateRepresentation;
}
+ (id)defaultImage;
- (id)assets;
- (id)canidateAssets;
- (void)canidateAssetsChanged:(id)arg1;
- (BOOL)groupsAreEditable;
- (void)setPredicate:(id)arg1 andIntermediateRepresentation:(id)arg2;
- (id)intermediateRepresentation;
- (id)predicate;
- (void)registerForNotifications;
- (void)dealloc;
- (id)initWithPropertyListRepresentation:(id)arg1 assetCategory:(id)arg2 andIdentifiedAssets:(id)arg3;
- (void)buildPropertyListRepresentation:(id)arg1;
- (id)initWithDisplayName:(id)arg1 andAssetCategory:(id)arg2;
@end
@interface DTSmartAssetGroupRuleEditorController : NSObject
{
NSPanel *smartGroupSheet;
NSRuleEditor *smartGroupRuleEditor;
NSTextField *smartGroupLabelTextField;
NSTextField *statusTextField;
DTAssetLibrary *library;
DTSmartAssetGroup *editedGroup;
DTAbstractAssetGroup *editedParentGroup;
id delegate;
}
- (id)basicCompoundRule;
- (id)basicRuleLHS;
- (id)predicateFromIntermediateRuleRepresentation:(id)arg1;
- (id)predicateFormatStringForCriterionID:(id)arg1;
- (id)userInputTypeForCriterionID:(id)arg1;
- (id)findValueForKey:(id)arg1 forCriterionID:(id)arg2 inCriteria:(id)arg3;
- (id)intermediateRepresentationForSmartGroupRow:(long long)arg1;
- (id)intermediateRepresentationForSimpleCriterion:(id)arg1 withDisplayValue:(id)arg2;
- (void)textDidChange:(id)arg1;
- (void)controlTextDidChange:(id)arg1;
- (void)ruleEditorRowsDidChange:(id)arg1;
- (id)ruleEditor:(id)arg1 displayValueForCriterion:(id)arg2 inRow:(long long)arg3;
- (id)ruleEditor:(id)arg1 child:(long long)arg2 forCriterion:(id)arg3 withRowType:(unsigned long long)arg4;
- (long long)ruleEditor:(id)arg1 numberOfChildrenForCriterion:(id)arg2 withRowType:(unsigned long long)arg3;
- (void)updateStatus;
- (void)prepareSmartGroup:(id)arg1 forParent:(id)arg2;
- (void)didEndSmartGroupSheet:(id)arg1 returnCode:(long long)arg2 contextInfo:(void *)arg3;
- (void)beginSmartGroupSheet;
- (void)addRulesForRepresentation:(id)arg1 nextRow:(long long *)arg2 parentRow:(long long)arg3;
- (void)cancelSmartGroupSheet:(id)arg1;
- (void)okSmartGroupSheet:(id)arg1;
- (void)setEditedParentGroup:(id)arg1;
- (id)editedParentGroup;
- (void)setEditedGroup:(id)arg1;
- (id)editedGroup;
- (id)statusTextField;
- (id)smartGroupSheet;
- (id)smartGroupLabelTextField;
- (id)smartGroupRuleEditor;
- (id)library;
- (void)setDelegate:(id)arg1;
- (id)delegate;
- (void)ensureUIIsLoaded;
- (void)dealloc;
- (id)initWithAssetLibrary:(id)arg1;
@end
@interface DTSplitView : NSView
{
NSString *autosaveName;
long long resizingMode;
double dividerThickness;
NSNumber *minViewSizeComponent;
BOOL vertical;
BOOL layingOut;
id delegate;
}
- (void)resetCursorRects;
- (id)dividerCursor;
- (id)autosaveName;
- (void)setAutosaveName:(id)arg1;
- (BOOL)acceptsFirstMouse:(id)arg1;
- (void)drawRect:(struct CGRect)arg1;
- (struct CGRect)dimpleRect;
- (id)dimpleImage;
- (void)mouseDown:(id)arg1;
- (void)splitterPositionMoved;
- (double)minSizeForView:(id)arg1;
- (void)setDelegate:(id)arg1;
- (id)delegate;
- (BOOL)isFlipped;
- (struct CGRect)dividerRect;
- (void)setResizingMode:(long long)arg1;
- (long long)resizingMode;
- (void)resizeSubviewsWithOldSize:(struct CGSize)arg1;
- (void)setVertical:(BOOL)arg1;
- (BOOL)isVertical;
- (void)setSplitterPosition:(double)arg1;
- (double)splitterPosition;
- (void)layoutFromDefaults;
- (void)trackSplitterWithMouseDown:(id)arg1;
- (void)layoutWithOldSize:(struct CGSize)arg1 andNewSize:(struct CGSize)arg2;
- (void)subviewDidResize:(id)arg1;
- (void)setMinViewSize:(struct CGSize)arg1 andMaxViewSize:(struct CGSize)arg2;
- (void)setMinViewFrame:(struct CGRect)arg1 andMaxViewFrame:(struct CGRect)arg2;
- (void)willRemoveSubview:(id)arg1;
- (void)didAddSubview:(id)arg1;
- (id)maxView;
- (id)minView;
- (void)setDividerThickness:(double)arg1;
- (double)dividerThickness;
- (void)setDefaultsBackedMinViewSizeComponent:(double)arg1;
- (double)defaultsBackedMinViewSizeComponent;
- (id)defaultsMinComponentKey;
- (BOOL)isValid;
- (void)dealloc;
- (id)initWithFrame:(struct CGRect)arg1;
@end
@interface DTTemplateButtonCell : NSButtonCell
{
struct CGPoint _origin;
BOOL _useRectHighlight;
}
+ (id)sharedStorage;
+ (void)initialize;
- (id)alternateImage;
- (struct CGRect)drawTitle:(id)arg1 withFrame:(struct CGRect)arg2 inView:(id)arg3;
- (void)drawImage:(id)arg1 withFrame:(struct CGRect)arg2 inView:(id)arg3;
- (void)drawWithFrame:(struct CGRect)arg1 inView:(id)arg2;
- (BOOL)useRectHighlight;
- (void)setUseRectHighlight:(BOOL)arg1;
- (id)initWithCoder:(id)arg1;
- (id)initTextCell:(id)arg1;
@end
@interface DTTemplateCategory : NSObject
{
NSString *displayName;
NSImage *image;
NSMutableArray *templateItems;
NSString *identifier;
}
@property(readonly) NSString *identifier; // @synthesize identifier;
@property(readonly) NSImage *image; // @synthesize image;
@property(readonly) NSString *displayName; // @synthesize displayName;
- (void)addTemplateItem:(id)arg1;
- (void)setTemplateItems:(id)arg1;
- (id)templateItems;
- (void)dealloc;
- (id)initWithDisplayName:(id)arg1 image:(id)arg2 templateItems:(id)arg3 identifier:(id)arg4;
@end
@interface DTTemplateChooserAccessoryBackgroundView : NSView
{
}
- (BOOL)isFlipped;
- (void)drawRect:(struct CGRect)arg1;
@end
@interface DTTemplateChooserDetailView : NSView
{
NSScrollView *descriptionScrollView;
NSTextField *descriptionTextField;
NSTextField *titleTextField;
NSImageView *imageView;
}
- (void)sizeToFit;
- (void)resizeSubviewsWithOldSize:(struct CGSize)arg1;
- (struct CGSize)descriptionSize;
- (double)headerHeight;
- (BOOL)isFlipped;
- (void)setDescription:(id)arg1;
- (void)setImage:(id)arg1;
- (void)setTitle:(id)arg1;
- (void)awakeFromNib;
@end
@interface DTTemplateChooserMatrix : NSMatrix
{
}
- (BOOL)needsPanelToBecomeKey;
- (void)keyDown:(id)arg1;
@end
@interface DTTemplateChooserViewController : NSViewController
{
NSView *templateChooser;
NSView *itemView;
NSScrollView *descriptionScrollView;
NSTextField *headingTextField;
DTTemplateChooserMatrix *categoryMatrix;
DTTemplateChooserMatrix *itemMatrix;
DTSplitView *itemSplitView;
DTFlippedView *descriptionView;
DTTemplateChooserDetailView *detailView;
NSView *accessoryView;
DTTemplateChooserAccessoryBackgroundView *accessoryBackgroundView;
DTTypeCompletionHandler *typeCompletionHandler;
NSMutableArray *templateCategories;
BOOL defaultsRestored;
id delegate;
}
@property(retain) NSView *accessoryView; // @synthesize accessoryView;
@property BOOL defaultsRestored; // @synthesize defaultsRestored;
- (void)splitViewSplitterDidMove:(id)arg1;
- (double)splitView:(id)arg1 minSizeForView:(id)arg2;
- (void)updateAccessoryView;
- (void)updateTemplateDescription;
- (void)updateTemplateItemsMatrix;
- (void)updateTemplateCategoriesMatrix;
- (void)update;
- (void)typeSelectionInMatrix:(id)arg1 forString:(id)arg2;
- (id)typeCompletionHandler:(id)arg1 typeCompletionStringForObject:(id)arg2;
- (void)itemDoubleClicked:(id)arg1;
- (void)itemClicked:(id)arg1;
- (void)updateSelectedTemplateDefault;
- (void)categoryClicked:(id)arg1;
- (void)updateSelectedCategoryDefault;
- (id)delegate;
- (void)setDelegate:(id)arg1;
- (id)selectedCategory;
- (id)selectedTemplate;
- (BOOL)selectLastUsedObjectInMatrix:(id)arg1 forKey:(id)arg2;
- (BOOL)selectObjectInMatrix:(id)arg1 forIdentifier:(id)arg2;
- (void)selectLastUsedObjects;
- (void)setHeadingText:(id)arg1;
- (void)addTemplateCategory:(id)arg1 atIndex:(unsigned long long)arg2;
- (void)addTemplateCategory:(id)arg1;
- (void)clearTemplateCategories;
- (void)setTemplateCategories:(id)arg1;
- (id)templateCategories;
- (void)templateChooserViewControllerViewDidResize:(id)arg1;
- (void)restoreDefaults;
- (void)resetSplitterPosition;
- (void)awakeFromNib;
- (void)dealloc;
- (id)init;
- (void)setInstructionField:(id)arg1;
@end
@interface DTTemplateItem : NSObject
{
NSString *displayName;
NSImage *image;
NSString *descriptionTitle;
NSString *description;
NSString *identifier;
NSString *subidentifier;
NSArray *subtemplates;
DTTemplateItem *selectedSubtemplate;
}
@property(nonatomic) DTTemplateItem *selectedSubtemplate; // @synthesize selectedSubtemplate;
@property(readonly) NSArray *subtemplates; // @synthesize subtemplates;
@property(readonly) NSString *subidentifier; // @synthesize subidentifier;
@property(readonly) NSString *identifier; // @synthesize identifier;
@property(readonly) NSString *description; // @synthesize description;
@property(readonly) NSString *descriptionTitle; // @synthesize descriptionTitle;
@property(readonly) NSImage *image; // @synthesize image;
@property(readonly) NSString *displayName; // @synthesize displayName;
- (id)subtemplateWithSubIdentifier:(id)arg1;
- (void)updateToMatchSelectedSubtemplate;
- (void)setIdentifier:(id)arg1;
- (void)setDescription:(id)arg1;
- (void)setDescriptionTitle:(id)arg1;
- (void)setImage:(id)arg1;
- (void)setDisplayName:(id)arg1;
- (void)dealloc;
- (id)initWithTemplates:(id)arg1 identifier:(id)arg2;
- (id)initWithDisplayName:(id)arg1 image:(id)arg2 description:(id)arg3 descriptionTitle:(id)arg4 identifier:(id)arg5 subidentifier:(id)arg6;
- (id)initWithDisplayName:(id)arg1 image:(id)arg2 description:(id)arg3 descriptionTitle:(id)arg4 identifier:(id)arg5;
@end
@interface DTTileViewItem : NSObject <NSCopying, NSCoding>
{
void *_reserved;
void *_reserved2;
NSMutableData *_archive;
DTTileView *_layoutItemOwnerView;
id _representedObject;
NSView *_view;
struct __tileItemFlags {
unsigned int _selected:1;
unsigned int _clicked:1;
unsigned int _removalNeeded:1;
unsigned int _suppressSelectionChangeNotification:1;
unsigned int _reservedAnimationContainer:28;
} _layoutItemFlags;
struct CGRect _targetViewFrameRect;
struct CGRect _appliedViewFrameRect;
unsigned long long _containerReferenceCounter;
}
- (id)description;
- (void)_finishShowAnimation;
- (void)_finishHideAnimation;
- (void)_applyTargetConfigurationWithAnimationMoveAndResize:(id *)arg1 show:(id *)arg2 hide:(id *)arg3;
- (void)_applyTargetConfigurationWithoutAnimation;
- (void)toggleSelected:(id)arg1;
- (BOOL)isSelected;
- (void)setSelected:(BOOL)arg1;
- (void)_setSelectedWithoutNotification:(BOOL)arg1;
- (struct CGRect)_targetViewFrameRect;
- (void)_setTargetViewFrameRect:(struct CGRect)arg1;
- (BOOL)_isRemovalNeeded;
- (void)_setRemovalNeeded:(BOOL)arg1;
- (id)view;
- (void)setView:(id)arg1;
- (id)representedObject;
- (void)setRepresentedObject:(id)arg1;
- (id)layoutView;
- (void)_setLayoutItemOwnerView:(id)arg1;
- (void)_decreaseContainerReferenceCounter;
- (void)_increaseContainerReferenceCounter;
- (BOOL)isEqual:(id)arg1;
- (void)dealloc;
- (void)_releaseResources;
- (id)copyWithZone:(struct _NSZone *)arg1;
- (void)_copyConnectionsOfView:(id)arg1 referenceObject:(id)arg2 toView:(id)arg3 referenceObject:(id)arg4;
- (void)encodeWithCoder:(id)arg1;
- (id)initWithCoder:(id)arg1;
- (id)init;
- (void)_init;
@end
@interface DTToolTip : NSObject
{
}
+ (id)boldToolTipFont;
+ (id)toolTipFont;
+ (id)attributedToolTipStringForString:(id)arg1;
+ (struct CGPoint)toolTipPositionForMouseLocation:(struct CGPoint)arg1;
+ (void)orderOutToolTip;
+ (void)fadeOut:(id)arg1;
+ (void)showToolTip:(id)arg1 withSourceRect:(struct CGRect)arg2 andMouseLocation:(struct CGPoint)arg3;
+ (void)showToolTip:(id)arg1 withSourceRect:(struct CGRect)arg2 andMouseLocation:(struct CGPoint)arg3 maximumWidth:(double)arg4;
+ (id)scheduledTimerWithInterval:(double)arg1;
@end
@interface DTToolTipManager : NSObject
{
struct __CFDictionary *registeredViews;
id eventMonitor;
NSTimer *timer;
long long enabledBlocks;
}
+ (id)sharedInstance;
- (void)mouseRested:(id)arg1;
- (void)unregisterViewForToolTips:(id)arg1;
- (void)registerViewForToolTips:(id)arg1 delegate:(id)arg2;
- (id)allViews;
- (id)delegateForView:(id)arg1;
- (void)monitorEvent:(id)arg1;
- (void)scheduleMouseRested;
- (void)unscheduleMouseRested;
- (void)enableTooltips;
- (void)disableTooltips;
- (BOOL)tooltipsAreEnabled;
- (void)dealloc;
- (id)init;
@end
@interface DTToolTipView : NSView
{
NSMutableAttributedString *string;
double maxWidth;
}
- (void)drawRect:(struct CGRect)arg1;
- (id)backgroundColor;
- (BOOL)isFlipped;
- (void)setAttributedString:(id)arg1;
- (void)setMaxWidth:(double)arg1;
- (double)maxWidth;
@end
@interface DTTypeCompletionHandler : NSObject
{
BOOL delegateImplementsTypeCompletionStringForObject;
BOOL delegateImplementsCompletionWillExpire;
BOOL delegateImplementsCompletionDisplayShouldExpire;
NSMutableString *completionString;
NSTimer *completionWillExpireTimer;
NSTimer *completionDisplayShouldExpireTimer;
NSString *runLoopMode;
id delegate;
}
+ (id)typeCompletionHandlerWithDelegate:(id)arg1;
+ (id)typeCompletionHandlerWithDelegate:(id)arg1 runLoopMode:(id)arg2;
- (id)processTypeSelectionInput:(id)arg1 objects:(id)arg2 index:(unsigned long long *)arg3 startingAtObject:(id)arg4;
- (id)processTypeSelectionInput:(id)arg1 objects:(id)arg2 index:(unsigned long long *)arg3;
- (void)invalidate;
- (void)expireCompletionDisplay:(id)arg1;
- (void)expireCompletion:(id)arg1;
- (void)clearAndRenewCompletionString;
- (void)clearAndRenewCompletionDisplayShouldExpireTimer;
- (void)clearCompletionDisplayShouldExpireTimer;
- (void)clearAndRenewCompletionWillExpireTimer;
- (void)clearCompletionWillExpireTimer;
- (id)currentTypeCompletionString;
- (void)setDelegate:(id)arg1;
- (id)delegate;
- (void)dealloc;
- (id)initWithDelegate:(id)arg1 runLoopMode:(id)arg2;
@end
@interface DTiMovieAssetCategory : DTAssetCategory
{
}
+ (id)_genericMovieImage;
+ (id)_iLifeBundle;
- (void)observeValueForKeyPath:(id)arg1 ofObject:(id)arg2 change:(id)arg3 context:(void *)arg4;
- (id)identifierForMediaGroup:(id)arg1;
- (id)identifierForMovie:(id)arg1;
- (BOOL)containsAssetWithIdentifer:(id)arg1 inAssetSourceWithIdentifier:(id)arg2 subpath:(id)arg3;
- (id)init;
@end
@interface DTiPhotoAssetCategory : DTAssetCategory
{
}
- (void)observeValueForKeyPath:(id)arg1 ofObject:(id)arg2 change:(id)arg3 context:(void *)arg4;
- (id)init;
@end
@interface IBDragDeleteTarget : NSObject
{
}
- (BOOL)performDragOperation:(id)arg1;
- (BOOL)prepareForDragOperation:(id)arg1;
- (unsigned long long)draggingUpdated:(id)arg1;
- (unsigned long long)draggingEntered:(id)arg1;
@end
@interface IBSimpleCrossfadeDragImageStateTransition : DTDraggedImageStateTransitionView
{
}
- (void)drawRect:(struct CGRect)arg1;
- (void)setProgress:(float)arg1;
- (struct CGSize)idealFrameSize;
- (struct CGPoint)toAnchor;
- (struct CGPoint)fromAnchor;
- (id)toImage;
- (id)fromImage;
- (id)initWithFromState:(id)arg1 andToState:(id)arg2;
@end
@interface NSClipView (ConnectionAutoScrolling)
- (BOOL)dtAutoscrollWithExternalDragEvent:(id)arg1 animate:(BOOL)arg2;
@end
@interface NSOutlineView (DragAndDropEnhancements)
- (id)draggedImageState:(id)arg1;
@end
@interface NSTableView (ConnectionAutoScrolling)
- (BOOL)dtAutoscrollWithExternalDragEvent:(id)arg1 animate:(BOOL)arg2;
@end
@interface NSTableView (DragAndDropEnhancements)
- (id)draggedImageState:(id)arg1;
@end
@interface NSView (ConnectionAutoScrolling)
- (BOOL)dtAutoscrollWithExternalDragEvent:(id)arg1 animate:(BOOL)arg2;
@end
@interface NSWindow (IBHacks)
- (id)draggedImageState:(id)arg1;
- (id)registeredDraggedTypes;
@end
@interface _DTTileViewRubberband : NSView
{
NSColor *_frameColor;
NSColor *_fillColor;
}
- (void)drawRect:(struct CGRect)arg1;
- (BOOL)isOpaque;
- (void)dealloc;
- (id)initWithFrameColor:(id)arg1 fillColor:(id)arg2;
@end
| 29,106 |
451 | <gh_stars>100-1000
#include "StdAfx.h"
#include "PaireImg.h"
using namespace std;
PaireImg::PaireImg() : numImg2(-1) {}
PaireImg::PaireImg(int n, ElSTDNS string nom): numImg2(n), nomFichier(nom) {
nbPtsInit=0;
nbPts=0;
isAlign=true;
for (int i=0; i<5; i++)
moment[i]=0;
}
void PaireImg::SetNbPtsInit(int n) {nbPtsInit=n;}
void PaireImg::IncrNbPts() {nbPts++;}
void PaireImg::SetIsAlign(bool b) {isAlign=b;}
int PaireImg::GetNumImg2() const {return numImg2;}
ElSTDNS string PaireImg::GetNomFichier() const {return nomFichier;}
int PaireImg::GetNbPtsInit() const {return nbPtsInit;}
int PaireImg::GetNbPts() const {return nbPts;}
bool PaireImg::GetIsAlign() const {return isAlign;}
bool PaireImg::operator < (const PaireImg& paire)const {
if (numImg2<paire.GetNumImg2()) {return true;}
else {return false;}
}
bool PaireImg::operator == (const PaireImg& paire)const {
return (numImg2==paire.GetNumImg2()) ;
}
bool PaireImg::operator == (const int num)const {
return (numImg2==num) ;
}
//Alignement
float PaireImg::DistAddPt(float x, float y)const{
float ps=x+(y-b)*a;
float d=1+a*a;
float x1=x-ps/d;
float y1=y-b-ps*a/d;
return x1*x1+y1*y1;
}
float PaireImg::DistRemovePt(float x, float y)const{return 0;}
void PaireImg::RecalculeAddPt(float x, float y, float dmax){
nbPts++;
if (nbPts>2 && isAlign) isAlign=(DistAddPt(x,y)<dmax*dmax);
if(isAlign) {
moment[0]+=x;
moment[1]+=y;
moment[2]+=x*x;
moment[3]+=x*y;
moment[4]+=y*y;
if (nbPts>1){
float A=(nbPts)*moment[3]+(-moment[1])*moment[1];
float B=(-moment[1])*moment[3]+(moment[2])*moment[1];
float D=moment[2]*nbPts+moment[0]*moment[0];
a=A/D;
b=B/D;
}
}
}
void PaireImg::RecalculeRemovePt(float x, float y){}
| 952 |
839 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.cxf.staxutils;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
/**
* Read from a StaX reader, stopping when the next element is a specified element.
* For example, this can be used to read all of the Header of a soap message into a DOM
* document stopping on contact with the body element.
*/
public class PartialXMLStreamReader extends DepthXMLStreamReader {
private QName endTag;
private boolean foundEnd;
private int endDepth;
private int currentEvent;
public PartialXMLStreamReader(XMLStreamReader r, QName endTag) {
super(r);
this.endTag = endTag;
currentEvent = r.getEventType();
}
@Override
public int next() throws XMLStreamException {
if (!foundEnd) {
currentEvent = super.next();
if (currentEvent == START_ELEMENT && getName().equals(endTag)) {
foundEnd = true;
endDepth = getDepth();
return START_ELEMENT;
}
return currentEvent;
} else if (endDepth > 0) {
endDepth--;
currentEvent = END_ELEMENT;
} else {
currentEvent = END_DOCUMENT;
}
return currentEvent;
}
@Override
public int getEventType() {
return currentEvent;
}
@Override
public boolean hasNext() {
return currentEvent != END_DOCUMENT;
}
}
| 800 |
2,073 | <reponame>thg-josh-coutinho/activemq<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.activemq.shiro.subject;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.Permission;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.ExecutionException;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.Callable;
/**
* @since 5.10.0
*/
public class SubjectAdapter implements Subject {
@Override
public Object getPrincipal() {
return null;
}
@Override
public PrincipalCollection getPrincipals() {
return null;
}
@Override
public boolean isPermitted(String permission) {
return false;
}
@Override
public boolean isPermitted(Permission permission) {
return false;
}
@Override
public boolean[] isPermitted(String... permissions) {
return new boolean[0];
}
@Override
public boolean[] isPermitted(List<Permission> permissions) {
return new boolean[0];
}
@Override
public boolean isPermittedAll(String... permissions) {
return false;
}
@Override
public boolean isPermittedAll(Collection<Permission> permissions) {
return false;
}
@Override
public void checkPermission(String permission) throws AuthorizationException {
}
@Override
public void checkPermission(Permission permission) throws AuthorizationException {
}
@Override
public void checkPermissions(String... permissions) throws AuthorizationException {
}
@Override
public void checkPermissions(Collection<Permission> permissions) throws AuthorizationException {
}
@Override
public boolean hasRole(String roleIdentifier) {
return false;
}
@Override
public boolean[] hasRoles(List<String> roleIdentifiers) {
return new boolean[0]; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public boolean hasAllRoles(Collection<String> roleIdentifiers) {
return false;
}
@Override
public void checkRole(String roleIdentifier) throws AuthorizationException {
}
@Override
public void checkRoles(Collection<String> roleIdentifiers) throws AuthorizationException {
}
@Override
public void checkRoles(String... roleIdentifiers) throws AuthorizationException {
}
@Override
public void login(AuthenticationToken token) throws AuthenticationException {
}
@Override
public boolean isAuthenticated() {
return false;
}
@Override
public boolean isRemembered() {
return false;
}
@Override
public Session getSession() {
return null;
}
@Override
public Session getSession(boolean create) {
return null;
}
@Override
public void logout() {
}
@Override
public <V> V execute(Callable<V> callable) throws ExecutionException {
return null;
}
@Override
public void execute(Runnable runnable) {
}
@Override
public <V> Callable<V> associateWith(Callable<V> callable) {
return null;
}
@Override
public Runnable associateWith(Runnable runnable) {
return runnable;
}
@Override
public void runAs(PrincipalCollection principals) throws NullPointerException, IllegalStateException {
}
@Override
public boolean isRunAs() {
return false;
}
@Override
public PrincipalCollection getPreviousPrincipals() {
return null;
}
@Override
public PrincipalCollection releaseRunAs() {
return null;
}
}
| 1,548 |
884 | /*
* Copyright 2014 - 2021 Blazebit.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.blazebit.persistence.impl;
import com.blazebit.persistence.parser.expression.AbortableVisitorAdapter;
import com.blazebit.persistence.parser.expression.FunctionExpression;
import com.blazebit.persistence.parser.expression.PathExpression;
import com.blazebit.persistence.parser.predicate.CompoundPredicate;
import com.blazebit.persistence.parser.predicate.IsNullPredicate;
/**
* Finds a PathExpression, and while traversing back along the stack, capture if we are in a disjunction.
* This is necessary for the EXISTS subquery rewrite for associations used in the ON clause.
* We must know, if the association represented by the path expression, is used in a context,
* where the cardinality 0 might be problematic. In a disjunctive or null aware context, cardinality is important.
* We say, it is "inConjunction" if the path expression is used in no disjunctive or null aware context.
*
* @author <NAME>
* @since 1.4.0
*/
public class ConjunctionPathExpressionFindingVisitor extends AbortableVisitorAdapter {
private PathExpression pathExpression;
private boolean disjunction;
public boolean isInConjunction(CompoundPredicate predicate, PathExpression pathExpression) {
this.pathExpression = pathExpression;
this.disjunction = false;
try {
predicate.accept(this);
return !disjunction;
} finally {
this.pathExpression = null;
}
}
@Override
public Boolean visit(PathExpression expression) {
if (pathExpression == expression) {
return true;
}
return super.visit(expression);
}
@Override
public Boolean visit(IsNullPredicate predicate) {
if (super.visit(predicate)) {
// When the path is used in a NULL aware context, we say it is in a disjunctive context
disjunction = true;
return true;
}
return false;
}
@Override
public Boolean visit(FunctionExpression expression) {
if (super.visit(expression)) {
if ("COALESCE".equalsIgnoreCase(expression.getFunctionName()) || "NULLIF".equalsIgnoreCase(expression.getFunctionName())) {
// When the path is used in a NULL aware context, we say it is in a disjunctive context
disjunction = true;
}
return true;
}
return false;
}
@Override
public Boolean visit(CompoundPredicate predicate) {
if (super.visit(predicate)) {
disjunction = disjunction || predicate.getOperator() == CompoundPredicate.BooleanOperator.OR ^ predicate.isNegated();
return true;
}
return false;
}
}
| 1,162 |
5,447 | <reponame>Kh4L/gluon-cv<filename>gluoncv/model_zoo/simple_pose/pose_target.py
"""
Target generator for Simple Baselines for Human Pose Estimation and Tracking
(https://arxiv.org/abs/1804.06208)
---------------------------------------------
Copyright (c) Microsoft
Licensed under the MIT License.
Written by <NAME> (<EMAIL>)
---------------------------------------------
"""
import numpy as np
class SimplePoseGaussianTargetGenerator(object):
"""Gaussian heatmap target generator for simple pose.
Adapted from https://github.com/Microsoft/human-pose-estimation.pytorch
Parameters
----------
num_joints : int
Number of joints defined by dataset
image_size : tuple of int
Image size, as (width, height).
heatmap_size : tuple of int
Heatmap size, as (width, height).
sigma : float
Gaussian sigma for the heatmap generation.
"""
def __init__(self, num_joints, image_size, heatmap_size, sigma=2):
self._num_joints = num_joints
self._sigma = sigma
self._image_size = np.array(image_size)
self._heatmap_size = np.array(heatmap_size)
assert self._image_size.shape == (2,), "Invalid shape of image_size, expected (2,)"
assert self._heatmap_size.shape == (2,), "Invalid shape of heatmap_size, expected (2,)"
self._feat_stride = self._image_size / self._heatmap_size
def __call__(self, joints_3d):
"""Generate heatmap target and target_weight
Parameters
----------
joints_3d : numpy.ndarray
3D joints, with shape (num_joints, 3, 2)
Returns
-------
(numpy.ndarray, numpy.ndarray)
target : regression target, with shape (num_joints, heatmap_h, heatmap_w)
target_weight : target weight to mask out non-interest target, shape (num_joints, 1, 1)
"""
target_weight = np.ones((self._num_joints, 1), dtype=np.float32)
target_weight[:, 0] = joints_3d[:, 0, 1]
target = np.zeros((self._num_joints, self._heatmap_size[1], self._heatmap_size[0]),
dtype=np.float32)
tmp_size = self._sigma * 3
for i in range(self._num_joints):
mu_x = int(joints_3d[i, 0, 0] / self._feat_stride[0] + 0.5)
mu_y = int(joints_3d[i, 1, 0] / self._feat_stride[1] + 0.5)
# check if any part of the gaussian is in-bounds
ul = [int(mu_x - tmp_size), int(mu_y - tmp_size)]
br = [int(mu_x + tmp_size + 1), int(mu_y + tmp_size + 1)]
if (ul[0] >= self._heatmap_size[0] or ul[1] >= self._heatmap_size[1] or
br[0] < 0 or br[1] < 0):
# return image as is
target_weight[i] = 0
continue
# generate gaussian
size = 2 * tmp_size + 1
x = np.arange(0, size, 1, np.float32)
y = x[:, np.newaxis]
x0 = y0 = size // 2
# the gaussian is not normalized, we want the center value to be equal to 1
g = np.exp(-((x - x0) ** 2 + (y - y0) ** 2) / (2 * (self._sigma ** 2)))
# usable gaussian range
g_x = max(0, -ul[0]), min(br[0], self._heatmap_size[0]) - ul[0]
g_y = max(0, -ul[1]), min(br[1], self._heatmap_size[1]) - ul[1]
# image range
img_x = max(0, ul[0]), min(br[0], self._heatmap_size[0])
img_y = max(0, ul[1]), min(br[1], self._heatmap_size[1])
v = target_weight[i]
if v > 0.5:
target[i, img_y[0]:img_y[1], img_x[0]:img_x[1]] = g[g_y[0]:g_y[1], g_x[0]:g_x[1]]
return target, np.expand_dims(target_weight, -1)
| 1,751 |
32,544 | <reponame>DBatOWL/tutorials
package com.baeldung.concurrent.semaphore;
import java.util.concurrent.Semaphore;
public class SemaPhoreDemo {
static Semaphore semaphore = new Semaphore(10);
public void execute() throws InterruptedException {
System.out.println("Available permit : " + semaphore.availablePermits());
System.out.println("Number of threads waiting to acquire: " + semaphore.getQueueLength());
if (semaphore.tryAcquire()) {
try {
// perform some critical operations
} finally {
semaphore.release();
}
}
}
}
| 197 |
3,562 | // 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.
#ifndef DORIS_BE_SRC_UTIL_THREAD_POOL_H
#define DORIS_BE_SRC_UTIL_THREAD_POOL_H
#include <boost/intrusive/list.hpp>
#include <boost/intrusive/list_hook.hpp>
#include <deque>
#include <functional>
#include <memory>
#include <string>
#include <unordered_set>
#include <utility>
#include "common/atomic.h"
#include "common/status.h"
#include "gutil/ref_counted.h"
#include "util/condition_variable.h"
#include "util/monotime.h"
#include "util/mutex.h"
namespace doris {
class Thread;
class ThreadPool;
class ThreadPoolToken;
class Runnable {
public:
virtual void run() = 0;
virtual ~Runnable() {}
};
// ThreadPool takes a lot of arguments. We provide sane defaults with a builder.
//
// name: Used for debugging output and default names of the worker threads.
// Since thread names are limited to 16 characters on Linux, it's good to
// choose a short name here.
// Required.
//
// trace_metric_prefix: used to prefix the names of TraceMetric counters.
// When a task on a thread pool has an associated trace, the thread pool
// implementation will increment TraceMetric counters to indicate the
// amount of time spent waiting in the queue as well as the amount of wall
// and CPU time spent executing. By default, these counters are prefixed
// with the name of the thread pool. For example, if the pool is named
// 'apply', then counters such as 'apply.queue_time_us' will be
// incremented.
//
// The TraceMetrics implementation relies on the number of distinct counter
// names being small. Thus, if the thread pool name itself is dynamically
// generated, the default behavior described above would result in an
// unbounded number of distinct counter names. The 'trace_metric_prefix'
// setting can be used to override the prefix used in generating the trace
// metric names.
//
// For example, the Raft thread pools are named "<tablet id>-raft" which
// has unbounded cardinality (a server may have thousands of different
// tablet IDs over its lifetime). In that case, setting the prefix to
// "raft" will avoid any issues.
//
// min_threads: Minimum number of threads we'll have at any time.
// Default: 0.
//
// max_threads: Maximum number of threads we'll have at any time.
// Default: Number of CPUs detected on the system.
//
// max_queue_size: Maximum number of items to enqueue before returning a
// Status::ServiceUnavailable message from Submit().
// Default: INT_MAX.
//
// idle_timeout: How long we'll keep around an idle thread before timing it out.
// We always keep at least min_threads.
// Default: 500 milliseconds.
//
// metrics: Histograms, counters, etc. to update on various threadpool events.
// Default: not set.
//
class ThreadPoolBuilder {
public:
explicit ThreadPoolBuilder(std::string name);
// Note: We violate the style guide by returning mutable references here
// in order to provide traditional Builder pattern conveniences.
ThreadPoolBuilder& set_min_threads(int min_threads);
ThreadPoolBuilder& set_max_threads(int max_threads);
ThreadPoolBuilder& set_max_queue_size(int max_queue_size);
ThreadPoolBuilder& set_idle_timeout(const MonoDelta& idle_timeout);
// Instantiate a new ThreadPool with the existing builder arguments.
Status build(std::unique_ptr<ThreadPool>* pool) const;
private:
friend class ThreadPool;
const std::string _name;
int _min_threads;
int _max_threads;
int _max_queue_size;
MonoDelta _idle_timeout;
DISALLOW_COPY_AND_ASSIGN(ThreadPoolBuilder);
};
// Thread pool with a variable number of threads.
//
// Tasks submitted directly to the thread pool enter a FIFO queue and are
// dispatched to a worker thread when one becomes free. Tasks may also be
// submitted via ThreadPoolTokens. The token Wait() and Shutdown() functions
// can then be used to block on logical groups of tasks.
//
// A token operates in one of two ExecutionModes, determined at token
// construction time:
// 1. SERIAL: submitted tasks are run one at a time.
// 2. CONCURRENT: submitted tasks may be run in parallel. This isn't unlike
// tasks submitted without a token, but the logical grouping that tokens
// impart can be useful when a pool is shared by many contexts (e.g. to
// safely shut down one context, to derive context-specific metrics, etc.).
//
// Tasks submitted without a token or via ExecutionMode::CONCURRENT tokens are
// processed in FIFO order. On the other hand, ExecutionMode::SERIAL tokens are
// processed in a round-robin fashion, one task at a time. This prevents them
// from starving one another. However, tokenless (and CONCURRENT token-based)
// tasks can starve SERIAL token-based tasks.
//
// Usage Example:
// static void Func(int n) { ... }
// class Task : public Runnable { ... }
//
// std::unique_ptr<ThreadPool> thread_pool;
// CHECK_OK(
// ThreadPoolBuilder("my_pool")
// .set_min_threads(0)
// .set_max_threads(5)
// .set_max_queue_size(10)
// .set_idle_timeout(MonoDelta::FromMilliseconds(2000))
// .Build(&thread_pool));
// thread_pool->Submit(shared_ptr<Runnable>(new Task()));
// thread_pool->SubmitFunc(std::bind(&Func, 10));
class ThreadPool {
public:
~ThreadPool();
// Wait for the running tasks to complete and then shutdown the threads.
// All the other pending tasks in the queue will be removed.
// NOTE: That the user may implement an external abort logic for the
// runnables, that must be called before Shutdown(), if the system
// should know about the non-execution of these tasks, or the runnable
// require an explicit "abort" notification to exit from the run loop.
void shutdown();
// Submits a Runnable class.
Status submit(std::shared_ptr<Runnable> r);
// Submits a function bound using std::bind(&FuncName, args...).
Status submit_func(std::function<void()> f);
// Waits until all the tasks are completed.
void wait();
// Waits for the pool to reach the idle state, or until 'until' time is reached.
// Returns true if the pool reached the idle state, false otherwise.
bool wait_until(const MonoTime& until);
// Waits for the pool to reach the idle state, or until 'delta' time elapses.
// Returns true if the pool reached the idle state, false otherwise.
bool wait_for(const MonoDelta& delta);
Status set_min_threads(int min_threads);
Status set_max_threads(int max_threads);
// Allocates a new token for use in token-based task submission. All tokens
// must be destroyed before their ThreadPool is destroyed.
//
// There is no limit on the number of tokens that may be allocated.
enum class ExecutionMode {
// Tasks submitted via this token will be executed serially.
SERIAL,
// Tasks submitted via this token may be executed concurrently.
CONCURRENT
};
std::unique_ptr<ThreadPoolToken> new_token(ExecutionMode mode, int max_concurrency = INT_MAX);
// Return the number of threads currently running (or in the process of starting up)
// for this thread pool.
int num_threads() const {
MutexLock l(&_lock);
return _num_threads + _num_threads_pending_start;
}
int max_threads() const {
MutexLock l(&_lock);
return _max_threads;
}
int min_threads() const {
MutexLock l(&_lock);
return _min_threads;
}
int num_threads_pending_start() const {
MutexLock l(&_lock);
return _num_threads_pending_start;
}
int num_active_threads() const {
MutexLock l(&_lock);
return _active_threads;
}
int get_queue_size() const {
MutexLock l(&_lock);
return _total_queued_tasks;
}
private:
friend class ThreadPoolBuilder;
friend class ThreadPoolToken;
// Client-provided task to be executed by this pool.
struct Task {
std::shared_ptr<Runnable> runnable;
// Time at which the entry was submitted to the pool.
MonoTime submit_time;
};
// Creates a new thread pool using a builder.
explicit ThreadPool(const ThreadPoolBuilder& builder);
// Initializes the thread pool by starting the minimum number of threads.
Status init();
// Dispatcher responsible for dequeueing and executing the tasks
void dispatch_thread();
// Create new thread.
//
// REQUIRES: caller has incremented '_num_threads_pending_start' ahead of this call.
// NOTE: For performance reasons, _lock should not be held.
Status create_thread();
// Aborts if the current thread is a member of this thread pool.
void check_not_pool_thread_unlocked();
// Submits a task to be run via token.
Status do_submit(std::shared_ptr<Runnable> r, ThreadPoolToken* token);
// Releases token 't' and invalidates it.
void release_token(ThreadPoolToken* t);
const std::string _name;
int _min_threads;
int _max_threads;
const int _max_queue_size;
const MonoDelta _idle_timeout;
// Overall status of the pool. Set to an error when the pool is shut down.
//
// Protected by '_lock'.
Status _pool_status;
// Synchronizes many of the members of the pool and all of its
// condition variables.
mutable Mutex _lock;
// Condition variable for "pool is idling". Waiters wake up when
// _active_threads reaches zero.
ConditionVariable _idle_cond;
// Condition variable for "pool has no threads". Waiters wake up when
// _num_threads and num_pending_threads_ are both 0.
ConditionVariable _no_threads_cond;
// Number of threads currently running.
//
// Protected by _lock.
int _num_threads;
// Number of threads which are in the process of starting.
// When these threads start, they will decrement this counter and
// accordingly increment '_num_threads'.
//
// Protected by _lock.
int _num_threads_pending_start;
// Number of threads currently running and executing client tasks.
//
// Protected by _lock.
int _active_threads;
// Total number of client tasks queued, either directly (_queue) or
// indirectly (_tokens).
//
// Protected by _lock.
int _total_queued_tasks;
// All allocated tokens.
//
// Protected by _lock.
std::unordered_set<ThreadPoolToken*> _tokens;
// FIFO of tokens from which tasks should be executed. Does not own the
// tokens; they are owned by clients and are removed from the FIFO on shutdown.
//
// Protected by _lock.
std::deque<ThreadPoolToken*> _queue;
// Pointers to all running threads. Raw pointers are safe because a Thread
// may only go out of scope after being removed from _threads.
//
// Protected by _lock.
std::unordered_set<Thread*> _threads;
// List of all threads currently waiting for work.
//
// A thread is added to the front of the list when it goes idle and is
// removed from the front and signaled when new work arrives. This produces a
// LIFO usage pattern that is more efficient than idling on a single
// ConditionVariable (which yields FIFO semantics).
//
// Protected by _lock.
struct IdleThread : public boost::intrusive::list_base_hook<> {
explicit IdleThread(Mutex* m) : not_empty(m) {}
// Condition variable for "queue is not empty". Waiters wake up when a new
// task is queued.
ConditionVariable not_empty;
DISALLOW_COPY_AND_ASSIGN(IdleThread);
};
boost::intrusive::list<IdleThread> _idle_threads; // NOLINT(build/include_what_you_use)
// ExecutionMode::CONCURRENT token used by the pool for tokenless submission.
std::unique_ptr<ThreadPoolToken> _tokenless;
DISALLOW_COPY_AND_ASSIGN(ThreadPool);
};
// Entry point for token-based task submission and blocking for a particular
// thread pool. Tokens can only be created via ThreadPool::new_token().
//
// All functions are thread-safe. Mutable members are protected via the
// ThreadPool's lock.
class ThreadPoolToken {
public:
// Destroys the token.
//
// May be called on a token with outstanding tasks, as Shutdown() will be
// called first to take care of them.
~ThreadPoolToken();
// Submits a Runnable class.
Status submit(std::shared_ptr<Runnable> r);
// Submits a function bound using std::bind(&FuncName, args...).
Status submit_func(std::function<void()> f);
// Marks the token as unusable for future submissions. Any queued tasks not
// yet running are destroyed. If tasks are in flight, Shutdown() will wait
// on their completion before returning.
void shutdown();
// Waits until all the tasks submitted via this token are completed.
void wait();
// Waits for all submissions using this token are complete, or until 'until'
// time is reached.
//
// Returns true if all submissions are complete, false otherwise.
bool wait_until(const MonoTime& until);
// Waits for all submissions using this token are complete, or until 'delta'
// time elapses.
//
// Returns true if all submissions are complete, false otherwise.
bool wait_for(const MonoDelta& delta);
bool need_dispatch();
size_t num_tasks() {
MutexLock l(&_pool->_lock);
return _entries.size();
}
private:
// All possible token states. Legal state transitions:
// IDLE -> RUNNING: task is submitted via token
// IDLE -> QUIESCED: token or pool is shut down
// RUNNING -> IDLE: worker thread finishes executing a task and
// there are no more tasks queued to the token
// RUNNING -> QUIESCING: token or pool is shut down while worker thread
// is executing a task
// RUNNING -> QUIESCED: token or pool is shut down
// QUIESCING -> QUIESCED: worker thread finishes executing a task
// belonging to a shut down token or pool
enum class State {
// Token has no queued tasks.
IDLE,
// A worker thread is running one of the token's previously queued tasks.
RUNNING,
// No new tasks may be submitted to the token. A worker thread is still
// running a previously queued task.
QUIESCING,
// No new tasks may be submitted to the token. There are no active tasks
// either. At this state, the token may only be destroyed.
QUIESCED,
};
// Writes a textual representation of the token state in 's' to 'o'.
friend std::ostream& operator<<(std::ostream& o, ThreadPoolToken::State s);
friend class ThreadPool;
// Returns a textual representation of 's' suitable for debugging.
static const char* state_to_string(State s);
// Constructs a new token.
//
// The token may not outlive its thread pool ('pool').
ThreadPoolToken(ThreadPool* pool, ThreadPool::ExecutionMode mode, int max_concurrency = INT_MAX);
// Changes this token's state to 'new_state' taking actions as needed.
void transition(State new_state);
// Returns true if this token has a task queued and ready to run, or if a
// task belonging to this token is already running.
bool is_active() const { return _state == State::RUNNING || _state == State::QUIESCING; }
// Returns true if new tasks may be submitted to this token.
bool may_submit_new_tasks() const {
return _state != State::QUIESCING && _state != State::QUIESCED;
}
State state() const { return _state; }
ThreadPool::ExecutionMode mode() const { return _mode; }
// Token's configured execution mode.
ThreadPool::ExecutionMode _mode;
// Pointer to the token's thread pool.
ThreadPool* _pool;
// Token state machine.
State _state;
// Queued client tasks.
std::deque<ThreadPool::Task> _entries;
// Condition variable for "token is idle". Waiters wake up when the token
// transitions to IDLE or QUIESCED.
ConditionVariable _not_running_cond;
// Number of worker threads currently executing tasks belonging to this
// token.
int _active_threads;
// The max number of tasks that can be ran concurrenlty. This is to limit
// the concurrency of a thread pool token, and default is INT_MAX(no limited)
int _max_concurrency;
// Number of tasks which has been submitted to the thread pool's queue.
int _num_submitted_tasks;
// Number of tasks which has not been submitted to the thread pool's queue.
int _num_unsubmitted_tasks;
DISALLOW_COPY_AND_ASSIGN(ThreadPoolToken);
};
} // namespace doris
#endif //DORIS_BE_SRC_UTIL_THREAD_POOL_H
| 5,792 |
521 | # -*- coding: utf-8 -*-
"""Test Python routines."""
# -----------------------------------------------------------------------------
# Imports
# -----------------------------------------------------------------------------
from ..python import _is_python, PythonFilter
# -----------------------------------------------------------------------------
# Test Python
# -----------------------------------------------------------------------------
def test_python():
assert _is_python("print('Hello world!')")
assert not _is_python("Hello world!")
def test_python_filter():
filter = PythonFilter()
assert filter('a\nb # ipymd-skip\nc\n') == 'a\nb # ipymd-skip\nc'
filter = PythonFilter(ipymd_skip=True)
assert filter('a\nb # ipymd-skip\nc\n') == 'a\nc'
| 197 |
14,668 | <gh_stars>1000+
// 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 "base/at_exit.h"
#include "base/command_line.h"
#include "base/message_loop/message_pump_type.h"
#include "base/run_loop.h"
#include "base/task/single_thread_task_executor.h"
#include "base/task/thread_pool/thread_pool_instance.h"
#include "mojo/core/embedder/embedder.h"
#include "remoting/test/ftl_signaling_playground.h"
int main(int argc, char const* argv[]) {
base::AtExitManager exitManager;
base::CommandLine::Init(argc, argv);
base::SingleThreadTaskExecutor io_task_executor(base::MessagePumpType::IO);
remoting::FtlSignalingPlayground playground;
if (playground.ShouldPrintHelp()) {
playground.PrintHelp();
return 0;
}
base::ThreadPoolInstance::CreateAndStartWithDefaultParams(
"FtlSignalingPlayground");
mojo::core::Init();
playground.StartLoop();
return 0;
}
| 345 |
1,056 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.j2ee.deployment.impl.ui.actions;
import org.netbeans.modules.j2ee.deployment.impl.ServerInstance;
import org.openide.util.HelpCtx;
import org.openide.NotifyDescriptor;
import org.openide.util.NbBundle;
import org.openide.DialogDisplayer;
import org.openide.nodes.Node;
import org.openide.util.actions.CookieAction;
/**
* Remove instance action displays a confirmation dialog whether the server should
* be removed. The server is stopped before removal if it was started from within
* the IDE before.
*
* @author nn136682
*/
public class RemoveAction extends CookieAction {
protected void performAction(org.openide.nodes.Node[] nodes) {
for (int i=0; i<nodes.length; i++) {
ServerInstance instance = (ServerInstance) nodes[i].getCookie(ServerInstance.class);
if (instance == null || instance.isRemoveForbidden()) {
continue;
}
String title = NbBundle.getMessage(RemoveAction.class, "MSG_RemoveInstanceTitle");
String msg = NbBundle.getMessage(RemoveAction.class, "MSG_ReallyRemoveInstance", instance.getDisplayName());
NotifyDescriptor d = new NotifyDescriptor.Confirmation(msg, title, NotifyDescriptor.YES_NO_OPTION);
if (DialogDisplayer.getDefault().notify(d) == NotifyDescriptor.YES_OPTION) {
instance.remove();
}
}
}
protected boolean enable (Node[] nodes) {
for (int i = 0; i < nodes.length; i++) {
ServerInstance instance = (ServerInstance)nodes[i].getCookie(ServerInstance.class);
if (instance == null || instance.isRemoveForbidden()
|| instance.getServerState() == ServerInstance.STATE_WAITING) {
return false;
}
}
return true;
}
protected Class[] cookieClasses() {
return new Class[] {
ServerInstance.class
};
}
protected int mode() {
return MODE_ALL;
}
public String getName() {
return NbBundle.getMessage(RemoveAction.class, "LBL_Remove");
}
public org.openide.util.HelpCtx getHelpCtx() {
return HelpCtx.DEFAULT_HELP;
}
protected boolean asynchronous() {
return false;
}
}
| 1,155 |
746 | package io.openlineage.spark.agent.lifecycle.plan;
import io.openlineage.spark.agent.SparkAgentTestExtension;
import org.junit.jupiter.api.extension.ExtendWith;
@ExtendWith(SparkAgentTestExtension.class)
class JDBCRelationVisitorTest {}
| 84 |
1,546 | /////////////////////////////////////////////////////////////////////////////////////////////////
//
// Tencent is pleased to support the open source community by making libpag available.
//
// Copyright (C) 2021 THL A29 Limited, a Tencent company. 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.
//
/////////////////////////////////////////////////////////////////////////////////////////////////
#pragma once
#include "tgfx/core/Mesh.h"
namespace tgfx {
class TriangularPathMesh : public Mesh {
public:
TriangularPathMesh(std::vector<float> vertices, int vertexCount, Rect bounds)
: _vertices(std::move(vertices)), _vertexCount(vertexCount), _bounds(bounds) {
}
Rect bounds() const override {
return _bounds;
}
private:
std::pair<std::unique_ptr<GLDrawOp>, Matrix> getOp(const Matrix& viewMatrix) const override;
std::vector<float> _vertices;
int _vertexCount;
Rect _bounds;
};
} // namespace tgfx
| 392 |
2,268 | <filename>sp/src/utils/vbsp/manifest.h<gh_stars>1000+
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=====================================================================================//
#ifndef __MANIFEST_H
#define __MANIFEST_H
#ifdef _WIN32
#pragma once
#endif
#include "boundbox.h"
//
// Each cordon is a named collection of bounding boxes.
//
struct Cordon_t
{
inline Cordon_t()
{
m_bActive = false;
}
CUtlString m_szName;
bool m_bActive; // True means cull using this cordon when cordoning is enabled.
CUtlVector<BoundBox> m_Boxes;
};
class CManifestMap
{
public:
CManifestMap( void );
char m_RelativeMapFileName[ MAX_PATH ];
bool m_bTopLevelMap;
};
class CManifest
{
public:
CManifest( void );
static ChunkFileResult_t LoadManifestMapKeyCallback( const char *szKey, const char *szValue, CManifestMap *pManifestMap );
static ChunkFileResult_t LoadManifestVMFCallback( CChunkFile *pFile, CManifest *pManifest );
static ChunkFileResult_t LoadManifestMapsCallback( CChunkFile *pFile, CManifest *pManifest );
static ChunkFileResult_t LoadCordonBoxCallback( CChunkFile *pFile, Cordon_t *pCordon );
static ChunkFileResult_t LoadCordonBoxKeyCallback( const char *szKey, const char *szValue, BoundBox *pBox );
static ChunkFileResult_t LoadCordonKeyCallback( const char *szKey, const char *szValue, Cordon_t *pCordon );
static ChunkFileResult_t LoadCordonCallback( CChunkFile *pFile, CManifest *pManifest );
static ChunkFileResult_t LoadCordonsKeyCallback( const char *pszKey, const char *pszValue, CManifest *pManifest );
static ChunkFileResult_t LoadCordonsCallback( CChunkFile *pFile, CManifest *pManifest );
static ChunkFileResult_t LoadManifestCordoningPrefsCallback( CChunkFile *pFile, CManifest *pManifest );
bool LoadSubMaps( CMapFile *pMapFile, const char *pszFileName );
epair_t *CreateEPair( char *pKey, char *pValue );
bool LoadVMFManifest( const char *pszFileName );
const char *GetInstancePath( ) { return m_InstancePath; }
void CordonWorld( );
private:
bool LoadVMFManifestUserPrefs( const char *pszFileName );
CUtlVector< CManifestMap * > m_Maps;
char m_InstancePath[ MAX_PATH ];
bool m_bIsCordoning;
CUtlVector< Cordon_t > m_Cordons;
entity_t *m_CordoningMapEnt;
};
#endif // #ifndef __MANIFEST_H
| 869 |
4,339 | /*
* 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.ignite.internal.processors.cache;
import java.net.URL;
import java.util.Random;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.cache.CacheAtomicityMode;
import org.apache.ignite.cache.CacheInterceptor;
import org.apache.ignite.cache.CacheInterceptorAdapter;
import org.apache.ignite.cache.affinity.rendezvous.RendezvousAffinityFunction;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.internal.IgniteEx;
import org.apache.ignite.internal.util.typedef.G;
import org.apache.ignite.testframework.GridTestExternalClassLoader;
import org.apache.ignite.testframework.config.GridTestProperties;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
import org.junit.Test;
import static java.lang.Math.abs;
/**
* Checks that exception does not happen when a cache interceptor absences in a client side.
*/
public class NoPresentCacheInterceptorOnClientTest extends GridCommonAbstractTest {
/** Name of transactional cache. */
private static final String TX_DEFAULT_CACHE_NAME = "tx_" + DEFAULT_CACHE_NAME;
/** Quantity of entries which will load. */
private static final int ENTRIES_TO_LOAD = 100;
/** Cache interceptor class name. */
private static final String INTERCEPTOR_CLASS = "org.apache.ignite.tests.p2p.cache.OddEvenCacheInterceptor";
/** True that means a custom classloader will be assigned through node configuration, otherwise false. */
private boolean useCustomLdr;
/** Test class loader. */
private ClassLoader testClassLoader;
/** {@inheritDoc} */
@Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);
if (useCustomLdr)
cfg.setClassLoader(testClassLoader);
return cfg;
}
/** {@inheritDoc} */
@Override protected void beforeTest() throws Exception {
super.beforeTest();
stopAllGrids();
testClassLoader = new GridTestExternalClassLoader(new URL[] {
new URL(GridTestProperties.getProperty("p2p.uri.cls"))});
}
/**
* Test starts two caches and checks (both with interceptor configured) them that they work on a client side.
*
* @throws Exception If failed.
*/
@Test
public void testStartCacheFromServer() throws Exception {
useCustomLdr = true;
IgniteEx ignite0 = startGrid(0);
IgniteCache<Integer, Integer> cache = ignite0.getOrCreateCache(generateCacheConfiguration(
DEFAULT_CACHE_NAME,
CacheAtomicityMode.ATOMIC
));
IgniteCache<Integer, Integer> txCache = ignite0.getOrCreateCache(generateCacheConfiguration(
TX_DEFAULT_CACHE_NAME,
CacheAtomicityMode.TRANSACTIONAL
));
checkCache(cache, false);
checkCache(txCache, false);
useCustomLdr = false;
IgniteEx client = startClientGrid(1);
assertNotNull(cache.getConfiguration(CacheConfiguration.class).getInterceptor());
assertNotNull(txCache.getConfiguration(CacheConfiguration.class).getInterceptor());
checkCache(client.cache(DEFAULT_CACHE_NAME), false);
checkCache(client.cache(TX_DEFAULT_CACHE_NAME), false);
}
/**
* Test starts two caches, each of them with interceptor, from a client node.
* Check all of these cache work correct and the interceptors present in a started configurations on server.
*
* @throws Exception If failed.
*/
@Test
public void testStartCacheFromClient() throws Exception {
useCustomLdr = false;
IgniteEx ignite0 = startGrid(0);
IgniteEx client = startClientGrid(1);
IgniteCache<Integer, Integer> cache = client.getOrCreateCache(generateCacheConfiguration(
DEFAULT_CACHE_NAME,
CacheAtomicityMode.ATOMIC
));
IgniteCache<Integer, Integer> txCache = client.getOrCreateCache(generateCacheConfiguration(
TX_DEFAULT_CACHE_NAME,
CacheAtomicityMode.TRANSACTIONAL
));
assertNotNull(ignite0.cache(DEFAULT_CACHE_NAME).getConfiguration(CacheConfiguration.class).getInterceptor());
assertNotNull(ignite0.cache(TX_DEFAULT_CACHE_NAME).getConfiguration(CacheConfiguration.class).getInterceptor());
checkCache(cache, true);
checkCache(txCache, true);
}
/**
* Generates a cache configuration with an interceptor.
*
* @param name Cache name.
* @param mode Atomic mode.
* @return Cache configuration.
* @throws Exception If failed.
*/
private CacheConfiguration<Integer, Integer> generateCacheConfiguration(String name, CacheAtomicityMode mode) throws Exception {
return new CacheConfiguration<Integer, Integer>(name)
.setAffinity(new RendezvousAffinityFunction(false, 64))
.setAtomicityMode(mode)
.setInterceptor(useCustomLdr ?
(CacheInterceptor<Integer, Integer>)testClassLoader.loadClass(INTERCEPTOR_CLASS).newInstance() :
new CacheInterceptorAdapter<Integer, Integer>());
}
/**
* Checks a work of caches by loading entries and checking values from cache.
*
* @param cache Ignite cache.
* @param isPlainInterceptor True when using a plain interceptor, false that using a specific interceptor from
* the user defined class loader.
* @throws Exception If failed.
*/
private void checkCache(IgniteCache<Integer, Integer> cache, boolean isPlainInterceptor) throws Exception {
CacheAtomicityMode atomicityMode = cache.getConfiguration(CacheConfiguration.class).getAtomicityMode();
if (atomicityMode == CacheAtomicityMode.TRANSACTIONAL) {
Ignite ignite = G.ignite(cacheFromCtx(cache).context().igniteInstanceName());
doInTransaction(ignite, () -> {
loadCache(cache);
return null;
});
}
else
loadCache(cache);
for (int i = 0; i < ENTRIES_TO_LOAD; i++) {
if (isPlainInterceptor)
assertNotNull(cache.get(i));
else
assertTrue(abs(i % 2) == abs(cache.get(i) % 2));
}
}
/**
* Loads {@see ENTRIES_TO_LOAD} rows to the cache specified.
*
* @param cache Ignite cache.
*/
private void loadCache(IgniteCache<Integer, Integer> cache) {
Random rand = new Random();
for (int i = 0; i < ENTRIES_TO_LOAD; i++)
cache.put(i, rand.nextInt());
}
}
| 2,707 |
799 | <filename>Packs/TrendMicroApex/Integrations/TrendMicroApex/test_data/add_file_command_mock.json
{
"result_code": 1,
"result_description": "Operation successful",
"result_content": "None"
} | 73 |
3,287 | <reponame>YuanyuanNi/azure-cli
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
from .constant import SPARK_DOTNET_ASSEMBLY_SEARCH_PATHS_KEY, SPARK_DOTNET_UDFS_FOLDER_NAME
def categorized_files(reference_files):
files = []
jars = []
for file in reference_files:
file = file.strip()
if file.endswith(".jar"):
jars.append(file)
else:
files.append(file)
return files, jars
def check_udfs_folder(conf):
paths = conf.get(SPARK_DOTNET_ASSEMBLY_SEARCH_PATHS_KEY, '').split(',')
paths = [path for path in paths if path != '']
udfs_folder_name = './{}'.format(SPARK_DOTNET_UDFS_FOLDER_NAME)
if udfs_folder_name not in paths:
paths.append(udfs_folder_name)
conf[SPARK_DOTNET_ASSEMBLY_SEARCH_PATHS_KEY] = ','.join(paths)
def get_tenant_id():
from azure.cli.core._profile import Profile
profile = Profile()
sub = profile.get_subscription()
tenant_id = sub['tenantId']
return tenant_id
| 465 |
526 | /* SPDX-License-Identifier: Apache-2.0 */
/* Copyright Contributors to the ODPi Egeria project. */
package org.odpi.openmetadata.conformance.workbenches;
/**
* The OpenMetadataConformanceWorkbench drives the execution of a batch of tests.
*/
public abstract class OpenMetadataConformanceWorkbench implements Runnable
{
protected String workbenchId; /* setup by the subclass */
protected String workbenchName; /* setup by the subclass */
protected String versionNumber; /* setup by the subclass */
protected String workbenchDocumentationURL; /* setup by the subclass */
protected static volatile boolean runningFlag = true;
/**
* Constructor taking in the URL root of the server under test.
*
* @param workbenchId unique identifier of this workbench
* @param workbenchName name of this workbench
* @param versionNumber version number of workbench
* @param workbenchDocumentationURL url to the documentation for this workbench
*/
public OpenMetadataConformanceWorkbench(String workbenchId,
String workbenchName,
String versionNumber,
String workbenchDocumentationURL)
{
this.workbenchId = workbenchId;
this.workbenchName = workbenchName;
this.versionNumber = versionNumber;
this.workbenchDocumentationURL = workbenchDocumentationURL;
}
/**
* Return the workbench id.
*
* @return id
*/
public String getWorkbenchId()
{
return workbenchId;
}
/**
* Return the workbench name.
*
* @return name
*/
public String getWorkbenchName()
{
return workbenchName;
}
/**
* Return the string version number of the workbench.
*
* @return version number
*/
public String getVersionNumber()
{
return versionNumber;
}
/**
* Return the link to the documentation for this workbench
*
* @return string url
*/
public String getWorkbenchDocumentationURL()
{
return workbenchDocumentationURL;
}
/**
* Shutdown the running thread
*/
public synchronized void stopRunning()
{
runningFlag = false;
}
/**
* Test to see if the thread should keep running.
*
* @return boolean flag
*/
protected synchronized boolean isRunning()
{
return runningFlag;
}
}
| 1,160 |
391 | /*
*
* Copyright (C) 2020 iQIYI (www.iqiyi.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.qiyi.lens.ui.traceview;
import android.Manifest;
import android.content.pm.PackageManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import com.qiyi.lens.ui.FloatingPanel;
import com.qiyi.lens.ui.FullScreenPanel;
import com.qiyi.lens.ui.traceview.compare.SelectLaunchTimePanel;
import com.qiyi.lens.ui.traceview.compare.TimeStampUtilDao;
import com.qiyi.lens.ui.widget.DataViewLoader;
import com.qiyi.lens.ui.widget.ViewPagerTitleBinder;
import com.qiyi.lens.utils.DataPool;
import com.qiyi.lens.utils.OSUtils;
import com.qiyi.lens.utils.TimeStampUtil;
import com.qiyi.lenssdk.R;
/**
* 启动时间面板
* a tab style view pager
*/
public class LaunchTimeDetailPanel extends FullScreenPanel implements View.OnClickListener {
private TimeStampUtil data;
public LaunchTimeDetailPanel(FloatingPanel panel) {
super(panel);
data = (TimeStampUtil) DataPool.obtain().getData(DataPool.DATA_TYPE_LAUNCH_TIME);
}
@Override
public View onCreateView(ViewGroup group) {
View root = inflateView(R.layout.lens_trace_view, group);
ViewPager pager = root.findViewById(R.id.len_launch_time_pager);
ViewGroup tank = root.findViewById(R.id.lens_time_bottom_bar);
root.findViewById(R.id.lens_save).setOnClickListener(this);
root.findViewById(R.id.lens_compare).setOnClickListener(this);
TimeStampInfo detailInfo = data.buidStampInfo();
pager.setAdapter(new DataAdapter(3, new DataViewLoader[]{
new TimeGapPage(getContext(), detailInfo),
new TimeStampPage(detailInfo),
new ThreadInfoPage(detailInfo)
}));
new ViewPagerTitleBinder(pager, tank);
return root;
}
@Override
public void show() {
if (data != null) {
super.show();
} else {
Toast.makeText(context, "启动数据为空,无法展示面板", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onClick(final View v) {
if (OSUtils.isPreQ() && ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(context, "为了跨版本对比启动数据,请授予外部存储权限后重试", Toast.LENGTH_SHORT).show();
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
return;
}
if (v.getId() == R.id.lens_save) {
new TimeStampUtilDao(context).save(data, new TimeStampUtilDao.Callback<Void>() {
@Override
public void onResult(Void data) {
Toast.makeText(context, "保存成功", Toast.LENGTH_SHORT).show();
((TextView) v).setText("已保存");
v.setEnabled(false);
}
});
} else if (v.getId() == R.id.lens_compare) {
new SelectLaunchTimePanel().show();
}
}
static class DataAdapter extends PagerAdapter {
int count;
DataViewLoader[] mLoaders;
DataAdapter(int c, DataViewLoader[] loaders) {
this.count = c;
mLoaders = loaders;
if (loaders == null || loaders.length != count) {
throw new IllegalArgumentException("loader count is not same with demanded where now is : " + (loaders == null ? "null " : loaders.length)
+ "while demanded is " + (loaders == null ? "null" : loaders.length));
}
}
@Override
public int getCount() {
return count;
}
@Override
public boolean isViewFromObject(@Nullable View view, @Nullable Object object) {
return view == object;
}
@Override
public @NonNull
Object instantiateItem(@NonNull ViewGroup container, int position) {
View view = mLoaders[position].loadView(container);
container.removeView(view);
container.addView(view);
return view;
}
@Override
public void destroyItem(ViewGroup container, int position, @NonNull Object object) {
View view = (View) object;
container.removeView(view);
}
}
}
| 2,250 |
391 | <gh_stars>100-1000
#!/usr/bin/env python3
# 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.
'''
Splits a syntax tree by type and models the data within each type.
'''
import collections
import doctest
import heapq
import io
import itertools
import math
import operator
import ast
import idl
# TODO: This is a SWAG. Maybe do this iteratively and refine the estimate.
BLOCK_SWITCH_COST_ESTIMATE = 4
class Block(object):
def __init__(self, universe_size, histo, start, end):
self.histo = histo
model = huffman(histo)
self.cost = sum(map(lambda p: p[1] * model[p[0]], histo.items()))
# Models are free, for now
# TODO: Model cost is complicated--there's no notion of reuse
#self.cost += huffman_model_cost(model, universe_size)
self.cost += math.log2(end - start) # Distance cost
self.cost += BLOCK_SWITCH_COST_ESTIMATE
self.pred = self.succ = None
self.cost_delta = 0
self.start = start
self.end = end
def __repr__(self):
return f'Block({self.start}-{self.end}, {self.histo})'
def __lt__(self, other):
return self.cost_delta < other.cost_delta
# TODO: Rescale combined histograms
def combine_histo(l, r):
lr = collections.defaultdict(int)
for k, v in itertools.chain(l.items(), r.items()):
lr[k] += v
return lr
class MergeBlock(Block):
def __init__(self, universe_size, left, right):
'''Creates a proposal to merge two blocks.
The caller must wire up the pred and succ properties of this block.'''
super().__init__(universe_size, combine_histo(left.histo, right.histo), left.start, right.end)
assert left.succ is right
assert right.pred is left
self.left = left
self.right = right
self.cost_delta = self.cost - (left.cost + right.cost)
self.committed = False # This is just a proposal
def __repr__(self):
return f'MergeBlock({self.left},{self.right},{self.cost_delta})'
def accept(self, universe_size, heap):
# This block is furniture now, we can't "apply" it again
self.cost_delta = 0
self.committed = True
# There's three things going on here:
# 1. Remove the things which merged with the old left and right block.
if self.pred:
old_pred = self.pred.pred
heap.remove(self.pred)
else:
old_pred = None
if self.succ:
old_succ = self.succ.succ
heap.remove(self.succ)
else:
old_succ = None
# 2. Wire up the committed block's predecessor, successor pointers, for producing the text again.
self.pred = self.left.pred
if self.pred:
self.pred.succ = self
self.succ = self.right.succ
if self.succ:
self.succ.pred = self
# Will be reheapified later.
heap.remove(self.left)
heap.remove(self.right)
heap.append(self) # We were popped before accept
# 3. Add things which merge with the new block
if self.pred:
a = MergeBlock(universe_size, self.pred, self)
a.pred = old_pred
if old_pred:
old_pred.succ = a
heap.append(a)
else:
a = None
if self.succ:
c = MergeBlock(universe_size, self, self.succ)
c.succ = old_succ
if old_succ:
old_succ.pred = c
heap.append(c)
else:
c = None
if a and c:
a.succ = c
c.pred = a
# TODO: This would be cheaper if replacement was in-place and bubble-up
heapq.heapify(heap)
def split_consistency_check(heap):
for val in heap:
#print(val)
#print('pred:', val.pred)
#print('succ:', val.succ)
assert val.pred is None or val.pred.succ is val
assert val.succ is None or val.succ.pred is val
if type(val) is MergeBlock:
#print('left:', val.left)
#print('right:', val.right)
assert (val.left in heap) != val.committed
assert (val.right in heap) != val.committed
def split(universe_size, values):
'''Breaks a sequence of values up into parts encoded with different models.
>>> u = Block(26, {'a': 1}, 0, 1)
>>> u.cost > 0
True
>>> v = Block(26, {'a': 1}, 1, 2)
>>> u.succ = v
>>> v.pred = u
>>> w = MergeBlock(26, u, v)
>>> w.start
0
>>> w.end
2
>>> w.cost_delta < 0
True
>>> vals = list('aaaaaa')
>>> c = split(26, vals)
>>> while c:
... print(c.histo)
... c = c.succ
defaultdict(<class 'int'>, {'a': 6})
>>> vals = list('a man aa plaaan a canal panama')
>>> c = split(26, vals)
>>> cost = 0
>>> while c:
... cost += c.cost
... print(c.start, c.end, dict(c.histo))
... c = c.succ
0 8 {'a': 4, ' ': 2, 'm': 1, 'n': 1}
8 11 {' ': 1, 'p': 1, 'l': 1}
11 18 {'a': 4, 'n': 1, ' ': 2}
18 19 {'c': 1}
19 23 {'a': 2, 'n': 1, 'l': 1}
23 25 {' ': 1, 'p': 1}
25 30 {'a': 3, 'n': 1, 'm': 1}
>>> print(int(cost))
84
>>> hist = collections.defaultdict(int)
>>> for v in vals: hist[v] += 1
>>> huff = huffman(hist)
>>> print(int(huffman_encode_cost(huff, 26, vals)))
115
'''
# Make a sequence of leaf blocks and proposals for merging them
blocks = [Block(universe_size, {sym: 1}, i, i+1) for i, sym in enumerate(values)]
proposed_merges = []
for u, v in zip(blocks, blocks[1:]):
u.succ = v; v.pred = u
proposed_merges.append(MergeBlock(universe_size, u, v))
for m, n in zip(proposed_merges, proposed_merges[1:]):
m.succ = n
n.pred = m
# TODO: It's lazy to have these blocks here, keep track of them separately
proposed_merges += blocks
split_consistency_check(proposed_merges)
heapq.heapify(proposed_merges)
while True:
#print('-' * 80)
#for i in proposed_merges:
# print(i)
candidate = heapq.heappop(proposed_merges)
#print(f'candidate={candidate}')
if candidate.cost_delta < 0:
candidate.accept(universe_size, proposed_merges)
split_consistency_check(proposed_merges)
else:
break
if type(candidate) is MergeBlock and not candidate.committed:
candidate = candidate.left
while candidate.pred:
candidate = candidate.pred
return candidate
def huffman_encode_cost(table, universe_size, values):
'''Given a table of code lengths, the cost of encoding it and values with it.
>>> table = huffman({'a': 2, 'b': 1, 'c': 0})
>>> huffman_encode_cost(table, 3, ['a', 'b'])
5.0
'''
return huffman_model_cost(table, universe_size) + sum(map(lambda v: table[v], values))
def huffman_model_cost(table, universe_size):
'''Estimates the cost of encoding a Huffman table.
>>> huffman_model_cost({'a': 1}, 1024)
10.0
>>> huffman_model_cost({'a': 1, 'b': 1}, 1024)
20.0
>>> huffman_model_cost({'a': 1, 'b': 2, 'c': 2}, 1024)
32.0
'''
if len(table) == 1:
# Just encode the symbol
return math.log2(universe_size)
if len(table) <= universe_size // 2:
# Say we'd encode each of the members and their code length
return math.log2(universe_size) * len(table) + sum(map(math.log2, table.values()))
# We'd just encode the lengths and expect 0s to compress well.
return sum(map(math.log2, table.values()))
def huffman(histogram):
'''Builds a Huffman tree and returns a dictionary of key to code length.
>>> huffman({'a': 47})
{'a': 0}
>>> huffman({'a': 20, 'b': 3, 'c': 1})
{'c': 2, 'b': 2, 'a': 1}
'''
# Make a heap of (count, n, key); wrap keys in one-element tuples
# to distinguish them as leaves.
#
# n is a unique number which means we don't compare keys during heap
# operations. Without n, this comparison would happen if two symbols
# had the same count.
h = list(map(lambda p: (p[1][1], p[0], (p[1][0],)), enumerate(histogram.items())))
heapq.heapify(h)
# Merge items to build the tree
while len(h) > 1:
fst = heapq.heappop(h)
snd = heapq.heappop(h)
heapq.heappush(h, (fst[0] + snd[0], fst[1], (fst[2], snd[2])))
table = {}
def visit(cost, node):
if len(node) == 1:
table[node[0]] = cost
else:
visit(cost + 1, node[0])
visit(cost + 1, node[1])
visit(0, h[0][2])
return table
def universe_size_for_key(k, vs):
ty, field_name = k
if ty is idl.TY_TYPE:
# TY_TYPE is used to mark the root; we expect the decoder to know that type
return 1
if field_name == 'list-length':
# This, and string/double/etc. are imperfect; they assume a dictionary we're indexing into.
return len(set(vs))
attr_ty = ty.type_of(field_name)
return universe_size_for_type(attr_ty, vs)
def universe_size_for_type(ty, vs):
if type(ty) in [idl.TyInterface, idl.TyNone, idl.TyFrozenArray]:
return 1
if type(ty) is idl.TyEnum:
return len(ty.values)
if type(ty) is idl.TyRef:
assert False, 'unreachable'
if type(ty) is idl.Alt:
return sum(map(lambda t: universe_size_for_type(t, []), ty.tys))
if ty is idl.TY_BOOLEAN:
return 2
if ty in [idl.TY_DOUBLE, idl.TY_LONG, idl.TY_STRING, idl.TY_UNSIGNED_LONG]:
return len(set(vs))
# To dump stats for a file:
#
# types = idl.parse_es6_idl()
# tree = ast.load_ast(...)
# shard = model.TreeSharder(types); shard.visit(types.interfaces['Script'], tree); model.total_stats(shard.group)
def total_stats(groups):
by_size = []
for k, v in groups.items():
by_size.append(group_stats(v, universe_size_for_key(k, v)) + k)
by_size = list(sorted(by_size, key=lambda p: p[1]))
total_size_bits = sum(map(operator.itemgetter(0), by_size))
total_size_huff_bits = sum(map(operator.itemgetter(1), by_size))
for _, _, message, ty, name in by_size:
print(str(ty), name)
print(message)
print()
print('-' * 10)
print(len(groups), 'groups')
print(total_size_bits / 8, 'bytes')
print('huffman:', total_size_huff_bits / 8, 'bytes')
print('note: does not include string data')
def entropy(values):
'''Computes entropy, in bits, of a set of frequency values.
>>> entropy([100])
0.0
>>> entropy([1, 1])
1.0
'''
total = sum(values)
entropy = 0.0
for value in values:
p = value / total
entropy -= p * math.log2(p)
return entropy
def group_stats(group, universe_size):
hist = collections.defaultdict(int)
for item in group:
hist[item] += 1
msg = []
msg.append(f'{len(hist.keys())} symbols')
size = len(group)
msg.append(f'{size} instances')
entropy_bits = entropy(list(hist.values()))
msg.append(f'{entropy_bits} bits per symbol')
msg.append(f'~= {entropy_bits * size / 8} bytes')
huff_table = huffman(hist)
huff_cost = huffman_encode_cost(huff_table, universe_size, group)
msg.append(f'Huffman {huff_cost / len(group)} bits per symbol')
msg.append(f'Huffman encoding ~= {huff_cost / 8} bytes')
return size * entropy_bits, huff_cost, '\n'.join(msg)
# This collapses some fields with similar function to save model space.
def map_model_key(types, k):
if k[0] == types.interfaces['StaticMemberAssignmentTarget'] and k[1] == 'property':
return (types.interfaces['StaticMemberExpression'], 'property')
return k
class TreeSharder(ast.AstVisitor):
'''
Traverses a tree, grouping items by declared type.
>>> types = idl.parse_es6_idl()
>>> tree = ast.load_test_ast('y5R7cnYctJv.js.dump')
>>> sharder = TreeSharder(types)
>>> sharder.visit(types.interfaces['Script'], tree)
>>> k = (types.interfaces['AssertedDeclaredName'], 'isCaptured')
>>> len(sharder.group[k])
31
>>> sharder.group[k][0:10]
[True, False, False, False, False, False, False, False, False, False]
'''
def __init__(self, types):
super().__init__(types)
self.group = collections.defaultdict(list)
# Not really a type, but we need to record the kick-off record
self.field = [(idl.TY_TYPE, 'init')]
# self.array_field = []
def visit_list(self, ty, xs):
self.group[(ty, 'list-length')].append(len(xs))
# self.array_field.append(self.field[-1])
super().visit_list(ty, xs)
# self.array_field.pop()
# def visit_list_item(self, ty, i, x):
# self.field.append((self.array_field[-1], i % 8))
# super().visit_list_item(ty, i, x)
# self.field.pop()
def visit_struct(self, declared_ty, actual_ty, obj):
# Record types here, and not in the type field, because
# the type narrowing happens when decoding the struct.
# Note, this probably records some fields with fixed types
# which need no encoding.
self.group[self.field[-1]].append(actual_ty)
super().visit_struct(declared_ty, actual_ty, obj)
def visit_field(self, struct_ty, obj, i, attr):
self.field.append(map_model_key(self.types, (struct_ty, attr.name)))
super().visit_field(struct_ty, obj, i, attr)
self.field.pop()
def visit_primitive(self, ty, value):
if ty is idl.TY_TYPE:
return
if value is None:
value = idl.TyNone()
self.group[self.field[-1]].append(value)
def model_tree(types, ty, tree):
'''Builds per-field probability models for a tree of a given type.'''
sharder = TreeSharder(types)
sharder.visit(ty, tree)
# We skip TY_TYPE because it marks the first item.
tables = {k: make_model(k[0], k[1], v) for k, v in sharder.group.items() if k[0] != idl.TY_TYPE}
for k, v in tables.items():
assert v is not None, (k, make_model(k[0], k[1], sharder.group[k]))
return tables
def make_huffman_codebook(values):
'''Makes a canonical Huffman code modeling values.
Symbols must be comparable to sort them for the canonical code.
Returns:
A code, code length -> symbol map, and symbol -> code, code_length map.
>>> c, s = make_huffman_codebook(list('appl'))
>>> c[(0, 1)]
'p'
>>> c[(0b10, 2)]
'a'
>>> c[(0b11, 2)]
'l'
>>> s['p']
(0, 1)
'''
hist = collections.defaultdict(int)
for value in values:
hist[value] += 1
lengths = huffman(hist)
# Now assign canonical codes
return huffman_assign_order(list(sorted(map(lambda s: (lengths[s], type(s) is idl.TyNone and 1 or 2, s), hist.keys()))))
def huffman_assign_order(length_order_code):
if len(length_order_code) == 1:
assert length_order_code[0][0] == 0
code = (0, 0)
sym = length_order_code[0][2]
return {code: sym}, {sym: code}
assign_order = list(filter(lambda p: p[0] > 0, length_order_code)) + [(20, None, None)]
code = 0
codes = {}
symbols = {}
for (code_length, _, symbol), (next_code_length, _, _) in zip(assign_order, assign_order[1:]):
k = (code, code_length)
codes[k] = symbol
symbols[symbol] = k
assert next_code_length >= code_length, f'{k}, {next_code_length}, {code_length}'
code = (code + 1) << ((next_code_length - code_length))
return codes, symbols
# The model also has to produce the symbol values
class ExplicitSymbolModel(object):
def from_values(self, values):
self.code_to_symbol, self.symbol_to_code = make_huffman_codebook(values)
return self
def in_use_syms(self):
yield from self.symbol_to_code.keys()
# The encoder can use symbol indices to produce values
class IndexedSymbolModel(object):
def __init__(self, symbols):
self.symbols = symbols
self.index = {s: i for i, s in enumerate(self.symbols)}
assert len(self.index) == len(self.symbols), 'must be bijection'
def from_values(self, values):
self.code_to_symbol, self.symbol_to_code = make_huffman_codebook(values)
return self
def in_use_syms(self):
yield from self.symbol_to_code.keys()
# A model which must exist because a given array type instantiates it,
# although there are no values at runtime. This arises because array
# lengths are shared by array type and are not specific to a field.
class UnreachableModel(object):
@property
def symbol_to_code(self):
assert False, 'unreachable'
@property
def code_to_symbol(self):
assert False, 'unreachable'
def in_use_syms(self):
return []
# There is statically only one value. These models should not be written to the file.
class TrivialModel(object):
def __init__(self, ty):
self.ty = ty
self.symbol_to_code = {ty: (0, 0)}
self.code_to_symbol = {(0, 0): ty}
def in_use_syms(self):
yield self.ty
# Makes a model for a field, including a synthetic field list-length
def make_model(ty, field_name, group):
assert ty != idl.TY_TYPE
assert None not in group, (str(ty), field_name)
if field_name == 'list-length':
return ExplicitSymbolModel().from_values(group)
ty = ty.type_of(field_name)
return make_model_for_type(ty, group)
# This must be in sync with is_indexed_type
def is_indexed_type(ty):
if type(ty) is idl.Alt:
return all(map(lambda t: is_indexed_type(t) or type(t) is idl.TyInterface, ty.tys))
else:
return type(ty) in [idl.TyNone, idl.TyEnum] or ty == idl.TY_BOOLEAN or (type(ty) is idl.TyFrozenArray and is_indexed_type(ty.element_ty))
def symbols_for_indexed_type(ty):
if type(ty) is idl.TyFrozenArray:
return symbols_for_indexed_type(ty.element_ty)
if type(ty) is idl.Alt:
assert is_indexed_type(ty)
return ty.tys
if type(ty) is idl.TyEnum:
return ty.values
if ty is idl.TY_BOOLEAN:
return [False, True]
# Makes a model where the values are a specific type.
def make_model_for_type(ty, group):
if type(ty) is idl.TyInterface:
assert all(map(lambda x: x == ty, group)), (ty, group)
return TrivialModel(ty)
if type(ty) is idl.TyFrozenArray:
return make_model_for_type(ty.element_ty, group)
if type(ty) is idl.Alt:
if is_indexed_type(ty):
return IndexedSymbolModel(ty.tys).from_values(group)
else:
return ExplicitSymbolModel().from_values(group)
if type(ty) is idl.TyEnum:
return IndexedSymbolModel(ty.values).from_values(group)
if ty is idl.TY_BOOLEAN:
return IndexedSymbolModel([False, True]).from_values(group)
if type(ty) is idl.TyPrimitive:
return ExplicitSymbolModel().from_values(group)
assert False, ('unreachable', ty, group)
if __name__ == '__main__':
doctest.testmod()
| 7,033 |
1,481 | <filename>full/src/test/java/apoc/data/email/ExtractEmailTest.java
package apoc.data.email;
import apoc.util.TestUtil;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.neo4j.test.rule.DbmsRule;
import org.neo4j.test.rule.ImpermanentDbmsRule;
import static apoc.util.TestUtil.testCall;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertEquals;
public class ExtractEmailTest {
@ClassRule
public static DbmsRule db = new ImpermanentDbmsRule();
@BeforeClass
public static void setUp() throws Exception {
TestUtil.registerProcedure(db, ExtractEmail.class);
}
@Test
public void testPersonalPresent() {
testCall(db, "RETURN apoc.data.email('David <<EMAIL>>').personal AS value",
row -> assertEquals("David", row.get("value")));
}
@Test
public void testPersonalMissing() {
testCall(db, "RETURN apoc.data.email('<<EMAIL>>').personal AS value",
row -> assertEquals(null, row.get("value")));
}
@Test
public void testUser() {
testCall(db, "RETURN apoc.data.email('Unusual <<EMAIL>>').user AS value",
row -> assertEquals("example-throwaway", row.get("value")));
}
@Test
public void testMissingUser() {
testCall(db, "RETURN apoc.data.email('mail.com').user AS value",
row -> assertEquals(null, row.get("value")));
}
@Test
public void testQuotedEmail() {
testCall(db, "RETURN apoc.data.email('<<EMAIL>>').domain AS value",
row -> Assert.assertThat(row.get("value"), equalTo("bar.baz")));
}
@Test
public void testEmail() {
testCall(db, "RETURN apoc.data.email('<EMAIL>').domain AS value",
row -> Assert.assertThat(row.get("value"), equalTo("bar.baz")));
}
@Test
public void testLocalEmail() {
// Internet standards strongly discourage this possibility, but it's out there.
testCall(db, "RETURN apoc.data.email('root@localhost').domain AS value",
row -> Assert.assertThat(row.get("value"), equalTo("localhost")));
}
@Test
public void testNull() {
testCall(db, "RETURN apoc.data.email(null).domain AS value",
row -> assertEquals(null, row.get("value")));
}
@Test
public void testBadString() {
testCall(db, "RETURN apoc.data.email('asdsgawe4ge').domain AS value",
row -> assertEquals(null, row.get("value")));
}
@Test
public void testEmailWithDotsBeforeAt() {
testCall(db, "RETURN apoc.data.email('<EMAIL>').domain AS value",
row -> Assert.assertThat(row.get("value"), equalTo("bar.baz")));
}
}
| 1,137 |
1,350 | <reponame>Shashi-rk/azure-sdk-for-java<gh_stars>1000+
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.microsoft.azure.spring.cloud.config;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.endpoint.RefreshEndpoint;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import com.microsoft.azure.spring.cloud.config.stores.ClientStore;
@Configuration
@ConditionalOnProperty(prefix = AppConfigurationProperties.CONFIG_PREFIX, name = "enabled", matchIfMissing = true)
@EnableAsync
public class AppConfigurationAutoConfiguration {
@Configuration
@ConditionalOnClass(RefreshEndpoint.class)
static class AppConfigurationWatchAutoConfiguration {
@Bean
public AppConfigurationRefresh getConfigWatch(AppConfigurationProperties properties,
AppConfigurationPropertySourceLocator sourceLocator, ClientStore clientStore) {
return new AppConfigurationRefresh(properties, sourceLocator.getStoreContextsMap(), clientStore);
}
}
}
| 388 |
612 | <reponame>jaxnb/icestorm
#!/usr/bin/env python3
from fuzzconfig import *
import numpy as np
import os
device_class = os.getenv("ICEDEVICE")
working_dir = "work_%s_ram40" % (device_class, )
os.system("rm -rf " + working_dir)
os.mkdir(working_dir)
for idx in range(num):
with open(working_dir + "/ram40_%02d.v" % idx, "w") as f:
glbs = ["glb[%d]" % i for i in range(np.random.randint(8)+1)]
# Connecting GLB to CE pins seemingly disallowed
if device_class == "5k":
glbs_choice = ["wa", "ra", "msk", "wd", "we", "wc", "re", "rc"]
else:
glbs_choice = ["wa", "ra", "msk", "wd", "we", "wce", "wc", "re", "rce", "rc"]
print("""
module top (
input [%d:0] glb_pins,
input [%d:0] in_pins,
output [15:0] out_pins
);
wire [%d:0] glb, glb_pins;
SB_GB gbufs [%d:0] (
.USER_SIGNAL_TO_GLOBAL_BUFFER(glb_pins),
.GLOBAL_BUFFER_OUTPUT(glb)
);
""" % (len(glbs)-1, len(pins) - len(glbs) - 16 - 1, len(glbs)-1, len(glbs)-1), file=f)
bits = ["in_pins[%d]" % i for i in range(60)]
bits = list(np.random.permutation(bits))
for i in range(num_ramb40):
tmp = list(np.random.permutation(bits))
rmode = np.random.randint(4)
if rmode == 3:
wmode = np.random.randint(1, 4)
else:
wmode = np.random.randint(4)
raddr_bits = (8, 9, 10, 11)[rmode]
waddr_bits = (8, 9, 10, 11)[wmode]
rdata_bits = (16, 8, 4, 2)[rmode]
wdata_bits = (16, 8, 4, 2)[wmode]
bits_waddr = [tmp.pop() for k in range(waddr_bits)]
bits_raddr = [tmp.pop() for k in range(raddr_bits)]
bits_mask = [tmp.pop() for k in range(16)]
bits_wdata = [tmp.pop() for k in range(wdata_bits)]
bit_we = tmp.pop()
bit_wclke = tmp.pop()
bit_wclk = tmp.pop()
bit_re = tmp.pop()
bit_rclke = tmp.pop()
bit_rclk = tmp.pop()
if len(glbs) != 0:
s = np.random.choice(glbs_choice)
glbs_choice.remove(s)
if s == "wa": bits_waddr[np.random.randint(len(bits_waddr))] = glbs.pop()
if s == "ra": bits_raddr[np.random.randint(len(bits_raddr))] = glbs.pop()
if s == "msk": bits_mask [np.random.randint(len(bits_mask ))] = glbs.pop()
if s == "wd": bits_wdata[np.random.randint(len(bits_wdata))] = glbs.pop()
if s == "we": bit_we = glbs.pop()
if s == "wce": bit_wclke = glbs.pop()
if s == "wc": bit_wclk = glbs.pop()
if s == "re": bit_re = glbs.pop()
if s == "rce": bit_rclke = glbs.pop()
if s == "rc": bit_rclk = glbs.pop()
bits_waddr = "{%s}" % ", ".join(bits_waddr)
bits_raddr = "{%s}" % ", ".join(bits_raddr)
bits_mask = "{%s}" % ", ".join(bits_mask)
bits_wdata = "{%s}" % ", ".join(bits_wdata)
if wmode != 0: bits_mask = ""
memtype = np.random.choice(["", "NR", "NW", "NRNW"])
wclksuffix = "N" if memtype in ["NW", "NRNW"] else ""
rclksuffix = "N" if memtype in ["NR", "NRNW"] else ""
print("""
wire [%d:0] rdata_%d;
SB_RAM40_4K%s #(
.READ_MODE(%d),
.WRITE_MODE(%d)
) ram_%d (
.WADDR(%s),
.RADDR(%s),
.MASK(%s),
.WDATA(%s),
.RDATA(rdata_%d),
.WE(%s),
.WCLKE(%s),
.WCLK%s(%s),
.RE(%s),
.RCLKE(%s),
.RCLK%s(%s)
);
""" % (
rdata_bits-1, i, memtype, rmode, wmode, i,
bits_waddr, bits_raddr, bits_mask, bits_wdata, i,
bit_we, bit_wclke, wclksuffix, bit_wclk,
bit_re, bit_rclke, rclksuffix, bit_rclk
), file=f)
bits = list(np.random.permutation(bits))
for k in range(rdata_bits):
bits[k] = "rdata_%d[%d] ^ %s" % (i, k, bits[k])
print("assign out_pins = rdata_%d;" % i, file=f)
print("endmodule", file=f)
with open(working_dir + "/ram40_%02d.pcf" % idx, "w") as f:
p = list(np.random.permutation(pins))
for i in range(len(pins) - len(glbs) - 16):
print("set_io in_pins[%d] %s" % (i, p.pop()), file=f)
for i in range(16):
print("set_io out_pins[%d] %s" % (i, p.pop()), file=f)
output_makefile(working_dir, "ram40")
| 2,920 |
5,169 | <reponame>Gantios/Specs
{
"name": "Dengage.Framework.Extensions",
"version": "1.0.5",
"summary": "Dengage.Framework.Extensions contains custom categories (Carousel Notification)",
"description": "Dengage.Framework.Extensions provides necessary classes and functions which handles notification for Rich Notifications",
"homepage": "https://github.com/whitehorse-technology/Dengage.Framework.Extensions",
"license": {
"type": "GNU GPLv3",
"file": "LICENSE"
},
"authors": {
"<EMAIL>": "<EMAIL>"
},
"source": {
"git": "https://github.com/whitehorse-technology/Dengage.Framework.Extensions.git",
"tag": "1.0.5"
},
"platforms": {
"ios": "11.0"
},
"source_files": "Dengage.Framework.Extensions/Classes/**/*",
"swift_versions": [
"4.0",
"4.2",
"5.0"
],
"resource_bundles": {
"Dengage.Framework.Extensions": [
"Dengage.Framework.Extensions/Views/*",
"Dengage.Framework.Extensions/*.storyboard"
]
},
"dependencies": {
"Dengage.Framework": [
]
},
"swift_version": "5.0"
}
| 435 |
28,056 | package com.alibaba.json.bvt.path;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPath;
import com.alibaba.fastjson.parser.Feature;
import junit.framework.TestCase;
import java.util.HashMap;
import java.util.Map;
public class TestSpecial_3 extends TestCase {
public void test_special() throws Exception {
String json = "[{\"@type\":\"NAME_CORRECTION\",\"value\":23}]";
JSONArray array = (JSONArray) JSON.parse(json, Feature.DisableSpecialKeyDetect);
Object obj = JSONPath.eval(array, "[\\@type='NAME_CORRECTION']");
assertNotNull(obj);
}
public void test_special_1() throws Exception {
String json = "[{\":lang\":\"NAME_CORRECTION\",\"value\":23}]";
JSONArray array = (JSONArray) JSON.parse(json, Feature.DisableSpecialKeyDetect);
Object obj = JSONPath.eval(array, "[\\:lang='NAME_CORRECTION']");
assertNotNull(obj);
}
public void test_special_2() throws Exception {
String json = "{\"cpe-item\":{\"@name\":\"cpe:/a:google:chrome:172.16.58.3\",\"cpe-23:cpe23-item\":{\"@name\":\"cpe:2.3:a:google:chrome:172.16.58.3:*:*:*:*:*:*:*\"},\"title\":[{\"#text\":\"グーグル クローム 172.16.58.3\",\"@xml:lang\":\"ja-JP\"},{\"#text\":\"Google Chrome 172.16.58.3\",\"@xml:lang\":\"en-US\"}]}}";
String path = "['cpe-item']['title'][\\@xml\\:lang='en-US']['#text'][0]";
JSONObject object = (JSONObject) JSON.parse(json, Feature.DisableSpecialKeyDetect);
Object obj = JSONPath.eval(object, path);
assertNotNull(obj);
}
}
| 652 |
2,728 | <gh_stars>1000+
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from ._data_collection_endpoints_operations import DataCollectionEndpointsOperations
from ._data_collection_rule_associations_operations import DataCollectionRuleAssociationsOperations
from ._data_collection_rules_operations import DataCollectionRulesOperations
__all__ = [
'DataCollectionEndpointsOperations',
'DataCollectionRuleAssociationsOperations',
'DataCollectionRulesOperations',
]
| 195 |
338 | package com.tvd12.ezyfoxserver.testing.setting;
import static org.testng.Assert.assertEquals;
import org.testng.annotations.Test;
import com.tvd12.ezyfoxserver.constant.EzyEventType;
import com.tvd12.ezyfoxserver.context.EzyZoneContext;
import com.tvd12.ezyfoxserver.controller.EzyAbstractZoneEventController;
import com.tvd12.ezyfoxserver.event.EzyServerReadyEvent;
import com.tvd12.ezyfoxserver.ext.EzyAppEntry;
import com.tvd12.ezyfoxserver.ext.EzyAppEntryLoader;
import com.tvd12.ezyfoxserver.ext.EzyPluginEntry;
import com.tvd12.ezyfoxserver.ext.EzyPluginEntryLoader;
import com.tvd12.ezyfoxserver.setting.EzyAppSettingBuilder;
import com.tvd12.ezyfoxserver.setting.EzyPluginSettingBuilder;
import com.tvd12.ezyfoxserver.setting.EzySimpleAppSetting;
import com.tvd12.ezyfoxserver.setting.EzySimpleAppsSetting;
import com.tvd12.ezyfoxserver.setting.EzySimpleEventControllersSetting;
import com.tvd12.ezyfoxserver.setting.EzySimplePluginSetting;
import com.tvd12.ezyfoxserver.setting.EzySimplePluginSetting.EzySimpleListenEvents;
import com.tvd12.ezyfoxserver.setting.EzySimplePluginsSetting;
import com.tvd12.ezyfoxserver.setting.EzySimpleStreamingSetting;
import com.tvd12.ezyfoxserver.setting.EzySimpleUserManagementSetting;
import com.tvd12.ezyfoxserver.setting.EzySimpleZoneSetting;
import com.tvd12.ezyfoxserver.setting.EzyUserManagementSettingBuilder;
import com.tvd12.ezyfoxserver.setting.EzyZoneSettingBuilder;
public class EzyZoneSettingBuilderTest {
@Test
public void test() {
EzySimpleAppSetting appSetting = new EzyAppSettingBuilder()
.configFile("config.properties")
.entryLoader(TestAppEntryLoader.class)
.entryLoaderArgs(new String[] {"hello"})
.maxUsers(100)
.name("test")
.threadPoolSize(3)
.build();
EzySimpleAppsSetting appsSetting = new EzySimpleAppsSetting();
EzySimpleListenEvents listenEvents = new EzySimpleListenEvents();
EzySimplePluginSetting pluginSetting = new EzyPluginSettingBuilder()
.configFile("config.properties")
.entryLoader(TestPluginEntryLoader.class)
.name("test")
.threadPoolSize(3)
.priority(1)
.listenEvents(listenEvents)
.addListenEvent(EzyEventType.USER_LOGIN)
.addListenEvent(EzyEventType.USER_LOGIN.toString())
.build();
EzySimplePluginsSetting pluginsSetting = new EzySimplePluginsSetting();
EzySimpleStreamingSetting streamingSetting = new EzySimpleStreamingSetting();
EzySimpleEventControllersSetting eventControllersSetting = new EzySimpleEventControllersSetting();
EzySimpleUserManagementSetting userManagementSetting = new EzyUserManagementSettingBuilder()
.allowChangeSession(true)
.allowGuestLogin(true)
.guestNamePrefix("Guest#")
.maxSessionPerUser(3)
.userMaxIdleTimeInSecond(100)
.userNamePattern("user#name")
.build();
EzySimpleZoneSetting setting = new EzyZoneSettingBuilder()
.configFile("config.properties")
.maxUsers(1000)
.name("test")
.applications(appsSetting)
.application(appSetting)
.plugins(pluginsSetting)
.plugin(pluginSetting)
.streaming(streamingSetting)
.eventControllers(eventControllersSetting)
.userManagement(userManagementSetting)
.addEventController(EzyEventType.SERVER_READY, HelloZoneServerReadyController.class)
.build();
assertEquals(setting.getConfigFile(), "config.properties");
assertEquals(setting.getMaxUsers(), 1000);
assertEquals(setting.getName(), "test");
assertEquals(setting.getApplications(), appsSetting);
assertEquals(setting.getPlugins(), pluginsSetting);
assertEquals(setting.getStreaming(), streamingSetting);
assertEquals(setting.getEventControllers(), eventControllersSetting);
assertEquals(setting.getUserManagement(), userManagementSetting);
appSetting = appsSetting.getAppByName("test");
assertEquals(appSetting.getConfigFile(true), "config.properties");
assertEquals(appSetting.getEntryLoader(), TestAppEntryLoader.class.getName());
assertEquals(appSetting.getFolder(), "test");
assertEquals(appSetting.getMaxUsers(), 100);
assertEquals(appSetting.getName(), "test");
assertEquals(appSetting.getThreadPoolSize(), 3);
assertEquals(appSetting.getConfigFileInput(), "config.properties");
pluginSetting = pluginsSetting.getPluginByName("test");
assertEquals(pluginSetting.getConfigFile(true), "config.properties");
assertEquals(pluginSetting.getEntryLoader(), TestPluginEntryLoader.class.getName());
assertEquals(pluginSetting.getFolder(), "test");
assertEquals(pluginSetting.getName(), "test");
assertEquals(pluginSetting.getThreadPoolSize(), 3);
assertEquals(pluginSetting.getPriority(), 1);
assertEquals(pluginSetting.getListenEvents().getEvents().size(), 1);
userManagementSetting = setting.getUserManagement();
assertEquals(userManagementSetting.isAllowChangeSession(), true);
assertEquals(userManagementSetting.isAllowGuestLogin(), true);
assertEquals(userManagementSetting.getGuestNamePrefix(), "Guest#");
assertEquals(userManagementSetting.getMaxSessionPerUser(), 3);
assertEquals(userManagementSetting.getUserMaxIdleTimeInSecond(), 100);
assertEquals(userManagementSetting.getUserNamePattern(), "user#name");
}
public static class TestAppEntryLoader implements EzyAppEntryLoader {
public TestAppEntryLoader(String config) {
}
@Override
public EzyAppEntry load() throws Exception {
return null;
}
}
public static class TestPluginEntryLoader implements EzyPluginEntryLoader {
@Override
public EzyPluginEntry load() throws Exception {
return null;
}
}
public static class HelloZoneServerReadyController
extends EzyAbstractZoneEventController<EzyServerReadyEvent> {
@Override
public void handle(EzyZoneContext ctx, EzyServerReadyEvent event) {
// add logic here
}
}
}
| 2,681 |
903 | package org.develnext.jphp.core.tokenizer.token.expr.operator.cast;
import php.runtime.env.Environment;
import php.runtime.env.TraceInfo;
import php.runtime.memory.StringMemory;
import php.runtime.Memory;
import org.develnext.jphp.core.tokenizer.TokenMeta;
import org.develnext.jphp.core.tokenizer.TokenType;
public class StringCastExprToken extends CastExprToken {
public StringCastExprToken(TokenMeta meta) {
super(meta, TokenType.T_STRING_CAST);
}
@Override
public Class<?> getResultClass() {
return String.class;
}
@Override
public Memory calc(Environment env, TraceInfo trace, Memory o1, Memory o2) {
return new StringMemory(o1.toString());
}
@Override
public String getCode() {
return "toString";
}
@Override
public boolean isImmutableResult() {
return true;
}
}
| 323 |
946 | <reponame>hexrain/utymap<filename>core/src/mapcss/Color.hpp
#ifndef MAPCSS_COLOR_HPP_INCLUDED
#define MAPCSS_COLOR_HPP_INCLUDED
#include <algorithm>
#include <cstdint>
namespace utymap {
namespace mapcss {
/// Represents RGBA color.
struct Color final {
unsigned char r, g, b, a;
Color() : r(0), g(0), b(0), a(0) {
}
Color(int r, int g, int b, int a) :
r(static_cast<unsigned char>(std::max(0, std::min(r, 0xff)))),
g(static_cast<unsigned char>(std::max(0, std::min(g, 0xff)))),
b(static_cast<unsigned char>(std::max(0, std::min(b, 0xff)))),
a(static_cast<unsigned char>(std::max(0, std::min(a, 0xff)))) {
};
Color(int rgba) {
r = static_cast<unsigned char>((rgba >> 24) & 0xff);
g = static_cast<unsigned char>((rgba >> 16) & 0xff);
b = static_cast<unsigned char>((rgba >> 8) & 0xff);
a = static_cast<unsigned char>((rgba >> 0) & 0xff);
}
operator std::uint32_t() const {
return (r << 24) | (g << 16) | (b << 8) | a;
}
Color operator+(const Color &o) const {
return Color(r + o.r, g + o.g, b + o.b, a + o.a);
}
Color operator*(double f) const {
return Color(static_cast<int>(r*f),
static_cast<int>(g*f),
static_cast<int>(b*f),
static_cast<int>(a*f));
}
};
}
}
#endif // MAPCSS_COLOR_HPP_INCLUDED
| 606 |
17,703 | <gh_stars>1000+
#pragma once
#include <string>
#include <vector>
#include "envoy/access_log/access_log.h"
#include "envoy/config/core/v3/base.pb.h"
#include "envoy/http/header_map.h"
#include "source/common/protobuf/protobuf.h"
#include "source/common/router/header_formatter.h"
namespace Envoy {
namespace Router {
class HeaderParser;
using HeaderParserPtr = std::unique_ptr<HeaderParser>;
/**
* HeaderParser manipulates Http::HeaderMap instances. Headers to be added are pre-parsed to select
* between a constant value implementation and a dynamic value implementation based on
* StreamInfo::StreamInfo fields.
*/
class HeaderParser {
public:
/*
* @param headers_to_add defines the headers to add during calls to evaluateHeaders
* @return HeaderParserPtr a configured HeaderParserPtr
*/
static HeaderParserPtr configure(
const Protobuf::RepeatedPtrField<envoy::config::core::v3::HeaderValueOption>& headers_to_add);
/*
* @param headers_to_add defines headers to add during calls to evaluateHeaders.
* @param append defines whether headers will be appended or replaced.
* @return HeaderParserPtr a configured HeaderParserPtr.
*/
static HeaderParserPtr
configure(const Protobuf::RepeatedPtrField<envoy::config::core::v3::HeaderValue>& headers_to_add,
bool append);
/*
* @param headers_to_add defines headers to add during calls to evaluateHeaders
* @param headers_to_remove defines headers to remove during calls to evaluateHeaders
* @return HeaderParserPtr a configured HeaderParserPtr
*/
static HeaderParserPtr configure(
const Protobuf::RepeatedPtrField<envoy::config::core::v3::HeaderValueOption>& headers_to_add,
const Protobuf::RepeatedPtrField<std::string>& headers_to_remove);
void evaluateHeaders(Http::HeaderMap& headers, const StreamInfo::StreamInfo& stream_info) const;
void evaluateHeaders(Http::HeaderMap& headers, const StreamInfo::StreamInfo* stream_info) const;
/*
* Same as evaluateHeaders, but returns the modifications that would have been made rather than
* modifying an existing HeaderMap.
* @param stream_info contains additional information about the request.
* @param do_formatting whether or not to evaluate configured transformations; if false, returns
* original values instead.
*/
Http::HeaderTransforms getHeaderTransforms(const StreamInfo::StreamInfo& stream_info,
bool do_formatting = true) const;
protected:
HeaderParser() = default;
private:
struct HeadersToAddEntry {
HeaderFormatterPtr formatter_;
const std::string original_value_;
};
std::vector<std::pair<Http::LowerCaseString, HeadersToAddEntry>> headers_to_add_;
std::vector<Http::LowerCaseString> headers_to_remove_;
};
} // namespace Router
} // namespace Envoy
| 884 |
356 | <reponame>majk1/netbeans-mmd-plugin
/*
* Copyright 2015-2018 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.igormaznitsa.nbmindmap.nb.swing;
import com.igormaznitsa.mindmap.ide.commons.FilePathWithLine;
import com.igormaznitsa.nbmindmap.utils.NbUtils;
import java.io.File;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.swing.JFileChooser;
import com.igormaznitsa.mindmap.ide.commons.SwingUtils;
import com.igormaznitsa.mindmap.swing.services.UIComponentFactory;
import com.igormaznitsa.mindmap.swing.services.UIComponentFactoryProvider;
public final class FileEditPanel extends javax.swing.JPanel {
private static final UIComponentFactory UI_COMPO_FACTORY = UIComponentFactoryProvider.findInstance();
public static final class DataContainer {
private final FilePathWithLine path;
private final boolean showWithSystemTool;
public DataContainer(@Nullable final String path, final boolean showWithSystemTool) {
this.path = new FilePathWithLine(path);
this.showWithSystemTool = showWithSystemTool;
}
@Nonnull
public FilePathWithLine getFilePathWithLine() {
return this.path;
}
public boolean isShowWithSystemTool() {
return this.showWithSystemTool;
}
public boolean isEmptyOrOnlySpaces() {
return this.path.isEmptyOrOnlySpaces();
}
public boolean isValid () {
try {
return this.path.isEmptyOrOnlySpaces() ? true : new File(this.path.getPath()).exists();
}
catch (Exception ex) {
return false;
}
}
}
private static final long serialVersionUID = -6683682013891751388L;
private final File projectFolder;
public FileEditPanel(@Nullable final File projectFolder, @Nullable final DataContainer initialData) {
initComponents();
this.projectFolder = projectFolder;
this.textFieldFilePath.setText(initialData == null ? "" : initialData.getFilePathWithLine().toString());
this.textFieldFilePath.setComponentPopupMenu(SwingUtils.addTextActions(UI_COMPO_FACTORY.makePopupMenu()));
this.checkBoxShowFileInSystem.setSelected(initialData == null ? false : initialData.isShowWithSystemTool());
}
@Nonnull
public DataContainer getData() {
return new DataContainer(this.textFieldFilePath.getText().trim(), this.checkBoxShowFileInSystem.isSelected());
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
labelBrowseCurrentLink = new javax.swing.JLabel();
textFieldFilePath = new javax.swing.JTextField();
buttonChooseFile = new javax.swing.JButton();
buttonReset = new javax.swing.JButton();
optionPanel = new javax.swing.JPanel();
checkBoxShowFileInSystem = new javax.swing.JCheckBox();
setBorder(javax.swing.BorderFactory.createEmptyBorder(10, 10, 1, 10));
setLayout(new java.awt.GridBagLayout());
labelBrowseCurrentLink.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/igormaznitsa/nbmindmap/icons/file_link.png"))); // NOI18N
java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("com/igormaznitsa/nbmindmap/i18n/Bundle"); // NOI18N
labelBrowseCurrentLink.setToolTipText(bundle.getString("FileEditPanel.labelBrowseCurrentLink.toolTipText")); // NOI18N
labelBrowseCurrentLink.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
labelBrowseCurrentLink.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
labelBrowseCurrentLink.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
labelBrowseCurrentLinkMouseClicked(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.ipadx = 10;
add(labelBrowseCurrentLink, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1000.0;
add(textFieldFilePath, gridBagConstraints);
buttonChooseFile.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/igormaznitsa/nbmindmap/icons/file_manager.png"))); // NOI18N
buttonChooseFile.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonChooseFileActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
add(buttonChooseFile, gridBagConstraints);
buttonReset.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/igormaznitsa/nbmindmap/icons/cross16.png"))); // NOI18N
buttonReset.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonResetActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
add(buttonReset, gridBagConstraints);
optionPanel.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT));
org.openide.awt.Mnemonics.setLocalizedText(checkBoxShowFileInSystem, bundle.getString("FileEditPanel.checkBoxShowFileInSystem.text")); // NOI18N
optionPanel.add(checkBoxShowFileInSystem);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.ipadx = 2;
add(optionPanel, gridBagConstraints);
}// </editor-fold>//GEN-END:initComponents
private void labelBrowseCurrentLinkMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_labelBrowseCurrentLinkMouseClicked
if (evt.getClickCount() > 1) {
final File file = new File(this.textFieldFilePath.getText().trim());
NbUtils.openInSystemViewer(null, file);
}
}//GEN-LAST:event_labelBrowseCurrentLinkMouseClicked
private void buttonChooseFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonChooseFileActionPerformed
final File theFile = new File(this.textFieldFilePath.getText().trim());
final File parent = theFile.getParentFile();
final JFileChooser chooser = new JFileChooser(parent == null ? this.projectFolder : parent);
if (theFile.isFile()) {
chooser.setSelectedFile(theFile);
}
chooser.setApproveButtonText("Select");
chooser.setDialogTitle("Select file");
chooser.setMultiSelectionEnabled(false);
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
final File selected = chooser.getSelectedFile();
this.textFieldFilePath.setText(selected.getAbsolutePath());
}
}//GEN-LAST:event_buttonChooseFileActionPerformed
private void buttonResetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonResetActionPerformed
this.textFieldFilePath.setText("");
}//GEN-LAST:event_buttonResetActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton buttonChooseFile;
private javax.swing.JButton buttonReset;
private javax.swing.JCheckBox checkBoxShowFileInSystem;
private javax.swing.JLabel labelBrowseCurrentLink;
private javax.swing.JPanel optionPanel;
private javax.swing.JTextField textFieldFilePath;
// End of variables declaration//GEN-END:variables
}
| 3,015 |
5,964 | // Copyright 2012 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#if V8_TARGET_ARCH_MIPS64
#include <memory>
#include "src/codegen.h"
#include "src/isolate.h"
#include "src/macro-assembler.h"
#include "src/mips64/simulator-mips64.h"
namespace v8 {
namespace internal {
#define __ masm.
#if defined(V8_HOST_ARCH_MIPS)
MemCopyUint8Function CreateMemCopyUint8Function(Isolate* isolate,
MemCopyUint8Function stub) {
#if defined(USE_SIMULATOR)
return stub;
#else
size_t allocated = 0;
byte* buffer = AllocatePage(isolate->heap()->GetRandomMmapAddr(), &allocated);
if (buffer == nullptr) return stub;
MacroAssembler masm(isolate, buffer, static_cast<int>(allocated),
CodeObjectRequired::kNo);
// This code assumes that cache lines are 32 bytes and if the cache line is
// larger it will not work correctly.
{
Label lastb, unaligned, aligned, chkw,
loop16w, chk1w, wordCopy_loop, skip_pref, lastbloop,
leave, ua_chk16w, ua_loop16w, ua_skip_pref, ua_chkw,
ua_chk1w, ua_wordCopy_loop, ua_smallCopy, ua_smallCopy_loop;
// The size of each prefetch.
uint32_t pref_chunk = 32;
// The maximum size of a prefetch, it must not be less than pref_chunk.
// If the real size of a prefetch is greater than max_pref_size and
// the kPrefHintPrepareForStore hint is used, the code will not work
// correctly.
uint32_t max_pref_size = 128;
DCHECK(pref_chunk < max_pref_size);
// pref_limit is set based on the fact that we never use an offset
// greater then 5 on a store pref and that a single pref can
// never be larger then max_pref_size.
uint32_t pref_limit = (5 * pref_chunk) + max_pref_size;
int32_t pref_hint_load = kPrefHintLoadStreamed;
int32_t pref_hint_store = kPrefHintPrepareForStore;
uint32_t loadstore_chunk = 4;
// The initial prefetches may fetch bytes that are before the buffer being
// copied. Start copies with an offset of 4 so avoid this situation when
// using kPrefHintPrepareForStore.
DCHECK(pref_hint_store != kPrefHintPrepareForStore ||
pref_chunk * 4 >= max_pref_size);
// If the size is less than 8, go to lastb. Regardless of size,
// copy dst pointer to v0 for the retuen value.
__ slti(a6, a2, 2 * loadstore_chunk);
__ bne(a6, zero_reg, &lastb);
__ mov(v0, a0); // In delay slot.
// If src and dst have different alignments, go to unaligned, if they
// have the same alignment (but are not actually aligned) do a partial
// load/store to make them aligned. If they are both already aligned
// we can start copying at aligned.
__ xor_(t8, a1, a0);
__ andi(t8, t8, loadstore_chunk - 1); // t8 is a0/a1 word-displacement.
__ bne(t8, zero_reg, &unaligned);
__ subu(a3, zero_reg, a0); // In delay slot.
__ andi(a3, a3, loadstore_chunk - 1); // Copy a3 bytes to align a0/a1.
__ beq(a3, zero_reg, &aligned); // Already aligned.
__ subu(a2, a2, a3); // In delay slot. a2 is the remining bytes count.
if (kArchEndian == kLittle) {
__ lwr(t8, MemOperand(a1));
__ addu(a1, a1, a3);
__ swr(t8, MemOperand(a0));
__ addu(a0, a0, a3);
} else {
__ lwl(t8, MemOperand(a1));
__ addu(a1, a1, a3);
__ swl(t8, MemOperand(a0));
__ addu(a0, a0, a3);
}
// Now dst/src are both aligned to (word) aligned addresses. Set a2 to
// count how many bytes we have to copy after all the 64 byte chunks are
// copied and a3 to the dst pointer after all the 64 byte chunks have been
// copied. We will loop, incrementing a0 and a1 until a0 equals a3.
__ bind(&aligned);
__ andi(t8, a2, 0x3F);
__ beq(a2, t8, &chkw); // Less than 64?
__ subu(a3, a2, t8); // In delay slot.
__ addu(a3, a0, a3); // Now a3 is the final dst after loop.
// When in the loop we prefetch with kPrefHintPrepareForStore hint,
// in this case the a0+x should be past the "a4-32" address. This means:
// for x=128 the last "safe" a0 address is "a4-160". Alternatively, for
// x=64 the last "safe" a0 address is "a4-96". In the current version we
// will use "pref hint, 128(a0)", so "a4-160" is the limit.
if (pref_hint_store == kPrefHintPrepareForStore) {
__ addu(a4, a0, a2); // a4 is the "past the end" address.
__ Subu(t9, a4, pref_limit); // t9 is the "last safe pref" address.
}
__ Pref(pref_hint_load, MemOperand(a1, 0 * pref_chunk));
__ Pref(pref_hint_load, MemOperand(a1, 1 * pref_chunk));
__ Pref(pref_hint_load, MemOperand(a1, 2 * pref_chunk));
__ Pref(pref_hint_load, MemOperand(a1, 3 * pref_chunk));
if (pref_hint_store != kPrefHintPrepareForStore) {
__ Pref(pref_hint_store, MemOperand(a0, 1 * pref_chunk));
__ Pref(pref_hint_store, MemOperand(a0, 2 * pref_chunk));
__ Pref(pref_hint_store, MemOperand(a0, 3 * pref_chunk));
}
__ bind(&loop16w);
__ Lw(a4, MemOperand(a1));
if (pref_hint_store == kPrefHintPrepareForStore) {
__ sltu(v1, t9, a0); // If a0 > t9, don't use next prefetch.
__ Branch(USE_DELAY_SLOT, &skip_pref, gt, v1, Operand(zero_reg));
}
__ Lw(a5, MemOperand(a1, 1, loadstore_chunk)); // Maybe in delay slot.
__ Pref(pref_hint_store, MemOperand(a0, 4 * pref_chunk));
__ Pref(pref_hint_store, MemOperand(a0, 5 * pref_chunk));
__ bind(&skip_pref);
__ Lw(a6, MemOperand(a1, 2, loadstore_chunk));
__ Lw(a7, MemOperand(a1, 3, loadstore_chunk));
__ Lw(t0, MemOperand(a1, 4, loadstore_chunk));
__ Lw(t1, MemOperand(a1, 5, loadstore_chunk));
__ Lw(t2, MemOperand(a1, 6, loadstore_chunk));
__ Lw(t3, MemOperand(a1, 7, loadstore_chunk));
__ Pref(pref_hint_load, MemOperand(a1, 4 * pref_chunk));
__ Sw(a4, MemOperand(a0));
__ Sw(a5, MemOperand(a0, 1, loadstore_chunk));
__ Sw(a6, MemOperand(a0, 2, loadstore_chunk));
__ Sw(a7, MemOperand(a0, 3, loadstore_chunk));
__ Sw(t0, MemOperand(a0, 4, loadstore_chunk));
__ Sw(t1, MemOperand(a0, 5, loadstore_chunk));
__ Sw(t2, MemOperand(a0, 6, loadstore_chunk));
__ Sw(t3, MemOperand(a0, 7, loadstore_chunk));
__ Lw(a4, MemOperand(a1, 8, loadstore_chunk));
__ Lw(a5, MemOperand(a1, 9, loadstore_chunk));
__ Lw(a6, MemOperand(a1, 10, loadstore_chunk));
__ Lw(a7, MemOperand(a1, 11, loadstore_chunk));
__ Lw(t0, MemOperand(a1, 12, loadstore_chunk));
__ Lw(t1, MemOperand(a1, 13, loadstore_chunk));
__ Lw(t2, MemOperand(a1, 14, loadstore_chunk));
__ Lw(t3, MemOperand(a1, 15, loadstore_chunk));
__ Pref(pref_hint_load, MemOperand(a1, 5 * pref_chunk));
__ Sw(a4, MemOperand(a0, 8, loadstore_chunk));
__ Sw(a5, MemOperand(a0, 9, loadstore_chunk));
__ Sw(a6, MemOperand(a0, 10, loadstore_chunk));
__ Sw(a7, MemOperand(a0, 11, loadstore_chunk));
__ Sw(t0, MemOperand(a0, 12, loadstore_chunk));
__ Sw(t1, MemOperand(a0, 13, loadstore_chunk));
__ Sw(t2, MemOperand(a0, 14, loadstore_chunk));
__ Sw(t3, MemOperand(a0, 15, loadstore_chunk));
__ addiu(a0, a0, 16 * loadstore_chunk);
__ bne(a0, a3, &loop16w);
__ addiu(a1, a1, 16 * loadstore_chunk); // In delay slot.
__ mov(a2, t8);
// Here we have src and dest word-aligned but less than 64-bytes to go.
// Check for a 32 bytes chunk and copy if there is one. Otherwise jump
// down to chk1w to handle the tail end of the copy.
__ bind(&chkw);
__ Pref(pref_hint_load, MemOperand(a1, 0 * pref_chunk));
__ andi(t8, a2, 0x1F);
__ beq(a2, t8, &chk1w); // Less than 32?
__ nop(); // In delay slot.
__ Lw(a4, MemOperand(a1));
__ Lw(a5, MemOperand(a1, 1, loadstore_chunk));
__ Lw(a6, MemOperand(a1, 2, loadstore_chunk));
__ Lw(a7, MemOperand(a1, 3, loadstore_chunk));
__ Lw(t0, MemOperand(a1, 4, loadstore_chunk));
__ Lw(t1, MemOperand(a1, 5, loadstore_chunk));
__ Lw(t2, MemOperand(a1, 6, loadstore_chunk));
__ Lw(t3, MemOperand(a1, 7, loadstore_chunk));
__ addiu(a1, a1, 8 * loadstore_chunk);
__ Sw(a4, MemOperand(a0));
__ Sw(a5, MemOperand(a0, 1, loadstore_chunk));
__ Sw(a6, MemOperand(a0, 2, loadstore_chunk));
__ Sw(a7, MemOperand(a0, 3, loadstore_chunk));
__ Sw(t0, MemOperand(a0, 4, loadstore_chunk));
__ Sw(t1, MemOperand(a0, 5, loadstore_chunk));
__ Sw(t2, MemOperand(a0, 6, loadstore_chunk));
__ Sw(t3, MemOperand(a0, 7, loadstore_chunk));
__ addiu(a0, a0, 8 * loadstore_chunk);
// Here we have less than 32 bytes to copy. Set up for a loop to copy
// one word at a time. Set a2 to count how many bytes we have to copy
// after all the word chunks are copied and a3 to the dst pointer after
// all the word chunks have been copied. We will loop, incrementing a0
// and a1 until a0 equals a3.
__ bind(&chk1w);
__ andi(a2, t8, loadstore_chunk - 1);
__ beq(a2, t8, &lastb);
__ subu(a3, t8, a2); // In delay slot.
__ addu(a3, a0, a3);
__ bind(&wordCopy_loop);
__ Lw(a7, MemOperand(a1));
__ addiu(a0, a0, loadstore_chunk);
__ addiu(a1, a1, loadstore_chunk);
__ bne(a0, a3, &wordCopy_loop);
__ Sw(a7, MemOperand(a0, -1, loadstore_chunk)); // In delay slot.
__ bind(&lastb);
__ Branch(&leave, le, a2, Operand(zero_reg));
__ addu(a3, a0, a2);
__ bind(&lastbloop);
__ Lb(v1, MemOperand(a1));
__ addiu(a0, a0, 1);
__ addiu(a1, a1, 1);
__ bne(a0, a3, &lastbloop);
__ Sb(v1, MemOperand(a0, -1)); // In delay slot.
__ bind(&leave);
__ jr(ra);
__ nop();
// Unaligned case. Only the dst gets aligned so we need to do partial
// loads of the source followed by normal stores to the dst (once we
// have aligned the destination).
__ bind(&unaligned);
__ andi(a3, a3, loadstore_chunk - 1); // Copy a3 bytes to align a0/a1.
__ beq(a3, zero_reg, &ua_chk16w);
__ subu(a2, a2, a3); // In delay slot.
if (kArchEndian == kLittle) {
__ lwr(v1, MemOperand(a1));
__ lwl(v1,
MemOperand(a1, 1, loadstore_chunk, MemOperand::offset_minus_one));
__ addu(a1, a1, a3);
__ swr(v1, MemOperand(a0));
__ addu(a0, a0, a3);
} else {
__ lwl(v1, MemOperand(a1));
__ lwr(v1,
MemOperand(a1, 1, loadstore_chunk, MemOperand::offset_minus_one));
__ addu(a1, a1, a3);
__ swl(v1, MemOperand(a0));
__ addu(a0, a0, a3);
}
// Now the dst (but not the source) is aligned. Set a2 to count how many
// bytes we have to copy after all the 64 byte chunks are copied and a3 to
// the dst pointer after all the 64 byte chunks have been copied. We will
// loop, incrementing a0 and a1 until a0 equals a3.
__ bind(&ua_chk16w);
__ andi(t8, a2, 0x3F);
__ beq(a2, t8, &ua_chkw);
__ subu(a3, a2, t8); // In delay slot.
__ addu(a3, a0, a3);
if (pref_hint_store == kPrefHintPrepareForStore) {
__ addu(a4, a0, a2);
__ Subu(t9, a4, pref_limit);
}
__ Pref(pref_hint_load, MemOperand(a1, 0 * pref_chunk));
__ Pref(pref_hint_load, MemOperand(a1, 1 * pref_chunk));
__ Pref(pref_hint_load, MemOperand(a1, 2 * pref_chunk));
if (pref_hint_store != kPrefHintPrepareForStore) {
__ Pref(pref_hint_store, MemOperand(a0, 1 * pref_chunk));
__ Pref(pref_hint_store, MemOperand(a0, 2 * pref_chunk));
__ Pref(pref_hint_store, MemOperand(a0, 3 * pref_chunk));
}
__ bind(&ua_loop16w);
if (kArchEndian == kLittle) {
__ Pref(pref_hint_load, MemOperand(a1, 3 * pref_chunk));
__ lwr(a4, MemOperand(a1));
__ lwr(a5, MemOperand(a1, 1, loadstore_chunk));
__ lwr(a6, MemOperand(a1, 2, loadstore_chunk));
if (pref_hint_store == kPrefHintPrepareForStore) {
__ sltu(v1, t9, a0);
__ Branch(USE_DELAY_SLOT, &ua_skip_pref, gt, v1, Operand(zero_reg));
}
__ lwr(a7, MemOperand(a1, 3, loadstore_chunk)); // Maybe in delay slot.
__ Pref(pref_hint_store, MemOperand(a0, 4 * pref_chunk));
__ Pref(pref_hint_store, MemOperand(a0, 5 * pref_chunk));
__ bind(&ua_skip_pref);
__ lwr(t0, MemOperand(a1, 4, loadstore_chunk));
__ lwr(t1, MemOperand(a1, 5, loadstore_chunk));
__ lwr(t2, MemOperand(a1, 6, loadstore_chunk));
__ lwr(t3, MemOperand(a1, 7, loadstore_chunk));
__ lwl(a4,
MemOperand(a1, 1, loadstore_chunk, MemOperand::offset_minus_one));
__ lwl(a5,
MemOperand(a1, 2, loadstore_chunk, MemOperand::offset_minus_one));
__ lwl(a6,
MemOperand(a1, 3, loadstore_chunk, MemOperand::offset_minus_one));
__ lwl(a7,
MemOperand(a1, 4, loadstore_chunk, MemOperand::offset_minus_one));
__ lwl(t0,
MemOperand(a1, 5, loadstore_chunk, MemOperand::offset_minus_one));
__ lwl(t1,
MemOperand(a1, 6, loadstore_chunk, MemOperand::offset_minus_one));
__ lwl(t2,
MemOperand(a1, 7, loadstore_chunk, MemOperand::offset_minus_one));
__ lwl(t3,
MemOperand(a1, 8, loadstore_chunk, MemOperand::offset_minus_one));
} else {
__ Pref(pref_hint_load, MemOperand(a1, 3 * pref_chunk));
__ lwl(a4, MemOperand(a1));
__ lwl(a5, MemOperand(a1, 1, loadstore_chunk));
__ lwl(a6, MemOperand(a1, 2, loadstore_chunk));
if (pref_hint_store == kPrefHintPrepareForStore) {
__ sltu(v1, t9, a0);
__ Branch(USE_DELAY_SLOT, &ua_skip_pref, gt, v1, Operand(zero_reg));
}
__ lwl(a7, MemOperand(a1, 3, loadstore_chunk)); // Maybe in delay slot.
__ Pref(pref_hint_store, MemOperand(a0, 4 * pref_chunk));
__ Pref(pref_hint_store, MemOperand(a0, 5 * pref_chunk));
__ bind(&ua_skip_pref);
__ lwl(t0, MemOperand(a1, 4, loadstore_chunk));
__ lwl(t1, MemOperand(a1, 5, loadstore_chunk));
__ lwl(t2, MemOperand(a1, 6, loadstore_chunk));
__ lwl(t3, MemOperand(a1, 7, loadstore_chunk));
__ lwr(a4,
MemOperand(a1, 1, loadstore_chunk, MemOperand::offset_minus_one));
__ lwr(a5,
MemOperand(a1, 2, loadstore_chunk, MemOperand::offset_minus_one));
__ lwr(a6,
MemOperand(a1, 3, loadstore_chunk, MemOperand::offset_minus_one));
__ lwr(a7,
MemOperand(a1, 4, loadstore_chunk, MemOperand::offset_minus_one));
__ lwr(t0,
MemOperand(a1, 5, loadstore_chunk, MemOperand::offset_minus_one));
__ lwr(t1,
MemOperand(a1, 6, loadstore_chunk, MemOperand::offset_minus_one));
__ lwr(t2,
MemOperand(a1, 7, loadstore_chunk, MemOperand::offset_minus_one));
__ lwr(t3,
MemOperand(a1, 8, loadstore_chunk, MemOperand::offset_minus_one));
}
__ Pref(pref_hint_load, MemOperand(a1, 4 * pref_chunk));
__ Sw(a4, MemOperand(a0));
__ Sw(a5, MemOperand(a0, 1, loadstore_chunk));
__ Sw(a6, MemOperand(a0, 2, loadstore_chunk));
__ Sw(a7, MemOperand(a0, 3, loadstore_chunk));
__ Sw(t0, MemOperand(a0, 4, loadstore_chunk));
__ Sw(t1, MemOperand(a0, 5, loadstore_chunk));
__ Sw(t2, MemOperand(a0, 6, loadstore_chunk));
__ Sw(t3, MemOperand(a0, 7, loadstore_chunk));
if (kArchEndian == kLittle) {
__ lwr(a4, MemOperand(a1, 8, loadstore_chunk));
__ lwr(a5, MemOperand(a1, 9, loadstore_chunk));
__ lwr(a6, MemOperand(a1, 10, loadstore_chunk));
__ lwr(a7, MemOperand(a1, 11, loadstore_chunk));
__ lwr(t0, MemOperand(a1, 12, loadstore_chunk));
__ lwr(t1, MemOperand(a1, 13, loadstore_chunk));
__ lwr(t2, MemOperand(a1, 14, loadstore_chunk));
__ lwr(t3, MemOperand(a1, 15, loadstore_chunk));
__ lwl(a4,
MemOperand(a1, 9, loadstore_chunk, MemOperand::offset_minus_one));
__ lwl(a5,
MemOperand(a1, 10, loadstore_chunk, MemOperand::offset_minus_one));
__ lwl(a6,
MemOperand(a1, 11, loadstore_chunk, MemOperand::offset_minus_one));
__ lwl(a7,
MemOperand(a1, 12, loadstore_chunk, MemOperand::offset_minus_one));
__ lwl(t0,
MemOperand(a1, 13, loadstore_chunk, MemOperand::offset_minus_one));
__ lwl(t1,
MemOperand(a1, 14, loadstore_chunk, MemOperand::offset_minus_one));
__ lwl(t2,
MemOperand(a1, 15, loadstore_chunk, MemOperand::offset_minus_one));
__ lwl(t3,
MemOperand(a1, 16, loadstore_chunk, MemOperand::offset_minus_one));
} else {
__ lwl(a4, MemOperand(a1, 8, loadstore_chunk));
__ lwl(a5, MemOperand(a1, 9, loadstore_chunk));
__ lwl(a6, MemOperand(a1, 10, loadstore_chunk));
__ lwl(a7, MemOperand(a1, 11, loadstore_chunk));
__ lwl(t0, MemOperand(a1, 12, loadstore_chunk));
__ lwl(t1, MemOperand(a1, 13, loadstore_chunk));
__ lwl(t2, MemOperand(a1, 14, loadstore_chunk));
__ lwl(t3, MemOperand(a1, 15, loadstore_chunk));
__ lwr(a4,
MemOperand(a1, 9, loadstore_chunk, MemOperand::offset_minus_one));
__ lwr(a5,
MemOperand(a1, 10, loadstore_chunk, MemOperand::offset_minus_one));
__ lwr(a6,
MemOperand(a1, 11, loadstore_chunk, MemOperand::offset_minus_one));
__ lwr(a7,
MemOperand(a1, 12, loadstore_chunk, MemOperand::offset_minus_one));
__ lwr(t0,
MemOperand(a1, 13, loadstore_chunk, MemOperand::offset_minus_one));
__ lwr(t1,
MemOperand(a1, 14, loadstore_chunk, MemOperand::offset_minus_one));
__ lwr(t2,
MemOperand(a1, 15, loadstore_chunk, MemOperand::offset_minus_one));
__ lwr(t3,
MemOperand(a1, 16, loadstore_chunk, MemOperand::offset_minus_one));
}
__ Pref(pref_hint_load, MemOperand(a1, 5 * pref_chunk));
__ Sw(a4, MemOperand(a0, 8, loadstore_chunk));
__ Sw(a5, MemOperand(a0, 9, loadstore_chunk));
__ Sw(a6, MemOperand(a0, 10, loadstore_chunk));
__ Sw(a7, MemOperand(a0, 11, loadstore_chunk));
__ Sw(t0, MemOperand(a0, 12, loadstore_chunk));
__ Sw(t1, MemOperand(a0, 13, loadstore_chunk));
__ Sw(t2, MemOperand(a0, 14, loadstore_chunk));
__ Sw(t3, MemOperand(a0, 15, loadstore_chunk));
__ addiu(a0, a0, 16 * loadstore_chunk);
__ bne(a0, a3, &ua_loop16w);
__ addiu(a1, a1, 16 * loadstore_chunk); // In delay slot.
__ mov(a2, t8);
// Here less than 64-bytes. Check for
// a 32 byte chunk and copy if there is one. Otherwise jump down to
// ua_chk1w to handle the tail end of the copy.
__ bind(&ua_chkw);
__ Pref(pref_hint_load, MemOperand(a1));
__ andi(t8, a2, 0x1F);
__ beq(a2, t8, &ua_chk1w);
__ nop(); // In delay slot.
if (kArchEndian == kLittle) {
__ lwr(a4, MemOperand(a1));
__ lwr(a5, MemOperand(a1, 1, loadstore_chunk));
__ lwr(a6, MemOperand(a1, 2, loadstore_chunk));
__ lwr(a7, MemOperand(a1, 3, loadstore_chunk));
__ lwr(t0, MemOperand(a1, 4, loadstore_chunk));
__ lwr(t1, MemOperand(a1, 5, loadstore_chunk));
__ lwr(t2, MemOperand(a1, 6, loadstore_chunk));
__ lwr(t3, MemOperand(a1, 7, loadstore_chunk));
__ lwl(a4,
MemOperand(a1, 1, loadstore_chunk, MemOperand::offset_minus_one));
__ lwl(a5,
MemOperand(a1, 2, loadstore_chunk, MemOperand::offset_minus_one));
__ lwl(a6,
MemOperand(a1, 3, loadstore_chunk, MemOperand::offset_minus_one));
__ lwl(a7,
MemOperand(a1, 4, loadstore_chunk, MemOperand::offset_minus_one));
__ lwl(t0,
MemOperand(a1, 5, loadstore_chunk, MemOperand::offset_minus_one));
__ lwl(t1,
MemOperand(a1, 6, loadstore_chunk, MemOperand::offset_minus_one));
__ lwl(t2,
MemOperand(a1, 7, loadstore_chunk, MemOperand::offset_minus_one));
__ lwl(t3,
MemOperand(a1, 8, loadstore_chunk, MemOperand::offset_minus_one));
} else {
__ lwl(a4, MemOperand(a1));
__ lwl(a5, MemOperand(a1, 1, loadstore_chunk));
__ lwl(a6, MemOperand(a1, 2, loadstore_chunk));
__ lwl(a7, MemOperand(a1, 3, loadstore_chunk));
__ lwl(t0, MemOperand(a1, 4, loadstore_chunk));
__ lwl(t1, MemOperand(a1, 5, loadstore_chunk));
__ lwl(t2, MemOperand(a1, 6, loadstore_chunk));
__ lwl(t3, MemOperand(a1, 7, loadstore_chunk));
__ lwr(a4,
MemOperand(a1, 1, loadstore_chunk, MemOperand::offset_minus_one));
__ lwr(a5,
MemOperand(a1, 2, loadstore_chunk, MemOperand::offset_minus_one));
__ lwr(a6,
MemOperand(a1, 3, loadstore_chunk, MemOperand::offset_minus_one));
__ lwr(a7,
MemOperand(a1, 4, loadstore_chunk, MemOperand::offset_minus_one));
__ lwr(t0,
MemOperand(a1, 5, loadstore_chunk, MemOperand::offset_minus_one));
__ lwr(t1,
MemOperand(a1, 6, loadstore_chunk, MemOperand::offset_minus_one));
__ lwr(t2,
MemOperand(a1, 7, loadstore_chunk, MemOperand::offset_minus_one));
__ lwr(t3,
MemOperand(a1, 8, loadstore_chunk, MemOperand::offset_minus_one));
}
__ addiu(a1, a1, 8 * loadstore_chunk);
__ Sw(a4, MemOperand(a0));
__ Sw(a5, MemOperand(a0, 1, loadstore_chunk));
__ Sw(a6, MemOperand(a0, 2, loadstore_chunk));
__ Sw(a7, MemOperand(a0, 3, loadstore_chunk));
__ Sw(t0, MemOperand(a0, 4, loadstore_chunk));
__ Sw(t1, MemOperand(a0, 5, loadstore_chunk));
__ Sw(t2, MemOperand(a0, 6, loadstore_chunk));
__ Sw(t3, MemOperand(a0, 7, loadstore_chunk));
__ addiu(a0, a0, 8 * loadstore_chunk);
// Less than 32 bytes to copy. Set up for a loop to
// copy one word at a time.
__ bind(&ua_chk1w);
__ andi(a2, t8, loadstore_chunk - 1);
__ beq(a2, t8, &ua_smallCopy);
__ subu(a3, t8, a2); // In delay slot.
__ addu(a3, a0, a3);
__ bind(&ua_wordCopy_loop);
if (kArchEndian == kLittle) {
__ lwr(v1, MemOperand(a1));
__ lwl(v1,
MemOperand(a1, 1, loadstore_chunk, MemOperand::offset_minus_one));
} else {
__ lwl(v1, MemOperand(a1));
__ lwr(v1,
MemOperand(a1, 1, loadstore_chunk, MemOperand::offset_minus_one));
}
__ addiu(a0, a0, loadstore_chunk);
__ addiu(a1, a1, loadstore_chunk);
__ bne(a0, a3, &ua_wordCopy_loop);
__ Sw(v1, MemOperand(a0, -1, loadstore_chunk)); // In delay slot.
// Copy the last 8 bytes.
__ bind(&ua_smallCopy);
__ beq(a2, zero_reg, &leave);
__ addu(a3, a0, a2); // In delay slot.
__ bind(&ua_smallCopy_loop);
__ Lb(v1, MemOperand(a1));
__ addiu(a0, a0, 1);
__ addiu(a1, a1, 1);
__ bne(a0, a3, &ua_smallCopy_loop);
__ Sb(v1, MemOperand(a0, -1)); // In delay slot.
__ jr(ra);
__ nop();
}
CodeDesc desc;
masm.GetCode(isolte, &desc);
DCHECK(!RelocInfo::RequiresRelocation(desc));
Assembler::FlushICache(buffer, allocated);
CHECK(SetPermissions(buffer, allocated, PageAllocator::kReadExecute));
return FUNCTION_CAST<MemCopyUint8Function>(buffer);
#endif
}
#endif
UnaryMathFunctionWithIsolate CreateSqrtFunction(Isolate* isolate) {
#if defined(USE_SIMULATOR)
return nullptr;
#else
size_t allocated = 0;
byte* buffer = AllocatePage(isolate->heap()->GetRandomMmapAddr(), &allocated);
if (buffer == nullptr) return nullptr;
MacroAssembler masm(isolate, buffer, static_cast<int>(allocated),
CodeObjectRequired::kNo);
__ MovFromFloatParameter(f12);
__ sqrt_d(f0, f12);
__ MovToFloatResult(f0);
__ Ret();
CodeDesc desc;
masm.GetCode(isolate, &desc);
DCHECK(!RelocInfo::RequiresRelocation(desc));
Assembler::FlushICache(buffer, allocated);
CHECK(SetPermissions(buffer, allocated, PageAllocator::kReadExecute));
return FUNCTION_CAST<UnaryMathFunctionWithIsolate>(buffer);
#endif
}
#undef __
} // namespace internal
} // namespace v8
#endif // V8_TARGET_ARCH_MIPS64
| 11,422 |
435 | <filename>warehouse/query-core/src/test/java/datawave/query/RebuildingScannerTestHelper.java<gh_stars>100-1000
package datawave.query;
import datawave.accumulo.inmemory.InMemoryBatchScanner;
import datawave.accumulo.inmemory.InMemoryConnector;
import datawave.accumulo.inmemory.InMemoryInstance;
import datawave.accumulo.inmemory.InMemoryScanner;
import datawave.accumulo.inmemory.InMemoryScannerBase;
import datawave.accumulo.inmemory.ScannerRebuilder;
import datawave.query.attributes.Document;
import datawave.query.function.deserializer.KryoDocumentDeserializer;
import datawave.query.iterator.profile.FinalDocumentTrackingIterator;
import org.apache.accumulo.core.client.AccumuloException;
import org.apache.accumulo.core.client.AccumuloSecurityException;
import org.apache.accumulo.core.client.BatchDeleter;
import org.apache.accumulo.core.client.BatchScanner;
import org.apache.accumulo.core.client.BatchWriter;
import org.apache.accumulo.core.client.BatchWriterConfig;
import org.apache.accumulo.core.client.ConditionalWriter;
import org.apache.accumulo.core.client.ConditionalWriterConfig;
import org.apache.accumulo.core.client.Connector;
import org.apache.accumulo.core.client.Instance;
import org.apache.accumulo.core.client.IteratorSetting;
import org.apache.accumulo.core.client.MultiTableBatchWriter;
import org.apache.accumulo.core.client.Scanner;
import org.apache.accumulo.core.client.ScannerBase;
import org.apache.accumulo.core.client.TableNotFoundException;
import org.apache.accumulo.core.client.admin.InstanceOperations;
import org.apache.accumulo.core.client.admin.NamespaceOperations;
import org.apache.accumulo.core.client.admin.ReplicationOperations;
import org.apache.accumulo.core.client.admin.SecurityOperations;
import org.apache.accumulo.core.client.admin.TableOperations;
import org.apache.accumulo.core.client.sample.SamplerConfiguration;
import org.apache.accumulo.core.client.security.tokens.AuthenticationToken;
import org.apache.accumulo.core.client.security.tokens.PasswordToken;
import org.apache.accumulo.core.data.ByteSequence;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.PartialKey;
import org.apache.accumulo.core.data.Range;
import org.apache.accumulo.core.data.Value;
import org.apache.accumulo.core.iterators.IterationInterruptedException;
import org.apache.accumulo.core.iterators.IteratorEnvironment;
import org.apache.accumulo.core.iterators.SortedKeyValueIterator;
import org.apache.accumulo.core.security.Authorizations;
import org.apache.accumulo.core.util.ByteBufferUtil;
import org.apache.accumulo.core.util.TextUtil;
import org.apache.hadoop.io.Text;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.Spliterator;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
/**
* This helper provides support for testing the teardown of iterators at randomly. Simply use the getConnector methods and all scanners created will contain an
* iterator that will force the stack to be torn down.
*/
public class RebuildingScannerTestHelper {
public enum TEARDOWN {
NEVER(NeverTeardown.class), ALWAYS(AlwaysTeardown.class), RANDOM(RandomTeardown.class), EVERY_OTHER(EveryOtherTeardown.class), ALWAYS_SANS_CONSISTENCY(
AlwaysTeardownWithoutConsistency.class), RANDOM_SANS_CONSISTENCY(RandomTeardownWithoutConsistency.class), EVERY_OTHER_SANS_CONSISTENCY(
EveryOtherTeardownWithoutConsistency.class);
private Class<? extends TeardownListener> tclass;
TEARDOWN(Class<? extends TeardownListener> tclass) {
this.tclass = tclass;
}
public TeardownListener instance() {
try {
return tclass.newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
public enum INTERRUPT {
NEVER(NeverInterrupt.class),
RANDOM(RandomInterrupt.class),
EVERY_OTHER(EveryOtherInterrupt.class),
FI_EVERY_OTHER(FiEveryOtherInterrupt.class),
RANDOM_HIGH(HighRandomInterrupt.class);
private Class<? extends InterruptListener> iclass;
INTERRUPT(Class<? extends InterruptListener> iclass) {
this.iclass = iclass;
}
public InterruptListener instance() {
try {
return iclass.newInstance();
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
}
}
}
public static class InterruptIterator implements SortedKeyValueIterator<Key,Value> {
private SortedKeyValueIterator<Key,Value> source;
private InterruptListener interruptListener;
private boolean initialized = false;
public InterruptIterator() {
// no-op
}
public InterruptIterator(InterruptIterator other, IteratorEnvironment env) {
this.interruptListener = other.interruptListener;
this.source = other.source.deepCopy(env);
}
@Override
public void init(SortedKeyValueIterator<Key,Value> source, Map<String,String> map, IteratorEnvironment iteratorEnvironment) throws IOException {
this.source = source;
}
@Override
public boolean hasTop() {
return source.hasTop();
}
@Override
public void next() throws IOException {
if (initialized && interruptListener != null && interruptListener.interrupt(source.getTopKey())) {
throw new IterationInterruptedException("testing next interrupt");
}
source.next();
}
@Override
public void seek(Range range, Collection<ByteSequence> collection, boolean inclusive) throws IOException {
if (interruptListener != null && interruptListener.interrupt(null)) {
throw new IterationInterruptedException("testing seek interrupt");
}
source.seek(range, collection, inclusive);
initialized = true;
}
@Override
public Key getTopKey() {
return source.getTopKey();
}
@Override
public Value getTopValue() {
return source.getTopValue();
}
@Override
public SortedKeyValueIterator<Key,Value> deepCopy(IteratorEnvironment env) {
return new InterruptIterator(this, env);
}
// must be set by the RebuildingIterator after each rebuild
public void setInterruptListener(InterruptListener listener) {
this.interruptListener = listener;
}
}
public interface InterruptListener {
boolean interrupt(Key key);
void processedInterrupt(boolean interrupt);
}
/**
* Never interrupts
*/
public static class NeverInterrupt implements InterruptListener {
@Override
public boolean interrupt(Key key) {
return false;
}
@Override
public void processedInterrupt(boolean interrupt) {
// no-op
}
}
/**
* Sets interrupting at 50% rate
*/
public static class RandomInterrupt implements InterruptListener {
protected final Random random = new Random();
protected boolean interrupting = random.nextBoolean();
@Override
public boolean interrupt(Key key) {
return interrupting;
}
@Override
public void processedInterrupt(boolean interrupt) {
interrupting = random.nextBoolean();
}
}
/**
* Sets interrupting at 95% rate
*/
public static class HighRandomInterrupt extends RandomInterrupt {
@Override
public void processedInterrupt(boolean interrupt) {
interrupting = random.nextInt(100) < 95;
}
}
/**
* interrupts every other call
*/
public static class EveryOtherInterrupt implements InterruptListener {
protected boolean interrupting = false;
@Override
public boolean interrupt(Key key) {
return interrupting;
}
@Override
public void processedInterrupt(boolean interrupt) {
interrupting = !interrupting;
}
}
/**
* interrupt every other fi key, otherwise don't interrupt
*/
public static class FiEveryOtherInterrupt extends EveryOtherInterrupt {
public FiEveryOtherInterrupt() {
// initialize to true first
processedInterrupt(false);
}
@Override
public boolean interrupt(Key key) {
if (key != null && key.getColumnFamily().toString().startsWith("fi" + Constants.NULL)) {
return super.interrupt(key);
}
return false;
}
}
public static Connector getConnector(InMemoryInstance i, String user, byte[] pass, TEARDOWN teardown, INTERRUPT interrupt) throws AccumuloException,
AccumuloSecurityException {
return new RebuildingConnector((InMemoryConnector) (i.getConnector(user, new PasswordToken(pass))), teardown, interrupt);
}
public static Connector getConnector(InMemoryInstance i, String user, ByteBuffer pass, TEARDOWN teardown, INTERRUPT interrupt) throws AccumuloException,
AccumuloSecurityException {
return new RebuildingConnector((InMemoryConnector) (i.getConnector(user, ByteBufferUtil.toBytes(pass))), teardown, interrupt);
}
public static Connector getConnector(InMemoryInstance i, String user, CharSequence pass, TEARDOWN teardown, INTERRUPT interrupt) throws AccumuloException,
AccumuloSecurityException {
return new RebuildingConnector((InMemoryConnector) (i.getConnector(user, TextUtil.getBytes(new Text(pass.toString())))), teardown, interrupt);
}
public static Connector getConnector(InMemoryInstance i, String principal, AuthenticationToken token, TEARDOWN teardown, INTERRUPT interrupt)
throws AccumuloException, AccumuloSecurityException {
return new RebuildingConnector((InMemoryConnector) (i.getConnector(principal, token)), teardown, interrupt);
}
public interface TeardownListener {
boolean teardown();
boolean checkConsistency();
}
public static class RebuildingIterator implements Iterator<Map.Entry<Key,Value>> {
private InMemoryScannerBase baseScanner;
private Iterator<Map.Entry<Key,Value>> delegate;
private final ScannerRebuilder scanner;
private final TeardownListener teardown;
private final InterruptListener interruptListener;
private Map.Entry<Key,Value> next = null;
private Map.Entry<Key,Value> lastKey = null;
private KryoDocumentDeserializer deserializer = new KryoDocumentDeserializer();
private boolean initialized = false;
public RebuildingIterator(InMemoryScannerBase baseScanner, ScannerRebuilder scanner, TeardownListener teardown, InterruptListener interruptListener) {
this.baseScanner = baseScanner;
this.scanner = scanner;
this.teardown = teardown;
this.interruptListener = interruptListener;
init();
}
private void init() {
// create the interruptIterator and add it to the base scanner
InterruptIterator interruptIterator = new InterruptIterator();
interruptIterator.setInterruptListener(interruptListener);
// add it to the baseScanner injected list so that this iterator is not torn down and losing state with
// every interrupt or rebuild
baseScanner.addInjectedIterator(interruptIterator);
}
@Override
public boolean hasNext() {
if (!initialized) {
findNext();
initialized = true;
}
return next != null;
}
@Override
public Map.Entry<Key,Value> next() {
if (!initialized) {
findNext();
initialized = true;
}
lastKey = next;
findNext();
return lastKey;
}
private void findNext() {
boolean interrupted = false;
int interruptCount = 0;
// track if the iterator has already been rebuilt or not, do not rebuild on the same key more than once
boolean rebuilt = false;
do {
try {
if (delegate == null) {
// build initial iterator. It can be interrupted since it calls seek/next under the covers to prepare the first key
delegate = baseScanner.iterator();
}
if (interrupted) {
Key last = lastKey != null ? lastKey.getKey() : null;
if (!rebuilt) {
delegate = scanner.rebuild(last);
rebuilt = true;
} else {
// cal with a null last key to prevent an update to the ranges
delegate = scanner.rebuild(null);
}
}
if (lastKey != null && teardown.teardown()) {
boolean hasNext = delegate.hasNext();
Map.Entry<Key,Value> next = (hasNext ? delegate.next() : null);
if (hasNext && (next == null)) {
throw new RuntimeException("Pre teardown: If hasNext() is true, next() must not return null. interrupted: " + interruptCount);
}
if (!rebuilt) {
delegate = scanner.rebuild(lastKey.getKey());
rebuilt = true;
} else {
// was already rebuilt once with this key, just re-create the iterator
delegate = scanner.rebuild(null);
}
boolean rebuildHasNext = delegate.hasNext();
Map.Entry<Key,Value> rebuildNext = (rebuildHasNext ? delegate.next() : null);
if (rebuildHasNext && (rebuildNext == null)) {
throw new RuntimeException("After rebuild: If hasNext() is true, next() must not return null. interrupted: " + interruptCount);
}
if (hasNext != rebuildHasNext) {
// the only known scenario where this is ok is when the rebuild causes us to have a "FinalDocument" where previously we did not
// have/need one
if (teardown.checkConsistency() && (hasNext || !FinalDocumentTrackingIterator.isFinalDocumentKey(rebuildNext.getKey()))) {
throw new RuntimeException("Unexpected change in top key: hasNext is no longer " + hasNext + " interrupted: " + interruptCount);
}
} else if (hasNext) {
if (teardown.checkConsistency()) {
// if we are dealing with a final document, then both prebuild and postbuild must be returning a final document
// otherwise the keys need to be identical save for the timestamp
boolean nextFinal = FinalDocumentTrackingIterator.isFinalDocumentKey(next.getKey());
boolean rebuildNextFinal = FinalDocumentTrackingIterator.isFinalDocumentKey(rebuildNext.getKey());
if (nextFinal || rebuildNextFinal) {
if (nextFinal != rebuildNextFinal) {
throw new RuntimeException("Unexpected change in top key: expected " + next + " BUT GOT " + rebuildNext
+ " interrupted: " + interruptCount);
}
} else if (!next.getKey().equals(rebuildNext.getKey(), PartialKey.ROW_COLFAM_COLQUAL_COLVIS)) {
final Document rebuildDocument = deserializer.apply(rebuildNext).getValue();
final Document lastDocument = deserializer.apply(lastKey).getValue();
// if the keys don't match but are returning the previous document and using a new key this is okay
if (!lastDocument.get("RECORD_ID").getData().toString().equals(rebuildDocument.get("RECORD_ID").getData().toString())
&& !lastKey.getKey().equals(rebuildNext.getKey(), PartialKey.ROW_COLFAM_COLQUAL_COLVIS)) {
throw new RuntimeException("Unexpected change in top key: expected " + next + " BUT GOT " + rebuildNext);
}
}
}
}
this.next = rebuildNext;
} else {
this.next = (delegate.hasNext() ? delegate.next() : null);
// only clear interrupts flag when not dealing with rebuilds
interruptListener.processedInterrupt(false);
}
// reset interrupted flag
interrupted = false;
} catch (IterationInterruptedException e) {
interrupted = true;
interruptListener.processedInterrupt(true);
interruptCount++;
}
} while (interrupted);
}
@Override
public void remove() {
delegate.remove();
}
@Override
public void forEachRemaining(Consumer<? super Map.Entry<Key,Value>> action) {
delegate.forEachRemaining(action);
}
}
public static class RandomTeardown implements TeardownListener {
private final Random random = new Random();
@Override
public boolean teardown() {
return (random.nextBoolean());
}
@Override
public boolean checkConsistency() {
return true;
}
}
public static class RandomTeardownWithoutConsistency extends RandomTeardown {
@Override
public boolean checkConsistency() {
return false;
}
}
public static class EveryOtherTeardown implements TeardownListener {
private transient boolean teardown = false;
@Override
public boolean teardown() {
teardown = !teardown;
return (teardown);
}
@Override
public boolean checkConsistency() {
return true;
}
}
public static class EveryOtherTeardownWithoutConsistency extends EveryOtherTeardown {
@Override
public boolean checkConsistency() {
return false;
}
}
public static class AlwaysTeardown implements TeardownListener {
@Override
public boolean teardown() {
return true;
}
@Override
public boolean checkConsistency() {
return true;
}
}
public static class AlwaysTeardownWithoutConsistency extends AlwaysTeardown {
@Override
public boolean checkConsistency() {
return false;
}
}
public static class NeverTeardown implements TeardownListener {
@Override
public boolean teardown() {
return false;
}
@Override
public boolean checkConsistency() {
return true;
}
}
public static class RebuildingScanner extends DelegatingScannerBase implements Scanner {
private final TEARDOWN teardown;
private final INTERRUPT interrupt;
public RebuildingScanner(InMemoryScanner delegate, TEARDOWN teardown, INTERRUPT interrupt) {
super(delegate);
this.teardown = teardown;
this.interrupt = interrupt;
}
@Override
public Iterator<Map.Entry<Key,Value>> iterator() {
try {
return new RebuildingIterator((InMemoryScannerBase) delegate, ((InMemoryScanner) delegate).clone(), teardown.instance(), interrupt.instance());
} catch (Exception e) {
throw new RuntimeException("Misconfigured teardown listener class most likely", e);
}
}
@Override
public void setTimeOut(int timeOut) {
((InMemoryScanner) delegate).setTimeOut(timeOut);
}
@Override
public int getTimeOut() {
return ((InMemoryScanner) delegate).getTimeOut();
}
@Override
public void setRange(Range range) {
((InMemoryScanner) delegate).setRange(range);
}
@Override
public Range getRange() {
return ((InMemoryScanner) delegate).getRange();
}
@Override
public void setBatchSize(int size) {
((InMemoryScanner) delegate).setBatchSize(size);
}
@Override
public int getBatchSize() {
return ((InMemoryScanner) delegate).getBatchSize();
}
@Override
public void enableIsolation() {
((InMemoryScanner) delegate).enableIsolation();
}
@Override
public void disableIsolation() {
((InMemoryScanner) delegate).disableIsolation();
}
@Override
public long getReadaheadThreshold() {
return ((InMemoryScanner) delegate).getReadaheadThreshold();
}
@Override
public void setReadaheadThreshold(long batches) {
((InMemoryScanner) delegate).setReadaheadThreshold(batches);
}
}
public static class RebuildingBatchScanner extends DelegatingScannerBase implements BatchScanner {
private final TEARDOWN teardown;
private final INTERRUPT interrupt;
public RebuildingBatchScanner(InMemoryBatchScanner delegate, TEARDOWN teardown, INTERRUPT interrupt) {
super(delegate);
this.teardown = teardown;
this.interrupt = interrupt;
}
@Override
public Iterator<Map.Entry<Key,Value>> iterator() {
try {
return new RebuildingIterator((InMemoryScannerBase) delegate, ((InMemoryBatchScanner) delegate).clone(), teardown.instance(),
interrupt.instance());
} catch (Exception e) {
throw new RuntimeException("Misconfigured teardown listener class most likely", e);
}
}
@Override
public void setRanges(Collection<Range> ranges) {
((InMemoryBatchScanner) delegate).setRanges(ranges);
}
}
public static class RebuildingConnector extends Connector {
private final InMemoryConnector delegate;
private final TEARDOWN teardown;
private final INTERRUPT interrupt;
public RebuildingConnector(InMemoryConnector delegate, TEARDOWN teardown, INTERRUPT interrupt) {
this.delegate = delegate;
this.teardown = teardown;
this.interrupt = interrupt;
}
@Override
public BatchScanner createBatchScanner(String s, Authorizations authorizations, int i) throws TableNotFoundException {
return new RebuildingBatchScanner((InMemoryBatchScanner) (delegate.createBatchScanner(s, authorizations, i)), teardown, interrupt);
}
@Override
@Deprecated
public BatchDeleter createBatchDeleter(String s, Authorizations authorizations, int i, long l, long l1, int i1) throws TableNotFoundException {
return delegate.createBatchDeleter(s, authorizations, i, l, l1, i1);
}
@Override
public BatchDeleter createBatchDeleter(String s, Authorizations authorizations, int i, BatchWriterConfig batchWriterConfig)
throws TableNotFoundException {
return delegate.createBatchDeleter(s, authorizations, i, batchWriterConfig);
}
@Override
@Deprecated
public BatchWriter createBatchWriter(String s, long l, long l1, int i) throws TableNotFoundException {
return delegate.createBatchWriter(s, l, l1, i);
}
@Override
public BatchWriter createBatchWriter(String s, BatchWriterConfig batchWriterConfig) throws TableNotFoundException {
return delegate.createBatchWriter(s, batchWriterConfig);
}
@Override
@Deprecated
public MultiTableBatchWriter createMultiTableBatchWriter(long l, long l1, int i) {
return delegate.createMultiTableBatchWriter(l, l1, i);
}
@Override
public MultiTableBatchWriter createMultiTableBatchWriter(BatchWriterConfig batchWriterConfig) {
return delegate.createMultiTableBatchWriter(batchWriterConfig);
}
@Override
public Scanner createScanner(String s, Authorizations authorizations) throws TableNotFoundException {
return new RebuildingScanner((InMemoryScanner) (delegate.createScanner(s, authorizations)), teardown, interrupt);
}
@Override
public ConditionalWriter createConditionalWriter(String s, ConditionalWriterConfig conditionalWriterConfig) throws TableNotFoundException {
return delegate.createConditionalWriter(s, conditionalWriterConfig);
}
@Override
public Instance getInstance() {
return delegate.getInstance();
}
@Override
public String whoami() {
return delegate.whoami();
}
@Override
public TableOperations tableOperations() {
return delegate.tableOperations();
}
@Override
public NamespaceOperations namespaceOperations() {
return delegate.namespaceOperations();
}
@Override
public SecurityOperations securityOperations() {
return delegate.securityOperations();
}
@Override
public InstanceOperations instanceOperations() {
return delegate.instanceOperations();
}
@Override
public ReplicationOperations replicationOperations() {
return delegate.replicationOperations();
}
}
public static class DelegatingScannerBase implements ScannerBase {
protected final ScannerBase delegate;
public DelegatingScannerBase(ScannerBase delegate) {
this.delegate = delegate;
}
@Override
public void addScanIterator(IteratorSetting cfg) {
delegate.addScanIterator(cfg);
}
@Override
public void removeScanIterator(String iteratorName) {
delegate.removeScanIterator(iteratorName);
}
@Override
public void updateScanIteratorOption(String iteratorName, String key, String value) {
delegate.updateScanIteratorOption(iteratorName, key, value);
}
@Override
public void fetchColumnFamily(Text col) {
delegate.fetchColumnFamily(col);
}
@Override
public void fetchColumn(Text colFam, Text colQual) {
delegate.fetchColumn(colFam, colQual);
}
@Override
public void fetchColumn(IteratorSetting.Column column) {
delegate.fetchColumn(column);
}
@Override
public void clearColumns() {
delegate.clearColumns();
}
@Override
public void clearScanIterators() {
delegate.clearScanIterators();
}
@Override
public Iterator<Map.Entry<Key,Value>> iterator() {
return delegate.iterator();
}
@Override
public void setTimeout(long timeOut, TimeUnit timeUnit) {
delegate.setTimeout(timeOut, timeUnit);
}
@Override
public long getTimeout(TimeUnit timeUnit) {
return delegate.getTimeout(timeUnit);
}
@Override
public void close() {
delegate.close();
}
@Override
public Authorizations getAuthorizations() {
return delegate.getAuthorizations();
}
@Override
public void setSamplerConfiguration(SamplerConfiguration samplerConfig) {
delegate.setSamplerConfiguration(samplerConfig);
}
@Override
public SamplerConfiguration getSamplerConfiguration() {
return delegate.getSamplerConfiguration();
}
@Override
public void clearSamplerConfiguration() {
delegate.clearSamplerConfiguration();
}
@Override
public void setBatchTimeout(long timeOut, TimeUnit timeUnit) {
delegate.setBatchTimeout(timeOut, timeUnit);
}
@Override
public long getBatchTimeout(TimeUnit timeUnit) {
return delegate.getBatchTimeout(timeUnit);
}
@Override
public void setClassLoaderContext(String classLoaderContext) {
delegate.setClassLoaderContext(classLoaderContext);
}
@Override
public void clearClassLoaderContext() {
delegate.clearClassLoaderContext();
}
@Override
public String getClassLoaderContext() {
return delegate.getClassLoaderContext();
}
@Override
public void forEach(Consumer<? super Map.Entry<Key,Value>> action) {
delegate.forEach(action);
}
@Override
public Spliterator<Map.Entry<Key,Value>> spliterator() {
return delegate.spliterator();
}
}
}
| 14,151 |
2,151 | /*
* This file is part of Wireless Display Software for Linux OS
*
* Copyright (C) 2014 Intel Corporation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
#include <assert.h>
#include <iostream>
#include <string.h>
#include <netinet/in.h> // htons()
#include "connman-client.h"
#include "information-element.h"
int main (int argc, const char **argv)
{
// check that packing works
if (sizeof(P2P::DeviceInformationSubelement) !=
P2P::SubelementSize[P2P::DEVICE_INFORMATION] ||
sizeof(P2P::AssociatedBSSIDSubelement) !=
P2P::SubelementSize[P2P::ASSOCIATED_BSSID] ||
sizeof(P2P::CoupledSinkInformationSubelement) !=
P2P::SubelementSize[P2P::COUPLED_SINK_INFORMATION]) {
std::cout << "Subelement struct size checks failed"<< std::endl;
return 1;
}
P2P::InformationElement ie;
auto sub_element = P2P::new_subelement(P2P::DEVICE_INFORMATION);
auto dev_info = (P2P::DeviceInformationSubelement*)sub_element;
dev_info->session_management_control_port = htons(8080);
dev_info->maximum_throughput = htons(50);
dev_info->field1.device_type = P2P::PRIMARY_SINK;
dev_info->field1.session_availability = true;
ie.add_subelement (sub_element);
ie.add_subelement (P2P::new_subelement(P2P::COUPLED_SINK_INFORMATION));
ie.add_subelement (P2P::new_subelement(P2P::ASSOCIATED_BSSID));
auto array = ie.serialize ();
P2P::InformationElement ie2(array);
auto array1 = ie.to_string();
auto array2 = ie2.to_string();
if (array1 != array2) {
std::cout << "Expected byte array '" << array1
<< "', got '" << array2 << "'" << std::endl;
return 1;
}
return 0;
}
| 901 |
762 | #include "stdafx.hpp"
#include "Transform.hpp"
IGNORE_WARNINGS_PUSH
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/quaternion.hpp>
#include <glm/gtx/matrix_decompose.hpp>
#include <glm/mat4x4.hpp>
#include <glm/vec3.hpp>
#include "BulletDynamics/Dynamics/btRigidBody.h"
IGNORE_WARNINGS_POP
#include "Helpers.hpp"
#include "Physics/RigidBody.hpp"
#include "Scene/GameObject.hpp"
namespace flex
{
Transform Transform::m_Identity = Transform(VEC3_ZERO, QUAT_IDENTITY, VEC3_ONE);
Transform::Transform()
{
SetAsIdentity();
}
Transform::Transform(const glm::vec3& position, const glm::quat& rotation, const glm::vec3& scale) :
localPosition(position),
localRotation(rotation),
localScale(scale),
worldPosition(position),
worldRotation(rotation),
worldScale(scale),
localTransform(glm::translate(MAT4_IDENTITY, position) *
// Cast away constness
glm::mat4((glm::quat)rotation) *
glm::scale(MAT4_IDENTITY, scale)),
worldTransform(glm::translate(MAT4_IDENTITY, position) *
// Cast away constness
glm::mat4((glm::quat)rotation) *
glm::scale(MAT4_IDENTITY, scale)),
forward(VEC3_FORWARD),
up(VEC3_UP),
right(VEC3_RIGHT)
{
}
Transform::Transform(const glm::vec3& position, const glm::quat& rotation) :
localPosition(position),
localRotation(rotation),
localScale(VEC3_ONE),
worldPosition(position),
worldRotation(rotation),
worldScale(VEC3_ONE),
localTransform(glm::translate(MAT4_IDENTITY, position) *
glm::mat4((glm::quat)rotation) *
glm::scale(MAT4_IDENTITY, VEC3_ONE)),
worldTransform(glm::translate(MAT4_IDENTITY, position) *
glm::mat4((glm::quat)rotation) *
glm::scale(MAT4_IDENTITY, VEC3_ONE)),
forward(VEC3_FORWARD),
up(VEC3_UP),
right(VEC3_RIGHT)
{
}
Transform::Transform(const glm::vec3& position) :
localPosition(position),
localRotation(QUAT_IDENTITY),
localScale(VEC3_ONE),
worldPosition(position),
worldRotation(VEC3_ZERO),
worldScale(VEC3_ONE),
localTransform(glm::translate(MAT4_IDENTITY, position) *
glm::mat4(glm::quat(VEC3_ZERO)) *
glm::scale(MAT4_IDENTITY, VEC3_ONE)),
worldTransform(glm::translate(MAT4_IDENTITY, position) *
glm::mat4(glm::quat(VEC3_ZERO)) *
glm::scale(MAT4_IDENTITY, VEC3_ONE)),
forward(VEC3_FORWARD),
up(VEC3_UP),
right(VEC3_RIGHT)
{
}
Transform::Transform(const Transform& other) :
localPosition(other.localPosition),
localRotation(other.localRotation),
localScale(other.localScale),
worldPosition(other.localPosition),
worldRotation(other.localRotation),
worldScale(other.localScale),
forward(VEC3_FORWARD),
up(VEC3_UP),
right(VEC3_RIGHT),
localTransform(glm::translate(MAT4_IDENTITY, other.localPosition) *
glm::mat4((glm::quat)other.localRotation) *
glm::scale(MAT4_IDENTITY, other.localScale)),
worldTransform(glm::translate(MAT4_IDENTITY, other.worldPosition) *
glm::mat4((glm::quat)other.worldRotation) *
glm::scale(MAT4_IDENTITY, other.worldScale))
{
}
Transform::Transform(const Transform&& other) :
localPosition(other.localPosition),
localRotation(other.localRotation),
localScale(other.localScale),
worldPosition(other.worldPosition),
worldRotation(other.worldRotation),
worldScale(other.worldScale),
forward(VEC3_FORWARD),
up(VEC3_UP),
right(VEC3_RIGHT)
{
localTransform = (glm::translate(MAT4_IDENTITY, localPosition) *
glm::mat4(localRotation) *
glm::scale(MAT4_IDENTITY, localScale));
worldTransform = (glm::translate(MAT4_IDENTITY, worldPosition) *
glm::mat4(worldRotation) *
glm::scale(MAT4_IDENTITY, worldScale));
}
Transform& Transform::operator=(const Transform& other)
{
localPosition = other.localPosition;
localRotation = other.localRotation;
localScale = other.localScale;
worldPosition = other.worldPosition;
worldRotation = other.worldRotation;
worldScale = other.worldScale;
localTransform = glm::mat4(glm::translate(MAT4_IDENTITY, localPosition) *
glm::mat4(localRotation) *
glm::scale(MAT4_IDENTITY, localScale));
worldTransform = glm::mat4(glm::translate(MAT4_IDENTITY, worldPosition) *
glm::mat4(worldRotation) *
glm::scale(MAT4_IDENTITY, worldScale));
forward = other.forward;
up = other.up;
right = other.right;
return *this;
}
Transform& Transform::operator=(const Transform&& other)
{
if (this != &other)
{
localPosition = other.localPosition;
localRotation = other.localRotation;
localScale = other.localScale;
worldPosition = other.worldPosition;
worldRotation = other.worldRotation;
worldScale = other.worldScale;
localTransform = glm::mat4(glm::translate(MAT4_IDENTITY, localPosition) *
glm::mat4(localRotation) *
glm::scale(MAT4_IDENTITY, localScale));
worldTransform = glm::mat4(glm::translate(MAT4_IDENTITY, worldPosition) *
glm::mat4(worldRotation) *
glm::scale(MAT4_IDENTITY, worldScale));
forward = other.forward;
up = other.up;
right = other.right;
}
return *this;
}
Transform::~Transform()
{
}
Transform Transform::ParseJSON(const JSONObject& transformObject)
{
glm::vec3 pos;
glm::quat rot;
glm::vec3 scale;
ParseJSON(transformObject, pos, rot, scale);
return Transform(pos, rot, scale);
}
void Transform::ParseJSON(const JSONObject& object, glm::mat4& outModel)
{
const JSONObject& transformObject = object.GetObject("transform");
glm::vec3 pos;
glm::quat rot;
glm::vec3 scale;
ParseJSON(transformObject, pos, rot, scale);
outModel = glm::translate(MAT4_IDENTITY, pos) *
glm::mat4(rot) *
glm::scale(MAT4_IDENTITY, scale);
}
void Transform::ParseJSON(const JSONObject& object, glm::vec3& outPos, glm::quat& outRot, glm::vec3& outScale)
{
std::string posStr = object.GetString("pos");
std::string rotStr = object.GetString("rot");
std::string scaleStr = object.GetString("scale");
outPos = glm::vec3(0.0f);
if (!posStr.empty())
{
outPos = ParseVec3(posStr);
}
glm::vec3 rotEuler(0.0f);
if (!rotStr.empty())
{
rotEuler = ParseVec3(rotStr);
}
outScale = glm::vec3(1.0f);
if (!scaleStr.empty())
{
outScale = ParseVec3(scaleStr);
}
// Check we aren't getting garbage data in
#if DEBUG
if (IsNanOrInf(outPos))
{
PrintError("Read garbage value from transform pos in serialized scene file! Using default value instead\n");
outPos = VEC3_ZERO;
}
if (IsNanOrInf(rotEuler))
{
PrintError("Read garbage value from transform rot in serialized scene file! Using default value instead\n");
rotEuler = VEC3_ZERO;
}
if (IsNanOrInf(outScale))
{
PrintError("Read garbage value from transform scale in serialized scene file! Using default value instead\n");
outScale = VEC3_ONE;
}
#endif
outRot = glm::quat(rotEuler);
}
JSONField Transform::Serialize() const
{
return Serialize(localPosition, localRotation, localScale, m_GameObject->GetName().c_str());
}
JSONField Transform::Serialize(const glm::mat4 matrix, const char* objName)
{
glm::vec3 pos;
glm::quat rot;
glm::vec3 scale;
glm::vec3 skew;
glm::vec4 persp;
glm::decompose(matrix, scale, rot, pos, skew, persp);
return Serialize(pos, rot, scale, objName);
}
JSONField Transform::Serialize(const glm::vec3& inPos, const glm::quat& inRot, const glm::vec3& inScale, const char* objName)
{
const i32 floatPrecision = 3;
glm::vec3 pos = inPos;
glm::quat rot = inRot;
glm::vec3 scale = inScale;
JSONField transformField = {};
transformField.label = "transform";
JSONObject transformObject = {};
if (IsNanOrInf(pos))
{
PrintError("Attempted to serialize garbage value for position of %s, writing default value\n", objName);
pos = VEC3_ZERO;
}
if (IsNanOrInf(rot))
{
PrintError("Attempted to serialize garbage value for rotation of %s, writing default value\n", objName);
rot = glm::quat();
}
if (IsNanOrInf(scale))
{
PrintError("Attempted to serialize garbage value for scale of %s, writing default value\n", objName);
scale = VEC3_ONE;
}
if (pos != VEC3_ZERO)
{
std::string posStr = VecToString(pos, floatPrecision);
transformObject.fields.emplace_back("pos", JSONValue(posStr));
}
if (rot != QUAT_IDENTITY)
{
glm::vec3 rotEuler = glm::eulerAngles(rot);
std::string rotStr = VecToString(rotEuler, floatPrecision);
transformObject.fields.emplace_back("rot", JSONValue(rotStr));
}
if (scale != VEC3_ONE)
{
std::string scaleStr = VecToString(scale, floatPrecision);
transformObject.fields.emplace_back("scale", JSONValue(scaleStr));
}
transformField.value = JSONValue(transformObject);
return transformField;
}
void Transform::Translate(const glm::vec3& deltaPosition)
{
localPosition += deltaPosition;
UpdateParentTransform();
}
void Transform::Translate(real deltaX, real deltaY, real deltaZ)
{
localPosition.x += deltaX;
localPosition.y += deltaY;
localPosition.z += deltaZ;
UpdateParentTransform();
}
void Transform::Rotate(const glm::quat& deltaQuatRotation)
{
localRotation *= deltaQuatRotation;
UpdateParentTransform();
}
void Transform::Scale(const glm::vec3& deltaScale)
{
localScale *= deltaScale;
UpdateParentTransform();
}
void Transform::Scale(real deltaScale)
{
Scale(glm::vec3(deltaScale));
}
void Transform::Scale(real deltaX, real deltaY, real deltaZ)
{
Scale(glm::vec3(deltaX, deltaY, deltaZ));
}
void Transform::SetWorldTransform(const glm::mat4& desiredWorldTransform)
{
if (m_GameObject->GetParent() != nullptr)
{
localTransform = glm::inverse(m_GameObject->GetParent()->GetTransform()->GetWorldTransform()) * desiredWorldTransform;
}
else
{
localTransform = desiredWorldTransform;
}
glm::vec3 localSkew;
glm::vec4 localPerspective;
glm::decompose(localTransform, localScale, localRotation, localPosition, localSkew, localPerspective);
UpdateParentTransform();
}
void Transform::SetAsIdentity()
{
*this = m_Identity;
}
bool Transform::IsIdentity() const
{
bool result = (localPosition == m_Identity.localPosition &&
localRotation == m_Identity.localRotation &&
localScale == m_Identity.localScale);
return result;
}
Transform Transform::Identity()
{
Transform result;
result.SetAsIdentity();
return result;
}
void Transform::SetGameObject(GameObject* gameObject)
{
m_GameObject = gameObject;
}
GameObject* Transform::GetGameObject() const
{
return m_GameObject;
}
const glm::mat4& Transform::GetWorldTransform() const
{
return worldTransform;
}
const glm::mat4& Transform::GetLocalTransform() const
{
return localTransform;
}
void Transform::UpdateParentTransform()
{
localTransform = (glm::translate(MAT4_IDENTITY, localPosition) *
glm::mat4(localRotation) *
glm::scale(MAT4_IDENTITY, localScale));
GameObject* parent = m_GameObject->GetParent();
if (parent == nullptr)
{
worldPosition = localPosition;
worldRotation = localRotation;
worldScale = localScale;
}
if (parent != nullptr)
{
parent->GetTransform()->UpdateParentTransform();
}
else
{
UpdateChildTransforms();
}
glm::mat3 rotMat(worldRotation);
right = rotMat[0];
up = rotMat[1];
forward = rotMat[2];
if (updateParentOnStateChange && m_GameObject != nullptr)
{
m_GameObject->OnTransformChanged();
}
}
void Transform::UpdateChildTransforms()
{
// Our local matrix should already have been updated at this point (in UpdateParentTransform)
GameObject* parent = m_GameObject->GetParent();
if (parent != nullptr)
{
Transform* parentTransform = parent->GetTransform();
worldTransform = parentTransform->GetWorldTransform() * localTransform;
glm::vec3 worldSkew;
glm::vec4 worldPerspective;
glm::decompose(worldTransform, worldScale, worldRotation, worldPosition, worldSkew, worldPerspective);
}
else
{
worldTransform = localTransform;
worldPosition = localPosition;
worldRotation = localRotation;
worldScale = localScale;
}
RigidBody* rigidBody= m_GameObject->GetRigidBody();
if (rigidBody != nullptr)
{
rigidBody->MatchParentTransform();
}
const std::vector<GameObject*>& children = m_GameObject->GetChildren();
for (GameObject* child : children)
{
child->GetTransform()->UpdateChildTransforms();
}
}
glm::vec3 Transform::GetLocalPosition() const
{
return localPosition;
}
glm::vec3 Transform::GetWorldPosition() const
{
return worldPosition;
}
glm::quat Transform::GetLocalRotation() const
{
return localRotation;
}
glm::quat Transform::GetWorldRotation() const
{
return worldRotation;
}
glm::vec3 Transform::GetLocalScale() const
{
return localScale;
}
glm::vec3 Transform::GetWorldScale() const
{
return worldScale;
}
glm::vec3 Transform::GetRight() const
{
return right;
}
glm::vec3 Transform::GetUp() const
{
return up;
}
glm::vec3 Transform::GetForward() const
{
return forward;
}
void Transform::SetLocalPosition(const glm::vec3& position, bool bUpdateChain /* = true */)
{
localPosition = position;
if (bUpdateChain)
{
UpdateParentTransform();
}
}
void Transform::SetWorldPosition(const glm::vec3& position, bool bUpdateChain /* = true */)
{
GameObject* parent = m_GameObject->GetParent();
if (parent != nullptr)
{
localPosition = position - parent->GetTransform()->GetWorldPosition();
}
else
{
localPosition = position;
// NOTE: World position will be set in UpdateParentTransform
}
if (bUpdateChain)
{
UpdateParentTransform();
}
}
void Transform::SetLocalRotation(const glm::quat& quatRotation, bool bUpdateChain /* = true */)
{
localRotation = quatRotation;
if (bUpdateChain)
{
UpdateParentTransform();
}
}
void Transform::SetWorldRotation(const glm::quat& quatRotation, bool bUpdateChain /* = true */)
{
GameObject* parent = m_GameObject->GetParent();
if (parent != nullptr)
{
localRotation = glm::inverse(parent->GetTransform()->GetWorldRotation()) * quatRotation;
}
else
{
localRotation = quatRotation;
// World rotation will be set in UpdateParentTransform
}
if (bUpdateChain)
{
UpdateParentTransform();
}
}
void Transform::SetLocalScale(const glm::vec3& scale, bool bUpdateChain /* = true */)
{
localScale = scale;
if (bUpdateChain)
{
UpdateParentTransform();
}
}
void Transform::SetWorldScale(const glm::vec3& scale, bool bUpdateChain /* = true */)
{
GameObject* parent = m_GameObject->GetParent();
if (parent != nullptr)
{
localScale = scale / parent->GetTransform()->GetWorldScale();
}
else
{
localScale = scale;
// World scale will be set in UpdateParentTransform
}
if (bUpdateChain)
{
UpdateParentTransform();
}
}
void Transform::SetWorldFromMatrix(const glm::mat4& mat, bool bUpdateChain /* = true */)
{
glm::vec3 pos;
glm::quat rot;
glm::vec3 scale;
glm::vec3 skew;
glm::vec4 perspective;
if (glm::decompose(mat, scale, rot, pos, skew, perspective))
{
SetWorldPosition(pos, false);
SetWorldRotation(rot, false);
SetWorldScale(scale, bUpdateChain);
if (!bUpdateChain)
{
glm::mat3 rotMat(worldRotation);
right = rotMat[0];
up = rotMat[1];
forward = rotMat[2];
}
}
}
} // namespace flex
| 5,900 |
7,113 | /*
* Copyright (C) 2010-2101 Alibaba Group Holding Limited.
*
* 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.alibaba.otter.manager.biz.config.alarm.dal.ibatis;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;
import com.alibaba.otter.shared.common.utils.Assert;
import com.alibaba.otter.manager.biz.config.alarm.dal.AlarmRuleDAO;
import com.alibaba.otter.manager.biz.config.alarm.dal.dataobject.AlarmRuleDO;
import com.alibaba.otter.shared.common.model.config.alarm.AlarmRuleStatus;
/**
* @author simon
*/
public class IbatisAlarmRuleDAO extends SqlMapClientDaoSupport implements AlarmRuleDAO {
public AlarmRuleDO insert(AlarmRuleDO entityObj) {
Assert.assertNotNull(entityObj);
getSqlMapClientTemplate().insert("insertAlarmRule", entityObj);
return entityObj;
}
public void update(AlarmRuleDO entityObj) {
Assert.assertNotNull(entityObj);
getSqlMapClientTemplate().update("updateAlarmRule", entityObj);
}
public void delete(Long id) {
Assert.assertNotNull(id);
getSqlMapClientTemplate().update("deleteAlarmRuleById", id);
}
public AlarmRuleDO findById(Long alarmRuleId) {
Assert.assertNotNull(alarmRuleId);
AlarmRuleDO alarmRuleDo = (AlarmRuleDO) getSqlMapClientTemplate().queryForObject("findByRuleId", alarmRuleId);
return alarmRuleDo;
}
public List<AlarmRuleDO> listByPipelineId(Long pipelineId) {
Assert.assertNotNull(pipelineId);
List<AlarmRuleDO> alarmRuleDos = getSqlMapClientTemplate().queryForList("listAlarmByPipelineId", pipelineId);
return alarmRuleDos;
}
public List<AlarmRuleDO> listByPipelineId(Long pipelineId, AlarmRuleStatus status) {
List<AlarmRuleDO> alarmRuleDos = listByPipelineId(pipelineId);
List<AlarmRuleDO> result = new ArrayList<AlarmRuleDO>();
for (AlarmRuleDO alarmRuleDo : alarmRuleDos) {
if (alarmRuleDo.getStatus().equals(status)) {
result.add(alarmRuleDo);
}
}
return result;
}
public List<AlarmRuleDO> listAll() {
List<AlarmRuleDO> alarmRuleDos = getSqlMapClientTemplate().queryForList("listAllAlarmRule");
return alarmRuleDos;
}
public List<AlarmRuleDO> listAllByPipeline(Map condition) {
List<AlarmRuleDO> alarmRuleDos = getSqlMapClientTemplate().queryForList("listAllAlarmOrderByPipeline",
condition);
return alarmRuleDos;
}
public List<AlarmRuleDO> listByStatus(AlarmRuleStatus status) {
List<AlarmRuleDO> alarmRuleDos = getSqlMapClientTemplate().queryForList("listAlarmByStatus", status);
return alarmRuleDos;
}
public int getCount() {
Integer count = (Integer) getSqlMapClientTemplate().queryForObject("getAlarmRuleCount");
return count.intValue();
}
}
| 1,365 |
2,554 | #define _DEFAULT_SOURCE
#include <string.h>
#include "greatest/greatest.h"
#include "theft/theft.h"
#include "match.h"
static void *string_alloc_cb(struct theft *t, theft_hash seed, void *env) {
(void)env;
int limit = 128;
size_t sz = (size_t)(seed % limit) + 1;
char *str = malloc(sz + 1);
if (str == NULL) {
return THEFT_ERROR;
}
for (size_t i = 0; i < sz; i += sizeof(theft_hash)) {
theft_hash s = theft_random(t);
for (uint8_t b = 0; b < sizeof(theft_hash); b++) {
if (i + b >= sz) {
break;
}
str[i + b] = (uint8_t)(s >> (8 * b)) & 0xff;
}
}
str[sz] = 0;
return str;
}
static void string_free_cb(void *instance, void *env) {
free(instance);
(void)env;
}
static void string_print_cb(FILE *f, void *instance, void *env) {
char *str = (char *)instance;
(void)env;
size_t size = strlen(str);
fprintf(f, "str[%zd]:\n ", size);
uint8_t bytes = 0;
for (size_t i = 0; i < size; i++) {
fprintf(f, "%02x", str[i]);
bytes++;
if (bytes == 16) {
fprintf(f, "\n ");
bytes = 0;
}
}
fprintf(f, "\n");
}
static uint64_t string_hash_cb(void *instance, void *env) {
(void)env;
char *str = (char *)instance;
int size = strlen(str);
return theft_hash_onepass((uint8_t *)str, size);
}
static void *string_shrink_cb(void *instance, uint32_t tactic, void *env) {
(void)env;
char *str = (char *)instance;
int n = strlen(str);
if (tactic == 0) { /* first half */
return strndup(str, n / 2);
} else if (tactic == 1) { /* second half */
return strndup(str + (n / 2), n / 2);
} else {
return THEFT_NO_MORE_TACTICS;
}
}
static struct theft_type_info string_info = {
.alloc = string_alloc_cb,
.free = string_free_cb,
.print = string_print_cb,
.hash = string_hash_cb,
.shrink = string_shrink_cb,
};
static theft_trial_res prop_should_return_results_if_there_is_a_match(char *needle,
char *haystack) {
int match_exists = has_match(needle, haystack);
if (!match_exists)
return THEFT_TRIAL_SKIP;
score_t score = match(needle, haystack);
if (needle[0] == '\0')
return THEFT_TRIAL_SKIP;
if (score == SCORE_MIN)
return THEFT_TRIAL_FAIL;
return THEFT_TRIAL_PASS;
}
TEST should_return_results_if_there_is_a_match() {
struct theft *t = theft_init(0);
struct theft_cfg cfg = {
.name = __func__,
.fun = prop_should_return_results_if_there_is_a_match,
.type_info = {&string_info, &string_info},
.trials = 100000,
};
theft_run_res res = theft_run(t, &cfg);
theft_free(t);
GREATEST_ASSERT_EQm("should_return_results_if_there_is_a_match", THEFT_RUN_PASS, res);
PASS();
}
static theft_trial_res prop_positions_should_match_characters_in_string(char *needle,
char *haystack) {
int match_exists = has_match(needle, haystack);
if (!match_exists)
return THEFT_TRIAL_SKIP;
int n = strlen(needle);
size_t *positions = calloc(n, sizeof(size_t));
if (!positions)
return THEFT_TRIAL_ERROR;
match_positions(needle, haystack, positions);
/* Must be increasing */
for (int i = 1; i < n; i++) {
if (positions[i] <= positions[i - 1]) {
return THEFT_TRIAL_FAIL;
}
}
/* Matching characters must be in returned positions */
for (int i = 0; i < n; i++) {
if (toupper(needle[i]) != toupper(haystack[positions[i]])) {
return THEFT_TRIAL_FAIL;
}
}
free(positions);
return THEFT_TRIAL_PASS;
}
TEST positions_should_match_characters_in_string() {
struct theft *t = theft_init(0);
struct theft_cfg cfg = {
.name = __func__,
.fun = prop_positions_should_match_characters_in_string,
.type_info = {&string_info, &string_info},
.trials = 100000,
};
theft_run_res res = theft_run(t, &cfg);
theft_free(t);
GREATEST_ASSERT_EQm("should_return_results_if_there_is_a_match", THEFT_RUN_PASS, res);
PASS();
}
SUITE(properties_suite) {
RUN_TEST(should_return_results_if_there_is_a_match);
RUN_TEST(positions_should_match_characters_in_string);
}
| 1,715 |
1,056 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.spi.java.project.support.ui;
import java.io.File;
import javax.swing.JPanel;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import org.netbeans.api.queries.CollocationQuery;
import static org.netbeans.spi.java.project.support.ui.Bundle.*;
import org.netbeans.spi.project.support.ant.AntProjectHelper;
import org.netbeans.spi.project.support.ant.PropertyUtils;
import org.openide.WizardDescriptor;
import org.openide.filesystems.FileUtil;
import org.openide.util.ChangeSupport;
import org.openide.util.NbBundle.Messages;
final class MakeSharableVisualPanel1 extends JPanel {
private AntProjectHelper helper;
private ChangeSupport support;
private WizardDescriptor settings;
private DocumentListener docListener;
/** Creates new form MakeSharableVisualPanel1 */
public MakeSharableVisualPanel1(ChangeSupport supp) {
initComponents();
this.support = supp;
docListener = new DocumentListener() {
public void insertUpdate(DocumentEvent e) {
support.fireChange();
}
public void removeUpdate(DocumentEvent e) {
support.fireChange();
}
public void changedUpdate(DocumentEvent e) {
support.fireChange();
}
};
txtDefinition.getDocument().addDocumentListener(docListener);
}
@Messages("TIT_LibraryDefinitionSelection=Library Folder")
@Override
public String getName() {
return TIT_LibraryDefinitionSelection();
}
@Messages({
"WARN_MakeSharable.absolutePath=<html>Please make sure that the absolute path in the Libraries Folder field is valid for all users.<html>",
"WARN_makeSharable.relativePath=<html>Please make sure that the relative path in the Libraries Folder field is valid for all users.<html>"
})
boolean isValidPanel() {
String location = getLibraryLocation();
boolean wrong = false;
if (new File(location).isAbsolute()) {
settings.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE, WARN_MakeSharable_absolutePath());
wrong = true;
} else {
File projectLoc = FileUtil.toFile(helper.getProjectDirectory());
File libLoc = PropertyUtils.resolveFile(projectLoc, location);
if (!CollocationQuery.areCollocated(projectLoc, libLoc)) {
settings.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE, WARN_makeSharable_relativePath());
wrong = true;
}
}
if (!wrong) {
settings.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE, null);
}
return true;
}
private String getLibraryLocation() {
return txtDefinition.getText().trim();
}
private void setLibraryLocation(String loc) {
txtDefinition.setText(loc);
}
void readSettings(WizardDescriptor wiz) {
settings = wiz;
String loc = (String) wiz.getProperty(SharableLibrariesUtils.PROP_LOCATION);
helper = (AntProjectHelper) wiz.getProperty(SharableLibrariesUtils.PROP_HELPER);
if (loc == null) {
loc = "." + File.separator + "lib"; //NOI18N
} else {
loc = loc.substring(0, loc.length() - SharableLibrariesUtils.DEFAULT_LIBRARIES_FILENAME.length());
}
setLibraryLocation(loc);
support.fireChange();
}
void storeSettings(WizardDescriptor wiz) {
String librariesDefinition = getLibraryLocation();
if (librariesDefinition != null) {
if (librariesDefinition.length() != 0 && !librariesDefinition.endsWith(File.separator)) {
librariesDefinition += File.separatorChar;
}
librariesDefinition += SharableLibrariesUtils.DEFAULT_LIBRARIES_FILENAME;
}
wiz.putProperty(SharableLibrariesUtils.PROP_LOCATION, librariesDefinition);
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
lblDefinition = new javax.swing.JLabel();
txtDefinition = new javax.swing.JTextField();
btnDefinition = new javax.swing.JButton();
lblNote = new javax.swing.JLabel();
lblDefinition.setLabelFor(txtDefinition);
org.openide.awt.Mnemonics.setLocalizedText(lblDefinition, org.openide.util.NbBundle.getMessage(MakeSharableVisualPanel1.class, "MakeSharableVisualPanel1.lblDefinition.text")); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(btnDefinition, org.openide.util.NbBundle.getMessage(MakeSharableVisualPanel1.class, "MakeSharableVisualPanel1.btnDefinition.text")); // NOI18N
btnDefinition.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnDefinitionActionPerformed(evt);
}
});
org.openide.awt.Mnemonics.setLocalizedText(lblNote, org.openide.util.NbBundle.getMessage(MakeSharableVisualPanel1.class, "MakeSharableVisualPanel1.lblNote.text")); // NOI18N
lblNote.setVerticalAlignment(javax.swing.SwingConstants.TOP);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(lblDefinition)
.addGap(10, 10, 10)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lblNote, javax.swing.GroupLayout.DEFAULT_SIZE, 365, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(txtDefinition, javax.swing.GroupLayout.DEFAULT_SIZE, 257, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnDefinition))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnDefinition)
.addComponent(lblDefinition)
.addComponent(txtDefinition, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lblNote, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(116, Short.MAX_VALUE))
);
lblDefinition.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getMessage(MakeSharableVisualPanel1.class, "ACSD_lblDefinition")); // NOI18N
txtDefinition.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getMessage(MakeSharableVisualPanel1.class, "ACSD_lblDefinition")); // NOI18N
btnDefinition.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getMessage(MakeSharableVisualPanel1.class, "ACSD_btnDefinition")); // NOI18N
}// </editor-fold>//GEN-END:initComponents
private void btnDefinitionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDefinitionActionPerformed
File f = FileUtil.toFile(helper.getProjectDirectory()); // NOI18N
String curr = SharableLibrariesUtils.browseForLibraryLocation(getLibraryLocation(), this, f);
if (curr != null) {
setLibraryLocation(curr);
}
}//GEN-LAST:event_btnDefinitionActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnDefinition;
private javax.swing.JLabel lblDefinition;
private javax.swing.JLabel lblNote;
private javax.swing.JTextField txtDefinition;
// End of variables declaration//GEN-END:variables
}
| 3,653 |
5,169 | <reponame>Gantios/Specs
{
"name": "PlanetaryMaps",
"version": "1.0.1",
"summary": "iOS OpenGL Tiled Maps Viewer",
"description": "An iOS library that allows the developer to easily add a Google Earth style zoomable mapping view. It supports arbitrary zooming and panning and a clean API to draw lines and markers on the planet surface. You will need to provide URLs for map tiles that are in geodetic projection. Several Python and Bash scripts are provided that can be used to convert GeoTIFF and GeoPDF files to geodetic tiles that can be used with PlanetaryMaps.",
"homepage": "https://github.com/spietari/PlanetaryMaps",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"<NAME>": "<EMAIL>"
},
"source": {
"git": "https://github.com/spietari/PlanetaryMaps.git",
"tag": "1.0.1"
},
"social_media_url": "https://twitter.com/pietarinenseppo",
"platforms": {
"ios": "8.0"
},
"source_files": "PlanetaryMaps/Classes/**/*",
"resource_bundles": {
"PlanetaryMaps": [
"PlanetaryMaps/Assets/**/*"
]
},
"frameworks": "GLKit"
}
| 384 |
892 | <gh_stars>100-1000
{
"schema_version": "1.2.0",
"id": "GHSA-wpgj-52pg-3797",
"modified": "2022-04-29T01:28:18Z",
"published": "2022-04-29T01:28:17Z",
"aliases": [
"CVE-2003-1568"
],
"details": "GoAhead WebServer before 2.1.6 allows remote attackers to cause a denial of service (NULL pointer dereference and daemon crash) via an invalid URL, related to the websSafeUrl function.",
"severity": [
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2003-1568"
},
{
"type": "WEB",
"url": "http://data.goahead.com/Software/Webserver/2.1.8/release.htm#null-pointer-crash-in-webssafeurl"
}
],
"database_specific": {
"cwe_ids": [
"CWE-20"
],
"severity": "MODERATE",
"github_reviewed": false
}
} | 376 |
2,380 | /**
*
* Copyright 2003-2007 Jive Software.
*
* 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.jivesoftware.smackx.search;
import java.util.List;
import org.jivesoftware.smack.SmackException.NoResponseException;
import org.jivesoftware.smack.SmackException.NotConnectedException;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException.XMPPErrorException;
import org.jivesoftware.smackx.disco.ServiceDiscoveryManager;
import org.jivesoftware.smackx.xdata.form.FillableForm;
import org.jivesoftware.smackx.xdata.form.Form;
import org.jivesoftware.smackx.xdata.packet.DataForm;
import org.jxmpp.jid.DomainBareJid;
/**
* The UserSearchManager is a facade built upon Jabber Search Services (XEP-055) to allow for searching
* repositories on a Jabber Server. This implementation allows for transparency of implementation of
* searching (DataForms or No DataForms), but allows the user to simply use the DataForm model for both
* types of support.
* <pre>
* XMPPConnection con = new XMPPTCPConnection("jabber.org");
* con.login("john", "doe");
* UserSearchManager search = new UserSearchManager(con, "users.jabber.org");
* Form searchForm = search.getSearchForm();
* FillableForm answerForm = searchForm.getFillableForm()
* // Fill out the form.
* answerForm.setAnswer("last", "DeMoro");
* ReportedData data = search.getSearchResults(answerForm);
* // Use Returned Data
* </pre>
*
* @author <NAME>
*/
public class UserSearchManager {
private final XMPPConnection con;
private final UserSearch userSearch;
/**
* Creates a new UserSearchManager.
*
* @param con the XMPPConnection to use.
*/
public UserSearchManager(XMPPConnection con) {
this.con = con;
userSearch = new UserSearch();
}
/**
* Returns the form to fill out to perform a search.
*
* @param searchService the search service to query.
* @return the form to fill out to perform a search.
* @throws XMPPErrorException if there was an XMPP error returned.
* @throws NoResponseException if there was no response from the remote entity.
* @throws NotConnectedException if the XMPP connection is not connected.
* @throws InterruptedException if the calling thread was interrupted.
*/
public Form getSearchForm(DomainBareJid searchService) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
DataForm dataForm = userSearch.getSearchForm(con, searchService);
return new Form(dataForm);
}
/**
* Submits a search form to the server and returns the resulting information
* in the form of <code>ReportedData</code>.
*
* @param searchForm the <code>Form</code> to submit for searching.
* @param searchService the name of the search service to use.
* @return the ReportedData returned by the server.
* @throws XMPPErrorException if there was an XMPP error returned.
* @throws NoResponseException if there was no response from the remote entity.
* @throws NotConnectedException if the XMPP connection is not connected.
* @throws InterruptedException if the calling thread was interrupted.
*/
public ReportedData getSearchResults(FillableForm searchForm, DomainBareJid searchService)
throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
DataForm dataForm = searchForm.getDataFormToSubmit();
return userSearch.sendSearchForm(con, dataForm, searchService);
}
/**
* Returns a collection of search services found on the server.
*
* @return a Collection of search services found on the server.
* @throws XMPPErrorException if there was an XMPP error returned.
* @throws NoResponseException if there was no response from the remote entity.
* @throws NotConnectedException if the XMPP connection is not connected.
* @throws InterruptedException if the calling thread was interrupted.
*/
public List<DomainBareJid> getSearchServices() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
ServiceDiscoveryManager discoManager = ServiceDiscoveryManager.getInstanceFor(con);
return discoManager.findServices(UserSearch.NAMESPACE, false, false);
}
}
| 1,521 |
4,345 | <reponame>awesome-archive/Coding-iOS
//
// CSTopicModel.h
// Coding_iOS
//
// Created by <NAME> on 15/7/15.
// Copyright (c) 2015年 Coding. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface CSTopicModel : NSObject
+ (NSArray*)latestUseTopiclist;
+ (void)addAnotherUseTopic:(NSString*)topicName;
@end
| 123 |
1,350 | <gh_stars>1000+
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.sqlvirtualmachine.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
/** Active Directory account details to operate Windows Server Failover Cluster. */
@Fluent
public final class WsfcDomainProfile {
@JsonIgnore private final ClientLogger logger = new ClientLogger(WsfcDomainProfile.class);
/*
* Fully qualified name of the domain.
*/
@JsonProperty(value = "domainFqdn")
private String domainFqdn;
/*
* Organizational Unit path in which the nodes and cluster will be present.
*/
@JsonProperty(value = "ouPath")
private String ouPath;
/*
* Account name used for creating cluster (at minimum needs permissions to
* 'Create Computer Objects' in domain).
*/
@JsonProperty(value = "clusterBootstrapAccount")
private String clusterBootstrapAccount;
/*
* Account name used for operating cluster i.e. will be part of
* administrators group on all the participating virtual machines in the
* cluster.
*/
@JsonProperty(value = "clusterOperatorAccount")
private String clusterOperatorAccount;
/*
* Account name under which SQL service will run on all participating SQL
* virtual machines in the cluster.
*/
@JsonProperty(value = "sqlServiceAccount")
private String sqlServiceAccount;
/*
* Optional path for fileshare witness.
*/
@JsonProperty(value = "fileShareWitnessPath")
private String fileShareWitnessPath;
/*
* Fully qualified ARM resource id of the witness storage account.
*/
@JsonProperty(value = "storageAccountUrl")
private String storageAccountUrl;
/*
* Primary key of the witness storage account.
*/
@JsonProperty(value = "storageAccountPrimaryKey")
private String storageAccountPrimaryKey;
/**
* Get the domainFqdn property: Fully qualified name of the domain.
*
* @return the domainFqdn value.
*/
public String domainFqdn() {
return this.domainFqdn;
}
/**
* Set the domainFqdn property: Fully qualified name of the domain.
*
* @param domainFqdn the domainFqdn value to set.
* @return the WsfcDomainProfile object itself.
*/
public WsfcDomainProfile withDomainFqdn(String domainFqdn) {
this.domainFqdn = domainFqdn;
return this;
}
/**
* Get the ouPath property: Organizational Unit path in which the nodes and cluster will be present.
*
* @return the ouPath value.
*/
public String ouPath() {
return this.ouPath;
}
/**
* Set the ouPath property: Organizational Unit path in which the nodes and cluster will be present.
*
* @param ouPath the ouPath value to set.
* @return the WsfcDomainProfile object itself.
*/
public WsfcDomainProfile withOuPath(String ouPath) {
this.ouPath = ouPath;
return this;
}
/**
* Get the clusterBootstrapAccount property: Account name used for creating cluster (at minimum needs permissions to
* 'Create Computer Objects' in domain).
*
* @return the clusterBootstrapAccount value.
*/
public String clusterBootstrapAccount() {
return this.clusterBootstrapAccount;
}
/**
* Set the clusterBootstrapAccount property: Account name used for creating cluster (at minimum needs permissions to
* 'Create Computer Objects' in domain).
*
* @param clusterBootstrapAccount the clusterBootstrapAccount value to set.
* @return the WsfcDomainProfile object itself.
*/
public WsfcDomainProfile withClusterBootstrapAccount(String clusterBootstrapAccount) {
this.clusterBootstrapAccount = clusterBootstrapAccount;
return this;
}
/**
* Get the clusterOperatorAccount property: Account name used for operating cluster i.e. will be part of
* administrators group on all the participating virtual machines in the cluster.
*
* @return the clusterOperatorAccount value.
*/
public String clusterOperatorAccount() {
return this.clusterOperatorAccount;
}
/**
* Set the clusterOperatorAccount property: Account name used for operating cluster i.e. will be part of
* administrators group on all the participating virtual machines in the cluster.
*
* @param clusterOperatorAccount the clusterOperatorAccount value to set.
* @return the WsfcDomainProfile object itself.
*/
public WsfcDomainProfile withClusterOperatorAccount(String clusterOperatorAccount) {
this.clusterOperatorAccount = clusterOperatorAccount;
return this;
}
/**
* Get the sqlServiceAccount property: Account name under which SQL service will run on all participating SQL
* virtual machines in the cluster.
*
* @return the sqlServiceAccount value.
*/
public String sqlServiceAccount() {
return this.sqlServiceAccount;
}
/**
* Set the sqlServiceAccount property: Account name under which SQL service will run on all participating SQL
* virtual machines in the cluster.
*
* @param sqlServiceAccount the sqlServiceAccount value to set.
* @return the WsfcDomainProfile object itself.
*/
public WsfcDomainProfile withSqlServiceAccount(String sqlServiceAccount) {
this.sqlServiceAccount = sqlServiceAccount;
return this;
}
/**
* Get the fileShareWitnessPath property: Optional path for fileshare witness.
*
* @return the fileShareWitnessPath value.
*/
public String fileShareWitnessPath() {
return this.fileShareWitnessPath;
}
/**
* Set the fileShareWitnessPath property: Optional path for fileshare witness.
*
* @param fileShareWitnessPath the fileShareWitnessPath value to set.
* @return the WsfcDomainProfile object itself.
*/
public WsfcDomainProfile withFileShareWitnessPath(String fileShareWitnessPath) {
this.fileShareWitnessPath = fileShareWitnessPath;
return this;
}
/**
* Get the storageAccountUrl property: Fully qualified ARM resource id of the witness storage account.
*
* @return the storageAccountUrl value.
*/
public String storageAccountUrl() {
return this.storageAccountUrl;
}
/**
* Set the storageAccountUrl property: Fully qualified ARM resource id of the witness storage account.
*
* @param storageAccountUrl the storageAccountUrl value to set.
* @return the WsfcDomainProfile object itself.
*/
public WsfcDomainProfile withStorageAccountUrl(String storageAccountUrl) {
this.storageAccountUrl = storageAccountUrl;
return this;
}
/**
* Get the storageAccountPrimaryKey property: Primary key of the witness storage account.
*
* @return the storageAccountPrimaryKey value.
*/
public String storageAccountPrimaryKey() {
return this.storageAccountPrimaryKey;
}
/**
* Set the storageAccountPrimaryKey property: Primary key of the witness storage account.
*
* @param storageAccountPrimaryKey the storageAccountPrimaryKey value to set.
* @return the WsfcDomainProfile object itself.
*/
public WsfcDomainProfile withStorageAccountPrimaryKey(String storageAccountPrimaryKey) {
this.storageAccountPrimaryKey = storageAccountPrimaryKey;
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
}
}
| 2,631 |
3,787 | import os
import sys
additional_path = os.path.realpath('../')
if additional_path not in sys.path:
sys.path.append(additional_path)
| 48 |
32,544 | package com.baeldung.jersey.server;
import javax.ws.rs.FormParam;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.PathParam;
public class ItemParam {
@HeaderParam("headerParam")
private String shopKey;
@PathParam("pathParam")
private String itemId;
@FormParam("formParam")
private String price;
public String getShopKey() {
return shopKey;
}
public void setShopKey(String shopKey) {
this.shopKey = shopKey;
}
public String getItemId() {
return itemId;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
@Override
public String toString() {
return "ItemParam{shopKey='" + shopKey + ", itemId='" + itemId + ", price='" + price + '}';
}
}
| 369 |
1,899 | <gh_stars>1000+
"""Test using user-defined models with sandman2."""
import json
from pytest_flask.fixtures import client
from tests.resources import (
GET_ERROR_MESSAGE,
INVALID_ACTION_MESSAGE,
)
model_module = 'tests.user_models'
database = 'blog.sqlite3'
def test_validate_get(client):
"""Do we get back an error message when making a GET request that fails
validation?"""
response = client.get('/user/')
assert response.status_code == 400
assert response.json['message'] == INVALID_ACTION_MESSAGE
def test_validate_get_single_resource(client):
"""Do we get back an error message when making a GET request for a
single resource which fails validation ?"""
response = client.get('/user/1')
assert response.status_code == 400
assert response.json['message'] == INVALID_ACTION_MESSAGE
def test_get_datetime(client):
"""Do we get back a properly formatted datetime on a model that defines one?"""
response = client.get('/post/1.0')
assert response.status_code == 200
assert response.json['posted_at'] is not None
def test_validate_post(client):
"""Do we get back an error message when making a POST request that fails
validation?"""
response = client.post(
'/user/',
data=json.dumps({
'name': '<NAME>',
'email': '<EMAIL>',
}),
headers={'Content-Type': 'application/json'}
)
assert response.status_code == 400
assert response.json['message'] == INVALID_ACTION_MESSAGE
def test_validate_post_existing_resource(client):
"""Do we get back an error message when making a POST request on a resource that already exists?"""
response = client.post(
'/user/',
data=json.dumps({
'name': '<NAME>',
'email': '<EMAIL>',
}),
headers={'Content-Type': 'application/json'}
)
assert response.status_code == 400
assert response.json['message'] == INVALID_ACTION_MESSAGE
def test_validate_put_existing(client):
"""Do we get back an error message when making a PUT request for
an exisitng resource?"""
response = client.put(
'/user/1',
data=json.dumps({
'name': '<NAME>',
'email': '<EMAIL>',
}),
headers={'Content-Type': 'application/json'}
)
assert response.status_code == 400
assert response.json['message'] == INVALID_ACTION_MESSAGE
def test_validate_put_new(client):
"""Do we get back an error message when making a PUT request for a
totally new resource?"""
response = client.put(
'/user/2',
data=json.dumps({
'name': '<NAME>',
'email': '<EMAIL>',
}),
headers={'Content-Type': 'application/json'}
)
assert response.status_code == 400
assert response.json['message'] == INVALID_ACTION_MESSAGE
def test_validate_patch(client):
"""Do we get back an error message when making a PATCH request on an
existing resource?"""
response = client.patch(
'/user/1',
data=json.dumps({
'name': '<NAME>',
}),
headers={'Content-Type': 'application/json'}
)
assert response.status_code == 400
assert response.json['message'] == INVALID_ACTION_MESSAGE
def test_validate_delete(client):
"""Do we get back an error message when making a DELETE request that fails
validation?"""
response = client.delete('/user/1')
assert response.status_code == 400
assert response.json['message'] == INVALID_ACTION_MESSAGE
| 1,401 |
583 | <reponame>392113274/ServerStatus-Hotaru
# -*- coding: utf-8 -*-
# Update by: https://github.com/CokeMine/ServerStatus-Hotaru
# 依赖于psutil跨平台库:
# 支持Python版本:2.6 to 3.7
# 支持操作系统: Linux, Windows, OSX, Sun Solaris, FreeBSD, OpenBSD and NetBSD, both 32-bit and 64-bit architectures
import socket
import time
import json
import psutil
from collections import deque
SERVER = "127.0.0.1"
PORT = 35601
USER = "USER"
PASSWORD = "<PASSWORD>"
INTERVAL = 1 # 更新间隔,单位:秒
def check_interface(net_name):
net_name = net_name.strip()
invalid_name = ['lo', 'tun', 'kube', 'docker', 'vmbr', 'br-', 'vnet', 'veth']
return not any(name in net_name for name in invalid_name)
def get_uptime():
return int(time.time() - psutil.boot_time())
def get_memory():
mem = psutil.virtual_memory()
swap = psutil.swap_memory()
return int(mem.total / 1024.0), int(mem.used / 1024.0), int(swap.total / 1024.0), int(swap.used / 1024.0)
def get_hdd():
valid_fs = ['ext4', 'ext3', 'ext2', 'reiserfs', 'jfs', 'btrfs', 'fuseblk', 'zfs', 'simfs', 'ntfs', 'fat32', 'exfat',
'xfs']
disks = dict()
size = 0
used = 0
for disk in psutil.disk_partitions():
if disk.device not in disks and disk.fstype.lower() in valid_fs:
disks[disk.device] = disk.mountpoint
for disk in disks.values():
usage = psutil.disk_usage(disk)
size += usage.total
used += usage.used
return int(size / 1024.0 / 1024.0), int(used / 1024.0 / 1024.0)
def get_load():
try:
return round(psutil.getloadavg()[0], 1)
except Exception:
return -1.0
def get_cpu():
return psutil.cpu_percent(interval=INTERVAL)
class Network:
def __init__(self):
self.rx = deque(maxlen=10)
self.tx = deque(maxlen=10)
self._get_traffic()
def _get_traffic(self):
net_in = 0
net_out = 0
net = psutil.net_io_counters(pernic=True)
for k, v in net.items():
if check_interface(k):
net_in += v[1]
net_out += v[0]
self.rx.append(net_in)
self.tx.append(net_out)
def get_speed(self):
self._get_traffic()
avg_rx = 0
avg_tx = 0
queue_len = len(self.rx)
for x in range(queue_len - 1):
avg_rx += self.rx[x + 1] - self.rx[x]
avg_tx += self.tx[x + 1] - self.tx[x]
avg_rx = int(avg_rx / queue_len / INTERVAL)
avg_tx = int(avg_tx / queue_len / INTERVAL)
return avg_rx, avg_tx
def get_traffic(self):
queue_len = len(self.rx)
return self.rx[queue_len - 1], self.tx[queue_len - 1]
def get_network(ip_version):
if ip_version == 4:
host = 'ipv4.google.com'
elif ip_version == 6:
host = 'ipv6.google.com'
else:
return False
try:
socket.create_connection((host, 80), 2).close()
return True
except Exception:
return False
if __name__ == '__main__':
socket.setdefaulttimeout(30)
while True:
try:
print("Connecting...")
s = socket.create_connection((SERVER, PORT))
data = s.recv(1024).decode()
if data.find("Authentication required") > -1:
s.send((USER + ':' + PASSWORD + '\n').encode("utf-8"))
data = s.recv(1024).decode()
if data.find("Authentication successful") < 0:
print(data)
raise socket.error
else:
print(data)
raise socket.error
print(data)
if data.find('You are connecting via') < 0:
data = s.recv(1024).decode()
print(data)
timer = 0
check_ip = 0
if data.find("IPv4") > -1:
check_ip = 6
elif data.find("IPv6") > -1:
check_ip = 4
else:
print(data)
raise socket.error
traffic = Network()
while True:
CPU = get_cpu()
NetRx, NetTx = traffic.get_speed()
NET_IN, NET_OUT = traffic.get_traffic()
Uptime = get_uptime()
Load = get_load()
MemoryTotal, MemoryUsed, SwapTotal, SwapUsed = get_memory()
HDDTotal, HDDUsed = get_hdd()
array = {}
if not timer:
array['online' + str(check_ip)] = get_network(check_ip)
timer = 150
else:
timer -= 1 * INTERVAL
array['uptime'] = Uptime
array['load'] = Load
array['memory_total'] = MemoryTotal
array['memory_used'] = MemoryUsed
array['swap_total'] = SwapTotal
array['swap_used'] = SwapUsed
array['hdd_total'] = HDDTotal
array['hdd_used'] = HDDUsed
array['cpu'] = CPU
array['network_rx'] = NetRx
array['network_tx'] = NetTx
array['network_in'] = NET_IN
array['network_out'] = NET_OUT
s.send(("update " + json.dumps(array) + "\n").encode("utf-8"))
except KeyboardInterrupt:
raise
except socket.error:
print("Disconnected...")
# keep on trying after a disconnect
if 's' in locals().keys():
del s
time.sleep(3)
except Exception as e:
print("Caught Exception:", e)
if 's' in locals().keys():
del s
time.sleep(3)
| 2,996 |
3,102 | <reponame>clayne/DirectXShaderCompiler
// RUN: %clang_cc1 -fsyntax-only -verify %s -triple x86_64-apple-darwin9
// expected-no-diagnostics
// From <rdar://problem/12322000>. Do not warn about undefined behavior of parameter
// argument types in unreachable code in a macro.
#define VA_ARG_RDAR12322000(Marker, TYPE) ((sizeof (TYPE) < sizeof (UINTN_RDAR12322000)) ? (TYPE)(__builtin_va_arg (Marker, UINTN_RDAR12322000)) : (TYPE)(__builtin_va_arg (Marker, TYPE)))
// 64-bit system
typedef unsigned long long UINTN_RDAR12322000;
int test_VA_ARG_RDAR12322000 (__builtin_va_list Marker)
{
return VA_ARG_RDAR12322000 (Marker, short); // no-warning
} | 257 |
372 | /* Editor Settings: expandtabs and use 4 spaces for indentation
* ex: set softtabstop=4 tabstop=8 expandtab shiftwidth=4: *
* -*- mode: c, c-basic-offset: 4 -*- */
/*
* Copyright © BeyondTrust Software 2004 - 2019
* 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.
*
* BEYONDTRUST MAKES THIS SOFTWARE AVAILABLE UNDER OTHER LICENSING TERMS AS
* WELL. IF YOU HAVE ENTERED INTO A SEPARATE LICENSE AGREEMENT WITH
* BEYONDTRUST, THEN YOU MAY ELECT TO USE THE SOFTWARE UNDER THE TERMS OF THAT
* SOFTWARE LICENSE AGREEMENT INSTEAD OF THE TERMS OF THE APACHE LICENSE,
* NOTWITHSTANDING THE ABOVE NOTICE. IF YOU HAVE QUESTIONS, OR WISH TO REQUEST
* A COPY OF THE ALTERNATE LICENSING TERMS OFFERED BY BEYONDTRUST, PLEASE CONTACT
* BEYONDTRUST AT beyondtrust.com/contact
*/
#include "../includes.h"
DWORD
ADUCopyFileFromRemote(
IN PCSTR pszSourcePath,
IN PCSTR pszTargetPath
)
{
DWORD dwError = 0;
IO_FILE_HANDLE hRemoteFile = NULL;
int hLocalFile = -1;
BAIL_ON_NULL_POINTER(pszSourcePath);
BAIL_ON_NULL_POINTER(pszTargetPath);
dwError = ADURemoteOpenFile(
pszSourcePath,
FILE_READ_DATA,
FILE_SHARE_READ,
FILE_OPEN,
FILE_NON_DIRECTORY_FILE,
&hRemoteFile);
BAIL_ON_MAC_ERROR(dwError);
dwError = ADULocalOpenFile(
(PCSTR)pszTargetPath,
O_WRONLY|O_TRUNC|O_CREAT,
0666,
&hLocalFile);
BAIL_ON_MAC_ERROR(dwError);
do
{
BYTE szBuff[BUFF_SIZE];
DWORD dwRead = 0;
DWORD dwWrote = 0;
dwError = ADURemoteReadFile(
hRemoteFile,
szBuff,
sizeof(szBuff),
&dwRead); // number of bytes read
if (!dwRead)
{
dwError = 0;
break;
}
BAIL_ON_MAC_ERROR(dwError);
if ((dwWrote = write(hLocalFile, szBuff, dwRead)) == (unsigned int)-1)
{
dwError = errno;
// Can't build here because that freezes the compiler on OS X 10.6.
// Instead the bail is outside of the loop.
break;
}
} while(1);
BAIL_ON_MAC_ERROR(dwError);
cleanup:
if (hRemoteFile)
{
LwNtCloseFile(hRemoteFile);
}
if (hLocalFile >= 0)
{
close(hLocalFile);
}
return (dwError);
error:
goto cleanup;
}
DWORD
ADUCopyMultipleFilesFromRemote(
IN PCSTR pszSourcePath,
IN PCSTR pszTargetPath
)
{
DWORD dwError = 0;
BOOL bRestart = TRUE;
IO_FILE_HANDLE handle = NULL;
IO_STATUS_BLOCK ioStatus ;
PSTR pszEntryFilename = NULL;
BYTE buffer[MAX_BUFFER];
PFILE_BOTH_DIR_INFORMATION pInfo = NULL;
PSTR pszLocalPath = NULL;
PSTR pszRemotePath = NULL;
BAIL_ON_NULL_POINTER(pszSourcePath);
BAIL_ON_NULL_POINTER(pszTargetPath);
dwError = ADURemoteOpenFile(
pszSourcePath,
FILE_LIST_DIRECTORY, /* Desired access mask */
FILE_SHARE_READ, /* Share access */
FILE_OPEN, /* Create disposition */
FILE_DIRECTORY_FILE, /* Create options */
&handle);
BAIL_ON_MAC_ERROR(dwError);
for (;;)
{
dwError = LwNtQueryDirectoryFile(
handle, /* File handle */
NULL, /* Async control block */
&ioStatus, /* IO status block */
buffer, /* Info structure */
sizeof(buffer), /* Info structure size */
FileBothDirectoryInformation, /* Info level */
FALSE, /* Do not return single entry */
NULL, /* File spec */
bRestart); /* Restart scan */
switch (dwError)
{
case STATUS_NO_MORE_MATCHES:
dwError = 0;
goto cleanup;
case STATUS_SUCCESS:
break;
default:
BAIL_ON_MAC_ERROR(dwError);
}
bRestart = FALSE;
for (pInfo = (PFILE_BOTH_DIR_INFORMATION) buffer; pInfo;
pInfo = (pInfo->NextEntryOffset)?(PFILE_BOTH_DIR_INFORMATION) (((PBYTE) pInfo) + pInfo->NextEntryOffset):NULL)
{
RTL_FREE(&pszEntryFilename);
RTL_FREE(&pszRemotePath);
RTL_FREE(&pszLocalPath);
dwError = LwRtlCStringAllocateFromWC16String(
&pszEntryFilename,
pInfo->FileName
);
BAIL_ON_MAC_ERROR(dwError);
if (!strcmp(pszEntryFilename, "..") ||
!strcmp(pszEntryFilename, "."))
continue;
dwError = LwRtlCStringAllocatePrintf(
&pszRemotePath,
"%s/%s",
pszSourcePath,
pszEntryFilename);
BAIL_ON_MAC_ERROR(dwError);
dwError = LwRtlCStringAllocatePrintf(
&pszLocalPath,
"%s/%s",
pszTargetPath,
pszEntryFilename);
BAIL_ON_MAC_ERROR(dwError);
if(pInfo->FileAttributes != FILE_ATTRIBUTE_DIRECTORY)
{
dwError = ADUCopyFileFromRemote(
pszRemotePath,
pszLocalPath);
BAIL_ON_MAC_ERROR(dwError);
}
}
}
cleanup:
if (handle)
{
LwNtCloseFile(handle);
}
RTL_FREE(&pszLocalPath);
RTL_FREE(&pszRemotePath);
RTL_FREE(&pszEntryFilename);
return dwError;
error:
goto cleanup;
}
DWORD
ADUCopyDirFromRemote(
IN PCSTR pszSourcePath,
IN PCSTR pszTargetPath
)
{
DWORD dwError = 0;
BOOL bRestart = TRUE;
IO_FILE_HANDLE handle = NULL;
IO_STATUS_BLOCK ioStatus ;
PSTR pszEntryFilename = NULL;
BYTE buffer[MAX_BUFFER];
PFILE_BOTH_DIR_INFORMATION pInfo = NULL;
PSTR pszLocalPath = NULL;
PSTR pszRemotePath = NULL;
BAIL_ON_NULL_POINTER(pszSourcePath);
BAIL_ON_NULL_POINTER(pszTargetPath);
dwError = ADURemoteOpenFile(
pszSourcePath,
FILE_LIST_DIRECTORY, /* Desired access mask */
FILE_SHARE_READ, /* Share access */
FILE_OPEN, /* Create disposition */
FILE_DIRECTORY_FILE, /* Create options */
&handle);
BAIL_ON_MAC_ERROR(dwError);
dwError = ADULocalCreateDir(
pszTargetPath,
S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH);
BAIL_ON_MAC_ERROR(dwError);
for (;;)
{
dwError = LwNtQueryDirectoryFile(
handle, /* File handle */
NULL, /* Async control block */
&ioStatus, /* IO status block */
buffer, /* Info structure */
sizeof(buffer), /* Info structure size */
FileBothDirectoryInformation, /* Info level */
FALSE, /* Do not return single entry */
NULL, /* File spec */
bRestart); /* Restart scan */
switch (dwError)
{
case STATUS_NO_MORE_MATCHES:
dwError = 0;
goto cleanup;
case STATUS_SUCCESS:
break;
default:
BAIL_ON_MAC_ERROR(dwError);
}
bRestart = FALSE;
for (pInfo = (PFILE_BOTH_DIR_INFORMATION) buffer; pInfo;
pInfo = (pInfo->NextEntryOffset)?(PFILE_BOTH_DIR_INFORMATION) (((PBYTE) pInfo) + pInfo->NextEntryOffset):NULL)
{
RTL_FREE(&pszEntryFilename);
RTL_FREE(&pszRemotePath);
RTL_FREE(&pszLocalPath);
dwError = LwRtlCStringAllocateFromWC16String(
&pszEntryFilename,
pInfo->FileName
);
BAIL_ON_MAC_ERROR(dwError);
if (!strcmp(pszEntryFilename, "..") ||
!strcmp(pszEntryFilename, "."))
continue;
dwError = LwRtlCStringAllocatePrintf(
&pszRemotePath,
"%s/%s",
pszSourcePath,
pszEntryFilename);
BAIL_ON_MAC_ERROR(dwError);
dwError = LwRtlCStringAllocatePrintf(
&pszLocalPath,
"%s/%s",
pszTargetPath,
pszEntryFilename);
BAIL_ON_MAC_ERROR(dwError);
if(pInfo->FileAttributes == FILE_ATTRIBUTE_DIRECTORY)
{
dwError = ADUCopyDirFromRemote(
pszRemotePath,
pszLocalPath);
BAIL_ON_MAC_ERROR(dwError);
}
else
{
dwError = ADUCopyFileFromRemote(
pszRemotePath,
pszLocalPath);
BAIL_ON_MAC_ERROR(dwError);
}
}
}
cleanup:
if (handle)
{
LwNtCloseFile(handle);
}
RTL_FREE(&pszLocalPath);
RTL_FREE(&pszRemotePath);
RTL_FREE(&pszEntryFilename);
return dwError;
error:
goto cleanup;
}
DWORD
ADUCopyFileToRemote(
IN PCSTR pszSourcePath,
IN PCSTR pszTargetPath
)
{
DWORD dwError = 0;
IO_FILE_HANDLE hRemoteFile = NULL;
int hLocalFile = -1;
DWORD dwBytesRead = 0;
CHAR szBuf[BUFF_SIZE];
BAIL_ON_NULL_POINTER(pszSourcePath);
BAIL_ON_NULL_POINTER(pszTargetPath);
dwError = ADULocalOpenFile(
(PCSTR)pszSourcePath,
O_RDONLY,
0,
&hLocalFile);
BAIL_ON_MAC_ERROR(dwError);
dwError = ADURemoteOpenFile(
pszTargetPath,
FILE_WRITE_DATA,
0,
FILE_OPEN_IF,
FILE_NON_DIRECTORY_FILE,
&hRemoteFile);
BAIL_ON_MAC_ERROR(dwError);
do
{
DWORD dwWritten = 0;
memset (szBuf,0,BUFF_SIZE);
if ((dwBytesRead = read(hLocalFile, szBuf, sizeof(szBuf))) == (unsigned int)-1)
{
dwError = errno;
BAIL_ON_MAC_ERROR(dwError);
}
if (dwBytesRead == 0)
{
break;
}
dwError = ADURemoteWriteFile(
hRemoteFile,
szBuf,
dwBytesRead,
&dwWritten);
BAIL_ON_MAC_ERROR(dwError);
} while (dwBytesRead != 0);
cleanup:
if (hRemoteFile)
{
LwNtCloseFile(hRemoteFile);
}
if (hLocalFile >= 0)
{
close(hLocalFile);
}
return (dwError);
error:
goto cleanup;
}
DWORD
ADUCopyDirToRemote(
IN PCSTR pszSourcePath,
IN PCSTR pszTargetPath
)
{
DWORD dwError = 0;
DIR* pDir = NULL;
struct dirent* pDirEntry = NULL;
struct stat statbuf;
PSTR pszLocalPath = NULL;
PSTR pszRemotePath = NULL;
BAIL_ON_NULL_POINTER(pszSourcePath);
BAIL_ON_NULL_POINTER(pszTargetPath);
if ((pDir = opendir(pszSourcePath)) == NULL)
{
dwError = errno;
BAIL_ON_MAC_ERROR(dwError);
}
// Remove the destination directory (if present), as we are going to replace the contents with the files from pszSourcePath
LOG("Purging remote directory %s to replace with context of %s", pszTargetPath, pszSourcePath);
dwError = ADURemoteRemoveDirRecursive(pszTargetPath, TRUE);
if (dwError)
{
LOG_ERROR("Failed to remove remote directory %s [dwError:0x%x]", pszTargetPath, dwError);
dwError = 0;
}
while ((pDirEntry = readdir(pDir)) != NULL)
{
RTL_FREE(&pszRemotePath);
RTL_FREE(&pszLocalPath);
if (!strcmp(pDirEntry->d_name, "..") ||
!strcmp(pDirEntry->d_name, "."))
continue;
dwError = LwRtlCStringAllocatePrintf(
&pszLocalPath,
"%s/%s",
pszSourcePath,
pDirEntry->d_name);
BAIL_ON_MAC_ERROR(dwError);
memset(&statbuf, 0, sizeof(struct stat));
if (stat(pszLocalPath, &statbuf) < 0)
{
dwError = errno;
BAIL_ON_MAC_ERROR(dwError);
}
dwError = LwRtlCStringAllocatePrintf(
&pszRemotePath,
"%s/%s",
pszTargetPath,
pDirEntry->d_name);
BAIL_ON_MAC_ERROR(dwError);
if ((statbuf.st_mode & S_IFMT) == S_IFDIR)
{
LOG("Copying directory %s to %s", pszLocalPath, pszRemotePath);
dwError = ADUCopyDirToRemote(
pszLocalPath,
pszRemotePath);
}
else
{
LOG("Copying file %s to %s", pszLocalPath, pszRemotePath);
dwError = ADUCopyFileToRemote(
pszLocalPath,
pszRemotePath);
}
BAIL_ON_MAC_ERROR(dwError);
}
if(closedir(pDir) < 0)
{
pDir = NULL;
dwError = LwErrnoToNtStatus(dwError);
BAIL_ON_MAC_ERROR(dwError);
}
pDir = NULL;
cleanup:
if (pDir)
closedir(pDir);
RTL_FREE(&pszLocalPath);
RTL_FREE(&pszRemotePath);
return dwError;
error:
goto cleanup;
}
DWORD
ADURemoteOpenFile(
IN PCSTR pszFileName,
IN ULONG ulDesiredAccess,
IN ULONG ulShareAccess,
IN ULONG ulCreateDisposition,
IN ULONG ulCreateOptions,
OUT PIO_FILE_HANDLE phFile
)
{
DWORD dwError = 0;
NTSTATUS status = STATUS_SUCCESS;
IO_FILE_NAME filename = {0};
IO_FILE_HANDLE hFile = NULL;
IO_STATUS_BLOCK ioStatus ;
PSTR pszRemoteFileName = NULL;
BAIL_ON_NULL_POINTER(pszFileName);
// TODO: We will not do this when we switch to using CreateFile
if (!strncmp(pszFileName, "//", sizeof("//")-1))
{
pszFileName++;
}
dwError = LwRtlCStringAllocatePrintf(
&pszRemoteFileName,
"/rdr%s",
pszFileName);
BAIL_ON_MAC_ERROR(dwError);
dwError = RtlUnicodeStringAllocateFromCString(&filename.Name, pszRemoteFileName);
BAIL_ON_MAC_ERROR(dwError);
status = LwNtCreateFile(
&hFile, /* File handle */
NULL, /* Async control block */
&ioStatus, /* IO status block */
&filename, /* Filename */
NULL, /* Security descriptor */
NULL, /* Security QOS */
ulDesiredAccess, /* Desired access mask */
0, /* Allocation size */
0, /* File attributes */
ulShareAccess, /* Share access */
ulCreateDisposition, /* Create disposition */
ulCreateOptions, /* Create options */
NULL, /* EA buffer */
0, /* EA length */
NULL, /* ECP list */
NULL); /* Creds */
if (status != STATUS_SUCCESS)
{
LOG_ERROR("Failed to open/create file [%s][status:0x%x]",
pszFileName,
status);
dwError = MAC_AD_ERROR_CREATE_FAILED;
}
BAIL_ON_MAC_ERROR(dwError);
*phFile = hFile;
cleanup:
RTL_FREE(&pszRemoteFileName);
RTL_UNICODE_STRING_FREE(&filename.Name);
return dwError;
error:
*phFile = NULL;
if (hFile)
{
LwNtCloseFile(hFile);
}
goto cleanup;
}
DWORD
ADULocalOpenFile(
IN PCSTR pszFileName,
IN INT dwMode,
IN INT dwPerms,
OUT INT *dwHandle
)
{
DWORD dwError = 0;
int fd = -1;
BAIL_ON_NULL_POINTER(pszFileName);
if ((fd = open(pszFileName, dwMode, dwPerms)) == -1)
{
dwError = errno;
BAIL_ON_MAC_ERROR(dwError);
}
error:
*dwHandle = fd;
return dwError;
}
DWORD
ADULocalCreateDir(
IN PCSTR pszPath,
IN mode_t dwFileMode
)
{
DWORD dwError = 0;
PSTR pszTmpPath = NULL;
BAIL_ON_NULL_POINTER(pszPath);
dwError = LwAllocateString(
pszPath,
&pszTmpPath);
BAIL_ON_MAC_ERROR(dwError);
dwError = ADULocalCreateDirInternal(
pszTmpPath,
NULL,
dwFileMode);
BAIL_ON_MAC_ERROR(dwError);
cleanup:
if (pszTmpPath)
LwFreeMemory(pszTmpPath);
return dwError;
error:
goto cleanup;
}
DWORD
ADULocalCreateDirInternal(
IN PSTR pszPath,
IN PSTR pszLastSlash,
IN mode_t dwFileMode
)
{
DWORD dwError = 0;
PSTR pszSlash = NULL;
BOOLEAN bDirExists = FALSE;
BOOLEAN bDirCreated = FALSE;
BAIL_ON_NULL_POINTER(pszPath);
pszSlash = pszLastSlash ? strchr(pszLastSlash + 1, '/') : strchr(pszPath, '/');
if (pszSlash)
{
*pszSlash = '\0';
}
if (pszPath[0])
{
dwError = ADULocalCheckDirExists(pszPath, &bDirExists);
BAIL_ON_MAC_ERROR(dwError);
if (!bDirExists)
{
if (mkdir(pszPath, S_IRWXU) != 0)
{
dwError = errno;
BAIL_ON_MAC_ERROR(dwError);
}
bDirCreated = TRUE;
}
}
if (pszSlash)
{
*pszSlash = '/';
}
if (pszSlash)
{
dwError = ADULocalCreateDirInternal(pszPath, pszSlash, dwFileMode);
BAIL_ON_MAC_ERROR(dwError);
}
if (pszSlash)
{
*pszSlash = '\0';
}
if (bDirCreated)
{
dwError = ADULocalChangePermissions(pszPath, dwFileMode);
BAIL_ON_MAC_ERROR(dwError);
}
if (pszSlash)
{
*pszSlash = '/';
}
cleanup:
return dwError;
error:
if (pszSlash)
{
*pszSlash = '\0';
}
if (bDirCreated)
{
ADULocalRemoveDir(pszPath);
}
if (pszSlash)
{
*pszSlash = '/';
}
goto cleanup;
}
DWORD
ADULocalChangePermissions(
IN PCSTR pszPath,
IN mode_t dwFileMode
)
{
DWORD dwError = 0;
BAIL_ON_NULL_POINTER(pszPath);
while (1)
{
if (chmod(pszPath, dwFileMode) < 0)
{
if (errno == EINTR)
{
continue;
}
dwError = errno;
BAIL_ON_MAC_ERROR(dwError);
}
else
{
break;
}
}
error:
return dwError;
}
DWORD
ADULocalCheckDirExists(
IN PCSTR pszPath,
IN PBOOLEAN pbDirExists
)
{
DWORD dwError = 0;
struct stat statbuf;
BAIL_ON_NULL_POINTER(pszPath);
while (1)
{
memset(&statbuf, 0, sizeof(struct stat));
if (stat(pszPath, &statbuf) < 0)
{
if (errno == EINTR)
{
continue;
}
else if (errno == ENOENT || errno == ENOTDIR)
{
*pbDirExists = FALSE;
break;
}
dwError = errno;
BAIL_ON_MAC_ERROR(dwError);
}
*pbDirExists = (((statbuf.st_mode & S_IFMT) == S_IFDIR) ? TRUE : FALSE);
break;
}
error:
return dwError;
}
DWORD
ADULocalRemoveDir(
IN PCSTR pszPath
)
{
DWORD dwError = 0;
DIR* pDir = NULL;
struct dirent* pDirEntry = NULL;
struct stat statbuf;
CHAR szBuf[BUFF_SIZE+1];
BAIL_ON_NULL_POINTER(pszPath);
if ((pDir = opendir(pszPath)) == NULL)
{
dwError = errno;
BAIL_ON_MAC_ERROR(dwError);
}
while ((pDirEntry = readdir(pDir)) != NULL)
{
if (!strcmp(pDirEntry->d_name, "..") ||
!strcmp(pDirEntry->d_name, "."))
continue;
sprintf(szBuf, "%s/%s", pszPath, pDirEntry->d_name);
memset(&statbuf, 0, sizeof(struct stat));
if (stat(szBuf, &statbuf) < 0)
{
dwError = errno;
BAIL_ON_MAC_ERROR(dwError);
}
if ((statbuf.st_mode & S_IFMT) == S_IFDIR)
{
dwError = ADULocalRemoveDir(szBuf);
BAIL_ON_MAC_ERROR(dwError);
if (rmdir(szBuf) < 0)
{
dwError = LwErrnoToNtStatus(dwError);
BAIL_ON_MAC_ERROR(dwError);
}
}
else
{
dwError = ADULocalRemoveFile(szBuf);
BAIL_ON_MAC_ERROR(dwError);
}
}
if(closedir(pDir) < 0)
{
pDir = NULL;
dwError = LwErrnoToNtStatus(dwError);
BAIL_ON_MAC_ERROR(dwError);
}
pDir = NULL;
if (rmdir(pszPath) < 0)
{
dwError = LwErrnoToNtStatus(dwError);
BAIL_ON_MAC_ERROR(dwError);
}
error:
if (pDir)
closedir(pDir);
return dwError;
}
DWORD
ADULocalRemoveFile(
IN PCSTR pszPath
)
{
DWORD dwError = 0;
BAIL_ON_NULL_POINTER(pszPath);
while (1)
{
if (unlink(pszPath) < 0)
{
if (errno == EINTR)
{
continue;
}
dwError = errno;
BAIL_ON_MAC_ERROR(dwError);
}
else
{
break;
}
}
error:
return dwError;
}
DWORD
ADURemoteReadFile(
IN IO_FILE_HANDLE hFile,
OUT PVOID pBuffer,
IN DWORD dwNumberOfBytesToRead,
OUT PDWORD pdwBytesRead
)
{
DWORD dwError = 0;
NTSTATUS status = STATUS_SUCCESS;
IO_STATUS_BLOCK ioStatus;
status = LwNtReadFile(
hFile, // File handle
NULL, // Async control block
&ioStatus, // IO status block
pBuffer, // Buffer
(ULONG) dwNumberOfBytesToRead, // Buffer size
NULL, // File offset
NULL); // Key
switch (status)
{
case STATUS_SUCCESS:
case STATUS_END_OF_FILE:
break;
default:
LOG_ERROR("Failed to read from file [status:0x%x]", status);
dwError = MAC_AD_ERROR_READ_FAILED;
break;
}
BAIL_ON_MAC_ERROR(dwError);
*pdwBytesRead = (int) ioStatus.BytesTransferred;
cleanup:
return dwError;
error:
*pdwBytesRead = 0;
pBuffer = NULL;
goto cleanup;
}
DWORD
ADURemoteWriteFile(
IN IO_FILE_HANDLE hFile,
IN PVOID pBuffer,
IN DWORD dwNumBytesToWrite,
OUT PDWORD pdwNumBytesWritten
)
{
DWORD dwError = 0;
NTSTATUS status = STATUS_SUCCESS;
IO_STATUS_BLOCK ioStatus ;
BAIL_ON_NULL_POINTER(pBuffer);
status = LwNtWriteFile(
hFile, // File handle
NULL, // Async control block
&ioStatus, // IO status block
pBuffer, // Buffer
(ULONG) dwNumBytesToWrite, // Buffer size
NULL, // File offset
NULL); // Key
if (status != STATUS_SUCCESS)
{
LOG_ERROR("Failed to write to file [status:0x%x]", status);
dwError = MAC_AD_ERROR_WRITE_FAILED;
}
BAIL_ON_MAC_ERROR(dwError);
*pdwNumBytesWritten = (int) ioStatus.BytesTransferred;
cleanup:
return dwError;
error:
*pdwNumBytesWritten = 0;
goto cleanup;
}
DWORD
ADURemoteRemoveFile(
IN PCSTR pszPath
)
{
DWORD dwError = 0;
IO_FILE_HANDLE hRemoteFile = NULL;
BAIL_ON_NULL_POINTER(pszPath);
dwError = ADURemoteOpenFile(
pszPath,
DELETE,
0,
FILE_OPEN,
FILE_DELETE_ON_CLOSE,
&hRemoteFile);
BAIL_ON_MAC_ERROR(dwError);
cleanup:
if (hRemoteFile)
{
LwNtCloseFile(hRemoteFile);
}
return (dwError);
error:
goto cleanup;
}
DWORD
ADURemoteRemoveDirRecursive(
IN PCSTR pszPath,
BOOL bDeleteContentsOnly
)
{
DWORD dwError = 0;
BOOL bRestart = TRUE;
IO_FILE_HANDLE handle = NULL;
IO_STATUS_BLOCK ioStatus ;
PSTR pszEntryFilename = NULL;
BYTE buffer[MAX_BUFFER];
PFILE_BOTH_DIR_INFORMATION pInfo = NULL;
PSTR pszRemotePath = NULL;
ULONG ulCreateOption = FILE_DIRECTORY_FILE;
BAIL_ON_NULL_POINTER(pszPath);
if (!bDeleteContentsOnly)
{
ulCreateOption |= FILE_DELETE_ON_CLOSE;
}
dwError = ADURemoteOpenFile(
pszPath,
DELETE | FILE_LIST_DIRECTORY, /* Desired access mask */
0, /* Share access */
FILE_OPEN, /* Create disposition */
ulCreateOption, /* Create options */
&handle);
BAIL_ON_MAC_ERROR(dwError);
for (;;)
{
dwError = LwNtQueryDirectoryFile(
handle, /* File handle */
NULL, /* Async control block */
&ioStatus, /* IO status block */
buffer, /* Info structure */
sizeof(buffer), /* Info structure size */
FileBothDirectoryInformation, /* Info level */
FALSE, /* Do not return single entry */
NULL, /* File spec */
bRestart); /* Restart scan */
switch (dwError)
{
case STATUS_NO_MORE_MATCHES:
dwError = 0;
goto cleanup;
case STATUS_SUCCESS:
break;
default:
BAIL_ON_MAC_ERROR(dwError);
}
bRestart = FALSE;
for (pInfo = (PFILE_BOTH_DIR_INFORMATION) buffer; pInfo;
pInfo = (pInfo->NextEntryOffset)?(PFILE_BOTH_DIR_INFORMATION) (((PBYTE) pInfo) + pInfo->NextEntryOffset):NULL)
{
RTL_FREE(&pszEntryFilename);
RTL_FREE(&pszRemotePath);
dwError = LwRtlCStringAllocateFromWC16String(
&pszEntryFilename,
pInfo->FileName
);
BAIL_ON_MAC_ERROR(dwError);
if (!strcmp(pszEntryFilename, "..") ||
!strcmp(pszEntryFilename, "."))
continue;
dwError = LwRtlCStringAllocatePrintf(
&pszRemotePath,
"%s/%s",
pszPath,
pszEntryFilename);
BAIL_ON_MAC_ERROR(dwError);
if(pInfo->FileAttributes == FILE_ATTRIBUTE_DIRECTORY)
{
// Get rid of the contents of the sub-directory
dwError = ADURemoteRemoveDirRecursive(pszRemotePath, FALSE);
BAIL_ON_MAC_ERROR(dwError);
LOG("Removed remote sub-directory %s", pszRemotePath);
}
else
{
// Get rid of the this file from the directory
dwError = ADURemoteRemoveFile(pszRemotePath);
BAIL_ON_MAC_ERROR(dwError);
LOG("Removed remote file %s", pszRemotePath);
}
}
}
LOG("Removed remote directory %s", pszPath);
cleanup:
if (handle)
{
LwNtCloseFile(handle);
}
RTL_FREE(&pszRemotePath);
RTL_FREE(&pszEntryFilename);
return dwError;
error:
LOG_ERROR("Failed remove directory recursive operation for remote directory %s, [dwError: 0x%x]", pszPath, dwError);
goto cleanup;
}
DWORD
ADURemoteCreateDirectory(
const char* pszPath
)
{
DWORD dwError = 0;
IO_FILE_HANDLE handle = NULL;
BAIL_ON_NULL_POINTER(pszPath);
dwError = ADURemoteOpenFile(
pszPath,
GENERIC_WRITE, /* Desired access mask */
0, /* Share access */
FILE_CREATE, /* Create disposition */
FILE_DIRECTORY_FILE, /* Create options */
&handle);
BAIL_ON_MAC_ERROR(dwError);
cleanup:
if (handle)
{
LwNtCloseFile(handle);
}
return (dwError);
error:
goto cleanup;
}
| 16,950 |
2,100 | /*
* Copyright (C) 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gapid;
import static com.google.gapid.util.GapidVersion.GAPID_VERSION;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.logging.Level.INFO;
import static java.util.logging.Level.WARNING;
import com.google.gapid.models.Info;
import com.google.gapid.models.Settings;
import com.google.gapid.models.Strings;
import com.google.gapid.proto.service.Service;
import com.google.gapid.proto.stringtable.Stringtable;
import com.google.gapid.rpc.Rpc;
import com.google.gapid.rpc.RpcException;
import com.google.gapid.server.Client;
import com.google.gapid.server.GapisConnection;
import com.google.gapid.server.GapisProcess;
import com.google.gapid.util.Flags;
import com.google.gapid.util.Flags.Flag;
import com.google.gapid.util.Logging;
import com.google.gapid.util.Version;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import java.util.logging.Logger;
/**
* Starts the {@link GapisProcess} and manages the connections to it.
*/
public class Server {
private static final Logger LOG = Logger.getLogger(Server.class.getName());
private static final int FETCH_INFO_TIMEOUT_MS = 3000;
private static final int FETCH_STRING_TABLE_TIMEOUT_MS = 3000;
public static final Flag<String> gapis = Flags.value(
"gapis", "", "<host:port> of the gapis server to connect to.");
public static final Flag<String> gapisAuthToken = Flags.value(
"gapis-auth", "", "The auth token to use when connecting to an exisiting server.");
public static final Flag<Boolean> useCache = Flags.value(
"cache", true, "Whether to use a cache between the UI and the gapis server.", true);
private final Settings settings;
private GapisConnection gapisConnection;
private Client client;
public Server(Settings settings) {
this.settings = settings;
}
public void connect(GapisProcess.Listener listener) throws GapisInitException {
connectToServer(listener);
String status = "";
try {
status = "Fetching server info";
listener.onStatus(status + "...");
fetchServerInfo();
status = "Fetching string table";
listener.onStatus(status + "...");
fetchStringTable();
status = "Monitoring logs";
listener.onStatus(status + "...");
client.streamLog(Logging::logMessage);
} catch (ExecutionException | RpcException | TimeoutException e) {
throw new GapisInitException(
GapisInitException.MESSAGE_FAILED_INIT, "Failed: " + status, e);
}
}
public Client getClient() {
return client;
}
public void disconnect() {
if (gapisConnection != null) {
gapisConnection.close();
gapisConnection = null;
}
}
private void connectToServer(GapisProcess.Listener listener) throws GapisInitException {
GapisConnection connection = createConnection(listener);
if (!connection.isConnected()) {
throw new GapisInitException(GapisInitException.MESSAGE_FAILED_CONNECT, "not connected");
}
gapisConnection = connection;
try {
if (!useCache.get()) {
LOG.log(WARNING, "** Not using caching in the UI, this is only meant for testing. **");
}
client = new Client(connection.createGapidClient(useCache.get()));
} catch (IOException e) {
throw new GapisInitException(
GapisInitException.MESSAGE_FAILED_CONNECT, "unable to create client", e);
}
}
private GapisConnection createConnection(GapisProcess.Listener listener) {
if (gapis.get().isEmpty()) {
return new GapisProcess(settings, listener).connect();
} else {
listener.onStatus("Connecting to gapis...");
return GapisConnection.create(
gapis.get(), gapisAuthToken.get(), 0, con -> listener.onServerExit(-1, null));
}
}
/**
* Requests, blocks, and then checks the server info.
*/
private void fetchServerInfo()
throws RpcException, TimeoutException, ExecutionException, GapisInitException {
Service.ServerInfo info = Rpc.get(client.getSeverInfo(), FETCH_INFO_TIMEOUT_MS, MILLISECONDS);
LOG.log(INFO, "Server info: {0}", info);
Version gapisVersion = Version.fromProto(info);
if (!GAPID_VERSION.isCompatible(gapisVersion)) {
throw new GapisInitException("Incompatible gapis version. Found: " + gapisVersion +
", wanted: " + GAPID_VERSION.toPatternString(), "");
}
Info.setServerInfo(info);
}
/**
* Requests, blocks, and then makes current the string table from the server.
*/
private void fetchStringTable() throws ExecutionException, RpcException, TimeoutException {
List<Stringtable.Info> infos =
Rpc.get(client.getAvailableStringTables(), FETCH_STRING_TABLE_TIMEOUT_MS, MILLISECONDS);
if (infos.size() == 0) {
LOG.log(WARNING, "No string tables available");
return;
}
Stringtable.Info info = infos.get(0);
Stringtable.StringTable table =
Rpc.get(client.getStringTable(info), FETCH_STRING_TABLE_TIMEOUT_MS, MILLISECONDS);
Strings.setCurrent(table);
}
/**
* Exception thrown if the application fails to launch the GAPIS server.
*/
public static class GapisInitException extends Exception {
public static final String MESSAGE_FAILED_CONNECT =
"Failed to connect to the graphics debugger";
public static final String MESSAGE_FAILED_INIT = "Failed to initialize the graphics debugger";
public static final String MESSAGE_TRACE_FILE_EMPTY = "Empty trace file ";
public static final String MESSAGE_TRACE_FILE_BROKEN = "Invalid/Corrupted trace file ";
public static final String MESSAGE_TRACE_FILE_LOAD_FAILED = "Failed to load trace file ";
public static final String MESSAGE_TRACE_FILE_SAVE_FAILED = "Failed to save trace file ";
private final String userMessage;
public GapisInitException(String userMessage, String debugMessage) {
super(debugMessage);
this.userMessage = userMessage;
}
public GapisInitException(String userMessage, String debugMessage, Throwable cause) {
super(debugMessage, cause);
this.userMessage = userMessage;
}
/**
* @return The message to display to the user
*/
@Override
public String getLocalizedMessage() {
return userMessage;
}
}
}
| 2,345 |
309 | /* ***** BEGIN LICENSE BLOCK *****
* JTransforms
* Copyright (c) 2007 onward, <NAME>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*
* ***** END LICENSE BLOCK ***** */
package org.jtransforms.dct;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jtransforms.fft.DoubleFFT_1D;
import org.jtransforms.utils.CommonUtils;
import pl.edu.icm.jlargearrays.ConcurrencyUtils;
import pl.edu.icm.jlargearrays.DoubleLargeArray;
import pl.edu.icm.jlargearrays.LargeArray;
import pl.edu.icm.jlargearrays.LongLargeArray;
import pl.edu.icm.jlargearrays.LargeArrayUtils;
import static org.apache.commons.math3.util.FastMath.*;
/**
* Computes 1D Discrete Cosine Transform (DCT) of double precision data. The
* size of data can be an arbitrary number. This is a parallel implementation of
* split-radix and mixed-radix algorithms optimized for SMP systems. <br>
* <br>
* Part of the code is derived from General Purpose FFT Package written by
* Takuya Ooura (http://www.kurims.kyoto-u.ac.jp/~ooura/fft.html)
*
* @author <NAME> (<EMAIL>)
*/
public class DoubleDCT_1D
{
private int n;
private long nl;
private int[] ip;
private LongLargeArray ipl;
private double[] w;
private DoubleLargeArray wl;
private int nw;
private long nwl;
private int nc;
private long ncl;
private boolean isPowerOfTwo = false;
private DoubleFFT_1D fft;
private static final double PI = 3.14159265358979311599796346854418516;
private boolean useLargeArrays;
/**
* Creates new instance of DoubleDCT_1D.
*
* @param n size of data
*/
public DoubleDCT_1D(long n)
{
if (n < 1) {
throw new IllegalArgumentException("n must be greater than 0");
}
this.useLargeArrays = (CommonUtils.isUseLargeArrays() || n > LargeArray.getMaxSizeOf32bitArray());
this.n = (int) n;
this.nl = n;
if (!useLargeArrays) {
if (n > (1 << 28)) {
throw new IllegalArgumentException("n must be smaller or equal to " + (1 << 28) + " when useLargeArrays argument is set to false");
}
if (CommonUtils.isPowerOf2(n)) {
this.isPowerOfTwo = true;
this.ip = new int[(int) ceil(2 + (1 << (int) (log(n / 2 + 0.5) / log(2)) / 2))];
this.w = new double[this.n * 5 / 4];
nw = ip[0];
if (n > (nw << 2)) {
nw = this.n >> 2;
CommonUtils.makewt(nw, ip, w);
}
nc = ip[1];
if (n > nc) {
nc = this.n;
CommonUtils.makect(nc, w, nw, ip);
}
} else {
this.w = makect(this.n);
fft = new DoubleFFT_1D(2 * n);
}
} else if (CommonUtils.isPowerOf2(n)) {
this.isPowerOfTwo = true;
this.ipl = new LongLargeArray((long) ceil(2 + (1l << (long) (log(n / 2 + 0.5) / log(2)) / 2)));
this.wl = new DoubleLargeArray(this.nl * 5l / 4l);
nwl = ipl.getLong(0);
if (n > (nwl << 2l)) {
nwl = this.nl >> 2l;
CommonUtils.makewt(nwl, ipl, wl);
}
ncl = ipl.getLong(1);
if (n > ncl) {
ncl = this.nl;
CommonUtils.makect(ncl, wl, nwl, ipl);
}
} else {
this.wl = makect(n);
fft = new DoubleFFT_1D(2 * n);
}
}
/**
* Computes 1D forward DCT (DCT-II) leaving the result in <code>a</code>.
*
* @param a data to transform
* @param scale if true then scaling is performed
*/
public void forward(double[] a, boolean scale)
{
forward(a, 0, scale);
}
/**
* Computes 1D forward DCT (DCT-II) leaving the result in <code>a</code>.
*
* @param a data to transform
* @param scale if true then scaling is performed
*/
public void forward(DoubleLargeArray a, boolean scale)
{
forward(a, 0, scale);
}
/**
* Computes 1D forward DCT (DCT-II) leaving the result in <code>a</code>.
*
* @param a data to transform
* @param offa index of the first element in array <code>a</code>
* @param scale if true then scaling is performed
*/
public void forward(final double[] a, final int offa, boolean scale)
{
if (n == 1) {
return;
}
if (useLargeArrays) {
forward(new DoubleLargeArray(a), offa, scale);
} else if (isPowerOfTwo) {
double xr = a[offa + n - 1];
for (int j = n - 2; j >= 2; j -= 2) {
a[offa + j + 1] = a[offa + j] - a[offa + j - 1];
a[offa + j] += a[offa + j - 1];
}
a[offa + 1] = a[offa] - xr;
a[offa] += xr;
if (n > 4) {
rftbsub(n, a, offa, nc, w, nw);
CommonUtils.cftbsub(n, a, offa, ip, nw, w);
} else if (n == 4) {
CommonUtils.cftbsub(n, a, offa, ip, nw, w);
}
CommonUtils.dctsub(n, a, offa, nc, w, nw);
if (scale) {
CommonUtils.scale(n, sqrt(2.0 / n), a, offa, false);
a[offa] = a[offa] / sqrt(2.0);
}
} else {
final int twon = 2 * n;
final double[] t = new double[twon];
System.arraycopy(a, offa, t, 0, n);
int nthreads = ConcurrencyUtils.getNumberOfThreads();
for (int i = n; i < twon; i++) {
t[i] = t[twon - i - 1];
}
fft.realForward(t);
if ((nthreads > 1) && (n > CommonUtils.getThreadsBeginN_1D_FFT_2Threads())) {
nthreads = 2;
final int k = n / nthreads;
Future<?>[] futures = new Future[nthreads];
for (int j = 0; j < nthreads; j++) {
final int firstIdx = j * k;
final int lastIdx = (j == (nthreads - 1)) ? n : firstIdx + k;
futures[j] = ConcurrencyUtils.submit(new Runnable()
{
public void run()
{
for (int i = firstIdx; i < lastIdx; i++) {
int twoi = 2 * i;
int idx = offa + i;
a[idx] = w[twoi] * t[twoi] - w[twoi + 1] * t[twoi + 1];
}
}
});
}
try {
ConcurrencyUtils.waitForCompletion(futures);
} catch (InterruptedException ex) {
Logger.getLogger(DoubleDCT_1D.class.getName()).log(Level.SEVERE, null, ex);
} catch (ExecutionException ex) {
Logger.getLogger(DoubleDCT_1D.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
for (int i = 0; i < n; i++) {
int twoi = 2 * i;
int idx = offa + i;
a[idx] = w[twoi] * t[twoi] - w[twoi + 1] * t[twoi + 1];
}
}
if (scale) {
CommonUtils.scale(n, 1 / sqrt(twon), a, offa, false);
a[offa] = a[offa] / sqrt(2.0);
}
}
}
/**
* Computes 1D forward DCT (DCT-II) leaving the result in <code>a</code>.
*
* @param a data to transform
* @param offa index of the first element in array <code>a</code>
* @param scale if true then scaling is performed
*/
public void forward(final DoubleLargeArray a, final long offa, boolean scale)
{
if (nl == 1) {
return;
}
if (!useLargeArrays) {
if (!a.isLarge() && !a.isConstant() && offa < Integer.MAX_VALUE) {
forward(a.getData(), (int) offa, scale);
} else {
throw new IllegalArgumentException("The data array is too big.");
}
} else if (isPowerOfTwo) {
double xr = a.getDouble(offa + nl - 1);
for (long j = nl - 2; j >= 2; j -= 2) {
a.setDouble(offa + j + 1, a.getDouble(offa + j) - a.getDouble(offa + j - 1));
a.setDouble(offa + j, a.getDouble(offa + j) + a.getDouble(offa + j - 1));
}
a.setDouble(offa + 1, a.getDouble(offa) - xr);
a.setDouble(offa, a.getDouble(offa) + xr);
if (nl > 4) {
rftbsub(nl, a, offa, ncl, wl, nwl);
CommonUtils.cftbsub(nl, a, offa, ipl, nwl, wl);
} else if (nl == 4) {
CommonUtils.cftbsub(nl, a, offa, ipl, nwl, wl);
}
CommonUtils.dctsub(nl, a, offa, ncl, wl, nwl);
if (scale) {
CommonUtils.scale(nl, sqrt(2.0 / nl), a, offa, false);
a.setDouble(offa, a.getDouble(offa) / sqrt(2.0));
}
} else {
final long twon = 2 * nl;
final DoubleLargeArray t = new DoubleLargeArray(twon);
LargeArrayUtils.arraycopy(a, offa, t, 0, nl);
int nthreads = ConcurrencyUtils.getNumberOfThreads();
for (long i = nl; i < twon; i++) {
t.setDouble(i, t.getDouble(twon - i - 1));
}
fft.realForward(t);
if ((nthreads > 1) && (nl > CommonUtils.getThreadsBeginN_1D_FFT_2Threads())) {
nthreads = 2;
final long k = nl / nthreads;
Future<?>[] futures = new Future[nthreads];
for (int j = 0; j < nthreads; j++) {
final long firstIdx = j * k;
final long lastIdx = (j == (nthreads - 1)) ? nl : firstIdx + k;
futures[j] = ConcurrencyUtils.submit(new Runnable()
{
public void run()
{
for (long i = firstIdx; i < lastIdx; i++) {
long twoi = 2 * i;
long idx = offa + i;
a.setDouble(idx, wl.getDouble(twoi) * t.getDouble(twoi) - wl.getDouble(twoi + 1) * t.getDouble(twoi + 1));
}
}
});
}
try {
ConcurrencyUtils.waitForCompletion(futures);
} catch (InterruptedException ex) {
Logger.getLogger(DoubleDCT_1D.class.getName()).log(Level.SEVERE, null, ex);
} catch (ExecutionException ex) {
Logger.getLogger(DoubleDCT_1D.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
for (long i = 0; i < nl; i++) {
long twoi = 2 * i;
long idx = offa + i;
a.setDouble(idx, wl.getDouble(twoi) * t.getDouble(twoi) - wl.getDouble(twoi + 1) * t.getDouble(twoi + 1));
}
}
if (scale) {
CommonUtils.scale(nl, 1 / sqrt(twon), a, offa, false);
a.setDouble(offa, a.getDouble(offa) / sqrt(2.0));
}
}
}
/**
* Computes 1D inverse DCT (DCT-III) leaving the result in <code>a</code>.
*
* @param a data to transform
* @param scale if true then scaling is performed
*/
public void inverse(double[] a, boolean scale)
{
inverse(a, 0, scale);
}
/**
* Computes 1D inverse DCT (DCT-III) leaving the result in <code>a</code>.
*
* @param a data to transform
* @param scale if true then scaling is performed
*/
public void inverse(DoubleLargeArray a, boolean scale)
{
inverse(a, 0, scale);
}
/**
* Computes 1D inverse DCT (DCT-III) leaving the result in <code>a</code>.
*
* @param a data to transform
* @param offa index of the first element in array <code>a</code>
* @param scale if true then scaling is performed
*/
public void inverse(final double[] a, final int offa, boolean scale)
{
if (n == 1) {
return;
}
if (useLargeArrays) {
inverse(new DoubleLargeArray(a), offa, scale);
} else if (isPowerOfTwo) {
double xr;
if (scale) {
CommonUtils.scale(n, sqrt(2.0 / n), a, offa, false);
a[offa] = a[offa] / sqrt(2.0);
}
CommonUtils.dctsub(n, a, offa, nc, w, nw);
if (n > 4) {
CommonUtils.cftfsub(n, a, offa, ip, nw, w);
rftfsub(n, a, offa, nc, w, nw);
} else if (n == 4) {
CommonUtils.cftfsub(n, a, offa, ip, nw, w);
}
xr = a[offa] - a[offa + 1];
a[offa] += a[offa + 1];
for (int j = 2; j < n; j += 2) {
a[offa + j - 1] = a[offa + j] - a[offa + j + 1];
a[offa + j] += a[offa + j + 1];
}
a[offa + n - 1] = xr;
} else {
final int twon = 2 * n;
if (scale) {
CommonUtils.scale(n, sqrt(twon), a, offa, false);
a[offa] = a[offa] * sqrt(2.0);
}
final double[] t = new double[twon];
int nthreads = ConcurrencyUtils.getNumberOfThreads();
if ((nthreads > 1) && (n > CommonUtils.getThreadsBeginN_1D_FFT_2Threads())) {
nthreads = 2;
final int k = n / nthreads;
Future<?>[] futures = new Future[nthreads];
for (int j = 0; j < nthreads; j++) {
final int firstIdx = j * k;
final int lastIdx = (j == (nthreads - 1)) ? n : firstIdx + k;
futures[j] = ConcurrencyUtils.submit(new Runnable()
{
public void run()
{
for (int i = firstIdx; i < lastIdx; i++) {
int twoi = 2 * i;
double elem = a[offa + i];
t[twoi] = w[twoi] * elem;
t[twoi + 1] = -w[twoi + 1] * elem;
}
}
});
}
try {
ConcurrencyUtils.waitForCompletion(futures);
} catch (InterruptedException ex) {
Logger.getLogger(DoubleDCT_1D.class.getName()).log(Level.SEVERE, null, ex);
} catch (ExecutionException ex) {
Logger.getLogger(DoubleDCT_1D.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
for (int i = 0; i < n; i++) {
int twoi = 2 * i;
double elem = a[offa + i];
t[twoi] = w[twoi] * elem;
t[twoi + 1] = -w[twoi + 1] * elem;
}
}
fft.realInverse(t, true);
System.arraycopy(t, 0, a, offa, n);
}
}
/**
* Computes 1D inverse DCT (DCT-III) leaving the result in <code>a</code>.
*
* @param a data to transform
* @param offa index of the first element in array <code>a</code>
* @param scale if true then scaling is performed
*/
public void inverse(final DoubleLargeArray a, final long offa, boolean scale)
{
if (nl == 1) {
return;
}
if (!useLargeArrays) {
if (!a.isLarge() && !a.isConstant() && offa < Integer.MAX_VALUE) {
inverse(a.getData(), (int) offa, scale);
} else {
throw new IllegalArgumentException("The data array is too big.");
}
} else if (isPowerOfTwo) {
double xr;
if (scale) {
CommonUtils.scale(nl, sqrt(2.0 / nl), a, offa, false);
a.setDouble(offa, a.getDouble(offa) / sqrt(2.0));
}
CommonUtils.dctsub(nl, a, offa, ncl, wl, nwl);
if (nl > 4) {
CommonUtils.cftfsub(nl, a, offa, ipl, nwl, wl);
rftfsub(nl, a, offa, ncl, wl, nwl);
} else if (nl == 4) {
CommonUtils.cftfsub(nl, a, offa, ipl, nwl, wl);
}
xr = a.getDouble(offa) - a.getDouble(offa + 1);
a.setDouble(offa, a.getDouble(offa) + a.getDouble(offa + 1));
for (long j = 2; j < nl; j += 2) {
a.setDouble(offa + j - 1, a.getDouble(offa + j) - a.getDouble(offa + j + 1));
a.setDouble(offa + j, a.getDouble(offa + j) + a.getDouble(offa + j + 1));
}
a.setDouble(offa + nl - 1, xr);
} else {
final long twon = 2 * nl;
if (scale) {
CommonUtils.scale(nl, sqrt(twon), a, offa, false);
a.setDouble(offa, a.getDouble(offa) * sqrt(2.0));
}
final DoubleLargeArray t = new DoubleLargeArray(twon);
int nthreads = ConcurrencyUtils.getNumberOfThreads();
if ((nthreads > 1) && (nl > CommonUtils.getThreadsBeginN_1D_FFT_2Threads())) {
nthreads = 2;
final long k = nl / nthreads;
Future<?>[] futures = new Future[nthreads];
for (int j = 0; j < nthreads; j++) {
final long firstIdx = j * k;
final long lastIdx = (j == (nthreads - 1)) ? nl : firstIdx + k;
futures[j] = ConcurrencyUtils.submit(new Runnable()
{
public void run()
{
for (long i = firstIdx; i < lastIdx; i++) {
long twoi = 2 * i;
double elem = a.getDouble(offa + i);
t.setDouble(twoi, wl.getDouble(twoi) * elem);
t.setDouble(twoi + 1, -wl.getDouble(twoi + 1) * elem);
}
}
});
}
try {
ConcurrencyUtils.waitForCompletion(futures);
} catch (InterruptedException ex) {
Logger.getLogger(DoubleDCT_1D.class.getName()).log(Level.SEVERE, null, ex);
} catch (ExecutionException ex) {
Logger.getLogger(DoubleDCT_1D.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
for (long i = 0; i < nl; i++) {
long twoi = 2 * i;
double elem = a.getDouble(offa + i);
t.setDouble(twoi, wl.getDouble(twoi) * elem);
t.setDouble(twoi + 1, -wl.getDouble(twoi + 1) * elem);
}
}
fft.realInverse(t, true);
LargeArrayUtils.arraycopy(t, 0, a, offa, nl);
}
}
/* -------- initializing routines -------- */
private double[] makect(int n)
{
int twon = 2 * n;
int idx;
double delta = PI / twon;
double deltaj;
double[] c = new double[twon];
c[0] = 1;
for (int j = 1; j < n; j++) {
idx = 2 * j;
deltaj = delta * j;
c[idx] = cos(deltaj);
c[idx + 1] = -sin(deltaj);
}
return c;
}
private DoubleLargeArray makect(long n)
{
long twon = 2 * n;
long idx;
double delta = PI / twon;
double deltaj;
DoubleLargeArray c = new DoubleLargeArray(twon);
c.setDouble(0, 1);
for (long j = 1; j < n; j++) {
idx = 2 * j;
deltaj = delta * j;
c.setDouble(idx, cos(deltaj));
c.setDouble(idx + 1, -sin(deltaj));
}
return c;
}
private static void rftfsub(int n, double[] a, int offa, int nc, double[] c, int startc)
{
int k, kk, ks, m;
double wkr, wki, xr, xi, yr, yi;
int idx1, idx2;
m = n >> 1;
ks = 2 * nc / m;
kk = 0;
for (int j = 2; j < m; j += 2) {
k = n - j;
kk += ks;
wkr = 0.5 - c[startc + nc - kk];
wki = c[startc + kk];
idx1 = offa + j;
idx2 = offa + k;
xr = a[idx1] - a[idx2];
xi = a[idx1 + 1] + a[idx2 + 1];
yr = wkr * xr - wki * xi;
yi = wkr * xi + wki * xr;
a[idx1] -= yr;
a[idx1 + 1] -= yi;
a[idx2] += yr;
a[idx2 + 1] -= yi;
}
}
private static void rftfsub(long n, DoubleLargeArray a, long offa, long nc, DoubleLargeArray c, long startc)
{
long k, kk, ks, m;
double wkr, wki, xr, xi, yr, yi;
long idx1, idx2;
m = n >> 1l;
ks = 2 * nc / m;
kk = 0;
for (long j = 2; j < m; j += 2) {
k = n - j;
kk += ks;
wkr = 0.5 - c.getDouble(startc + nc - kk);
wki = c.getDouble(startc + kk);
idx1 = offa + j;
idx2 = offa + k;
xr = a.getDouble(idx1) - a.getDouble(idx2);
xi = a.getDouble(idx1 + 1) + a.getDouble(idx2 + 1);
yr = wkr * xr - wki * xi;
yi = wkr * xi + wki * xr;
a.setDouble(idx1, a.getDouble(idx1) - yr);
a.setDouble(idx1 + 1, a.getDouble(idx1 + 1) - yi);
a.setDouble(idx2, a.getDouble(idx2) + yr);
a.setDouble(idx2 + 1, a.getDouble(idx2 + 1) - yi);
}
}
private static void rftbsub(int n, double[] a, int offa, int nc, double[] c, int startc)
{
int k, kk, ks, m;
double wkr, wki, xr, xi, yr, yi;
int idx1, idx2;
m = n >> 1;
ks = 2 * nc / m;
kk = 0;
for (int j = 2; j < m; j += 2) {
k = n - j;
kk += ks;
wkr = 0.5 - c[startc + nc - kk];
wki = c[startc + kk];
idx1 = offa + j;
idx2 = offa + k;
xr = a[idx1] - a[idx2];
xi = a[idx1 + 1] + a[idx2 + 1];
yr = wkr * xr + wki * xi;
yi = wkr * xi - wki * xr;
a[idx1] -= yr;
a[idx1 + 1] -= yi;
a[idx2] += yr;
a[idx2 + 1] -= yi;
}
}
private static void rftbsub(long n, DoubleLargeArray a, long offa, long nc, DoubleLargeArray c, long startc)
{
long k, kk, ks, m;
double wkr, wki, xr, xi, yr, yi;
long idx1, idx2;
m = n >> 1l;
ks = 2 * nc / m;
kk = 0;
for (long j = 2; j < m; j += 2) {
k = n - j;
kk += ks;
wkr = 0.5 - c.getDouble(startc + nc - kk);
wki = c.getDouble(startc + kk);
idx1 = offa + j;
idx2 = offa + k;
xr = a.getDouble(idx1) - a.getDouble(idx2);
xi = a.getDouble(idx1 + 1) + a.getDouble(idx2 + 1);
yr = wkr * xr + wki * xi;
yi = wkr * xi - wki * xr;
a.setDouble(idx1, a.getDouble(idx1) - yr);
a.setDouble(idx1 + 1, a.getDouble(idx1 + 1) - yi);
a.setDouble(idx2, a.getDouble(idx2) + yr);
a.setDouble(idx2 + 1, a.getDouble(idx2 + 1) - yi);
}
}
}
| 14,809 |
1,405 | package com.lenovo.lps.reaper.sdk.c;
import android.util.Log;
import android.util.Xml;
import com.lenovo.lps.reaper.sdk.b.a;
import com.lenovo.lps.reaper.sdk.e.b;
import java.util.List;
/* loaded from: classes.dex */
public final class c implements Runnable {
private final a a;
public c(a aVar) {
this.a = aVar;
}
private boolean a(String str) {
d dVar = new d(this);
try {
Xml.parse(str, dVar);
b.b("ReaperServerAddressQueryTask", String.valueOf(dVar.b()));
b.b("ReaperServerAddressQueryTask", dVar.a().toString());
dVar.b();
List a = dVar.a();
if (a != null) {
if (a.size() == 1) {
a aVar = this.a;
a.b((String) a.get(0));
this.a.c((String) a.get(0));
return true;
} else if (a.size() > 1) {
int size = (int) (((double) a.size()) * Math.random());
a aVar2 = this.a;
a.b((String) a.get(size));
this.a.c((String) a.get(size));
return true;
} else {
b.d("ReaperServerAddressQueryTask", "don't get reaper server url from lds.");
}
}
return false;
} catch (Exception e) {
Log.e("ReaperServerAddressQueryTask", "processResponseResult fail. " + e.getMessage());
return false;
}
}
/* JADX WARN: Finally extract failed */
/* JADX WARN: Multi-variable type inference failed */
/* JADX WARN: Removed duplicated region for block: B:32:0x00eb */
/* JADX WARN: Removed duplicated region for block: B:48:? A[RETURN, SYNTHETIC] */
/* JADX WARN: Type inference failed for: r0v14 */
/* JADX WARN: Type inference failed for: r0v18 */
/* JADX WARN: Type inference failed for: r0v22 */
/* JADX WARN: Type inference failed for: r0v38 */
/* JADX WARN: Type inference failed for: r0v8 */
@Override // java.lang.Runnable
/*
Code decompiled incorrectly, please refer to instructions dump.
To view partially-correct add '--show-bad-code' argument
*/
public final void run() {
/*
Method dump skipped, instructions count: 321
To view this dump add '--comments-level debug' option
*/
throw new UnsupportedOperationException("Method not decompiled: com.lenovo.lps.reaper.sdk.c.c.run():void");
}
}
| 1,223 |
2,151 |
#ifndef I915_SW_PUBLIC_H
#define I915_SW_PUBLIC_H
struct i915_winsys;
struct i915_winsys * i915_sw_winsys_create(void);
#endif
| 64 |
8,194 | <reponame>zxsean/EhViewer
/*
* Copyright 2016 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.client.parser;
import org.json.JSONException;
import org.json.JSONObject;
public class VoteCommentParser {
public static class Result {
public long id;
public int score;
public int vote;
public int expectVote;
}
// {"comment_id":1253922,"comment_score":-19,"comment_vote":0}
public static Result parse(String body, int vote) throws JSONException {
Result result = new Result();
JSONObject jo = new JSONObject(body);
result.id = jo.getLong("comment_id");
result.score = jo.getInt("comment_score");
result.vote = jo.getInt("comment_vote");
result.expectVote = vote;
return result;
}
}
| 447 |
14,668 | <filename>chromecast/media/avsettings/avsettings_dummy.h
// 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.
#ifndef CHROMECAST_MEDIA_AVSETTINGS_AVSETTINGS_DUMMY_H_
#define CHROMECAST_MEDIA_AVSETTINGS_AVSETTINGS_DUMMY_H_
#include "chromecast/public/avsettings.h"
namespace chromecast {
// Dummy implementation of AvSettings.
class AvSettingsDummy : public AvSettings {
public:
AvSettingsDummy();
~AvSettingsDummy() override;
// AvSettings implementation:
void Initialize(Delegate* delegate) override;
void Finalize() override;
ActiveState GetActiveState() override;
bool TurnActive(bool switch_to_cast) override;
bool TurnStandby() override;
bool KeepSystemAwake(int time_millis) override;
AudioVolumeControlType GetAudioVolumeControlType() override;
bool GetAudioVolumeStepInterval(float* step_interval) override;
int GetAudioCodecsSupported() override;
int GetMaxAudioChannels(AudioCodec codec) override;
bool GetScreenResolution(int* width, int* height) override;
int GetHDCPVersion() override;
int GetSupportedEotfs() override;
int GetDolbyVisionFlags() override;
int GetScreenWidthMm() override;
int GetScreenHeightMm() override;
bool GetOutputRestrictions(OutputRestrictions* restrictions) override;
void ApplyOutputRestrictions(const OutputRestrictions& restrictions) override;
WakeOnCastStatus GetWakeOnCastStatus() override;
bool EnableWakeOnCast(bool enabled) override;
HdrOutputType GetHdrOutputType() override;
bool SetHdmiVideoMode(bool allow_4k,
int optimize_for_fps,
HdrOutputType output_type) override;
bool IsHdrOutputSupportedByCurrentHdmiVideoMode(
HdrOutputType output_type) override;
private:
Delegate* delegate_;
// Disallow copy and assign.
AvSettingsDummy(const AvSettingsDummy&) = delete;
AvSettingsDummy& operator=(const AvSettingsDummy&) = delete;
};
} // namespace chromecast
#endif // CHROMECAST_MEDIA_AVSETTINGS_AVSETTINGS_DUMMY_H_
| 681 |
314 | <filename>src/nemesis-proto_ip.c
/*
* THE NEMESIS PROJECT
* Copyright (C) 2002, 2003 <NAME> <<EMAIL>>
* Original version submitted by ocsic <<EMAIL>>
*
* nemesis-proto_ip.c (IP Packet Generator)
*/
#include "nemesis-ip.h"
#include "nemesis.h"
int buildip(ETHERhdr *eth, IPhdr *ip, struct file *pd, struct file *ipod, libnet_t *l)
{
uint32_t len = 0, ip_len = 0, link_offset = 0;
int n;
if (pd->file_buf == NULL)
pd->file_len = 0;
if (ipod->file_buf == NULL)
ipod->file_len = 0;
if (got_link) /* data link layer transport */
link_offset = LIBNET_ETH_H;
len = link_offset + LIBNET_IPV4_H + pd->file_len + ipod->file_len;
ip_len = len - link_offset;
#ifdef DEBUG
printf("DEBUG: IP packet length %u.\n", len);
printf("DEBUG: IP options size %zd.\n", ipod->file_len);
printf("DEBUG: IP payload size %zd.\n", pd->file_len);
#endif
if (got_ipoptions) {
if ((libnet_build_ipv4_options(ipod->file_buf, ipod->file_len, l, 0)) == -1)
fprintf(stderr, "ERROR: Unable to add IP options, discarding them.\n");
}
libnet_build_ipv4(ip_len,
ip->ip_tos,
ip->ip_id,
ip->ip_off,
ip->ip_ttl,
ip->ip_p,
0,
ip->ip_src.s_addr,
ip->ip_dst.s_addr,
pd->file_buf,
pd->file_len,
l,
0);
if (got_link)
libnet_build_ethernet(eth->ether_dhost, eth->ether_shost, ETHERTYPE_IP, NULL, 0, l, 0);
n = nemesis_send_frame(l, &len);
if (n != (int)len) {
fprintf(stderr, "ERROR: Incomplete packet injection. Only wrote %d bytes.\n", n);
} else {
if (verbose) {
if (got_link)
printf("Wrote %d byte IP packet through linktype %s.\n",
n, nemesis_lookup_linktype(l->link_type));
else
printf("Wrote %d byte IP packet\n", n);
}
}
libnet_destroy(l);
return n;
}
| 821 |
2,232 | /*
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: <NAME>
*/
#pragma once
#include "kernel/environment.h"
namespace lean {
/** \brief Unfold any macro occurring in \c e that has trust level higher than the one
allowed in \c env.
\remark We use this function before sending declarations to the kernel.
The kernel refuses any expression containing "untrusted" macros, i.e.,
macros with trust level higher than the one allowed.
*/
expr unfold_untrusted_macros(environment const & env, expr const & e);
declaration unfold_untrusted_macros(environment const & env, declaration const & d);
expr unfold_all_macros(environment const & env, expr const & e);
declaration unfold_all_macros(environment const & env, declaration const & d);
}
| 236 |
1,091 | <reponame>ariscahyadi/onos-1.14-with-indopronos-app
/*
* Copyright 2017-present Open Networking Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.soam.web;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.onosproject.codec.CodecContext;
import org.onosproject.codec.JsonCodec;
import org.onosproject.incubator.net.l2monitoring.cfm.Mep.Priority;
import org.onosproject.incubator.net.l2monitoring.cfm.identifier.MepId;
import org.onosproject.incubator.net.l2monitoring.soam.MilliPct;
import org.onosproject.incubator.net.l2monitoring.soam.SoamConfigException;
import org.onosproject.incubator.net.l2monitoring.soam.StartTime;
import org.onosproject.incubator.net.l2monitoring.soam.StopTime;
import org.onosproject.incubator.net.l2monitoring.soam.delay.DelayMeasurementCreate.Version;
import org.onosproject.incubator.net.l2monitoring.soam.loss.DefaultLmCreate;
import org.onosproject.incubator.net.l2monitoring.soam.loss.LossMeasurementCreate;
import org.onosproject.incubator.net.l2monitoring.soam.loss.LossMeasurementThreshold;
import java.time.Duration;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.onlab.util.Tools.nullIsIllegal;
import static org.onosproject.incubator.net.l2monitoring.soam.loss.LossMeasurementCreate.CounterOption;
import static org.onosproject.incubator.net.l2monitoring.soam.loss.LossMeasurementCreate.LmType;
import static org.onosproject.incubator.net.l2monitoring.soam.loss.LossMeasurementCreate.LmCreateBuilder;
/**
* Encode and decode to/from JSON to LossMeasurementCreate object.
*/
public class LmCreateCodec extends JsonCodec<LossMeasurementCreate> {
public static final String LM = "lm";
public static final String VERSION = "version";
public static final String LM_CFG_TYPE = "lmCfgType";
public static final String LMLMM = "LMLMM";
public static final String REMOTE_MEP_ID = "remoteMepId";
public static final String PRIORITY = "priority";
public static final String COUNTERS_ENABLED = "countersEnabled";
public static final String THRESHOLDS = "thresholds";
public static final String AVAILABILITY_MEASUREMENT_INTERVAL_MINS =
"availabilityMeasurementIntervalMins";
public static final String AVAILABILITY_NUMBER_CONSECUTIVE_FLR_MEASUREMENTS =
"availabilityNumberConsecutiveFlrMeasurements";
public static final String AVAILABILITY_FLR_THRESHOLD_PCT =
"availabilityFlrThresholdPct";
public static final String AVAILABILITY_NUMBER_CONSECUTIVE_INTERVALS =
"availabilityNumberConsecutiveIntervals";
public static final String AVAILABILITY_NUMBER_CONSECUTIVE_HIGH_FLR =
"availabilityNumberConsecutiveHighFlr";
public static final String FRAME_SIZE = "frameSize";
public static final String MESSAGE_PERIOD_MS = "messagePeriodMs";
public static final String MEASUREMENT_INTERVAL_MINS =
"measurementIntervalMins";
public static final String ALIGN_MEASUREMENT_INTERVALS =
"alignMeasurementIntervals";
public static final String ALIGN_MEASUREMENT_OFFSET_MINS =
"alignMeasurementOffsetMins";
public static final String START_TIME = "startTime";
public static final String STOP_TIME = "stopTime";
@Override
public LossMeasurementCreate decode(ObjectNode json,
CodecContext context) {
if (json == null || !json.isObject()) {
return null;
}
JsonNode lmNode = json.get(LM);
Version version = Version.Y17312011;
if (lmNode.get(VERSION) != null) {
version = Version.valueOf(lmNode.get(VERSION).asText());
}
LmType lmCfgType = LmType.LMLMM;
if (lmNode.get(LM_CFG_TYPE) != null) {
lmCfgType = LmType.valueOf(lmNode.get(LM_CFG_TYPE).asText(LMLMM));
}
MepId remoteMepId = MepId.valueOf(
nullIsIllegal(lmNode.get(REMOTE_MEP_ID), REMOTE_MEP_ID + " is required")
.shortValue());
Priority prio = Priority.valueOf(nullIsIllegal(lmNode.get(PRIORITY),
PRIORITY + " is required in the format 'PRIOn'").asText());
try {
LmCreateBuilder builder = DefaultLmCreate
.builder(version, remoteMepId, prio, lmCfgType);
if (lmNode.get(COUNTERS_ENABLED) != null) {
context.codec(CounterOption.class)
.decode((ArrayNode) (lmNode.get(COUNTERS_ENABLED)), context)
.forEach(builder::addToCountersEnabled);
}
if (lmNode.get(THRESHOLDS) != null) {
context.codec(LossMeasurementThreshold.class)
.decode((ArrayNode) (lmNode.get(THRESHOLDS)), context)
.forEach(builder::addToLossMeasurementThreshold);
}
if (lmNode.get(AVAILABILITY_MEASUREMENT_INTERVAL_MINS) != null) {
builder = builder.availabilityMeasurementInterval(
Duration.ofMinutes(lmNode.get(AVAILABILITY_MEASUREMENT_INTERVAL_MINS).asInt()));
}
if (lmNode.get(AVAILABILITY_NUMBER_CONSECUTIVE_FLR_MEASUREMENTS) != null) {
builder = builder.availabilityNumberConsecutiveFlrMeasurements(
lmNode.get(AVAILABILITY_NUMBER_CONSECUTIVE_FLR_MEASUREMENTS).asInt());
}
if (lmNode.get(AVAILABILITY_FLR_THRESHOLD_PCT) != null) {
builder = builder.availabilityFlrThreshold(
MilliPct.ofPercent((float) lmNode.get(AVAILABILITY_FLR_THRESHOLD_PCT).asDouble()));
}
if (lmNode.get(AVAILABILITY_NUMBER_CONSECUTIVE_INTERVALS) != null) {
builder = builder.availabilityNumberConsecutiveIntervals(
(short) lmNode.get(AVAILABILITY_NUMBER_CONSECUTIVE_INTERVALS).asInt());
}
if (lmNode.get(AVAILABILITY_NUMBER_CONSECUTIVE_HIGH_FLR) != null) {
builder = builder.availabilityNumberConsecutiveHighFlr(
(short) lmNode.get(AVAILABILITY_NUMBER_CONSECUTIVE_HIGH_FLR).asInt());
}
if (lmNode.get(FRAME_SIZE) != null) {
builder = (LmCreateBuilder) builder.frameSize(
(short) lmNode.get(FRAME_SIZE).asInt());
}
if (lmNode.get(MESSAGE_PERIOD_MS) != null) {
builder = (LmCreateBuilder) builder.messagePeriod(Duration.ofMillis(
lmNode.get(MESSAGE_PERIOD_MS).asInt()));
}
if (lmNode.get(MEASUREMENT_INTERVAL_MINS) != null) {
builder = (LmCreateBuilder) builder.measurementInterval(
Duration.ofMinutes(
lmNode.get(MEASUREMENT_INTERVAL_MINS).asInt()));
}
if (lmNode.get(ALIGN_MEASUREMENT_INTERVALS) != null) {
builder = (LmCreateBuilder) builder.alignMeasurementIntervals(
lmNode.get(ALIGN_MEASUREMENT_INTERVALS).asBoolean());
}
if (lmNode.get(ALIGN_MEASUREMENT_OFFSET_MINS) != null) {
builder = (LmCreateBuilder) builder.alignMeasurementOffset(Duration.ofMinutes(
lmNode.get(ALIGN_MEASUREMENT_OFFSET_MINS).asInt()));
}
if (lmNode.get(START_TIME) != null) {
builder = (LmCreateBuilder) builder.startTime(context.codec(StartTime.class)
.decode((ObjectNode) lmNode.get(START_TIME), context));
}
if (lmNode.get(STOP_TIME) != null) {
builder = (LmCreateBuilder) builder.stopTime(context.codec(StopTime.class)
.decode((ObjectNode) lmNode.get(STOP_TIME), context));
}
return builder.build();
} catch (SoamConfigException e) {
throw new IllegalArgumentException(e);
}
}
@Override
public ObjectNode encode(LossMeasurementCreate lm, CodecContext context) {
checkNotNull(lm, "LM cannot be null");
ObjectNode result = context.mapper().createObjectNode()
.put(LM_CFG_TYPE, lm.lmCfgType().name())
.put(VERSION, lm.version().name())
.put(REMOTE_MEP_ID, lm.remoteMepId().id())
.put(PRIORITY, lm.priority().name());
if (lm.countersEnabled() != null) {
result.set(COUNTERS_ENABLED, new LmCounterOptionCodec()
.encode(lm.countersEnabled(), context));
}
if (lm.messagePeriod() != null) {
result.put(MESSAGE_PERIOD_MS, lm.messagePeriod().toMillis());
}
if (lm.frameSize() != null) {
result.put(FRAME_SIZE, lm.frameSize());
}
return result;
}
}
| 4,441 |
397 | // sciplot - a modern C++ scientific plotting library powered by gnuplot
// https://github.com/sciplot/sciplot
//
// Licensed under the MIT License <http://opensource.org/licenses/MIT>.
//
// Copyright (c) 2018-2021 <NAME>
//
// 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.
// Catch includes
#include <tests/catch.hpp>
// sciplot includes
#include <sciplot/specs/GridSpecsBase.hpp>
using namespace sciplot;
TEST_CASE("GridSpecsBase", "[specs]")
{
auto defaultgrid = GridSpecsBase();
defaultgrid.show(true);
defaultgrid.back();
defaultgrid.lineColor(internal::DEFAULT_GRID_LINECOLOR);
defaultgrid.lineWidth(internal::DEFAULT_GRID_LINEWIDTH);
defaultgrid.lineType(internal::DEFAULT_GRID_LINETYPE);
defaultgrid.dashType(internal::DEFAULT_GRID_DASHTYPE);
SECTION("Using constructor GridSpecsBase()")
{
auto grid = GridSpecsBase();
CHECK( grid.repr() == defaultgrid.repr() );
grid.show(true);
grid.front();
grid.lineStyle(7);
grid.lineType(4);
grid.lineWidth(5);
grid.lineColor("red");
grid.dashType(9);
CHECK( grid.repr() == "set grid front linestyle 7 linetype 4 linewidth 5 linecolor 'red' dashtype 9" );
}
const auto majortics = true;
const auto minortics = false;
SECTION("Using constructor GridSpecsBase(ticsname, true===majortics)")
{
auto xtics_major_grid = GridSpecsBase("xtics", majortics);
xtics_major_grid.show(true);
xtics_major_grid.front();
xtics_major_grid.lineStyle(2);
xtics_major_grid.lineType(6);
xtics_major_grid.lineWidth(1);
xtics_major_grid.lineColor("black");
xtics_major_grid.dashType(3);
CHECK( xtics_major_grid.repr() == "set grid xtics front linestyle 2 linetype 6 linewidth 1 linecolor 'black' dashtype 3" );
xtics_major_grid.show(false);
CHECK( xtics_major_grid.repr() == "set grid noxtics" );
}
SECTION("Using constructor GridSpecsBase(ticsname, false===minortics)")
{
auto ytics_minor_grid = GridSpecsBase("mytics", minortics);
ytics_minor_grid.show(true);
ytics_minor_grid.back();
ytics_minor_grid.lineStyle(6);
ytics_minor_grid.lineType(2);
ytics_minor_grid.lineWidth(11);
ytics_minor_grid.lineColor("purple");
ytics_minor_grid.dashType(13);
// Note the comma below. This is because the line properties correspond to grid lines of minor tics. See documentation of `set grid` in Gnuplot manual.
CHECK( ytics_minor_grid.repr() == "set grid mytics back , linestyle 6 linetype 2 linewidth 11 linecolor 'purple' dashtype 13" );
ytics_minor_grid.show(false);
CHECK( ytics_minor_grid.repr() == "set grid nomytics" );
}
}
| 1,426 |
455 | /* Added for Tor. */
#include "lib/cc/torint.h"
#define crypto_uint64 uint64_t
| 31 |
7,137 | package io.onedev.server.web.asset.codemirror;
import java.util.List;
import org.apache.wicket.markup.head.CssHeaderItem;
import org.apache.wicket.markup.head.HeaderItem;
import org.apache.wicket.markup.head.JavaScriptHeaderItem;
import org.apache.wicket.request.resource.CssResourceReference;
import org.apache.wicket.request.resource.JavaScriptResourceReference;
import io.onedev.server.web.asset.hotkeys.HotkeysResourceReference;
import io.onedev.server.web.page.base.BaseDependentCssResourceReference;
import io.onedev.server.web.page.base.BaseDependentResourceReference;
import io.onedev.server.web.resourcebundle.ResourceBundle;
@ResourceBundle
public class CodeMirrorResourceReference extends BaseDependentResourceReference {
private static final long serialVersionUID = 1L;
public CodeMirrorResourceReference() {
super(CodeMirrorResourceReference.class, "codemirror-integration.js");
}
@Override
public List<HeaderItem> getDependencies() {
List<HeaderItem> dependencies = super.getDependencies();
dependencies.add(JavaScriptHeaderItem.forReference(new JavaScriptResourceReference(CodeMirrorResourceReference.class, "lib/codemirror.js")));
dependencies.add(JavaScriptHeaderItem.forReference(new JavaScriptResourceReference(CodeMirrorResourceReference.class, "addon/mode/overlay.js")));
dependencies.add(JavaScriptHeaderItem.forReference(new JavaScriptResourceReference(CodeMirrorResourceReference.class, "addon/mode/simple.js")));
dependencies.add(JavaScriptHeaderItem.forReference(new JavaScriptResourceReference(CodeMirrorResourceReference.class, "addon/mode/multiplex.js")));
dependencies.add(JavaScriptHeaderItem.forReference(new JavaScriptResourceReference(CodeMirrorResourceReference.class, "addon/edit/matchbrackets.js")));
dependencies.add(JavaScriptHeaderItem.forReference(new JavaScriptResourceReference(CodeMirrorResourceReference.class, "addon/dialog/dialog.js")));
dependencies.add(JavaScriptHeaderItem.forReference(new JavaScriptResourceReference(CodeMirrorResourceReference.class, "addon/fold/foldcode.js")));
dependencies.add(JavaScriptHeaderItem.forReference(new JavaScriptResourceReference(CodeMirrorResourceReference.class, "addon/fold/foldgutter.js")));
dependencies.add(JavaScriptHeaderItem.forReference(new JavaScriptResourceReference(CodeMirrorResourceReference.class, "addon/fold/brace-fold.js")));
dependencies.add(JavaScriptHeaderItem.forReference(new JavaScriptResourceReference(CodeMirrorResourceReference.class, "addon/fold/xml-fold.js")));
dependencies.add(JavaScriptHeaderItem.forReference(new JavaScriptResourceReference(CodeMirrorResourceReference.class, "addon/fold/markdown-fold.js")));
dependencies.add(JavaScriptHeaderItem.forReference(new JavaScriptResourceReference(CodeMirrorResourceReference.class, "addon/fold/comment-fold.js")));
dependencies.add(JavaScriptHeaderItem.forReference(new JavaScriptResourceReference(CodeMirrorResourceReference.class, "addon/search/searchcursor.js")));
dependencies.add(JavaScriptHeaderItem.forReference(new JavaScriptResourceReference(CodeMirrorResourceReference.class, "addon/search/search.js")));
dependencies.add(JavaScriptHeaderItem.forReference(new JavaScriptResourceReference(CodeMirrorResourceReference.class, "addon/search/matchesonscrollbar.js")));
dependencies.add(JavaScriptHeaderItem.forReference(new BaseDependentResourceReference(CodeMirrorResourceReference.class, "matchesonscrollbar2.js")));
dependencies.add(JavaScriptHeaderItem.forReference(new JavaScriptResourceReference(CodeMirrorResourceReference.class, "addon/selection/active-line.js")));
dependencies.add(JavaScriptHeaderItem.forReference(new JavaScriptResourceReference(CodeMirrorResourceReference.class, "addon/scroll/annotatescrollbar.js")));
dependencies.add(JavaScriptHeaderItem.forReference(new JavaScriptResourceReference(CodeMirrorResourceReference.class, "addon/display/fullscreen.js")));
dependencies.add(JavaScriptHeaderItem.forReference(new JavaScriptResourceReference(CodeMirrorResourceReference.class, "addon/selection/mark-selection.js")));
dependencies.add(JavaScriptHeaderItem.forReference(new JavaScriptResourceReference(CodeMirrorResourceReference.class, "addon/hint/show-hint.js")));
dependencies.add(JavaScriptHeaderItem.forReference(new BaseDependentResourceReference(CodeMirrorResourceReference.class, "annotatescrollbar2.js")));
dependencies.add(JavaScriptHeaderItem.forReference(new BaseDependentResourceReference(CodeMirrorResourceReference.class, "simplescrollbars.js")));
dependencies.add(JavaScriptHeaderItem.forReference(new BaseDependentResourceReference(CodeMirrorResourceReference.class, "gotoline.js")));
dependencies.add(JavaScriptHeaderItem.forReference(new BaseDependentResourceReference(CodeMirrorResourceReference.class, "identifier-highlighter.js")));
dependencies.add(JavaScriptHeaderItem.forReference(new BaseDependentResourceReference(CodeMirrorResourceReference.class, "loadmode.js")));
dependencies.add(JavaScriptHeaderItem.forReference(new JavaScriptResourceReference(CodeMirrorResourceReference.class, "mode/meta.js")));
dependencies.add(JavaScriptHeaderItem.forReference(new ModeUrlResourceReference()));
dependencies.add(JavaScriptHeaderItem.forReference(new HotkeysResourceReference()));
dependencies.add(CssHeaderItem.forReference(new CssResourceReference(CodeMirrorResourceReference.class, "lib/codemirror.css")));
dependencies.add(CssHeaderItem.forReference(new CodeThemeCssResourceReference()));
dependencies.add(CssHeaderItem.forReference(new CssResourceReference(CodeMirrorResourceReference.class, "addon/dialog/dialog.css")));
dependencies.add(CssHeaderItem.forReference(new CssResourceReference(CodeMirrorResourceReference.class, "addon/fold/foldgutter.css")));
dependencies.add(CssHeaderItem.forReference(new CssResourceReference(CodeMirrorResourceReference.class, "addon/scroll/simplescrollbars.css")));
dependencies.add(CssHeaderItem.forReference(new CssResourceReference(CodeMirrorResourceReference.class, "addon/search/matchesonscrollbar.css")));
dependencies.add(CssHeaderItem.forReference(new CssResourceReference(CodeMirrorResourceReference.class, "addon/display/fullscreen.css")));
dependencies.add(CssHeaderItem.forReference(new CssResourceReference(CodeMirrorResourceReference.class, "addon/hint/show-hint.css")));
dependencies.add(CssHeaderItem.forReference(new BaseDependentCssResourceReference(CodeMirrorResourceReference.class, "codemirror-custom.css")));
return dependencies;
}
}
| 1,845 |
419 | <reponame>JuanluMorales/KRG
#include "EngineToolsUI.h"
#include "OrientationGuide.h"
#include "Engine/Core/Entity/EntityWorldManager.h"
#include "Engine/Core/Entity/EntityWorldDebugger.h"
#include "Engine/Core/Entity/EntityWorld.h"
#include "Engine/Core/Systems/WorldSystem_PlayerManager.h"
#include "System/Render/Imgui/ImguiX.h"
#include "System/Input/InputSystem.h"
#include "System/Core/Settings/SettingsRegistry.h"
//-------------------------------------------------------------------------
#if KRG_DEVELOPMENT_TOOLS
namespace KRG
{
constexpr static float const g_menuHeight = 19.0f;
constexpr static float const g_minTimeScaleValue = 0.1f;
constexpr static float const g_maxTimeScaleValue = 3.5f;
//-------------------------------------------------------------------------
void EngineToolsUI::Initialize( UpdateContext const& context )
{
m_pWorldManager = context.GetSystem<EntityWorldManager>();
for ( auto pWorld : m_pWorldManager->GetWorlds() )
{
if ( pWorld->IsGameWorld() )
{
m_pWorldDebugger = KRG::New<EntityWorldDebugger>( pWorld );
break;
}
}
}
void EngineToolsUI::Shutdown( UpdateContext const& context )
{
KRG::Delete( m_pWorldDebugger );
m_pWorldManager = nullptr;
}
//-------------------------------------------------------------------------
void EngineToolsUI::EndFrame( UpdateContext const& context )
{
UpdateStage const updateStage = context.GetUpdateStage();
KRG_ASSERT( updateStage == UpdateStage::FrameEnd );
// Update internal state
//-------------------------------------------------------------------------
float const k = 2.0f / ( context.GetFrameID() + 1 );
m_averageDeltaTime = context.GetDeltaTime() * k + m_averageDeltaTime * ( 1.0f - k );
// Get game world
//-------------------------------------------------------------------------
EntityWorld* pGameWorld = nullptr;
for ( auto pWorld : m_pWorldManager->GetWorlds() )
{
if ( pWorld->IsGameWorld() )
{
pGameWorld = pWorld;
break;
}
}
if ( pGameWorld == nullptr )
{
return;
}
// Process user input
//-------------------------------------------------------------------------
HandleUserInput( context, pGameWorld );
// Draw overlay window
//-------------------------------------------------------------------------
Render::Viewport const* pViewport = pGameWorld->GetViewport();
ImGuiWindowFlags windowFlags = ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_NoBringToFrontOnFocus;
if ( m_debugOverlayEnabled )
{
windowFlags |= ImGuiWindowFlags_MenuBar;
}
ImVec2 windowPos, windowSize;
if ( !m_windowName.empty() )
{
auto pWindow = ImGui::FindWindowByName( m_windowName.c_str() );
KRG_ASSERT( pWindow != nullptr );
windowPos = pWindow->Pos;
windowSize = pWindow->Size;
}
else
{
windowPos = ImVec2( 0, 0 );
windowSize = ImVec2( pViewport->GetDimensions() );
}
ImGui::SetNextWindowPos( windowPos );
ImGui::SetNextWindowSize( windowSize );
ImGui::PushStyleVar( ImGuiStyleVar_WindowBorderSize, 0.0f );
ImGui::PushStyleVar( ImGuiStyleVar_WindowPadding, ImVec2( 0.0f, 0.0f ) );
ImGui::SetNextWindowBgAlpha( 0.0f );
if ( ImGui::Begin( "ViewportOverlay", nullptr, windowFlags ) )
{
ImGui::PopStyleVar( 2 );
// The overlay elements should always be drawn
DrawOverlayElements( context, pViewport );
//-------------------------------------------------------------------------
if ( m_debugOverlayEnabled )
{
DrawMenu( context, pGameWorld );
}
}
ImGui::End();
// The debug windows should be always be drawn if enabled
DrawWindows( context, pGameWorld );
// Always show the log if any errors/warnings occurred
auto const unhandledWarningsAndErrors = Log::GetUnhandledWarningsAndErrors();
if ( !unhandledWarningsAndErrors.empty() )
{
m_isLogWindowOpen = true;
}
}
//-------------------------------------------------------------------------
// Drawing
//-------------------------------------------------------------------------
void EngineToolsUI::DrawMenu( UpdateContext const& context, EntityWorld* pGameWorld )
{
if ( ImGui::BeginMenuBar() )
{
ImVec2 const totalAvailableSpace = ImGui::GetContentRegionAvail();
float const currentFPS = 1.0f / context.GetDeltaTime();
float const allocatedMemory = Memory::GetTotalAllocatedMemory() / 1024.0f / 1024.0f;
TInlineString<10> const warningsStr( TInlineString<10>::CtorSprintf(), KRG_ICON_QUESTION_CIRCLE" %d", Log::GetNumWarnings() );
TInlineString<10> const errorsStr( TInlineString<10>::CtorSprintf(), KRG_ICON_EXCLAMATION_CIRCLE" %d", Log::GetNumErrors() );
TInlineString<40> const perfStatsStr( TInlineString<40>::CtorSprintf(), "FPS: %3.0f Mem: %.2fMB", currentFPS, allocatedMemory );
ImVec2 const warningsTextSize = ImGui::CalcTextSize( warningsStr.c_str() );
ImVec2 const errorTextSize = ImGui::CalcTextSize( errorsStr.c_str() );
ImVec2 const perfStatsTextSize = ImGui::CalcTextSize( perfStatsStr.c_str() );
float const itemSpacing = ImGui::GetStyle().ItemSpacing.x;
float const framePadding = ImGui::GetStyle().FramePadding.x;
float const perfStatsOffset = totalAvailableSpace.x - perfStatsTextSize.x - ( itemSpacing * 2 );
float const warningsAndErrorsOffset = perfStatsOffset - warningsTextSize.x - errorTextSize.x - ( itemSpacing * 3 ) - ( framePadding * 4 );
float const debugCameraOffset = warningsAndErrorsOffset - 30;
//-------------------------------------------------------------------------
ImGui::PushStyleColor( ImGuiCol_Text, Colors::LimeGreen.ToFloat4() );
bool const drawDebugMenu = ImGui::BeginMenu( KRG_ICON_BUG );
ImGui::PopStyleColor();
if ( drawDebugMenu )
{
if ( ImGui::MenuItem( KRG_ICON_SLIDERS_H" Show Debug Settings", nullptr, &m_isDebugSettingsWindowOpen ) )
{
m_isDebugSettingsWindowOpen = true;
}
if ( ImGui::MenuItem( KRG_ICON_CLOCK" Show Time Controls", nullptr, &m_isTimeControlWindowOpen ) )
{
m_isTimeControlWindowOpen = true;
}
ImGui::EndMenu();
}
// Draw world debuggers
//-------------------------------------------------------------------------
m_pWorldDebugger->DrawMenu( context );
// Camera controls
//-------------------------------------------------------------------------
ImGui::SameLine( debugCameraOffset, 0 );
auto pPlayerManager = pGameWorld->GetWorldSystem<PlayerManager>();
bool const debugCamEnabled = pPlayerManager->GetDebugMode() == PlayerManager::DebugMode::OnlyDebugCamera;
if ( debugCamEnabled )
{
if ( ImGuiX::FlatButton( KRG_ICON_VIDEO"##DisableDebugCam" ) )
{
pPlayerManager->SetDebugMode( PlayerManager::DebugMode::PlayerWithDebugCamera );
}
}
else
{
if ( ImGuiX::FlatButton( KRG_ICON_VIDEO_SLASH"##EnableDebugCam") )
{
pPlayerManager->SetDebugMode( PlayerManager::DebugMode::OnlyDebugCamera );
}
}
// Log
//-------------------------------------------------------------------------
ImGuiX::VerticalSeparator();
if ( ImGuiX::FlatButton( warningsStr.c_str() ) )
{
m_isLogWindowOpen = true;
m_systemLogView.m_showLogMessages = false;
m_systemLogView.m_showLogWarnings = true;
m_systemLogView.m_showLogErrors = false;
}
ImGuiX::VerticalSeparator();
if ( ImGuiX::FlatButton( errorsStr.c_str() ) )
{
m_isLogWindowOpen = true;
m_systemLogView.m_showLogMessages = false;
m_systemLogView.m_showLogWarnings = false;
m_systemLogView.m_showLogErrors = true;
}
ImGuiX::VerticalSeparator();
// Draw Performance Stats
//-------------------------------------------------------------------------
ImGui::SameLine( 0, 8 );
ImGui::Text( perfStatsStr.c_str() );
ImGui::EndMenuBar();
}
}
void EngineToolsUI::DrawOverlayElements( UpdateContext const& context, Render::Viewport const* pViewport )
{
m_pWorldDebugger->DrawOverlayElements( context );
if ( m_debugOverlayEnabled )
{
ImVec2 const guidePosition = ImGui::GetWindowPos() + ImGui::GetWindowContentRegionMax() - ( ImGuiX::OrientationGuide::GetSize() / 2 );
ImGuiX::OrientationGuide::Draw( guidePosition, *pViewport );
}
}
void EngineToolsUI::DrawWindows( UpdateContext const& context, EntityWorld* pGameWorld, ImGuiWindowClass* pWindowClass )
{
m_pWorldDebugger->DrawWindows( context, pWindowClass );
//-------------------------------------------------------------------------
if ( m_isLogWindowOpen )
{
ImGui::SetNextWindowBgAlpha( 0.75f );
m_isLogWindowOpen = m_systemLogView.Draw( context );
}
if ( m_isDebugSettingsWindowOpen )
{
ImGui::SetNextWindowBgAlpha( 0.75f );
m_isDebugSettingsWindowOpen = SystemDebugView::DrawDebugSettingsView( context );
}
//-------------------------------------------------------------------------
if ( m_isTimeControlWindowOpen )
{
ImGui::SetNextWindowSizeConstraints( ImVec2( 100, 54 ), ImVec2( FLT_MAX, 54 ) );
ImGui::SetNextWindowBgAlpha( 0.75f );
if ( ImGui::Begin( "Time Controls", &m_isTimeControlWindowOpen, ImGuiWindowFlags_NoScrollbar ) )
{
ImVec2 const buttonSize( 24, 0 );
// Play/Pause
if ( pGameWorld->IsPaused() )
{
if ( ImGui::Button( KRG_ICON_PLAY"##ResumeWorld", buttonSize ) )
{
ToggleWorldPause( pGameWorld );
}
ImGuiX::ItemTooltip( "Resume" );
}
else
{
if ( ImGui::Button( KRG_ICON_PAUSE"##PauseWorld", buttonSize ) )
{
ToggleWorldPause( pGameWorld );
}
ImGuiX::ItemTooltip( "Pause" );
}
// Step
ImGui::SameLine();
ImGui::BeginDisabled( !pGameWorld->IsPaused() );
if ( ImGui::Button( KRG_ICON_STEP_FORWARD"##StepFrame", buttonSize ) )
{
RequestWorldTimeStep( pGameWorld );
}
ImGuiX::ItemTooltip( "Step Frame" );
ImGui::EndDisabled();
// Slider
ImGui::SameLine();
ImGui::SetNextItemWidth( ImGui::GetContentRegionAvail().x - buttonSize.x - ImGui::GetStyle().ItemSpacing.x );
float currentTimeScale = m_timeScale;
if ( ImGui::SliderFloat( "##TimeScale", ¤tTimeScale, g_minTimeScaleValue, g_maxTimeScaleValue, "%.2f", ImGuiSliderFlags_NoInput ) )
{
SetWorldTimeScale( pGameWorld, currentTimeScale );
}
ImGuiX::ItemTooltip( "Time Scale" );
// Reset
ImGui::SameLine();
if ( ImGui::Button( KRG_ICON_UNDO"##ResetTimeScale", buttonSize ) )
{
ResetWorldTimeScale( pGameWorld );
}
ImGuiX::ItemTooltip( "Reset TimeScale" );
}
ImGui::End();
}
}
//-------------------------------------------------------------------------
void EngineToolsUI::HandleUserInput( UpdateContext const& context, EntityWorld* pGameWorld )
{
auto pInputSystem = context.GetSystem<Input::InputSystem>();
KRG_ASSERT( pInputSystem != nullptr );
// Enable/disable debug overlay
//-------------------------------------------------------------------------
auto const pKeyboardState = pInputSystem->GetKeyboardState();
if ( pKeyboardState->WasReleased( Input::KeyboardButton::Key_Tilde ) )
{
m_debugOverlayEnabled = !m_debugOverlayEnabled;
auto pPlayerManager = pGameWorld->GetWorldSystem<PlayerManager>();
pPlayerManager->SetDebugMode( m_debugOverlayEnabled ? PlayerManager::DebugMode::OnlyDebugCamera : PlayerManager::DebugMode::None );
}
// Time Controls
//-------------------------------------------------------------------------
if ( pKeyboardState->WasReleased( Input::KeyboardButton::Key_Pause ) )
{
ToggleWorldPause( pGameWorld );
}
if ( pKeyboardState->WasReleased( Input::KeyboardButton::Key_PageUp ) )
{
SetWorldTimeScale( pGameWorld, m_timeScale + 0.1f );
}
if ( pKeyboardState->WasReleased( Input::KeyboardButton::Key_PageDown ) )
{
SetWorldTimeScale( pGameWorld, m_timeScale - 0.1f );
}
if ( pKeyboardState->WasReleased( Input::KeyboardButton::Key_Home ) )
{
ResetWorldTimeScale( pGameWorld );
}
if ( pKeyboardState->WasReleased( Input::KeyboardButton::Key_End ) )
{
RequestWorldTimeStep( pGameWorld );
}
}
void EngineToolsUI::ToggleWorldPause( EntityWorld* pGameWorld )
{
// Unpause
if ( pGameWorld->IsPaused() )
{
pGameWorld->SetTimeScale( m_timeScale );
}
else // Pause
{
m_timeScale = pGameWorld->GetTimeScale();
pGameWorld->SetTimeScale( -1.0f );
}
}
void EngineToolsUI::SetWorldTimeScale( EntityWorld* pGameWorld, float newTimeScale )
{
m_timeScale = Math::Clamp( newTimeScale, g_minTimeScaleValue, g_maxTimeScaleValue );
pGameWorld->SetTimeScale( m_timeScale );
}
void EngineToolsUI::ResetWorldTimeScale( EntityWorld* pGameWorld )
{
m_timeScale = 1.0f;
if ( !pGameWorld->IsPaused() )
{
pGameWorld->SetTimeScale( m_timeScale );
}
}
void EngineToolsUI::RequestWorldTimeStep( EntityWorld* pGameWorld )
{
if ( pGameWorld->IsPaused() )
{
pGameWorld->RequestTimeStep();
}
}
}
#endif | 6,961 |
743 | <reponame>silviuvergoti/pebble
/*
* Copyright (c) 2013 by <NAME>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
package com.mitchellbosecke.pebble.spring.config;
import com.mitchellbosecke.pebble.PebbleEngine;
import com.mitchellbosecke.pebble.loader.ClasspathLoader;
import com.mitchellbosecke.pebble.loader.Loader;
import com.mitchellbosecke.pebble.spring.bean.SomeBean;
import com.mitchellbosecke.pebble.spring.extension.SpringExtension;
import com.mitchellbosecke.pebble.spring.servlet.PebbleViewResolver;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.servlet.ViewResolver;
/**
* Spring configuration for unit test
*
* @author <NAME>
*/
@Configuration(proxyBeanMethods = false)
public class MVCConfig {
@Bean
public SomeBean foo() {
return new SomeBean();
}
@Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("com.mitchellbosecke.pebble.spring.messages");
return messageSource;
}
@Bean
public PebbleEngine pebbleEngine(SpringExtension springExtension,
Loader<?> templateLoader) {
return new PebbleEngine.Builder()
.loader(templateLoader)
.strictVariables(false)
.extension(springExtension)
.build();
}
@Bean
public SpringExtension springExtension(MessageSource messageSource) {
return new SpringExtension(messageSource);
}
@Bean
public Loader<?> templateLoader() {
return new ClasspathLoader();
}
@Bean
public ViewResolver viewResolver(PebbleEngine pebbleEngine) {
PebbleViewResolver viewResolver = new PebbleViewResolver(pebbleEngine);
viewResolver.setPrefix("com/mitchellbosecke/pebble/spring/template/");
viewResolver.setSuffix(".html");
viewResolver.setContentType("text/html");
return viewResolver;
}
}
| 752 |
Subsets and Splits